Formatting and writing data I'm primarily looking for ways to increase the performance of my code.

It is used to transform mesh data from blender into a format I can use and then save it to a file.

First it collects the colors of each vertex with an index to reference them, then for each of the vertices it writes its coordinates followed by its average color. The last part decides if each polygon is a triangle or a rectangle and writes the indices of each of its vertices, while converting rectangles to 2 triangles.

import bpy
mesh = "mesh"
filepath = "filepath"
out = open(filepath, 'w')
m = bpy.data.meshes[mesh]
colData = m.vertex_colors["Col"].data
colors = []
index = []
for pol in m.polygons:
    count = 0
    for li in pol.loop_indices:
        for rgb in colData[li].color:
            colors += [rgb]
        index += [pol.vertices[count]]
        count += 1
for ver in m.vertices:
    indices = [i for i, x in enumerate(index) if x == ver.index]
    for f in ver.co:
        out.write(str(f)+' ')
    for f in range(3):
        c = 0
        for i in indices:
            c += colors[i*3+f]
        c = c/len(indices)
        out.write(str(c)+' ')
    out.write('\n')
out.write('\n')
for pol in m.polygons:
    if len(pol.vertices)==3:
        for i in pol.vertices:
            out.write(str(i)+' ')
    else:
        for i in pol.vertices[:3]:
            out.write(str(i)+' ')
        for i in pol.vertices[2:]:
            out.write(str(i)+' ')
        out.write(str(pol.vertices[0])+' ')
    out.write('\n')
out.write('\n')
out.close()

You could try to replace some loops with string formatting, for example change this

for i in pol.vertices[:3]:
    out.write(str(i)+' ')
for i in pol.vertices[2:]:
    out.write(str(i)+' ')
out.write(str(pol.vertices[0])+' ')

to this

out.write('{0} {1} {2} {2} {3} {0} '.format(*pol.vertices))


Check if select has a certain option I suspect there is a simpler way to find if a select has a certain option, but don't know what. The objective of the following is to check if the desired option exists or not, and if it does, set it as the selected option:

Markup

<input type="text" size="2" id="selectVal"/>
<button onclick="setSelect()">Set the select</button>
<select id="mySelect">
    <option value="0">Select an option</option>
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
</select>

JS

function setSelect() {
    var desiredOption = $("#selectVal").val();
    if (desiredOption == '') {
        $("#selectVal").focus();
        return false;
    }
    var hasOption = $('#mySelect option[value="' + desiredOption + '"]');
    if (hasOption.length == 0) {
        alert('No such option');
    } else {
        $('#mySelect').val(desiredOption);
    }
    $("#selectVal").select();
}

To be clear, I wonder if a single method could do the job of the following two lines:

var hasOption = $('#mySelect option[value="' + desiredOption + '"]');
if (hasOption.length == 0)

Any suggestions?

jsfiddle here.

You could try and force the option to be selected.  Because jQuery doesn't throw errors when it doesn't have a set of elements, you can use this to your advantage inside an if statement. Couple this with jQuery's chaining and you can do something like:

function setSelect() {
    var desiredOption = $("#selectVal").val();
    if (desiredOption == '') {
        $("#selectVal").focus();
        return false;
    }
    if (!$('#mySelect option[value="' +desiredOption+ '"]').prop("selected", true).length) {
        alert('No such option');
    }
    $("#selectVal").select();
}

  Updated fiddle: http://jsfiddle.net/SPvrA/7/


Laravel 4 search function I am using this code in my controller and would like to know if this is good code to use or if I can write it better, or more compact, and so on. I am just trying to learn from this. It does work, so that is not my question.

public function search()
{
    $search     = Input::get('search');
    $result     = Categories::where('name', 'LIKE', '%'. $search .'%')->get();

    if ($result->first()) {

        $categories     = Categories::where('name', 'LIKE', '%'. $search .'%')->Paginate(Auth::user()->categories);

        Session::flash('alertMessage', 'The below results are filtered due to a search action!');

        return View::make('categories.index', compact('categories'));
    }
    else {

        $categories = Categories::orderBy('name', 'asc')->Paginate(Auth::user()->categories);

        Session::flash('alertMessage', 'Your search has returned 0 results from the database.');

        return View::make('categories.index', compact('categories'));
    }
}

Here are few things I'd do to improve your code:

I would compact your first if statement into something such as if (Categories::where('name', 'LIKE', '%'. $search .'%')->first()) { since you only use $result for that purpose.
Remove that unnecessary horizontal space after your first assignment to $categories.
I hope that your flash messages are only for development purposes. They aren't very useful or user friendly as they are right now. Look at studied websites (Amazon, StackExchange, etc.) and UX.SE for tips on how to improve the user experience of your search function.
Be careful using the compact function. It's easy to lose track of it and forget to update it or your variables and therefore have something throw an error later on.
Fix the format of your else. Pick-and-choose either

} else {

or

}
else
{

Most search functions don't return anything when nothing was found. Again, this an issue to bring up at UX.SE, but your user might find themselves thinking that the results from your else clause are actually what they're looking for.

Overall, very nice. I'm sure you've done this, if not though, read through what you find from a search like this just to see how others have solved this problem. You'll find out good ways and bad ways of doing what you've done.


HangPerson in Haskell I created a HangPerson game in Haskell and I must admit it feels very imperative. How can I make it more "functional?" Are there more elegant ways of breaking up the task? The getUserLines function seems to be doing a lot of work. Any additional feedback on efficiency or anything of the sort is also appreciated.

import Control.Monad.State
import System.Random
import Data.List
import System.Process
import Data.Char

type GameValue = String
type GameState = (Int, String)

playGame :: String -> String -> State GameState GameValue
playGame [] word = do
    (_, guessed) <- get
    return guessed

playGame (x:xs) word = do
    (missed, guessed) <- get
    put $ check missed x word guessed
    playGame xs word

check n c word guessed
    | not $ isAlpha c || c `elem` guessed = (n, guessed)
    | c `elem` word    = (n, c:guessed)
    | otherwise        = (n + 1, c:guessed)

replace word guess = map replace' word
    where replace' char = if char `elem` guess then char else '_'

gallows n = "\n\n       |||========|||\n" ++
            (if n > 0 then "       |||         |\n" else "       |||          \n") ++
            (if n > 1 then "       |||         O\n" else "       |||          \n") ++
            (if n < 2 then "       |||           \n" else (helper1 n)) ++
            (if n < 5 then "       |||           \n" else (helper2 n)) ++
            "       |||\n" ++ "       |||\n" ++ "     =================\n\n"

helper1 n
    | n <= 3    = "       |||        /  \n"
    | n <= 4    = "       |||        /| \n"
    | otherwise = "       |||        /|\\\n"

helper2 6 = "       |||        / \\\n"
helper2 _ = "       |||        /  \n"

safeHead []     = ' '
safeHead (x:xs) = x

menu = "\x1B[32m\t\t\t\tWelcome to Hangperson.\nThe rules are the same as always except\n\nIf you enter multiple characters only the first will be read.\nPress Ctrl+D to Give up.\nHave fun\x1B[0m"

getUserLines :: String -> IO String
getUserLines word = go (0, "")
      where go contents = do
            system "clear"
            putStrLn menu
            let misses = fst contents
            let guessed = snd contents
            putStrLn $ gallows misses
            putStrLn $ "You've missed " ++ (show $ misses) ++ " out of 7"
            putStrLn $ "You've guessed: " ++ "\x1B[31m" ++ guessed ++ "\x1B[0m"
            putStrLn $ intersperse ' ' $ replace word guessed
            putStrLn "Guess a letter: "
            line <- getLine
            let guess = [safeHead line]
            let result = execState (playGame guess word) contents
            if (((fst result) == 7) || '_' `notElem` (replace word ((snd result))))
            then (if (fst result) < 7 then return ("You won! The word was " ++ word) else return ("You lost! The word was " ++ word))
            else go result

main = do
    system "reset"
    s <- readFile "/usr/share/dict/words"
    num <- randomIO :: IO Int
    let word = (lines s) !! (num `mod` 230000) --(length $ lines s)) efficient way?
    gameResult <- getUserLines (map toLower word)
    putStrLn gameResult
    putStrLn "Play again? :"
    option <- getLine
    if option == "y" then main else return ()

While your code might be working and written in a functional language, it also feels very procedural to me. Most idiomatic Haskell code I see has a very high signal to noise ratio. In your code I have to read every single line and figure out what it does in my head.

You can achieve this by making a lot of tiny functions (after all, composition is key for a functional program), and use as much of the domain language as possible. These tiny functions don't need to stand on their own; using let x=... in ... or where x= tends to help a lot.

Also, try to figure out what state you need to keep, and name it. I see a lot of functional programmers design their apps types-first. Having an explicit model that doesn't allow faulty state tends to help big-time.

Make sure you don't add state you can calculate from other state, use functions for that, otherwise your data structure might get inconsistent.

AFAIK tuples should mostly be used inside functions, but never exposed, except maybe for the most trivial cases like key-value pairs, and even that is debatable... After all, how much work is it to define data KeyValuePair a b= KeyValuePair a b

I am by no means an expert in Haskell, and learned these rules from doing mostly object-oriented programming. However, in a functional language these rules tend to be way easier to implement.

About operator shortcuts etc: I don't use them a lot - yet -, unless the Haskell linter suggests me to use it.

I do think that using a tool like ghc-mod and hlint is a necessity for Haskell development.

TL;DR: use proper types, extract parts into smaller functions, and try to properly name them.

import           Control.Monad (when)
import           Data.Char     (toLower)
import           Data.List     (transpose)
import           System.Random (randomIO)

wordsPath :: FilePath
wordsPath = "words.txt"-- "/usr/share/dict/words"

data GameState = GameState
    { _wordToGuess :: String
    , guesses     :: String
    }

data GameStatus = Guessing | GameWon | GameLost deriving Eq

hangmanImages :: [[String]]
hangmanImages =
    transpose
    [ [ "   ", " O ", " O ", " O ", " O " , "_O " , "_O_"  ]
    , [ "   ", "   ", " | ", " | ", " | " , " | " , " | "  ]
    , [ "   ", "   ", "   ", "/  ", "/ \\", "/ \\", "/ \\" ]
    ]

fullHangmanImage :: Int -> [String]
fullHangmanImage index =
    "=========" :
    "|    |" :
    map ("|   " ++) img
    where img = hangmanImages !! index

maxWrongGuesses :: Int
maxWrongGuesses = length hangmanImages - 1

numberOfWrongGuesses :: GameState -> Int
numberOfWrongGuesses (GameState word' guesses') =
    length $ filter charNotInWord guesses'
    where charNotInWord c = c `notElem` word'

gameStatus :: GameState -> GameStatus
gameStatus (GameState word' guesses')
    | isGuessed     = GameWon
    | isLastGuess'  = GameLost
    | otherwise     = Guessing
    where
        isGuessed = all isCharInGuesses word'
        isCharInGuesses x = x `elem` guesses'
        gameState = GameState word' guesses'
        isLastGuess' = numberOfWrongGuesses gameState == maxWrongGuesses

-- for one reason or another getChar also appends <CR>
-- so I implemented my own getChar and made sure empty input is refused
getAChar :: IO Char
getAChar = do
    line <- getLine
    case line of
        [] -> getAChar
        (c:_) -> return c

getANewChar :: GameState -> IO Char
getANewChar gameState = do
    putStrLn "Next char to guess"
    c <- getAChar
    if c `elem` guesses gameState
    then do
        putStrLn "Character already used in guesses."
        getANewChar gameState
    else
        return c

displayState :: GameState -> IO ()
displayState (GameState word' guesses')  =
    putStrLn $ unlines $ case gameStatus gameState of
        Guessing -> fullHangmanImage' ++
            [ "Word to guess: " ++ wordWithGuesses
            , ""
            , "Guesses: " ++ guesses'
            ]
        GameWon -> fullHangmanImage' ++
            [ "CONGRATULATIONS!"
            , "You correctly guessed the word " ++ word'
            , " in " ++ show (length guesses') ++ " tries "
            ]
        GameLost -> fullHangmanImage' ++
            [ "YOU FAILED!"
            , "You failed to guess the word " ++ word'
            ]
    where
        gameState = GameState word' guesses'
        fullHangmanImage' = fullHangmanImage currentHangmanIndex
        currentHangmanIndex = numberOfWrongGuesses gameState
        wordWithGuesses = blankOrChar <$> word'
        blankOrChar c
            | c `elem` guesses' = c
            | otherwise = '_'

gameLoop :: GameState -> IO ()
gameLoop gameState = do
    displayState gameState
    when (gameStatus gameState == Guessing) $ do
        c <- getANewChar gameState
        gameLoop $ gameState { guesses = guesses gameState ++ [c] }

newGame :: IO GameState
newGame = do
    contents <- readFile wordsPath
    let words' = filter validWord $ lines contents
    let wordcount = length words'
    randomNumber <- randomIO
    let randomWord = words' !! (randomNumber `mod` wordcount)
    return $ GameState randomWord []
    where
        validWord word =
            '\'' `notElem` word &&
            map toLower word == word

main :: IO ()
main = do
    newGame >>= gameLoop
    putStrLn "Play again? (y/n):"
    option <- getAChar
    when (option == 'y') main


Testing whether sums of cubes are Fibonacci numbers I'm trying to iterate through all the combinations of pairs of positive long integers in Java and testing the sum of their cubes to discover if it's a Fibonacci number. I'm currently doing this by using the value of the outer loop variable as the inner loop's upper limit, with the effect being that the outer loop runs a little slower each time. Initially it appeared to run very quickly--I was up to 10 digits within minutes. But now after 2 full days of continuous execution, I'm only somewhere in the middle range of 15 digits. At this rate it may end up taking a whole year just to finish running this program.

import java.lang.*;
import java.math.*;

public class FindFib
{
 public static void main(String args[])
 {
  long uLimit=9223372036854775807L;   //long maximum value
  BigDecimal PHI=new BigDecimal(1D+Math.sqrt(5D)/2D);  //Golden Ratio

  for(long a=1;a<=uLimit;a++)    //Outer Loop, 1 to maximum
   for(long b=1;b<=a;b++)     //Inner Loop, 1 to current outer
   {
    //Cube the numbers and add
    BigDecimal c=BigDecimal.valueOf(a).pow(3).add(BigDecimal.valueOf(b).pow(3));
    System.out.print(c+" ");  //Output result
    //Upper and lower limits of interval for Mobius test: [c*PHI-1/c,c*PHI+1/c]
    BigDecimal d=c.multiply(PHI).subtract(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP)),
     e=c.multiply(PHI).add(BigDecimal.ONE.divide(c,BigDecimal.ROUND_HALF_UP));
    //Mobius test: if integer in interval (floor values unequal) Fibonacci number!
    if (d.toBigInteger().compareTo(e.toBigInteger())!=0)
     System.out.println();    //Line feed
    else
      System.out.print("\r");    //Carriage return instead
   }
  //Display final message
  System.out.println("\rDone.                                                                                ");
 }
}

Now the use of BigDecimal and BigInteger was deliberate; I need them to get the necessary precision. Is there anything other than my variable types that I could change to gain better efficiency?

You could change the order of your loops.

Loop over the Fibonacci numbers - there is only O(log N) of these less than N.

Then loop down from to cbrt(N) to cbrt(N/2) looking for the highest of the two cubes in its sum.


Checking if a CDN file is available I have the following code working on a WordPress plugin. But there's no WP issue, the matter is:
can I trust @get_headers to perform most of times?

public function enqueue()
{
    $http = is_ssl() ? 'https:' : 'http:';
    $url = "$http//netdna.bootstrapcdn.com/font-awesome/3.2.0/css/font-awesome.min.csss";
    if( $this->get_http_response_code( $url ) ) {
        my_load_external_script();
    }
    else {
        my_load_local_script();
    }
}

/**
 * Problem with getting header, return false
 *
 * otherwise return if headers are 200 or not
 *
 * @param  $url     string
 * @return boolean
 */
private function get_http_response_code( $url )
{
    $headers = @get_headers( $url );
    if( !$headers )
        return false;

    return substr( $headers[0], 9, 3 ) === '200';
 }

The current requirement for running WordPress is PHP 5.2.4 or greater. As I understand it, there's no 100% guarantee, but for having a plugin running in the wild I'd prefer the less problematic path. I've checked the following Stack Overflow Q&A's, but haven't come to any conclusion:

get_headers is throwing a warning instead of just returning false?
Can I try/catch a warning?

In my experience no, using curl is much better an reliable. I use the following code in one of my projects, this always works (and allows redirects, if you don't want to set CURLOPT_MAXREDIRS to 0).

<?php

/**
 * Check if the URL is reachable.
 *
 * @param string $url
 *   The URL to check.
 * @return this
 * @throws \LogicException
 */
public function checkReachability($url) {
  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_AUTOREFERER    => true,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_ENCODING       => "",
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_MAXREDIRS      => 1,
    CURLOPT_NOBODY         => true,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT        => 5,
    // It's very important to let other webmasters know who's probing their servers.
    CURLOPT_USERAGENT      => "Mozilla/5.0 (compatible; StackOverflow/0.0.1; +https://codereview.stackexchange.com/)",
  ]);
  curl_exec($ch);
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  if ($code !== 200) {
    throw new LogicException("The URL doesn’t exists (more specifically isn’t reachable).");
  }
  return $this;
}

?>

Of course you have the problem that you don't always have curl available, a fallback would be.

<?php

// PHP 5.3+
stream_context_set_default(array("http" => array(
  "method"     => "HEAD",
  "user_agent" => "Mozilla/5.0 (compatible; StackOverflow/0.0.1; +https://codereview.stackexchange.com/)",
)));

set_error_handler(function ($errno, $errstr, $errfile, $errline ) {
  throw new LogicException("The URL doesn’t exists (more specifically isn’t reachable).");
});
$headers = get_headers($url);
restore_error_handler();

// String comparisons should be made with ==
if (!isset($headers[0]) || substr($headers[0], 9, 3) != "200") {
  throw new LogicException("The URL doesn’t exists (more specifically isn’t reachable).");
}

?>


Disjoint set in Haskell I think my error-handling here is atrocious, but I'm really new to Haskell so hoping one of you sages can help me out. This program is a command-line tool which you use by typing one of two commands: "Add  " or "Check  ". When you Add a pair of ints, it makes them connected, and when you Check two ints, it tells you whether they are connected (directly or indirectly). This uses the Union find data structure.

import Data.Map (Map)
import qualified Data.Map as Map
import qualified Text.Read as Read

data DisjointSet k = DisjointSet
  { parent :: Map k k
  , rank :: Map k Int
  }

empty :: (Ord k) => DisjointSet k
empty = DisjointSet {parent = Map.empty, rank = Map.empty}

make :: Ord k => k -> DisjointSet k -> DisjointSet k
make k d
  | (Map.member k (parent d)) = d
  | otherwise =
    d {parent = Map.insert k k (parent d), rank = Map.insert k 0 (rank d)}

find :: Ord k => k -> DisjointSet k -> Maybe (k, DisjointSet k)
find k d = do
  k' <- (Map.lookup k (parent d))
  if (k' == k)
    then return (k, d)
    else do
      (k'', d') <- find k' d
      return (k'', d' {parent = Map.insert k k'' (parent d')})

merge :: Ord k => k -> k -> DisjointSet k -> Maybe (DisjointSet k)
merge k1 k2 d =
  let d' = (make k1 (make k2 d))
  in do (k1', d'') <- find k1 d'
        (k2', d''') <- find k2 d''
        r1 <- Map.lookup k1' (rank d''')
        r2 <- Map.lookup k2' (rank d''')
        case compare r1 r2 of
          LT -> return d''' {parent = Map.insert k1' k2' (parent d''')}
          GT -> return d''' {parent = Map.insert k2' k1' (parent d''')}
          EQ ->
            return
              d'''
              { parent = Map.insert k1' k2' (parent d''')
              , rank = Map.insert k2' (r2 + 1) (rank d''')
              }

data Action
  = Add Int
        Int
  | Check Int
          Int
  deriving (Show, Read)

main :: IO ()
main = repl empty

repl :: DisjointSet Int -> IO ()
repl d = do
  line <- getLine
  case (Read.readMaybe line) of
    Just action ->
      case action of
        Add k1 k2 ->
          case (merge k1 k2 d) of
            Just d' -> repl d'
        Check k1 k2 ->
          case (find k1 d) of
            Just (k1', d') ->
              case (find k2 d') of
                Just (k2', d'') -> do
                  if (k1' == k2')
                    then putStrLn "Together"
                    else putStrLn "Apart"
                  repl d''

How do I clean up my code?

Naming

While it's usually not a big deal to have names like d and d' flying around, seeing d''' made me wonder: is there no better name for that?

Indentation

data Action
  = Add Int
        Int
  | Check Int
          Int
  deriving (Show, Read)

That seems.. unusal. Why is the second Int on a new line? Nice of you to seperate the constructors to their own lines, though.

data Action
    = Add Int Int
    | Check Int Int
    deriving (Show, Read)

Handling errors

You've said your error handling is atrocious. I wouldn't really call it that, because it simply does not exist. You never take any action on Nothing, which means the repl will stop as soon as something bad happens.

The glaring problem: The rat's tail

repl :: DisjointSet Int -> IO ()
repl d = do
  line <- getLine
  case (Read.readMaybe line) of
    Just action ->
      case action of
        Add k1 k2 ->
          case (merge k1 k2 d) of
            Just d' -> repl d'
        Check k1 k2 ->
          case (find k1 d) of
            Just (k1', d') ->
              case (find k2 d') of
                Just (k2', d'') -> do
                  if (k1' == k2')
                    then putStrLn "Together"
                    else putStrLn "Apart"
                  repl d''

Having lots of nested cases always yells: refactor me.

Let's follow the flow of repl for a second...

Get a line and read it to an Action. If that is possible, diverge on the type of action: if it's an Add, merge them and repeat on success. If it's a Check, find the first one. If it's found, find the second one. If that is found, show whether they are together or apart and repeat.

There are lots of actions and processes stuffed together here, so let's help the poor repl breathe by splitting it up into pieces.

Reading input

What should happen when the user types garbage, such as "Bananas are a fruit"? Maybe we should just try again... so let's do that.

getAction :: IO Action
getAction = case Read.readMaybe <$> getLine of
    Just action -> return action
    Nothing     -> putStrLn "Oops, try again..." >> getAction

We read a line of user input and Read.readMaybe it to form an Action (<$> is just the infix operator for fmap). If that succeeds, horray, we got ourselves an Action! If not.. say something to the user and try again.

Executing the action

What should happen on an error here? That is your decision to make. If anything goes wrong, I'll just return the old DisjointSet and do nothing. I like to indent the case-statements based on the indentation level on the case itself, so let's do that.

execute :: DisjointSet Int -> Action -> IO (DisjointSet Int)
execute d (Add a b)   = return $ maybe d id (merge a b d)
execute d (Check a b) = case find a d of
                          Nothing       -> return d
                          Just (a', d') -> case find b d' of
                                             Nothing         -> return d
                                             Just (b', d'') -> if a' == b'
                                                                then putStrLn "Together" >> return d''
                                                                else putStrln "Apart"    >> return d''

(Note to Editors: The long line is on purpose)
Damn, that's still long.

Monads to the rescue!

The beauty of Maybe as a monad is that it'll stop doing whatever it does and just return Nothing once it encounters one. So let's use that!

execute :: DisjointSet Int -> Action -> IO (Maybe (DisjointSet Int))
execute d (Add a b)   = return $ merge a b d
execute d (Check a b) = do
    (together, d'') <- (do
             (a', d')  <- find a d
             (b', d'') <- find b d'
             return (a' == b', d''))
    when together       (putStrLn "Together")
    when (not together) (putStrLn "Apart")
    return d''

Putting it together

Using these fancy new functions, your new repl would be:

repl :: DisjointSet Int -> IO ()
repl d = getAction >>= execute d >>= \c -> case c of
    Just d' -> repl d'
    Nothing -> return ()


Generation of Dictionary in Python Is there a way to refactor the following Python code so that the number of lines in generation of the dictionary can be reduced?

data = frame['data'].split(';')

cat_data = {
    'xbee_address': '\x00' + frame['source_addr'],
    'state': data[0],
    'flow_rate': data[1],
    'operating_hours': data[2],
    'operating_minutes': data[3],
    'operating_seconds': data[4],
    'hours_until_maintenance': data[5],
    'number_of_cleansing': data[6],
    'serial_number': data[7],
    'item_number': data[8],
    'month_of_manufacturing': data[9],
    'year_of_manufacturing': data[10],
    'software_version': data[11],
}

TL;DR: use {k: v for k, v in zip(names, data)} where names is a list of names for your values, or dict(zip(names, data)) (which I personally find less readable).

There are two sources of complexity in your code (and I mean human-percieved complexity, not computational complexity):

details, which hide the big picture of what's going on;
the fact that the values in data have names, and those names depend on the order of the data list.

The 1st is easy to solve, just split everything into functions, each of which does one thing only, on the appropriate level of abstraction.

The 2nd is more tricky, since even if you define a tuple of names for your values, there's still an implicit relationship left between the order of values in the frame['data'] string, and the order of values in your tuple. Those kinds of implicit relations are not obvious to someone who doesn't know as much as you do about your code (i.e. to everyone else).

Imagine that the structure of the string in frame['data'] changes. Then, your code will be broken, probably in a very unobvious way, and in a totally unrelated place. It's stuff like this that creates spaghetti code.

I don't know where the frame comes from, so it's hard to give a good advice here. In general, you can pack the frame and the tuple of names into another data structure where you create the frame, and never use the frame alone. Or, make the tuple of names a part of frame. In any case, you want to keep them bound together.

Or, you may encapsulate frame's contents in a  class. This class can have a method which returns data in the appropriate dictionary form. The order of the names can be a private variable, encapsulated inside the class.

If I had to stay with frame as it is, I'd do something like this (the names of the functions can be chosen much better, I don't know enough context to come up with good names):

NAMES = (
    'state',
    'flow_rate',
    'operating_hours',
)
def get_cat_data(frame):
    data = _get_data(frame)
    base = _data_to_dict(data, NAMES)
    base.update(_get_xbee_address(frame))
    return base

def _get_data(frame):
    return frame['data'].split(';')

def _data_to_dict(data, names):
     return {k: v for k, v in zip(names, data)}

def _get_xbee_address(frame):
     return {'xbee_address': '\x00' + frame['source_addr']} #consider naming the string literal and using a constant instead

I hope this helps.


Determine total number of seconds since the epoch I am looking for ways to enhance this function in C++.

The function gets a date and returns the total number of seconds since the epoch (01/01/1970).

Do you have any suggestion regarding the algorithm, the code style, etc ?

Note: I use this function instead of the standard library functions because it can handle negative dates and dates before 1900.

static int NDaysInMonth[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

double getUnixTimeStamp(int y, int m, int d, int h, int mn, int s)
{
    // Begin bounds checking
    if (y < 0 || m < 1 || d < 1 || h < 0 || mn < 0 || s < 0)
        return -1;
    // End bounds checking

    int ye = 1970; //UNIX epoch 01/01/1970

    int sign = y > ye ? 1 : -1;

    int maxY = std::max(y, ye);
    int minY = std::min(y, ye);

    int nleapYears = 0;

    for (int i = minY; i < maxY; i++)
        if ((i % 100 != 0 && i % 4 == 0) || i % 400 == 0) nleapYears++;

    if (m > 2)
        if ((y % 100 != 0 && y % 4 == 0) || y % 400 == 0)
            nleapYears += sign;

    nleapYears = std::max(0, nleapYears);

    double monthsNDays = 0;

    for (int i = 1; i < m; i++)
        monthsNDays += NDaysInMonth[i - 1];

    return ((y - ye) * 365 + sign * nleapYears + monthsNDays + d - 1) * 86400
        + h * 3600 + mn * 60 + s;
}

Edit: I very wrongly accused Jacobi of posting a flawed algorithm. So I removed my ranting and replaced by:

I had a try compiling your code and I worked on it to represent how I would have written it. See below. I hope this gives you hints about a different possible coding style. I hope to demonstrate some benefits. The main differences are:

Comment for readability. In six months you might be very much in doubt yourself of all the intricacies of an algorithm. I had a hard time deciphering your algorithm. I am also in favor of including references to the definitions of formulas etc, which allows reviewers to check them more quickly.
A good practice that I still don't manage to discipline myself to is to write commenting immediately for doxygen or another doc generator, so you can save yourself the hassle later. It usually forces you to document all parameters, return values, ... which is good practice anyway.
Code formatting to represent the structure of the code. I am a big fan of lots of spacing and horizontal alignment to spot the difference between similar lines easily.
I would refactor to avoid repeating the same code twice, even in the case of isLeapYear. I think the algorithm also becomes more readable when you change the condition by a clear function name. For reading how the algorithm works, I actually don't care about the implementation of the leapyear test.
Instead of testing for m < 2 to add or remove extra leapyears, I think it is beneficial to try and represent the reality in your code. I do this here by creating N_DAYS_IN_LEAP_MONTH. This benefits not only in simplifying the code, it also serves in multiple places, as now the input validation is more correct as well.
Returning -1 on error is misleading because it could also be a valid outcome. I would propose in any case to return 0 on error instead of -1, so it can be distinguished from valid output with a Boolean test as if( x = getUnixTimeStamp(...) ) -> valid. If you want to garantee no ambiguity, you should probably return a struct with an error status, an error message and a result.
Personally I prefer longer variable names for clarity, but I suppose that has to do with taste. I also changed nleapyears to nleapdays, which corresponds more to what is is.
I try to use const where I can. In this example it is a bit trivial, and compilers would probably compile it to the exact same assembler code without these consts, so you have to see if you find it worth the extra code. If your parameters aren't basic types, but objects however starting to take them as const refernces really starts making a difference.

Not implemented but advised:

Allow supporting inputs for the whole range of double. This makes your function more general, and thus more useful. If a program logic needs to restrict more, that should not be done in this function.

#include <algorithm>
#include <iostream>

double getUnixTimeStamp( int year, int month, int day, int hour, int minute, int second );

int main()
{
    std::cout << std::fixed << getUnixTimeStamp( 1979, 12, 31, 23, 59, 59 ) << std::endl;

    return 0;
}

// start of getUnixTimeStamp code
static const int N_DAYS_IN_MONTH     [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static const int N_DAYS_IN_LEAP_MONTH[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

// Is the passed in year a leap year?
// https://en.wikipedia.org/wiki/Leap_year#Algorithm
inline
bool
isLeapYear( const int year )
{
    return

             year % 400 == 0
        || ( year % 4   == 0  &&  year % 100 != 0 )

    ;
}

// returns the epoch timestamp for a given date in UTC
// reference: https://en.wikipedia.org/wiki/Unix_time

// current minimum supported date = 0000-01-01 00:00:00
// current maximum supported date = 2999-12-31 59:00:00
// returns 0 on faulty input, as well as for epoch input

// TODO: support full range of double rather than limiting arbitrarily

double
getUnixTimeStamp( const int year, const int month, const int day, const int hour, const int minute, const int second )
{
    // Do some bounds checking
    // Note that double will still not be indefinite, and you should check what the boundaries for double are.
    // (this also changes per implementation, so you need to check limits.h or something like that)
    // It would be more logical and correct to limit to the range permitted by double than to arbitrarily limit a 0y.
    // If your program needs this limit, you should enforce it outside this function, because it doesn't belong here.

    const int* const DAYS_PER_MONTH = isLeapYear( year ) ? N_DAYS_IN_LEAP_MONTH : N_DAYS_IN_MONTH;

    if
    (
            year   < 0  ||  year   > 3000
        ||  month  < 1  ||  month  > 12
        ||  day    < 1  ||  day    > DAYS_PER_MONTH[ month-1 ]
        ||  hour   < 0  ||  hour   > 24
        ||  minute < 0  ||  minute > 60
        ||  second < 0  ||  second > 60
    )

        return 0;
        // it is problematic to do error handling with the return value, as all possible return values could be valid epochs as well.
        // at least by taking 0 you can use a boolean check like if( x = getUnixTimeStamp(...) ) -> valid.
        // The check will fail for 1970-01-01-00-00-00

    // Calculate the seconds since or to epoch
    // Formula for dates before epoch will subtract the full years first, and then add the days passed in that year.

    int epoch       = 1970                  ; // UNIX epoch 01/01/1970
    int sign        = year > epoch ? 1 : -1 ; // So we know whether to add or subtract leap days

    int nleapdays   = 0                     ; // The number of leap days
    int monthsNDays = 0                     ; // The number of days passed in the current year

    // Count the leap days
    for( int i = std::min( year, epoch );  i < std::max( year, epoch );  i++ )

        if( isLeapYear( i )  )

            ++nleapdays;

    // Calculate the number of days passed in the current year
    for( int i = 1;  i < month;  i++ )

        monthsNDays += DAYS_PER_MONTH[ i - 1 ];

    return

        (
              ( year - epoch )  * 365       // add or subtract the full years
            +   sign            * nleapdays // add or subtract the leap days
            +   monthsNDays                 // The number of days since the beginning of the year for full months
            +   day - 1                     // The number of full days this month

        )         * 86400                   // number of seconds in 1 day

        + hour    * 3600
        + minute  * 60
        + second
    ;
}


Prime generator from one to n My code calculates primes from one to n. I have verified that the code always produces all the primes in that range correctly.

Are there any optimizations that I can make? Are there any bad programming practices besides variable names (e.g. l is close to 1)? Any better normal Windows API? I am using the Sieve of Eratosthenes.

#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <Windows.h>

using namespace std;

#define printprimes() //for each(bool b in primes) cout << b << endl;

int main(int argc, char* argv[])
{
    const double s = GetTickCount();
    unsigned long long numt;
    if(argc < 2) {
        cout << "Usage: "<<argv[0]<<" <primes until...>" << endl;
        return 1;
    }

    else if(atoi(argv[1])<1) {
        cout << "Usage: "<<argv[0]<<" <primes until...>" << endl;
        return 1;
    }
    numt = atol(argv[1])+1;

    bool skipprint = false;

    if(argc >=3) if(!strcmp(argv[2], "noprint")) skipprint = true;

    vector<bool> primes(numt);

    primes.assign(numt, true);

    primes[0] = false;
    primes[1] = false;

    long double sqrtt = sqrt(numt);
    for(unsigned long long l = 0; l<=sqrtt; l++) {
        if(!primes[l]) {
            //cout << l << " is false" << endl;
            continue;
        }
        for(unsigned long long cl = 2*l; cl < numt; cl+= l) {
            //cout << cl << ", a multiple of " << l << endl;
            primes[cl] = false;
        }
    }
    const double m = GetTickCount();
    unsigned long long count = 0;
    if(!skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) {
        cout << l << endl;
        count ++;
    }
    if(skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) count ++;
    const double e = GetTickCount();
    cout << endl;
    cout << count << " primes less than or equal to " << numt-1 << endl;
    cout << "Calculation took " << m-s << " ms";
    if(!skipprint) cout << " and printing took " << e-m << " ms";
    else cout << " and counting took " << e-m << " ms";
    cout <<"." << endl;
    //for each(bool b in primes) cout << b << endl;

    return 0;
}

The algorithm looks good overall. Here are a few comments :

using namespace std; is sometimes frowned upon : some might say that putting it in a cpp file (by opposition to a header file) is ok, some might say that it's not. In any case, it is worth having a read at the link.

#define printprimes() //for each(bool b in primes) cout << b << endl;

does not seem really useful.

If you want to handle wrong input in a better way you could have a look at the other ways to convert arrays of char to number.

bool skipprint = false;

if(argc >=3) if(!strcmp(argv[2], "noprint")) skipprint = true;

can become :

bool skipprint = false;
if(argc >=3 && !strcmp(argv[2], "noprint")) skipprint = true;

which is nothing but :

bool skipprint = (argc >=3 && !strcmp(argv[2], "noprint"));

Also it might be even better to do :

bool print = (argc < 3 || strcmp(argv[2], "noprint"));

    if(!primes[l]) {
        //cout << l << " is false" << endl;
        continue;
    }
    for(unsigned long long cl = 2*l; cl < numt; cl+= l) {
        //cout << cl << ", a multiple of " << l << endl;
        primes[cl] = false;
    }

can be written :

    if(primes[l]) {
        for(unsigned long long cl = 2*l; cl < numt; cl+= l) {
            //cout << cl << ", a multiple of " << l << endl;
            primes[cl] = false;
        }
    }

In for(unsigned long long l = 0; l<=sqrtt; l++), you can start from index 2. Please note that if you forget to initialise prime[0] to false, you'll get stuck in an infinite loop.

In for(unsigned long long cl = 2*l; cl < numt; cl+= l), you can start at index l*l because any i*l with i < l should have been crossed out already.

if(!skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) {
    cout << l << endl;
    count ++;
}
if(skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) count ++;

could be rewritten in many different ways. Most obvious one is to use an else :

if (skipprint) for(unsigned long long l = 0; l<numt; l++) if(primes[l]) count ++;
else for(unsigned long long l = 0; l<numt; l++) if(primes[l]) {
    cout << l << endl;
    count ++;
}

A probably better option in order not to repeat code is to do :

for(unsigned long long l = 0; l<numt; l++) if(primes[l]) {
    if (!skipprint)
        cout << l << endl;
    count ++;
}

Also, you should probably write your algorithm in a function on its own. Other optimisation can be analysed like removing all even numbers from the beginning to use a smaller container.


Simple equation parser and evaluator I am relatively new to C++ coming from languages such as Java and would like tips to make my code more C++ like and doing things in the C++ way.
The header file:
#pragma once

#include <string>
#include <memory>

class Expression
{
public:
    std::string symbol;
    std::shared_ptr<Expression> left;
    std::shared_ptr<Expression> right;

    float eval();
    static Expression parse(std::string s);

private:
    Expression(std::string symbol, Expression *left, Expression *right);
    static Expression parseRec(std::string s);
    static float evalRec(const Expression &e);
};

cpp file:
#include "Expression.hpp"
#include <unordered_map>

Expression::Expression(std::string symbol, Expression *left, Expression *right)
    : symbol(symbol), left(left), right(right) {}

float Expression::eval()
{
    return Expression::evalRec(*this);
}

float Expression::evalRec(const Expression &e)
{
    switch (e.symbol[0])
    {
    case '+':
        return evalRec(*e.left) + evalRec(*e.right);
    case '-':
        return evalRec(*e.left) - evalRec(*e.right);
    case '*':
        return evalRec(*e.left) * evalRec(*e.right);
    case '/':
        return evalRec(*e.left) / evalRec(*e.right);
    default:
        return std::stoi(e.symbol);
    }
}

Expression Expression::parse(std::string s)
{
    //Remove whitespace
    std::string output;
    for (auto &i : s)
    {
        if (i != ' ')
            output += i;
    }
    return parseRec(output);
}

Expression Expression::parseRec(std::string s)
{
    const std::unordered_map<char, int> precedence = {{'+', 1}, {'-', 1}, {'*', 10}, {'/', 10}};
    int indexOfLowest = -1;
    int i = 0;
    for (auto &&j : s)
    {
        switch (j)
        {
        case '+':
        case '-':
        case '*':
        case '/':
            if (indexOfLowest == -1)
                indexOfLowest = i;
            else if (precedence.at(j) <= precedence.at(s[indexOfLowest]))
                indexOfLowest = i;
            break;
        default:
            break;
        }
        i++;
    }
    if (indexOfLowest == -1)
    {
        return Expression(s, NULL, NULL);
    }
    else
    {
        return Expression(std::string(1, s[indexOfLowest]),
                          new Expression(parseRec(s.substr(0, indexOfLowest))),
                          new Expression(parseRec(s.substr(indexOfLowest + 1, s.length() - indexOfLowest - 1))));
    }
}

and a simple main:
#include <iostream>
#include "Expression.hpp"

int main(int argc, char const *argv[])
{
    //Parsed expression tree
    Expression e = Expression::parse("5 + 10 * 2 + 6 / 3");
    std::cout << e.eval() << std::endl;
    return 0;
}

Here are some things that may help you improve your code.
Use include guards
There should be an include guard in each .h file.  That is, start the file with:
#ifndef EXPRESSION_H
#define EXPRESSION_H
// file contents go here
#endif // EXPRESSION_H

The use of #pragma once is a common extension, but it's not in the standard and thus represents at least a potential portability problem.  See SF.8
Consider using standard routines
C++ provides a great number of useful utilites such as std::remove that you could use instead of your own hand-written function to remove whitespace.  They're almost always faster and less buggy and by using library software, you can develop your own code more quickly and accurately.  So instead of this:
//Remove whitespace
std::string output;
for (auto &i : s)
{
    if (i != ' ')
        output += i;
}
return parseRec(output);

One could use this:
s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
return parseRec(s);

Note that this uses s rather than output per the next suggestion.
Understand pass-by-value
One thing that is quite different about C++ as compared with Java is how parameter passing is done.  In general, there is pass-by-value and pass-by-reference.  The pass-by-value is what we get when we write things like this:
static Expression parse(std::string s);

The gives parse its own copy of s.  If we use pass-by-reference, it would generally look something like this:
static Expression parse(const std::string& s);

Now we are giving parse a reference (indicated by &) rather than copying it.  In this example, we use the very common idiom of passing a const reference.  This indicates that the called function parse may examine but not alter the value.  Unlike Java, there is no automatic garbage collector in C++, so it's up to you to manage memory.  Generally, passing by reference is faster and uses less memory, but in cases where we would be making a copy anyway, passing by value makes sense.
Prefer private to public where practical
The Expression class has its only data members as public members.  Rather than do it that way, it would be better to keep them private. See C.9 for details.
Eliminate redundant functions
When a non-static member function is called in a C++ class, *this is implicitly passed.  So the result is that this function is entirely useless:
float Expression::eval()
{
    return Expression::evalRec(*this);
}

Instead, just rename evalRec as eval and write it as a member function:
float Expression::eval()
{
    switch (symbol[0])
    {
    case '+':
        return left->eval() + right->eval();
    case '-':
        return left->eval() - right->eval();
    case '*':
        return left->eval() * right->eval();
    case '/':
        return left->eval() / right->eval();
    default:
        return std::stoi(symbol);
    }
}

Simplify your code by making full use of standard library structures
The parseRec routine uses a std::ordered_map and also a switch to find the operator with the lowest precedence.  I suggest that when you see that you have repeated the operators in multiple places, this is a hint that perhaps you could use a different approach to avoid this duplication.  In this case, my inclination would be to use std::min_element.  This requires beginning and ending iterators and a comparison operation.  First, let's write a comparison operation:
enum class op_precedence { LOW, MED, NON_OP };

static constexpr op_precedence precedence(char ch) {
    op_precedence val{op_precedence::NON_OP};
    switch (ch) {
        case '+':
        case '-':
            val = op_precedence::LOW;
            break;
        case '*':
        case '/':
            val = op_precedence::MED;
            break;
        default:
            break;
    }
    return val;
}

Now we can use std::min_element:
std::string::iterator lowest{std::min_element(s.begin(), s.end(),
    [](const char &a, const char &b){
        return precedence(a) < precedence(b);
    })
};

This uses a lambda to actually effect the comparison.  So now the whole function looks like this:
Expression Expression::parseRec(std::string s) {
    std::string::iterator lowest{std::min_element(s.begin(), s.end(),
        [](const char &a, const char &b){
            return precedence(a) < precedence(b);
        })
    if (precedence(*lowest) == op_precedence::NON_OP) {
        return Expression(s, nullptr, nullptr);
    } else {
        return Expression(std::string(1, *lowest),
                          new Expression(parseRec(s.substr(0, lowest-s.begin()))),
                          new Expression(parseRec(s.substr(lowest-s.begin() + 1)))
                          );
    }
}

Note, too, that this uses the modern nullptr rather than the old C-style NULL.
Dive deeper into C++
I know you're just beginning with C++ (and it looks like a promising beginning!) but to whet your appetite for more, we can actually go a little further with the concept mentioned above.  Specifically, we have a similar duplication in eval, so we could further consolidate information.  Here's one way to do it:
enum class op_precedence { LOW, MED, NON_OP };
struct op {
    op_precedence precedence;
    float (*operation)(float, float);
};

static const std::unordered_map<char, op> operation = {
    { '+', { op_precedence::LOW, [](float a, float b){return a+b;}} },
    { '-', { op_precedence::LOW, [](float a, float b){return a-b;}} },
    { '*', { op_precedence::MED, [](float a, float b){return a*b;}} },
    { '/', { op_precedence::MED, [](float a, float b){return a/b;}} },
};

static op_precedence precedence(char ch) {
    auto myop{operation.find(ch)};
    return myop == operation.end() ? op_precedence::NON_OP : myop->second.precedence;
}

Now the rest of the program gets shorter and more concise:
float Expression::eval()
{
    auto myop{operation.find(symbol[0])};
    if (myop == operation.end()) {
        return std::stoi(symbol);
    }
    return myop->second.operation(left->eval(), right->eval());
}

Expression Expression::parse(std::string s)
{
    s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
    return parseRec(s);
}

Expression Expression::parseRec(std::string s)
{
    std::string::iterator lowest{std::min_element(s.begin(), s.end(), [](const char &a, const char &b){
        return precedence(a) < precedence(b); })};
    if (precedence(*lowest) == op_precedence::NON_OP)
    {
        return Expression(s, nullptr, nullptr);
    }
    else
    {
        return Expression(std::string(1, *lowest),
                          new Expression(parseRec(s.substr(0, lowest-s.begin()))),
                          new Expression(parseRec(s.substr(lowest-s.begin() + 1)))
                          );
    }
}

Don't use std::endl if you don't really need it
The difference betweeen std::endl and '\n' is that '\n' just emits a newline character, while std::endl actually flushes the stream.  This can be time-consuming in a program with a lot of I/O and is rarely actually needed.  It's best to only use std::endl when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one.  Avoiding the habit of using std::endl when '\n' will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.
About return 0;
All compliant compilers will generate the equivalent of return 0 at the end of main, so I generally omit that.  Others prefer to write it explicitly for stylistic reasons.  Whichever you choose, it's useful to know.
Use the appropriate smart pointer type
The code, as written, abuses std::shared_ptr because no two objects should ever actually share the same Expression.  For that reason, what you really should use instead is std::unique_ptr, but that makes things a bit more complex.  In particular, we can no longer freely make copies (or they wouldn't be unique!) so we must use C++ move semantics.  It's all perhaps a bit much for a beginner, but here's how one would rewrite the relevant portions of the class declaration.
std::unique_ptr<Expression> left;
std::unique_ptr<Expression> right;
Expression(std::string symbol, std::unique_ptr<Expression> &&left, std::unique_ptr<Expression> &&right);

Now the constructor looks like this:
Expression::Expression(std::string symbol, std::unique_ptr<Expression> &&left, std::unique_ptr<Expression> &&right)
    : symbol(symbol), left(std::move(left)), right(std::move(right)) {}

And instead of using new (which is rather rare in modern C++), we use std::make_unique instead:
return Expression(std::string(1, *lowest),
                  std::make_unique<Expression>(parseRec(s.substr(0, lowest-s.begin()))),
                  std::make_unique<Expression>(parseRec(s.substr(lowest-s.begin() + 1)))
                  );


Combining ADD and VOLUME on a nodejs Dockerfile I have a node project. My scripts section of package.json looks like this:

"scripts": {
  "postinstall": "gulp",
  "start": "node index.js",
  "test": "node ./node_modules/mocha/bin/mocha test"
},

My Dockerfile looks like this

FROM node:6.11-alpine

RUN mkdir -p /code
ADD . /code
WORKDIR /code
VOLUME /code

RUN npm install -g -s --no-progress yarn && \
    yarn && \
    yarn run test && \
    yarn cache clean

My docker-compose.yml looks like this:

version: "3"

services:
  web:
    build: .
    volumes:
      - .:/code
    command: "npm start"
    ports:
      - "8080:8080"
    networks:
      - internal

networks:
  internal:

This combination of ADD and VOLUME seems to give me what I need in terms of the javascript being there during the build stage and changes getting picked up in real time. However, I'm scared I'm doing something terribly wrong.

This Dockerfile should contain:

FROM node:6.11-alpine

COPY . /code
WORKDIR /code

RUN npm install -g -s --no-progress yarn && \
    yarn && \
    yarn run test && \
    yarn cache clean

EXPOSE 8080

CMD ["npm", "start"]

COPY copies your current directory to /code for building the final image (that holds compiled code normally).

In your docker-compose.yml, mounting a volume is used for your dev purposes, so that the files modified replace the ones on your image.

version: "3"

services:
  web:
    build: .
    volumes:
      - .:/code
    command: "npm run start:dev"
    ports:
      - "8080:8080"
    networks:
      - internal

networks:
  internal:


Simple todo list in Javascript I'm looking for someone to tell me how I could refactor/change/improve my JS, I'm still learning and really want my code to be the best it can be for when it comes time for me getting a job in the industry. Would really appreciate a professional's help.

It's just a fairly simple todo list...

Here is the JS

let ul = document.getElementById('list');
let input = document.querySelector("input");
let toggle = document.querySelector('.fa-plus');

toggle.addEventListener('click', function() {
    toggle.classList.toggle('rotated');
    input.classList.toggle('hide');
});

input.addEventListener('keydown', function(e) {
    if (e.keyCode === 13 && input.value !== '') {
        addTodo();
    };
});

let deleted = () => {
    let spans = document.querySelectorAll('span');
    for (let span of spans) {
        span.addEventListener('click', function() {
            this.parentNode.parentNode.removeChild(this.parentNode);
        });
    };
};

let addTodo = () => {
    let listItem = document.createElement('li');
    listItem.innerHTML = ' ' + input.value;
    listItem.addEventListener("click", function() {
        this.classList.toggle("lineThrough");
    });
    ul.appendChild(listItem);
    deleted();
    input.value = '';
};

Here is the link to the project on codepen - https://codepen.io/ruaridouglas/pen/mdeaaKV

You declare all your variables with let. You aren't using var, so that's good - but it's better to prefer const over let unless you have no choice but to reassign the variable later. (I recently did a check of one of my scripts and found 414 uses of const compared to 16 uses of let - that's the sort of proportion you want to be aiming towards.) Code is most readable when any reader can immediately understand that a variable is never going to be reassigned from its initial value.
This is a bit opinion-based, but I would prefer to avoid IDs in HTML when possible: they not only automatically create properties on the global object (which can result in strange bugs), but also, only one element with a particular ID can exist in the document at a given time. So, for example, if you were tasked to refactor the code so that multiple lists can be interacted with on a page, you would have to make changes.
(Actually, in new code, I get the feeling that the "industry standard" is to usually avoid vanilla DOM manipulation like this at all - usually, a framework like React is used instead, allowing for the functional composition of components. Eg, if you had a working TodoList, changing to a page with two of them would be as simple as
<TodoList />

<TodoList />
)
You do
<input onblur="this.placeholder = 'What do you want to do?'" onfocus="this.placeholder = ''" placeholder="What do you want to do?" type="text">

Never, ever use inline handlers. They have numerous problems (such as executing inside a few confusing with blocks) and have no place in modern code. To attach an event listener to an element, use addEventListener instead.
But here, you don't need Javascript at all: you can use CSS instead:
input:focus::placeholder {
  color: transparent;
}

You sometimes use functions, and you sometimes use arrow functions. Code is best when its style is consistent - I'd recommend picking one and sticking with it everywhere. (I'd prefer arrow functions, since they're always expressions rather than hoisted and reassignable declarations, and because they're usually more concise, and because they make it clear that this is not being captured in the new function.)
You use KeyboardEvent.keyCode, but it's deprecated. As MDN puts it:

This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

I'd prefer to use the key property instead, which is not only supported, but it's also a whole lot more intuitive when you can simply perform a comparison against a character as a string rather than have to refer to a table mapping keycode numbers to their characters. So, this:
if (e.keyCode === 13 && input.value !== '') {

can be replaced with:
if (e.key === 'Enter' && input.value !== '') {

The deleted function here:
let deleted = () => {
    let spans = document.querySelectorAll('span');
    for (let span of spans) {
        span.addEventListener('click', function() {
            this.parentNode.parentNode.removeChild(this.parentNode);
        });
    };
};

can be improved. First, its name isn't particularly informative - it's good for a function's name to represent what it does. What this function does is it adds an event listener to each  in the document, which deletes the span's ancestor when clicked. A better name would be deleteTodosOnTrashClick.
But, it selects all s in the document. So, if you had, say, a header with a  in addition to the todo list, if the header's span was clicked on, the header would be removed. It would be better to remove only the s which are children of the todo list:
const spans = ul.querySelectorAll('span');

But you're also adding an event listener to every span, every time a new todo is added. Since these spans are being created dynamically, it would be even better to add an event listener to just the created , at the moment that it's created:
const addTodo = () => {
    const listItem = document.createElement('li');
    listItem.innerHTML = ' ' + input.value;
    listItem.addEventListener("click", function() {
        this.classList.toggle("lineThrough");
    });
    ul.appendChild(listItem);
    listItem.querySelector('span').addEventListener('click', () => {
        listItem.remove();
    });
    input.value = '';
};

Note the use of .remove(). This is often preferable to removeChild because removeChild requires a reference to both the parent and the child, which can get a bit verbose, as you can see in your original code.
There's another issue in addTodo. You are creating the HTML string for the new todo by concatenating user input, which should be avoided without taking precautions; this allows the user to execute arbitrary scripts, and insert arbitrary elements, which is a security risk and can result in unpredictable behavior.
For example, imagine if this was hosted on a website for students learning, where the students have logged in, and one of them got a message saying:

Try pasting the following string into the todo list, you won't believe what happens next!

(except obfuscated). Then the student could have their login stolen by an attacker, because the site created the HTML by concatenating user input and did not sanitize it beforehand.
Either strip out all HTML tags from the input first, or assign to the textContent of the container for the text instead, or use insertAdjacentText:
listItem.innerHTML = ' ';
// ...
listItem.insertAdjacentText('beforeend', input.value);

It would also be a good idea (as always) to run the script in strict mode, and put it inside an IIFE so as to avoid global pollution. All together:

(() => {
  'use strict';
  const ul = document.querySelector('.list');
  const input = document.querySelector("input");
  const toggle = document.querySelector('.fa-plus');
  toggle.addEventListener('click', () => {
    toggle.classList.toggle('rotated');
    input.classList.toggle('hide');
  });

  input.addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && input.value !== '') {
      addTodo();
    };
  });

  const addTodo = () => {
    const listItem = document.createElement('li');
    listItem.innerHTML = ' ';
    listItem.addEventListener("click", () => {
      listItem.classList.toggle("lineThrough");
    });
    ul.appendChild(listItem);
    listItem.querySelector('span').addEventListener('click', () => {
      listItem.remove();
    });
    listItem.insertAdjacentText('beforeend', input.value);
    input.value = '';
  };
})();
html {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  font-size: 16px;
}

*,
*:before,
*:after {
  -webkit-box-sizing: inherit;
  -moz-box-sizing: inherit;
  box-sizing: inherit;
}

body,
h1,
h2,
h3,
h4,
h5,
h6,
p,
ol,
ul {
  margin: 0;
  padding: 0;
  font-weight: normal;
}

ol,
ul {
  list-style: none;
}

img {
  max-width: 100%;
  height: auto;
}

/* RESET FINISHED */

@import url('https://fonts.googleapis.com/css2?family=Heebo:wght@500&display=swap');
body {
  font-family: 'Heebo', sans-serif;
  background: rgb(200, 230, 201);
  background: linear-gradient(90deg, #00b09b 0%, #96c93d 100%);
}

#container {
  width: 360px;
  margin: 100px auto;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(42, 59, 56, 0.4);
}

h1 {
  font-size: 1.6em;
  font-weight: bold;
  padding: .8em .5em;
  background: #00b09b;
  color: #fff;
}

.fa-plus {
  float: right;
  transition: ease-in .2s;
}

.rotated {
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transition: ease-in .2s;
}

.hide {
  display: none;
}

input {
  clear: left;
  font-size: 1em;
  padding: .8em .5em;
  width: 100%;
  outline: none;
  border-top: none;
  border-left: none;
  border-right: none;
  border-bottom: 1px solid rgba(48, 87, 80, 0.4);
  background-color: rgb(236, 236, 236);
  transition: ease-in .2s;
}

input:focus {
  box-shadow: 0 5px 5px rgba(42, 59, 56, .4);
  border-bottom: none;
}
input:focus::placeholder {
  color: transparent;
}

.lineThrough {
  text-decoration: line-through;
  color: grey;
  transition: ease-in .2s;
}

li {
  width: 100%;
  line-height: 40px;
  transition: ease-in .2s;
}

li:nth-child(2n) {
  background-color: rgb(236, 236, 236);
}

span {
  background-color: #e74c3c;
  height: 40px;
  margin-right: 10px;
  text-align: center;
  color: #fff;
  width: 0;
  display: inline-block;
  transition: 0.2s linear;
  opacity: 0;
}

li:hover span {
  width: 40px;
  opacity: 1;
}

Javascript To-Do List

  <input placeholder="What do you want to do?" type="text">


Clearing filters, copying a range, and then pasting a formula down a row Novice coder here. I have the following code to perform a few actions like clearing filters, copying a range, and then pasting a formula down a row till the last line.

It works perfectly, but it takes longer than a minute to complete since I am addressing each in my for next loop individually. Would anyone know how to speed this up by using a range call instead of a cell call?

My constraint is that I must start on row six of the column selected and autofill to the bottom. The same with the paste values of the column to the left.

 Sub testingme2()

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

Dim myvalue As Double, lastrow As Long, paster As String

lastrow = Worksheets("x").Cells(Rows.Count, 1).End(xlUp).Row
myvalue = Worksheets("y").Cells(6, 2).Value
paster = "formula"

If Sheets("x").FilterMode Then
    Sheets("x").Cells.AutoFilter
End If

Sheets("x").Select
Range("A6:AG5000").Select
Selection.Copy
Sheets("z").Select
Range("A6").Select
Selection.PasteSpecial xlPasteValues
Sheets("x").Select

For i = 6 To lastrow
    Worksheets("x").Cells(i, (myvalue) + 20).Copy
    Worksheets("x").Cells(i, (myvalue) + 20).PasteSpecial xlPasteValues
    Worksheets("x").Cells(i, (myvalue) + 21).Cells.FormulaR1C1 = paster
Next

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub

This should be much faster:

We get rid of the .Select and .Activate. They will slow the process down because it is telling excel to do something, that takes time.
Since we only want the values we assign them directly avoiding the clipboard.  Again just the moving of data into the clipboard takes an extra step and then moving them out again is another step.  We can do it in one.
When using R1C1 we can put the formula in bulk, so no looping.  The R1C1 references will adjust accordingly.
Using the With block and proper . notation allows us to limit typing the sheet over and over again, but still allowing the proper parentage to be assigned.

Sub testingme2()

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

Dim myvalue As Double, lastrow As Long, paster As String

lastrow = Worksheets("x").Cells(Rows.Count, 1).End(xlUp).Row
myvalue = Worksheets("y").Cells(6, 2).Value
paster = "formula"

If Sheets("x").FilterMode Then
    Sheets("x").Cells.AutoFilter
End If

Sheets("Z").Range("A6:AG5000").Value = Sheets("x").Range("A6:AG5000").Value

With Worksheets("x")
    .Range(.Cells(6, (myvalue) + 20), .Cells(lastrow, (myvalue) + 20)).Value = .Range(.Cells(6, (myvalue) + 20), .Cells(lastrow, (myvalue) + 20)).Value
    .Range(.Cells(6, (myvalue) + 21), .Cells(lastrow, (myvalue) + 21)).FormulaR1C1 = paster
End With

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub


Autoloading Class files and instantiating a class - Admin backend At the moment I am auto loading my classes with:

spl_autoload_register(function ($class) {
    require_once 'classes/class.'. $class .'.php';
});

And instantiating the class with:

$backend = new backend();
$dashboard = new dashboard();
$article = new article();
$video = new video();
$theme = new theme();

These are in a config file required on every action page of my admin section.

backend is my main class holding database functions and other global functions.

The other classes all extends backend.

As I understand it, I could call backend functions through for example article, as it is an extension of the class.

Is this a good method for instantiating the classes, or is there a way I can call them automatically without having to write these in the config file at all?

Using spl_autoload_register() is a well known and recommended way of auto-loading classes.

And of course you can't call objects without having them instantiated first.


Normalizing `DateTime` values to strings I have this as part of a project to normalize DateTime values to more readable strings, localized to the relative time in the past that they happened.
It allows you to make several customizations. If you don't want a time to show up, specify "" for the timeFormat, etc. You can change the reference DateTime so that you can measure values between any two DateTime points.
The idea is to put them in forms like:

Event happened just now
Event happened 29 minutes ago
Event happened yesterday at 3:54 pm
etc

I'm looking for any and all improvements (as per the standard rules).
I assume my use of optional statements is less than idea, but I'm open to any and all suggestions about everything here.
public static string ToNormalizedString(this DateTime DateTime, DateTime? reference = null, string dateFormat = "MMM d, yyyy", string timeFormat = "h:mm tt", string preDateString = "", string preTimeString = "at", bool capitalizeModifiers = true)
{
    string result = "";

    DateTime referenceDateTime = DateTime.UtcNow;

    if (reference.HasValue)
    {
        referenceDateTime = reference.Value;
    }

    if (DateTime.Date == referenceDateTime.Date)
    {
        TimeSpan TimeDifference = referenceDateTime - DateTime;

        if (TimeDifference < new TimeSpan(0, 1, 0))
        {
            result = (capitalizeModifiers ? "Just now" : "just now");
        }
        else if (TimeDifference < new TimeSpan(0, 2, 0))
        {
            result = (capitalizeModifiers ? "About a minute ago" : "about a minute ago");
        }
        else if (TimeDifference < new TimeSpan(1, 0, 0))
        {
            result = (capitalizeModifiers ? "About " : "about ") + Math.Ceiling(TimeDifference.TotalMinutes).ToString() + " minutes ago";
        }
        else
        {
            result = (capitalizeModifiers ? "About " : "about ") + Math.Ceiling(TimeDifference.TotalHours).ToString() + " hours ago";
        }
    }
    else if (DateTime.Date.AddDays(1) == referenceDateTime.Date)
    {
        result = (capitalizeModifiers ? "Yesterday at " : "yesterday at ") + DateTime.ToString(timeFormat);
    }
    else if (DateTime.Date.AddDays(7) > referenceDateTime.Date)
    {
        result = preDateString + DateTime.DayOfWeek.ToString() + (timeFormat == "" ? "" : " " + preTimeString + " " + DateTime.ToString(timeFormat));
    }
    else
    {
        result = preDateString + DateTime.ToString(dateFormat) + (timeFormat == "" ? "" : " " + preTimeString + " " + DateTime.ToString(timeFormat));
    }

    return result;
}

As usual this code is free to anyone who wishes to use it.

TimeSpan.FromMinutes(1) and TimeSpan.FromHours(1) are much easier to read than new TimeSpan(0, 1, 0) and new TimeSpan(1, 0, 0).

Consider using multiple return statements, instead of just the one.

Stick to the naming conventions: change the parameter DateTime to dateTime, and the variable TimeDifference to timeDifference.

It's a good idea to document that this is relative to UTC time, otherwise users might get strange behaviour like this:

var twoHoursAgo = DateTime.Now.AddHours(-2);
Console.WriteLine(twoHoursAgo.ToNormalizedString());

Just now


Finding suggested flight destinations from database in Golang This is my first Go project. Coming from a Java developer background, this code just smells very bad. But, cannot figure out better way to do this.

It's a small app to find suggested flight destinations based on one or more origins (by their airport-codes, called codesbelow).
Basically finding flights that have the same destination and about the same arrival times.

// SuggestDestinations takes a list of origin airport codes, an earliest arrival time and a latest arrival time and
// returns a map, where the destination is the key, and the suggested flights.
func (service *FlightService) SuggestDestinations(codes []string, earliestArrival, latestArrival time.Time) (destinationMap map[string][]internal.Flight, err error) {
    rows, err := service.db.Query(selectFlightsSQL, pq.Array(codes), earliestArrival, latestArrival)
    if err != nil {
        return nil, err
    }
    defer rows.Close()
    var m map[string][]internal.Flight
    m = make(map[string][]internal.Flight)
    for rows.Next() {
        var a internal.Flight
        var origin, destination, airline string
        if e := rows.Scan(&origin, &destination, &airline, &a.Departure, &a.Arrival); err != nil {
            return nil, e
        }
        a.Origin, err = service.GetAirport(origin)
        a.Destination, err = service.GetAirport(destination)
        a.Airline, err = service.GetAirline(airline)
        // Filter out destinations which is one of the origins
        if !contains(codes, a.Destination.Code) {
            m[a.Destination.Code] = append(m[a.Destination.Code], a)
        }
    }

    // Delete destinations for which there are not flights from every given origin
    for k := range m {
        if !containsAllCodes(m[k], codes) {
            delete(m, k)
        }
    }

    return m, nil
}

Where containsAllCodes looks like this:

func containsAllCodes(flights []internal.Flight, codes []string) bool {
containsAllOrigin := true
for _, c := range codes {
    containsOrigin := false
    for _, f := range flights {
        containsOrigin = containsOrigin || f.Origin.Code == c
    }
    containsAllOrigin = containsAllOrigin && containsOrigin
    }
    return containsAllOrigin
}

... this code just smells very bad. But, cannot figure out better way
  to do this.

Let's look at a more complete, more fragrant implementation.

For data, you are using PostgreSQL: db.Query(selectFlightsSQL, pq.Array(codes), ...). Therefore, define data using the SQL Data Definition Language (DDL). For example,

CREATE TABLE airlines (
    airlinecode char(3) NOT NULL,
    airlinename varchar(64) NOT NULL,
    PRIMARY KEY (airlinecode),
    UNIQUE (airlinename)
);

CREATE TABLE airports (
    airportcode char(3) NOT NULL,
    airportname varchar(64) NOT NULL,
    timezonename varchar(64) NOT NULL,
    PRIMARY KEY (airportcode),
    UNIQUE (airportname)
);

CREATE TABLE flights (
    airlinecode char(3) NOT NULL,
    flightno integer NOT NULL,
    departtime timestamptz NOT NULL, -- local time
    origincode char(3) NOT NULL,
    arrivetime timestamptz NOT NULL, -- local time
    destinationcode char(3) NOT NULL,
    PRIMARY KEY (airlinecode, flightno, departtime),
    FOREIGN KEY (airlinecode) REFERENCES airlines,
    FOREIGN KEY (origincode) REFERENCES airports,
    FOREIGN KEY (destinationcode) REFERENCES airports
);

Access the data using the SQL Data Manipulation Language (DML). For example,

    -- $1  origincode list
    -- $2  origincode list length
    -- $3  earliest arrivaltime
    -- $4  latest arrivaltime
    SELECT destinationcode, airportd.airportname AS destinationname, arrivetime, airportd.timezonename AS arrivezone,
        origincode, airporto.airportname AS originname, departtime, airporto.timezonename AS departzone,
        destinations.airlinecode, airlines.airlinename, flightno

    FROM (

        SELECT destinationcode, origincode, airlinecode, flightno, departtime, arrivetime,
            count(origincode) OVER (PARTITION BY destinationcode) AS origins
        FROM flights
        WHERE arrivetime >= $3 AND arrivetime <= $4
            AND origincode = ANY($1)
            AND destinationcode != ANY($1)

    ) AS destinations
    LEFT JOIN airlines ON airlines.airlinecode = destinations.airlinecode
    LEFT JOIN airports AS airportd ON airportd.airportcode = destinationcode
    LEFT JOIN airports AS airporto ON airporto.airportcode = origincode

    WHERE origins = $2

    ORDER BY destinationcode, arrivetime, airlinecode, flightno, departtime
    ;

Consider optimizations such as indices.

Data access is implemented in SQL for any programming language that implements an interface to PostgreSQL (and other relational DBMS`s), not just Go.

In Go, the remaining algorithmic, procedural task is simple: convert the SQL rows to a Go hash map indexed by destination code. For example,

package main

import (
    "database/sql"
    "time"

    "github.com/lib/pq"
    _ "github.com/lib/pq"
)

type Flight struct {
    DestinationCode string
    DestinationName string
    ArriveTime      time.Time
    ArriveZone      string
    OriginCode      string
    OriginName      string
    DepartTime      time.Time
    DepartZone      string
    AirlineCode     string
    AirlineName     string
    FlightNo        int
}

func destinations(db *sql.DB, origins []string, earliest, latest time.Time) (map[string][]Flight, error) {
    query := `
        -- $1  origincode list
        -- $2  origincode list length
        -- $3  earliest arrivaltime
        -- $4  latest arrivaltime
       SELECT destinationcode, airportd.airportname AS destinationname, arrivetime, airportd.timezonename AS arrivezone,
            origincode, airporto.airportname AS originname, departtime, airporto.timezonename AS departzone,
            destinations.airlinecode, airlines.airlinename, flightno

        FROM (

            SELECT destinationcode, origincode, airlinecode, flightno, departtime, arrivetime,
                count(origincode) OVER (PARTITION BY destinationcode) AS origins
            FROM flights
            WHERE arrivetime >= $3 AND arrivetime <= $4
                AND origincode = ANY($1)
                AND destinationcode != ANY($1)

        ) AS destinations
        LEFT JOIN airlines ON airlines.airlinecode = destinations.airlinecode
        LEFT JOIN airports AS airportd ON airportd.airportcode = destinationcode
        LEFT JOIN airports AS airporto ON airporto.airportcode = origincode

        WHERE origins = $2

        ORDER BY destinationcode, arrivetime, airlinecode, flightno, departtime
        ;
        `

    dst := make(map[string][]Flight)
    rows, err := db.Query(query, pq.Array(origins), len(origins), earliest, latest)
    if err != nil {
        return nil, err
    }
    defer rows.Close()
    for rows.Next() {
        var flt Flight
        err := rows.Scan(
            &flt.DestinationCode,
            &flt.DestinationName,
            &flt.ArriveTime,
            &flt.ArriveZone,
            &flt.OriginCode,
            &flt.OriginName,
            &flt.DepartTime,
            &flt.DepartZone,
            &flt.AirlineCode,
            &flt.AirlineName,
            &flt.FlightNo,
        )
        if err != nil {
            return nil, err
        }
        dst[flt.DestinationCode] = append(dst[flt.DestinationCode], flt)
    }
    err = rows.Err()
    if err != nil {
        return nil, err
    }
    return dst, nil
}

func main() {}

The XY problem is asking about your attempted solution rather than your actual problem: The XY Problem. Therefore, without a problem, we have no way of knowing whether a solution is correct. There are no use cases or examples.

TODO: Domain knowledge is important. Airline arrival and departure times are local times. Any solution needs to be verified and tested across time zones and for standard and daylight saving times.


Is this file a good starting point for accessing data inside this json file via javascript classes? I was given a spreadsheet of data that I turned into a CSV file and then converted it into a JSON file.
I threw it into my application and I am processing it in the following manner:
const fs = require("fs");

class DataRepository {
  constructor(filename) {
    if (!filename) {
      throw new Error("Creating a repository requires a filename");
    }

    this.filename = filename;
    try {
      fs.accessSync(this.filename);
    } catch (error) {
      console.error("data does not exist");
    }
  }

  async getAll() {
    // Open the file called this.filename
    return JSON.parse(
      await fs.promises.readFile(this.filename, {
        encoding: "utf-8",
      })
    );
  }

  async getOneBy(filters) {
    const records = await this.getAll();

    for (let record of records) {
      let found = true;

      for (let key in filters) {
        if (record[key] !== filters[key]) {
          found = false;
        }
      }

      if (found) {
        return record;
      }
    }
  }
}

module.exports = new DataRepository("cales_data.json");

With this approach, will I later be able to create some JavaScript classes to access values inside of it like so:
export class Address {
    constructor() {
        this.Address = repo.Address;
    }
}

Some issues:

The constructor recognizes an error if the file doesn't exist but, after logging, just behaves as if nothing is wrong.  It does not communicate back an error.  Probably, you should just let the exception go back to the caller or don't test it at all in the constructor and let the operation that actually uses the file get the error and communicate that error back to the caller then.

You're using a mix of synchronous and asynchronous file access.  That's usually a wrong choice because if you are in a programming situation where synchronous access is fine (like startup code or a single user script), then it's just simpler to use synchronous access everywhere.  If not (like in a server environment) and you should be using asynchronous access everywhere, then you should be using asynchronous access everywhere.

If you're doing this synchronously in nodejs, then require() of a filename with a .json file extension will automatically read and parse the file for you.

It's not clear why any of this involves methods on an instantiated object.  These are all stand-alone functions.  While you do access this.filename, that is not required if you just pass the filename to getAll().


Using TinyMCE with responsive file manager PHP and Javascript I use TinyMCE with responsivefilemanager and I wanted to know that is my code well-written maintainable and readable, Sorry If this sounds like a stupid and basic question because this is such a basic thing to do, and I have also been in web dev for a long time but I am new at WYSIWYG editors and TinyMCE.
Here is my file structure
Website's main parent folder/public_html
    myapp folder for the whole app
      my HTML & some PHP files which use TinyMCE and responsivefilemanager
      my tinyMCE's init.js file
      plugins folder for all my 3rd party plugins
        TinyMCE folder which contains TinyMCE itself
          other folders you find inside TinyMCE
          a plugins folder inside TinyMCE used for plugins related to it
            filemanager folder for the responsivefilemanager plugin

Here is my necessary code of config.php file which is inside the filemanager's config folder
<?php

    /*
        |--------------------------------------------------------------------------
        | DON'T TOUCH (base url (only domain) of site).
        |--------------------------------------------------------------------------
        |
        | without final / (DON'T TOUCH)
        |
        */
        'base_url' => ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http"). "://". @$_SERVER['HTTP_HOST'],
        /*
        |--------------------------------------------------------------------------
        | path from base_url to base of upload folder
        |--------------------------------------------------------------------------
        |
        | with start and final /
        |
        */
        'upload_dir' => '/myapp/uploads/',
        /*
        |--------------------------------------------------------------------------
        | relative path from filemanager folder to upload folder
        |--------------------------------------------------------------------------
        |
        | with final /
        |
        */
        'current_path' => '../../uploads/',

        /*
        |--------------------------------------------------------------------------
        | relative path from filemanager folder to thumbs folder
        |--------------------------------------------------------------------------
        |
        | with final /
        | DO NOT put inside upload folder
        |
        */
        'thumbs_base_path' => '../../thumb/',
?>

My init.js file so I can initialize TinyMCE for my textarea
         tinymce.init({
            selector: "textarea",
            plugins: [
                "advlist autolink link image lists charmap print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars insertdatetime media nonbreaking",
                "table contextmenu directionality emoticons paste textcolor responsivefilemanager code codesample"
            ],
            toolbar1: "undo redo | bold italic underline | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | styleselect",
            toolbar2: "| responsivefilemanager | link unlink anchor | image media | codesample | forecolor backcolor  | print preview code ",
            image_advtab: true,
            branding: false,

            external_filemanager_path: "plugins/filemanager/",
            filemanager_title: "Scintilla Filemanager for Lessons",
            external_plugins: {
                "filemanager": "plugins/filemanager/plugin.min.js"
            }
        });

        tinymce.init(demoBaseConfig);

How you want to arrange your JS files depends also on your build processes too, and whether you want to utilise the cloud version of TinyMCE, or a self-hosted one.
If you're sticking with self-hosted, I find it easier to move external plugins out of the TinyMCE folder - this just makes updating the TinyMCE core easier. You can replace an entire TinyMCE folder with a new version, and know that the Responsive File Manager is not lost.
I would recommend splitting any external plugins (like Responsive File Manager, or anything else you write yourself too) to a separate folder outside of the TinyMCE folder - in the long run, just makes it easier to maintain.
Alternatively, you could use the TinyMCE cloud version - which means you don't need to host it yourself, and you would get the minor point updates as they come out (which for the 5 version have had some really nice features added). To do this, you can visit tiny.cloud and sign up for an API key, which is free. They offer premium plugins at a cost if there are features that you want to use.
For the config.php file, that all looks fine - it's about tweaking it to suit your folder structure.
In your init.js file, I'm assuming you have two different TinyMCE configs? If that is not the case, and you only have one configuration, then you don't need your second init call - the one that references "demoBaseConfig" could be removed.
The first call is initialising TinyMCE on any textarea, using the plugins and toolbar as stated, and hooking in to the Responsive File Manager.
If you wanted to clean it up, you could slim down your plugins array to only include those that you're actually using. There are some plugins here that you don't have in your toolbar, so could slim down the configuration further.
One thing I have done when using TinyMCE is have a number of JS objects that store different configurations, with a selector of "textarea.simple" or "textarea.full" (for two editor types).
The two configurations here are a simple editor (such as maybe basic text choices, adding links, etc) where as the full is a more feature-rich experience too. There are times when you may want to give your users a HTML editor but without too many options (such as for a bio or small snippet) and others where they need a full suite of options (like an article editor). This is more about UX, but just something to be aware of - not every TinyMCE instance needs to look the same.
If you were to go down this path, you would have one init call per configuration option, such as:
tinymce.init({
    selector: "textarea.simple",
    ...
    [whatever simple config options you need]
});

tinymce.init({
    selector: "textarea.full",
    ...
    [whatever full suite config options you need]
});

Just remember to add the appropriate class to your textarea and you'll be good to go.


IPC The sleeping barber problem in C feedback I would love to get some feedback on this Sleeping barber implementation in C.
the entire project can be found here: https://github.com/T0iS/sleeping-barber
    How to run.

1. make
2. start the server on a selected port ( ./server XXXX)
3. start the client on localhost and connect to the previously specified port (./holic_cl localhost XXXX)

I would love to hear some advice on the code quality in general, what to do, what not to do and/or how could I improve the code stability and quality or readability as well.
Editing the question and specifying the code parts, did not know about that rule, thanks for letting me know.
The most important parts are these.
The readline function that reads a line from a FD
int readline(fdStruct& fd, char* buf){

    int ret, mv;
    char temp[256];
    bzero(temp, sizeof(temp));
    char* t = NULL;

    while(1){
        bzero(temp, sizeof(temp));
        bzero(buf,sizeof(buf));

        ret = read(fd.fd, &temp, 256 - sizeof(strlen(fd.BUF)));
        if (ret > 0 ){
            temp[ret] = '\0';
        }

        strcat(fd.BUF, temp);
        t = strchr(fd.BUF,'\n');

        if (t != NULL){
            mv = t-fd.BUF+1;
            strncpy(buf,fd.BUF, mv);
            strcpy(fd.BUF,fd.BUF+mv);
            return strlen(buf);
        }
        if (ret <= 0) {

            if (strlen(fd.BUF) == 0){
                return ret;
            }
            strcpy(buf, fd.BUF);
            strcpy(fd.BUF,fd.BUF+strlen(buf));
            return strlen(buf);
        }
    }
}

The other one the actual barber code (and also the customer one, not including that one since it would be too long)
void* holic(void* arg){

    if(global_data->child_count>0){
        close(comPipe[1]);
    }
    log_msg(LOG_INFO, "Getting to work..");

    msg m;
    char l[256];
    int val_check = -1;
    int cut_time = 0;

    global_data->customer_count = 0;

    while(1){

        sem_getvalue(sem_customers, &val_check);
        if (val_check==0){
            log_msg(LOG_INFO,"Sleeping..");
        }

        sem_wait(sem_customers);

        log_msg(LOG_INFO, "Woke up, start cutting..");
        global_data->customer_count -= 1;

        sem_post(sem_barber);

        bzero(l,sizeof(l));
        bzero(m.text, sizeof(m.text));
        log_msg(LOG_INFO, "barber before read %d", fd_pipe.fd);

        int tmp = read(comPipe[0], l, sizeof(l));
        l[tmp] = '\0';
        //wait_for_message(fd_pipe,l,&m,'A', AI_Zakazka);

        sscanf(l, "Cut me for %d seconds", &cut_time);
        global_data->chairs[global_data->last_chair] = 0;
        log_msg(LOG_INFO, "Cutting hair, customer on chair %d, duration %d sec.",global_data->last_chair, cut_time);

        sleep(cut_time);
        sem_post(sem_cutting);

        bzero(l,sizeof(l));
        bzero(m.text, sizeof(m.text));

        wait_for_message(fd_pipe,l,&m,'A', AI_Nashledanou);
        log_msg(LOG_INFO, "Goodbye.");

    }
    if (global_data->child_count>0){
        close(comPipe[0]);
    }
}

Thanks for every input!

readline

buf is a pointer. sizeof(buf) is either 8 or 4, depending on the architecture. bzero(buf,sizeof(buf)); only clears 8 (or 4) bytes of the buffer.

Similarly, sizeof(strlen(fd.BUF)) is equal to sizeof(int), and 256 - sizeof(strlen(fd.BUF) always evaluates to 252, regardless of the fd.BUF contents. Doesn't look right, and may lead to a buffer overrun.

Looking for '\n' in fd.BUF may degrade the performance. Looking for it in temp would be faster (because temp is smaller).

I don't see why do you need temp at all. It only introduces an extra copy. You may read directly to fd.BUF.

strcpy(fd.BUF,fd.BUF+mv) is very dangerous, and technically introduces an undefined behaviour: strcpy is declared as
  cher * stpcpy(char * dst, const char * src);

The const states a contract, that the source string is not modified. You invocation violates the contract.


Scrabble score calculator in Java Please review my code as I'm wondering if there is a better way. Here is the question I'm trying to solve:

  Scrabble Score

  Given a word, compute the scrabble score for that word.

  Letter Values

  You'll need these:

```plain
Letter                           Value
A, E, I, O, U, L, N, R, S, T       1
D, G                               2
B, C, M, P                         3
F, H, V, W, Y                      4
K                                  5
J, X                               8
Q, Z                               10
```

  Examples

  "cabbage" should be scored as worth 14 points:

  3 points for C
  1 point for A, twice
  3 points for B, twice
  2 points for G
  1 point for E

  And to total:

  3 + 2*1 + 2*3 + 2 + 1
  = 3 + 2 + 6 + 3
  = 5 + 9
  = 14

  Extensions

  You can play a double or a triple letter.
  You can play a double or a triple word.

Here's my answer:

import java.util.HashMap;
import java.util.Map;

class Scrabble {

    private String word;

    Scrabble(String word) {
        this.word = word;
    }

    int getScore() {

        Map<Character, Integer> lettersMap = new HashMap<>();
        String lettersCap = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        for (int i = 0; i < lettersCap.length(); i++) {
            if (lettersCap.charAt(i) == 'A' || lettersCap.charAt(i) == 'E' ||
                    lettersCap.charAt(i) == 'I' || lettersCap.charAt(i) == 'O' ||
                    lettersCap.charAt(i) == 'O' || lettersCap.charAt(i) == 'U' ||
                    lettersCap.charAt(i) == 'L' || lettersCap.charAt(i) == 'N' ||
                    lettersCap.charAt(i) == 'R' || lettersCap.charAt(i) == 'S' ||
                    lettersCap.charAt(i) == 'T') {

                lettersMap.put(lettersCap.charAt(i), 1);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 1);
            }

            if (lettersCap.charAt(i) == 'D' || lettersCap.charAt(i) == 'G') {
                lettersMap.put(lettersCap.charAt(i), 2);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 2);
            }

            if (lettersCap.charAt(i) == 'B' || lettersCap.charAt(i) == 'C' ||
                    lettersCap.charAt(i) == 'M' || lettersCap.charAt(i) == 'P') {
                lettersMap.put(lettersCap.charAt(i), 3);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 3);
            }

            if (lettersCap.charAt(i) == 'F' || lettersCap.charAt(i) == 'H' ||
                    lettersCap.charAt(i) == 'V' || lettersCap.charAt(i) == 'W' ||
                    lettersCap.charAt(i) == 'Y') {
                lettersMap.put(lettersCap.charAt(i), 4);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 4);
            }

            if (lettersCap.charAt(i) == 'K') {
                lettersMap.put(lettersCap.charAt(i), 5);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 5);
            }

            if (lettersCap.charAt(i) == 'J' || lettersCap.charAt(i) == 'X') {
                lettersMap.put(lettersCap.charAt(i), 8);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 8);
            }

            if (lettersCap.charAt(i) == 'Q' || lettersCap.charAt(i) == 'Z') {
                lettersMap.put(lettersCap.charAt(i), 10);
                lettersMap.put(lettersCap.toLowerCase().charAt(i), 10);
            }

        }

        int totalValue = 0;

        for (int j = 0; j < word.length(); j++) {

            totalValue += lettersMap.get(word.charAt(j));
        }

        return totalValue;
    }

}

First of all, you should probably create lettersMap from your constructor. You don't need to create it again every time you want to get score for a word.

There are various ways to make the code shorter. The simplest method is to define the scores as an array, in the same order as the letters:

int[] letterScore = {1, 3, 3, 2 ... 4, 10};

Then your whole for-cycle gets reduced to

for (int i = 0; i < lettersCap.length(); i++) {
    lettersMap.put(lettersCap.charAt(i), letterScore[i]);
    lettersMap.put(lettersCap.toLowerCase().charAt(i), letterScore[i]);
}

However, it will also make the code less readable.

You could also define every part separately:

char[] score1letters = {'A', 'E', 'I', 'O', … 'T'};
char[] score2letters = {'D', 'G'};
...
char[] score10letters = {'Q', 'Z'}

and for every such array:

for (int i = 0; i < score1letters.length; i++) {
    lettersMap.put(lettersCap.charAt(i), 1);
    lettersMap.put(lettersCap.toLowerCase().charAt(i), 1);
}

To be honest, the most readable version will probably be:

private static final Map<Character, Integer> lettersMap;
static {
    lettersMap = new HashMap<Character, Integer>();
    lettersMap.put('A', 1);
    lettersMap.put('B', 3);
    lettersMap.put('C', 3);
    lettersMap.put('D', 2);
    ...
    lettersMap.put('Y', 4);
    lettersMap.put('Z', 10);
}

To put lowercase chars, you can either get all the keys at the end and copy their values with lowercased key, or, you can leave only uppercase letters there and instead convert the word to uppercase before calculating its score.