texts: Last five non-zero digits of a factorial in base b

texts:
This HackerRank problem (based on Project Euler problem 160) says:

  For any \$n\$, let \$f_b(n)\$ be the last five digits before the trailing zeroes in \$n!\$ written in base \$b\$.

  For example,

  \$9! = 362880\$ so \$f_{10}(9)=36288\$
  \$10! = 3628800\$ so \$f_{10}(10)=36288\$
  \$20! = 2432902008176640000\$ so \$f_{10}(20)=17664\$

  Input format

  First line of each file contains two numbers: \$b\$ (base) and \$q\$ (number of queries). \$q\$ lines follow, each with an integer \$n\$ written in base \$b\$.

  Constraints

  \$2 \le b \le 36\$
  \$1 \le q \le 10^5\$
  \$0 \le n \le 10^{18}\$
  Every character in \$n\$ is a valid digit in base \$b\$ (0-9, A-Z for values \$>9\$)

  Output Format

  Output \$q\$ lines. On each line print exactly 5 digits in base \$b\$ - the answer to the \$i\$-th query. If for some \$n\$, \$n!\$ contains fewer than 5 digits, put the corresponding number of leading zeroes before the answer.

I believe the code works:

def treeFactor(low, high):
    if low + 1 < high:
        mid = (high+low) // 2
        return treeFactor(low, mid) * treeFactor(mid + 1, high)
    if low == high:
        return low
    return low * high

def convert(num,b,numerals="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
    return ((num == 0) and numerals[0]) or (convert(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])

def removeZ(ans):
    while ans[-1] == "0":
        ans = ans[:-1]
    return ans[-5:]

b, q = raw_input().split(" ")
b = int(b)
q = int(q)

for _ in xrange(q):
    ans = int(str(raw_input()), 10)
    if ans < 2:
        print "1"
    else:
        ans = treeFactor(1, ans)
        ans = convert(ans, b)
        ans = removeZ(ans)
        k = len(ans)
        if k < 5:
            ans = (5 - k * "0").join(ans)
        print ans

However, it doesn't run fast enough to pass the tests. I changed the factorial method and tried to cut down on str() conversions, using xrange() and so on, but it still isn't efficient enough. Can you see any bottlenecks, or methods that could be improved further (without the use of specialist packages like NumPy).

(on a slight side note, would it be possible to perform the factorial method on numbers without converting them to base 10, while maintaining efficiency?)


texts:
I'm trying to make a REST service using Spring Boot and Spring Data. I have written a query using join and have achieved the required o/p but I'm curious to know if that is a right way of doing it or I can do it with a better approach.

Here is the query using @Query annotation:

@Query("select b.bookId, b.bookName, a.authorId, a.authorName, b.language, "
            + "g.genreId, g.genreName,b.goodReadReviews from Book b, Author a, "
            + "Genre g where b.author=a.authorId and b.genre=g.genreId and "
            + "a.authorId=?1 and g.genreId=?2")
    List<Object[]> findByAuthorIdAndGenreId(int authorId, int genreId);


texts: Loop through all virtualhost log files and run goaccess on each file

texts:
So I have multiple websites running under apache2 virtualhost - and I wanted to use GoAccess to process the access.log for each site.

The directory structure is like so:

/home/www/site1/html
/home/www/site1/log
/home/www/site1/stats

/home/www/site2/html
/home/www/site2/log
/home/www/site2/stats

Some sites contain two different access.log files -

ssl.access.log for SSL

access.log for non-SSL

These are located in the /log directory of each site

I wanted a cronjob to run every night to process the stats with GoAccess, but I didn't want to write multiple lines of nearly duplicate commands.

I've never written a bash script before, and so I do not know if this is the most efficient way of doing things.

Each report that is generated, needs the month/year in it, so each night it gets overwritten with that months latest stats.

the reports are outputted in the stats directory of each site, in the following format

yyyy-mm.html
sslyyyy-mm.html

The Script

#!/bin/bash

# find all log files which match ess.log
LOG_FILES="/home/www/*/log/*ess.log"

# set the date format
NOW=$(date +"%Y-%m")

# loop through each log file
for f in $LOG_FILES
do

  # drop back from /home/www/site/log to /home/www/site
  path=`dirname $f`
  path=`dirname $path`

  # get the current log filename
  filename=`basename $f`

  # if /home/www/site/stats does not exist - create it
  if [ ! -d "$path/stats" ]; then
    mkdir "$path/stats"
  fi

 # get the first part of the log filename
 prefix=(${filename//./ })

 # if its equal to access, then it's not ssl log, so remove the prefix
 if [ $prefix == 'access' ]; then
   prefix=''
 fi

  # run the goaccess process
  goaccess -f $f --date-format=%d/%b/%Y --log-format='%h %^[%d:%^] "%r" %s %b "%R" "%u"' -a > "$path/stats/$prefix$NOW.html"

done

I know this is a fairly simple task, but as I have not any experience specifically in this it would be great to know where I could improve this.


texts:
I want to store image (details) in my database, and want for each image the possibility to have from 1 to N versions.

I want a single file (src) to be associated with a single version. There must not be more than one version for an single image with the same dimensions and format (no point having a version with 1920x1080 jpg and 1920x1080 jpg, whereas 1920x1080 jpg and 1920x1080 png would be ok).

I have come out with the following tables :

-- ---------------------------------------------------------------------------------
-- IMAGE TABLE
-- ---------------------------------------------------------------------------------

DROP TABLE IF EXISTS "image_e";

CREATE TABLE IF NOT EXISTS "image_e"
(
    "id"    int unsigned NOT NULL AUTO_INCREMENT,
    "title" varchar(32)  NOT NULL,
    "alt"   varchar(16)  NOT NULL,

    PRIMARY KEY ("id")

)   ENGINE = MyISAM DEFAULT CHARSET = utf8 COLLATE = utf8_bin;

-- ---------------------------------------------------------------------------------
-- IMAGE VERSION TABLE
-- ---------------------------------------------------------------------------------

DROP TABLE IF EXISTS "image_version_e";

CREATE TABLE IF NOT EXISTS "image_version_e"
(
    "id"      int unsigned NOT NULL AUTO_INCREMENT,
    "imageId" int unsigned NOT NULL,
    "format"  varchar(4)   NOT NULL,
    "size"    int unsigned NOT NULL,
    "width"   int unsigned NOT NULL,
    "height"  int unsigned NOT NULL,
    "src"     varchar(64)  NOT NULL,

    PRIMARY KEY ("id")

)   ENGINE = MyISAM DEFAULT CHARSET = utf8 COLLATE = utf8_bin;

ALTER TABLE "image_version_e" ADD UNIQUE KEY ("imageId", "format", "width", "height");
ALTER TABLE "image_version_e" ADD UNIQUE KEY ("src");

image_version_e.imageId references image_e.id

This version is MyISAM, i will make a second version for InnoDB with this foreign key.

I don't care about insert / update / delete speed, but i do care about select speed as i will use this for a wallpaper gallery with a search function.

Are my unique keys done correctly ? Isn't it too much or not enough ? Is the schema well thought ? Is there a way to optimize it ?

Thanks for reading and for your help :)


texts:
I came across a problem in my NodeJS app, which I solved by creating a method called groupBy. The purpose of this method is simple: take an array, and a function which will select a field from an element in the array. Each element in the array should then be grouped based on this field and returned as an object with the key being the value of the field selected.

var groupBy = function(arr, keySelector) {
    var map = {};
    arr.map(function(element) {
        var key = keySelector(element);
        if(key === undefined)
            throw 'undefined key!';

        map[key] = map[key] || [];
        map[key].push(element);
    });
    return map;
};

It works perfectly, but could it be improved in any way?


texts:
Per Learn You a Haskell, I implemented a simple command-line program, Todo, that accepts 1 of 3 arguments: view or add or delete.

Please review my code for Haskell idioms & overall quality.

-- view, add and delete tasks
-- borrows delete from previous LYAH exercise
import System.Environment
import System.Directory
import System.IO
import Data.List

data Action = Add | View | Delete

main = do
    args <- getArgs
    progName <- getProgName
    let maybeAction = validArgs args
    executeTodo maybeAction

executeTodo :: (Maybe Action) -> IO ()
executeTodo (Just Add)    = addTodo
executeTodo (Just View)   = viewTodo
executeTodo (Just Delete) = deleteTodo
executeTodo Nothing       = print "invalid user input"

viewTodo :: IO ()
viewTodo = do
    withFile "todo_file.txt" ReadMode (\handle -> do
        contents <- hGetContents handle
        putStr contents)
    return ()

addTodo :: IO ()
addTodo = do
   todoItem <- getLine
   appendFile "todo_file.txt" (todoItem ++ "\n")

deleteTodo :: IO ()
deleteTodo = do
    handle <- openFile "todo_file.txt" ReadMode
    (tempName, tempHandle) <- openTempFile "." "temp"
    contents <- hGetContents handle
    let todoTasks = lines contents
        numberedTasks = zipWith (\n line -> show n ++ " - " ++ line) [0..] todoTasks
    putStrLn "These are your TO-DO items:"
    putStr $ unlines numberedTasks
    putStrLn "Which one do you want to delete?"
    numberString <- getLine
    let number = read numberString
        newTodoItems = delete (todoTasks !! number) todoTasks
    hPutStr tempHandle $ unlines newTodoItems
    hClose handle
    hClose tempHandle
    removeFile "todo_file.txt"
    renameFile tempName "todo_file.txt"

validArgs :: [String] -> Maybe Action
validArgs (x:[]) = isValidAction x
validArgs _      = Nothing

isValidAction :: String -> Maybe Action
isValidAction x
  | x == "view"   = Just View
  | x == "add"    = Just Add
  | x == "delete" = Just Delete
  | otherwise     = Nothing


texts:
I had written with very few PHP skills a conjugator script.
It was not good, so I decided to start it from scratch with a help from a friend. I'm using the code formatter from eclipse.

Now I need your reviews and improvement tips.

I know all my long arrays with the all verbs and many more long arrays aren't a good way,but I have no clue how to put them all in a database and how then to use them.

Now a specific question:

word_stem.php In this file, the script gets the correct word_stem to building in conjugate.php function in the line:

Compiling a conjugated verb

$conjugated_verb = word_stem($infinitiveVerb, $person, $tense, $mood) . ending($person, $tense, $mood, $endingwith, $exceptionmodel, $infinitiveVerb);

They are many exception rules for many verb groups.
That's why I had to writte somethings long and complicated if conditions to find the needed changed mood-tense-person combinations, which should use the correct word_stem.

Excerpt 1 from word_stem()

if (in_array($exceptionmodel->getValue(), [
    ExceptionModel::Eler_Ele,
    ExceptionModel::Eter_Ete
]) && (($mood->getValue() === Mood::Indicatif && $tense->getValue() === Tense::Present && in_array($person->getValue(), [
    Person::FirstPersonSingular,
    Person::SecondPersonSingular,
    Person::ThirdPersonSingular,
    Person::ThirdPersonPlural
]) || $tense->getValue() === Tense::Futur) || ($mood->getValue() === Mood::Subjonctif && $tense->getValue() === Tense::Present && in_array($person->getValue(), [
    Person::FirstPersonSingular,
    Person::SecondPersonSingular,
    Person::ThirdPersonSingular,
    Person::ThirdPersonPlural
])) || ($mood->getValue() === Mood::Conditionnel && $tense->getValue() === Tense::Present) || ($mood->getValue() === Mood::Imperatif && $tense->getValue() === Tense::Present && $person->getValue() === Person::SecondPersonSingular))) {
    $word_stem = substr_replace($word_stem, 'è', - 2, 1);
}

Excerpt 2

if ($exceptionmodel->getValue() === ExceptionModel::VALOIR && (($mood->getValue() === Mood::Indicatif && $tense->getValue() === Tense::Present && in_array($person->getValue(), [
    Person::FirstPersonSingular,
    Person::SecondPersonSingular,
    Person::ThirdPersonSingular
]) || $tense->getValue() === Tense::Futur) || ($mood->getValue() === Mood::Conditionnel && $tense->getValue() === Tense::Present) || (($mood->getValue() === Mood::Imperatif && $tense->getValue() === Tense::Present && $person->getValue() === Person::SecondPersonSingular)))) {
    $word_stem = word_stem_length($infinitiveVerb, 4) . 'u';
}
if ($exceptionmodel->getValue() === ExceptionModel::VALOIR && ($mood->getValue() === Mood::Subjonctif && $tense->getValue() === Tense::Present && in_array($person->getValue(), [
    Person::FirstPersonSingular,
    Person::SecondPersonSingular,
    Person::ThirdPersonSingular,
    Person::ThirdPersonPlural
]))) {
    $word_stem = word_stem_length($infinitiveVerb, 4) . 'ill';
}

Sometimes I need in one if condition all persons from a tense in a mood and sometimes only some parts froma tense in a mood.

So looks for example a exception array for one Person in one time and mood.

$endings[Mood::Indicatif][Tense::Present][Person::FirstPersonSingular]

Feel free, to have a look at the other files and give me please tips.
You can also become a constributor in this project.

I will use the script for my german speaking learning website.


texts: Add timeline link to questions and answers on Stack Exchange

texts:
The following script is meant to be a user script, but it should work on the console. It takes the id of the question and adds the corresponding /posts/id/timeline link to the post-menu element, just besides others. It's meant to not have problem with other scripts. The same as above for the answers, just that in this case it should loop through all the answers and add its corresponding timeline link.

let question = document.getElementById("question");
let qid = question.dataset.questionid;
if (qid) {
    let span = document.createElement("span");
    let alink = document.createElement("a");
    alink.class = "userscript-timeline";
    alink.href = "/posts/" + Number(qid) + "/timeline";
    alink.title = "timeline for this question";
    alink.textContent = "timeline";
    span.appendChild(alink);
    question.getElementsByClassName("post-menu")[0].appendChild(span);
}
let answers = document.getElementsByClassName("answer");
if (answers) {
    for (let i = 0; i < answers.length; i += 1) {
        let aid = answers[i].dataset.answerid;
        let answer = document.getElementById("answer-" + aid);
        let span = document.createElement("span");
        let alink = document.createElement("a");
        alink.class = "userscript-timeline";
        alink.href = "/posts/" + Number(aid) + "/timeline";
        alink.title = "timeline for this answer";
        alink.textContent = "timeline";
        span.appendChild(alink);
        answer.getElementsByClassName("post-menu")[0].appendChild(span);
    }
}

I'm not sure if it's convenient to abstract the logic that create and adds the link, as I'm afraid it could introduce needless complexity. My naming sense could be better.


texts: Emulate Java 8 predicate chaining in JavaScript

texts:
I am trying to emulate Java 8's predicate chaining in JavaScript.
So far it works, but is there a more efficient way to write this? Furthermore, I had to create get and run methods to return the predicate so that is can be passed into a filter function.
Update: I added an _unwrap method to unwrap the internal predicate function so that you can pass a Predicate to another Predicate.

const records = [
  { name: 'Andrew' , age: 21, position: 'Developer' },
  { name: 'Bill'   , age: 26, position: 'Developer' },
  { name: 'Chris'  , age: 45, position: 'Manager'   },
  { name: 'Dave'   , age: 30, position: 'Developer' },
  { name: 'Eric'   , age: 32, position: 'Manager'   }
];

class Predicate {
  constructor(predicateFn) {
    this.predicateFn = this._unwrap(predicateFn);
  }
  /* @private */ _unwrap(predicateFn) {
    return predicateFn instanceof Predicate ? predicateFn.get() : predicateFn;
  }
  and(predicateFn) {
    return new Predicate((item) => this.predicateFn(item) && this._unwrap(predicateFn)(item));
  }
  or(predicateFn) {
    return new Predicate((item) => this.predicateFn(item) || this._unwrap(predicateFn)(item));
  }
  not() {
    return new Predicate((item) => !this.predicateFn(item));
  }
  get() {
    return this.predicateFn;
  }
  run(arr) {
    return arr.filter(this.predicateFn);
  }
}

const display = ({ name, age, position }) => `${name} (${age}) [${position}]`;

const ageOver21AndDeveloper = new Predicate(({ age }) => age > 21)
  .and(({ position }) => position === 'Developer');

console.log(ageOver21AndDeveloper.run(records).map(display).join(', '));

const billOrManager = new Predicate(({ name }) => name === 'Bill')
  .or(({ position }) => position === 'Manager');

console.log(billOrManager.run(records).map(display).join(', '));

const notUnder30 = new Predicate(({ age }) => age < 30).not();

console.log(notUnder30.run(records).map(display).join(', '));

// Pass predicate object to another predicate.
console.log(billOrManager.or(ageOver21AndDeveloper).run(records).map(display).join(', '));
.as-console-wrapper { top: 0; max-height: 100% !important; }


texts:
Suppose there is a huge bitmap, huge_bitmap, in the drawable-nodpi folder. I want to create a custom view with huge_bitmap as its background:

public class CustomView extends View {

    private Bitmap mBackground;

    public CustomView(Context context) {
        super(context);
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mBackground = decodeAndResizeFromResource(getResources(),
            R.drawable.huge_bitmap, getMeasuredWidth(), getMeasuredHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(mBackground, 0, 0, mPaint);
        super.onDraw(canvas);
    }

}

where decodeAndResizeFromResource method subsamples the image and loads a smaller, scaled version into memory.

This works fine. However, onMeasure will often be invoked more than once. Lint warns about this:

  Avoid object allocations during draw/layout operations (preallocate and reuse instead)

Allocating objects in methods such as onMeasure, onLayout, onSizeChanged and onDraw should therefore be avoided.

How do I correctly fix the example above?

I obviously don’t want to preallocate the bitmap (assume it will throw an OutOfMemoryError). Since I need the view’s measured width and height in order to subsample/scale accordingly, I need to load the bitmap after measuring.

Here are two possible workarounds:

@Override
protected void onDraw(Canvas canvas) {
    if (mBackground == null) {
        mBackground = decodeAndResizeFromResource(getResources(),
            R.drawable.huge_bitmap, getMeasuredWidth(), getMeasuredHeight());
    }
    canvas.drawBitmap(mBackground, 0, 0, mPaint);
    super.onDraw(canvas);
}

or maybe

private int mWidth, mHeight;

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    final int w = getMeasuredWidth();
    final int h = getMeasuredHeight();
    if (mWidth != w || mHeight != h) {
        mBackground = decodeAndResizeFromResource(getResources(),
            R.drawable.huge_bitmap, w, h);
        mWidth = w;
        mHeight = h;
    }
}

but both feel clumsy. What would you recommend?


texts: Are there any problems with this memcpy() implementation?

texts:
I received this question at a C++ programming interview:

void memcpy(char* dst, const char* src, int numBytes)
{
    int* wordDist = (int*)dst;
    int* wordSrc = (int*)src;
    int numWords = numBytes >> 2;
    for (int i = 0; i < numWords; i++)
    {
        *wordDist++ = *wordSrc++;
    }
    int whatisleft = numBytes >> 2 - (numWords );
    dst = (char*)wordDist;
    src = (char*)wordSrc;
    for (int i = 0 ; i <= whatisleft; i++);
    {
        *dst++ = *src++;
    }
}

What are portability issues?
At least 1 syntax error?
Algorithm considerations?

Now I found that this line:

int whatisleft = numBytes >> 2 - (numWords );

is wrong as it doesn't calculates the correct number of bytes left to copy.

The correct one should be:

int numBytesInWord = (numWords << 2 );
int whatisleft = numBytes  - numBytesInWord;

At the end, the copied char array is several characters shorter than the source.


texts: Mapping a file system to a tree structure

texts:
I need to write a very basic file/directory browser. The data structure I'm using is pretty simple - a Node with an optional parent and children. Along with the data structure I also need a simple function that will recurse a file system building up the tree of nodes. This is what I have come up with so far and I'd really appreciate any advice as to how I can improve it:

case class Node(name: String, parent: Option[Node]) {
    val children : ListBuffer[Node] = ListBuffer[Node]()

    def addChild(child: Node): Unit = children += child
    def removeChild(child: Node): Unit = children -= child
    def getChildren : Seq[Node] = children.toSeq
}

def getTree: Node = {
    def getChildren(file: File, parent: Node) : Node = {
        val self = Node(file.getName, Some(parent))
        parent.addChild(self)
        if (file.isDirectory) file.listFiles().foreach(child => getChildren(child, self))
        self
    }

    val rootNode = Node("test", Option.empty)
    getChildren(new File("/tmp/test"), rootNode)
}

// simple test
def printNode(node: Node, indent: String = "") : Unit = {
    println(indent + node.name)
    node.children.foreach(printNode(_, indent + "  "))
}

I'm pretty happy with the data structure (although I don't mind changing it) but I'm no so happy with the getTree function. In particular I don't like the fact that it's not tail call recursive and I could end up with quite a large stack ... but maybe I'm worrying about nothing?


texts:
I've updated my text-based terrain generator a lot. Even though I haven't worked on it all that much. I really just want to know, like usual, is there anything I can improve? How can I shorten the code? What can be made more efficient? Yada yada yada...

#!/usr/bin/env python
from random import choice
from os import system, name

class Tiles(object):
    tree = '\033[7;1;32m  \033[0m'
    land = '\033[7;32m  \033[0m'
    sand = '\033[7;1;33m  \033[0m'
    water = '\033[7;1;34m  \033[0m'

class Sizes(object):
    small = 10
    med1 = 20
    med2 = 30
    large = 40

sizes = (
    Sizes.small, Sizes.med1, Sizes.med2, Sizes.large)

tiles = (
    Tiles.land, Tiles.sand, Tiles.tree, Tiles.water)

def generate(world_size):
    system('cls' if name == 'nt' else 'clear')
       for _ in range(world_size):
            print(''.join(choice(tiles) for _ in range(world_size)))

if __name__ == "__main__":
    generate(choice(sizes))

Also, this is python 2.7 I just prefer to use print() over print.


texts: When to use a new variable vs string interpolation?

texts:
I wrote a script that I decided to refactor so I could add functionality to it as my coworkers think of it. I only saved four lines in the effort, but the main change is I removed both methods and reduced the number of called variables in favor of string interpolation/manipulation. Is there a preference for this? Is it better to declare a new variable just to use once, or is it more DRY to just make minor tweaks to the string when you need to use it? For example here is the original code:

$EMBED_HTML = ""

$BASE_URL = ""

$SAMPLE_FLV = ""

def normalize_directory(dir)
  normalized = dir.gsub('\\', '/')
  normalized += '/' unless normalized[-1] == '/'
end

def validate_directory(dir)
  puts "Enter the full directory path of the flv files." unless dir
  dir =  dir || gets.chomp
  dir = normalize_directory(dir)
  until File.directory?(dir) && Dir.glob("#{dir}*.flv") != []
    puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
    dir = $stdin.gets.chomp
    dir = normalize_directory(dir)
  end

  dir
end

def output_html_wrapper(flv_filename, output_folder)
  html_filename = flv_filename.gsub(".flv", ".html")

  html_body = $EMBED_HTML.gsub($SAMPLE_FLV, flv_filename.sub(/[a-z][:]/, ''))
  html_output = File.open(html_filename, "w")
  html_output.write(html_body)
  html_output.close

  link = flv_filename.sub(/[a-z][:]/, '').gsub(".flv", ".html")
  link_list = File.open("#{output_folder}List of Links.txt", "a")
  link_list.write($BASE_URL + link + "\n")
  link_list.close

  puts "#{html_filename} created successfully." if File.exists?(html_filename)
end

folder = ARGV[0].dup unless ARGV.empty?
folder = validate_directory(folder)
flvs = Dir.glob("#{folder}*.flv")
File.delete("#{folder}List of Links.txt") if File.exists?("#{folder}List of Links.txt")
flvs.each { |flv| output_html_wrapper(flv, folder) }

And the new stuff:

flash_folder = ARGV[0].dup unless ARGV.empty?

if !flash_folder
  puts "Enter the full directory path of the flv files."
  flash_folder = gets.chomp
end

flash_folder.gsub!('\\', '/')
flash_folder += '/' unless flash_folder[-1..-1] == '/'
until File.directory?(flash_folder) && Dir.glob("#{flash_folder}*.flv") != []
  puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
  flash_folder = $stdin.gets.chomp
  flash_folder.gsub!('\\', '/')
  flash_folder += '/' unless flash_folder[-1..-1] == '/'
end

flash_files = Dir.glob("#{flash_folder}*.flv")

File.delete("#{flash_folder}List of Links.txt") if File.exists?("#{flash_folder}List of Links.txt")

flash_files.each do |flv|
  html_output = File.open("#{flv.gsub(".flv", ".html")}", "w")
    html_output.write("#{embed_code.gsub("sample.flv", flv.slice(7..flv.length))}")
  html_output.close
  link_list = File.open("#{flash_folder}List of Links.txt", "a")
    link_list.write("#{flash_url}#{flv.slice(2..flv.length).gsub(".flv", ".html")}\n")
  link_list.close
end

puts "Finished."


texts: Python - Predicting the probability of 6 Heads or Tails in a row from a set sample size

texts:
I'm wondering whether there is a way to make this even more efficient or reduce the number of variables.
import random
numberOfStreaks = 0
results = []
head_streak = ['H'] * 6
tail_streak = ['T'] * 6
sample_size = 1000000
for i, experimentNumber in enumerate(range(sample_size)):
    # Code that creates a list of 100 'heads' or 'tails' values.
    results.append(random.choice(('H', 'T')))

    # Code that checks if there is a streak of 6 heads or tails in a row.
    try:
        temp = results[i-5:]
        if temp == head_streak or temp == tail_streak:
            numberOfStreaks += 1
    except:
        pass

print('Chance of streak: %s%%' % (numberOfStreaks / sample_size))


texts: SQLAlchemy - InsertFromSelect with columns support

texts:
In SQL there is no way to do an "INSERT... SELECT". If you want to do it without using raw SQL in several places of your code you can create custom SQL compilation.

There is an example about how to do "INSERT...SELECT" in SA documentation. This example doesn't support column in the INSERT part of the sentence, some thing like: INSERT into table(col1, col2)...".

I've modified the example to that, this support table ("INSERT INTO table (SELECT...)") or columns ("INSERT INTO table (col1, col2) (SELECT...)".

Please, have a look an comment :)

from sqlalchemy.sql.expression import Executable, ClauseElement
from sqlalchemy.ext.compiler import compiles

class InsertFromSelect(Executable, ClauseElement):
    def __init__(self, insert_spec, select):
        self.insert_spec = insert_spec
        self.select = select

@compiles(InsertFromSelect)
def visit_insert_from_select(element, compiler, **kw):
    if type(element.insert_spec) == list:
        columns = []
        for column in element.insert_spec:
            if element.insert_spec[0].table != column.table:
                raise Exception("Insert columns must belong to the same table")
            columns.append(compiler.process(column, asfrom=True))

        table = compiler.process(element.insert_spec[0].table)
        columns = ", ".join(columns)

        sql = "INSERT INTO %s (%s) (%s)" % (
                table, columns,
                compiler.process(element.select))

    else:
        sql = "INSERT INTO %s (%s)" % (
                compiler.process(element.insert_spec, asfrom=True),
                compiler.process(element.select))

    return sql

Example of its use with columns:

InsertFromSelect([dst_table.c.col2, dst_table.c.col1], select([src_table.c.col1, src_table.c.col1]))

Example of its use only with a table:

InsertFromSelect(dst_table, select(src_table]))

This works for me, but I want to hear other opinions.


texts: Find the length of minimum sub array with maximum degree in an array

texts:
I tried solving a problem in Hackerrank which is to find the length of minimum sub array with maximum degree in an array.

For example, consider the example {2, 2, 1, 2, 3, 1, 1} the min sub-array length is 4 as 2 has the maximum degree and the smallest sub array which has degree 3 is  {2, 2, 1, 2}

Below is my solution for the problem:

public class FindingMinSubArrayWithDegree {
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int[] arr = new int[n];
    for (int i = 0; i < n; i++) {
        arr[i] = sc.nextInt();
    }
    System.out.println(degreeOfArray(arr));
    sc.close();
}

static int degreeOfArray(int[] arr) {
    HashMap<Integer, Integer> numbersByDegree = new HashMap<Integer, Integer>();
    for (int i = 0; i < arr.length; i++) {
        int degree = numbersByDegree.getOrDefault(arr[i], 0);
        numbersByDegree.put(arr[i], degree + 1);
    }
    List<Map.Entry<Integer, Integer>> sortedEntries = sortByValue(numbersByDegree);
    int maxDegree = sortedEntries.get(0).getValue();

    int[] degreeArr = new int[arr.length] ;
    int minSubArrayLength = arr.length;
    for (Map.Entry<Integer, Integer> entry : sortedEntries) {
        if (entry.getValue() < maxDegree) {
            break;
        }
        for (int i = 0; i < arr.length; i++) {
            if (entry.getKey() == arr[i]) {
                if (i - 1 >= 0)
                    degreeArr[i] = degreeArr[i - 1] + 1;
                else
                    degreeArr[i] = 1;
            } else {
                if (i - 1 >= 0)
                    degreeArr[i] = degreeArr[i - 1];
            }
        }
        boolean startIndexFound = false, endIndexFound = false;
        int startIndex = 0, endIndex = 0;
        for (int i = 0; i < degreeArr.length; i++) {
            if (startIndexFound && endIndexFound)
                break;
            if (!startIndexFound && degreeArr[i] == 1) {
                startIndex = i;
                startIndexFound = true;
            }
            if (!endIndexFound && degreeArr[i] == entry.getValue()) {
                endIndex = i;
                endIndexFound = true;
            }
        }
        if ((endIndex - startIndex) < minSubArrayLength) {
            minSubArrayLength = endIndex - startIndex;
        }
        for (int i = 0; i < degreeArr.length; i++)
            degreeArr[i] = 0;
    }
    return minSubArrayLength + 1;
}

private static <K, V extends Comparable<? super V>> List<Map.Entry<K, V>>
sortByValue(Map<K, V> map) {
    List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
    Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
        public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
            return (o2.getValue()).compareTo( o1.getValue() );
        }
    });
    return list;
}
}

This approach has a worst case running time of O(N ^ 2) for inputs like { 1, 1, 2, 2, 3, 3, 4, 4} .

Can this problem be solved in better runtime and space complexity ? Also It would be good if someone can review my approach and solution


texts:
There is a function which is getting maximum values of each period-length interval in array.
I am trying to optimize this function by performance.

void maximumsT(const std::vector<double> &src, size_t period, std::vector<double> &dst)
{
    dst.resize(src.size());

    for (size_t i = 1; i <= period; ++i) {
        dst[i - 1] = *std::max_element(src.begin(), src.begin() + i);
    }

    for (size_t i = period; i <= src.size(); ++i) {
        dst[i - 1] = *std::max_element(src.begin() + i - period, src.begin() + i);
    }
}

I asked this SO question
and got this solution.

Then I tried to implement the solution.

#include <vector>
#include <deque>
#include <algorithm>

void maximumsT(const std::vector<double> &src, size_t period, std::vector<double> &dst)
{
    dst.resize(src.size());

    for (size_t i = 1; i <= period; ++i) {
        dst[i - 1] = *std::max_element(src.begin(), src.begin() + i);
    }

    for (size_t i = period; i <= src.size(); ++i) {
        dst[i - 1] = *std::max_element(src.begin() + i - period, src.begin() + i);
    }
}

void maximums(const std::vector<double> &src, size_t period, std::vector<double> &dst)
{
    dst.resize(src.size());
    std::deque<std::pair<size_t, double>> deq;

    for (size_t i = 0; i < src.size(); ++i) {
        if (!deq.empty() && i >= period && deq.front().first <= i - period) {
            deq.pop_front();
        }

        while (!deq.empty() && deq.back().second < src[i]) {
            deq.pop_back();
        }

        deq.push_back(std::make_pair(i, src[i]));
        dst[i] = deq.front().second;
    }
}

bool test()
{
    std::vector<double> v(1 + rand() % 1000);
    for (double &e : v) {
        e = (double)rand() / RAND_MAX;
    }

    size_t period = 1 + (rand() % v.size());
    std::vector<double> vv, vvv;

    maximumsT(v, period, vv);
    maximums (v, period, vvv);

    return vv == vvv;
}

bool test(size_t iterations)
{
    for (size_t i = 0; i < iterations; ++i) {
        if (!test()) {
            return false;
        }
    }

    return true;
}

int main(int argc, char *argv[])
{
    return test(10000);
}

How can I improve and optimize this code?


texts:
I created a view called PullView which adds a level of interactivity to UI components. PullViews can be pulled sort of like a rubber-band and bounce a little when released. The code for it is fairly simple.

I would like comments on how to improve code structure, performance, etc. if possible.

import Foundation
import UIKit

/**
    If the view can be pulled (interacted with by the user)

    isPullable set to true by default

    Most applications will call for use as a container.
*/
class PullableView: UIView {

    override init(frame: CGRect) {
       super.init(frame: frame)
        isPullable = true
    }

    init(frame: CGRect, pullable: Bool) {
        super.init(frame: frame)
        isPullable = pullable
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private struct Keys {
        static var isPullable = "isPullable"
        static var initCenter = "initCenter"
        static var initTouchPos = "initTouchPos"
        static var pullFactor = "pullFactor"
    }

    /**
        The initial center of the view
    */
    private var initCenter: CGPoint {
        get {
            return layer.value(forKey: Keys.initCenter) as? CGPoint ?? CGPoint.zero
        }
        set(value) {
            layer.setValue(value, forKey: Keys.initCenter)
        }
    }

    /**
        The initial position of the users touch
    */
    private var initTouchPos: CGPoint {
        get {
            return layer.value(forKey: Keys.initTouchPos) as? CGPoint ?? CGPoint.zero
        }
        set(value) {
            layer.setValue(value, forKey: Keys.initTouchPos)
        }
    }

    /**
         The reciprocal of the slope of the derivative of the curve describing the displacement.

         A higher pullFactor allows for less pulling.

         pullFactor should be greater than 1.
    */
    var pullFactor: CGFloat {
        get {
            return layer.value(forKey: Keys.pullFactor) as? CGFloat ?? 3
        }
        set(value) {
            layer.setValue(value, forKey: Keys.pullFactor)
        }
    }

    /**
        If the view can be pulled.
    */
    var isPullable: Bool {
        get {
            return layer.value(forKey: Keys.isPullable) as? Bool ?? false
        }
        set(value) {
            if value { isUserInteractionEnabled = true }
            layer.setValue(value, forKey: Keys.isPullable)
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if isPullable {
            initCenter = center
            initTouchPos = touches.first!.location(in: superview)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if isPullable {
            let loc = touches.first!.location(in: self.superview)
            let xOffset = loc.x - initTouchPos.x
            let yOffset = loc.y - initTouchPos.y
            let xOffsetD = xOffset / pullFactor
            let yOffsetD = yOffset / pullFactor

            center.x = xOffsetD + initCenter.x
            center.y = yOffsetD + initCenter.y
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if isPullable {
            UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: UIViewAnimationOptions.allowUserInteraction, animations: {
                self.center = self.initCenter
            }, completion: nil)
        }
    }
}


texts:
I am trying to get the hex colours from an image. The problem I am having is that for some reason randomly the code causes high CPU usage, which times out the browser and I am not sure how to optimise the code. I am not sure where the high CPU usage is. I've tried adding delays using setTimeout() but with no luck.

The code was original written in Javascript but I am converted it to Typescript,

Here is full code code which returns the hex values

import {Injectable} from '@angular/core';

@Injectable()
export class ExtractColours {

  private euclidean(p1, p2) {
    let s = 0;
    for (let i = 0, l = p1.length; i < l; i++) {
      s += Math.pow(p1[i] - p2[i], 2)
    }
    return Math.sqrt(s);
  }

  private calculateCenter(points, n) {
    let vals = [];
    let plen = 0;

    for (let i = 0; i < n; i++) { vals.push(0); }
    for (let i = 0, l = points.length; i < l; i++) {
      plen++;
      for (let j = 0; j < n; j++) {
        vals[j] += points[i][j];
      }
    }
    for (let i = 0; i < n; i++) {
      vals[i] = vals[i] / plen;
    }
    return vals;
  }

private kmeans(points, k, min_diff) {

        let plen = points.length;
        let clusters = [];
        let seen = [];

        while (clusters.length < k) {
          let idx = parseInt(String(Math.random() * plen));
          let found = false;
          for (let i = 0; i < seen.length; i++ ) {
            if (idx === seen[i]) {
              found = true;
              break;
            }
          }
          if (!found) {
            seen.push(idx);
            clusters.push([points[idx], [points[idx]]]);
          }
        }

        while (true) {
          let  plists = [];
          for (let i = 0; i < k; i++) {
            plists.push([]);
          }

          for (let j = 0; j < plen; j++) {
            let p = points[j];
            let smallest_distance = 10000000;
            let idx = 0;

            for (let i = 0; i < k; i++) {
              let distance = this.euclidean(p, clusters[i][0]);
              if (distance < smallest_distance) {
                smallest_distance = distance;
                idx = i;
              }
            }
            plists[idx].push(p);
          }

          let diff = 0;

          for (let i = 0; i < k; i++) {
            let old = clusters[i];
            let list = plists[i];
            let center = this.calculateCenter(plists[i], 3);
            let dist = this.euclidean(old[0], center);
            clusters[i] = [center, (plists[i])];
            diff = diff > dist ? diff : dist;
          }
          if (diff < min_diff) {
            break;
          }
        }

        return clusters;
      }

here I am converting the rgb to hex but I am also returning the alpha value

private rgbToHex(rgb) {

          function th(i) {
            let h = parseInt(i).toString(16);
            return h.length == 1 ? '0'+h : h;
          }

          let alpha = (parseInt(th(rgb[0]),16) + parseInt(th(rgb[1]),16) + parseInt(th(rgb[2]),16)) / 3;

        return parseInt(String(alpha)).toString(16) +'#' + th(rgb[0]) + th(rgb[1]) + th(rgb[2]) ;
      }

      public process_image(img, ctx) {
        let points = [];

        ctx.drawImage(img, 0, 0, 200, 200);

        let data = ctx.getImageData(0, 0, 200, 200).data;

        for (let i = 0, l = data.length; i < l;  i += 4) {
          let r = data[i];
          let g = data[i+1];
          let b = data[i+2];
          points.push([r, g, b]);
        }
        let results = this.kmeans(points, 3, 1);
        let hex = [];
        for (let i = 0; i < results.length; i++) {
          hex.push(this.rgbToHex(results[i][0]));
        }

        return hex;
      }
    }


texts: Is this code is safe or not (img upload) ? [PHP]

texts:
I'd like to know if this code is usable, because I'm not sure, thank you. The code is used to upload images to a predefined folder for users.
if(isset($_FILES['avatar']) AND !empty($_FILES['avatar']['name'])) {
$tailleMax = 6844685465456456;
$extensionsValides = array('jpg', 'jpeg', 'gif', 'png');

if($_FILES['avatar']['size'] <= $tailleMax) {

   $extensionUpload = strtolower(substr(strrchr($_FILES['avatar']['name'], '.'), 1));

   if(in_array($extensionUpload, $extensionsValides)) {

      $resultat = move_uploaded_file($_FILES['avatar']['tmp_name'], 'uploads/'.$_SESSION['id'].'.'.$extensionUpload);

      if($resultat) {

     echo "success";

          } else {

            echo "Erreur durant l'importation de votre photo de profil extension";
          }
       } else {

        echo "Votre photo de profil doit être au format jpg, jpeg, gif ou png";
       }
    } else {

       echo "Votre photo de profil ne doit pas dépasser 2Mo";
    }
 }else{
     echo ':/';
 }


texts:
It takes in a string from the command line. prints out the length of the string.
I'm mostly looking for tips and general convention suggestions
But I'm open to any other criticism also.
Roast it please thanks.

global _start

extern printf

section .data
    arg_err db `Invalid Arg Length\n\0`
    len_arg_err equ $ - arg_err
    arg_frmt db `%d\n\0`

section .text
_start:
    mov ecx, DWORD [esp]
    cmp ecx, 2
    jne _error_ext ; Args != 2?

    mov eax,DWORD [esp+8] ;char** argv
    mov ecx, eax

_label:
    mov dl, byte [ecx]
    cmp dl, 0; read byte and comp to 0
    je _exit
    add ecx, 1
    jmp _label

_exit:
    sub ecx,eax ; subtract end addr from start addr
    push ecx
    push arg_frmt
    call printf
    mov eax, 1
    int 0x80

_error_ext:
    mov ecx, arg_err
    mov edx, len_arg_err
    call _print
    mov eax, 1
    int 0x80

_print: ; needs ecx as char* edx as char* len

    push eax
    push ebx

    mov eax, 4
    mov ebx, 1
    int 0x80
    pop ebx
    pop eax
    retn


texts:
I've taken all the advice from here and have created a Craps class and gameplay.  I just wanted to ask for more advice on how to optimize my code.

#include <iostream>
#include <cmath>    // atan(), fabs()
#include "Craps.h"

using namespace std;

int main(int argc, char* argv[])
{
    int choice;
    Craps game;
    do {
        cin>> choice;
        if(!cin)
        {
            cin.clear();
            cin.ignore(200,'\n');
            cout<<"\n please inter int number \n\n";
        }

        switch (choice) {
            case 1:
                game.Play();
                break;
             case 2:
                break;

            default:
                break;
        }

    } while (choice != 2);

    return 0;
}

#include <iostream>
//#include <catdlib>
#include <ctime>
#include <string>
using namespace std;
class Craps
{
public:
    void DisplayInstruction();
    void Play();
    int DiceRoll();
private:
    int random;
};

void Craps::DisplayInstruction(){
    cout<<"DisplayInstruction"<<endl;
}

int Craps::DiceRoll()
{
    int die1  = (rand() + time(0)) % 6+1 ;
    int die2  = (rand() + time(0)) % 6+1 ;

    int sum  = die1 + die2;
    return sum;

}

void Craps::Play()
{
    bool won = false;
    bool lost =  false;

    string anyKey;

    int myPoint = 0;
    int sumeOfDice = DiceRoll();

    switch (sumeOfDice)
    {
        case 7:
            won= true;
            break;
        case 11:
            won= true;
            break;
        case 2:
            lost = true;
            break;
        case 3:
            lost = true;
            break;
        case 12:
            lost = true;
        break;
            default:
                myPoint = sumeOfDice;
                cout<< myPoint <<endl;
                break;
    }

    while (won  == false && lost ==false) {
        sumeOfDice = DiceRoll();
        if(sumeOfDice == myPoint)
        {
            won = true;
        }
        else
            if(sumeOfDice == 7)
            {
                lost = true;
            }
    }
    if (won ==  true)
    {
        cout<<"player win"<<endl;
    }
    else
    {
       cout<<"player lose "<<endl;
    }
}

#endif /* defined(__Craps__Craps__) */


texts:
I'm looking to make my code faster for loading a hash table.  Any pointers would be appreciated.  Below are my includes, the node def and the loading code.

The dictionary loaded could be any *.txt file.  Its pre processed to contains just lower case words sans punctuation.

#include <stdbool.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "dictionary.h"

// define hash table structure
typedef struct node
{
    char word[LENGTH + 1];
    struct node* next;
}
node;

bool load(const char* dictionary)
{

    // open dictionary and check for NULL
    FILE* fpdict = fopen(dictionary, "r");

    if (fpdict == NULL)
    {
        printf("Could not open %s.\n", dictionary);
        unload();
        return false;
    }

    // read in txt file
    else
    {
        node* new_node = malloc(sizeof(node));
        for ( ; fscanf(fpdict, "%s", new_node->word) != EOF;
            new_node = malloc(sizeof(node)) )
        {
            // call hash function to get key
            key = hash(new_node->word, strlen(new_node->word), TABLESIZE);

            // check if hashtable key is NULL
            if (hashtable[key] == NULL)
            {
                hashtable[key] = new_node;
                new_node->next = NULL;
            }

            // if linked list exists, insert it in order
            else if (hashtable[key] != NULL)
            {
                // point to first hashtable entry
                node* head = hashtable[key];
                // set crawler to head
                node* crawler = head;
                // check where to insert

                // insert word at end and set pointer to NULL
                while (crawler->next != NULL)
                {
                    crawler = crawler->next;
                }
                new_node->next = NULL;
                crawler->next = new_node;

            }
            wordCount += 1;
        }
        fclose(fpdict);
        free(new_node);
        return true;
    }

    return false;
}


texts:
The function func(int m,int n) outputs (for m = 3, n = 5):

3

34

345

34

3

I came up with this code:

void func(int m,int n)
{
  for(int i=1;i<n-m+2;i++)
{   int k=i;
  int j=m;

    while(k>0)
  {
    System.out.print(j);
     k--;j++;
   }
 System.out.println("");

}

for(int i=n-m;i>0;i--)
{  int k=i;
  int j=m;

  while(k>0)
  {
  System.out.print(j);
     k--;j++;
   }
System.out.println("");

    }

}

Is there an alternate, better way to do it? Can it be more efficient?


texts: Generic observer pattern implementation in C++

texts:
Implemented observers in C++11 in a generic and statically accessible way. Though an instance is created, it's used only for cleanup and lifetime management.

template<typename... Args>
class Observers
{
private:
    unordered_map<int, vector<function<void(Args...)>>> observers;
    static Observers<Args...> *instance;
public:
    Observers()
    {
        instance = this;
    }

    template<typename Observer>
    static void Register(int ev, Observer &&observer)
    {
        instance->observers[ev].push_back(forward<Observer>(observer));
    }

    static void Notify(int ev, Args... args)
    {
        try
        {
            auto &obs = instance->observers.at(ev);
            for (auto &o : obs)
                o(args...);
        }
        catch (...){}
    }
};

template<typename... Args>
Observers<Args...> *Observers<Args...>::instance;

usage:

using IntIntObservers = Observers < int, int > ;//optional type declaration

IntIntObservers o;//observer instance

IntIntObservers::Register(1, [=](int a, int b){whatever});

IntIntObservers::Notify(1, 4, 5);

An observer set can be accessed statically as long as the instance is alive. Multiple instances of the same type could be achieved by adding an id parameter to the template declaration, making it

template<int id, typename... Args>

Anything that I missed and could be improved?


texts: Function to use projections in legacy algorithms

texts:
I love the "projections" introduced by the ranges library, and I would like to use them in algorithms that haven't been rangeyfied yet.
I had the idea of using them through a function like this:
#include <utility>
#include <functional>

template<typename TFn, typename TProj = std::identity>
auto
constexpr proj(TFn &&Fn, TProj &&Proj = {})
{
  return [&Fn, &Proj]<typename... TArgs>(TArgs &&...Args)
  {
    return std::invoke(std::forward<TFn>(Fn),
                       std::invoke(std::forward<TProj>(Proj), std::forward<TArgs>(Args))...);
  };
}

This function enables writting, for example:
  std::sort(std::execution::par_unseq, v.begin(), v.end(), proj(std::less{}, &Pair::Key));

instead of:
  std::sort(std::execution::par_unseq, v.begin(), v.end(), [](auto const &lhs, auto const &rhs) { return lhs.Key < rhs.Key; });


texts:
I was working on writing a fast implementation of a simple Huffman code compression of text. The idea was to write it using only the standard library, but I can't seem to find a way to make it faster. I am also looking for advise on how to write it more "Pythonic", without sacrificing speed.
I am aware that if I want speed I shouldn't use Python, but I've taken it as an exercise to test pure Python performance.
from collections import Counter, defaultdict

def huffman_compress(input_file, output_file, encoding='utf8'):
    """This functions compresses a txt file using Huffman code compression."""

    # Store the text in memory since it is faster than reading twice
    text = open(input_file, "r", encoding=encoding).read()

    # Count the times each letter appears on the text
    letter_freq = Counter(text)
    alphabet = defaultdict(str)

    # Obtain the huffman code for each letter
    while len(letter_freq) > 1:
        (letter1, count1), (letter2, count2) = letter_freq.most_common(2)
        letter_freq[letter1+letter2] = count1 + count2
        for bit, combination in enumerate([letter1, letter2]):
            for letter in combination:
                alphabet[letter] = str(bit) + alphabet[letter]
            del letter_freq[combination]

    # Save the transformation to ascii for possible the 256 characters
    bit_to_ascii = {format(x, '08b'): chr(x) for x in range(256)}

    with open(output_file, 'w') as output:
        # Transform each letter to its huffman code
        me = ''.join(alphabet[ch] for ch in text)

        # Add 0's so that the string is multiple of 8
        extra_bits = 8 - len(me) % 8
        me +=  extra_bits * '0'

        # Write the number of letters compressed and the number of bits added
        output.write(f'{chr(len(alphabet))}{extra_bits}')

        # Write the letters compressed and their huffman code for the decompression
        output.write('|'.join(c for item in alphabet.items() for c in item))

        # Transform the huffman bits to ascii and save them on the compressed file.
        output.write(''.join(bit_to_ascii[me[j:j+8]] for j in range(0, len(me), 8)))


texts:
I have an algorithm to print all prime numbers in interval [2..N]:

void print_primes(int n) {
    std::vector<int> nums;

    for (int i = 0; i < n - 1; ++i) {
        nums.push_back(i + 2);
    }

    for (int i = 2; i <= n;) {
        std::cout << i << ' ';

        bool is_first = true;
        int cur = i;

        for (int j = i - 1; j < static_cast<int>(nums.size()); ++j) {

            if (nums[j] > 0) {

                if (nums[j] % cur == 0) {
                    nums[j] *= -1;
                } else if (is_first) {
                    i = nums[j];
                    is_first = false;
                }
            }
        }

        if (is_first) {
            break;
        }
    }
}

The problem is that I need to execute it for O(N) and I haven't ideas already... How to optimize it for O(N)?
Now, it works just marking next non-prime numbers to exclude it.


texts: Use of macros to aid visual parsing of SFINAE template metaprogramming

texts:
I've recently been introduced to SFINAE to solve the problem of unwanted promotion precedence.

i.e. I was hoping to catch integer types with Foo::Foo(long) and floating-point types with Foo::Foo(double), but alas int -> double rather than long.

    /*
    Constructors for various types, for example, 'Object{"foo"}, Object{42}, Object{3.14} should create a String Long Float respectively

    There is a problem with constructors.

    Python supports a single integer type, which we wrap with the Long class
    And the single floatingpoint type, which we wrap with the Float class

    In an ideal world we would just provide two overloads to allow a generic
    Object to be initialised as one of these types:

        Object(long   l) : Object{ Long {l} }  { }
        Object(double d) : Object{ Float{d} }  { }

    We want Object{5} to create a Long{5}
    Unfortunately, int gets promoted to double, not long ( http://stackoverflow.com/a/27276398/435129 )

    Very annoying. Fortunately we can use some SFINAE cunning.
    */
    #define DECAY(T) \
                            typename std::decay<T>::type

    #define IS_INTEGRAL(T) \
                            std::is_integral< DECAY(T) >::value

    #define IS_FLOATING(T) \
                            std::is_floating_point< DECAY(T) >::value

    #define SUBFAIL_UNLESS(PRED) \
                            typename X = typename std::enable_if<PRED>::type

    /*
    Note that the first template encounters a substitution failure for any non-integral type,
    hence only redirects integral types to init(long(t))

    Similarly for floatingpoint types.

    Note also the unfortunate use of an empty '...' C parameter expansion.
    Without this the compiler will complain that two templates are attempting
    to wrap a function with the same signature.

    Unfortunately it isn't smart enough to know that the conditions are mutually exclusive.

    If you required trapping of three or more such special cases, see NOTE_3_CASES at the bottom of the file.
    Also http://ideone.com/oDOSLH
    */

public:
    template<typename T, SUBFAIL_UNLESS(IS_INTEGRAL(T)) > explicit Object( T&& t      ) { init(long  (t)); }
    template<typename T, SUBFAIL_UNLESS(IS_FLOATING(T)) > explicit Object( T&& t, ... ) { init(double(t)); }

private:
    void init(long);
    void init(double);

    #undef DECAY
    #undef IS_INTEGRAL
    #undef IS_FLOATING

I know that macros are generally frowned upon. However, in this case they provide a very clear solution, making it very easy for my brain to parse the code.

I would like to know whether in this case the use of macros is justified, and if not what the best alternative would be.


texts:
I looked around for a script for popup menus in jQuery, but all i found were complex and largely-coded plugins.

I decided to write a small script myself:

$(document).on("click",".js_popup-trigger", function(e){
    e.preventDefault();

    //Set variables
    var element     = $(e.currentTarget).closest('.js_popup-trigger'),
        container   = element.parent('.js_popup-container'),
        menu        = element.next('.js_popup-menu');

    //Toggle the menu
    menu.fadeToggle(100);

    //Add the open classes to the container and trigger
    container.toggleClass('js_popup-container--open');
    element.toggleClass('js_popup-trigger--open');

    /*  Create a click listener for the document
    *   This is to close the menu if clicked outside of it */
    $(document).click(function closePopup(e){

        //If the clicked item is not in the popup, close it
        if(!$(e.target).closest(container[0]).length && element.is(":visible")){

            //Close the popup
            menu.fadeOut(100);

            //Remove the added classes
            container.removeClass('js_popup-container--open');
            element.removeClass('js_popup-trigger--open');

            //Unbind the closePopup function from the document
            $(document).unbind('click',closePopup);
        }
    });
});

This is working as it should at the moment, it simply allows you to create popup menus using the three classes in the script, one for the overall popup menu container, one for the trigger, and one for the menu items container.

When you click on the trigger, it opens the popup, and sets an event listener for a click event to the document which checks if the user clicked outside of the popup, which will close it if so.

Is this something that is efficient, if so then why the need for the large plugins? I assume those plugins have other functionalities and come with more styling options, effects, etc. But would a script like this be considered efficient?


texts: Calculate compilation time from AssemblyVersion attribute

texts:
In my program, I display the compilation time which is calculated from the AssemblyVersion attribute. The attribute is set to automatically generate a version number (with asterisk).

As you know probably, the build is equal to the number of days since January 1, 2000 (local time), and revision is equal to the number of seconds since midnight (local time, without taking into account time zone adjustments for daylight saving time), divided by 2! See the documentation of attribute for more information.

My code parses the version number to calculate the compilation time according to the previous statement with taking account time zone adjustments for daylight saving time! But, I'm not sure about the last part.

DateTime date = DateTime(2000, 1, 1, 0, 0, 0);  // January 1, 2000 at midnight

date = date.AddDays(build);

// Time zone adjustments for daylight saving time
if (TimeZoneInfo::FindSystemTimeZoneById("Central Europe Standard Time")->IsDaylightSavingTime(date)) // I'm living in Switzerland, so CEST
{
    date = date.AddHours(1);
}

date = date.AddSeconds(revision * 2);

Is my code correct? Can I optimize this?


texts:
I set myself the task to calculate the average of a list, but with two conditions:

negative numbers are ignored
numbers greater than 100 are counted as if they were 100

So the "skewed" average of the list '(1 -3 42 297 14) should be (1 + 42 + 100 + 14) / 4 (157/4).

I wrote 2 functions that do that. Please review and comment.

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

(defun skewed-average2 (list)
    "calculate average by building 'fixed' list"
    (let (newlist)
        (dolist (x list)
            (if (>= x 0)
                (progn
                    (if (> x 100) (setf x 100))
                    (setf newlist (cons x newlist)))))
        (/ (apply #'+ newlist) (length newlist))))

(let ((numbers '(1 -3 42 297 14)))
    (print (skewed-average1 numbers))
    (print (skewed-average2 numbers)))

Also, how should errors be treated? Imagine passing an empty list to the functions; or a list with all negative numbers.


texts:
I am currently in the process of learning WPF Prism and I have four buttons that I want to all go to the same place but with a different value being passed depending on which button has been pressed.

Below is the code that I currently have.

ApplicationCommands.cs

public class ApplicationCommands
{
    public static CompositeCommand LoginCommand = new CompositeCommand();
    public static CompositeCommand TotalOutstandingCommand = new CompositeCommand();
    public static CompositeCommand InSLACommand = new CompositeCommand();
    public static CompositeCommand GoingOOSLACommand = new CompositeCommand();
    public static CompositeCommand OOSLACommand = new CompositeCommand();
}

DashboardViewModel.cs

...
public DelegateCommand<object> TotalOutstandingCommand { get; set; }
public DelegateCommand<object> InSLACommand { get; set; }
public DelegateCommand<object> GoingOOSLACommand { get; set; }
public DelegateCommand<object> OOSLACommand { get; set; }

public DashboardViewModel(IDashboardView view, IRegionManager manager)
        : base(view)
    {
        _regionManager = manager;

        TotalOutstandingCommand = new DelegateCommand<object>(GoToAllocation);
        InSLACommand = new DelegateCommand<object>(GoToAllocation);
        GoingOOSLACommand = new DelegateCommand<object>(GoToAllocation);
        OOSLACommand = new DelegateCommand<object>(GoToAllocation);

        ApplicationCommands.TotalOutstandingCommand.RegisterCommand(TotalOutstandingCommand);
        ApplicationCommands.InSLACommand.RegisterCommand(InSLACommand);
        ApplicationCommands.GoingOOSLACommand.RegisterCommand(GoingOOSLACommand);
        ApplicationCommands
}

private void GoToAllocation(object value)
{
       //Logic Goes Here
}

I was curious to know if there is a simpler way to complete the task or do I need to declare and register a separate DelegateCommand for each button


texts: Check if integer is a palindrome in base 10

texts:
Here is the solution->
//Write a program to check the number whether it is palindrome or not
#include <stdio.h>
int
main(void){

//Put variables for the further proceed
int number, quotient=1, remainder,i=0;

//To declare a character array
char text[100];

//To show the message to the user
printf("Enter an integer number :");

//Taking input from the user
scanf("%d",&number);

//For finding escape the integer number in the reverse order specifically
int number_update=number;

//To find out the integer number in the reverse order
  while(quotient!=0){
  quotient=number_update/10;
  remainder=number_update%10;
  number_update=quotient;
  text[i] = remainder + '0';//Converts integer to character and store to the array
  i++;
  }
 //Converts the string to a whole integer
  int result_of_reverse=atoi(text);

  //Check the result of reverse order with the given integer number
  if(result_of_reverse==number){

    //To display the result
    printf("This is a palindrome number");
  }
  else{

    //To display the result
    printf("This is not a palindrome number");
  }

  }

I want to achieve: How can I simplify my solution? Is there any better strategy should I follow to solve these types of problems?


texts: Re-write custom feature encoding function python

texts:
I have a question regarding code quality and best practices. My task - to write a feature encoding function that will encode categorical labels, boolean labels as one-hot encoding, timestamps for further usage for ml training.

Input - dictionary of several dataframes, each dataframe consist of several columns of different types.

The function should return a dictionary of correctly encoded dataframes and a dictionary of label encoders for categorical columns.

Here is what I did:

# Encode bool values to one hot encoding, change NaN numerical values to single const value, make timestamp be time columns, add categorical encoding
def df_encoder(data_dict) :
    #encode all NA values of continuos data as a constant
    NA_values = 0.001
    # dictionary to save dictionary of label encodings from LabelEncoder
    labels_codes = dict()

    for names_df in data_dict:
        # list, where to save label encodings from LabelEncoder from one dataframe
        labels_codes[names_df] = list()

        #take iteratively dataframe from the dictionary of dataframes
        df_additional = data_dict[names_df]

        for col in df_additional:

            if is_bool_dtype(df_additional[col]):
                loc_col = df_additional.columns.get_loc(col)
                df_additional_one_hot = pd.get_dummies(df_additional[col], prefix=col, dummy_na=True)
                df_additional = pd.concat([df_additional.iloc[:, :loc_col], df_additional_one_hot, df_additional.iloc[:, loc_col:]], axis=1).drop(col, axis=1)

            elif is_numeric_dtype(df_additional[col]):
                df_additional[col].fillna(NA_values)

            elif is_datetime64_any_dtype(df_additional[col]):
                loc_col = df_additional.columns.get_loc(col)
                date_df = pd.DataFrame()
                date_df[col+'_year'] = df_additional[col].dt.year.fillna(0)
                date_df[col+'_month'] = df_additional[col].dt.month.fillna(0)
                date_df[col+'_day'] = df_additional[col].dt.day.fillna(0)
                date_df[col+'_hour'] = df_additional[col].dt.hour.fillna(25)
                date_df[col+'_minute'] = df_additional[col].dt.minute.fillna(60)
                date_df[col+'_seconds'] = df_additional[col].dt.second.fillna(60)
                df_additional = pd.concat([df_additional.iloc[:, :loc_col], date_df, df_additional.iloc[:, loc_col:]], axis=1).drop(col, axis=1)

            elif is_categorical_dtype(df_additional[col]) and df_additional[col].nunique()== 2:
                loc_col = df_additional.columns.get_loc(col)
                df_additional_two_val_categ = pd.get_dummies(df_additional[col], prefix=col, dummy_na=True)
                df_additional = pd.concat([df_additional.iloc[:, :loc_col], df_additional_two_val_categ, df_additional.iloc[:, loc_col:]], axis=1).drop(col, axis=1)

            elif is_categorical_dtype(df_additional[col]) and df_additional[col].nunique()>2:
                #keep only alphanumeric and space, and ignore non-ASCII
                df_additional[col].replace(regex=True,inplace=True,to_replace=r'[^A-Za-z0-9 ]+',value=r'')
                label_enc = LabelEncoder()
                df_additional[col] = label_enc.fit_transform(df_additional[col].astype(str))
                labels_codes[names_df].append({col: label_enc})

            data_dict[names_df] = df_additional
    return data_dict, labels_codes

The functions work well, but I'm not happy with its quality. I need some useful advice or examples of how to make this function more efficient, and more "best-coding practises" alike. Will appreciate any insights and critique.


texts: Python script to find employees who are in one PostgreSQL table but not in another

texts:
I'm writing a python script and do database query to get the ids of employees who are in one table but are not in another. I'm using psycopg2  module for python 2 and PostgreSQL as database. After querying from one table based on a condition, I do another query on another table to get the difference between these tables using the result of previous query. The problem is the full procedure takes a long time. I want to know is there any other method or technique which can make the entire procedure faster?
Below is the code I used for doing my feature:

def find_difference_assignment_pls_count(self):
        counter = 0
        emp_ids = []
        self.test_cursor.execute("""Select id,emp_id from test_test where flag=true and emp_id is not null and ver_id in(select id from test_phases where state='test')""")
        matching_records = self.test_cursor.fetchall()

        for match_record in matching_records:
            self.test_cursor.execute("""Select id from test_table where test_emp_id=%s and state='test_state'""",(match_record['emp_id'],))
            result = self.test_cursor.fetchall()

            if result:
                continue
            else:
                emp_ids.append(match_record['emp_id'])
                counter +=1

        print "Employees of test_test not in test_table: ", counter
        return emp_ids

I run these queries on two tables which at least have more than 500000 records. Therefore the performance is really slow.


texts:
Please review my solution to the minesweeper exercise in rust. Taken from this link at exercism. Overall I'd like to know what I can improve when it comes to performance (what if I had a board from 1e99x1e99). Also I would just like some generic pointers on my rust code as it would help me understand rust a bit better as I'm still learning.

mod minesweeper {
    use std;

    pub fn is_mine(string: &str, x_pos: usize) -> bool {
        string.chars().nth(x_pos).unwrap() == '*'
    }

    pub fn fill(empty: Vec<&str>) -> Vec<std::string::String> {
        let mut result = vec![];

        for (y_pos, row) in empty.iter().enumerate() {
            let mut new_row = String::from(empty[y_pos]);

            for (x_pos, c) in row.chars().enumerate() {
                let b_up: bool = y_pos > 0;
                let b_down: bool = empty.len() > y_pos + 1;
                let b_left: bool = x_pos > 0;
                let b_right: bool = row.len() > x_pos + 1;

                let mine_count = [
                    // looking up
                    b_up && is_mine(empty[y_pos - 1], x_pos),
                    // looking down
                    b_down && is_mine(empty[y_pos + 1], x_pos),
                    // looking left
                    b_left && is_mine(empty[y_pos], x_pos - 1),
                    // looking right
                    b_right && is_mine(empty[y_pos], x_pos + 1),
                    // looking up left
                    b_up && b_left && is_mine(empty[y_pos - 1], x_pos - 1),
                    // looking up right
                    b_up && b_right && is_mine(empty[y_pos - 1], x_pos + 1),
                    // looking down left
                    b_down && b_left && is_mine(empty[y_pos + 1], x_pos - 1),
                    // looking down right
                    b_down && b_right && is_mine(empty[y_pos + 1], x_pos + 1)
                ].iter().filter(|x| **x ).count();

                if c == ' ' && mine_count > 0 {
                    new_row.remove(x_pos);
                    new_row.insert(x_pos, mine_count.to_string()
                                                    .chars()
                                                    .next()
                                                    .unwrap());
                }
            }
            result.push(new_row);
        };

        result
    }
}

#[test]
fn add_numbers_to_empty_sweeper_board() {
    assert_eq!(
        minesweeper::fill(vec![
            "   ",
            "   ",
            "   "
        ]),
        vec![
            "   ",
            "   ",
            "   "
        ]
    )
}

#[test]
fn add_numbers_to_filled_sweeper_board() {
    assert_eq!(
        minesweeper::fill(vec![
            "** ",
            "   ",
            "   "
        ]),
        vec![
            "**1",
            "221",
            "   "
        ]
    )
}

#[test]
fn add_numbers_to_all_mines() {
    assert_eq!(
        minesweeper::fill(vec![
            "***",
            "* *",
            "***"
        ]),
        vec![
            "***",
            "*8*",
            "***"
        ]
    )
}

#[test]
fn add_numbers_to_bigger_filled_sweeper_board() {
    assert_eq!(
        minesweeper::fill(vec![
            "**  ",
            "    ",
            "  * ",
            "    "
        ]),
        vec![
            "**1 ",
            "2321",
            " 1*1",
            " 111"
        ]
    )
}


texts:
I have four fields a, b, c, and d.  All of them must be populated if any of them have a value.

So what I want to do is validate that they are all populated, if any of them have a value.  I'm trying to determine the best way to do this.  I think I could do this:

  class User < ActiveRecord::Base
    validates_presence_of :a, :b, :c, :if => lambda { self.d.present? }
    validates_presence_of :b, :c, :d, :if => lambda { self.a.present? }
    validates_presence_of :a, :c, :d, :if => lambda { self.b.present? }
    validates_presence_of :a, :b, :d, :if => lambda { self.c.present? }
  end


texts: Generate out_filename from input_filename and suffix

texts:
I do a lot of steps of processing over an input_file. To avoid having to think of an output_filename at every step, I created the following name generation function:

def generate_out_file(in_file, suffix='out'):
    body_str = in_file.strip('./')
    flag = '.' in body_str
    _list = body_str.split('.')
    body_list = _list[:-1] if flag else [in_file]
    extension = _list[-1] if flag else 'txt'
    out_file = '.'.join(body_list + [suffix, extension])
    if in_file.startswith('./'):
        out_file = './' + out_file
    if in_file.startswith('../'):
        out_file = '../' + out_file
    return out_file

It looks very huge for me. Can you review my code and help me to improve it?


texts:
I have a pseudosite, where I actually post small functions, so that I can re-use them*, but some posts have visitors. The top is Quicksort (C++). I feel that beginners visit it, so I do not care in improving (its poor) performance, but only the readability, so that the beginner can catch things more easily.

#include <iostream>

void quickSort(int a[], int first, int last);
int pivot(int a[], int first, int last);
void swap(int& a, int& b);
void swapNoTemp(int& a, int& b);
void print(int array[], const int& N);

using namespace std;

int main()
{
    int test[] = { 7, -13, 1, 3, 10, 5, 2, 4 };
    int N = sizeof(test)/sizeof(int);

    cout << "Size of test array :"  << N << endl;

    cout << "Before sorting : " << endl;
    print(test, N);

    quickSort(test, 0, N-1);

    cout << endl << endl << "After sorting : " << endl;
    print(test, N);

    return 0;
}

/**
 * Quicksort.
 * @param a - The array to be sorted.
 * @param first - The start of the sequence to be sorted.
 * @param last - The end of the sequence to be sorted.
*/
void quickSort( int a[], int first, int last )
{
    int pivotElement;

    if(first < last)
    {
        pivotElement = pivot(a, first, last);
        quickSort(a, first, pivotElement-1);
        quickSort(a, pivotElement+1, last);
    }
}

/**
 * Find and return the index of pivot element.
 * @param a - The array.
 * @param first - The start of the sequence.
 * @param last - The end of the sequence.
 * @return - the pivot element
*/
int pivot(int a[], int first, int last)
{
    int  p = first;
    int pivotElement = a[first];

    for(int i = first+1 ; i <= last ; i++)
    {
        /* If you want to sort the list in the other order, change "<=" to ">" */
        if(a[i] <= pivotElement)
        {
            p++;
            swap(a[i], a[p]);
        }
    }

    swap(a[p], a[first]);

    return p;
}

/**
 * Swap the parameters.
 * @param a - The first parameter.
 * @param b - The second parameter.
*/
void swap(int& a, int& b)
{
    int temp = a;
    a = b;
    b = temp;
}

/**
 * Swap the parameters without a temp variable.
 * Warning! Prone to overflow/underflow.
 * @param a - The first parameter.
 * @param b - The second parameter.
*/
void swapNoTemp(int& a, int& b)
{
    a -= b;
    b += a;// b gets the original value of a
    a = (b - a);// a gets the original value of b
}

/**
 * Print an array.
 * @param a - The array.
 * @param N - The size of the array.
*/
void print(int a[], const int& N)
{
    for(int i = 0 ; i < N ; i++)
        cout << "array[" << i << "] = " << a[i] << endl;
}

As you see, I use many things from C, since I wanted the code to be able to work in a C program with minor modifications, thus I am adding c tag too.

*since I find it easier to find them there than in my FS and it helps in restoring harmony after a nuke.


texts: Speed-Distance-Time Calculator in Rust 1.8

texts:
Whenever I try a new language I always try to write a speed-distance-time calculator as well as possible. I did this with C++ a while ago now. This is a similar question but this time in Rust.

The program calculates speed, distance or time from the other two variables in the equation and the idea is to try to do this without a load of nested if statements and repetition. I try to make as elegant a solution as possible but the program needs to show the working for the equation.

I want to know how I could adjust the program to:

Fit in with good (Rust) practices
Shorten the program as much as possible
Catch all errors
Add support for units and conversions later on as well as other common equations
Make better use of Rust

    use std::io;

// Simple input function to simplify calc functions

fn get_param(s: &str) -> f64 {
    println!("{}", s); // Print input instructions

    loop { // loop until a float is entered
        println!("Enter a floating point number!");
        let mut input = String::new();

        io::stdin().read_line(&mut input)
                .expect("failed to read line");

        let input: f64 = match input.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        return input;
    }
}

fn calc_speed() -> f64 {
    let distance: f64   = get_param("Enter distance:");
    let time: f64       = get_param("Enter time:");
    println!("Speed = distance / time");
    println!("Speed = {} / {}", distance, time);
        distance / time
}

fn calc_time() -> f64 {
    let speed: f64      = get_param("Enter speed:");
    let distance: f64   = get_param("Enter distance:");
    println!("Time = distance / speed");
    println!("Time = {} / {}", distance, speed);
        distance / speed
}

fn calc_distance() -> f64 {
    let speed: f64      = get_param("Enter speed:");
    let time: f64       = get_param("Enter time:");
    println!("Distance = speed * time");
    println!("Distance = {} * {}", speed, time);
        speed * time
}

fn main() {
    let mut calc_input = String::new();

    println!("Hello, would you like to calculate speed, distance or time?");

    io::stdin().read_line(&mut calc_input)
            .expect("failed to read line");

    let answer: f64;

    match calc_input.trim() {
        "speed" | "Speed"       => {
            answer = calc_speed();
            println!("Speed = {}", answer);
        }
        "distance" | "Distance" => {
            answer = calc_distance();
            println!("Distance = {}", answer);
        }
        "time" | "Time"         => {
            answer = calc_time();
            println!("Time = {}", answer);
        }
        _                       => {
            println!("Enter speed, distance or time!")
        }
    }

}

I am new to Rust and know only a little about the language, coming primarily from C++. I know if I was writing C++ I would probably write a sdt class and maybe a struct for working.


texts: Find one duplicate in container with N+1 integers between 1 and N

texts:
Time complexity is supposed to be \$O(n \cdot \log(n))\$ and space complexity is supposed to be \$O(1)\$. Neither the elements of the container nor the container should be modified.

// Copyright [2015] <none>
#include <cstdlib>
#include <cstddef>
#include <cassert>
#include <iostream>
#include <vector>
#include <iterator>
#include <numeric>
#include <random>
#include <algorithm>
#include <limits>

// #define NODEBUG

/**
 * Finds one duplicate number in container where the largest number in the
 * container is smaller than the size of the container.
 */
template <class It>
It FindOneDuplicate(It first, It last) {
  int n = static_cast<int>(std::distance(first, last) - 1);
  int range_start = 1;
  int range_end = n / 2;
  while (true) {
  next_range:
    int range_size = range_end - range_start + 1;
    int count = 0;
    for (auto current{first}; current != last; ++current) {
      int element = *current;
      if (element >= range_start && element <= range_end) {
        ++count;
        if (count > range_size) {
          n = range_end;
          range_end = (n + range_start) / 2;
          if (range_size == 1) {
            return current;
          }
          // break and continue
          goto next_range;
        }
      }
    }
    // This should never happen
    assert(range_end != n);

    range_start = range_end + 1;
    range_end = n;
  }
}

// This is just a test run
int main(int argc, char* argv[]) {
  if (argc != 2) {
    std::cerr << "Usage: " << argv[0] << " <N>" << std::endl;
    return EXIT_FAILURE;
  }
  int n =
      static_cast<int>(std::strtol(argv[1], static_cast<char**>(nullptr), 10));
  assert(n > 0 && n < std::numeric_limits<int>::max());
  std::random_device rd;
  std::mt19937 generator(rd());
  std::uniform_int_distribution<> dist(1, n);
  std::size_t size{static_cast<std::size_t>(n + 1)};
  std::vector<int> elements(size);
  // Fill and increment except last
  std::iota(elements.begin(), elements.end() - 1, 1);
  // Fill last with random value [1..N]
  elements.back() = dist(generator);
  // Shuffle elements
  std::shuffle(elements.begin(), elements.end(), generator);
  auto duplicate = FindOneDuplicate(elements.begin(), elements.end());
  for (const auto& element : elements) {
    bool isduplicate = element == *duplicate;
    if (isduplicate) {
      // bold;red
      std::cout << "\033[1;31m";
    }
    std::cout << element;
    if (isduplicate) {
      // reset
      std::cout << "\033[0m";
    }
    if (&element != &elements.back()) {
      std::cout << ", ";
    }
  }
  std::cout << std::endl;
  return EXIT_SUCCESS;
}

Since this is my first real piece of C++ code I'd love to get some code review before I start working on any open source projects.

Note that I'm trying to follow the Google C++ style guide here.


texts:
How can I make the following code shorter or efficient (maybe with other loops or other nice ideas), and keep the current functionality?

my $examine = shift; my $detect = 0;
foreach my $ProteinDB (@DB) {
    my $Set =  $ProteinDB->{'ID'};
    if($Set =~ /$examine/) {
        $detect = 1;
        my @Pointer = keys(%$ProteinDB);
        foreach my $key (@Pointer) {
            if($key ne "ID" && $key ne "SQ") {
                print "$key " . $ProteinDB->{$key} . "\n";
                print "\n";
            }
        }
        print "SQ  " . $ProteinDB->{"SQ"} . "\n";
        print "//\n";
    }
}
if($detect == 0) {
    print "Error : For the ID $examine NO-Entry could be Found !\n";
}

It's nice code and easy to understand, but I don't have that experience that I can tell what I can do more with this code.  I am gonna keep trying to change it until it's shorter.


texts: Changing a character in a string at a specified index position

texts:
Could you please tell me what you liked or may have disliked about this code? What can be made better?

#!/usr/bin/python3

def change_char_at(ch, s, indx):
    """
    Strings in Python are immutable objects. So, it is not possible to change a
    certain character in a string in place. For example, an attempt to run the
    following code will fail with a TypeError:

        s = "spam"
        s[1] = "z" # TypeError: 'str' object does not support item assignment

    What this function does is it provides you with a nice interface when you
    want to change a character in a string at a certain index position. So, use
    this function instead of doing everything manually which can sometimes be
    tricky. Notice that the character parameter does not necessarily have to be
    one character long. It can be an empty string which means that a character
    at a certain position will effectively be deleted from the string. If it's
    more than one character long, then they all will be inserted into the string
    starting at the specified index position.

    Parameters:
    ch:   character to insert
    s:    string to insert into
    indx: index position where to insert the character
    """
    # Error handling
    if type(ch) is not str:
        raise TypeError("first argument must be a string")
    if type(s) is not str or not len(s) > 0:
        raise TypeError("second argument must be a non-empty string")

    length = len(s) - 1
    if not(indx >= 0 and indx <= length):
        msg  = "string index out of range; "
        msg += "attempt to access index at {0}; ".format(indx)
        msg += "allowable index range 0 to {0}".format(length)
        raise IndexError(msg)

    # Actual function logic
    return s[:indx] + ch + s[indx + 1:]
    """
    Another possible implementation:

        ls       = list(s)
        ls[indx] = ch
        return ''.join(ls)

    This works well too and is equally good, but might be conspired unpythonic
    by some compared to the one right above it.
    """

def main():
    my_string = "spam"
    my_string = change_char_at("z", my_string, 1)
    print(my_string) # prints "szam"

if __name__ == "__main__": main()


texts:
I have the following code which is located within a case, in a switch statement. Its goal is to add a Pupil to a Subject using the Collections in the respective class.

I've tried to make the code as readable as possible, but I'm sure there's a better approach.

  System.out.println("Adding a Pupil...");

  String AddPupilSubj;
  do {

      UserInput.prompt("\nEnter the Subject Code to add the Pupil to, or enter 'list' to list all Subjects: ");
      AddPupilSubj = UserInput.readString();

      if(AddPupilSubj.equals("list"))
        school.listSubjects();

  } while(AddPupilSubj.isEmpty() || AddPupilSubj.equals("list"));

  Boolean found = false;

  // Locate the Subject
  for(Object obj : school.getSubjects()) {
      Subject subj = (Subject) obj;

      if(subj.getCode().equals(AddPupilSubj)) {

        found = true;

        // Get the ID of the Pupil
        UserInput.prompt("Enter Pupil ID: ");
        int id = UserInput.readInt();

        // Get the Pupil's Name
        UserInput.prompt("Enter Pupil Name: ");
        String name = UserInput.readString();

        // Get the Address of the Pupil
        UserInput.prompt("Enter Pupil Address: ");
        String address = UserInput.readString();

        String date; Boolean valid;
        do {

             // Get the Pupil's Date of Birth
            UserInput.prompt("Enter Pupil Date of Birth (dd/mm/yyyy): ");
            date = UserInput.readString();

            valid = validDOB(date);

        } while(!valid);

        // Get the Pupil's email address
        UserInput.prompt("Enter Pupil Email: ");
        String email = UserInput.readString();

        DateTime dob = DateTime.forDateOnly(Integer.parseInt(date.substring(6, 10)),
                  Integer.parseInt(date.substring(3, 5)),
                  Integer.parseInt(date.substring(0, 2)));

        DateTime admitted = DateTime.today(TimeZone.getDefault());

        Pupil Pupil = new Pupil(id, name, address, dob, email, admitted);
        if(subj.addPupil(Pupil)) {

             System.out.println(
                 String.format("\nPupil, %s, has been added to the %s Subject.",
                               Pupil.getName(),
                               subj.getName()));

        } else {

             System.out.println(
                 String.format("Pupil #%s is already in the Subject!",
                               Pupil.getID()));

        }

        break;
      }

  }

  if(!found) {
      System.out.println(
        String.format("A Subject with code, %s, doesn't exist!",
          AddPupilSubj));
  }


texts: A "C" shape of 7 boxes that turn green on click

texts:
Company name asks you to build a website with 7 boxes shaped like a c, which should turn green on click, and then when all are clicked, should turn red in reverse clicking order.

https://jsfiddle.net/yx296/dvacLduw/

document.addEventListener('DOMContentLoaded', function() {
  var boxHolder = document.querySelector(".boxHolder");
  var count = 0;

  boxHolder.addEventListener('click', changeGreen);

  var boxes = [];

  function changeGreen(e) {
    if (e.target !== e.currentTarget) {
      var box = e.target;
      if (box.style.backgroundColor !== 'green') {
        box.style.backgroundColor = 'green';
        count++;
        boxes.push(e.target);
      }
    }

    if (count === 7) {
      count = 0;
      setTimeout(function() {
        reverseTurnRed();
      }, 1000);
    }
    e.stopPropagation();
  }

  function reverseTurnRed() {
    boxes.reverse();
    boxes.forEach(function(box, index) {
      setTimeout(function() {
        box.style.backgroundColor = 'red';
      }, index * 500)
    });
    setTimeout(function() {
      boxes = [];
    }, 0)
  }
});
div {
  box-sizing: border-box;
}

.container {
  font-size: 0;
  margin: 0 auto;
  width: 400px;
  height: 400px;
  border: 1px solid blue;
  position: relative;
}

.boxHolder {
  border: 1px solid black;
  display: inline-block;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.box {
  width: 50px;
  height: 50px;
  border: 1px solid black;
  margin: 2px;
}

.topRow {
  display: inline-block;
}

.bottomRow {
  display: inline-block;
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>vanillaJSAddeparChallenge</title>
  <link rel="stylesheet" href="styles.css">

It seems it doesn't matter whether or not I leave the e.stopPropagation in there... what is the point of it?

Willing to accept any critique on HTML, CSS or JavaScript.


texts: Ideas for simplificaton - Logic to choose which view to load

texts:
I have a situation where depending on what the value of a uri segment is, my controller will load a different view. Here's what the code looks like in part:

          //which view do we load?
          if (strpos(strtoupper($data['hardwaremodel']),"HP") !== false)
          {
          //hp view should be loaded
          $data['main_content']='hpad';
          }
          elseif (strpos(strtoupper($data['hardwaremodel']),"DELL") !== false)
          {
          $data['main_content']='dellad';
          }
          //load view.
          $this->load->view('includes/template', $data);

For many methods in my controller, I have similar logic. So another method would have the exact same code, but the names of the view would be different dpending on what action the user requested.
So for example, instead of loading the Dell address page above ('dellad') it would load the Dell status page ('dellstatus')

I'm wondering if I change my logic so that all the methods in the controller call a new function that determines what view to load for them will simplify things.

I think the function would have to look something like: (just pseudocode)

 private function loadview($callingfunctionname, $hardwaremodel)
 {
 switch ($callingfunctionname)
 {
     case 'functionA':
           if hardware = dell {
               return "viewabc"
           }
           else {
              return "viewdef"
            }
           break;
     case 'functionB':
           if hardware = dell {
               return "view123"
           }
           else {
              return "view456"
            }
           break;
    }//end switch
   }

But I don't know that it will really simplify things to it this way.  Can you help me improve this code? the other point is that eventually, I will end up with more than 2 hardware types that I have to check for.

Thanks.


texts: Extension pattern in a flask controller using importlib 2.0

texts:
The first edition of the code can be found in this 1.0 version.

To summarize the problem :

I have an endpoint in flask where the work logic change according to the query
I am trying to implement an extension mechanism where the right class is loaded
The first version did not provide caching of the imported class

Based on the answer from @netme, this is a code update where I lazy load the right handler class and cache it :

./run.py:

from flask import Flask, abort
import handler

app = Flask(__name__)

handler_collection = handler.HandlerCollection()

@app.route('/')
def api_endpoint():
    try:
        endpoint = "simple" # Custom logic to choose the right handler
        handler_instance = handler_collection.getInstance(endpoint)
    except handler.UnknownEndpoint as e:
        abort(404)

    print(handler_instance, handler_instance.name)
    # Handler processing. Not yet implemented

    return "Hello World"

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080, debug=True)

./handler.py:

# -*- coding: utf-8 -*-
import importlib

import handlers

class UnknownEndpoint(Exception):
    pass

class HandlerCollection:
    _endpoints_classes = {}

    def addClass(self, endpoint_class):
        self._endpoints_classes[endpoint_class.name] = endpoint_class

    def getClass(self, endpoint_name):
        if (endpoint_name in self._endpoints_classes):
            return self._endpoints_classes.get(endpoint_name)

        try:
            # Try to import endpoint handler from a module in handlers package
            endpoint_module = importlib.import_module(
                '.{}'.format(str(endpoint_name)),
                'handlers')
            endpoint_module.register(self)
        except ImportError as e:
            raise UnknownEndpoint('Unknown endpoint \'{}\''.format(endpoint_name)) from e

        return self._endpoints_classes.get(endpoint_name)

    def getInstance(self, endpoint_name):
        endpoint_class = self.getClass(endpoint_name)
        return endpoint_class()

./handlers/simple.py:

# -*- coding: utf-8 -*-
class SimpleWebhookHandler:
    name = "simple"

def register(handler_collection):
    handler_collection.addClass(SimpleWebhookHandler)

Each handler needs to provide a register function which allows to have different handler class name and each handler class needs to provide a class attribute name.

Can you give me your opinion on this piece of code ? Is it "pythonic" ?


texts: Filter shell script to find lines that contain all specified patterns

texts:
I wrote a script that does the following:

Run another script on the system
Filter the output to find lines that contain ALL of the given patterns
Pipe the output to a second script on the system

I feel like the way I did it is a dirty hack. I use a control character to join the arguments, and then replace them with / && / for awk. Is there a better way? Also, this script is probably vulnerable to injection; I don't really need to worry about hostile attackers being able to manipulate the input to awk but I do need to worry about typos screwing up the regular expression.

#!/bin/bash

function join {
        local IFS=$'\x02'
        echo "$*" | sed 's/'$'\x02''/\/ \&\& \//g'
}

/path/to/first/script |
awk "/$(join $@)/" |
/path/to/second/script


texts: Selective autorotation in a UINavigationController

texts:
In a current project I needed to enable/disable autorotation of the UI to specific UIView's. I looked around and did not find a working solution that fitted my case and returning NO in

shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

method did not work as it seems to get overridden by the value returned by the UIView in which the UINavigationController resides in.

So I now keep track of which view is currently being pushed into the stack by using the delegate method:

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated

and then check if the current view is my "don't rotate view" in

shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

and return NO if that's the case, works perfectly.

In my code it looks like this:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if (currentView == [DimensionConversionViewController class]) {
        return NO;
    }
    return YES;
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    currentView = [viewController class];
}

This looks more like a hack to me. Has anybody come across the same problem and solved it in another/more elegant way? As stated above this seems to be the only way to achieve this.


texts:
I created a SafeQueue class, which stores pointers. It has two methods:

push: Adds a new pointer to the queue
next: If the queue is empty, returns nullptr. Otherwise it returns the front element, and pop the queue

Most of the time, I have one producer and one consumer. But there may be more.

The producer just simply calls .push(ptr)

The consumer(s) call .next(), until a nullptr is returned. Or they continue the loop forever.

The reason I did this, is to eliminate .isEmpty function, so between the .empty() and .front() no other thread can pop the queue.

It works, but I don't think, that it is the preferable or an optimal solution for the problem.

The code is:

template<class T>
class SafeQueue {

    std::queue<T*> q;
    std::mutex m;

public:

    SafeQueue() {}

    void push(T* elem) {

        m.lock();
        if(elem != nullptr) {
            q.push(elem);
        }
        m.unlock();

    }

    T* next() {

        T* elem = nullptr;

        m.lock();
        if(!q.empty()) {
            elem = q.front();
            q.pop();
        }
        m.unlock();

        return elem;

    }

};