Printing 64-bit decimal numbers in freestanding environment I need to print signed 64-bit numbers in decimal form. Program runs in freestanding environment (no C library available, libgcc may be unavailable too, or may not work correctly). So I can't use printf(3) function.

I'am trying to write function, which will be able to convert number from binary form (int64_t) to ascii. Simple solution is to divide number by 10, and use remainder as next digit (from left to right, iteratively).

Unfortunately, processor doesn't have 64 bit division, and I can't rely on libgcc in that (__udivdi3 function). So I invented other way to perform binary->decimal conversion, by using binary coded decimal (BCD) numbers. First I convert binary number to BCD form (bit by bit, need 64 iterations, and need to sum BCD numbers), then convert BCD to ASCII.

Source code is following:

/*static*/ void _print_dec(intmax_t num)
{
    char *p;
    char buf[24 /* > log10(2^64) */];
    uint_fast8_t r;
    uint64_t n = num < 0 ? -num : +num;

    uint_fast16_t result_h = 0, digit_h = 0;
    uint64_t result = 0, digit = 1;
    while (n != 0)
    {
        /* sum bcd numbers: r = a + b, where r should be L-value  */
        #define BCD_ADD(type, r, a, b) do { \
            type t1 = a + (type)(0x6666666666666666 & ((type)-1 >> 4)), t2 = t1 ^ b; \
            t1 += b, t2 = ~(t1 ^ t2) & (type)0x1111111111111110; r = t1 - (t2>>2 | t2>>3); \
        } while (0);

        /* this macro computes rh:rl = ah:al + bh:bl (sum of compound BCD number), rh:rl should be L-value */
        #define BCD_ADD_COMPOUND(type_h, type, rh, rl, ah, al, bh, bl) do { \
            uint_fast8_t c = 0; \
            type t1 = al, t2 = bl; \
            BCD_ADD(type, rl, al, bl); \
            c = rl >> (sizeof(type)*CHAR_BIT-4); \
            BCD_ADD(type_h, rh, ah, bh); \
            if (c >= 10 || (rl < t1 && rl < t2)) { \
                rl = (rl & ((type)-1 >> 4)) | ((c - 10ULL) << (sizeof(type)*CHAR_BIT-4)); \
                BCD_ADD(type_h, rh, rh, 1); \
            } \
        } while (0)

        if (n & 1)
            BCD_ADD_COMPOUND(uint_fast16_t, uint64_t, result_h, result, result_h, result, digit_h, digit);

        BCD_ADD_COMPOUND(uint_fast16_t, uint64_t, digit_h, digit, digit_h, digit, digit_h, digit);
        n >>= 1;
    }

    p = &buf[sizeof(buf) - 1];
    *p = 0;
    do {
        r = result & 0x0f;
        *--p = r + '0';
        result = (result >> 4) | ((uint64_t)(result_h & 0x0f) << (sizeof(uint64_t)*CHAR_BIT-4));
        result_h = result_h >> 4;

    } while (result_h != 0 || result != 0);

    if (num < 0) *--p = '-';
    print_cstr(p);
}
#define print_dec(num) DECL_FUNC(_print_dec, num)

I hope, that somebody suggests me some improvements...

How can I print 64-bit decimal numbers in freestanding environment?
  suggests me some improvements...

Create test cases

Post lacks a good way to assess its correctness.  Since the goal is to print rather than form a string, that is later printed, (a better function IMO), we will do things the simply, but a bit the hard way and visually compare output.

Test case code

#include <inttypes.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>

void print_uint64_dec(uint64_t u) {
  if (u >= 10) {
    uint64_t udiv10 = u/10;
    u %= 10;
    print_uint64_dec(udiv10);
  }
  putchar((int)u + '0');
}

void print_int64_dec(int64_t i) {
  uint64_t u = (uint64_t) i;
  if (i < 0) {
    putchar('-');
    u = -u;
  }
  print_uint64_dec(u);
}

int main(void) {
  int64_t ia[] = {INT64_MIN + 1, 0, 10, INT64_MAX/2, INT64_MAX - 1};
  for (size_t index = 0; index< sizeof ia/sizeof ia[0]; index++) {
    int64_t i = ia[index];
    print_int64_dec(i-1); putchar('\n');
    print_int64_dec(i+0); putchar('\n');
    print_int64_dec(i+1); putchar('\n');
  }
}

And its output:

-9223372036854775808
-9223372036854775807
-9223372036854775806
-1
0
1
9
10
11
4611686018427387902
4611686018427387903
4611686018427387904
9223372036854775805
9223372036854775806
9223372036854775807

OP code produced the same results.

Plan for the future

"processor doesn't have 64 bit division, and I can't rely on libgcc" --> accepting this as a given, this curious restriction could easily be removed later.  To that end, recommend to encapsulate this specialized code - and only the specialized part needed - the divide and mod of a int64_t, without the print part.

Something like

static unsigned mod10(uint64_t *u) {
  uint64_t dividend = *u;
  uint64_t quo = 0;
  uint64_t div = 0xA000000000000000; //largest shifted 10
  while (div >= 10) {
    quo <<= 1; // quo *= 2;
    if (dividend >= div) {
      dividend -= div;
      quo++;
    }
    div >>= 1;
  }
  *u = quo;
  return (unsigned) dividend;
}

void print_uint64_dec(uint64_t u) {
  if (u >= 10) {
    #if CURIOUS_CODE_NEEDED
      uint64_t udiv10 = u;
      u = mod10(&udiv10);
    #else
      uint64_t udiv10 = u/10;
      u %= 10;
    #endif
    print_uint64_dec(udiv10);
  }
  putchar((int)u + '0');
}

Simplify

I just had too much trouble following the "invented other way".  I recommend to  re-write to only replace the missing /10, mod 10 functionality in  a stand-alone function.  When a target platform lacks standard functionality, do not entangle your fill-in-the-gap code with the rest of user code.  Keep them separate.

Minor - Use consistent types

Code   converts intmax_t to uint64_t as if  intmax_t is always a 64-bit type.  (u)intmax_t is at least a 64-bit type.  Choose (u)intmax_t or (u)int64_t.

Minor - Avoid UB

intmax_t num ... -num is UB when num == INTMAX_MIN.  Simply enough to fix. Negate an unsigned type

// uint64_t n = num < 0 ? -num : +num;
uint64_t n = num;
if (num < 0) n = -n;
// OR
uint64_t n = num < 0 ? -(uintmax_t)num : num;
// Or various other approaches.

Minor - Missing  headers

I needed the below to compile your code.

#include <limits.h>
#include <stdint.h>


JavaScript program to find if array is in Arithmetic or Geometric sequence Given an array of numbers I've to write a function to return the string "Arithmetic" if the sequence follows an arithmetic pattern or return "Geometric" if it follows a geometric pattern. If the sequence doesn't follow either pattern return "neither arithmetic and geometric".

I'm a beginner and I thought of following solution first. How do I improve on it and write better code next time?

var arr =[2,4,6,8,10];// [2,6,18,54]- Geometric
var arthCount=0;
var geoCount=0;
    function ArthGeo(){
        for (var i=0;i<arr.length-2;i++){
             if(arr[i+1]-arr[i]===arr[i+2]-arr[i+1]){
                 arthCount++;
            }
            else if(arr[i+1]/arr[i] ===arr[i+2]/arr[i+1]){
                 geoCount++;
            }
            else return "neither arithmetic nor geometric";
        }
         if(arthCount===arr.length-2)
             return "Arthematic series";
         else if(geocount===arr.length-2)
             return "Geometric series";
     }
 console.log(ArthGeo());

This is great example to practice identifying the right abstraction.

In testing to see if an array is geometric or arithmetic series, what you are really doing is testing if a particular mathemtical relation holds for each element.  That is, the heart of your program is in these 2 lines:

if(arr[i+1]-arr[i]===arr[i+2]-arr[i+1]){
//...
else if(arr[i+1]/arr[i] ===arr[i+2]/arr[i+1]){

Let's go ahead and extract just these relations into their own functions:

// This tells if an arithmetic relation holds at a particular index of the array
// The function signature here is chosen to work with javascript's every method
// The reason will become clear below.
function isArithmeticAtIndex(elm, i, arr) {
  if (i < 2) return true; // trivially true when it can't be false
  return arr[i] - arr[i-1] === arr[i-1] - arr[i-2];
}

function isGeometricAtIndex(elm, i, arr) {
  if (i < 2) return true;
  if (arr[i-1] == 0 || arr[i-2] == 0) return false; // can't divide by 0
  return arr[i] / arr[i-1] === arr[i-1] / arr[i-2];
}

Now we'll create a generic function that tells us if a particular mathematical relation holds at every elment of an array:

function hasSeriesRelation(arr, relationFn) {
  // geometric and arithmetic series (and most others)
  // don't make sense with less than 3 elements
  if (arr.length < 3) return false;
  return arr.every(relationFn);
}

At this point, we are basically done.  We can use what we've written as follows:

a = [1,2,3,4];
hasSeriesRelation(a, isArithmeticAtIndex);
// => true
a = [1,2,3,5];
hasSeriesRelation(a, isArithmeticAtIndex);
// => false
a = [1,2,4,8];
hasSeriesRelation(a, isGeometricAtIndex);
// => true
a = [1,2,4,9];
hasSeriesRelation(a, isGeometricAtIndex);
// => false

But writing hasSeriesRelation(a, isGeometricAtIndex) is cumbersome, so let's wrap these up in their own functions, and make them array methods:

Array.prototype.isArithmeticSeries = function() { return hasSeriesRelation(this, isArithmeticAtIndex) };
Array.prototype.isGeometricSeries = function() { return hasSeriesRelation(this, isGeometricAtIndex) };

And now we can write things like:

[1,2,4,8].isGeometricSeries();
[1,2,3,4].isArithmeticSeries();

Side Note: Some consider extending Array.prototype bad practice.  I think it can be okay depending on your circumstances.  See this post for more discussion.  In any case, it's only marginally relevant to this discussion, because you can easily rewrite the above to functions with signatures like function isArithmeticSeries(arr)

Finally, note that we have gained the ability to quickly and easily add new types of series.  For example, we might want to identify Fibonacci-like series:

function isFibonacciAtIndex(elm, i, arr) {
  if (i < 2) return true; // trivially true when it can't be false
  return arr[i] === arr[i-1] + arr[i-2];
}

a = [1,1,2,3,5,8];
hasSeriesRelation(a, isFibonacciAtIndex);
// => true


SEDE Query to Find... Weird Question/Protect Combinations I was interested in finding some of the weirdest question/protection combinations, basically out of curiosity.

I heuristically defined this as:

Low view counts
Not a moderator/SE employee
From users who protect multiple questions

I'm... let's just say not an expert in SQL. Though this query works, it feels super inefficient (especially the 2x left join, it seems plausible that could be a single join).

Looking basically for any feedback. I used this site to format things, so hopefully it's more readable than the mess it was before I started formatting it.

You can play with it here if your curiosity is also too strong to resist ;)

DECLARE @postViews int
SET @postViews = ##postView##
SELECT [Post Link] = ph.PostId,
       [User Link] = ph.UserId,
       Protected.ProtectCount,
       Unprotected.UnprotectedCount
FROM PostHistory ph
JOIN Posts p ON ph.PostID=p.id
LEFT JOIN
  (SELECT count(UserID) AS ProtectCount,
          PostID
   FROM PostHistory ph
   WHERE ph.PostHistoryTypeID=19
   GROUP BY PostID) AS Protected ON Protected.PostID=ph.PostID
LEFT JOIN
  (SELECT count(ph.UserID) AS UnprotectedCount,
          PostID
   FROM PostHistory ph
   WHERE ph.PostHistoryTypeID=20
   GROUP BY PostID) AS Unprotected ON Unprotected.PostID=ph.PostID
WHERE ph.UserID IN
    (SELECT top ##NumbUsers## ph.UserId
     FROM PostHistory ph
     JOIN Posts p ON ph.PostID=p.id
     WHERE ph.PostHistoryTypeId = 19
       AND p.ViewCount < @postViews
       /* exclude former moderators */
       AND ph.UserID NOT IN (419,
                             1228,
                             1288,
                             19679,
                             23354,
                             50049,
                             59303,
                             102937,
                             106224,
                             246246,
                             -1)
     GROUP BY ph.UserId
     ORDER BY COUNT (ph.UserId) DESC)
  AND ph.PostHistoryTypeId = 19
  AND p.ClosedDate IS NULL
  AND p.ViewCount < @postViews
  AND isnull(Protected.ProtectCount,0) != isnull(Unprotected.UnprotectedCount,0)
ORDER BY ph.UserId

One of the first things you should do if you have an arbitrary data set (as you do in your list of UserIds) would be to extract it out of the WHERE clause. Just make a @TempTable variable. If the data set gets very large, consider a "physical" #TempTable.
DECLARE @UsersToExclude TABLE (UserId INT PRIMARY KEY);
INSERT INTO @UsersToExclude (UserId)
VALUES
  /*Some comments to explain these numbers would be good:*/
  (419),
  (1228),
  (1288),
  (19679),
  (23354),
  (50049),
  (59303),
  (102937),
  (106224),
  (246246),
  (-1);

Then you can just do an existence check in your query:
   AND ph.UserID NOT IN (
     SELECT usrExcl.UserID from @UsersToExclude as usrExcl
   )

Please get into the habit of using the (optional) keyword AS to reference to table aliases. If not used it can be ambiguous whether it's supposed to be an alias or a query hint for something else, like NOLOCK.
FROM PostHistory AS ph
  JOIN Posts AS p ON ph.PostID = p.id

This bracketing style is a bit unusual:

LEFT JOIN
  ( SELECT foo
   FROM bar
   WHERE ...) AS Unprotected ON Unprotected.PostID=ph.PostID

It looks like LISP-style brackets. Most often in SQL either C# or Java style brackets are used (depending on the programming shop).
C#-style
LEFT JOIN
(
    SELECT foo
    FROM bar
    WHERE ...
)
AS Unprotected ON Unprotected.PostID=ph.PostID

Java-style
LEFT JOIN (
    SELECT foo
    FROM bar
    WHERE ...
) AS Unprotected ON Unprotected.PostID=ph.PostID

What does this number mean?

WHERE ph.PostHistoryTypeID=19

No easy way to tell. Consider something like:
DECLARE @QuestionProtected INT = (SELECT Id FROM PostHistoryTypes WHERE Name = 'Question Protected');

Then it's easier to follow:
WHERE ph.PostHistoryTypeID = @QuestionProtected

SEDE magic
You can get this valueat the top, or assign a default value for newbies like me:
-- postViews: Number of post views
DECLARE @postViews INT = ##postViews:int?10000##;

The other one is a script variable so it can't be manipulated as easily, but can still be assigned a default value (and documented):
WHERE
  ph.UserID IN (
    -- NumbUsers: Max number of users
    SELECT TOP ##NumbUsers:int?5000##

One more thing,
  AND isnull(Protected.ProtectCount,0) != isnull(Unprotected.UnprotectedCount,0)

The != operator is not SQL standard. Instead, use <>. Also, consider using COALESCE() instead of ISNULL() for some of the reasons listed here. Performance is right about the same, but it handles types better, usually (and can take more than 2 arguments, if needed).

Everything combined (demo on SEDE)
-- postViews: Number of post views
DECLARE @postViews INT = ##postViews:int?10000##;

DECLARE @UsersToExclude TABLE (UserId INT PRIMARY KEY);
DECLARE @QuestionProtected INT = (SELECT Id FROM PostHistoryTypes WHERE Name = 'Question Protected');
INSERT INTO
  @UsersToExclude (UserId)
VALUES
  /*Some comments to explain these numbers would be good:*/
  (419),
  (1228),
  (1288),
  (19679),
  (23354),
  (50049),
  (59303),
  (102937),
  (106224),
  (246246),
  (-1);
SELECT
  [Post Link] = ph.PostId,
  [User Link] = ph.UserId,
  Protected.ProtectCount,
  Unprotected.UnprotectedCount,
  p.ViewCount
FROM
  PostHistory AS ph
  INNER JOIN
    Posts AS p ON ph.PostID = p.id
  LEFT JOIN (
    SELECT
      count(UserID) AS ProtectCount,
      PostID
    FROM PostHistory ph
    WHERE ph.PostHistoryTypeID = @QuestionProtected
      GROUP BY PostID
  ) AS Protected ON Protected.PostID = ph.PostID
  LEFT JOIN (
    SELECT
      count(ph.UserID) AS UnprotectedCount,
      PostID
     FROM PostHistory ph
     WHERE ph.PostHistoryTypeID=20
     GROUP BY PostID
  ) AS Unprotected ON Unprotected.PostID = ph.PostID
WHERE
  ph.UserID IN (
    -- NumbUsers: Max number of users
    SELECT TOP ##NumbUsers:int?5000##
      ph.UserId
    FROM PostHistory ph
      JOIN Posts p ON ph.PostID=p.id
    WHERE ph.PostHistoryTypeId = @QuestionProtected
      AND p.ViewCount < @postViews /* exclude former moderators */
      AND ph.UserID NOT IN (
         SELECT usrExcl.UserID from @UsersToExclude as usrExcl
      )
    GROUP BY ph.UserId
    ORDER BY COUNT(ph.UserId) DESC
  )
  AND ph.PostHistoryTypeId = @QuestionProtected
  AND p.ClosedDate IS NULL
  AND p.ViewCount < @postViews
  AND COALESCE(Protected.ProtectCount,0) <> COALESCE(Unprotected.UnprotectedCount,0)
ORDER BY ph.UserId ASC;


Writing an HTTP POST body that has new lines I am looking for general ways to simplify this. What it does is write a body and send an HTTP POST request to an endpoint. I had the method require a list just to append new lines for each string I build at an earlier point in time. The expected response is in JSON, so I'm also looking for ways to simplify capturing the response. If there are any small libraries that can do this I can consider using them.

private void makeRequest(List<String> records) throws IOException
{
    URL url = new URL("http://my-api.com/post-endpoint");
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    try (OutputStream output = connection.getOutputStream()) {
        Iterator<String> iterator = records.iterator();
        while (iterator.hasNext()) {
            String json = iterator.next();
            output.write(json.getBytes(Charset.forName("UTF-8")));
            if (iterator.hasNext()) {
                output.write('\n');
            }
        }
    }

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    System.out.println("RESPONSE: " + response.toString());
}

Iterating over a list

Using an Iterator to iterate over a list is very old-fashioned.
It's better to use the for-each syntax when possible:

for (String record : records) {
    // ...
}

I noticed that the last element is treated differently from the others:
a \n character is not appended after the last record.
Is that really necessary?
I doubt it. Trailing \n characters should not make the JSON invalid.
Although the implementation may be correct to not print a trailing \n,
it seems a bit pedantic.

If for some reason you need to keep the special treatment of the last line,
you can still use the for-each technique with twist:

if (!records.isEmpty()) {
    output.write(records.get(0).getBytes(Charset.forName("UTF-8")));
    for (String record : records.subList(1, records.size())) {
        output.write('\n');
        output.write(record.getBytes(Charset.forName("UTF-8")));
    }
}

That is, instead of treating the last item specially,
we treat the first item specially,
and then use .subList to effectively work with the tail of the list.
Note that .subList does not copy the content of the list,
so it's not inefficient.

And if you can use Java 8, then an even more compact solution is possible using String.join:

output.write(String.join("\n", records).getBytes(Charset.forName("UTF-8")));

try-with-resources

You used try-with-resources when writing to the output stream, but not when reading from the input stream. It's always good to use it whenever possible:

StringBuilder response = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
}


Simple script to insert data This is a simple script which inserts data into a couple of tables. I'm very new to SQL so any feeback, of any kind, would be much appreciated!

DECLARE
      @Model_ID INT
    , @ModelVersion VARCHAR(10)
    , @ExistsInDM INT
    , @IsActive BIT

SET @ModelVersion = '2.46.7' -- new version number
SET @IsActive = '1'

SELECT  @Model_ID = Model_ID
FROM    [sch_AM].[tblDMModelVersion] WITH (NOLOCK)
WHERE   [ModelVersion] = @ModelVersion

IF @Model_ID IS NULL
BEGIN
    INSERT  INTO [sch_AM].[tblDMModelVersion]
            (  [ModelVersion]
                ,[IsActive]
                            )
    VALUES  ( @ModelVersion
                ,@IsActive
                )

    EXECUTE sch_AM.usp_GetActiveModel_ID @ModelVersion, @Model_ID OUTPUT

    SELECT @ExistsInDM = COUNT(Model_ID)
    FROM [sch_AM].[tblDMModelToTable] WITH (NOLOCK)
    WHERE Model_ID = @Model_ID

    IF @ExistsInDM = 0
        BEGIN
            INSERT INTO [sch_AM].[tblDMModelToTable]
            SELECT
                    @Model_ID
                    ,[Table_ID]
                    ,[TableVersion]
                    ,[UserViewable]
                    ,[TableRequiredByModel]
            FROM [sch_AM].[tblDMModelToTable] WITH (NOLOCK)
            WHERE Model_ID = 1
        END
END

SELECT * FROM [sch_AM].[tblDMModelVersion] WHERE Model_ID = @Model_ID
SELECT * FROM [sch_AM].[tblDMModelToTable] WHERE Model_ID = @Model_ID

Just 1 will work here.  It will do a cast to 1

SET @IsActive = 1

You can also assign in the declare

DECLARE
      @Model_ID INT
    , @ModelVersion VARCHAR(10) = 'lasdf'
    , @ExistsInDM INT
    , @IsActive BIT = 1

SELECT  @Model_ID = Model_ID
FROM    [sch_AM].[tblDMModelVersion] WITH (NOLOCK)
WHERE   [ModelVersion] = @ModelVersion

Above will get the last value read.

with (nolock)

Is typically not advised.


Movement function for a Sokoban game using Python I've been working on the functions that handle when a player's sprite interacts with either a wall (0) or say the crate to push (£)
I'm just wondering how this looks and if there alternative methods, as I've been told I can make things more complicated than they really need to be.

def MOVE_UP():
    x = MapGrid.getCharLocation(PlayerMan.getRow() - 1, PlayerMan.getCol())
    y = MapGrid.getCharLocation(Boxes.getRow() - 1, Boxes.getCol())
    if x == '0':
        pass
    elif x == '£':
        if y == '0':
            pass
        else:
            MapGrid.despawn(Boxes.getRow(), Boxes.getCol())
            Boxes.pushUp()
            MapGrid.spawnBoxes(Boxes.getChar(), Boxes.getRow(), Boxes.getCol())

            MapGrid.despawn(PlayerMan.getRow(), PlayerMan.getCol())
            PlayerMan.MOVE_UP()
            MapGrid.spawnMan(PlayerMan.getChar(), PlayerMan.getRow(), PlayerMan.getCol())
            print(Boxes.displayOnScreen())

    else:
        MapGrid.despawn(PlayerMan.getRow(), PlayerMan.getCol())
        PlayerMan.MOVE_UP()
        MapGrid.spawnMan(PlayerMan.getChar(), PlayerMan.getRow(), PlayerMan.getCol())
        print(MapGrid.displayOnScreen())
        print(PlayerMan.displayOnScreen())

This code, in Python 3.6, is repeated for the other three directions.

strings

I seems your grid is a nested list of strings. It would be clearer, if you change that to Enums

from enum import Enum

class Tiles(Enum):
    WALL = '0'
    PLAYER = "*"
    BOX = '£'
    EMPTY = '.'

so you can do something like this:

w = Tiles.WALL
e = Tiles.EMPTY
b = Tiles.BOX
p = Tiles.PLAYER
grid = [
    [w,w,w,w,w],
    [w,e,e,e,w],
    [w,e,e,b,w],
    [w,b,b,p,w],
    [w,e,e,b,w],
    [w,e,e,b,w],
    [w,e,e,e,w],
    [w,w,w,w,w],
]

getter and setters

Python does not have the Java tradition of setters and getters. If you want to work with a calculated property, of protect a property, you can use @property. This can work like this

class Boxes:
    def __init__(self, row, ...):
        self._row = row
        ...

    @property
    def row(self):
        return self._row

and so on for char and column

double work

The position of the Boxes and the player is kept both in the MapGrid , and in PlayerMan and Boxes. This is double work, and prone to errors.

Now to move something, you have to adapt it both in the grid (.despawn and .spawnXXX and on the PlayerMan and Boxes, resulting in a lot of unnecessary code.

All you really need to capture the state of the board is this:

class SokobanGrid():
    def __init__(self, grid, position, strength=None):
        grid = list(map(list, grid))  # make a copy of the grid
        assert grid[position[0]][position[1]] == Tiles.PLAYER
        num_players = sum(
            sum(tile == Tiles.PLAYER for tile in row)
            for row in grid
        )
        assert num_players == 1

        self._grid = grid

        self._dimensions = len(grid), len(grid[0])
        self.position = position
        self.strength = strength

    def copy(self):
        return SokobanGrid(self._grid, position=self.position)

displayOnScreen()

instead of making a method that returns a string representation of the board, you can define __str__ and/or __repr__

    def __str__(self):
        rows = (
            f'x{idx}: ' + ''.join(tile.value for tile in row)
            for idx, row in enumerate(self._grid)
        )
        header = ' ' * 4 + ''.join(map(str, range(self._dimensions[1]))) + '\n'
        return header + '\n'.join(rows)

you can omit the position parameter, and go look for it yourself.

g = SokobanGrid(grid=grid, position=(3, 3))
print(g)

    01234
x0: 00000
x1: 0...0
x2: 0..£0
x3: 0££*0
x4: 0..£0
x5: 0..£0
x6: 0...0
x7: 00000

The interactions with the tile then go like this:

    def tile(self, x, y):
        return self._grid[x][y]

    def iswall(self, x, y):
        return self.tile(x, y) == Tiles.WALL

    def isbox(self, x, y):
        return self.tile(x, y) == Tiles.BOX

    def isempty(self, x, y):
        return self.tile(x, y) == Tiles.EMPTY

    def set_tile(self, x, y, tile):
        self._grid[x][y] = tile

    def swap_tiles(self, old, new):
        old_tile = self.tile(*old)
        new_tile = self.tile(*new)
        self.set_tile(*old, new_tile)
        self.set_tile(*new, old_tile)

moving

Instead of a move method for each direction, you can make a generic one, that accepts a direction. The directions can be an Enum, with a value the change in coordinates it entails (UP is (-1, 0), because row 0 is the top row)

class Direction(Enum):
    UP = (-1, 0)
    DOWN = (1, 0)
    LEFT = (0, -1)
    RIGHT = (0, 1)

The first helper method yields all the moves in a certain direction until it hits a wall (not included) or an empty spot (included)

    def _moves(self, Direction):
        x, y, = self.position
        x_max, y_max = self._dimensions
        dx, dy = Direction.value
        while 0 <= x < x_max and 0 <= y < y_max:
            if self.iswall(x, y):
                return
            yield x, y
            if self.isempty(x, y):
                return
            x, y = x + dx, y + dy

the second helper method checks whether the player can move in a certain direction:

    def can_move(self, direction):
        for boxes, position in enumerate(self._moves(direction)):
            if self.isempty(*position):
                return True
            if self.iswall(*position):
                return False
            if self.strength and boxes > self.strength:
                return False
        return False

This raises a class IllegalMove(Exception): pass to signal to the user interface that a move is not allowed. You might use a ValueError instead

This can be tested with

d = Direction.DOWN
u = Direction.UP
l = Direction.LEFT
r = Direction.RIGHT

assert g.can_move(u)
assert g.can_move(d)
assert not g.can_move(l)
assert not g.can_move(r)

The meaning of the strength parameter, is the maximum amount of boxes the player can push. If we set this to 1, it should not be able to push down anymore:

g_1 = g.copy()
g_1.strength = 1
assert g_1.can_move(u)
assert not g_1.can_move(d)
assert not g_1.can_move(l)
assert not g_1.can_move(r)

Now to move, we must start from the first empty tile to the player, and swap the tiles piece by piece

    def move(self, direction):
        if not self.can_move(direction):
            raise IllegalMove
        moves = self._moves(direction)
        moves = reversed(list(moves))
        for old, new in pairwise(moves):
            self.swap_tiles(old, new)

pairwise is from the itertools recipes

from itertools import tee, takewhile
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

so:

g_move = g.copy()
g_move.move(d)
print(g_move)

    01234
x0: 00000
x1: 0...0
x2: 0..£0
x3: 0££.0
x4: 0..*0
x5: 0..£0
x6: 0..£0
x7: 00000


Automatic CRL files converter In my job we use our internal CA, which runs on a Windows server. When I want to use its CRL on a Linux machine I have to do these steps:

download root CA and intermediate CAs
covert them to x509
merge into one file (CRL.pem)

For this I wrote the small script below, which I run automatically by timer unit (cron on systems without systemd) once a day.

#!/usr/bin/env bash

crls=(RootCA IntermediateCA IntermediateCA2)
new_crl="newcrl.pem"
crl_temp=$(mktemp -q -d /tmp/pullcrl.XXXXX)
crl_dir="/etc/pki/tls/misc"

for crl in ${crls[@]}; do
  if curl -s http://url_of_crls/${crl}.crl -o ${crl_temp}/${crl}.crl; then
    openssl crl -in ${crl_temp}/${crl}.crl -inform DER -out ${crl_temp}/${crl}.pem
  else
    echo "Download a crl file failed!"
    exit 1
  fi
done

cat ${crl_temp}/*.pem > ${crl_temp}/${new_crl}

mv ${crl_temp}/${new_crl} ${crl_dir}/${new_crl}

Could I do something better?

for crl in ${crls[@]}; do

It's a good habit to always double-quote array expansions.

Cleaning up the temp directory after a successful run would be a nice touch (or do away with it altogether; see below).

cat ${crl_temp}/*.pem > ${crl_temp}/${new_crl}
mv ${crl_temp}/${new_crl} ${crl_dir}/${new_crl}

I assume you're doing this to get atomic replacement?  It only works if /tmp and /etc are on the same filesystem.  If they're not, you could get an empty destination file when (for example) the target is full.  Consider creating a working directory under /etc to be certain.

You could be more concise using cd and brace expansion and bash's own error handling (via set -euxo pipefail):

set -euxo pipefail

cd /etc/pki/tls/misc
temp=$( mktemp -p . )

for url in http://…blahblah…/{RootCA,IntermediateCA,IntermediateCA2}.crl ; do
    curl $url | openssl crl -in - -inform DER
done > $temp
mv $temp newcrl.pem


Codeigniter calling conditional data retrieval model method from controller I am wondering if there's a better way to structure my code. I want to keep my controllers thin but at the same time want to keep the model methods flexible. As you can see below, it's almost as if I can write active record code directly on my controller itself (Which not be a good thing?)

The line of code in the controller:

$request_forms = $this->request_form_model->where('status', Request_form_model::STATUS_ON)->find_all(NULL, NULL, NULL, ['title', 'id', 'service_category_id'])->result();

The relevant code in MY_Model which the Request_form_model extends from:

function where($field, $value){
    $this->db->where($field, $value);
    return $this;
}

function find_all($limit = NULL, $offset = NULL, $order_by = NULL, $select_fields = '*', $escape_select = NULL){

    if( is_array( $select_fields ) ) {
        $select_fields = implode(',', $select_fields);
    }

    $this->db->select($select_fields, $escape_select);

    if(isset($order_by)) {
        $this->order_by($order_by);
    }

    $this->limit($limit, $offset);

    return $this->db->get_where($this->table_name);
}

Readability and Usability

Your function is indeed quite generic, which does give you a lot of power in your controller. But I would agree with you, that this is not necessarily a good thing.

Just looking at your controller line, I would have no idea what it does, because it's impossible to know what all the NULL values stand for. Apart from it being hard to read, I would also think that this function is hard to use. I would have to look up the order of the parameters each time when I write a query.

Need for Flexibility

The first thing I would check is if your models actually need to be this flexible. Because that way, you do blow up your controller a bit, as it has to make the decision of what to actually extract.

In your example, you don't actually need the limit, offset, or order_by, so if it's not needed elsewhere (and probably also not needed in the future), think about removing it.

I'll just assume that you do indeed need the flexibility, but it's something to think about.

Two Possible Alternatives

I could think of two different ways to improve your code, one offering reduced flexibility, the other keeping the existing flexibility and increasing readability.

Option 1

The first option is to write additional functions which access your find_all function internally:

function find_all_sorted($order_by) {
    // call find_all
}

function find_from_to($from, $to) {
    // call find_all
}

// [...]

You loose some flexibility (or you have to add quite a lot of methods to get the same flexibility), but your controller will be slimmer. If you can cover all needed use-cases with a couple of these methods, this might be the way to go.

Option 2

The second possibility is to expose the database methods to the outside as you did with the where method. You will have the same flexibility as before, but your code will be more readable.

If you don't want to expose the actual methods of the database (which would be cleaner, as the controller shouldn't actually care about the way the database is accessed), you could also just add setters to it:

function from_to($from, $to) {
    $this->from = $from;
    $this->to = $to;
}

function order_by($order_by) {
    $this->from = $from;
    $this->to = $to;
}

function select($fields) {
    $this->fields = $fields;
}

function query() {
    // call find_all with the set parameters, like you did before from the controller
}

In the controller, it would then look like this:

$this->request_form_model
    ->select(['title', 'id', 'service_category_id'])
    ->where('status', Request_form_model::STATUS_ON)
    ->from_to('1', '10')
    ->order_by('title')
    ->query();

Each of the method calls is optional, and it's clear for the reader what the query will return, without looking up the documentation for each method.


Retrieve filename and ID with Google Drive API in C# I am trying to retrieve filename and ID list with Google Drive API (the latest Drive API version v3 is used here) as a first step in order to analyze and manipulate these files on Google Drive. The experimental implementation is as below. (Note: credentials.json file is needed and the step to generate this file is here. )
The experimental implementation
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GoogleDriveFileManager
{
    class Program
    {
        static string[] Scopes = { DriveService.Scope.DriveReadonly };
        static string ApplicationName = "GoogleDriveFileManager";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine($"Credential file saved to: {credPath}");
            }

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 1000;
            listRequest.Fields = "nextPageToken, files(id, name)";

            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
            Console.WriteLine("Files:");
            Console.WriteLine($"file.Name{new String('\t', 6)}file.Id{new String('\t', 8)}file.ModifiedTime");
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    Console.WriteLine(
                        $"{file.Name.PadRight(56)}{file.Id.PadRight(36)}{file.ModifiedTime}"
                        );
                }
            }
            else
            {
                Console.WriteLine("No files found.");
            }
            Console.Read();
        }
    }
}

If there is any possible improvement about potential drawback or unnecessary overhead, please let me know.

First of all let me clarify that I'm not familiar with the Google Drive API. I've done some refactoring but I haven't tested it (just make it compile).
If I can assume you are using greater C# version than 8 then you can refactor your code like this:
using static {YourMainNamespace}.Constants;

class Program
{
    static async Task Main(string[] args)
    {
        UserCredential credential = await AuthorizeAgainstGoogleDriveAsync();
        IList<Google.Apis.Drive.v3.Data.File> files = await GetFilesMetaInfoAsync(credential);
        DisplayFilesMetaInfoInTabularFashion(files);
        Console.ReadLine();
    }

    static async Task<UserCredential> AuthorizeAgainstGoogleDriveAsync(
        string sourceRelativePath = Authorize.RelativeFilePath.Source,
        string targetRelativePath = Authorize.RelativeFilePath.Target)
    {
        using var stream = new FileStream(sourceRelativePath, FileMode.Open, FileAccess.Read);

        var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(stream).Secrets,
            Authorize.Scopes,
            Authorize.User,
            CancellationToken.None,
            new FileDataStore(targetRelativePath, true));

        Console.WriteLine($"Credential file saved to: {Authorize.RelativeFilePath.Target}");

        return credential;
    }

    static async Task<IList<Google.Apis.Drive.v3.Data.File>> GetFilesMetaInfoAsync(
        UserCredential credential,
        string applicationName = GetFiles.ApplicationName,
        int pageSize = GetFiles.PageSize,
        string fields = GetFiles.Fields)
    {
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = applicationName,
        });

        FilesResource.ListRequest listRequest = service.Files.List();
        listRequest.PageSize = pageSize;
        listRequest.Fields = fields;

        var fileList = await listRequest.ExecuteAsync();

        return fileList.Files;
    }

    static void DisplayFilesMetaInfoInTabularFashion(IList<Google.Apis.Drive.v3.Data.File> files)
    {
        Console.WriteLine("Files:");
        Console.WriteLine($"{DisplayFiles.Name}{new string('\t', 6)}{DisplayFiles.Id}{new string('\t', 8)}{DisplayFiles.ModifiedTime}");

        if (files == null || files.Count <= 0)
        {
            Console.WriteLine(DisplayFiles.NoFileMessage);
            return;
        }

        foreach (var file in files)
        {
            Console.WriteLine($"{file.Name,-56}{file.Id,-36}{file.ModifiedTime}");
        }

    }
}

static class Constans
{
    public static class Authorize
    {
        public const string User = "user";
        public readonly static string[] Scopes = new[] { DriveService.Scope.DriveReadonly };

        public static class RelativeFilePath
        {
            public const string Source = "credentials.json";
            public const string Target = "token.json";
        }
    }

    public static class GetFiles
    {
        public const string ApplicationName = "GoogleDriveFileManager";
        public const int PageSize = 1000;
        public const string Fields = "nextPageToken, files(id, name)";
    }

    public static class DisplayFiles
    {
        private const string prefix = "file.";
        public const string Name = prefix + nameof(Name);
        public const string Id = prefix + nameof(Id);
        public const string ModifiedTime = prefix + nameof(ModifiedTime);
        public const string NoFileMessage = "No files found.";
    }
}

Let me give you some context for each part:
Main
static async Task Main(string[] args)
{
    UserCredential credential = await AuthorizeAgainstGoogleDriveAsync();
    IList<Google.Apis.Drive.v3.Data.File> files = await GetFilesMetaInfoAsync(credential);
    DisplayFilesMetaInfoInTabularFashion(files);
    Console.ReadLine();
}

I've made your Main async (supported since C# 7.1) to be able to use async-await
I've split your logic into three smaller functions to make your Main short and concise

If the scope of the application is this small then you can use shorter names of course, like

AuthorizeAsync
GetFiles
DisplayFiles

Constants
using static {YourMainNamespace}.Constants;

...

static class Constans
{
    public static class Authorize
    {
        public const string User = "user";
        public readonly static ImmutableArray<string> Scopes = new[] { DriveService.Scope.DriveReadonly }.ToImmutableArray();

        public static class RelativeFilePath
        {
            public const string Source = "credentials.json";
            public const string Target = "token.json";
        }
    }

    public static class GetFiles
    {
        public const string ApplicationName = "GoogleDriveFileManager";
        public const int PageSize = 1000;
        public const string Fields = "nextPageToken, files(id, name)";
    }

    public static class DisplayFiles
    {
        private const string prefix = "file.";
        public const string Name = prefix + nameof(Name);
        public const string Id = prefix + nameof(Id);
        public const string ModifiedTime = prefix + nameof(ModifiedTime);
        public const string NoFileMessage = "No files found.";
    }
}

I've put all of the hardcoded values into a hierarchical structure

Because I'm unfamiliar with the domain I've organize them based on the usage
In normal cases you should organize them based on their semantics

I've used const (which is implicit static) to prevent modification
In case of Scope I've used ImmutableArray to prevent modification

Here I can't use const but it could (and should) be marked as readonly

I've used using static to avoid prefixing with Constants each and every time

AuthorizeAgainstGoogleDriveAsync
static async Task<UserCredential> AuthorizeAgainstGoogleDriveAsync(
    string sourceRelativePath = Authorize.RelativeFilePath.Source,
    string targetRelativePath = Authorize.RelativeFilePath.Target)
{
    using var stream = new FileStream(sourceRelativePath, FileMode.Open, FileAccess.Read);

    var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets,
        Authorize.Scopes,
        Authorize.User,
        CancellationToken.None,
        new FileDataStore(targetRelativePath, true));

    Console.WriteLine($"Credential file saved to: {Authorize.RelativeFilePath.Target}");

    return credential;
}

I've made the source and target file paths configurable (but with default values)

If you wish you can make the same with user and scopes

One can argue whether the Console.WriteLine should belong here or inside the Main

I've put it here to make the main as concise as possible
But from reusability point of view it should not belong here

I've used using declaration (which is a C# 8 feature) to avoid the block operator ({ ... })

GetFilesMetaInfoAsync
static async Task<IList<Google.Apis.Drive.v3.Data.File>> GetFilesMetaInfoAsync(
    UserCredential credential,
    string applicationName = GetFiles.ApplicationName,
    int pageSize = GetFiles.PageSize,
    string fields = GetFiles.Fields)
{
    var service = new DriveService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = applicationName,
    });

    FilesResource.ListRequest listRequest = service.Files.List();
    listRequest.PageSize = pageSize;
    listRequest.Fields = fields;

    var fileList = await listRequest.ExecuteAsync();

    return fileList.Files;
}

I've made this API call to async (Execute >> ExecuteAsync) to make use of the async non-blocking I/O
I've declared the function with three optional parameters to be able to customize the request if needed
I've realized that you are not making use of the nextPageToken but I did not remove it

I've assumed that the implementation of paging will be your next step

DisplayFilesMetaInfoInTabularFashion
static void DisplayFilesMetaInfoInTabularFashion(IList<Google.Apis.Drive.v3.Data.File> files)
{
    Console.WriteLine("Files:");
    Console.WriteLine($"{DisplayFiles.Name}{new string('\t', 6)}{DisplayFiles.Id}{new string('\t', 8)}{DisplayFiles.ModifiedTime}");

    if (files == null || files.Count <= 0)
    {
        Console.WriteLine(DisplayFiles.NoFileMessage);
        return;
    }

    foreach (var file in files)
    {
        Console.WriteLine($"{file.Name,-56}{file.Id,-36}{file.ModifiedTime}");
    }
}

This operation is tightly coupled to the request

It highly relies on the retrieved fields
So, it might make sense to it make more dynamic if needed

I've used new string instead of new String

I suggest to read this article

I've reverted the if statement to use the early exit pattern

With this the main logic (foreach) is not indented

I've also used the capabilities of string interpolation to avoid calls like PadRight


Project Euler problem 23 - non-abundant sums I present my solution for Project Euler problem 23 written in Python (2.7).

The problem statement is:

  A perfect number is a number for which the sum of its proper divisors
  is exactly equal to the number. For example, the sum of the proper
  divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28
  is a perfect number.

  A number whose proper divisors are less than the number is called
  deficient and a number whose proper divisors exceed the number is
  called abundant.

  As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the
  smallest number that can be written as the sum of two abundant numbers
  is
  24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers.
  However, this upper limit cannot be reduced any further by analysis
  even though it is known that the greatest number that cannot be
  expressed as the sum of two abundant numbers is less than this limit.

  Find the sum of all the positive integers which cannot be written as
  the sum of two abundant numbers.

I have done everything to my knowledge to make the code run as fast as possible. It takes about 600 milliseconds on my machine.

It is one of the first times that I actually put the else part of the for statement to use. Using any alternatively turned out to be about 1.5× as slow.

SMALLEST_ABUNDANT = 12

# largest number for which we have to test if it can be expressed as the
# sum of two abundant numbers
MAX_TEST_SUM_OF_TWO_ABUNDANT = 28123

# largest number for which we have to know if it is abundant
MAX_TEST_ABUNDANT = MAX_TEST_SUM_OF_TWO_ABUNDANT - SMALLEST_ABUNDANT

# largest possible divisor that we have to consider
MAX_DIVISOR = MAX_TEST_ABUNDANT / 2

from collections import defaultdict

def solve_euler23():
    """Return the sum of all positive integers which cannot be written
    as the sum of two abundant numbers.
    """
    # mapping from a number to the set of its proper divisors (i.e.,
    # excluding the number itself)
    divisors = defaultdict(set)
    for divisor in range(1, MAX_DIVISOR+1):
        for number in range(2*divisor, MAX_TEST_ABUNDANT+1, divisor):
            divisors[number].add(divisor)

    def is_abundant(number):
        return sum(divisors[number]) > number

    abundant_numbers = sorted(filter(is_abundant, divisors))

    # make a set so that membership can be tested efficiently
    abundant_numbers_set = set(abundant_numbers)

    impossible_sum_of_two_abundant_numbers = []
    for number in range(1, MAX_TEST_SUM_OF_TWO_ABUNDANT+1):
        for abundant in abundant_numbers:
            if number - abundant in abundant_numbers_set:
                break # is the sum of two abundant numbers
        else:
            impossible_sum_of_two_abundant_numbers.append(number)

    return sum(impossible_sum_of_two_abundant_numbers)

if __name__=='__main__':
    print solve_euler23()

My questions are:

Is there a better algorithm?
Did I overlook something which would make the implementation of my chosen algorithm more efficient?
Can I make the code shorter or clearer?

1. Sieving for sums

The computation of the sum of divisors can be improved using a bit of math. Let's call the sum-of-divisors function \$σ\$, and consider \$σ(60)\$: $$ σ(60) = 1 + 2 + 3 + 4 + 5 + 6 + 10 + 12 + 15 + 20 + 30 + 60. $$ Collect together the divisors by powers of 2: $$ \eqalign{σ(60) &= (1 + 3 + 5 + 15) + (2 + 6 + 10 + 30) + (4 + 12 + 20 + 60) \\ &= (1 + 2 + 4)(1 + 3 + 5 + 15) \\ &= (1 + 2 + 4)σ(15)}. $$ Then do the same thing for \$σ(15)\$, collecting together the divisors by powers of 3: $$ \eqalign{σ(15) &= (1 + 5) + (3 + 15) \\ &= (1 + 3)(1 + 5) \\ &= (1 + 3)σ(5)}. $$ And so on, getting \$σ(60) = (1 + 2 + 4)(1 + 3)(1 + 5)\$. In general, if we can factorize \$n\$ as: $$ n = 2^a3^b5^c\dotsm $$ then $$ σ(n) = (1 + 2 + \dotsb + 2^a)(1 + 3 + \dotsb + 3^b)(1 + 5 + \dotsb + 5^c)\dotsm $$ These multipliers occur many times, for example \$(1 + 2 + 4)\$ occurs in the sum of divisors of every number divisible by 4 but not by 8, so it's most efficient to sieve for the sums of many divisors at once, like this:

def all_sum_divisors(n):
    """Return a list of the sums of divisors for the numbers below n.

    >>> all_sum_divisors(10) # https://oeis.org/A000203
    [1, 1, 3, 4, 7, 6, 12, 8, 15, 13]

    """
    result = [1] * n
    for p in range(2, n):
        if result[p] == 1: # p is prime
            p_power, last_m = p, 1
            while p_power < n:
                m = last_m + p_power
                for i in range(p_power, n, p_power):
                    result[i] //= last_m
                    result[i] *= m
                last_m = m
                p_power *= p
    return result

2. Review

I would change the signature of the function as follows:

def solve_euler23(n=28124):
    """Return the sum of all positive integers below n which cannot be
    written as the sum of two abundant numbers."""

The reason for doing this is to make it possible to test the function on small instances: for example, you could test the claim in the problem statement (that 24 is the smallest number that cannot be written etc.), by running solve_euler23(24) and checking that it returns \$ \sum_{1≤i<24}i=276 \$, and then running solve_euler23(25) and checking that it returns the same result.
The division operator / returns a float in Python 3, so for portability it would be worth writing:

MAX_DIVISOR = MAX_TEST_ABUNDANT // 2

The efficiency gain of avoiding computing the sum of divisors of the numbers up to SMALLEST_ABUNDANT (12) is negligible, and it deprives you of the chance to check that your sum-of-divisors algorithm is correct on small numbers (for example, an off-by-one error might lead it to deduce that 6 is abundant, but if you started at 12 you might have trouble spotting the bug).
The question only asks for the sum of the positive integers which cannot be written as the sum of two abundant numbers, so it's not necessary to keep a list of the numbers themselves.
When looking for sums adding up to number, the code tests every abundant number:

for number in range(1, MAX_TEST_SUM_OF_TWO_ABUNDANT+1):
    for abundant in abundant_numbers:
        if number - abundant in abundant_numbers_set:
            break

but we only need to test abundant numbers up to number // 2 (if two abundant numbers add up to number, then one of them will be no more than number // 2). We could test for this in the loop:

for number in range(1, MAX_TEST_SUM_OF_TWO_ABUNDANT+1):
    for abundant in abundant_numbers:
        if number - abundant in abundant_numbers_set:
            break
        else if abundant >= number // 2:
            impossible_sum_of_two_abundant_numbers.append(number)
            break

but because abundant_numbers is sorted, we can quickly calculate how far along this list we need to go, using bisect.bisect and itertools.islice:

for number in range(1, MAX_TEST_SUM_OF_TWO_ABUNDANT+1):
    for abundant in islice(abundant_numbers,
                           bisect(abundant_numbers, number // 2)):
        if number - abundant in abundant_numbers_set:
            break

3. Revised code

from bisect import bisect
from itertools import islice

def solve_euler23(n=28124):
    """Return the sum of all positive integers below n which cannot be
    written as the sum of two abundant numbers.

    """
    sum_divisors = all_sum_divisors(n)
    abundant = [i for i in range(1, n) if sum_divisors[i] > 2 * i]
    abundant_set = set(abundant)
    def unsums():
        for i in range(1, n):
            for j in islice(abundant, bisect(abundant, i // 2)):
                if i - j in abundant_set:
                    break
            else:
                yield i
    return sum(unsums())

I find this is about three times as fast as the code in the original post.


.htaccess Recommendations I have a personal website that's used primarily for fun. I upload images, videos and text that I want to share. An HTML submission form accepts questions and string submissions from users, which uses a phpmyadmin database table for storage.
The below snippet is my current .htaccess file. https://gtmetrix.com/ notes that redirects are the largest culprit in slowing down my page loads, but I'm unsure of how to streamline them.
RewriteEngine On

#REDIRECT TO SECURE HTTPS CONNECTION
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www.MYDOMAIN.com [NC]
RewriteRule ^(.*)$ https://MYDOMAIN.com/$1 [L,R=301]

#URL EXTENSION REMOVAL
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

#HOTLINKING PROTECTION
    #NOTE: having |html| and |htm| included prevented access of the site through browser search, so i removed them.
RewriteCond %{HTTP_REFERER} !^https://(www\.)?MYDOMAIN\.com(/.*)*$ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(css|flv|gif|ico|jpe|jpeg|jpg|js|mp3|mp4|php|png|pdf|swf|txt)$ - [F]

#CONTENT SECURITY POLICY
<FilesMatch "\.(html|php)$">
    Header set Content-Security-Policy "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: 'unsafe-inline'; media-src 'self' data: 'unsafe-inline'; connect-src 'self';"
</FilesMatch>

#REDIRECT FOR DATE PAGE
Redirect /date /storage/date-202010

#REDIRECT FOR HOME PAGE
Redirect /home /

#CUSTOM ERROR PAGES
ErrorDocument 400 /allerror.php
ErrorDocument 401 /allerror.php
ErrorDocument 403 /allerror.php
ErrorDocument 404 /allerror.php
ErrorDocument 405 /allerror.php
ErrorDocument 408 /allerror.php
ErrorDocument 500 /allerror.php
ErrorDocument 502 /allerror.php
ErrorDocument 504 /allerror.php

#PREVENT DIRECTORY BROWSING
Options All -Indexes

#FILE CACHING
    #cache html and htm files for one day
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "max-age=43200"
</FilesMatch>
    #cache css, javascript and text files for one week
<FilesMatch "\.(js|css|txt)$">
Header set Cache-Control "max-age=604800"
</FilesMatch>
    #cache flash and images for one month
<FilesMatch "\.(flv|swf|ico|gif|jpg|jpeg|mp4|png)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>
    #disable cache for script files
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>

#BLOCKS FILE TYPES FOR USERS
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|inc|bak)$">
Order Allow,Deny
Deny from all
</FilesMatch>

UPDATE
I have created a new post integrating an HSTS and many of the changes that were recommended by Mr. White. The bounty has been awarded. Please direct any further feedback to the New Post.

https://gtmetrix.com/ notes that redirects are the largest culprit in slowing down my page loads

gtmetrix.com's "suggestion" in this regard is arguably "incorrect" (or rather, not nearly as serious as it implies), assuming you are already consistently linking to the canonical URL*1 throughout your site (and you have no other redirects in your application code). These redirects are only likely to affect a "very small fraction" of your site visitors on their very first visit.
(*1 Canonical URL being HTTPS + non-www + no .html extension.)
You have 3 external redirects in the .htaccess code you posted:

#REDIRECT TO SECURE HTTPS CONNECTION
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

#URL EXTENSION REMOVAL
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

If you have implemented HSTS then you need to redirect from HTTP to HTTPS on the same host, before canonicalising the www subdomain - which is what you are doing above in the first rule. This is a requirement of HSTS and the "preload list". So you cannot avoid having at least 2 redirects (worst case) in this scenario.
However, if you have no intention of implementing HSTS then you can combine the first two redirects into one. Which you can do by simply reversing the order of the first two rules. For example:
#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]

#REDIRECT TO SECURE HTTPS CONNECTION
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The first rule, that redirects www to non-www, also redirects to HTTPS, so there is never a need to execute the 2nd redirect as well. So, there is only ever 1 redirect to canonicalise HTTPS and non-www.
I also removed the redundant capturing subpattern (ie. (.*)) in the "HTTP to HTTPS" RewriteRule pattern, since you are using the REQUEST_URI server variable instead. And changed the other "www to non-www" redirect to be consistent. Note that the REQUEST_URI server variable contains the full URL-path, including the slash prefix, whereas the captured backreference omits the slash prefix.
The above two rules could be combined into a single (marginally more complex) rule, but there is no benefit in doing so.
The rules could also be made more "generic", without having to explicitly state the canonical hostname. However, how you implement this and whether this is easily possible is dependent on whether you have other subdomains or not. But again, this serves no "benefit", other than being more copy/pastable. Generally, it is preferable to be explicit here - less prone to error.

#URL EXTENSION REMOVAL
RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

You can also avoid the .html "extension removal redirect" from triggering an additional redirect by including this redirect first (before the above two canonical redirects) and redirecting directly to HTTPS and non-www (the canonical scheme+hostname) as part of the redirect.
UPDATE: This should also be a 301 (permanent) redirect, not a 302 (temporary) redirect that it is currently. A 301 redirect is cached by the browser by default, so it avoids unnecessary round trips to the server. When you don't explicitly include the status code with the R flag, it defaults to a 302.
The NC flag is also not required on the RewriteRule directive, since you are not matching anything here that is case-sensitive.
This rule to remove the .html extension probably works OK for your URLs, however, it's not necessarily correct and could possibly be made more efficient. The reason for checking against THE_REQUEST server variable, as opposed to the RewriteRule pattern or REQUEST_URI server variable is to avoid a potential redirect loop by preventing rewritten requests from being redirected. This is because THE_REQUEST does not change after the request is rewritten - it contains the first line of the HTTP request headers. However, THE_REQUEST also contains the query string, so it's possible for a legitimate request that contains .html as part of the query string to be incorrectly redirected.
For example, request example.com/?p1=foo.html&p2=bar (the homepage with a query string and URL parameters containing the value foo.html) and this will be incorrectly redirected to example.com/?p1=foo, truncating the query string.
The regex /([^.]+)\.html will also fail to match any URL that contains dots as part of the URL-path in places other than the file extension. eg. A request for /foo.bar.html would not be redirected. Although this may be perfectly OK for the URLs on your site.
To avoid these "incorrect" redirects you could capture the URL-path from the RewriteRule pattern instead and either use a simpler condition and check against THE_REQUEST (to avoid a loop) or use the REDIRECT_STATUS environment variable instead, which is always empty on direct requests.
For example:
#URL EXTENSION REMOVAL
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule (.+)\.html$ https://example.com/$1 [NC,R=301,L]

This captures the URL-path before the .html file extension using the RewriteRule pattern (which naturally excludes the query string). The simple condition that checks the REDIRECT_STATUS env var prevents a redirect loop.
Bringing the above points together we have:
#URL EXTENSION REMOVAL
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule (.+)\.html$ https://example.com/$1 [NC,R=301,L]

#FORCE WWW TO NON-WWW
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^ https://example.com%{REQUEST_URI} [L,R=301]

#REDIRECT TO SECURE HTTPS CONNECTION
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The NC flag was not required in the "URL extension removal" redirect.
This now triggers at most 1 redirect regardless of whether a request comes in for HTTP, www or includes the .html extension. However, as noted, this is at the expense of not satisfying the requirements for HSTS.
And it should be noted, that in real terms, there may not be a perceivable difference between 1, 2 or even 3 redirects here. Particularly since it will not affect the vast majority of visitors anyway.

Additional:

#REDIRECT FOR DATE PAGE
Redirect /date /storage/date-202010

#REDIRECT FOR HOME PAGE
Redirect /home /

Generally, you should avoid mixing redirects from both mod_alias (Redirect / RedirectMatch) and mod_rewrite (RewriteRule). The two modules run independently and at different times during the request, despite the apparent order of the directives in the .htaccess file.  mod_rewrite runs first. So, you can get unexpected conflicts.
Note also that Redirect is prefix-matching and everything after the match is appended on to the end of the target URL. eg. /date/foo would get redirected to /storage/date-202010/foo by the first rule. These particular redirects are also 302 (temporary) redirects. It looks like they should be 301 (permanent)?
However, in this case it probably does not matter whether you use Redirect or RewriteRule, but as a general rule, if you are using mod_rewrite for some redirects, then use mod_rewrite for all redirects. For example:
#REDIRECT FOR DATE PAGE
RewriteRule ^date$ /storage/date-202010 [R=301,L]

#REDIRECT FOR HOME PAGE
RewriteRule ^home$ / [R=301,L]

#BLOCKS FILE TYPES FOR USERS
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|inc|bak)$">
Order Allow,Deny
Deny from all
</FilesMatch>

You stated in comments that you are using Apache 2.4, however Order, Allow and Deny are Apache 2.2 directives and are formerly deprecated on Apache 2.4. They still work, but for backwards compatibility only and should be updated as soon as.
Note that you need to update all instances on your system since the newer directives don't necessarily mix well.
On Apache 2.4 you would use the Require directive instead:
#BLOCKS FILE TYPES FOR USERS
<FilesMatch "\.(ht[ap]|ini|log|sh|inc|bak)$">
Require all denied
</FilesMatch>

Note that the Apache server config "should" already be blocking direct access to .htaccess and .htpasswd files, but better to be safe I guess.

ErrorDocument 500 /allerror.php

Defining the 500 ErrorDocument late in .htaccess is probably too late to catch most 500 (Internal Server Error) responses (that result from misconfigurations). There's probably not much you can do about this, but it would be preferable to define this earlier in the server config (or <VirtualHost> container) in order to be more "useful".


Calculate the Lagrange polynomial I had to write a program to calculate the Lagrange polynomial of the maddening degree of function: \$\log(x+1)+\cos(x-1)\$

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#define GRADE 6

/* Funzione per costruire la successione dei nodi (xi,yi) dei punti di valutazione*/
void nodeSuccession(double* xNode, double* yNode, double* xVal){
    int i;

    printf("xNode [");
    for(i = 0; i < GRADE + 1; i++){
        xNode[i] = i; /* Array contenete le ascisse dei nodi */
        printf("%.4f, ", xNode[i]);
        yNode[i] = 0; /* Array contenete le ordinate dei nodi */
    }
    printf("\b\b]\n");

    printf("yNode [");
    for(i = 0; i < GRADE + 1; i++){
        yNode[i] = (log(xNode[i] + 1)) + cos(xNode[i] - 1);
        printf("%.4f, ", yNode[i]);
    }
    printf("\b\b]\n");

    printf("xVal  [");
    for(i = 0; i < GRADE; i++){
        xVal[i] = (xNode[i] + xNode[i+1]) / 2;
        printf("%.4f, ", xVal[i]);
    }
    printf("\b\b]\n");

}
/* Funzione per costruire il polinomio di lagrange e lo valuto nei punti */
double* polynomial(double *xVal, double *xNode, double *yNode){
    int i, j, k;
    double pr, *sum = malloc(GRADE * sizeof(double));

    for(j = 0; j < GRADE; j++){
        sum[j] = 0;
        for(k = 0; k < GRADE + 1; k++){
            pr = 1;
            for(i = 0; i < GRADE + 1; i++){
                if(k != i)
                    pr = pr * ((xVal[j] - xNode[i])/(xNode[k] - xNode[i]));
            }
            sum[j] = sum[j] + yNode[k] * pr;
        }
    }

    return sum;
}

/* Funzione per la valutazione dell'errore di interpolazione */
double* error(double *xVal, double *sum){

    int i;
    double *err = malloc(GRADE * sizeof(double));

    for(i = 0; i < GRADE; i++)
        err[i] = fabs(((log(xVal[i] + 1)) + cos(xVal[i] - 1)) - sum[i]);

    return err;
}

int main(void){
    int i;
    double xNode[GRADE + 1], xVal[GRADE], yNode[GRADE + 1];
    double *poly = malloc(GRADE * sizeof(double)), *err = malloc(GRADE * sizeof(double));

    system("clear");
    printf("\n===== PROGRAMMA PER IL CALCOLO DEL POLINOMIO DI LAGRANGE =====\n\n");

    nodeSuccession(xNode, yNode, xVal);
    poly = polynomial(xVal, xNode, yNode);

    printf("\npoly  [");
    for(i = 0; i < GRADE; i++)
        printf("%.4f, ", poly[i]);
    printf("\b\b]\n");

    err = error(xVal, poly);
    printf("err   [");
    for(i = 0; i < GRADE; i++)
        printf("%.4f, ", err[i]);
    printf("\b\b]\n");

    free(poly);
    free(err);

    return 0;
}

Consider passing in the array size rather than fixing it at 6 in the polynomial(), nodeSuccession() functions.

// polynomial(xVal, xNode, yNode)
polynomial(6, xVal, xNode, yNode)

Minor stuff

Two backspaces may not truly "back-space".  Less problematic to not print unwanted text.  Various solutions. Perhaps as below.

const char *separator = "";
printf("xNode [");
for (i = 0; i < GRADE + 1; i++) {
  xNode[i] = i;
  printf("%s%.4f", separator, xNode[i]);
  yNode[i] = 0;
  separator = ", ";
}
printf("\n");

The various calls to like code suggest that a helper print function should be written.
For printing double, I find %e more informative than %f.
Rather than allocate to the size of the type, allocate to the size of the de-referenced pointer.  It easier to code correctly, review and maintain.  Putting the sizeof part first insures any integer math is done with at least size_t width.  Checking for a NULL allocation makes for robust code.

// sum = malloc(GRADE * sizeof(double));
sum = malloc(sizeof *sum * GRADE);
if (sum == NULL) TBD();

Use const with the pointers to insure wider application of the function and allow optimizations the compiler may not readily recognize.

// double* polynomial(double *xVal, double *xNode, double *yNode){
double* polynomial(const double *xVal, const double *xNode, const double *yNode){

// double* error(double *xVal, double *sum)
double* error(const double *xVal, const double *sum)

Help convey the double-ness of the variable.

// sum[j] = 0;  // This looks `int`-ish
sum[j] = 0.0;


Simple dishwasher C++ code I have a project in embedded systems and I have to write the code in C, and make it simple.

This is my first time, and it's only a simulation of how it should work.

#include<iostream.h>
#include<stdio.h>

void manualMode();
 void defaultMode();

int temp, timeToWash, operation;

int main() {
     int mode =0, part=3, waterLevel;
     int doorSensor=0, timer = 3,waterLevelSensor = 0, tempSensor = 25;
     char startPause;
     cout<<"Washing Machine CE224"<<endl;
 do{
      cout<<"Choose Mode: (1)Default, (2)Manual \n";
      cin>>mode;
      if (mode == 1)
                 defaultMode();
      if (mode == 2)
                 manualMode();
 }while(mode == 0);

 cout<<"Choose Parts to wash: (1)Upper Only, (2)Lower Only, (3)Upper and Lower \n";
 cin>>part;
 switch(part){
            case 1:
            case 2:
                 waterLevel= 0.5;
                 break;
            case 3:
                 waterLevel = 1;
                 break;
 }
 if (doorSensor == 0){
      do{
                 cout<<"Press (S) to Start,and close the Door."<<endl;
                 cin>>startPause;
                 cout<<"LED is On\n";
                 while(waterLevelSensor != waterLevel){
                             waterLevelSensor++;
                 }
                 while(tempSensor != temp){
                             tempSensor++;
                 }
                 cout<<"Washing Operation Started!               Time Left:"<<timeToWash<<endl;
                 cout<<"Washing with Soap Operation Started!\n";
                 timeToWash = timeToWash / 2 ;
                 cout<<"Rinsing Operation Started!               Time Left:"<<timeToWash<<endl;
                 timeToWash = timeToWash / 2 ;
                 cout<<"Drying Operation Started!               Time Left:"<<timeToWash<<endl;
                 timeToWash = 0 ;
                 startPause = 'P';
      }while((startPause == 's') || (startPause =='S'));
 }
 cout<<"End!\nLED is Off";
 return 0;
}

void manualMode(){
     cout<<"Enter Temperature: \n";
     cin>>temp;
     cout<<"Enter Time to wash: \n";
     cin>>timeToWash;
     cout<<"Choose Operation: (1)Water Only, (2)Water and Soap, (3)Rinse, (4)Dry, (5)All\n";
     cin>>operation;
}
void defaultMode(){
     int whatToWash;
     cout<<"Choose what to Wash: (1)Cups, (2)Plates, (3)Pots";
     cin>>whatToWash;
     switch(whatToWash){
          case 1:
                temp = 30;
                timeToWash = 3;
                break;
          case 2:
                temp = 40;
                timeToWash = 3;
                break;
          case 3:
                temp = 60;
                timeToWash = 3;
                break;
     }
 }

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

Indentation

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

Code organization

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

Variable initialization

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

Control flow

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

Input validation

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


My Google Maps Script v2 My Google Maps Script v1

Using the Google Maps JavaScript API v3.

Does my script have any room for improvement (naming, readability, oop, etc.)?

I'm going to pair it with some live time functionality, so that whenever the map its location changes the time would be updated accordingly.

I've added this script to my HTML code right after the last DOM node it needs to work.

google-maps.js

(function (window, document) {
    'use strict';

    var MAP_DEFAULT_ADDRESS = 'Paris, France',
        MAP_CANVAS_ID = 'map-canvas',
        ADDRESS_INPUT_ID = 'address-input',
        SEARCH_BUTTON_ID = 'search-button';

    var googleMap,
        currentLocation,
        googleGeocoder = new google.maps.Geocoder(),
        addressInput = document.getElementById(ADDRESS_INPUT_ID),
        markers = [];

    googleGeocoder.geocode({ 'address': MAP_DEFAULT_ADDRESS }, function (results, status) {
        if (status !== google.maps.GeocoderStatus.OK) {
            throw new Error('Geocode was unsuccessful: ' + status);
        }

        googleMap = new google.maps.Map(document.getElementById(MAP_CANVAS_ID), {
            // required
            center: results[0].geometry.location,
            zoom: 10,
            // disable direct GUI interaction
            disableDefaultUI: true,
            navigationControl: false,
            mapTypeControl: false,
            scaleControl: false,
            scrollwheel: false,
            draggable: false,
            zoomControl: false,
            disableDoubleClickZoom: true,
            suppressInfoWindows: true
        });

        currentLocation = results[0].geometry.location;

        addressInput.value = results[0].formatted_address;

        addMarker(results[0].geometry.location);
    });

    // center map responsively
    window.addEventListener('resize', function () {
        var center = googleMap.getCenter();

        google.maps.event.trigger(googleMap, 'resize');

        googleMap.setCenter(center);
    });

    addressInput.onkeydown = function (e) {
        if (e.keyCode === 13) {
            addressInput.blur();

            processAddressInput();
        }
    };

    document.getElementById(SEARCH_BUTTON_ID).onclick = function () {
        processAddressInput();
    }

    function addMarker(location) {
        var marker = new google.maps.Marker({
            map: googleMap,
            position: location
        });

        marker.setAnimation(google.maps.Animation.DROP);

        markers.push(marker);

        google.maps.event.addListener(marker, 'click', function () {
            if (marker.getAnimation() !== null) {
                marker.setAnimation(null);
            } else {
                marker.setAnimation(google.maps.Animation.BOUNCE);
            }
        });
    }

    function deleteAllMarkers() {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(null);
        }
    }

    function processAddressInput() {
        googleGeocoder.geocode({ 'address': addressInput.value }, function (results, status) {
            if (status !== google.maps.GeocoderStatus.OK) {
                if (status === google.maps.GeocoderStatus.ZERO_RESULTS) {
                    return;
                }

                throw new Error('Geocode was unsuccessful: ' + status);
            }

            if (results[0].geometry.location.equals(currentLocation)) {
                addressInput.value = results[0].formatted_address;

                return;
            }

            deleteAllMarkers();

            googleMap.fitBounds(results[0].geometry.viewport);
            googleMap.setCenter(results[0].geometry.location);

            currentLocation = results[0].geometry.location;

            addressInput.value = results[0].formatted_address;

            addMarker(results[0].geometry.location);
        });
    }
}(window, document));

This is almost spotless, congratulations.

When processing the results, you refer to results[0] many times.
I would put that in a local variable to clarify, for example firstResult.
(An IDE can give a warning if you mistype firstResult,
but it cannot give a warning if you mistype the array index (for example  results[2]))

You missed a semicolon at the end of this:

document.getElementById(SEARCH_BUTTON_ID).onclick = function () {
    processAddressInput();
}


List all possible numbers from a given array that sums up to a given number I have to solve the following problem: Given an array of integers and given an integer value, list all possible numbers frm the array that sums up to the given value.

Example:

Input: array = {1, 2, 2, 3, 4, 5}, int N = 5
Output: {1, 2, 2}, {1, 4}, {5} {2, 3}.

This is my solution:

import java.util.ArrayList;
public class SubSum {
    static ArrayList<ArrayList<Integer>> res;
    public static void main(String[] args) {
        int arr[] = {1, 2, 2, 3, 4, 5};
        int N = 5;
        solve(arr, N);
        for (int i = 0; i < res.size(); i++) {
            for (int j = 0; j < res.get(i).size(); j++) {
                System.out.print(res.get(i).get(j) + " ");
            }
            System.out.println();
        }
    }

    private static void solve(int[] arr, int n) {
        ArrayList<Integer> curr = new ArrayList<Integer>();
        int tmp = 0;
        int currPostion;
        helper(arr, n, tmp, curr, 0);
    }

    private static void helper(int[] arr, int n,
            int tmp, ArrayList<Integer> curr, int currPosition) {
        while(currPosition < arr.length){
            if(tmp == n){
                res.add(curr);
                int lastIndex = curr.size()-1;
                int lastEl = curr.remove(lastIndex);
                helper(arr, n, tmp-lastEl, curr, currPosition+1);

            }
            else{
                if((arr[currPosition] <= n) && (arr[currPosition] + tmp <= n)){
                    curr.add(arr[currPosition]);
                    helper(arr, n, tmp+arr[currPosition], curr, currPosition+1);
                }
                if((arr[currPosition] <= n) && (arr[currPosition] + tmp > n)){
                    helper(arr, n, tmp, curr, currPosition+1);
                    if(curr.size() >= 1){
                        int lastIndex = curr.size()-1;
                        int lastEl = curr.remove(lastIndex);
                        helper(arr, n, tmp-lastEl, curr, currPosition+1);
                    }
                }
            }
        }
    }
}

I couldn't come up with something faster than exhaustive search. Is this the best possible approach? Also any comments about the code are welcome. I don't like it much, since it looks more like functional programming than object oriented, but I don't know how to improve in this direction.

I think the cleanest solution is to first make one pass through the list, storing the numbers in a data structure.  Then use the data structure to perform the calculation.

Data Structure

You want to know how many times you've seen a particular number.

Because the input numbers repeat you can't use a java.util.Set or java.util.BitSet.

The simplest solution is to use a java.util.Map (like java.util.HashMap) where the key is the number and the value is how many times you've seen it.

It doesn't really matter what data structure you use, as long as you can easily look up whether a number has been seen or not.  (Finding that information in the original array is slow!)

Example

Input = {1, 4, 4, 3}, N=5

Process input 1
store (1->1) in the map.

Process input 4
store (4->1) in the map.

Process input 4
Kick out the old value (4->1), and replace it with (4->2).

Process input 3
Store (3->1) in the map.

Final result: ((1->1), (3->1), (4->2))
The pattern is: you retrieve the old value and if it's not null you add one to it.

Search for Solutions

The cleanest solution is to write something recursive.
One input is your data structure (see above), which tells you what numbers are available.
The other input is what your total number is.

Initial Conditions

Input = {1, 2, 2, 3, 4, 5}, N=5
Data structure = (1->1, 2->2, 3->1, 4->1, 5->1)
This means that 1,3,4,5 have been seen once, and 2 has been seen twice.

Start the search

Data structure = ((1->1), (2->2), (3->1), (4->1), (5->1)), N=5

Case 1: Find 5's

Five has been seen, so it's a valid solution.  Print out 5 and you're done.

Case 2: Find 4's

There is still a four remaining.
Add a four to an internal list.
Make a copy of the data structure. (*)
Decrement the number of 4s from your data structure.
Recursively search for things that add up to 1.  (5-4=1).

Case 3: Find 3's

There is still a three remaining.
Add a three to an internal list.
Make a copy of the data structure. (*)
Decrement the number of 3s from your data structure.
Recursively search for things that add up to 2. (5-3=2)

Case 3: Find 2's

(Same pattern as above.)

Case 4: Find 1's

(Same pattern as above.)

Print the results

When you get to the bottom of your recursion, print the current number plus all the previous numbers.

(*) There's a more efficient way of doing this that doesn't involve making a copy: modify the data structure, make the recursive call, then reset the data structure.  This technique is easy to get wrong, and it's a good place to cut corners unless you really have the time to polish your code.

Functional vs. Object-Oriented Programming

I don't see anything wrong with using functional programming for this assignment.  There's no reason why you need to create multiple classes, and it's only meaningful to talk about object-oriented programming when there is more than one class.

If you want to, you could create multiple classes with clearly defined responsibilities.  One could hold the data, one could perform the search, and a third could supply the initial conditions.


Handling optimistic concurrency violations I'm trying to establish a concurrency violation verification in my SQL updates using C# and raw SQL.

What I'm doing now is storing the TimeStamp value in a byte[] upon selection and before updating I'm checking if the stored value is equal to the current value. here's the code:

static void update()
{
    using (SqlConnection connection = new SqlConnection(""))
    {
        try
        {
            //open connection
            connection.Open();

            //select row for update - for testing purposes it's in the same block
            SqlCommand select = connection.CreateCommand();
            select.CommandText = "SELECT timeStamp FROM Person WHERE ID = 1";
            //store the time stamp in a byte[]
            byte[] ts = (byte[])select.ExecuteScalar();

            //check if the time stamp hasn't changed
            if (ByteArraysEqual(ts, (byte[])select.ExecuteScalar()))
            {
                //Update
                SqlCommand command = connection.CreateCommand();
                command.CommandText = "Update Person SET Age=1111 WHERE ID = 1";
                command.ExecuteNonQuery();
            }
            else
            {
                //cocurrency violation occured
                Console.WriteLine("concurrency error!");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Update error:\n" + ex.Message);
        }
        finally
        {
            connection.Close();
        }
    }
}
static bool ByteArraysEqual(byte[] b1, byte[] b2)
{
    if (b1 == b2) return true;
    if (b1 == null || b2 == null) return false;
    if (b1.Length != b2.Length) return false;
    for (int i = 0; i < b1.Length; i++)
    {
        if (b1[i] != b2[i]) return false;
    }
    return true;
}

I wonder if this is the right approach to verify the Person has not been updated by another user between the selection and the actual update?

What optimistic concurrency usually does is update the row specifying the old value in the where clause:

var command = connection.CreateCommand();
command.CommandText = "Update Person SET Age = @age timeStamp = @newTimeStamp WHERE ID = @id AND timeStamp = @originalTimeStamp";
command.Parameters.Add("@age", 1111);
command.Parameters.Add("@newTimeStamp", DateTime.Now);
command.Parameters.Add("@id", 1);
command.Parameters.Add("@originalTimeStamp", originalTimeStamp);
int affected = command.ExecuteNonQuery();

if (affected == 0)
{
    throw new OptimisticConcurrencyException("Data was changed by someone else, please refresh and try again");
}

Also, please use parameters for your SQL queries!


Is there better way of writing these IF checks? This is what I have, But I think I can write it in a sohrter and more efficient way too, what do you suggest?

    string actionString= string.Empty;

    if (auditAction == DSRHelper.SaveStatusEnum.Save)
    {
        actionString = Properties.Resources.SAVE_ACTION_MESSAGE;
    }

    if (auditAction == DSRHelper.SaveStatusEnum.Complete && model.Dirty)
    {
        actionString = "Save'NComplete";
    }
    else if(auditAction == DSRHelper.SaveStatusEnum.Complete)
    {
        actionString = "OnlyComplete.";
    }

EDIT: Ok I changed it a little bit, better now?

    string actionString= string.Empty;

    if (auditAction == DSRHelper.SaveStatusEnum.Save)
    {
        actionString = Properties.Resources.SAVE_ACTION_MESSAGE;
    }
    else if (auditAction == DSRHelper.SaveStatusEnum.Complete )
    {
        if (model.Dirty)
        {
            actionString = "Save'NComplete";
        }
        else
        {
            actionString = "OnlyComplete";
        }
    }

Maybe a switch?  Although whether it's shorter or more efficient or even easier to read up for debate.

string actionString = GetStatusMessage(auditAction);

// ...
function GetStatusMessage(DSRHelper.SaveStatusEnum status)
{
   switch(status)
   {
      case DSRHelper.SaveStatusEnum.Save:
           return Properties.Resources.SAVE_ACTION_MESSAGE;
      case DSRHelper.SaveStatusEnum.Complete:
           return model.Dirty ? "Save'NComplete" : "OnlyComplete.";
      default:
           return string.Empty;
   }
}


Function to parse a Javascript object and return a CSV This function converts a Javascript Object into a CSV.

var dataFromAPI = [{"name":"first"},{"name":"sec,ond"},{"name":"third 'jibberish"},{"name":"fourth, jibberish"}]

function convertToCSVandDownload(objArray) {
    var csvOutput = "";
    Object.keys(objArray).forEach(function(key) {
      if (csvOutput.length == 0) {
        csvOutput = "Index,Field Value\n";
        csvOutput = csvOutput + JSON.stringify(key) + "," + JSON.stringify(objArray[key]["name"]) + "\n";
      } else {
        csvOutput = csvOutput + JSON.stringify(key) + "," + JSON.stringify(objArray[key]["name"]) + "\n";
      }
    })
    return csvOutput;
}

console.log(convertToCSVandDownload(dataFromAPI));

Description

It would appear that your current solution is a bit complicated. Using JSON.parse just to ensure that you escape , is overkill.

The overall solution can be drastically simplified as you will see in this post.

const before let and let before var

All variables should be declared by default with const. If a variable is going to be mutated then use let. Don't use var unless that is what you intended.

/// bad
var dataFromAPI = ...

/// good
const dataFromAPI = ...

note: pushing an element to a list will only mutate the array and not the variable, thus no error

Work with arrays and not with strings.

/// bad
csvOutput = "Index,Field Value\n";

/// good
const csvOutput = [
  ["Index", "Field", "Value"]
];

Function names should describe what they do.

The convertToCSVandDownload method only converts to CSV but doesn't download. Change the name to convertToCSV

Working Solution

Use Array#reduce, destructuring assignment, Array#map, Array#join and spread syntax

const dataFromAPI = [{"name":"first"},{"name":"sec,ond"},{"name":"third 'jibberish"},{"name":"fourth, jibberish"}]

function convertToCSV(data, headers) {
  return data
  .reduce((a,{name},i)=>[...a, [i, `"${name}"`]], [headers])
  .map(row=>row.join(","))
  .join("\n");
}

const res = convertToCSV(dataFromAPI, ["Index", "Field Value"]);

console.log(res)


File of words to a linked-list of words I'd like to get a review for the function build_list() which reads a file containing words (separated by spaces) and returns a linked-list of words:

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

typedef struct ListNode {
    char* word;
    struct ListNode *next;
} ListNode;

typedef struct List {
    ListNode *head;
    ListNode *tail;
} List;

List* build_list(char* fileName)
{
    FILE* file = fopen(fileName, "r");
    assert(file != NULL);

    List* list = malloc(sizeof(List));
    assert(list != NULL);
    list->head = NULL;
    list->tail = NULL;

    char c;
    int word_size = 1;
    char* word = malloc(word_size);
    int word_count = 0;

    while ((c = fgetc(file)) != EOF)
    {
        assert(!ferror(file));

        while (c != ' ' && c != EOF)
        {
            if (word_count == word_size)
            {
                word_size += 1;
                word = realloc(word, word_size);
                assert(word != NULL);
            }

            word[word_count++] = c;

            c = fgetc(file);
            assert(!ferror(file));
        }

        word = realloc(word, word_size + 1);
        word[word_size] = '\0';

        ListNode *node = malloc(sizeof(ListNode));
        assert(node != NULL);
        node->next = NULL;
        node->word = word;

        if (list->head == NULL)
        {
            list->head = node;
            list->tail = node;
        }
        else
        {
            list->tail->next = node;
            list->tail = node;
        }

        if (c == EOF)
            break;

        word_count = 0;
        word_size = 1;
        word = malloc(word_size);

    }

    free(word);

    assert(!ferror(file));

    return list;
}

assert() isn't meant for runtime errors like an invalid filename. It's meant to aid in debugging by catching logical errors. Essentially, it says, "There should be no possible way this statement can be false. If it is false, something about this program is invalid, so I need to blow up."

A good use of assert() here would be:

List* build_list(char* fileName)
{
    assert(fileName && fileName[0]);
    // Alternately (more verbose, but maybe more clear):
    assert(fileName != NULL && fileName[0] != '\0');
    // Another alternative, which gives a helpful message
    // if it fails
    assert(fileName && fileName[0]
        && "build_list(char* fileName) was given a null or empty fileName");

This way, if you write a function somewhere else that passes a null filename into build_list, you'll get notified of the programming error.

A runtime error such as a missing file is better handled by returning some kind of error. You could return NULL on error, or you could take a List* (or List**) as an argument and return an integer result (0 for success is typical).


How can i simplify the following If code? I have the following code in JS (using last ES2020), the current code check if the type is 'asporto' or 'takeaway' and adding to current date hours from a setup fo type 'takeaway' or 'asporto' and if another setup called limiteOreTakeaway/Asporto is !== '00:00:00' I have to check if the current time is greater than the limiteOreTakeaway/Asporto, so I'm splitting the string limiteOreTakeaway/Asporto to Hours and Minutes and making my checks if the current date is > that limiteOreTakeaway/Asporto I'm adding to curDate the hours from setup + 24hours.
My code looks like this:
const curDate = new Date();
    if (this.carrello.tipo === 'asporto') {
      if (this.negozioSetup.limiteOreAsporto !== '00:00:00') {
        // controllo se l'orario limite è impostato (orariolimite != 00:00)
        const ore = parseInt(
          this.negozioSetup.limiteOreAsporto.split(':')[0],
          10
        );
        const minuti = parseInt(
          this.negozioSetup.limiteOreAsporto.split(':')[1],
          10
        );
        // controllo se l'ora di adesso ha superato l'orario limite
        if (curDate.getHours() > ore) {
          curDate.setHours(
            curDate.getHours() + this.negozioSetup.oreMinimeAsporto + 24
          );
         // se l'ora corrente è uguale controllo se i minuti limite hanno superato il limite
        }else if (curDate.getHours() === ore && curDate.getMinutes() > minuti) {
            // se l'orario corrente è maggiore di quello limite aggiungo 24 ore alla data corrente
            curDate.setHours(
              curDate.getHours() + this.negozioSetup.oreMinimeAsporto + 24
            );
        }
      } else {
        // orario limite disabilitato proseguo con l'aggiunta delle ore minime tra gli ordini
        curDate.setHours(
          curDate.getHours() + this.negozioSetup.oreMinimeAsporto
        );
      }
    } else if (this.carrello.tipo === 'takeaway') {
      if (this.negozioSetup.limiteOreTakeaway !== '00:00:00') {
        const ore = parseInt(
          this.negozioSetup.limiteOreTakeaway.split(':')[0],
          10
        );
        const minuti = parseInt(
          this.negozioSetup.limiteOreTakeaway.split(':')[1],
          10
        );
        if (curDate.getHours() > ore) {
          curDate.setHours(
            curDate.getHours() + this.negozioSetup.oreMinimeTakeaway + 24
          );
        }else if (curDate.getHours() === ore && curDate.getMinutes() > minuti) {
          curDate.setHours(
            curDate.getHours() + this.negozioSetup.oreMinimeTakeaway + 24
          );
        }
      } else {
        curDate.setHours(
          curDate.getHours() + this.negozioSetup.oreMinimeTakeaway
        );
      }
    }

I would like to simplify it. If it's possible, optimize it by using the last ES2020 available tools.

Use functions instead of repeating yourself The only difference between the tipo === 'asporto' branch and the tipo === 'takeaway' branch is the property name that gets passed into setHours: either .oreMinimeAsporto or .oreMinimeTakeaway. Create a function that takes that value as a parameter, then call it with either .oreMinimeAsporto or .oreMinimeTakeaway instead. That will about halve the size of your code.
const curDate = new Date();
const { tipo } = this.carrello;
if (tipo === 'asporto' || tipo === 'takeaway') {
    const casedProp = tipo[0].toUpperCase() + tipo.slice(1);
    changeDate(
        currDate,
        this.negozioSetup['oreMinime' + casedProp],
        this.negozioSetup['limiteOre' + casedProp],
    );
}

Split only once and destructure to grab the ore and minti values at once. You can also use Number instead of parseInt(str, 10), and use .map to apply the transformation to both elements at once:
const [ore, minuti] = this.negozioSetup.limiteOreAsporto.split(':').map(Number);

Call functions once rather than multiple times when possible - you don't need to call getHours every time, better to call it once and store the result in a variable.
const currHours = curDate.getHours();
const currHoursWithOffset = currHours + oreMinime;

Return early to avoid indentation hell - reading lots of {} blocks can make code more confusing to read than it needs to be. In the case of 00:00:00, consider running the one line that's needed and then returning, rather than having a large if/else.
The branches of currHours > ore and curDate.getHours() === ore && curDate.getMinutes() > minuti also contain the same logic inside the branches, so combine them into one if statement:
const changeDate = (date, oreMinime, limiteOre) => {
    const currHours = curDate.getHours();
    const currHoursWithOffset = currHours + oreMinime;
    if (limiteOre === '00:00:00') {
        curDate.setHours(currHoursWithOffset);
        return;
    }
    const [ore, minuti] = limiteOre.split(':').map(Number);
    if (currHours > ore || currHours === ore && curDate.getMinutes() > minuti) {
        curDate.setHours(
            currHours + oreMinime + 24
        );
    }
};
const curDate = new Date();
const { tipo } = this.carrello;
if (tipo === 'asporto' || tipo === 'takeaway') {
    const casedProp = tipo.slice(1).toUpperCase() + tipo.slice(1);
    changeDate(currDate, this.negozioSetup['oreMinime' + casedProp]);
}

You could put the values into variables first if you think the combined statement is difficult to read (I'll leave that to you, I don't understand the language) - eg
const cond1 = currHours > ore;
const cond2 = currHours === ore && curDate.getMinutes() > minuti;
if (cond1 || cond2) {
  // ...
}

Alternative to multiple separate properties On a broader scale, having to hard-code the correlation between this.carrello.tipo and the this.negozioSetup.oreMinime- property is a bit odd. If possible, consider rearranging your data so that the two oreMinime and limiteOre values are in an object instead of being two separate properties. Then you just need to use bracket notation to look up the value on the object:
ore: {
  asporto: { minime: <value>, takeaway: <value> },
  takeaway: { minime: <value>, takeaway: <value> },
}

Then you can:
changeDate(currDate, this.negozioSetup.ore[tipo]);

and change changeDate's parameters as needed.