Links controller in MVC N-layer architecture

Do you need it?

From your question it seems that you don't and your Data Access Layer simply forward calls to underlying layer/framework and map properties back/forward.

Complexity (paired with flexibility) comes at a cost (as you see) and for unneeded complexity you pay this cost without any benefit. Drop unneeded complexity! EF abstracts many underlying DB access details and you may won't need to reintroduce Repository pattern. See also Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application (read more for further details about when - IMO - Repository pattern is needed).

In a different context this kind of refactoring has even a name: Remove Middle Man. When a class (or an entire layer, in your case) is doing nothing but delegation/direct mapping then you should remove it entirely.

You'll then have just your presentation DLL and your model DLL (with EF to hide/abstract database access and mapping). You may want to introduce another level of abstraction in your presentation layer (View Model) when underlying model is too different from model you present to your users (or when interaction model is very complex) but there you should follow common pattern/practice of your UI framework (MVC, MVP, MVVM, MVCVM or whatever else).

If, in your scenario, you start designing model layer then a code-first approach will let you design your domain classes adding little or nothing code for mapping (no ORM is perfect). With this path (requisites, domain model, presentation) I usually add View Model classes to fit presentation needing otherwise using Model classes directly).

Repository Pattern, When?

I'd add a 3rd layer for Data Access only for these (not exhaustive list of) scenarios:

I need to map deeply different storage methods: relational database, XML file(s), file-system, NoSQL database.
I have to switch between different technologies: Entity Framework, LINQ to SQL, NHibernate.

For simpler scenarios (such as adding a Service layer) mediator, proxy and similars will (usually) do the job.

Note About Testing

With an ORM you (usually) have harder time to write tests because it's directly connected to underlying database. In this case to test extreme error conditions and/or to simulate network issues/speed can be harder. If you can't automate these tests elsewhere (for example with dedicated system tests instead of unit testing) you may want to introduce a different DbContext base class to be used for testing however details depends on ORM you're using, designing approach you selected and specific tests you need to perform.


The equation for computing the mean average precision (MAP) is shown below:

$$
\text{MAP}(Q) = \frac{1}{\lvert Q \rvert} \sum_{j=1}^{\lvert Q \rvert}\frac{1}{m_j} \sum_{k=1}^{m_j} \text{Precision}(R_{jk})
$$

The inner summation is something that we need to focus on. The outer summation is simply an average over the queries of the inner sum. The inner summation calculates point-wise precision values at the recall points. A recall point is defined as a position in the ranked list which retrieves a relevant document. Note that this quantity is divided by the total number of relevant documents for the jth query denoted by \$m_j\$, which adds the recall factor in an otherwise precision oriented metric.

Coming back to your code, you should thus change the following line

map += ap / topkTest.size();

to

map += ap / truePositives.size();

The rest of the code is okay.


Testing a service that makes database calls, without a database

Something that stands out is that calling voMock.getFileName() on mocked instances will always return null as no mock response has been defined. So your validation logic of

assertThat(voResult.getFileName())
            .isEqualTo(voMock.getFileName());

essentially winds up being

assertThat(voResult.getFileName())
            .isEqualTo(null);

This could end up giving false positives where voResult is incorrect, but the test passes because the filename is null.

You would need to specify a filename for the response object by calling when(voMock.getFileName()).thenReturn("TestFile"). This way your test can actually determine that the returned object is the expected one by checking the unique expected value of voMock.getFileName().

Alternatively, if the requirement is that the instance returned from the service method is the same instance that the *Proc method returns, just avoid calling getFileName when you're verifying the test result. You could instead use something like assertSame(voMock, voResult) to ensure that the instance returned by the service method is the same one that is returned by the *Proc method.

I would always also recommend writing fail/error cases for your class as well. I couldn't give an example without seeing the FusServiceImpl class, but it can sometimes help with spotting issues like the one I listed above. For instance, if you have a test case like

@Test
public void whenGetFileById_thenReturnFile(){
    final Long ID = 99999L;

    when(getFileInfobyIdProc.get(ID)).thenReturn(voMock);

    FileInfoVO voResult = service.getFile(ID - 1);

    assertThat(voResult.getFileName())
            .isNotEqualTo(voMock.getFileName());

}

and that test case passes, you know you've probably made a mistake in the test logic. You can also validate that the method fails in the correct manner - does it return an object with null filename? A null return value? Or raise an exception? It's the non-ideal cases that will crash applications in production, so make sure to test for those cases as well.


Determining if a target string is found in an array of strings

Expanding on my comment above:

Your isFoundIn function can be rewritten as simply

isFoundIn = (term, array) -> array.indexOf(term) isnt -1

indexOf uses the strict === comparison, which is what CoffeeScript also uses for is - i.e. it's equivalent to your code.

One could extend the native JS Array prototype with a include function to more closely mimic Ruby. In CoffeeScript, it'd be written as

Array::include = (term) -> @indexOf(term) isnt -1

Then you can do [1, 2, 3].include(3) and such. But extending native prototypes is generally frowned upon, and I can't recommend it. Tempting though.

As for your original function, you could just do an explicit return right away if the searchTerm is found - no need to loop through the rest of the array

    isFoundIn = (searchTerm, arrayToSearch) ->
      for a in arrayToSearch
        return true if searchTerm is a
      false

The point is moot, though, as indexOf does it all for you

Addendum: I do like the ? hack you used to fully match Ruby's method name, but it is still just that: A hack. You're effectively adding undefined as a possible return value for what should be a straight boolean. It'll also absorb errors (as that's its purpose) where e.g. the object responds to indexOf just fine, but - for whatever reason - hasn't been extended with the include function. So it's easy to get false negatives (unless you explicitly start checking for undefined and branch if that's the case and... well, the code fogs up quick)

So again, definite points for creativity - wish I'd thought of it - but I personally wouldn't go near it in production code


How to implement a dynamic temperature conversion method based on given enums?

The java.util.concurrent.TimeUnit enum class provides both a generic conversion method and specific methods for each modeled unit, e.g., toHours. You could do something similar and still provide the third-party TemperatureConvert.convert method if you want.

Here's the implementation of SECONDS:

SECONDS {
    public long toNanos(long d)   { return x(d, C3/C0, MAX/(C3/C0)); }
    public long toMicros(long d)  { return x(d, C3/C1, MAX/(C3/C1)); }
    ...
    public long toHours(long d)   { return d/(C5/C3); }
    ...
    public long convert(long d, TimeUnit u) { return u.toSeconds(d); }
},

Note that the author went for efficiency by precalculating many of the conversion constants. I wouldn't bother with that to start as it's probably premature for your needs. Your conversion methods should start simply:

CELCIUS {
    public double toFahrenheit(long t) {
        return t * 9 / 5 + 32;
    }
    public double toKelven(long t) {
        return t + 273;
    }
    public double convert(double t, TemperatureUnit u) {
        return u.toCelcius(v);
    }
}

Also, all of the conversion methods are stubs that throw an exception rather than abstract. Why? I don't know. If these weren't enums and could be extended, stub methods that fail only when called are handy for allowing optional operations--think Collection.remove(Object) which throws UnsupportedOperationException if not implemented by the concrete container.


I am assuming that backend.check_config() is different between your implementations.  In one case, it seems to return a boolean, but the other two make it look like it might raise an exception.  My answer is based on that assumption.

The name of the function is check_config.  If it were, parse_config, for example, I would say that it should throw an error because it is expected to do something, but can't because of a problem.  Since it is merely checking, I think a boolean fits better, so my preference goes to A.

Between B and C, it looks like the only difference is whether break is in the try block or the else block.  I am happy to see that you are aware of the else block, but my opinion is that it isn't necessary.  The else block is useful for the cases when you are trying to exclude a certain piece of code from the try block.  That makes sense for when the try is in another try, or for when you don't expect an error and want to know the error happened.  In this case, it is impossible for break to throw an error, so I believe the else block is an unnecessary complication.

I did notice that you took out the space between = and prompt(...) in B and C.  PEP 8, the Python style guide, recommends a space on each side of = in assignments. (It recommends no spaces in a function call such as dict(x=4, y=6))  That could be just a typo, but this is a review.

Based on how you use it, I would think that backend.config would be better as a dictionary.  That way, you could do backend.config[param_name] instead of the more complicated getattr(backend.config, param_name) (or settattr(...)).  If config is created externally, you might consider using vars(config) to create a dictionary of its attributes.  Without further information, I couldn't guarantee that it would be easier, but that's how it looks.


You may use mapcat to omit flatten:

user> (defn doublelist [coll]
        (mapcat #(repeat 2 %) coll))
#'user/doublelist
user> (doublelist [:a :b :c :d])
(:a :a :b :b :c :c :d :d)


I'm not really interested in handling it in the context.

You don't know it yet but you are interested in handling it in a context. Without a context it's as useful as the generic NullReferenceException in .NET. Something happened somewhere but nobody knows where and why.

  is it really bad practice to do this?

Yes it is. The user of your API should take care of logging. You should not force him to log something he might not need or want and most probably he'll log it anyway somewhere else so he'll end up having same exceptions logged multiple times.

If you want to provide a logger for your API then doing it via a decorator would be much better than hardcoding it by inheritance.


Is there any loss in performance converting a 'where' clause to a lambda?

There should not be any performance difference that is a result of the syntax used. The query syntax is just eye candy that gets converted to the same underlying code.  The difference between the two is really just

_ctx.DataContext.Actions
.Join(_ctx.DataContext.Events, blah, blah, blah)
.Single(a=>a.ActionId == actionId);

vs.

_ctx.DataContext.Actions
.Join(_ctx.DataContext.Events, blah, blah, blah)
.Where(a=>a.ActionId == actionId)
.Single();

If there's a performance difference, I'd be very surprised.  The only way to really tell is to run some tests.  I personally prefer your second method or my first; as I do not like mixing query syntax with imperative syntax.


Script to generate documents based on conditionals and CSV data

Instead of decoding each field within the CSV as CP1252, you should open the entire file that way.

I think that you should approach this more as a templating problem than a document-generation problem.  Templating is a challenge that has been solved many times before — though mainly generating HTML rather than OOXML.  Authoring OOXML directly looks like it would be a pain though.  Perhaps you would be better off using a templating solution (Django has one built in) to produce semantically correct HTML as an intermediate format.  Then, you can convert the HTML into DOCX using one of many such tools available, involving Python or not.

Basically, that strategy would decompose one programming headache into two solved problems.


A recursive function that performs a binary search

You return a boolean to indicate whether the value was found or not.  The function would be more useful if you returned an index at which the value was found (or -1 if not found).  It's better information for the same amount of work.

It appears that left is the leftmost index to consider, and right is the rightmost index to consider.  It would be more idiomatic to follow the convention of inclusive-exclusive bounds, with left being the leftmost index and right being just beyond the last element.  That way, right - left indicates the number of elements in the array.

You've implemented the search using recursion, but it could also be done using just a loop.  You would avoid the overhead of function calls and the possibility of stack overflow.

int mid = ( left + right ) / 2 is vulnerable to integer overflow if both indices are large.  int mid = left + (right - left) / 2 would not overflow.


Construct A String Using StringBuilder from a List using elements index

As far as your code is concerned, it would be more efficient to apply the strings from the first 2 and the last elements outside the loop.  This will eliminate 3 elements from the loop:

String buildObject(List<Integer> obj){
   StringBuilder name = new StringBuilder();
   name.append(obj.get(0))
       .append(" & ")
       .append(obj.get(1));
   int limit = obj.size() - 1;
   for(int i = 2; i < limit; i++){
       name.append(", ");
           .append(obj.get(i));
   }
   name.append(" and ")
       .append(obj.get(limit));
   return name.toString();
}


You could take the common bits out into a function:

<?php
function my_thing($name, $title) {
   if ( of_get_option("mm_sm_$name") ) {
      ?>

      <a href="<?php echo of_get_option("mm_sm_$name"); ?>"><img src="<?php echo  get_template_directory_uri(); ?>/images/socials/ico_<?php echo $name ?>.png" alt="<?php echo $title ?>"/><?php echo $title ?>

      <?
   }
}

my_thing('vimeo', 'Vimeo');
my_thing('gplus', 'Google Plus');
?>


Permutation of phone numbers starting at button x, ending at button y, and z numbers long

One probable solution could be to modify the code as this:

Have the code inside answer in another function, say, isNotTraversalCandidate which returns 0,1 if it the conditions confirm that no further traversal is required else it returns -1.
In recAnswer() use this function, isNotTraversalCandidate(), for the input x, y, z in every level. The recursive function should also verify the x, y, z with those conditions.


It looks nice. Can you please make me understand how it works

For example

 function f($n){$s='';$b=str_pad('*',($m=$n*2+1),' ',2);for($i=0;$i<$m;++$i)$s.=($i==$n)?str_repeat('*',$m):$b;return chunk_split($s, $m);}

Output

     *
     *
     *
     *
     *
***********
     *
     *
     *
     *

Sandbox

Let me write it in a way that is easier to see

$n = 5;
$row_len = $n*2+1;
$output = '';
//pad $n spaces on each side of *
$default = str_pad('*',$row_len,' ',STR_PAD_BOTH); //is = "     *     "

//loop once for each vertical row (same as width)
for($i=0;$i<$row_len;++$i){
    if($i==$n){
        //do the center line all *'s
        $output .= str_repeat('*',$row_len);//is = "***********"
    }else{
        //use the default line from above
        $output .= $default;
    }
}

//now we have a single line that is the length squared so we can chunk it
//into equal parts, to make a square
echo chunk_split($output, $row_len);  //is = "     *          *     ***********"

Sandbox

Basically we can create the "     *       " row by using string pad.  Because we can pad spaces on both sides of a * up to the length of a row  ($n*2)+1.

Then the center row, is just * so we can use string repeat to the length of the row for that line.

Last we take our big huge line of spaces and * and split it into chunks (\n) on the length of our row we want.


1.Using render shortcut function is more preferable than render_to_response. The difference is explained on SO

def index(request):
    intentions = Intention.objects.all();
    return render('intentions/templates/index.html', {'intentions': intentions})

2.Then django has another shortcut get_object_or_404

intention = get_object_or_404(Intention, pk=id)

It raises 404 Exception which is processed by middleware. You don't need to call custom HttpRequest for that.

3.Here lazy version reverse_lazy is redundant. Call reverse instead.

return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST

4.You also can look through CBV. Django offers for you some base class to handle forms. It may reduce your code.


Catching API changes for a service that doesn't version its API

Some comments:

Instead of using print statements, the logging module could be used
The return value of get_google_content should be a boolean value (True on success, False on failure)

Regarding ways to make the refresh_content method a little bit more pythonic, I would probably use a for loop and the all built-in function to make sure that all the calls to get_google_content  were successful.

@app.route('/admin/refresh_content')
def refresh_content():
    spreadsheet_keys = ['key_1', 'key_2', 'key_3']
    tables = [Table1, Table2, Table3]
    sheet_statuses = [
      get_google_content(spreadsheet_key, table)
      for spreadsheet_key, table
      in zip(spreadsheet_keys, tables)
    ]

    if all(sheet_statuses):
        return '
Success

Updated spreadsheets'
    else:
        return '
Failure

Unable to update all spreadsheets'

There are other strategies, but that depends on different things like whether you want to stop on the first failure or not.

I hope this helps.


Haskell Hspec/Quickcheck test for numeric function

Ah, a fine Spec. Has been a while since I've used Hspec, but your tests seem reasonable. So, first of all: well done!
There is one bit we should fix though, and you have identified it yourself: the property tests.
QuickCheck's newtypes
Creating any kind of number and then checking whether it's positive is a hassle, as half the numbers will get discarded per candidate. However, since Hspec uses QuickCheck, we can use Positive to only generate positive numbers:
prop_divisible (Positive a) (Positive b) =  a `mod` d == 0 && b `mod`d == 0
  where EuclidRes d s t = extendedEuclid a b

Other than that there are no more objective improvements.
However, there are some personal I would use in my own specs.
Reduce let … in … bindings in specs
Consider the following spec
  describe "Trivial" $ do
    it "trivial example 99 1" $
       let trivial = extendedEuclid 99 1
       in  trivial `shouldBe` (EuclidRes 1 (0) 1)

If I want to understand the spec, I have to read the first line, remember the value of trivial (and that it hasn't been changed after calling extendedEuclid), and supply it in the next one.
If I instead write
  describe "Trivial" $ do
    it "trivial example 99 1" $
       extendedEuclid 99  1 `shouldBe` (EuclidRes 1 (0) 1)
-- or
    it "trivial example 99 99" $
       extendedEuclid 99 99
           `shouldBe` (EuclidRes 99 (0) 1)

I immediately see that extendedEucild is getting tested. This also fits the official style, where let … in … bindings aren't used at all.
Other small pieces
You can use prop from Test.Hspec.QuickCheck instead of it "..." $ property $ ...:
import Test.Hspec.QuickCheck

...

  describe "properties" $ do
      prop "both numbers divisible a%gcd == 0, b%gcd ==0" $
            prop_divisible
      ...


Ok, I've got a possible simplification for you. The goal I had was to get to using one query:

SELECT DISTINCT location.mftcc, location.name FROM Location location

It turns out that Query.getResultList() behaves funny: It returns a List of Object[]! Each entry in the list represents a row returned from the database, where the entries in the Object[] are each field specified in the SELECT. Also, to furthur complicate matters, each field is returned as the JPA type. So, you have to treat the whole array as an Object[] and cast the individual elements.

Here's the code to get it to work:

public Map<String, String> getAvailableBorderTypes() {
   // create empty map to store results in. If we don't find results, an empty hashmap will be returned
   Map<String, String> results = new HashMap<String, String>();

   EntityManager em = entityManagerFactory.createEntityManager();

   // Construct and run query
   String jpaQuery = "SELECT DISTINCT location.mftcc, location.name FROM Location location";
   List<Object[]> resultList = em.createQuery(jpaQuery).getResultList();

   // Place results in map
   for (Object[] borderTypes: resultList) {
      results.put((String)borderTypes[0], (String)borderTypes[1]);
   }

   return results;
}


Project Euler # Triangular, pentagonal and hexagonal in Python

The way this was written, it was meant to steer you in the direction you did.

  Find the next triangle number that is also pentagonal and hexagonal.

You loop the triangles to find matches in the others:

for triangle in triangles:
    if triangle in pentagons and triangle in hexagons:
        yield triangle

But if you think about it, there are more triangles than pentagons and more pentagons than hexagons. And since you need to find occurences where all 3 types match, wouldn't it be better to loop the hexagons, and find a match on the others from there?

My point is:

Don't let the way a question is asked influence the way you implement an algorithm.


I still have trouble understanding how the whole works, but there are still some small things that could be improved:

In your comments, you say that A is an integer type used as a bitmask. The safest bitmask types are unsigned types or std::bitset. You should make this condition clear in your code, write

  template <typename T, typename BitmaskType=unsigned>
  struct static_store { /* ... */ };

You could even make it an error to use a nonconforming type and create a is_bitmask trait, which would allow you to create a meaningful error message:

static_assert(is_bitmask<BitmaskType>::value,
              "the BitmaskType requirements are not satisfied");

I got confused with these lines:

template <typename T, typename ...A>
inline T* static_new(A&& ...args)

It is once again a naming problem: I had in mind the template parameter A from static_store. Since it represents arguments to be forwarding, you should just use the common convetion and name it Args instead. I don't know whether there are written guidelines to name variadic parameter packs, but Args is probably the name that I saw the most often.
You could probably slightly hide details and reduce the visual burden by using a typedef for the type of store_:

using store_type = typename ::std::aligned_storage<sizeof(T), alignof(T)>::type;


Is this a secure way to hash a password?

Pretty much, yes. PBKDF2 is a well-established algorithm, and os.urandom is a suitable CSPRNG that can be used in salt generation on all major platforms (patched, of course).

Your implementation is also brutally simple. The simpler a system, the more secure it can be. Needless complexity leads to insecurities.

So yes, the system is secure, but it is also subject to Moore's law, just like every other computer system or piece of software. To get around this, the number of rounds (iterations) in strong encryption algorithms is a variable taken into account.

In bcrypt, for example, the number of rounds is 2^workload (default 12), and in PBKDF2 the number of rounds is an int passed to the function. Beware that if you need to use a Cython interface, your password hashing is a strongly blocking call (this has bitten me before)


Decide if a number is even or odd by using bitwise operator

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

Simplify your code

This can certainly be simplified.  Keep the goal in mind: get either 0 or 1 into EAX.  Once you've executed this instruction:

and     eax,    0x1

That's exactly what you have.  So that means all of this can be deleted:

    cmp     eax,    0x0
    je      print_result

    mov     eax,    0x1
print_result:

And all you need to do is print the result:

call    print_eax_binary


Executing method on a certain interval + offset

Do not put the random number generator creation in the TimerElapsed method. This could wind up generating the same value if called in succession rapidly. Instead put it at the class level:

private readonly Random _rnd = new Random();

and change appropriately in the method.


Retrieving data from SQL DB based on user input

I don't get the point of the ConnectionString class. Just about any example WRT writing db access code will use a connection string taken from a .config class; why aren't you following that recommendation?

Items like SqlConnection, SqlCommand, SqlDataReader should always be used in a using block in order to properly dispose of their resources. Look at examples like this one, or check this question on SO.

If you're going to place your SQL code in a separate class, I'd prefer it to be an embedded .sql file which you can then retrieve via code like this:

public static string GetQuery(string scriptName, string namespacePrefix)
{
    var resourceName = namespacePrefix + scriptName;
    var assembly = Assembly.GetExecutingAssembly();

    using (var stream = assembly.GetManifestResourceStream(resourceName))
    {
        if (stream == null)
        {
            throw new Exception($"Missing template: {resourceName}");
        }

        using (var streamReader = new StreamReader(stream))
        {
            return streamReader.ReadToEnd();
        }
    }
}

That way you'd at least get some IntelliSense for the SQL code.

Don't use AddWithValue().

On a more general note: avoid writing ADO.NET code by hand. Avoid using SqlDataReader etc. that require you to translate its results into your own custom classes and instead use one of the many tools that handles that for you. These days the vast majority of professional code is written using an ORM like Entity Framework. Even using a Micro ORM like Dapper would be much preferred.


Filter out strings that are short or that are outside the alphabet of a language

It took me a while to decipher what you meant with 'less than n values'. What your function actually does: it filters out all words that are either shorter than the specified length (less) or contain any character from the specified language(s).

The function name is very undescriptive. In a small project that may not be an issue, but in larger projects it quickly becomes impossible to remember what every piece of code does. A good name allows you to quickly understand what a function does. A poor name often requires you to look at how it's implemented, which takes a lot more time. What about removeShortAndForeignWords?
The same goes for parameter and variable names. Good names make code easier to understand: $array -> $words, $less -> $minimumLength, $lang -> $languageCode, $languages -> $languageFilters, and so on.
Why do you try to parse language names? That's very difficult to get right (what if I wanted to use American English, or ру́сский?), so the effect is that your function becomes less reliable, not easier to use. It's much more effective to just document which language codes your function supports (en, ru and tj). In a statically typed language I'd use an enum, but here a set of constants should do.
$lang[$lan] = str_replace($search, $replace, $lan); - Here, because you use $lan as a key, you're adding entries. If the input was array('en', 'ru'), you end up with array('en', 'ru', 'en' => 'en', 'ru' => 'ru'), which results in double work (the filters for each language are executed twice).
if(is_array($lang)) - Use else if here.
qwertyuiopasdfghjklzxcvbnm matches a specific keyboard layout, but abcdefghijklmnopqrstuvwxyz is a much more natural order for latin characters. However, since you're using a regex, you can simply use a-zA-Z.
You can remove a lot of code duplication by making your function recursive. If $lang is an array, then your function can call itself (once for every language code in the array) and then return the final result. Then the rest of the code doesn't need to take multiple language codes into account anymore.
The return value behavior of your function is inconsistent. If you pass an invalid language code, it returns false. However, if you pass an array of invalid language codes, it returns the input words array.
Personally I'd be very careful with references in PHP (&$array). I've seen some surprising edge-cases and as far as I know they often degrade performance. In this case, your function is both returning a filtered array, and it's updating the original array (but only if you pass an array of language codes). So in your last example, not only does the output contain 2 russian words, $words has also been replaced with the results array. That's a very surprising side-effect.

As per your request, here's how I would probably have written it. I don't often work with PHP, and I haven't thoroughly tested this, but it should give you a reasonable impression:

const LANG_EN = 'en';
const LANG_RU = 'ru';
const LANG_TJ = 'tj';

/**
 * Takes an array of words and filters out any words that are too short or that contain any characters from the specified language(s).
 *
 * @param array $words The array of words to filter
 * @param number $minimumLength The minimum allowed word length
 * @param string|array $languageCode The language(s) that must be filtered out. The following languages are supported: LANG_EN, LANG_RU and LANG_TJ.
 *
 * @return array The given words, excluding words that are too short and words that are from the specified language(s).
 */
function removeShortAndForeignWords($words, $minimumLength = 2, $languageCode = LANG_EN) {
    if (is_array($languageCode)) {
        foreach ($languageCode as $language) {
            $words = removeShortAndForeignWords($words, $minimumLength, $language);
        }
        return $words;
    }

    $languageFilters = [
        LANG_EN => '[^a-zA-Z]',
        LANG_RU => '[^ёйцукенгшщзхъфывапролджэячсмитьбюЁЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ]',
        LANG_TJ => '[^ғӯқҳҷӣҒӮҚҲҶӢ]',
    ];
    if (!isset($languageFilters[$languageCode])) {
        return false;
    }

    return preg_grep('~\A'.$languageFilters[$languageCode].'{'.$minimumLength.',}\z~u', $words);
}


Note that you can significantly simplify the import statements (two of which you never even use):

import random
import time

from mainlist import legendary_items, mood, ponder, powerup, ways_to_die

I have also arranged and renamed them as recommended by the style guide.

The methods in your class aren't consistently named. For example, ways_to_die and add_items are named differently but do similar things; based on what they actually do I would have named them add_way_to_die and add_item, although as the lists they add to are public attributes you could just let the user append to them without the convenience functions. Similarly, death should probably be named kill - instance methods generally contain verbs, as they do things to the instance.

The change_hp and change_mood methods are more consistently named, but also redundant; why not let the user do e.g. player.mood = 'happy' rather than player.change_mood('happy')? If you need to control e.g. the range of valid values later, you can make it a property:

class Player(object):

    VALID_MOODS = ['happy', 'sad']

    @property
    def mood(self):
        return self._mood  # note "private by convention" leading underscore

    @mood.setter
    def mood(self, mood):
        if mood not in self.VALID_MOODS:
            raise ValueError('Invalid mood: {}'.format(mood))
        self._mood = mood

playerlist (should be player_list, as above) can be built much more efficiently with a list comprehension, factoring out addplayers entirely:

player_list = [Player("Player{}".format(n+1)) for n in range(10)]

this makes it easier to change the number of players, and harder to accidentally leave one of the numbers out (e.g. [..., 'Player4', 'Player6', ...]) or make a typo (e.g. [..., 'Player4', 'Players5', 'Player6', ...]). If you still want to introduce them, you can easily do so:

for player in player_list:
    print ("{0.name} enters the game with {0.hit_points} HP of life "
           "and feels pretty much alive").format(player)

Note the use of Python's implicit concatenation of strings to keep the line length under 80 characters, and str.format rather than the more old-fashioned % formatting.

You could also get rid of player_mood (which is not very well-named), for example by:

adding mood as an initialisation parameter (def __init__(self, name, mood):) and calling random.choice in the list comprehension;
adding mood as an optional parameter (def __init__(self, name, mood=None):) and calling random.choice in the __init__ method if mood is None:; or
providing a convenience function Player.set_random_mood to the class (this could be combined with 2.: if mood is None: self.set_random_mood()).

Python indexing is 0-based, so:

print players[1].mood
print players[2].mood

will actually show the mood attributes of 'Player2' and 'Player3'. Not a deal-breaker, but you should be aware of it!

You should generally write docstrings for your modules, classes, methods and functions; this provides useful information to anyone using your code (including you!)


Learning nested for loops in Python with Pig Latin translator

It's nice that you created a function.  Unfortunately, your function accepts no parameters and returns no values.  Rather, it refers to the global sentence_list as its input, and prints the output as a side-effect.  Worse, it uses global variables pig_word and pig_list, which should definitely have been local variables instead.  (Call this function a second time, and you'll have a mess!)

Your variable naming is poor, here:

# breaks up the words in the string and puts them into a list
sentence_list = sentence.split()

… and here:

for item in sentence_list:

For clarity, those should be words = sentence.split() and for word in words:, respectively.  You could then drop the comment.

Since vowels is a constant, it should be named VOWELS instead.

The for letter in vowels loop is problematic.  You just want to see whether the first letter of the word is a vowel.  The way to do that should be

if word[0] in VOWELS:

Suggested solutions

VOWELS = 'AaEeIiOoUuYy'

def pig_latin_trans(sentence):
    pig_list = []
    for word in sentence.split():
        if word[0] in VOWELS:
            pig_list.append(word + "way")
        else:
            pig_list.append(word[1:] + word[0] + "ay")
    return " ".join(pig_list)

print(pig_latin_trans(raw_input("Enter words to be translated: ")))

The loop to build pig_list could be more elegantly expressed using a generator expression.

def pig_latin_trans(sentence):
    return " ".join(
        word + "way" if word[0] in VOWELS else
        word[1:] + word[0] + "ay"
        for word in sentence.split()
    )


Tokenizing each document in a large document of documents

Tokenizer method:

You use ref incorrectly, all reference types are always passed by reference, please read the MSDN or any other online resource to understand the ref
Your code doesn't follow naming conventions: local variables, parameters should be camelCased (e.g. StopWordSet)
use string.Split(new char[0], StringSplitOptions.RemoveEmptyEntries) overload to split on all whitespace characters and remove empty strings during tokenizing, rather than trimming result
strings are immutable, so the statement item.Trim() is useless unless you assign it to something
Tokenizer method always returns an empty list since tokens (not tokenz) is only intialized and not used. It looks like tokenz parameter is redundant and tokens variable should be used instead
To improve performance it might be better to change the type of stopwords parameter to ISet<string> and use it for matching, rather than create a new StopWordSet each time
As a result you'll get a cleaner version of Tokenizer:

private static IEnumerable<string> Tokenizer(StreamReader sr, ISet<string> stopwords)//function for tokenizing
{
    string line;
    List<string> tokens = new List<string>();//list of strings called tokens

    while ((line = sr.ReadLine()) != null)//as long as the streamreader has something
    {
        foreach (string item in line.Split(new char[0], StringSplitOptions.RemoveEmptyEntries))//split amongst strings
        {
            if (item.StartsWith("<") & item.EndsWith(">"))
            {
                if (item == "</DOC>")
                    tokens.Add(item); //adds the doc tags for later separation use
            }
            else
            {
                string newitem = Regex.Replace(item, @"[^A-Za-z0-9]+", "", RegexOptions.IgnoreCase).ToLower();
                if (!stopwords.Contains(newitem))
                    tokens.Add(newitem);
            }
        }
    }
    return tokens;
}

Now let's look at the AddToDictionaryAndCount method:

naming conventions - do name your variables/parameters properly, it's absolutely not clear what is the difference between doccounter2 parameter, doccounter and secondcounter variables. Rename them to smth. like documentIndex, numberOfTermOccurances etc.
while (counter <= tokens.LastIndexOf("</DOC>")) is the killer, you're looking for "</DOC>" entry on each iteration. Cache the calculated value instead.
since you know the number of iterations and you always increment the index it's better to use for instead of while
not sure why you pass docFreqCounter as parameter, it looks like is being used as a local variable.

As to performance improvements (other than caching LastIndexOf) - currently you scan the through the tokens list for each and every item in myLexicon. Assuming that lexicon is built from tokens it would be much better to scan the tokens list only once, tracking which items you've already counted and where are the doc boundaries. Since you haven't provided the meaning of all parameters participating in this method it's hard to suggest a proper solution, but here is the first approximation:

public static Dictionary<string, Dictionary<int, int>> AddToDictionaryAndCount(List<string> tokens)
{
    var result = new Dictionary<string, Dictionary<int,int>>();
    var documentIndex = 0; //tracks the current document index

    var lastDocumentIndex = tokens.LastIndexOf("</DOC>");
    for (int i = 0; i <= lastDocumentIndex; i++)
    {
        var token = tokens[i];
        if (token == "</DOC>")
        {
            //finalize stats for the document. not sure what goes here.
            //add the logic corresponding to "doccounter2 < doccounter"
            documentIndex++;
            continue;
        }

        Dictionary<int, int> documentStats;
        if (!result.TryGetValue(token, out documentStats))
            documentStats = result[token] = new Dictionary<int, int>();

        documentStats[documentIndex]++;
    }
    return result;
}


Yeah, without giving too much away (this is obviously homework)....

First though, the assumption I make is that the assignment is:

find the length of the longest series of either increasing, or decreasing numbers
sum the values in this longest sequence.

There are two parts to this problem as well. The first part is getting the user input, and the second is identifying and processing the sequences. I will assume that you can process the user input adequately, and put it in an array of integer int[] values = .... You use an ArrayList<Integer> which is not, in my opinion, a great container for doing arithmetic on...

This problem can be solved by managing three variables, and keeping a maxlen and maxsum total.

First you need to ensure you have at least 2 items in your values array, and, assuming you do, you initialize your three variables:

boolean increasing = values[0] < values[1];
int sum = values[0];
int len = 1;

int maxlen = len;
int maxsum = sum;

OK, we set up the system where we expect the third value to be a continuation of the sequence.... and then we start the loop, starting from position 1 (the second item) in the values array:

for (int i = 1; i <= arrays.length; i++) {
    // check here to see if we are going in the same direction
    if ( (increasing && value[i] >= value[i -1]) || ( ...decreasing and next is smaller) ) {
        // we are going on in the same direction as before:
        // increase the length, and add value[i] to the sum.
        // if the length is larger than maxlen, then change maxlen and maxsum to len and sum
    } else {
        // the value at position i breaks the sequence.
        // reset len and sum to be 2 and the sum of this and the previous value

        // EDIT: 'Obviously' you record the change in direction!
        increasing = !increasing;

    }
}

System.out.printf("The longest sequence is %d values long, and has a sum of %d\n", maxlen, maxsum);

Without going in to too much detail, you can easily convert this algorithm to work at the same time as you process the user input.... there is no real reason why you have to first convert all the values to int first, and only then process them.... you can process them as they are entered.

EDIT: I realize you may need to be smarter than I have suggested when setting up the variables initially... if the first values in the input are all the same then the algorithm above will assume the sequence is not increasing and will produce the wrong result. You need to find out the initial 'direction' of the sequence by looking for the first 'different' value


Instead of looping over the freq.keySet, I recommend using freq.forEach((k, v) -> bucket[v].add(k)). This avoids the map lookups. In your current code, for each key you do a search in the map, which takes time. By using forEach, this additional search is avoided.

Do you actually have any performance requirements? If not, I'd say the code is perfect. It is easy to read and understand, and well documented.

Your code might return more than the k elements that are requested, because of the addAll. This should be discussed with the interviewer whether it is ok.

Too bad that Java doesn't have a built-in Histogram class. Things would have been much simpler that way:

new Histogram(nums).stream()
    .limit(k)
    .forEach(System.out::println);


Efficiently convert 60 GB JSON file to a csv file

It looks like the actual processing is quite simple, so I would recommend using a streaming JSON parser like jq --stream or (in Python) ijson.


Evaluator for adding and subtracting algebraic expressions

Make sure your code is indented correctly here. It isn't.

Then document your code at least with some minimum amount of explanations and structure.

Common Lisp has ways to comment code:

;;;; program comment

;;; section comment

(defun bar ()

  "This is a retrievable function documentation
string, which
can be spread over many lines."

  (let ((foo (random 100)))
   ;;  indented code comment
   (+ foo 3)   ; inline code comment
   ))

#|
     Block comments
|#

Then one can retrieve the function documentation with some IDE keystrokes/mechanisms and:

(documentation 'bar 'function)

Some hints:

(defun expression? (exp)
  (or (eql (car exp) '+)
      (eql (car exp) '*)
      (eql (car exp) '-)))

(case exp
  ((+ * -) t)
  (otherwise nil))

(member (car exp) '(+ * -))

(defun first-expression (exp) (car (cdr exp)))

(cadr exp)
(second exp)

(defun second-expression (exp) (car (cdr (cdr exp))))

(caddr exp)
(third exp)

(defun make (e1 e2 op)
  (cond ((eql op '+)
         (make-addition e1 e2))
        ((eql op '-)
         (make-subtraction e1 e2))
        (t (make-product e1 e2))))

(case op
  (+ ...)
  (- ...)
  (otherwise ...))


Leaving alone an UB (which is already addressed), let's look at an actual solution, the credeit_pos function.

  From this list you would like to buy two items that add up to the entire value of the credit.

In a programming terms: given a range, find two values which add up to the given value.

The proposed solution is

for each elements in a range,
    try to find a peer adding up to a target

It is correct but an implementation has quadratic complexity. It feels wrong. Every time you work with a linear range and end up with a quadratic algorithm, ask yourself if it can be improved if the range was sorted (sort is cheap comparing to quadratic). In this case it can be indeed: finding (or failing to find) a peer in a sorted range is a binary search (\$\log(n)\$), which drives an overall complexity to \$n \log(n)\$.

Summing up, the template is

std::sort(std::begin(prices), std::end(prices));
for (auto it = std::begin(prices); it != std::end(prices); ++it) {
    auto peer = std::upper_bound(it, std::end(prices), target - *it);
    if (*it + * peer == credit) return std::make_pair(it, peer);
 }

PS: since the problem statement guarantees that the solution exists, I didn't bother to check that peer != end(prices).

PPS: the second phase could be completed in a linear time, but due to presence of sort it doesn't matter here.


How to efficiently find if numbers in a given range contains either 1 or 3, but not both?

A Bug

if (numOf1 > 0 || numOf3 > 0) {
    total++;
}

That overcounts. The definition of "lucky number" included "if it contains both 1 and 3, it is not a lucky number", but numbers that contain both a 1 and a 3 are counted. The break in the while-loop exits that loop when that condition is detected, but then the code above still runs. You could use:

if ((numOf1 > 0) != (numOf3 > 0)) {
    total++;
}

The != between two booleans is a slightly tricky way to say "one of them but not both". Of course that can be written out more explicitly.

An other bug

int total = 0;

Do you know how big the result is? By my count it's just over 3.48 billion. That's a problem, int only goes just over 2.14 billion. The count doesn't go over 4.29 billion, so you could still use int, and then interpret it as an unsigned integer later (eg printing total & 0xFFFFFFFFL). But that's strange, a bit advanced, not for beginners. Using long total = 0; is a simpler and more sensible solution.

  Is there a way to make this more efficient for range from 10000000000 to 20000000000?

There are some specific properties of that range that you could use.

First, let's ignore 20000000000 itself, it contains neither a 1 nor a 3.

Then, every number in the range for sure has at least one 1 in it, so you don't need to test it, this is something you already know. That would let you simplify the test to "check if there is any 3 in the number".

Counting without brute force

Forgetting the leading 1, the numbers in our range have 10 "variable" digits.
How many 10-digit strings of digits 0..9 don't have a 3 in them? Every place has 9 possible digits left instead of 10, so rather than pow(10, 10) it will be pow(9, 10).

pow(9, 10) is something that you can calculate easily, even with just Math.pow(9, 10). It's normally not really proper to use doubles for integer calculations, but this one works.

  With my implementation, it takes around 160 seconds.

Does it actually? That's an order of magnitude faster than it runs on my PC.


Is my use of CSS inheritance clean enough for these sprites?

There hasn't been a good reason to use extra elements such as spans for purposes of hiding text in the last 10 years.  If you need to support very old browsers, negative indentation is the simplest method.  Otherwise, there's plenty of clean, modern techniques to choose from.

.foo {
    text-indent: -100em;
}

http://nicolasgallagher.com/css-image-replacement-with-pseudo-elements/
http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement/

There's not really a good reason to use nth-child here.  You'd be better off using self-documenting class names.  If the order of the images need to be adjusted, then you don't have to make modifications in multiple places (markup and CSS).

.introSelect .dentist {
  background-position: 0 -180px ;
}
.introSelect .patient {
  background-position: -90px -180px;
}
.introSelect .lab {
  background-position: -180px -180px;
}


First of all, I would apply the "Extract Method" refactoring method and put the logic behind generating a checksum into a get_checksum() function.

Also, I would avoid hardcoding the trailing "salt" and the 0x10000 "normalizer" and put them into the default keyword argument value and to a "constant" respectively.

You can use sum() instead of having loop with if and else, which increase the overall nestedness. But, it might become less explicit and potentially a bit more difficult to understand.

Comments and docstrings would definitely be needed to describe the logic behind the checksum calculations.

Variable naming can be improved - str_a, str_b and string are not the best choices (even though the part1 and part2 in the code below are not either - think about what these strings represent - may be you'll come up with better variable names). Also, note that you are reusing the string variable to keep the "ords" of each character, which, strictly speaking, is not good - the variable name does not correspond to what it is used for.

At the end you would have something like:

DEFAULT_SALT = "trailing"
NORMALIZER = 0x10000

def get_checksum(part1, part2, salt=DEFAULT_SALT):
    """Returns a checksum of two strings."""

    combined_string = part1 + part2 + " " + salt if part2 != "***" else part1
    ords = [ord(x) for x in combined_string]

    checksum = ords[0]  # initial value

    # TODO: document the logic behind the checksum calculations
    iterator = zip(ords[1:], ords)
    checksum += sum(x + 2 * y if counter % 2 else x * y
                    for counter, (x, y) in enumerate(iterator))
    checksum %= NORMALIZER

    return checksum

We can see that the test you've mentioned in the question passes:

$ ipython3 -i test.py
In [1]: get_checksum("foo", "one")
Out[1]: 9167


Rails models for Users, Offers, Comments, Documents, and Reviews

First thing is if they are different treat them different. You can share code with help of interaction or service of some other way may be with active active_interaction. But if you really want to have less table then you may define one single model say Content and this will have a column content_type: integer with default value as 0 and all your other columns then convert the content_type to enum something like below

class Content < ApplicationRecord
  enum content_type: { comment: 0, rating: 1 }
end

this will help you to differentiate between comment and rating. With proper indexing it will make no issue.


Hmmm.....

--
-- Application Database Structure
--

-- Company Table
CREATE TABLE company (
    id SERIAL PRIMARY KEY,
    name varchar(60) NOT NULL
);

This probably works, for now.  I'm assuming the column can handle weird characters, things like Chinese characters, if appropriate.  Please note that international business gets a little strange, in terms of things like subsidiaries, and companies doing business in foreign countries (not sure if important).

-- Country Table
CREATE TABLE country (
    id SERIAL PRIMARY KEY,
    name varchar(255) NOT NULL
);

You're going to want to add a 'localization' table, in addition to refactoring this.  Something along these lines:

-- Country Table
CREATE TABLE country (
    id SERIAL PRIMARY KEY,
    Iso3166_1_Alpha_3 char(3) NOT NULL,
    Iso3166_1_Alpha_2 char(2),
    Iso3166_1_Numeric char(3) NOT NULL
        -- This last is comprised of digits,
        -- But not really a number, per se
);

-- Country Localization table
CREATE TABLE country_localization (
    country_id INTEGER NOT NULL REFERENCES country (id),
    language_id INTEGER NOT NULL REFERENCES language (id),
    name varchar(100) NOT NULL
);

.... Which means you're going to want a 'language' table (and localization) as well.  You can use this as the base pattern - the relevant ISO code standard is ISO 639.

-- Location Table
CREATE TABLE location (
    id SERIAL PRIMARY KEY,
    name varchar(255) NOT NULL,
    country_id integer NOT NULL REFERENCES country (id),
    coordinate varchar(255) NOT NULL
);

I can't really say if name is appropriate - what are you planning on storing there?  Please note that addresses are incredibly varied in international settings.  Storing country is likely okay.  coordinate is almost certainly wrong; if postgreSQL has a geo extension/module, use the relevant types - otherwise, use a pair of doubles/reals, and store latitude/longitude.

-- Source Table
CREATE TABLE source (
    id SERIAL PRIMARY KEY,
    name varchar(60) NOT NULL
);

... source of what?

-- Payment Method Table
CREATE TABLE payment_method (
    id SERIAL PRIMARY KEY,
    name varchar(60) NOT NULL
);

You may need to internationalize this one, as well.  I'm assuming this is effectively an Enum (eg, 'VISA', 'MASTERCARD', etc).

-- Payment Table
CREATE TABLE payment (
    -- Generic
    id SERIAL PRIMARY KEY,
    ip varchar(255),
    email varchar(255) NOT NULL,
    amount varchar(255),
    payment_method_id integer NOT NULL REFERENCES payment_method (id),
    -- Credit Card
    card_name varchar(255),
    card_expiration varchar(255),
    -- Paypal
    paypal_email varchar(255),
    paypal_transactionid varchar(255)
);

email suggests that you should have some sort of 'payee' table, either as a person, business or... company.  Also, why do you have two emails in the table?  Try to avoid storing multiple logical 'entities' in the same table.   While I applaud not having a column for 'credit card number', if you're going to be able to track reversals, you're going to have to know what number to reverse (assuming that you accept non-PayPal transactions).
Even under IPV6, you don't need an ip address that long - the maximum address is 39 characters (including delimiters).
  amount should be either DECIMAL or NUMERIC (at least you didn't make it float/double/real...).
I'm also nervous about card_expiration being character-based.  Really, what you have is an 'expires before business day' column (eg - it's usually expressed as 'expires 07/2012', which is 'active before 2012-08-01'), which probably ought to be stored as a date (probably without time, given the possibility of DST moving, but probably with timezone).  Note that is still complicated, because, due to timezones (and ignoring any shifting business themselves do), there are 2 concurrent business (sun-has-come-up) days on the planet happening at once: when any particular bank/payment pre-processor switches is up to them.

-- Job Table
CREATE TABLE job (
    -- Identification
    id SERIAL PRIMARY KEY,
    solrid varchar (10),
    -- Job Information
    title varchar(60) NOT NULL,
    description varchar(255) NOT NULL,
    truncated_description varchar(255) NOT NULL,
    keyword_description varchar(255) NOT NULL,
    how_to_apply varchar(255) NOT NULL,
    website_url varchar(255) NOT NULL,
    logo_url varchar(255),
    page_url varchar(255) NOT NULL,
    -- Dates
    date timestamp NOT NULL,
    expires timestamp NOT NULL,
    -- Linked Tables
    company_id integer NOT NULL REFERENCES company (id),
    source_id integer NOT NULL REFERENCES source (id),
    location_id integer NOT NULL REFERENCES location (id),
    payment_id integer NOT NULL REFERENCES payment (id),
    -- Status Flags
    active boolean DEFAULT FALSE,
    premium boolean DEFAULT FALSE,
    indexed boolean DEFAULT FALSE,
    error boolean DEFAULT FALSE,
    -- Email Flags
    email_reminder boolean DEFAULT FALSE,
    email_confirmation boolean DEFAULT FALSE
);

What's solrid?  There's no explanation.
You may want to create some sort of website table that you can just fk-reference, including things like the site and logo there.
truncated_description isn't any shorter than description... is one supposed to be shorter?
You are probably going to want a (internationalized?) tag (and job_tag) table, taking the place of keyword_description; split user search terms, get all matching tags, and find the jobs with the highest number of matches (and potentially search the regular description as well).
What date does date represent?  postedOn?  paidForOn?  fufilledOn?  Always try to name columns descriptively as to what they logically represent; these will often not include the column type.
expires probably shouldn't be a timestamp type.  If you have it, it should be a date (sans time) type.  The reasoning is that it's an imprecise, business-related concept (actual close of business isn't necessarily midnight...).  This may apply to date as well, but the name is too ambiguous to be able to tell.  Date ranges should also (pretty much always) be upper-bound exclusive (this blog mostly deals with SQL Server-specific problems, but the concepts are equivalent); in light of that, the name should probably be changed to something like activeUntil (or store the duration instead).
Is active derived information - can I tell just by whether the current (business) day is between date and expires?  If so, unless you have an actual performance issue, it's best to not store it (ie what happens if active is true after expires is in the past?).

-- Advert Table
CREATE TABLE advert (
    -- Identification
    id SERIAL PRIMARY KEY,
    -- Content
    title varchar(60) NOT NULL,
    description varchar(255) NOT NULL,
    page_url varchar(255) NOT NULL,
    -- Dates
    date timestamp NOT NULL,
    expires timestamp NOT NULL,
    -- Email Flags
    email_reminder boolean DEFAULT FALSE,
    email_confirmation boolean DEFAULT FALSE
    -- Linked Tables
    source_id integer NOT NULL REFERENCES source (id),
    payment_id integer NOT NULL REFERENCES payment (id),
    -- Status Flag
    active boolean DEFAULT FALSE,
    error boolean DEFAULT FALSE
);

See previous remarks about date, expires and active.
Hmm, you may want some sort of 'reminder' and 'confirmation' table sets.

All I can think of at the moment.  Providing expected (example) data contents may also help us critique your efforts.


style

PEP8

There is one too many blank line after your imports.
It is debatable if there is too many blank lines in your decorator too. I personally think it's good without the blank lines.
If you ignore the docstring then 17.6% of the function is blank lines.

  Use blank lines in functions, sparingly, to indicate logical sections.

You may feel the white space is needed, and so this section can be happily ignored.

PEP257

  Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description.

Yours has this short summary with the elaborate description.
I would be thrown off if your summery came up in my IDE,as I would be confused where this example is.

  The docstring is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ..."

Your summary line is more of a description. I'm not good with words, but the summary could be changed to, "Decorate a function inside a pygame loop, at the specified tick-rate.".

  The docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.

Yours does not explain what tick_rate is. A good way to do this is also explained in the PEP.

"""Form a complex number.

Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""

I was thrown off a bit to see the event handler below the main of the code. I think there is no difference, however it's probably best to keep to the norm.

Overall there's almost no problems with your style. Your docstrings could follow PEP257 more, as the biggest problem would be the summarized line at the beginning.

code

You should add the ability to pass a function to handle pygame events.
This is as the programmer currently would have to use a hack to get user input, or not use the decorator. Both bad options.

for a rudimentary example of what the handler could look like:

def even_handler(event):
    if event.type == pygame.QUIT:
        raise SystemExit

You could however use pygame.quit();sys.exit(0), but then if you exit multiple times you would need to make a function to exit, and it would remove a little added abstraction.

you would then need to add it to the decorator. The nicest way would probably be:

def game_loop(event_function, tick_rate=60):

    # replace the current event handler.
    for event in pygame.event.get():
        try:
            event_function(event)
        except SystemExit:
            pygame.quit()
            sys.exit(0)

This has the downside of having to pass an event-handler, unless you pass a default one, like the one above. However it allows the programmer to handle user input, a must in most pygame applications.


Array based queue implementation with C++20

Avoid unnecessary copies
enqueue() takes its parameter by value, which means the caller has to make a copy. Then it has to store that value in the array, making another copy. You can avoid copies by replacing the function that takes a value with two overloads, one for const references and one for rvalue references:
void enqueue(const_reference_type val) {
    // same as before
    ...
}

void enqueue(value_type &&val) {
    // mostly the same
    ...
    // but now we move:
    data[current_size++] = std::move(val);
}

The first version will make just one copy, the second one will use move assignment, which might avoid an expensive copy.
Similarly, dequeue() makes a copy. You can avoid this by splitting this function in two; one that returns a reference to the head element so the caller can read it without having to copy it, and another function that just removes the head element. You already have a head(), so then just modify dequeue() to be:
void dequeue() {
    // mostly the same as before, except without returning anything
    ...
}

This is also why std::queue provides a separate front() and pop() function. Also, doing it this way makes the requirements for T less strict; it now only requires it to be std::default_constructible and std::movable.
Make it look like std::queue
Programming is much easier if everything has a similar interface. Consider renaming your member functions to match that of std::queue:

enqueue() -> push()
dequeue() -> pop()
head() -> front()
tail() -> back()

You could also add emplace() and swap() to make it almost a drop-in replacement.


Print the length of words as a vertical histogram

main()

Your main() does three things: print a prompt, count the frequencies, and print the histogram.  The latter two, in particular, are well-defined complex tasks, they each deserve to be a function.

If the input is redirected from a file, rather than typed directly on the console, then the > prompt just messes up the output.  To see if standard input is a console, you should test isatty() on Unix, or _isatty() on Windows.

int main() {
    int histogram[21];
    if (isatty(fileno(stdin))) {
        putchar('>');
    }
    count_word_lengths(stdin, histogram, sizeof histogram / sizeof histogram[0]);
    print_histogram(histogram, sizeof histogram / sizeof histogram[0]);
}

Counting

If the input ends abruptly with a word followed by EOF, with no intervening whitespace, then the last word doesn't get counted.

Instead of if (c != ' ' && c != '\n' && c != '\t'), consider using tests like isspace() and ispunct().  By the way, you are treating punctuation as if they were part of words, which is probably not the right behaviour.

If the input contains any word with length 10 or greater, then the counting terminates prematurely with no indication that anything went wrong.  (Personally, I'd choose to count all excessively long words as if it were the maximum length supported by the histogram array.)

Printing

Destroying the histogram data as you print is a bad idea, especially if it will cause a print_histogram() function to wipe out its input parameter.

Once you fix that, the printf("x ") and printf("  ") would be better with a ternary expression.

for (int row = 1; row <= max_word_frequency; ++row) {
    for (int i = 0; i < 9; ++i) {
        printf(row <= histogram[i] ? "x " : "  ");
    }
    putchar('\n');
}


Compute arithmetic sum of a constant difference sequence

I notice three things about your code:

You're relying on tail-recursion. This is okay if you know your program will only ever run on implementations that perform tail call optimization, but you should be aware that the Common Lisp standard does not require TCO (and more practically speaking some implementations do indeed not offer it). So if you want your program to be portable, you should rewrite it using a loop¹.
Your d-depth function takes d-n and a as parameters, but only uses a in place of d-n if d-n is nil. It'd make more sense to me to remove the a parameter and instead pass in the a value as the initial value for d-n (instead of nil).
I would also write d_n instead of d-n to emphasize that n is an index, which is usually written using an underscore in ASCII. Also I'd call d-n-plus-1 d_n+1 instead, there's no reason to spell out "plus" in lisp.

In response to your update:

  I'm not crazy about "loop for x from 1 to depth" or that I used setq in this version. Can you think of a better way?

for x from 1 to depth is equivalent to repeat depth (unless you actually use x, which you don't). However in your code you're actually starting at 0, not 1 so you'd need repeat (+ 1 x) to get the same number of iterations.

The setq can be replaced using the for var = start then replacement-form syntax. The result would be something like this:

(defun d-depth (depth a c b)
  (loop repeat (+ 1 depth)
        for d_n = a then (d_n+1 d_n c b)
        finally (return d_n)))

¹ Or in scheme :p


When to initialize infrequently used base class objects

First: I doubt that creating a new List<> object creates enough overhead which has measurable impact on your system so unless you can prove that it's a problem don't worry about it.

That being said: The classic solution to that problem is lazy instantiation. As you have a property already this can be easily achieved by:

public class ErrorBase
{
    public bool HasError { get; set; }

    private List<Error> _ErrorList = null;
    public List<Error> ErrorList
    {
        get
        {
            if (_ErrorList == null)
            {
                _ErrorList = new List<Error>();
            }
            return _ErrorList;
        }
    }

    public ErrorBase()
    {
        HasError = false;
    }
}

If you have multiple threads adding to it then you need to add some locking in the get - but then on the other hand List<> itself is not thread-safe so I assume that's not the case.

In .NET 4.0 and later you have Lazy<> which will make the code a little bit shorter.


Intersect knockoutjs observablearray using linqjs

I would not use linq.js for anything time sensitive, it is known to be slow, definitely compared to just using old skool for loops and arrays. Which is what I would use.

Other than, if I were to write this, I would consider naming some thing differently:

obsArray2 -> observableArray, there is no obsArray1, and it was not clear at first if obs means there are objects in the array or it is an observable arrays.
self -> anything but self which usually refers to this, perhaps enum1 ?
arrValues1 really contains an Enumerable which is not really an array, confusing, I would perhaps have chosen set1 because in maths, intersections are made of sets or enum1 because that is what the variable type is
Same for arrValues2 of course
intersectedValues -> I would have gone for simply intersection

Furthermore,

You have 2 return statements, there can be only one
It seems silly to go back to self and filter out only elements that are in the intersection, can't you build the return value from intersectedValues ?


Find the range of index of consecutive integers from a sorted array

Correctness:

Your code doesn't seem to actually produce the correct answer.

When I ran this code, I got:

0--5
6--6
7--10
11--11
12--14
15--15

However... the list has 17 elements, so 16--16 is missing.

The reason for this is that once you are done with the for loop, you do handle the case when the last two elements are part of a consecutive range, but in your test case, they aren't.

The way to fix this is very easy: remove the if. It should look like this:

for(int i = 1; i < length ; ++i) {
    // same as yours
}
end_index = length - 1;
list.put(start_index, end_index);

return list;

Style:

Aside from the things that Mayur already mentioned,

Comment your code. It took me many more minutes than it should have to figure out what it does.
Along the same vein, name things according to what they do. For example, I would rename findList (A completely pointless name... might as well have been foobar) to buildConsecutiveRangeMap. I would also change array1 to numbers, or at least drop the unnecessary "1". Lastly, prog is just a completely meaningless name for a class...rethink this.
Make " "'s matter. Why do you have extra spaces between public and Map? > and findList? Right before the return? At the same time, you could use more to make length -2 into length - 2, array[index]+1 into array[index] + 1 and so on.
Don't prematurely optimize. That's the only reason I could see for using another variable to store array1.length instead of using that everywhere. Little secret: It's just a field lookup that takes O(1) time and a modern day JIT will notice that that value is constant and optimize your loop for you.
Import just the things you need. It's a waste to include everything under the sun.

Other comments

Test, test, test. Testing would have led you to find the bug and helps developers figure out what you are trying to accomplish based on the expected output.
To clean things up, I suggest checking if the range is something like 15--15 and instead just print 15.
Don't waste your time allocating things when you don't need to. You allocate some memory for list1 in main and then in the findList method, you allocate some more. The garbage collector will of course clean this up...but it also makes your code uglier. Just replace your
code in main with:

Map<Integer, Integer> rangeMap = findList(numbers);

Another feature you might want is to print the numbers in order. The fact that the results happened to be in order is coincidence. A Map guarantees nothing about order and it is up to you to sort the data as you like. Testing different numbers and larger data sets will make this clear.


Cool stuff, though instead of declaring _isOpen property as a <boolean> in the service class, you should provide a new interface (as you added modalId).
Something like:

interface IModalElementStatus {
    isOpen: boolean;
    id: string;
}


Finding the nth element of generalized Fibonacci sequences

The easiest way to simplify this is to come up with a method to represent the various sequences efficiently. For example, the following represents each as a tuple of starting values, and a function that takes one tuple and returns another (the next step):

SEQUENCES = {
    'fibonacci': ((0, 1), lambda a, b: (b, a+b)),
    'tribonacci': ((0, 1, 1), lambda a, b, c: (b, c, a+b+c)),
    ...
}

The function to apply these is then a trivial dictionary lookup and a loop over the number of steps:

def fibgolf(name, n):
    """Calculate the nth value of the named sequence."""
    vals, func = SEQUENCES[name]
    for _ in range(n):
        vals = func(*vals)
    return vals[0]


optimize binary classification method for speed

Well, an obvious improvement is not redoing work. You are currently doing twice as much work as needed because you don't save the results of the comparisons:
def confused(sys1, ann1):
    predicted_true, predicted_false = sys1 == 1, sys1 == 0
    true_true, true_false = ann1 == 1, ann1 == 0

    # True Positive (TP): we predict a label of 1 (positive), and the true label is 1.
    TP = np.sum(np.logical_and(true_true, predicted_true))

    # True Negative (TN): we predict a label of 0 (negative), and the true label is 0.
    TN = np.sum(np.logical_and(true_false, predicted_false))

    # False Positive (FP): we predict a label of 1 (positive), but the true label is 0.
    FP = np.sum(np.logical_and(true_false, predicted_true))

    # False Negative (FN): we predict a label of 0 (negative), but the true label is 1.
    FN = np.sum(np.logical_and(true_true, predicted_false))
return TP, TN, FP, FN

This should speed up the calculation, at the cost of keeping things in memory slightly longer. Make sure you have enough memory available.
I'm not sure I got your true and predicted labels right, which goes to show that ann1 and sys1 are really bad names. Something like true and predicted would be vastly more readable. And while you're at it, write out the other variables as well. Characters don't cost extra.
np.logical_and works perfectly fine with integers (at least on normal numpy vectors, you should check that this is also the case for sparse vectors), so as long as your vectors can only contain 0 or 1, you can directly use the input vectors and save on half the memory:
not_true = np.logical_not(true)
not_predicted = np.logical_not(predicted)
true_positive = np.sum(np.logical_and(true, predicted))
true_negative = np.sum(np.logical_and(not_true, not_predicted))
false_positive = np.sum(np.logical_and(not_true, predicted))
false_negative = np.sum(np.logical_and(true, not_predicted))

Note that you cannot use ~true and ~predicted here, since that does two's complement or something like that...
Finally, note that I could not find proof for or against np.logical_and (or np.logical_not for that matter) being implemented efficiently for sparse vectors, so maybe that is where you actually loose speed. In that case, go and implement it in C and/or Cython and write a pull request for sparse, I guess...


Calculating the interest on a series of loans

Do not represent monetary amounts as a decimal type; use an integer type instead.
Try to avoid the use of using namespace std.
You could still allow the user to enter an interest rate and have the program convert it to a decimal, especially if the user doesn't know how to do this.
You could just have days, rate, and interest declared or initialized within the loop.  It's usually best to have variables kept in as close scope as possible.

Moreover, if you're going to "list" variables, have each one on a separate line.  This is easier to read and avoids the possibility of needing to scroll horizontally.


Getting a sum of added cells in an ultragridview

Your Concerns

  I was just wondering if you could help me write this code neater or more efficiently?

Efficiency

You are looping through the data twice. Once to calculate adjustedsum from column["PrevFY"] and once for column["BudgetAmt"]. In both cases, actualsum gets calculated exactly the same way. It seems you so badly wanted to reuse variables that you forgot you could have just looped through the rows and store data in multiple variables.

decimal actualsum = 0m;
decimal adjustedTotal = 0m;
decimal originalTotal = 0m;

for (int i = 0; i < 2; i++)
{
    var row = dgvBudget.Rows[i];
    actualsum += Convert.ToDecimal(row.Cells["Actual_c"].Value);
}

for (int i = 3; i < 12; i++)
{
    var row = dgvBudget.Rows[i];
    adjustedTotal += Convert.ToDecimal(row.Cells["PrevFY"].Value);
    originalTotal += Convert.ToDecimal(row.Cells["BudgetAmt"].Value);
}

nbrAdjustedTotal.Value = adjustedTotal + actualsum;
nbrOriginalTotal.Value = originalTotal + actualsum;

Compactness (neatness)

You have recurring decimal parsing from data cells:

Convert.ToDecimal(row.Cells["Actual_c"].Value)

You could make a utility method for this. I'm assuming the class for the data row is called Row.

private static decimal ParseDecimal(Row row, string columnName)
{
    return Convert.ToDecimal(row.Cells[columnName].Value);
}

Further refactored:

decimal actualsum = 0m;
decimal adjustedTotal = 0m;
decimal originalTotal = 0m;

for (int i = 0; i < 2; i++)
{
    var row = dgvBudget.Rows[i];
    actualsum += ParseDecimal(row, "Actual_c");
}

for (int i = 3; i < 12; i++)
{
    var row = dgvBudget.Rows[i];
    adjustedTotal += ParseDecimal(row, "PrevFY");
    originalTotal += ParseDecimal(row, "BudgetAmt");
}

nbrAdjustedTotal.Value = adjustedTotal + actualsum;
nbrOriginalTotal.Value = originalTotal + actualsum;

Proposed Result

We could make the code even more compact by using LINQ's Skip, Take and Sum extension methods. I don't have access to the code, but I'm sure you could do something like:

var rows = dgvBudget.Rows.Take(3);
var actualsum = rows.Select(row => ParseDecimal(row, "Actual_c")).Sum();
var rows = dgvBudget.Rows.Skip(3).Take(9);
var adjustedTotal = rows.Select(row => ParseDecimal(row, "PrevFY")).Sum();
var originalTotal = rows.Select(row => ParseDecimal(row, "BudgetAmt")).Sum();

nbrAdjustedTotal.Value = adjustedTotal + actualsum;
nbrOriginalTotal.Value = originalTotal + actualsum;

This does come with a slight performance penalty, since you loop the first 3 items twice (once to skip). But it comes at a good increase in readability and compactness.


Vertex class

The INF constant is used only as the initializer for Vertex::distance, so I'd inline the value directly, like this:

struct Vertex
{
    const int id;
    int distance = std::numeric_limits<int>::max();
    Vertex *parent = nullptr;

    Vertex(int id)
        : id(id)
    {}
};

I've inlined the initializers that don't depend on arguments, and I've removed the std::move cast that has no benefit for a primitive type.  Since that constructor is now the same as default, we can omit it.

Graph class

The vertex_count member can (and should) be declared const; that also requires it to be initialized (not assigned) in the constructor.  That said, there's no need for it, as we can always use vertices.size().

The constructor argument isn't obvious from the class definition - name it and if necessary also add a comment.

Naming: distance_from_source() sounds like it can be used to obtain the results, but it actually prints to standard output.  I'd rename it to something like (using #include <iosfwd>):

std::ostream& print_distances(std::ostream&) const;

Constructor

We should tell the vector its final size, so it can reserve capacity and avoid multiple allocations.

We can use emplace_back() to simplify the population of the vector:

Graph::Graph(int v)
    : vertex_count(v)
{
    vertices.reserve(vertex_count);
    for (int i = 0;  i < vertex_count;  ++i) {
        vertices.emplace_back(i);
    }
}

Adding edges

The add_edge method doesn't check that src and dest are within range, and it does nothing if an edge already exists.  We can easily detect these conditions:

void Graph::add_edge(int src, int dest, int weight)
{
    if (src == dest) {
        throw std::logic_error("src==dest");
    }
    if (src < 0 || vertex_count <= src) {
        throw std::out_of_range("src");
    }
    if (dest < 0 || vertex_count <= dest) {
        throw std::out_of_range("dest");
    }

    auto const inserted = edge_weight.insert({ {src, dest}, weight });
    if (!inserted.second) {
        throw std::logic_error("existing edge");
    }
}

I recommend changing the index type from int to an unsigned type (e.g. std::size_t) as negative values are not valid.

Also, the use of std::pair rather than a specific structure makes it hard to follow code full of first and second all meaning different things.

Relaxing weights

It's inefficient to have to re-find() an edge.  However, we're passing weight to avoid that, so just re-use it:

void Graph::relax(int src, int dest, int weight)
{
    auto & existing = vertices[dest].distance;
    auto const proposed = vertices[src].distance + weight;
    if (proposed < existing) {
        existing = proposed;
    }
}

I've dropped the update to parent since we never use it.

Bellman-Ford computation

If we want to recalculate with a different origin node, we'll need to reset initial distances to maximum, as well as setting the origin to zero.

Modified program

#include <iosfwd>
#include <vector>
#include <map>

class Graph
{
    using index_type = std::size_t;
    using distance_type = int;

    static const distance_type max_distance;

    struct Vertex
    {
        const index_type id;
        distance_type distance = max_distance;
    };

    struct Edge
    {
        index_type from;
        index_type to;
        bool operator<(const Edge& other) const
        {
            return std::tie(from, to) < std::tie(other.from, other.to);
        }
    };

    std::vector<Vertex> vertices = {};
    std::map<Edge,distance_type> edge_weight = {};

public:
    Graph(index_type size);
    void add_edge(index_type from, index_type to, distance_type weight);
    bool bellman_ford(index_type origin); // true if no negative cycles
    std::ostream& print_distances(std::ostream&) const;

private:
    void relax(index_type from, index_type to, distance_type weight);
};

// Implementation

#include <limits>
#include <ostream>

const Graph::distance_type Graph::max_distance
    = std::numeric_limits<distance_type>::max();

Graph::Graph(index_type size)
{
    vertices.reserve(size);
    for (index_type i = 0;  i < size;  ++i) {
        vertices.push_back(Vertex{i});
    }
}

void Graph::add_edge(index_type src, index_type dest, distance_type weight)
{
    if (src == dest) {
        throw std::logic_error("src==dest");
    }
    if (vertices.size() <= src) {
        throw std::out_of_range("src");
    }
    if (vertices.size() <= dest) {
        throw std::out_of_range("dest");
    }

    auto const inserted = edge_weight.insert({ Edge{src, dest}, weight });
    if (!inserted.second) {
        throw std::logic_error("existing edge");
    }
}

void Graph::relax(index_type src, index_type dest, distance_type weight)
{
    auto& existing = vertices[dest].distance;
    auto const proposed = vertices[src].distance + weight;
    if (proposed < existing) {
        existing = proposed;
    }
}

bool Graph::bellman_ford(index_type src)
{
    // initialise distances
    for (auto& vertex: vertices) {
        vertex.distance = max_distance;
    }
    vertices[src].distance = 0;

    // relax edges
    for (index_type i = 1;  i < vertices.size();  ++i) {
        for (auto edge: edge_weight) {
            relax(edge.first.from, edge.first.to, edge.second);
        }
    }

    // check for negative-weight cycles
    for (auto edge: edge_weight) {
        auto const& from_vertex = vertices[edge.first.from];
        auto const& to_vertex = vertices[edge.first.to];
        if (to_vertex.distance > from_vertex.distance + edge.second) {
            return false;
        }
    }

    // success!
    return true;
}

std::ostream& Graph::print_distances(std::ostream& os) const
{
    os << "Vertex\t\tDistance from Source\n";
    for (auto vertex: vertices) {
        os << vertex.id << "\t\t" << vertex.distance << "\n";
    }
    return os;
}

// Test program

#include <iostream>

int main()
{
    Graph grp(5);
    grp.add_edge(0, 1, 6);
    grp.add_edge(0, 2, 7);
    grp.add_edge(1, 3, 5);
    grp.add_edge(1, 4, -4);
    grp.add_edge(1, 2, 8);
    grp.add_edge(2, 3, -3);
    grp.add_edge(2, 4, 9);
    grp.add_edge(3, 1, -2);
    grp.add_edge(4, 0, 2);
    grp.add_edge(4, 3, 7);

    if (grp.bellman_ford(0))
        std::cout << "Graph contains no negative cycle \n";
    else
        std::cout << "Graph conatins negative cycle \n";

    grp.print_distances(std::cout);
}


This line seems to be left over from a debugging session:

#import pudb; pu.db

But there is no need to edit your code to debug it — and you should strive to avoid doing so, because it's too easy to forget to remove the debugging code. (And in your other question you did forget to remove it!)

Instead, learn how to use the tools. You can run the built-in debugger pdb from the command line like this:

$ python -mpdb myprogram.py

and you can run pudb from the command line as described in the documentation.
The docstring is written from the wrong point of view:

"""Implement bubblesort algorithm: iterate L to R in list, switching values
if Left > Right. Break when no alterations made to to list. """

Docstrings should be written from the user's point of view: What does this function do? How should I call it? What values does it return? What side effects does it have? For example:

>>> help(abs)
Help on built-in function abs in module builtins:

abs(...)
    abs(number) -> number

    Return the absolute value of the argument.

Your docstring is written from the point of view of the implementer. This kind of material should be in comments.
You spelled your variable list_ to avoid shadowing the built-in function list. I would prefer to find a better name for the variable rather than arbitrarily respelling it like this. Since your algorithm works on any mutable sequence (not just lists), then seq might be a good name.
Instead of:

else:
    if condition:
        code

write:

elif condition:
    code

You have a special case:

if val == len(list_)-1: val = 0

to ensure that val + 1 does not run off the end of the list. But it would be better to stop the iteration before that happens. So instead of:

for val, item in enumerate(list_):

write:

for val in range(len(list_) - 1):

val is an index into the list: it's conventional to give such variables names like i and j.
Each time around the while not_complete loop, you make a pass over the whole of the sequence. But there is an easy optimization, noted by Wikipedia:

  The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n-1 items when running for the n-th time.

So I would write it like this:

def bubble_sort(seq):
    """Sort the mutable sequence seq in place and return it."""
    for i in reversed(range(len(seq))):
        finished = True
        for j in range(i):
            if seq[j] > seq[j + 1]:
                seq[j], seq[j + 1] = seq[j + 1], seq[j]
                finished = False
        if finished:
            break
    return seq

You have some test code at the end of the script. It is best to organize test code like this into unit tests using the unittest module. For example:

from unittest import TestCase
from random import random

class BubbleSortTest(TestCase):
    def test_bubble_sort(self):
        seq = [random() for _ in range(4000)]
        sorted_seq = sorted(seq)
        self.assertEqual(bubble_sort(seq), sorted_seq)

Note how I've used randomization to get a wider range of test cases. (I've also made the length of the test array large enough to give a noticeable delay and so emphasize how poor an algorithm bubble sort is.)


Treat undef in Perl's  operator as +inf instead of 0

In fact, Perl treats undef as 0 in numeric contexts, and warns about that (why there's no -w in your one-liner?). You can use the defined-or operator to handle it:

sort { ($a // 'Inf') <=> ($b // 'Inf') } 3, undef, 2, 1

You need Perl v5.10+ for it to work, in older versions, you have to be more verbose:

(defined $a ? $a : 'Inf')


Finding person with most medals in Olympics database

This alternative to @rolfl's answer is more readable, in my opinion.  It also has a more efficient execution plan.

WITH medal_count AS (
    SELECT athlete
         , SUM(total_medals) AS grand_total_medals
         , RANK() OVER (ORDER BY SUM(total_medals) DESC) AS rank
        FROM Olympics
        GROUP BY athlete
)
SELECT athlete
     , grand_total_medals
    FROM medal_count
    WHERE rank = 1
    ORDER BY athlete;

SQLFiddle


Kotlin reflection to generate one class from class similar with similar properties

inline functions

inline function are great when:

You want to surround a lambda with a little code
You want to use reified types.

They are not great when you have a large function, as every call to that function will be replaced with the body of the function.

Therefor, inlining apiToDomain seams the wrong choice.
You have another function: API.toDomain.

associate

I found the following in your code:
    map{ it.a to it.b }.toMap()

This can replaced by:

associate{ it.a to it.b }

(it can be used if you have one parameter)

associateWith

In kotlin 1.3, you can use associateWith for simpleConstruct:

val map = listOf(1,2,3).associateWith{ it.toString }
println(map) // [1:"1", 2:"2", 3:"3"]

when

your when looks like

when {
    param.type.classifier == List::class ->
    param.type.classifier == DateTime::class ->
    else ->
}

this can be simplified to:

when(param.type.classifier) {
    List::class ->
    DateTime::class ->
    else ->
}

run

in your function, you use {...}(). run{} does exactly the same, but you can't forget to invoke it. This is however a personal choice.

function bodies

I personnaly don't like functions where the body starts with return:

fun fromApi(apiModel: API): DOMAIN {
    return apiToDomain(apiModel, clazz)
}

you can rewrite this as:

fun fromApi(apiModel: API): DOMAIN = apiToDomain(apiModel, clazz)

or even like:

fun fromApi(apiModel: API) = apiToDomain(apiModel, clazz)

typealias

I dont know exactly the purpose of

abstract class Adapter<A, B> : (B) -> A

but maybe you can use a typealias?

typealias Adapter<A, B> = (B) -> A

constructing

I thing you forgot a keyword in front of your constructor? As you wrote it out and you have a companion-object that creates a type of your class...
Ps. If you want to construct in your companion-object, but it should look like a constructor-call, you can use operator fun invoke(...)

Hope this helps a bit


How about using Generate as prefix?

GenerateMonitorPacket
GenerateControlTempPacket
GeneratePutPeakInfoPacket
GenerateGetPeakInfoPacket

Alternatively, you can also create a separate class for each type of packet generator. You've only shown the code to create the packet for Monitor, so I don't know how complex the code for the other packets is, but separating these four methods into their own class might be logical and beneficial in the long run. If you create separate classes, you put the name of the packet (Monitor, ControlTemp, PutPeakInfo and GetPeakInfo) in the class name.

public class MonitorPacketGenerator
{
    public byte[] Generate(int ddcNum) { ... }
}


Mutable keys are a very bad idea, try this:

public void Foo()
{
    var mutable = new Mutable { Value = 1 };
    var dictionary = new Dictionary<Mutable, string> { { mutable, "one" } };
    mutable.Value = 2;
    var explodesHere = dictionary[mutable];
}

public class Mutable
{
    public int Value;

    public override int GetHashCode()
    {
        return Value;
    }
}

GetHashCode must not change while the instance is used in a collection that relies on the value. There are two ways to solve this:

Calculate the hash from values that cannot change. Prefer this wherever possible.
Make sure that the values affecting the hash are not changed while the instance is used in a collection. This is a pit of failure.

You can create a dictionary passing in an IEqualityComparer<TKey>
About your example:

ID reads like a property that uniquely identifies an entity and does not change.
If this is the case it is a nice candidate to use as a key. I'm guessing a bit here but I'm getting a feeling you really want:

var idNameMap = new Dictionary<int, string>();
idNameMap.Add(t1.ID, t1.Name);


Really your question boils down to whether or not there is a better way to set a custom function. That's hard to say because your approach will work fine. Really any kind of answer your going to get is largely subjective.

For me I tend to avoid the prototype method for objects unless I'm overriding or extending some other function or object. You started on the right track with your declaration of the SliderControl object; you can incorporate your prototype into that method declaration as well to greatly simplify and encapsulate your code.

It could use some cleanup I'm sure but here's my quick take.

<!DOCTYPE>

  <title>Slider</title>
  <meta charset="utf-8" />

The value is 0.4

Now above and beyond your initial question...

To make your slider more portable (and practical) you should also create the dom structure in the object so that all you have to pass in during initialization is the element you'd like to put it in.

You'll also want to add the ability to set a default value, in case you're loading and editing preset data.

I would also suggest removing 'actionWhenActive' and 'actionWhenSet' and replacing them with your existing 'action' and a new 'actionSet' function. You can check if one or the other is null or undefined to give you the same effect as the booleans. This will also give your slider the ability to perform both operations (ie displaying a value, and then saving it when done).


Error handling for Stripe credit card processing

Your first step would be to separate out actually rendering the error message from rescueing the exceptions:

def render_errors(errors, template: :err_show,  status: :payment_required)
  render template, status: status, json: errors
end

Then can you group the majority of the exceptions:

rescue Stripe::InvalidRequestError,
       Stripe::AuthenticationError
       Stripe::APIConnectionError,
       Stripe::StripeError => e

render_errors( stripe_error(e) )

A good idea would be then to separate generating the errors and logging them.


I would use functools.partial() to pass the block size into the comparator
choose more explicit and readable variable names - left, right and block_size instead of l, r and r
there is a simpler way to create an expected result dictionary:

expected_result = {key: sum(a[left:right+1]) for key, (left, right) in queries.items()}

we can unpack left and right range borders instead of getting them by index
note that there is no cmp in Python 3 anymore - you would have to use the cmp_to_key() helper to make it work

Improved code:

from functools import partial
import math

def compare(block_size, x, y):
    """The heart of the Mo's algorithm - determines if a range preceeds another."""
    _, (x_left, x_right) = x
    _, (y_left, y_right) = y

    if x_left / block_size != y_left / block_size:
        return x_left / block_size < y_left / block_size

    return x_right < y_right

def get_expected_result(a, queries):
    """Calculates given queries as sums of given ranges."""
    return {key: sum(a[left:right + 1]) for key, (left, right) in queries.items()}

def mos_algorithm(a, queries):
    """Mo's algorithm implementation."""
    block_size = math.sqrt(len(a))

    cur_sum, cur_left, cur_right = 0, 0, -1
    result = {}
    for key, (left, right) in sorted(queries.items(), cmp=partial(compare, block_size)):
        while cur_right < right:
            cur_right += 1
            cur_sum += a[cur_right]

        while cur_right > right:
            cur_sum -= a[cur_right]
            cur_right -= 1

        while cur_left < left:
            cur_sum -= a[cur_left]
            cur_left += 1

        while cur_left > left:
            cur_left -= 1
            cur_sum += a[cur_left]

        result[key] = cur_sum

    return result

if __name__ == '__main__':
    a = [1, 1, 2, 1, 3, 4, 5, 2, 8]
    queries = {0: [0, 5], 1: [5, 8], 2: [2, 4], 3: [5, 6]}

    result = mos_algorithm(a, queries)
    expected_result = get_expected_result(a, queries)

    print(result)
    print(expected_result)

Prints:

{0: 12, 1: 19, 2: 6, 3: 9}
{0: 12, 1: 19, 2: 6, 3: 9}


Click n times on image to match with random number n

The code looks clean and well readable and with one exception I would say there is nothing wrong with it per se, however you are using several unusual approaches.

The task asks for

  A text element to show result

I'm not sure what a "text element" means here, but it could be an <input type="text">. However that would be wrong, since there are for input and not output. Your choice of a <b> element is better, but HTML 5 provides the <output> element, that would be even more suitable.

Your choice to collect your variables in objects (elements, data, events)  seems somewhat arbitrary. It's not wrong, and after getting used to it, it actually helped readability somewhat (except that now almost all lines begin with elements...., which seems a bit repetitive).

Just be aware that it's an unusual thing to do, because people usually expect objects like that to have sort of technical use, instead of just grouping variables.

The use of the comma operator to separate statements (or to be exact expressions) instead of semicolons (or just line breaks) is very unusual. Since the comma operator is very rarely used, it can be confusing for beginners and experts may try to find deeper meaning to it, even when there is none. Especially the first line of init() irritated me for a moment, because there is no line break after the commas, so that it looks like some special is happening, which isn't.

The only point that I consider wrong: The use of && instead of a regular if. This (and the use of the comma operator) looks like you are trying to emulate the kind of "optimizations" that code compressors do. Don't do this. It compromises readablily. If you want to serve compact code, then use a code compressor.