Front running in Bitcoin – Bitcoin Stack Exchange


Your privacy


By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.




python – Employee directory – Code Review Stack Exchange

Starting with the last line:

menu()

Standard practice is to put this in a “main guard”, so that the file is usable from other programs:

if __name__ == '__main__':
    menu()

This bit looks fragile:

    key = str("0"*(6-len(str(x)))) + str(x)

There’s an assumption there that all employee ids are 6 digits (and that’s a convoluted way to format – much simpler would be key = f'{x:06u}').


Recursively calling menu() as the last action of each user function means that we constantly recurse into that function. Simply looping is more memory-efficient.


        os.system("clear")

That’s risky. We’re using whatever PATH we inherited, which might not include a clear command – or worse, it might include one that does something completely unexpected.


What’s the reset() function for? It seems to replace dict with a copy of itself, which seems like a waste of electricity.


if selection == "1":
    ⋮
if selection == "2":
    ⋮
if selection == "3":
    ⋮
if selection == "4":
    ⋮
if selection == "5":
    ⋮

This kind of switch/case is normally represented in Python using an action dictionary. If you really want to use if, it’s better to use elif to skip the conditions following the match.


for x in range(1, len(dict)+1):
    key = list(dict.keys())(x-1)

Why offset everything by 1? We could as easily write for x in range(0, len(dict) and then simply use x rather than x-1. But in any case for x in range() is a code smell; here we just want to iterate over all of dict‘s elements:

for key,value in dict:
    print(f" Name: {value(1)} {value(2)}n Position: {value(0)}n Employee ID: {key} n")

This is a partial review; I ran out of time here.

Minesweeper in haskell – Code Review Stack Exchange

I have recently been learning Haskell, and wrote a minesweeper project as an exercise. Here is link to the project.

Basically the code is separated into two parts, the pure part (no monads) and impure part (deals with random and IO). Since I’m pretty new, I’m a little iffy about the whole setup. Any advice would be appreciated.

{-# LANGUAGE LambdaCase #-}
module Game where

import Data.List
import Data.Maybe
import Data.List.Split
import Control.Monad.Random
import Control.Monad.IO.Class
import Control.Monad.Reader

data Square = Square Bool SquareStatus | NumberedSquare Int
data SquareStatus = Untouched | LostMine | Flagged
data Pos = Pos Int Int deriving (Eq)
data Env = Env {
  getInitPos :: Pos,
  getWidth :: Int,
  getHeight :: Int,
  getNumMines :: Int
}

type Board = ((Square))
type Game a = ReaderT Env IO a

instance Show Square where
  show (Square _ Untouched) = "."
  show (Square _ LostMine) = "x"
  show (Square _ Flagged) = "f"
  show (NumberedSquare num) = if num > 0 then show num else " "

infixl 6 |+|
Pos a b |+| Pos c d = Pos (a+c) (b+d)

---------------
-- Game Control
---------------
play :: Int -> Int -> Int -> IO ()
play w h numMines = do
  initPos <- readInput
  board <- runReaderT createRandomBoard $ Env initPos w h numMines
  play' board initPos

play' :: Board -> Pos -> IO ()
play' board initPos = case expand board (initPos) of
    Just nextBoard -> do 
      printBoard nextBoard
      if checkWin nextBoard then 
        print "You won!"
      else do
        nextPos <- readInput
        play' nextBoard nextPos
    Nothing -> do
      print "You Lost :("
      printBoard $ markBoard board

readInput :: IO Pos
readInput = do
  pos <- do
    putStrLn "Make a move: (Format Int Int)"
    getLine
  let (initX, initY) = splitOn " " pos
  return $ Pos (read initX - 1) (read initY - 1)

--------------
--Impure Stuff
--------------
createRandomBoard :: Game Board
createRandomBoard = do
  width <- asks getWidth
  height <- asks getHeight
  randomLayout <- randMines
  let field = take height $ chunksOf width $ genField randomLayout $ width * height
  lift $ return field

randMines :: Game (Int)
randMines = do
  width <- asks getWidth
  height <- asks getHeight
  pos <- asks getInitPos
  n <- asks getNumMines
  randomSample n $ delete (posToIndex pos width height) (0..width*height-1)

randomSample :: Int -> (a) -> Game (a)
randomSample 0 list = pure ()
randomSample k list = do
  i <- getRandomR (0, length list - 1)
  let (a, xs) = splitAt i list
  l <- if not (null xs) then randomSample (k-1) (a ++ tail xs) else lift $ return ()
  pure $ if not (null xs) then head xs : l else l

----------------
--Pure Functions
----------------
genField :: (Int) -> Int -> (Square)
genField mines = genField' (sort mines) 0
  where
  genField' () index size = replicate (size - index) (Square False Untouched)
  genField' mines@(x:xs) index size
    | x == index = Square True Untouched : genField' xs (index+1) size
    | otherwise = Square False Untouched : genField' mines (index+1) size

getSquare :: Board -> Pos -> Maybe Square
getSquare b (Pos x y)
  | x >= length b || x < 0 = Nothing
  | y >= length (head b) || y < 0 = Nothing
  | otherwise = Just (b !! x !! y)

getNearMines :: Board -> Pos -> Int
getNearMines b pos =
  let 
    d = (-1, 0, 1)
    dirs = (|+|) <$> (Pos a b| a <- d, b <- d) <*> (pos)
  in
    foldl (acc p -> case getSquare b p of
                       Just (Square True _) -> acc + 1
                       _ -> acc) 0 dirs
  
getExpansions :: Board -> Pos -> (Pos)
getExpansions b pos =
  case getSquare b pos of
    Nothing -> ()
    Just (Square True _) -> ()
    Just _ -> expansions
  where
    isZero = getNearMines b pos == 0
    ds = if isZero then
            (Pos a b | a <- (-1, 0, 1), b <- (-1, 0, 1))
          else
            (Pos a b | (a,b) <- ((-1, 0), (0, -1), (1, 0), (0, 1), (0, 0)))
    dirs = (|+|) <$> ds <*> (pos)
    bounded_dirs = filter ((Pos x y) -> x >= 0 && y >= 0) dirs
    filtered_dirs = if isZero then 
                      bounded_dirs
                    else
                      filter (n -> n == pos || getNearMines b n == 0) bounded_dirs
    expansions = foldl (acc p -> case getSquare b p of
                        Just s@(Square False Untouched) -> p : acc
                        _ -> acc) () filtered_dirs

expand :: Board -> (Pos) -> Maybe Board
expand b p = do
  let expansions = concat $ mapMaybe (expand' b) p
  let newboard = foldr ((ri, row) r ->
                  foldr ((ci, s) c ->
                    if Pos ri ci `elem` expansions then
                      NumberedSquare (getNearMines b $ Pos ri ci) : c
                    else 
                      s : c
                  ) () (zip (0..) row) : r
                ) () (zip (0..) b)
  let removeCur = filter (`notElem` p) expansions
  if not $ lost b p then
    if null removeCur then 
      return newboard 
    else 
      expand newboard removeCur
  else
    Nothing
  where
    expand' :: Board -> Pos -> Maybe (Pos)
    expand' b' p' =
      case getSquare b' p' of
        Nothing -> Nothing
        Just (Square True _ ) -> Nothing
        _ -> Just (getExpansions b' p')

    lost :: Board -> (Pos) -> Bool
    lost _ () = False
    lost b' (x:xs) =
      case getSquare b' x of
        Just (Square True _) -> True
        _ -> lost b' xs

checkWin :: Board -> Bool
checkWin b = 
  all (==True) $ 
  fmap (all (==True) . 
    fmap (case
            Square False Untouched -> False
            _ -> True)) b

-----------
--Utilities
-----------
indexToPos :: Int -> Int -> Int -> Pos
indexToPos index w h = Pos (mod index w) (index `div` w)

posToIndex :: Pos -> Int -> Int -> Int
posToIndex (Pos x y) w h = y * w + x

printBoard :: Board -> IO ()
printBoard b = do
  let width = length $ head b
  putStrLn $ replicate (width * 2) '-'
  mapM_ (putStrLn . unwords . fmap show) b
  putStrLn $ replicate (length b * 2) '-'

markBoard :: Board -> Board
markBoard b =
  foldr ((ri, row) r ->
    foldr ((ci, s) c ->
      case s of
        Square False _ -> NumberedSquare (getNearMines b $ Pos ri ci) : c
        Square True _ -> Square True LostMine : c
        _ -> s : c
    ) () (zip (0..) row) : r
  ) () (zip (0..) b)

parseBoard :: (Char) -> Board
parseBoard text = 
  fmap charToSquare <$> chunksOf 5 text
  where 
    charToSquare c
      | c == '*' = Square True Untouched
      | otherwise = Square False Untouched

Yammer tenant tenant Migration – SharePoint Stack Exchange


Your privacy


By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.




PostgreSQL query performance issue – Database Administrators Stack Exchange

We are sometimes getting poor performance (~14s) when using the following query (PostgreSQL 9.6) to fetch rows from the table items whose ID is present in the table items_categories:

SELECT items.*
FROM items 
WHERE EXISTS (
    SELECT item_id 
    FROM items_categories 
    WHERE item_id = items.id  AND category_id = 626 
) 
AND items.active = TRUE
-- possibly some others "AND" here to use more filters on "items", but not considered for this question
ORDER BY modified_at DESC 
LIMIT 10

Relevant parts of our schema:

                              Table "public.items"
           Column      |       Type        |                     Modifiers
-----------------------+-------------------+----------------------------------------------------
 id                    | integer           | not null default nextval('items_id_seq'::regclass)
 active                | boolean           | default true
 modified_at           | timestamp without time zone | default now()
Indexes:
    "items_pkey" PRIMARY KEY, btree (id)
    "active_idx" btree (active)
    "aggregate_idx" btree (id)
    "items_modified_at_idx" btree (modified_at)


  Table "public.items_categories"
   Column    |  Type   | Modifiers
-------------+---------+-----------
 item_id     | integer | not null
 category_id | integer | not null
Indexes:
    "unique_cat_item_assoc" UNIQUE CONSTRAINT, btree (item_id, category_id)
    "items_categories_1_idx" btree (category_id)
    "items_categories_2_idx" btree (item_id)
Foreign-key constraints:
    "items_categories_category_id_fkey" FOREIGN KEY (category_id) REFERENCES categories(id)
    "items_categories_item_id_fkey" FOREIGN KEY (item_id) REFERENCES items(id)

The table items contains ~2 M rows, and the table items_categories contains ~4 M rows

When we ask for 10 items (i.e. LIMIT 10 at the end of the above query) and 10 or more rows match in items_categories, the performance is good (~10ms), but when we ask for 10 items and less than 10 rows match in items_categories, then the query takes ~14s because it’s doing an index scan on items.modified_at to look at each 2 M rows.

Query plan when less than 10 rows match in items_categories (poor performance):

Limit  (cost=0.86..11696.68 rows=10 width=1797) (actual time=168.376..14484.854 rows=7 loops=1)
  ->  Nested Loop Semi Join  (cost=0.86..2746178.23 rows=2348 width=1797) (actual time=168.376..14484.836 rows=7 loops=1)
        ->  Index Scan Backward using items_modified_at_idx on items  (cost=0.43..1680609.95 rows=2243424 width=1797) (actual time=0.054..7611.300 rows=2251395 loops=1)
              Filter: active
              Rows Removed by Filter: 2467
        ->  Index Only Scan using unique_cat_item_assoc on items_categories  (cost=0.43..0.47 rows=1 width=4) (actual time=0.003..0.003 rows=0 loops=2251395)
              Index Cond: ((item_id = items.id) AND (category_id = 626))
              Heap Fetches: 7
Planning time: 3.082 ms
Execution time: 14485.057 ms

Query plan when more than 10 rows match in items_categories (good performance):

Limit  (cost=0.86..24.07 rows=10 width=1857) (actual time=3.575..3.757 rows=10 loops=1)
  ->  Nested Loop Semi Join  (cost=0.86..2763459.56 rows=1190819 width=1857) (actual time=3.574..3.752 rows=10 loops=1)
        ->  Index Scan Backward using items_modified_at_idx on items  (cost=0.43..1684408.22 rows=2246967 width=1857) (actual time=0.013..2.205 rows=751 loops=1)
              Filter: active
        ->  Index Only Scan using unique_cat_item_assoc on items_categories  (cost=0.43..0.47 rows=1 width=4) (actual time=0.002..0.002 rows=0 loops=751)
              Index Cond: ((item_id = items.id) AND (category_id = 20))
              Heap Fetches: 10
Planning time: 1.650 ms
Execution time: 3.868 ms

How can we tune this query to handle both situations? (i.e. good performances no matter how many rows of items_categories match).

I have a POC working where I first count the number of matching rows in items_categories (separate query) then if the number is low I use a CTE to work on a subset of items instead of all its rows, but it’s really a dirty temporary hack IMO…

Thank you!

Google Sheet filter issue – Web Applications Stack Exchange

I have a Google Sheet that collects responses from a Google Form, this collects contact details and preferred location. I shall call this workbook Feeder.

In a second Google Workbook (called placements) the data from the feeder sheet is imported into a sheet via =importrange. In addition, this workbook has a series of sheets for each preferred location. These sheets display the records for each preferred location using =filter (on the data that has been imported via =importrange).

Additional information is typed in associated columns for each record in the preferred location sheets.

My issue is if a new entry is made in the feeder worksheet – it will populate in the correct location sheet (which is sorted by last name) – but will misplace the “additional information” that has been typed for the existing records.

Any help would be really grateful received.

Fizzbuzz in C lang – Code Review Stack Exchange

This is the first time I have recoded in C for several years and I would like to know how clean my code is.

#include <stdio.h>
#include <string.h>

#define EXIT_SUCCESS 0

void fizzbuzz(int n) {
    char result(9) = "";  // strlen("fizzbuzz") + 1 == 9
    if (n % 3 == 0) strcat(result, "fizz");
    if (n % 5 == 0) strcat(result, "buzz");
    if (!*result) sprintf(result, "%d", n);
    printf("%sn", result);
}

int main() {
    for (int i = 1; i <= 100; i++) fizzbuzz(i);
    return EXIT_SUCCESS;
}

I know that I could include stdlib so as not to have to define EXIT_SUCCESS myself, but as I only needed this constant, it’s a little clearer and more efficient to do this I think.

Photo Competition 2021-07-26: Music – Photography Stack Exchange

Theme: Music

Either literal (instruments, musicians, performance) or figurative (geometric or natural patterns which evoke the patterns of music).

This theme was suggested by mattdm.

Voting Rules

  • View the submissions sorted by active to give every submitter a fair chance
  • Vote up as many images as you like
  • Please, up votes only! Do NOT vote down your competitors! If you don’t like an image, don’t vote
  • Voting closes on August 9, 2021 at 12:01 AM UTC (00:01 UTC if you prefer a 24-hour time). The winner will be chosen based on votes at that time.

Submission Rules

  1. One photo submission per answer. Up to three (3) entries allowed.
  2. Post only photos taken by yourself or the person with you.
  3. All entries should include:
    • a title for the photo
    • a location and date, if known
    • camera, lens, and exposure settings, if known
    • any other explanatory notes, comments, etc., that you want to include (completely optional)
  4. The submitted image must conform to this site’s content license, Creative Commons Attribution-ShareAlike 4.0 (CC BY-SA 4.0) with attribution required.
  5. Do not use this as a forum for photo critique. Use chat instead, or ask a new question about your image.

Next Contest

Suggest a theme by writing a new answer at the Photo of the Week Theme Ideas thread. Please make sure to check the PotW theme ideas Archive first, to make sure you aren’t recycling a theme.

The highest-voted theme will be the next theme.

Good luck!

PYTHON RUNNING ERRORS – Computer Science Stack Exchange

PYTHON RUNNING ERRORS – Computer Science Stack Exchange

Meetup group 2nd strike – Web Applications Stack Exchange

Meetup group 2nd strike – Web Applications Stack Exchange

DreamProxies - Cheapest USA Elite Private Proxies 100 Cheap USA Private Proxies Buy 200 Cheap USA Private Proxies 400 Best Private Proxies Cheap 1000 USA Private Proxies 2000 USA Private Proxies 5000 Cheap USA Private Proxies ExtraProxies.com - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies ProxiesLive.com Proxies-free.com New Proxy Lists Every Day Proxies123.com Best Quality USA Private Proxies