Test whether a number is a Harshad Number

Written for NASM

Your program is a little hard to follow, mostly due to poor formatting. There is a lot of unnecessary duplication too and the user has no opportunity for correcting mistakes. The following prologue will address these initial criteria;

Prompt operator for what is required.
Use a function that allows the user to correct mistakes.
Test that entry is 4 characters long and the first digit is not zero.

      org   0x100

      DOS   equ 21H
     SHOW   equ  9
 BUFFERED   equ 10  ; Buffered input
   OUTCHR   equ  2
   GETCHR   equ  8

Begin:  mov ah, SHOW        ; Function 9 display string terminated with '$'
        mov dx, Prompt
        int DOS

        mov ah, BUFFERED    ; Function 10 Get buffered input
        mov dx, Entry
        int DOS

; Test that your criteria of 4 character entry and first digit not zero has been met.

        cld                 ; Make sure SI auto-increments
        mov si, dx
        inc si              ; Point to number of characters entered
        lodsb
        or  al, al
        jz  Err             ; You might want to put some sort of prompting text here
        cmp al, 4
        jnz Err
        cmp byte [si], '1'
        jae Evaluate

Err:    mov ah, SHOW        ; Function 9 again
        mov dx, ErrTxt
        int DOS
        ret                 ; Return to DOS

You do have these elements in your program, but I think you'll agree when there are in one place it's a lot easier to recognize which error testing mechanism has been implemented. Notice too, formatting is monumentally important, especially in ASSM.

Now we are ready to do the calculations and because we're not going to be using any DOS functions, there is a little more freedom in which registers we can use and for what. The criteria now becomes, establish a binary value of our entry and binary total of all digits.

Evaluate:

    ; AX = Working register, CX = character count

        movzx   cx, al      ; Move character count into CX
        xor     dx, dx      ; DX will be binary representation of input
        mov     bx, dx      ; BL will be total of digits
        mov     ax, dx

  .get: lodsb           ; Read character from input string
        cmp     al, '0'
        jb      Err
        cmp     al, '9'
        ja      Err

       and      ax, 1111b   ; Could be SUB AL,'0' too.
       add      bl, al      ; Bump total of digits
       xchg     ax, dx
       imul     ax, 10
       add      dx, ax
       loop     .get

     ; Now DX = Binary equivalent and BL divisor

        xor     ax, ax
        xchg    ax, dx
        push    ax          ; Going to need this again to determine if Special
        idiv    bx
        or      dl, dl      ; Determine if value is Harshad or not.

From this point I'd pretty much be doing the same as you have except there is still no need to address anything in memory other than prompting text as everything you need is on the stack and BL. Let us know what you come up with then we'll compare it with what I have.


Get title from database based on member country

Firstly, for questions like this is would be helpful to provide an SQL fiddle. I mocked one up to test on, it only takes a few minutes but would be much faster for you since you have the table definitions.

  Is it really necessary to have here 2 nested while clauses? Or can I get both in one SQL?

You can absolutely get everything you need in one SQL query without nested queries. In fact, you should. Performing database queries within a loop is never ideal and it's always a better idea to get the data you need (even if slightly more than you need) then filter it down with PHP to avoid having to do multiple queries.

The logic

  I want to get the first N members that have at least one address in the country "US" and I want to display all their titles.

OK - so you're aiming for two things - the member's name and their titles. Your conditions are based on the address table data, so you should start your query there:

SELECT `idMember` FROM `address`
WHERE `country` = 'US'
GROUP BY `idMember`
LIMIT 2

Your at least one address in the country "US" condition is covered by WHERE country = 'US', and the GROUP BY will limit your duplicated rows. If you want to see how many addresses each member has (or filter on it) you can add COUNT(*) to the select clause to see. You will adjust the LIMIT as required.

This gives you the member IDs that you need to retrieve titles for. From here, just query the tables you need and join the results above:

SELECT `member`.`id`, `member`.`name`, `title`.`name`
FROM `title`
INNER JOIN `title2memb` ON `title2memb`.`idRank` = `title`.`id`
INNER JOIN (
  SELECT `idMember` FROM `address`
  WHERE `country` = 'US'
  GROUP BY `idMember`
  LIMIT 2
) AS `us_members`
  ON `us_members`.`idMember` = `title2memb`.`idMember`
INNER JOIN `member` ON `member`.`id` = `us_members`.`idMember`;

Note that I've added the member's ID here because you'll use it to group the result set with PHP, as MySQL as a relational database is not able to return multi-dimensional results (see NoSQL/MongoDB/DynamoDB etc if you want that!).

  I have avoided using prepared statements and encoding the input to make the code more readable. I know that the here presented version is vulnerable to XSS.

Noted - won't comment on that.

To implement, you can do something like this:

$country = 'US';
$limit = 2;

$sql = '
    SELECT `member`.`id`, `member`.`name`, `title`.`name` AS `title_name`
    FROM `title`
    INNER JOIN `title2memb` ON `title2memb`.`idRank` = `title`.`id`
    INNER JOIN (
      SELECT `idMember` FROM `address`
      WHERE `country` = "' . $country . '"
      GROUP BY `idMember`
      LIMIT  ' . $limit . '
    ) AS `us_members`
      ON `us_members`.`idMember` = `title2memb`.`idMember`
    INNER JOIN `member` ON `member`.`id` = `us_members`.`idMember`;
';

$membersResult = $db->query($sql);

// Use PHP to group the results by the member ID
$members = array();
while ($member = $membersResult->fetch_assoc()) {
     // Track the member's name and an array of titles against their ID (which is unique)
     if (!array_key_exists($member['id'], $members)) {
        $members[$member['id']] = array(
            'name' => $member['name'],
            'titles' => array()
        );
     }
     // Add the title
     $members[$member['id']]['titles'][] = $member['title_name'];
}

This will give you a simple structured array like so:

Array
(
    [1] => Array
        (
            [name] => Bernd
            [titles] => Array
                (
                    [0] => Bee
                )
        )
    [3] => Array
        (
            [name] => Tom
            [titles] => Array
                (
                    [0] => Bear
                    [1] => Dog
                )
        )
)

Now, loop that array and output the data how you want to:

foreach ($members as $memberId => $member) {
    echo sprintf('%s: %s<br>', $member['name'], implode(' ', $member['titles']));
}

Example output (from a browser):

Bernd: Bee
Tom: Bear Dog

General formatting

While we're here, you should consider a few best practices:

Use single quotes always, unless you require double quotes
Choose a rule for indentation and stick to it. Four spaces is generally accepted as "the norm" for PHP (see while contents)
Add spaces before and after brackets in control structures (see while)
Space out arguments in function calls (see $db)


"abcdefghijklmnopqrstuvwxyz" is just the constant string.ascii_lowercase.

Whenever you have this pattern:

some_list = []
for dummy in some_iterable:
    some_list.append(some_function_of(dummy))

… that's a candidate for replacement with a list comprehension.

alpha.index(letter) and its inverse could be a performance issue when processing longer messages.  Making a dictionary for the translation table would be better.  Note that any character that is not ASCII lowercase will cause a ValueError.  For encrypt(),

translation = dict(zip(key, string.ascii_lowercase))
ciphertext = ''.join(translation.get(c, c) for c in original)

Here, translation.get(c, c) causes unrecognized characters to be passed through.  You can use translation[c] to restore the original exception-raising behaviour.


Your implementation depends on this.leaderboard.sort((a, b) => a.score - b.score);. Each and every time you insert, you sort again.

Depending on your access pattern, you could defer the sorting from adding to reading.

You could operate with a dictionary keeping the scores unorderd which makes inserting fast. And sort the entries only in case if you read them.

For the sake of the example I used plain numbers

let leaderboard = {
}

const addScore = (board, score) => {
  if(!board[score]) board[score] = []
  board[score].push(score)
  return board;
}

const getcurrentRanks = (board) => {
    const scoreranks = Object.keys(board).sort((a,b)=>b-a)
    return scoreranks.reduce((o,n )=>{
        return o.concat(board[n]);
    }, []);
}

But this has the downside of converging to your first implementation the more you read; e.g. for each time you insert a value you want to get all the ranks.

Otherwise I would encourage you to look into priority queues.


Optimize a parallelized program to optimize train schedules

Do not use using namespace std as it could cause clashing issues, which will introduce bugs.  More info about that here.
This is very unorganized:

#include <iostream>
#include <string>
#include <vector>
#include <time.h>
#include <cmath>
#include <iterator>

#include <algorithm>

#include <fstream>
#include <stdlib.h>
#include <sstream>

#include <stdlib.h>

#include <thread>
#include <random>

Steps to improve this:

Make sure there aren't any libraries that you aren't currently using or have repeated.
Make sure you aren't using any C libraries (which end with .h).  They should be replaced with the equivalent C++ library so that everything will be in the std namespace.
Sort them in a certain order for organization, such as alphabetically.  This will make it easier to locate certain libraries during maintaining.

Assuming every library is still being used, this is what it could look like:

#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <iterator>
#include <random>
#include <sstream>
#include <string>
#include <thread>
#include <vector>

This is one #include shorter because you've included <stdlib.h> twice.  Had this list been organized from the beginning, this wouldn't have been likely to happen.
Do not use global variables:

vector<Zug> Zuege;

int Planungsintervall;
int AnzahlZuege;
int AnzahlSchattenzuege;

They are accessible throughout the entire file or program, and can possibly be modified without your knowledge.  This can greatly hurt maintainability and also introduce bugs.  You should keep them in local scope, such as in a function, and pass them to other functions as needed.  This will make it much easier to keep track of their locality and determine how they're used.
The inline keyword likely won't offer you any benefit here.  The compiler is free to decide what should really be inlined and can ignore any explicit use of it.  It merely serves as a hint.
There is absolutely no need to call std::rand() when you're using C++11 and have already included <random>.  You should utilize this library and ditch std::rand() altogether.

Regarding the usage of std::rand() itself, you don't even call std::srand(), meaning you'll get the same random values with each call to std::rand().  Have you not even noticed this?
Why are you mixing std::vectors and dynamically-allocated arrays?  Vectors are the same type of array, but much more specialized.  You should ditch all the arrays and just use vectors (or any suitable storage container).  You end up passing these arrays (specifically the pointer to their first respective elements), which can get very nasty in C++, especially because memory-management will now be in your hands.  Just utilize storage containers and let them handle the dirty work for you (which is very necessary, as you fail to deallocate memory with delete, causing the whole program to leak memory).  They will also allow you to ditch the size variables since storage containers already keep track of their sizes (accessible via size()).
Since you use argv[1] in main() as the only command line argument, I assume that you're only expecting one additional argument.

In order to make sure that this argument is provided, check the value of argc at the start, before using argv[1].  If it's less than 2, terminate the program.  You may also print an error message to inform the user of this error.

if (argc < 2)
{
    std::cerr << "A filename argument is required!";
    return EXIT_FAILURE;
}

To sum it up:

This is quite broken and messy.  I'm sure there are other issues besides the ones I've mentioned, but this should address many of them.  Before worrying about optimization, I'd recommend cleaning this up and making sure it runs smoothly and correctly.


It would be a lot simpler to work out the length yourself rather than to interpret the results of encodeURI().
/**
 * Count bytes in a string's UTF-8 representation.
 *
 * @param   string
 * @return  int
 */
function getByteLen(normal_val) {
    // Force string type
    normal_val = String(normal_val);

    var byteLen = 0;
    for (var i = 0; i < normal_val.length; i++) {
        var c = normal_val.charCodeAt(i);
        byteLen += (c & 0xf800) == 0xd800 ? 2 :  // Code point is half of a surrogate pair
                   c < (1 <<  7) ? 1 :
                   c < (1 << 11) ? 2 : 3;
    }
    return byteLen;
}

JavaScript implementations may use either UCS-2 or UTF-16 to represent strings.
UCS-2 only supports Unicode code points up to U+FFFF, and such Unicode characters occupy 1, 2, or 3 bytes in their UTF-8 representation.  This is not too tricky to handle.
However, as @Mac points out, UTF-16 surrogate pairs are a tricky special case.  UTF-16 extends UCS-2 by adding support for code points U+10000 to U+10FFFF, which UTF-16 encodes using a pair of code points.  The first code point of such a pair (called the "high surrogate") is in the range D800 to DBFF; it should always be followed by another code point (called the "low surrogate") is in the range DC00 to DFFF.  Observe that the UTF-8 representation of any character in the range U+10000 to U+10FFFF would take 4 bytes.  Therefore, any surrogate pair in UTF-16 would translate to a 4-byte UTF-8 representation.  Or, we could say that whenever we encounter half of a surrogate pair (i.e., a code point is in the range from D800 to DFFF), just add two bytes to the UTF-8 length.


It is unclear what toolchain do you use and what is target processor. However, I can guess about performance degradation. pow function usually works with floating point values. Moreover, most probably power with negitive exp will also use division.
I compiled following code with ARM gcc 8.2 with -O3 flag:
#include <math.h>

int idiv(int a, int b) {
    return a * (pow(b, -1));
}

int idiv2(int a, int b) {

    return a/b;
}

I've got following assebly listing:
idiv:
        push    {r4, r5, r6, lr}
        mov     r6, r0
        mov     r0, r1
        bl      __aeabi_i2d
        mov     r2, r0
        mov     r3, r1
        mov     r0, #0
        ldr     r1, .L4
        bl      __aeabi_ddiv
        mov     r4, r0
        mov     r0, r6
        mov     r5, r1
        bl      __aeabi_i2d
        mov     r2, r0
        mov     r3, r1
        mov     r0, r4
        mov     r1, r5
        bl      __aeabi_dmul
        bl      __aeabi_d2iz
        pop     {r4, r5, r6, pc}
.L4:
        .word   1072693248
idiv2:
        push    {r4, lr}
        bl      __aeabi_idiv
        pop     {r4, pc}

From assebly code the reson of performance problems is obvious. And we still dependent on ABI.
If you want to have code that uses only assebly instructions? then you can implement integer division with "shift and subtract". Or you can google for some open source implementation of it. For example I found one here. Here is slightly modified example from here:
void unsigned_divide(unsigned int dividend,
             unsigned int divisor,
             unsigned int *quotient,
             unsigned int *remainder )
{
  unsigned int t, num_bits;
  unsigned int q, bit, d;
  int i;

  *remainder = 0;
  *quotient = 0;

  if (divisor == 0)
    return;

  if (divisor > dividend) {
    *remainder = dividend;
    return;
  }

  if (divisor == dividend) {
    *quotient = 1;
    return;
  }

  num_bits = 32;

  while (*remainder < divisor) {
    bit = (dividend & 0x80000000) >> 31;
    *remainder = (*remainder << 1) | bit;
    d = dividend;
    dividend = dividend << 1;
    num_bits--;
  }

  /* The loop, above, always goes one iteration too far.
     To avoid inserting an "if" statement inside the loop
     the last iteration is simply reversed. */
  dividend = d;
  *remainder = *remainder >> 1;
  num_bits++;

  for (i = 0; i < num_bits; i++) {
    bit = (dividend & 0x80000000) >> 31;
    *remainder = (*remainder << 1) | bit;
    t = *remainder - divisor;
    q = !((t & 0x80000000) >> 31);
    dividend = dividend << 1;
    *quotient = (*quotient << 1) | q;
    if (q) {
       *remainder = t;
     }
  }
}  /* unsigned_divide */

#define ABS(x)  ((x) < 0 ? -(x) : (x))

void signed_divide(int dividend,
           int divisor,
           int *quotient,
           int *remainder )
{
  unsigned int dend, dor;
  unsigned int q, r;

  dend = ABS(dividend);
  dor  = ABS(divisor);
  unsigned_divide( dend, dor, &q, &r );

  /* the sign of the remainder is the same as the sign of the dividend
     and the quotient is negated if the signs of the operands are
     opposite */
  *quotient = q;
  if (dividend < 0) {
    *remainder = -r;
    if (divisor > 0)
      *quotient = -q;
  }
  else { /* positive dividend */
    *remainder = r;
    if (divisor < 0)
      *quotient = -q;
  }

} /* signed_divide */

You can take any, verify it and optimize it according to your needs. Generalized functions are usually more complicated than specialized.


Splitting a list of strings into sublists where total of bytes of each sublist is <= N

You can greatly reduce the size of your code by using a total integer and one result list.  You can access the last item in the list by using result[-1].  Additionally, you can reduce the number of times you raise an error by just checking the size of each grouping.

def break_lst(lst, size):
    total = 0
    result = [[]]
    for v in lst:
        total += len(v)
        if total <= size:
            result[-1].append(v)
        else:
            total = len(v)
            if total > size:
                raise Exception("Error: use a bigger size than {}".format(size))
            result.append([v])
    return result


You don't need to wrap your JQuery code in $(document).ready(function() { ... }). See this Stackoverflow question here for more details on that.

The general style for brackets is that the open bracket is on the same line of the declaration, like this below example.

function f() {
    ...
}

Other than that, there's not much else here that I can see that's glaringly wrong, or in need of review. If there's anything else that you want me to cover, just ask, and I'll see what I can do.


Compute a students grade based on weight of assignments

from collections import namedtuple

You should put blank lines after imports, and between function/class definitions.

a = namedtuple('assignment', 'weight scores')

Using a namedtuple for a simple data class like this is a good idea, but it should still be named as a class; Assignment.

def average(scores:list):
    '''average a list of scores'''
    return sum(scores)/2

This function has an obvious bug; what about lists of scores with lengths other than two? Also you type the parameter but not the return value, and should again have some more whitespace; I'd write:

def average(scores: list) -> float:
    """Average a list of scores."""
    return sum(scores) / len(scores)

See PEP-257 for docstring conventions.

def get_grade(grades:list):
    '''compute final grade based on scores and their weights'''
    result = 0
    for a in grades:
        result += average(a.scores) * a.weight
    return result

I think you could simplify this with a bit more OOP. If we subclass the named tuple we can add a read only calculated attribute to it:

class Assignment(namedtuple('Assignment', 'weight scores')):

    @property
    def result(self) -> float:
        return average(self.scores) * self.weight

Then your function becomes:

def get_grade(assignments: list) -> float:
    """Compute final grade based on scores and their weights."""
    return sum(a.result for a in assignments)

Note the revised parameter name, which better describes the input.

def main():
   grades = [a(.30, [18/45, 11/55]),
             a(.20, [3/10, 7.5/10, 10/10]),
             a(.10, [9/10, 9/10, 10/10, 10/10, 8/10,
                6/10, 10/10, 10/10]),
             a(.40, [29/65]),
             a(.01, [1/1])]
   print(get_grade(grades))
main()

To keep things looking consistent without introducing a lot of indentation, I usually split lists with long elements across multiple lines as follows:

assignments = [
    Assignment(.30, [18/45, 11/55]),
    ...
    Assignment(
        .10,
        [9/10, 9/10, 10/10, 10/10, 8/10, 6/10, 10/10, 10/10]
    ),
    ...
]

Note splitting between, rather than within, the two parameters.

Also you should guard the invocation of the entry point as follows:

if __name__ == '__main__':
     main()

This means you can import this functionality more easily for testing and reuse.


Your code is quite difficult to manipulate into doing what you are trying to do.

Some specifics:

Don't use "goto" whenever possible

The following needs to be fixed:

   Dim Search_operation As BINSearch
   'Set Search_operation = BINSearch
   Set Search_operation = New BINSearch

When working with objects, you need to use New when using Set.

This is currently not handling any errors or anything for your input ranges.

Set Cells = Application.InputBox( _
    Prompt:="Enter Range to Search", _
    Type:=8)
Value = Application.InputBox( _
    Prompt:="Enter value that you waant to look for")
Position = Search_operation.Search(Cells, Value)

When you want to use global variables (which, while there are cases to use them, this is not one of them)  you need to dimension them still. Plus, the way you had them before won't compile anyways...

Public Value2 as String
Public Upper As Integer
Public Lower As Integer
Public Middle As Integer

I don't recommend this at all because it is hard to read.

The following does the random search the way you are looking for. I also added a comparison vs .Find to make it easier. I used the animal list here. This is the pastebin.

Public Declare Function GetTickCount Lib "kernel32.dll" () As Long

Private Function getRandomSearchArray(ByRef arr, wsRange As Range, ByVal numbAttempts As Long) As Variant

    ReDim arr(0 To numbAttempts)
    Dim wsArr
    wsArr = wsRange.Value

    Dim i As Long
    Dim rand As Double

    For i = LBound(arr) To UBound(arr)
        rand = Round(rnd() * (UBound(wsArr) - LBound(wsArr)), 0) + 1
        arr(i) = wsArr(rand, 1)
    Next i

End Function

Sub myBinarySearchExample()

    Dim searchRange As Range
    Dim sortedValues As Variant
    Dim searchValues As Variant
    Dim startTickCount As Double
    Dim numbAttempts As Long
    Dim i As Long
    Dim s As String
    Dim arrIndex As Integer

    Set searchRange = Worksheets("BinSearch").Range("A1:A141")
    numbAttempts = 100000

    sortedValues = searchRange.Value
    getRandomSearchArray searchValues, searchRange, numbAttempts

    startTickCount = GetTickCount

    'using Binary Search
    For i = 1 To numbAttempts
        s = searchValues(i)
        'Do this to simulate the "read into memory" each iteration
        sortedValues = searchRange.Value

        arrIndex = BinarySearch(sortedValues, s)
    Next i

    Debug.Print "It took: " & GetTickCount - startTickCount & " ms to run this with the Binary Search."

    'do with .Find
    startTickCount = GetTickCount

    For i = 1 To numbAttempts

        arrIndex = searchRange.Find(What:=searchValues(i), After:=Range("A1"), LookIn:=xlFormulas, _
            LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False).Row

    Next i

    Debug.Print "It took: " & GetTickCount - startTickCount & " ms to run this with the Excel Find."

End Sub

Function BinarySearch(searchArray As Variant, searchValue As String) As Integer

    'dimension these as long to avoid possible integer
    'overflow errors for large lists
    Dim curIndex As Long
    Dim firstIndex As Long
    Dim lastIndex As Long

    Dim nextMiddle As Long
    Dim strValue As String

    'set lower/upper bounds correctly initially for the search
    firstIndex = LBound(searchArray)
    lastIndex = UBound(searchArray)

    Do

        nextMiddle = Round((lastIndex - firstIndex) / 2 + firstIndex)

        strValue = searchArray(nextMiddle, 1)

        'check if it is before/after the current point
        If StrComp(searchValue, strValue, vbTextCompare) = -1 Then
            lastIndex = nextMiddle - 1
        ElseIf StrComp(searchValue, strValue, vbTextCompare) = 1 Then
            firstIndex = nextMiddle + 1
        Else
            BinarySearch = nextMiddle
            Exit Do
        End If

    Loop

End Function

It took: 3182 ms to run this with the Binary Search.
It took: 11763 ms to run this with the Excel Find.


Deallocate all memory in a container of pointers

This assumes that the container holds raw pointer and it owns the pointers. it is a better idea to then let the container hold smart pointers.

These will automatically clear the object they hold when they get destroyed (using delete by default).

typedef std::unique_ptr<Type> Type_ptr;
std::vector<Type_ptr> container;

and use emplace to fill it;

container.emplace_back(std::make_unique<Type>());


The context of this code example is not very clear, so in my remarks below I will suppose that the code is about a generic implementation of depth-first search.

TreeNode

If this is a generic implementation, my first question then is why TreeNode interface is there? This interface is part of Swing API, which has it own sphere of application. The objects implementing this interface may (or may not) be convenient here; anyway, they tend to be used in Swing/GUI-related situations and I'd not interfere with their scope for a generic case.

There is also something even more important concerning TreeNode. As you know, it has children() method which returns an Enumeration. This type is a very old Java thing (since JDK1.0), introduced even before Collections, and currently it looks like a rudiment. And it's not very pleasant to iterate on.

But if you still need/want to keep TreeNode, a type bound mark Enumeration<TreeNode> should be added, in order to avoid compilation warnings.

To replace TreeNode, I'd suggest to create a short and concise Node class, which points to a Collection (or even a Stream) of children Nodes and overrides hashCode and equals methods. This class would also be useful in other examples of your article.

Code Blocks

I understand that conciseness and lack of extra space is the priority in this code, but when I see this

if(top == null || find == null) return false;
else if(top.equals(find)) return true;

it looks for me more like code obfuscation. Please find a place to use braces:

if (top == null || find == null) {
    return false;
}
else if (top.equals(find)) {
     return true;
}

It can be very confusing and error-prone when the instruction that immediately follows a condition is not wrapped in a block.


This is largely a duplicate of https://stackoverflow.com/questions/6935442/x86-spinlock-using-cmpxchg, https://stackoverflow.com/questions/11959374/fastest-inline-assembly-spinlock, etc.

(1) Your code works only on 32-bit x86. If you're using 64-bit (x86-64), the calling convention is totally wrong (you need to save and restore %rbp rather than %ebp, and you're looking for the argument in the wrong place). If you're implementing your own OS, I suppose you know what you're doing... but in general I think it's weird to see 32-bit x86 code these days.

(2) Useless trivia of the day: The two instructions test ecx, ecx; jz .acquired could be replaced with the single instruction jecxz .acquired. I don't know whether this is an optimization or a pessimization on your particular hardware. It would be a size optimization, at least.

(2.5) Really, consider using cmpxchg instead of xchg; test. The cmpxchg mnemonic maps more directly onto the "Compare And Swap" idiom that you're using. It will also help you when it comes time to implement "is the lock held by this thread"; you can set the word to current-thread-id instead of just 1.

(3) See 'About PAUSE' below: Unfortunately there is no "About PAUSE" below. However, it seems like you're doing the right thing there. You could definitely tighten up the code; for example I don't know why you're wasting time with that test dword [eax], 1. You should just retry the xchg as soon as the pause is over.

(4) Consider removing the stack frame; it's not doing anything useful (unless it's necessary for your debugger of choice), just slowing things down.


Compare and Process Common and Uncommon files separately

Per shell checkers feedback, I suggest the following changes:

Fix#1
To prevent globing and word splitting it is recommended to use double quote. Hence, update this while [ $i -lt $total_HU ] to while [ $i -lt "$total_HU" ], and this while [ $j -lt $total_KU ] to while [ $j -lt "$total_KU" ]. I am aware we are dealing with number rather than string but no harm to double quote variables.

Fix#2
Per SC2199 and SC2076 this line of code if [[ ! "${COMMON_files[@]}" =~ "${file}" ]] is problematic, therefore, I changed it to if [[ ! "${COMMON_files[*]}" =~ ${file} ]].

In this context I am sure that I want to match literally so I could also use a trick like this if [[ ! "${COMMON_files[*]}" =~ "${file}"* ]].


Project Euler 21: Sum of Amicable Numbers

Your code looks nice but I have a few suggestions to make it easier to understand according to my personal preferences.

It might be worth defining a function to encapsulate your call to reduce and mul (if you go forward in Project Euler problems, you'll reuse it many times) :

def mult(iterable, start=1):
    """Returns the product of an iterable - like the sum builtin."""
    return functools.reduce(operator.mul, iterable, start)

That you can easily use :

def sum_of_factors(n):
    """
    >>> sum_of_factors(220)
    284
    >>> sum_of_factors(284)
    220
    """
    total = mult((fac**(exp+1)-1)/(fac-1) for fac,exp in factorize(n))
    return total - n

Your function factorize generates tuples of the form (prime factor, power) which is probably worth documenting (either in the doc or in the function name).

I think it'd be easier to generate prime factors without grouping them as this can be delegated to a different function.

You'd have something like :

def factorize(n):
    """Generate prime factors (potentially repeated) in order."""
    for factor in chain((2,), count(start=3,step=2)):
        if factor*factor > n:
            break

        while n % factor == 0:
            n //= factor
            yield factor
    if n > 1:
        yield n

This function does one thing (and does it well) and can be easily tested :

for i in range(1, 1000):
    fact = list(factorize(i))
    assert mult(fact) == i  # see, i've reused mult already :-)
    assert sorted(fact) == fact  # there was a time where I needed that property but it's not really important now

Grouping and counting can be delected to a collection.Counter.

def sum_of_factors(n):
    """
    >>> sum_of_factors(220)
    284
    >>> sum_of_factors(284)
    220
    """
    total = mult((fac**(exp+1)-1)/(fac-1) for fac,exp in collections.Counter(factorize(n)).items())
    return total - n

The function sum_of_factors probably deserves some additional explanation (especially because the name says sum while the code says mult). Maybe a link to some reference would be enough.

You can avoid a few cache lookups. Indeed, at the moment, you consider all pairs (a, b) with a != b and add a whenever you find one. You could limit yourself to pairs (a, b) with a < b and add a+b when you find it. Also, by doing so, you know for sure that the value you are looking for will be in the cache.

sum_facts = {k: sum_of_factors(k) if k else 0 for k in range(10000) }
print(sum(k + v for k, v in sum_facts.items() if v < k and sum_facts[v] == k))


It looks like you'll have to set up three dictionaries that reference the same data. In your case, the dictionaries are based on your TARGET data that should change: updateSheetArray. You need three dictionaries because you want to access the data three different ways. The trick is in choosing a unique value from the data to be used as the key into the data. The first two values are simple, single column values: PlanningGroup and GC.

Since one of your choices is "Both", you have to create a key from the data that combines both of those fields into a single value. This can be done on the worksheet itself in the form of a visible or hidden column (and thus also pulled into a memory array), or you can combine the fields in your VBA code. My preferred method for this is to combine the two (or more) fields into a single string in the code, though each situation is different. You can do a simple concatenate or concatenate with a delimiter, it does't matter.

Before we get to the dictionary part of the answer, I will suggest a few items in the code review part of this answer.

Always use Option Explicit. You might be doing this, but it's good to make sure it's visible in your questions (or answers) so it doesn't come up like this.
Declare your variables as close as possible to the first use of the variable. It saves lots of back and forth searching for declarations, plus your code is now a little grouped into "logic blocks".
Define constants for "magic numbers". These are typically a straight numerical value you've hard-coded into your routines. Any other developer that comes along will have to scratch their head to figure out why you're starting a loop from index 6. You also might need to use the same value in multiple places, so creating a Const once isolates the definition and then you only have to change it once.

The constants I've defined for my example solution are:

Private Const LOOKUP_TYPE_COL As Long = 5
Private Const LOOKUP_GROUP_COL As Long = 3
Private Const LOOKUP_GC_COL As Long = 4
Private Const LOOKUP_CHANGE_COL As Long = 6
Private Const UPDATE_GROUP_COL As Long = 13
Private Const UPDATE_GC_COL As Long = 3
Private Const UPDATE_CHANGE_COL As Long = 49
Private Const START_OF_LOOKUP_DATA As Long = 2
Private Const START_OF_UPDATE_DATA As Long = 6

I've made these constants Private at the global module level, but they easily could be restricted in scope to the single Sub in the code. (The example Sub below is a bit long and I could have separated it into smaller functions, I'll leave that as an exercise for the reader :) ).

One problem I noticed in your code is when you're calculating the last row. Your statement is good but you've missed a worksheet reference when using Rows.Count. Since the Rows is not qualified with a worksheet reference, it is counting the rows on the currently active sheet. My habit is to wrap the statement in a With block, just to make sure I have to correct reference:

Dim lookUpSheet As Worksheet
Dim lastRowLookup As Long
Dim lookUpSheetRange As Range
Dim lookUpSheetArray As Variant
Set lookUpSheet = Worksheets("Manual price changes")
With lookUpSheet
    lastRowLookup = .Cells(.Rows.Count, "F").End(xlUp).Row
    Set lookUpSheetRange = .Range("A1").Resize(lastRowLookup, 6)
    lookUpSheetArray = lookUpSheetRange.value
End With

Dim updateSheet As Worksheet
Dim lastRowUpdate As Long
Dim updateSheetRange As Range
Dim updateSheetArray As Variant
Set updateSheet = Worksheets("Price Build-up")
With updateSheet
    lastRowUpdate = .Cells(.Rows.Count, "B").End(xlUp).Row
    Set updateSheetRange = .Range("A1").Resize(lastRowUpdate, 49)
    updateSheetArray = updateSheetRange.value
End With

You are copying data from the worksheet Range into a memory-based array, and that will give you a much faster execution. The bonus is that you're not interacting with the screen, so Application.ScreenUpdating = False is not necessary. (You'll see another change to support this below)

Now comes the Dictionary build up. We're working with your target data, which is the sheet that needs to be updated. You want to be able to find any row in your data with a single reference. I'm assuming the data on your updateSheet could be hundreds or thousands of lines long. Notice in the loop below that I'm creating three dictionaries, including using a combination key to pick up the option to reference entries for "both".

Also, I figured that there could be more than one row in the data that may match the update criteria. So the dictionary keeps track by building a (string) list of row numbers to use later.

Dim groupKeys As Dictionary
Dim gcKeys As Dictionary
Dim bothKeys As Dictionary
Set groupKeys = New Dictionary
Set gcKeys = New Dictionary
Set bothKeys = New Dictionary

Dim updateGroup As String
Dim updateGC As String
Dim bothKey As String
Dim existingList As String
Dim i As Long
For i = START_OF_UPDATE_DATA To UBound(updateSheetArray, 1)
    updateGroup = updateSheetArray(i, UPDATE_GROUP_COL)
    updateGC = updateSheetArray(i, UPDATE_GC_COL)

    If Not groupKeys.Exists(updateGroup) Then
        groupKeys.Add updateGroup, CStr(i)
    Else
        existingList = groupKeys(updateGroup)
        groupKeys(updateGroup) = existingList & "," & CStr(i)
    End If

    If Not gcKeys.Exists(updateGC) Then
        gcKeys.Add updateGC, CStr(i)
    Else
        existingList = gcKeys(updateGC)
        gcKeys(updateGC) = existingList & "," & CStr(i)
    End If

    bothKey = updateGroup & updateGC
    If Not bothKeys.Exists(bothKey) Then
        bothKeys.Add bothKey, CStr(i)
    Else
        existingList = bothKeys(bothKey)
        bothKeys(bothKey) = existingList & "," & CStr(i)
    End If
Next i

Now that we have the dictionaries complete, we only need a single pass through the lookUpSheet data. We'll get the list of rows from the selected dictionary, then update only those rows in the memory-based array NOT directly on the worksheet. So this inside loop is restricted to ONLY the rows needing updated values. This is where you get your other burst of speed.

Dim valueGroup As String
Dim valueGC As String
Dim valueType As String
Dim valueChange As Double
Dim updateRows As Variant
For i = START_OF_LOOKUP_DATA To UBound(lookUpSheetArray, 1)
    valueType = lookUpSheetArray(i, LOOKUP_TYPE_COL)
    valueGroup = lookUpSheetArray(i, LOOKUP_GROUP_COL)
    valueGC = lookUpSheetArray(i, LOOKUP_GC_COL)
    bothKey = valueGroup & valueGC

    valueChange = lookUpSheetArray(i, LOOKUP_CHANGE_COL)

    updateRows = -1      'reset to a non-array value
    Select Case valueType
        Case "Planning group"
            If groupKeys.Exists(valueGroup) Then
                updateRows = Split(groupKeys(valueGroup), ",")
            End If

        Case "GC"
            If gcKeys.Exists(valueGC) Then
                updateRows = Split(gcKeys(valueGC), ",")
            End If

        Case "Both"
            If bothKeys.Exists(bothKey) Then
                updateRows = Split(bothKeys(bothKey), ",")
            End If

    End Select

    '--- update the values if we found the rows to update
    If IsArray(updateRows) Then
        Dim j As Long
        For j = LBound(updateRows, 1) To UBound(updateRows, 1)
            updateSheetArray(CLng(updateRows(j)), UPDATE_CHANGE_COL) = valueChange
        Next j
    End If
Next i

The final step is to copy the modified memory array back to the worksheet (which is why I created the updateSheetRange variable earlier).

updateSheetRange.value = updateSheetArray

Here is the whole solution in a single module:

Option Explicit

Private Const LOOKUP_TYPE_COL As Long = 5
Private Const LOOKUP_GROUP_COL As Long = 3
Private Const LOOKUP_GC_COL As Long = 4
Private Const LOOKUP_CHANGE_COL As Long = 6
Private Const UPDATE_GROUP_COL As Long = 13
Private Const UPDATE_GC_COL As Long = 3
Private Const UPDATE_CHANGE_COL As Long = 49
Private Const START_OF_LOOKUP_DATA As Long = 2
Private Const START_OF_UPDATE_DATA As Long = 6

Sub UpdateManualUpdates()
    Dim lookUpSheet As Worksheet
    Dim lastRowLookup As Long
    Dim lookUpSheetRange As Range
    Dim lookUpSheetArray As Variant
    Set lookUpSheet = Worksheets("Manual price changes")
    With lookUpSheet
        lastRowLookup = .Cells(.Rows.Count, "F").End(xlUp).Row
        Set lookUpSheetRange = .Range("A1").Resize(lastRowLookup, 6)
        lookUpSheetArray = lookUpSheetRange.value
    End With

    Dim updateSheet As Worksheet
    Dim lastRowUpdate As Long
    Dim updateSheetRange As Range
    Dim updateSheetArray As Variant
    Set updateSheet = Worksheets("Price Build-up")
    With updateSheet
        lastRowUpdate = .Cells(.Rows.Count, "B").End(xlUp).Row
        Set updateSheetRange = .Range("A1").Resize(lastRowUpdate, 49)
        updateSheetArray = updateSheetRange.value
    End With

    '--- build up the dictionaries for the UPDATE array where the keys
    '    are single or multiple fields and the entry is CSV list of
    '    row numbers that match the given key
    Dim groupKeys As Dictionary
    Dim gcKeys As Dictionary
    Dim bothKeys As Dictionary
    Set groupKeys = New Dictionary
    Set gcKeys = New Dictionary
    Set bothKeys = New Dictionary

    Dim updateGroup As String
    Dim updateGC As String
    Dim bothKey As String
    Dim existingList As String
    Dim i As Long
    For i = START_OF_UPDATE_DATA To UBound(updateSheetArray, 1)
        updateGroup = updateSheetArray(i, UPDATE_GROUP_COL)
        updateGC = updateSheetArray(i, UPDATE_GC_COL)

        If Not groupKeys.Exists(updateGroup) Then
            groupKeys.Add updateGroup, CStr(i)
        Else
            existingList = groupKeys(updateGroup)
            groupKeys(updateGroup) = existingList & "," & CStr(i)
        End If

        If Not gcKeys.Exists(updateGC) Then
            gcKeys.Add updateGC, CStr(i)
        Else
            existingList = gcKeys(updateGC)
            gcKeys(updateGC) = existingList & "," & CStr(i)
        End If

        bothKey = updateGroup & updateGC
        If Not bothKeys.Exists(bothKey) Then
            bothKeys.Add bothKey, CStr(i)
        Else
            existingList = bothKeys(bothKey)
            bothKeys(bothKey) = existingList & "," & CStr(i)
        End If
    Next i

    '--- now compare each row of the lookup data to find it in the update
    '    data and make the appropriate change to the memory array
    Dim valueGroup As String
    Dim valueGC As String
    Dim valueType As String
    Dim valueChange As Double
    Dim updateRows As Variant
    For i = START_OF_LOOKUP_DATA To UBound(lookUpSheetArray, 1)
        valueType = lookUpSheetArray(i, LOOKUP_TYPE_COL)
        valueGroup = lookUpSheetArray(i, LOOKUP_GROUP_COL)
        valueGC = lookUpSheetArray(i, LOOKUP_GC_COL)
        bothKey = valueGroup & valueGC

        valueChange = lookUpSheetArray(i, LOOKUP_CHANGE_COL)

        updateRows = -1      'reset to a non-array value
        Select Case valueType
            Case "Planning group"
                If groupKeys.Exists(valueGroup) Then
                    updateRows = Split(groupKeys(valueGroup), ",")
                End If

            Case "GC"
                If gcKeys.Exists(valueGC) Then
                    updateRows = Split(gcKeys(valueGC), ",")
                End If

            Case "Both"
                If bothKeys.Exists(bothKey) Then
                    updateRows = Split(bothKeys(bothKey), ",")
                End If

        End Select

        '--- update the values if we found the rows to update
        If IsArray(updateRows) Then
            Dim j As Long
            For j = LBound(updateRows, 1) To UBound(updateRows, 1)
                updateSheetArray(CLng(updateRows(j)), UPDATE_CHANGE_COL) = valueChange
            Next j
        End If
    Next i

    '--- all of the requested updates are complete, copy the array back to the worksheet
    updateSheetRange.value = updateSheetArray
End Sub


First of all I guess your first step of the detection process is processed server side because you said there is a fallback which is processed by JavaScript.
Therefore I guess you only perform a HTTP User-Agent check so far.
Suggestion BlackBerry
I would recommend to add also a check of the Accept request header to your first step of detection.
In one of my recent projects I ran into trouble cause the HTTP User-Agent detection of BlackBerry failed in some cases. For these casees I had to add an Accept request header check which looks for /vnd.rim/.
I didn't find out much about the background why it happens. I only know some BlackBerry browsers try to emulate IE or Firefox.
Example
Taken from the BlackBerry 8120 device specification document: application/vnd.rim.html
Suggestion J2ME Devices
Clients using this technology might be quite rare but to be sure you could include another RegEx for midp to cover all kind of MIDP devices.
Question
I know they're dead but I think there are still some around. What about Palm and webOS devices?


Changing a div that contains a view link

This is a nice simple approach to an SPA. I assume you are returning partial pages from your actions.

A slight improvement would be to hide all pages before showing. This way you don't have to touch the other functions when adding a new page.

Add a class to the page divs, like class='partial-page'. Then in your show page function:

function createItem(Id) {
   $(".partial-page").hide();
   $("#create").load("RolesAdmin/Create/" + Id);
}

You could also make things more generic and allow for a query string. e.g.

function showPage(url, param){
   $(".partial-page").hide();
   if ($.isPlainObject(param) {
     $("#create").load(url + '?' + $.param(param));
   }
   else {
     $("#create").load(url + '/' + param);
   }
}

function createItem(Id) {
   showPage("RolesAdmin/Create", id)
}

function showSomeOtherPage(id, name) {
   // RolesAdmin/SomeOtherPage?id=123&name=freddy
   showPage("RolesAdmin/SomeOtherPage", {id:id, name:name})
}

Further, you can support the back button by using jquery.history.js


I don't have any performance related suggestions unfortunately. I do have a couple cleanup suggestions though.

The bounds checking function can be cleaned up a bit by making use of "comparison chaining" similar to what you'd use in Pytbon:

(defn within-bounds? [[row col] width height]
  (and (< -1 row width)
       (< -1 col height)))

In the iteration function, you have

{:width width
 :height height
 :grid next-grid
 :ant-pos next-pos
 :ant-dir next-dir
 :stopped? false}

This is less than ideal for a few reasons

You're reassociating entries that already exist in the map. This is unlikely to effect performance, but causes unneeded code bloat. It also creates a potential source of bugs if you add a new entry into the game state. Will you remember to update the map retuned by the function? I'd use assoc here instead.
You're associating false with the :stopped? key. Following the logic of the function though, it must already be falsey there.

I'd just write

(assoc world :grid next-grid
             :ant-pos next-pos
             :ant-dir next-dir}

In init-world, you're using (into []) to convert to vectors. This can be written slightly neater using vec.

:grid (vec (repeat height
                   (vec (repeat width 0))))

I also typically space this code out like I have above (I actually write this exact code fairly often).

This is entirely subjective, but instead of maintaining a :stopped? flag, I prefer to use a :running? one instead (the logic is flipped). I find it tends to lead to easier to read code.


Method that concatenates strings, some of which may be null, with several different separators

The repeated task here is that you want to conditionally insert a separator between two strings if both are non-null.  So, write a helper function that does that:

private static String join(String a, String sep, String b) {
    return (a == null) ? b :
           (b == null) ? a : a + sep + b;
}

Then, the code becomes simple:

private String createString(String modeloVotacao, String tipoProposicao, String ordemNumero, String ordemAno) {
    String description = join(modeloVotacao, " - ",
                             join(tipoProposicao, " ",
                                 join(ordemNumero, "/", ordemAno)));
    return (description == null) ? "" : description;
}

Note that in your final example, where ordemNumero and ordemAno are both null, the output ends with a space.  That does not happen in my solution; I consider that to be an improvement.

Please avoid mixing Portuguese with English identifiers (such as createString()).  Stick with one or the other (preferably English).


Bash Shell Script uses Sed to create and insert multiple lines after a particular line in an existing file

1. Comments on your code

Your example input file is not a well-formed XML document. An XML document must have a single root element, but your example has two. What tool did you use to generate this file? You should ask yourself how it went wrong.

(If you're just writing it "by hand" in some other program using a bunch of print statements, you might ask yourself why you are using XML at all rather than something simple like CSV. You clearly can't be intending to process these file using standard XML tools, since most XML tools will refuse to process ill-formed documents.)
In the find command:

find generatedSchema/myApp/db/ -name *.hbm.xml

the pattern *.hbm.xml would be expanded by the shell (rather than the find command) if there happened to be any files matching the pattern in the directory where this command is being run. So single-quote the pattern to make sure this can't happen:

find generatedSchema/myApp/db/ -name '*.hbm.xml'

You might also consider adding the argument -type f to ensure that the names returned all refer to regular files. (It's not very likely in your case that someone will name a directory foo.hbm.xml, but adding a -type argument to a find command is often good practice.)
In this line you don't need to escape the dots:

javaFile=${myFile/%\.hbm\.xml/.java}

The pattern in ${VAR/pat/rep} here is not a regular expression, so dots are not special. For example:

$ FOO='a.b.c'
$ echo ${FOO/./|}
a|b.c

You use regular expressions to transform your XML into Java source. Now, as I'm sure you're aware, you can't reliably process XML using regular expressions. Perhaps what you've got here works because you control the format of these XML files. But really you should be using an XML-aware tool. See section 2 below.
You use a temporary file to store the output of your sed command, and then load it into a variable using a loop over its lines.

You don't need this loop, because you can load the contents of a file into a variable by writing:

VARIABLE=$(<filename)

And you don't need the temporary file either, because you can load the output of a command into a variable by writing

VARIABLE=$(command)

So just write

str=$(sed -n "...")

You could choose better variable names than myFile (why yours?) and str (what's in the string?).
In your last sed command, you use the expression s/pattern/\0\n$str/ to append $str after every match of pattern. You might consider using p;c instead so that you can simplify the pattern (it doesn't have to match the whole line any more):

sed -i -e "/^private static final long serialVersionUID/{p;c\
$str
}"

You expand variables myFile and javaFile in your script in contexts like this:

sed -i -e "..." $javaFile

This will go wrong if the variable javaFile contains spaces. You should double-quote the variable to ensure that it's treated as a single argument to sed even if it contains spaces. (Perhaps you know in this case that it can't contain spaces, but double-quoting variables containing filenames is still a good habit to get into.)

sed -i -e "..." "$javaFile"

I don't like the way you modify the Java source code in-place. This would be dangerous if this is your original Java source code, because a bug in your script could overwrite the Java source code with nonsense and break your build. (But since I can't see the rest of your build system I can't tell if this concern is justified.)

If the whole Java file is automatically generated, wouldn't it be better to do it in one go rather than piecemeal like this? I have a feeling that there are more improvements to be made to this code generation process.

2. Using a programming language with XML support

If you need to process data from XML documents, then use a programming language together with an XML parsing library.

For example, here's how you might rewrite this same script in Python. First, you'd change the way you generate your .hbm.xml files so that they are well-formed XML documents. Let's suppose that they now look like this:

<properties>
  <property name="address1C" type="string">
    <column name="address1_c" length="50" />
  </property>
  <property name="address2C" type="string">
    <column name="address2_c" length="50" />
  </property>
</properties>

Then you might write the following Python program:

#!/usr/bin/python

import fileinput
import sys
import xml.etree.ElementTree

def main():
    # Check command-line argument.
    hbm_xml_filename = sys.argv[1]
    ext = '.hbm.xml'
    if not hbm_xml_filename.endswith(ext):
        raise RuntimeError("Filename {} doesn't end with {}"
                           .format(hbm_xml_filename, ext))

    # Load property names and maximum lengths from input file.
    tree = xml.etree.ElementTree.parse(hbm_xml_filename)
    properties = []
    for property in tree.findall('property[@type="string"]'):
        column = property.find('column')
        properties.append(dict(name = property.attrib['name'],
                               length = column.attrib['length']))

    # Rewrite Java in-place to add "MAX_name = length;" declarations.
    java_filename = hbm_xml_filename.replace(ext, '.java')
    for line in fileinput.input(files=[java_filename], inplace=True):
        sys.stdout.write(line)
        if line.startswith('private static final long serialVersionUID'):
            sys.stdout.write('\n')
            for p in properties:
                sys.stdout.write(
                    '@SuppressWarnings({{"UnusedDeclaration"}}) '
                    'public static final int MAX_{name} = {length};\n'
                    .format(**p))

if __name__ == '__main__':
    main()

You'll see that I've used the xml.etree.ElementTree module to parse and query the XML, I've used an XPath query to find all properties with the attribute type="string", and I've used the fileinput module to update the Java source code in-place.

Then you can run this Python program from your shell script:

find generatedSchema/myApp/db/ -type f -name '*.hbm.xml' |
while read property_file; do
    add_property_lengths.py "$property_file"
done

3. Addendum

You said you were having some difficulty getting VAR=$(command) to work. You should be able to verify that it works in general by testing it in the shell:

$ NUMBERS=$(yes '' | head | nl -ba)
$ echo $NUMBERS
1 2 3 4 5 6 7 8 9 10

Clearly we have different versions of sed (I'm using the BSD-ish version that comes with Mac OS X, so I had to specify -E for extended regular expressions and change the regular expression syntax a bit) but the following works for me:

VAR=$(sed -E -n '/ *<property name="([^"]+)" type="string">/{
    N
    s/ *<property name="([^"]+)" type="string">\n *<column name="[^"]+" length="([0-9]+)".*/    @SuppressWarnings({"UnusedDeclaration"}) public static final int MAX_\1 = \2;/
    p
}' "$myFile")

so you should be able to figure out how to make something like it work for you (if you must do it this way).


Can phrase be made from whole words in another string?

Well, the challenge is named "Hash Tables: ..." so that might be a clue to use JS objects (which are basically hashes) instead of arrays. The array-searching (indexOf) is rather slow.

So it might work to instead treat the dictionary/vocabulary (the magazine words) as keys/property names.

function check(ransomString, magazineString) {
  const vocabulary = magazineString
    .split(" ")
    .reduce((hash, word) => {
      hash[word] = (hash[word] || 0) + 1;
      return hash;
    }, {});

  return ransomString
    .split(" ")
    .every(word => {
      vocabulary[word] -= 1;
      return vocabulary[word] >= 0;
    });
}

Here, the vocabulary object is built with the magazine words as keys, and a numeric count as its value, in case a word occurs more than once in the magazine. Keys in JS objects are automatically strings and case-sensitive.

To match it against the ransom note, we decrement the count for each of the words in the note, as we match them. If the word isn't in the vocabulary at all vocabulary[word] -= 1 will result in NaN, and NaN >= 0 is false.

Note: I don't actually see in the challenge description that words can only be used once, although it makes a lot of sense for the "story" they're telling (although the kidnapper could have bought multiple magazines). If the once-only constraint isn't there, you can do:

function check(ransomString, magazineString) {
  const vocabulary = magazineString
    .split(" ")
    .reduce((hash, word) => {
      hash[word] = true;
      return hash;
    }, {});

  return ransomString
    .split(" ")
    .every(word => vocabulary[word] === true);
}

Alternatively, if the words in magazine are unique already, but can only be used once, you could also do although the above are probably as fast/faster:

function check(ransomString, magazineString) {
  const vocabulary = magazineString
    .split(" ")
    .reduce((hash, word) => {
      hash[word] = true;
      return hash;
    }, {});

  return ransomString
    .split(" ")
    .every(word => {
      if(vocabulary[word] !== true) {
        return false;
      }
      delete vocabulary[word];
      return true;
    });
}


PHP RESTful API for a student repository

The StudentRepository is all about database, and shouldn't know about $request and $response objects, that is the job of the controller.

What if you were fetching data to put in an excel file, then you can't use the StudentRepository as it was to fetch that data.

<?php

namespace REST;

use Slim\PDO\Database;

interface IStudentRepository
{
    //Functions to be defined
    public function __construct(array $credentials);
    public function getStudentNames(array $args);
    public function getAll(array $args);
    public function addStudent($name, $id);
    public function updateName($id, $new_name);
}

class StudentRepository implements IStudentRepository
{
    //Queries and MYSQL connection
    protected $pdo;

    public function __construct(array $credentials)
    {
        // TODO configuration should be stored outside the class, in a config object or file
//        //Database connection
//        $dsn = 'mysql:host=localhost;dbname=College_DB;charset=utf8';
//        $usr = 'root';
//        $pwd = '';

        $this->pdo = new \Slim\PDO\Database($credentials['dsn'], $credentials['usr'], $credentials['pwd']);
    }

    public function getStudentNames(array $args)
    {
        // TODO recommend you use ORDER BY to get a consistent order from request, to request
        $sql = 'SELECT name FROM Students';

        $array_val = array();

        foreach ($this->pdo->query($sql) as $row) {
            $array_val[]=$row["name"];
        }

        return $array_val;
    }

    public function getAll(array $args)
    {
        // TODO recommend you use ORDER BY to get a consistent order from request, to request
        $sql = 'SELECT * FROM Students';

        $array_val = array();

        foreach ($this->pdo->query($sql) as $row) {
            $array_val[$row["id"]]=$row["name"];
        }

        return $array_val;
    }

    public function addStudent($id, $name)
    {
        $stmt = $this->pdo->prepare('INSERT into Students(id,name) values(:id,:namee)');
        $stmt->bindParam(":id", $id, \Slim\PDO\Database::PARAM_STR);
        $stmt->bindParam(":namee", $name, \Slim\PDO\Database::PARAM_STR);

        $stmt->execute();
    }

    public function updateName($id, $new_name)
    {
        $stmt = $this->pdo->prepare('UPDATE Students set name=:namee where id=:id');
        $stmt->bindParam(":id", $id, \Slim\PDO\Database::PARAM_STR);
        $stmt->bindParam(":namee", $new_name, \Slim\PDO\Database::PARAM_STR);

        $stmt->execute();
    }
}
?>

<?php

namespace REST;

class StudentController
{
    protected $Student_DB;

    public function __construct(IStudentRepository $Student_DB)
    {
        $this->Student_DB=$Student_DB;
    }

    public function getStudents($request, $response, array $args)
    {
        $all = $this->Student_DB->getAll();
        return $response->withJson($all, 200);
    }

    public function getStudentNames($request, $response, array $args)
    {
        $names = $this->Student_DB->getStudentNames();
        return $response->withJson($names, 200);
    }

    public function addStudent($request, $response, array $args)
    {

        // improve tests, as it was possible for $id and $name to be undefined with previous tests
        if (!array_key_exists("id", $args) || !array_key_exists("name", $args)) {
            return $response->withStatus(400);
        }

        $id = $args["id"];
        $name = $args["name"];

        if (!is_numeric($id) || !ctype_alpha($name)) {
            return $response->withStatus(400);
        }

        $this->Student_DB->addStudent($id, $name);
        return $response->withStatus(200);
    }
}


This is not secure at all.

Apart from the GET issue (use POST) and the hashing issue (use bcrypt) already mentioned, and the fact that == is not timing safe (use hash_equals), an attacker can log in without knowing the password like this:

login.php?userpass[]=1

The reason for this is that strcmp("STRING", [ARRAY]) returns NULL, and NULL == 0 is true. You should pretty much never use ==. Always use === for type-safe checks.


Using a dedicated enumeration type ByteOrder is a good idea.
CFByteOrder is (ultimately) a type alias for Int, so you can
assign arbitrary integers to it, not just CFByteOrderBig/LittleEndian.

If you don't pass the type in the unpack function then the compiler
has to infer it from the context and either of these would work:

let d1 = unpack(bytes, byteOrder: .BigEndian) as Double
let d2 : Double = unpack(bytes, byteOrder: .BigEndian)

If you pass the type as an argument then the compiler infers
the return type:

let d3 = unpack(bytes, toType: Double.self, byteOrder: .BigEndian)

I think it is a matter of taste which version you choose, I would
prefer passing the type explicitly.

Encapsulating the functions into a type is also a good idea.
But I would use a struct which is initialized with the byte order,
and make that instance methods and not class methods. The reason
is that you probably will do several calls with the same byte order
and you don't have to pass it to every call:

struct BytePacker {
    let byteOrder : ByteOrder

    init (byteOrder: ByteOrder) {
        self.byteOrder = byteOrder
    }

    func pack<T>(var value: T) -> [Byte] { ... }
    func unpack<T>(valueByteArray: [Byte], toType type: T.Type) -> T { ... }
}

which can be used as

let packer = BytePacker(byteOrder: .BigEndian)
let bytes = packer.pack(12.34)
let d = packer.unpack(bytes, toType: Double.self)

There is a problem with

return UnsafePointer<T>(bytes).memory

in your first version of unpack() because is not guaranteed that the
elements of a Swift Array are stored in contiguous memory.

return bytes.withUnsafeBufferPointer {
    return UnsafePointer<T>($0.baseAddress).memory
}

as in your second version of unpack() is the correct solution
because withUnsafeBufferPointer() calls the block with a pointer to contiguous
storage.

Your code assumes that the host byte order is little-endian,
which is the case for all current OS X and iOS platforms.
On the other hand, Swift is open source now and people already start
to port it to different platforms. I have no idea if Swift will be
ported to a big-endian platform at some time.

I would at least make that assumption explicit by defining

enum ByteOrder {
    case BigEndian
    case LittleEndian

    static var hostByteOrder = ByteOrder.LittleEndian
}

and then replace

return (byteOrder == .LittleEndian) ? valueByteArray : valueByteArray.reverse()

by

return (byteOrder == ByteOrder.hostByteOrder) ? valueByteArray : valueByteArray.reverse()

In addition, I would add an assertion

assert(UInt(littleEndian: 1) == 1)

e.g. to the init method of BytePacker.

Alternatively, you can determine the actual host byte order at
runtime:

enum ByteOrder {
    case BigEndian
    case LittleEndian

    static var hostByteOrder = ByteOrder()

    init() {
        self = (UInt(littleEndian: 1) == 1) ? .LittleEndian : .BigEndian
    }
}

but I don't know if that is worth the hassle. (Note that
the static property hostByteOrder is computed only once in
the lifetime of the app, not each time that it is used.)

Your generic pack/unpack functions can be called with
arguments of any type, and that would give wrong results or crashes for

reference types, where the instance is just a pointer to the object,
"complex types" like Array or String, which are a struct but
use opaque pointers to the actual memory holding the elements.

There is – as far as I know – no protocol which comprises all integer and
floating point types. What you could do is to define a protocol

protocol PackableType { }

and make all types which can safely be packed and unpacked explicitly conform to it:

extension Int : PackableType { }
extension UInt16 : PackableType { }
// More integer types ...

extension Double : PackableType { }
// More floating point types ...

(Unfortunately, there are many integer types and I don't know if the repetition
can be avoided.)

Now you can restrict the type <T> to <T : PackableType>.
Alternatively, take a different approach and make the pack/unpack
methods operate on the type itself by defining a protocol extension:

extension PackableType {

    func pack(byteOrder byteOrder: ByteOrder) -> [Byte] {
        var value = self
        let valueByteArray = withUnsafePointer(&value) {
            Array(UnsafeBufferPointer(start: UnsafePointer<Byte>($0), count: sizeofValue(value)))
        }
        return (byteOrder == ByteOrder.hostByteOrder) ? valueByteArray : valueByteArray.reverse()
    }

    static func unpack(valueByteArray: [Byte], byteOrder: ByteOrder) -> Self {
        let bytes = (byteOrder == ByteOrder.hostByteOrder) ? valueByteArray : valueByteArray.reverse()
        return bytes.withUnsafeBufferPointer {
            return UnsafePointer($0.baseAddress).memory
        }
    }
}

(Note how the compiler infers the type in return UnsafePointer($0.baseAddress).memory
automatically.)

This would now be used as

let bytes = 12.34.pack(byteOrder: .LittleEndian)
let double = Double.unpack(bytes, byteOrder: .LittleEndian)

and solve your question "how to define the return type in unpack" in a
different way.


Different algorithm

Instead of considering all pairs of strings which leads to a O(n^2) behavior (where n is the number of strings), you could operate differently and use a dictionnary to group words based on some kind of signature with would be the same for anagrams and different for non-anagrams.

In your case, you could use the "sorted" version of a word as a signature : only 2 anagrams will be indentical once sorted. Once you've determined how to compute this, you can easily define a dictionnary mapping sorted words to the anagrams they correspond to.

This is a typical situation where the setdefault method is useful.

You can write something like:

t1 = ["lint", "intl", "inlt", "code"] # return ["lint", "inlt", "intl"].
t2 = ["ab", "ba", "cd", "dc", "e"] # return ["ab", "ba", "cd", "dc"].

def anagrams(word_list):
    anagrams = {}
    for w in word_list:
        anagrams.setdefault(''.join(sorted(w)), []).append(w)
    # print(anagrams)
    return sorted(  # sort is to make results always the same
                [w for anagrams in anagrams.values()
                    if len(anagrams) > 1
                        for w in anagrams])

assert anagrams(t1) == ['inlt', 'intl', 'lint']
assert anagrams(t2) == ['ab', 'ba', 'cd', 'dc']


(defun skewed-average1 (list)
  "calculate average by summing and dividing"
  (let ((sum 0) (n 0))
    (dolist (x list)
      (if (>= x 0)
          (progn
            (if (> x 100) (setf x 100))
            (setf sum (+ x sum))
            (setf n (+ 1 n)))))
    (/ sum n)))

IF ... PROGN  is WHEN.

>= 0 is plusp.

(setf sum (+ ... is INCF.

(defun skewed-average1 (list &aux (sum 0) (n 0))
  "calculate average by summing and dividing"
  (dolist (x list (when (plusp n)
                     (/ sum n)))
    (when (plusp x)
      (incf sum (min x 100))
      (incf n))))

Next function:

(setf newlist (cons x newlist)) is (push x newlist).

Don't use APPLY, use REDUCE. APPLY has a list length limit.

Alternative implementations:

(defun skewed-average3 (list)
  (loop for x in list
        when (plusp x)
        sum (min x 100) into sum1
        and count t into count1
        finally (return (when (plusp count1)
                          (/ sum1 count1)))))

(defun skewed-average4 (list)
  (let ((new-list (remove-if #'minusp
                             (substitute-if 100
                                            (lambda (item) (> item 100))
                                            list))))
    (when new-list
      (/ (reduce #'+ new-list)
         (length new-list)))))


Yes, clearly you should write D.R.Y. code by not writing multiple methods that perform the same task.

You only need one image_path() and one destroy() method, it is the data delivery to those methods that needs to change and then of course the methods need to be altered to iterate the data.

If you expect to be handing multiple files the same way, I recommend a class variable (array of filenames) which can be filled as necessary, then iterated by your methods.

This mean doing away with:

public $filename;
public $filename2;

and instead use:

public $filenames = [];

A final note about reducing syntax:

if($this->delete()) {
    $target_path = PUBLIC_PATH.DS.'public'.DS.$this->image_path();
    return unlink($target_path) ? true : false;
} else {
    return false;
}

Can be rewritten as:

if (!$this->delete()) {
    return false;
}
return unlink(PUBLIC_PATH . DS . 'public' . DS . $this->image_path());

or even shorter if you prefer inline conditions:

return !$this->delete() ? false : unlink(PUBLIC_PATH . DS . 'public' . DS . $this->image_path());

That said, there is nothing wrong with if blocks, but your ? true : false is unnecessary, I try to avoid declaring  single-use variables, and I prefer to write failure / false / early returns before positive outcomes.


Signal output on Raspberry Pi that acts as input for FPGA

You should start by organising your code better. Try to avoid global variables and group together code in functions.

In addition, you should learn about list comprehensions. They make initializing your signals way easier.

import RPi.GPIO as GPIO

def twos_comp(i):
    ...

def gpio_setup(inputs, outputs):
    GPIO.setmode(GPIO.BCM)
    for pin in inputs:
        GPIO.setup(pin, GPIO.IN)
    for pin in outputs:
        GPIO.setup(pin, GPIO.OUT)

def main(input_pin, output_pins):
    signals = [1 if i % 2 else -1 for i in range(26)]
    bit_signals = [twos_comp(i) for i in signals]

    for i in bit_signals:
        GPIO.wait_for_edge(input_pin, GPIO.RISING)
        for pin, k in zip(output_pins, str(i)):
            GPIO.output(pin, k) #k will be 0 or 1 which is accepted input

if __name__ == "__main__":
    in, out = [5], range(21, 29)
    gpio_setup(in, out)
    main(in[0], out)
    GPIO.cleanup()

And finally, there are better ways to do twos complement. A nice one is for example here.


I really rather think you have the right idea with the interface and your real class. I do heartily endorse your use of readonly which doesn't get a lot of exposure. However, there are many good mocking frameworks out there that you don't need to write your own fake class to unit test with. For instance, we use Moq where I work and your unit test example would look like this:

Mock<IWebRequest> fakeRequest = new Mock<IWebRequest>();

fakeRequest
    .Setup(request => request.DownloadString(It.IsAny<string>())
    .Returns("fake response string");

TestClass test = new TestClass(fakeRequest.Object);
string fakeResponse = await test.DoStuff();


So essentially, you're just getting the unique configuration IDs. This can easily be done by converting your aConfigurations into an array of IDs and using Set to weed out duplicates. Then you can convert the set instance back into an array using Array.from.

const configIds = aConfigurations.map(config => config._metadata.id);
const configIdsSet = new Set(configIds);
const configIdsUnique = Array.from(configIdsSet);

Alternatively, without ES6, you can just use array.reduce to collect IDs as keys of an object and then use Object.keys to extract the keys into an array.

var configMap = aConfigurations.reduce(function(configs, config){
  configs[config._metadata.id] = true;
  return configs;
}, {});

var configIdsUnique = Object.keys(configMap);


The initial value of a map variable is not used, you can avoid this assignment and inline the variable. o is not used too.

If indexes in a map is consequent then it is better to use a List instead of Map. So the part of the code can be rewritten following way:

List<Map<String, String>> jsonmaps = new ArrayList<>();
for (Object j : jsons) {
    jsonmaps.add(mapper.readValue(j.toString(),
        new TypeReference<Map<String, String>>() {}));
}


From what I can tell a string starting with &H is a hex literal.

There exists a number of conversion functions that can convert an expression to the desired type.

So it should simply be, depending on desired type:

Function ConvertHex(ByVal value As String) As Currency
    Dim result As Currency
    result = CCur(value)

    If result < 0 Then
        'Add two times Int32.MaxValue and another 2 for the overflow
        'Because the hex value is apparently parsed as a signed Int64/Int32
        result = result + &H7FFFFFFF + &H7FFFFFFF + 2
    End If

    ConvertHex = result
End Function

Currency vs Double

Maximum accurately representable positive integer value :

&H0020000000000000 (9,007,199,254,740,992) for Double (IEEE 754 binary64)
&H000346DC5D638865 (922,337,203,685,477) for Currency

So why use Currency over Double when the latter works for a larger range of integers?

Currency is always accurate. If we overflow a Currency value we get an error. If we overflow the maximum representable integer value of a double we get an approximate integer value:

Dim doubleMax As Double
Dim doubleAfter As Double
doubleMax = CDbl("&H0020000000000000")
doubleAfter = doubleMax + 1

MsgBox "Double before: " & Format(doubleMax, "#") & vbNewLine & "after: " & Format(doubleAfter, "#")

Dim currencyMax As Currency
Dim currencyAfter As Currency
currencyMax = CCur("&H000346DC5D638865")
currencyAfter = currencyMax + 1

MsgBox "Currency before: " & Format(currencyMax, "#") & vbNewLine & "after: " & Format(currencyAfter, "#")

The output of this example is:

Double before: 9007199254740990
after: 9007199254740990

And then a run-time error '6': Overflow which is great if you want to avoid rounding errors. Now MSDN claims Double is

  stored as IEEE 64-bit (8-byte) floating-point number

but if you've read anything about the IEEE 754 binary64 you should be a bit surprised about the output from the example. The actual maximum is &H00038D7EA4C68000 (1,000,000,000,000,000).


Dropdown form that shows data from 2 different tables

I don't see how you could do this in a single queries, because both queries have nothing to do with each other.

Your code does contain a bit of duplication, but otherwise it looks good to me.

You can simplify your code by introducing a function:

<?php
    createTableSelectForm($conn, $table, $columnValue, $columnShow, $title) {
        $sql = ("SELECT * FROM " . $table);
        $results = $conn->query($sql);
        $form = '
                <select name="makeID">
                    <option value="">Choose ' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</option>';
        while($result = $results->fetch_assoc()) {
            $form .= '<option value="' . htmlspecialchars($result[$columnValue], ENT_QUOTES, 'UTF-8') . '">';
            $form .=  htmlspecialchars($result[$columnShow], ENT_QUOTES, 'UTF-8');
            $form .= '</option>';
        }
        $form .= '</select>';
        return $form;
    }

    require_once 'includes/connection.php';
?>

        <title>Car Makes</title>

Car Makes

            <form action="" method="get">
            <?php echo createTableSelectForm($conn, "tblmake", "makeID", "carmake", "Make");
            echo createTableSelectForm($conn, "tblclass", "classID", "carclass", "Class"); ?>
            <input type="submit" value="Insert">
        </form>

You really only need the first two arguments for the createTableSelectForm, but I added the other ones so that the method is more reusable.

I also added XSS protection, because with variable data, you can never be sure where it comes from (maybe, in the future you will allow visitors to add makes? Or now that the function is reusable, it will be reused somewhere else with user input? Who knows, and better safe than sorry; it also doesn't add that much overhead).

Misc

your naming is a bit confusing. The same thing should always have the same name, because it increases readability . But you have $sql and $getclass for basically the same thing. The same goes for $result vs $results (both hold multiple results). $sqlSelectMake/$sqlSelectClass and $resultMakes/$resultClasses would be better.


Finding collisions of the first few bits of a SHA-1 hash

I realized that while typing this, you should look into the Birthday Attack, which will probably much more elaborated than my answer, lol.

Considering your have 36 bits of data, it means you have a total number of possibilities of \$2^{36} = 68719476736\$. Based on the Pigeonhole principle, if you compared the hashed of 68719476736 different strings, you'd get a collision.

So that's easy! All you need to do is run this (pseudocode):

hashset = (new hashset that uses your hashing algorithm)
for(i = 0; i < 68719476736 + 1; i++) {

    if hashset.contains(string(i)) break;

    hashset.add(string(i));
}

print("This took " + i + " tried!")

With this, you're guaranteed to get a collision. But there's a problem. If every iteration took 100 milliseconds, you'd need about 217 years to get a solution. Tell your teacher your great-great-grandchildren will get back to you with a solution. You could also buy 2000 computers to run this in ~40 days.

My algorithm is pretty much guaranteed to finish (assuming none of the computers crash in any way), yours isn't. This is more of a lesson on "how to test things", which is valuable for developers. When you want to test something, try not to be random. The thing with your algorithm is that maybe you wouldn't ever get collisions. I understand that you kind of need randomness if you want this to finish running this one day.

So the question is, what could we do to make this better?

We could check about how many different strings we'd need to get a good enough chance there's a collision. It's kind of the Birthday Problem which gives us an easy way to calculate what are the chances n different persons have the same birthday in a group of m persons.

We can use the formula under Approximation of number of people and adapt it to our problem to understand that if we had 68719476736 + 1 strings in our possession (for example, every number between 1 and 68719476736 + 1), you'd need to pick 308652 of those to have about 50% chances of having a collision.

What you could try is randomly take 308652 numbers between 1 and 68719476736 + 1 and hash them to find a collision. Repeat this as long as you don't have a collision.

The pseudocode would look like this :

generator = RandomBigIntGenerator()
numbers = []

for(i = 0; i < 308652; i++) {
    numbers.add(generator.random(1,68719476736+1))
}

hashset = {} (With your hashing function)
for n in numbers {
    if hashset.contains(n) {
        print("yay done");
        break;
    }
    hashset.add(m);
}

All in all, you can hope to have collisions, but you need computing power.

In a code review point of view :

You need to keep track of the strings you already tried, they give you valuable information that can actually help you find collision.
Don't be too random when you create your strings.
Understand that 68719476736 is a biiggg number, but still so much smaller than the 1461501637330902918203684832716283019655932542976 possible values the SHA1 have :)


TodoItem component type checking for optional prop

Make the shapes the same In my experience, TypeScript is easiest when similar data has the same shape (type). Rather than conditionally passing a markCompletedTodo, consider passing that prop unconditionally, and in the child component, check todo.isCompleted when you need to identify whether to add the button or not.
Duplicate key bug You use:
{incompleteTodos.map((todo) => (
  <TodoItem
  key={todo.text}

What if the todo text is the same? Maybe someone adds "Get groceries" Tuesday, then comes back to the app on Thursday and adds "Get groceries" again for the next week. This means that you'll have duplicate mapped keys, which should not be done and will confuse React, possibly creating rendering problems.
Since it looks like todos have IDs, use those IDs as keys instead.
&& instead of conditional To conditionally render in React, you can use && or || to test, and put the element to be rendered on the right-hand side - it's a bit more concise than the conditional operator.
You could do something like:
// You could rename the definition of removeTodoRequest to removeTodo
// and markCompletedTodoRequest to markCompletedTodo
// so that you can use shorthand property names below:
const makeTodoItem = (todo: Todo) => (
  <TodoItem
    key={todo.id}
    {...{ todo, removeTodo, markCompletedTodo }}
  />
);
return (

Incomplete TODOS

  {incompleteTodos.map(makeTodoItem)}

Complete TODOS

  {completeTodos.map(makeTodoItem)}
); // don't forget this semicolon

type TodoProps = {
  todo: Todo;
  removeTodo: (id: string) => void;
  markCompletedTodo: (id: string) => void;
};

const TodoItem = ({ todo, removeTodo, markCompletedTodo }: TodoProps) => {
  return (

{todo.text}

      <button type="button" onClick={() => removeTodo(todo.id)}>
        Remove
      </button>
      {!todo.isCompleted && (
        <button type="button" onClick={() => markCompletedTodo(todo.id)}>
          Mark completed
        </button>
      )}

  );
};


Create a style for the classes hidden_year and visible_year. When you click a link use a selector that selects all with id containing "year_19" and set them all to hidden_year, then just set the link you clicked to visible_year.

You could use a loop to build up the id values 5-9 if you really wanted to. . . var curr_year = 'year_19' + i + '0' in a loop.

Here is an example:

<!doctype html>

<meta charset="utf-8">
<title>Year test</title>

1950

1960

1970

1980

1990


So given this is a blanket rule across all the functions i.e. val === undefined then throw you could introduce a common validator function you could share across all your functions e.g.

function assertParams(params) {
   for (const prop in params) {
       if (params[prop] === undefined) {
           throw new Error(`Argument ${prop} is undefined`);
       }
   }
}
...
export const function requestAddNew(firebase, uid, accountId) {
    assertParams({ firebase, uid, accountId });
    ...
}
export const function requestDeleteAccount(firebase, uid, accountId) {
    assertParams({ firebase, uid, accountId });
    ...
}

you'd need to call it in every function, however, this would give you the same effect of what you already have in one line as opposed to X lines based on the number of parameters you have.

If your using Babel, something to look at would be perhaps moving it to a decorator so it's completely outside the scope of your logic e.g.

@assertParams()
export const function requestAddNew(...)

The above code wouldn't just "work" in the decorator, would need a little bit of tweaking but I'm pretty sure it's doable.


This review will consist of 2 parts:

  The design/concept
  The code itself

1: Code should solve problems

Every piece of code you write and will ever write should solve a problem. If it is not a solution to a problem you have. Throw it away. Eventually it will break, and then kittens will die!

To make sure we don't kill to many kittens, we have to write good, solid and simple code. Code that everyone understands, even 'me'-in-5-days-with-a-hangover. Some very smart geeks have even made a couple of rules: SOLID, KISS ...

Let's look at your class. It's name is Database. That tells me that your class represents a Database. In orde to function, it will probably need a DatabaseConnection, and maybe even a LoggerInterface (psr-3). But thats just a guess. It will probably help me in creating transactions, flushing the data, error-retrieval, ...

I am so wrong

The Database object needs 1 parameter. It's called $config, sadly, the documentation is simply missing. So I start analysing the code. Apparantly it needs $driver, $host, $database, $username, $password. So why not ask for it? Really. What is more user friendly:

$dbConnection = new Database(array('config'=>array('username'=>'',...)));

or

$dbConnection = new Database('username','password',...);

If you need something, ask for it.

So what problem are you trying to solve?

One problem could be the creation of DatabaseConnections. This could be solved using a DatabaseConnection Factory. Using the factory pattern that is.

Or maybe, you are trying to create some kind of DBAL? A class that uses a DatabaseConnection and performs queries.

Or maybe you wanted to create an error-logger/catcher (looking at all those try/catch)?

Different problems need differen solutions

Every class should solve 1 problem. At max.

2: Code should be stupid

If code doesnt read like normal language or poetry, it is bad code. If code does read like normal language, read again to check if it makes sence. an example:

class Cabin
{
    public function open() {
        //the cabin is now open
    }
}

Looks perfectly normal.

$myCabin = new Cabin();
$myCabin->open();
//we can now put stuff in the cabin

Read well, everyone knows whats going on. Now read it again. The actor is the acinb, the action is open.You open something, so what is the cabin opening?
Somehow, we wrote code where the Cabin is opening itself, magically. Better would be:

$cabinHandler->openCabin($cabin);
if ( $myCabin->isOpen() ) {
    //we can no put stuff in the cabin
}

A more real-world example:

$user->resetPassword();
$user->setResetPasswordMail();

Looks normal, right? But why does the User know how to send emails? Better:

$email = new Email($resetPasswordEmailContent)
$mailer->sendEmail($email, $user);

Now back to your Database class. Let's just say you went for the DBAL solution. We start with the __construct. What is the exact minimum requirement? a connection. We use pdo:

//name is not perfect
class Database
{
    public function __construct(PDO $dbh)
    {
        $this->dbh = $pdo;
    }
}

We also want to abstract away the preparing, and statement handling etc etc

/**
 * Query the database connection and return the result
 * @param  {String} $sql            [description]
 * @param  {Array} $values=array() [description]
 * @return {Array}                 [description]
 */
public function query($sql, $values=array())
{
    try {
        $sth = $this->dbh->prepare($sql);
        $sth->execute($values);
    } catch (PDOException $e) {
        $this->logger->critical($e->getMessage, array($sql, $values));
        throw new DatabaseException('An error occured performing a query');
    }

    return $sth->fetchAll();
}

So instead of failing miserably on an exception. We log our PDO exception (We use PDO so we can know about it). And then throw e new more generic error message. The code that then called us can choose 2 things on an error: 1) ignore or 2) catch it and try and fix the problem.

Eventually, if there is no caller up the chain that actually knows what to do with this Excpetion. The DatabaseException will be caught by your error_handler. This one will simply show a nice error page with some generic error message. For instance the google-monkeys.

Now that we have established how we should code. Let's look at how the SOLID rules could help us.

S : Single responsibility principle

Every piece of code should have one single responsibility. This goes for Objects and for methods. The class DatabaseHandler should only handle the Database - or act as an abstraction. Every method should only do one thing: perform a query, open a transaction, close a transaction. It shouldn't perform a query AND handle the exceptions AND render the error-view (include html stuff).

O : open/closed principle

Every module - read piece of code - should be open for extension but closed for modification. This means that we should be able to change the behaviour without changing the source code itself. Your Database constructs the dsn for the PDO object. But what if you want to use sqlite instead of mySQL? Your Database class does  not handle this case. So for changing the behaviour, we need to change your SourceCode.

  :(

That is my sad face

L : Liskov substitution principle

Not applicable here since you are not extending classes. But it is a nice principle to look into when you start building very large aplications.

I : Interface segregation principle

Only ask what you need. And not only for variables, but for methods aswell. In your construct you are asking for a $config array. By just looking at it I know there is more then just the $config['database'] in there. Why? The database should care less about other config stuff. It shouldn't get them. It shouldn't even know that you are passing config around in an array. The same applies when using other objects.

Your problem with the SQLite db can forinstance be solved with Typehinting for an interface instead of a class (PDO in your case). You are only using the prepare($query) method. So why ask for an entire PDO object? What if we want to change PDO with something different - you never know, PDO could be the biggest kitten killer out there. So create an interface and ask that:

interface DatabaseConnection
{
    /**
     * @param  {String} $query The query with placeholders
     * @return {StatementHandler}
     */
    public function prepare($query);
}

and then typehint for this DatabaseConnection:

class Database
{
    public function __construct(DatabaseConnection $db) {
        $this->db = $db;
    }
}

Now everyone who is going to use your code knows what a DatabaseConnection should look like. A very easy example is the following one:

class PdoDatabaseConnection extends PDO implements DatabaseConnection {}

And now everyone is happy. Even the guy who is writing the dreadfull MysqlDatabaseConnection with all it's mysql_query glory

D : Dependency inversion principle

Your connect() function is a good example of how NOT to do it. What happens when you construct your database object is the following:

1) get some parameters from an array into a local variable (why? i dont know)
2) pass those variables to the connect function
3) try to connect to the database with the config/credentials provided
4) if you fail, handle the error and show an error screen.

That's a lot. To much. Your abstract 'Database' class that should have abstracted the hard PDO object, know completly depends on that PDO object. It even knows how to create it. While all the class needs it some object where he can call ->prepare() and then get a Statement back that he can ->execute() and ->fetchAll().

Everytime you find yourself writing new inside a class. And the class doesn't end witht he word Factory. Stop what you are doing and ask for an interface instead.

There are ofcourse exceptions. For instance PDO. The DatabaseConnection interface will be overkill in most real world examples.

Know we have established the SOLID rules, there still remains DRY: Don't Repeat Yourself. Your Database class has 5 methods, 70 lines of code. The 3 biggest methods have 23 lines of combined unique lnes, and the same amount of duplicated code (try catch stuff). That is WET code. And we all know what happens when you leave things wet for to long, fungus, smell, dead kittens.

  Note: Everything I wrote here is meant to help you in your journey in the land of code. If you feel offended, I apollogise. That was not what I meant to do. If you don't aggree, good for you. At the end of the day this is just another review. Happy coding!