texts:
I made a function that returns the number displayed for pagination. I want to get something like this (parentheses is the only show where the active site):

if pages < 10

1 2 3 4 5 6 7 8 9 10

if pages > 10

1 2 3 ... 20 [30] 40 ... 78 79 80

where [30] is active page. If active page < 3

1 2 [3] 4 ... 20 30 40 ... 78 79 80

etc. My code:

    count_all - number of all items
    items_on_page - items displayed on one page
    page - current page

    countpages = int(float(count_all+(items_on_page-1))/float(items_on_page))
    linkitems = 10

    if countpages > (linkitems-1):
        countpagesstr = list()
        for i in range(1,int(float(linkitems+(2))/float(3))):
            countpagesstr += [str(i)]

        countpagesstr += ['...']
        sr = int(countpages/2)
        for i in range(sr-1, sr+1):
            countpagesstr += [str(i)]

        countpagesstr += ['...']
        for i in range(countpages-3, countpages):
            countpagesstr += [str(i)]
    else:
        cp = list()
        for c in range(1,countpages+1):
            cp.append(str(c))
        countpagesstr = cp

    return countpagesstr

How to do it better?


texts:
I'm trying to track down what I suppose to be memory/thread leak in one of my programs.

My program uses a function to upload a file to a Windows Azure Storage Blob. In order to make this function resilient to various transient error conditions (such as intermittent network failures, etc.), I want to make use of the Transient Fault Handling Application Block for Windows Azure "topaz", part of Enterprise Library, which includes a configurable retry mechanism.

Also, in order to circumvent timeout conditions when dealing with large file and improve and reduce the scope for portions of the upload that should be repeated in case of failure, I try to upload the specified file stream in chunks, that each get uploaded independently.

Finally, in order to adhere to best practices using Windows Azure Storage, I make use of asynchronous operations as much as possible when dealing with Windows Azure, in an attempt to improve the scalability of my apps.

Here is the resulting snippet function :

    public static Task ChunkedUploadStreamAsync(CloudBlockBlob blob, Stream source, BlobRequestOptions options, int chunkSize, RetryPolicy policy)
    {
        var blockids = new List<string>();
        var blockid = 0;

        var count = 0;
        var bytes = new byte[chunkSize];

        // first create a list of TPL Tasks for uploading blocks asynchronously

        var tasks = new List<Task>();

        while ((count = source.Read(bytes, 0, bytes.Length)) != 0)
        {
            var id = Convert.ToBase64String(BitConverter.GetBytes(++blockid));

            Func<Task> uploadTaskFunc = () => new TaskFactory()
                .FromAsync(
                    (asyncCallback, state) => blob.BeginPutBlock(id, new MemoryStream(bytes, 0, count), null, null, null, null, asyncCallback, state)
                    , blob.EndPutBlock
                    , null
                )

                .ContinueWith(antecedent => blockids.Add(id), TaskContinuationOptions.NotOnFaulted);

            tasks.Add(policy.ExecuteAsync(uploadTaskFunc));
        }

        return new TaskFactory().ContinueWhenAll(
            tasks.ToArray(),
            array =>
                {
                    // propagate exceptions and make all faulted Tasks as observed
                    Task.WaitAll(array);

                    // create continuation task for committing uploaded blocks
                    Func<Task> commitTaskFunc = () => new TaskFactory()
                        .FromAsync(
                            (asyncCallback, state) => blob.BeginPutBlockList(blockids, asyncCallback, state)
                            , blob.EndPutBlockList
                            , null);

                    policy
                        .ExecuteAsync(commitTaskFunc)
                        .Wait();
                });
    }

With Performance Monitor, I can observe that after calling this function, the number of threads and amount of memory used by my program is increasing significantly. For instance, here is a snapshot of just one call of this function :

Please, can someone advise as to where I'm doing something wrong. Please, suggest a better design if necessary.


texts: Fixed space between two dynamically sized blocks

texts:
Trying to come up with a way to have a fixed space (eg 20px) between two blocks on a single line which dynamically resize to fit that line (50% each minus the fixed space between).

I ended up with the following code (demo):

HTML:

foo

bar

CSS:

.cont{
    outline: 3px solid #ddd;
    position: relative;
    height: 50px;
}

.cont div{
    border: 1px solid #f0f;
    background: #fef;
    height: 40px;
    position: absolute;
    top: 0;
}

.left{
    left: 0;
    right: 50%;
    margin-right: 10px;
}

.right{
    left: 50%;
    right: 0;
    margin-left: 10px;
}

Is this a common or a good way to do it? Are there other or better ways (which work in IE >= 7).

Tested successfully in IE8 & IE9, and latest versions of Chrome, Firefox, and Opera.


texts: Infinite Monkey Theorem Python Comparison

texts:
I wrote code to demonstrate the Infinite Monkey Theorem which states that if a monkey types at a keyboard for an infinite amount of time it will almost surely type a given text such as William Shakespeare. Here I've replaced the monkey with Python code. I have a sentence and let Python choose from the 26 letters of the alphabet and a space and have it randomly try to generate the chosen sentence.

import string
import random

def genString():
    letters = list(string.ascii_lowercase + " ")
    testList = [random.choice(letters) for letter in letters]
    testString = ''.join(testList)
    return testString

def score(n):
    score = 0
    test = "methinksit is like a weasel"
    if test == n:
        score = 100
    else:
        for letter in range(len(test)):
            if test[letter] == n[letter]:
                score = 1/27 + score
            else:
                score = 0/27 + score
    score = score * 100
    return score

def test():
    count = 0
    localScore = 0
    n = genString()
    guessString = ""
    while(localScore != 100):
        if score(n) > localScore:
            localScore = score(n)
            guessString = n
        if count%1000 == 0:
            print(localScore)
            print(guessString)
            print(count)
        n = genString()
        count = count + 1

However, for the test function I had a previous version which was:

def test2():
    count = 0
    localScore = 0
    n = genString()
    guessString = ""
    testList = [score(n)]
    while(100 not in testList):
        if max(testList) > localScore:
            localScore = max(testList)
            guessString = n
        if count%1000 == 0:
            print(localScore)
            print(guessString)
            print(count)
        n = genString()
        testList.append(score(n))
        count = count + 1

However, after testing it out I realized it was super slow. I'm guessing that the problem is that test2 has a runtime of O(n2) because of the loop and the max function and my previous test has a runtime of O(n). Is this true? Or is there another reason why it's super slow?


texts:
This program implements a sorted grep, that is, a specialized version of grep for sorted files. It uses binary search for the lines of a file that begin with a certain string.

You can copy and paste the code in a file and run it as:

$> runhaskell sgrep.hs "string to find" sorted_file

I'm looking for suggestions about style, efficiency, and correctness.

module Main where

import Data.List (isPrefixOf)
import Data.Maybe (isNothing, fromJust)
import System.Environment (getArgs)
import System.IO

-- Chunk of a file
data Chunk = Chunk Handle Integer Integer

-- Is char newline?
isNL :: Char -> Bool
isNL c = c == '\n'

-- Are we at the beginning of file?
isBOF :: Handle -> IO Bool
isBOF = (fmap (== 0)) . hTell

-- Go to beginning of line
goToBOL :: Handle -> IO ()
goToBOL h = do
        bof <- isBOF h
        if bof
           then return ()
           else do
                   eof <- hIsEOF h
                   if eof
                      then do
                              hSeek h RelativeSeek (-2)
                              goToBOL h

                      else do
                              c <- hGetChar h
                              if isNL c
                                 then return ()
                                 else do
                                         hSeek h RelativeSeek (-2)
                                         goToBOL h

getCurrentLine :: Handle -> IO String
getCurrentLine h = goToBOL h >> hGetLine h

getPrevLine :: Handle -> IO (Maybe String)
getPrevLine h = do
        goToBOL h
        bof <- isBOF h
        if bof
           then return Nothing
           else do
                   hSeek h RelativeSeek (-2)
                   goToBOL h
                   bof <- isBOF h
                   if bof
                      then return Nothing
                      else do
                              hSeek h RelativeSeek (-2)
                              goToBOL h
                              line <- hGetLine h
                              return $ Just line

goTo :: Handle -> Integer -> IO ()
goTo h i = do
        hSeek h AbsoluteSeek i

search :: Chunk -> String -> IO (Maybe String)
search (Chunk h start end) str
        | start >= end = return Nothing
        | otherwise = do
                if mid == (end - 1)
                   then return Nothing
                   else do
                           goTo h mid
                           midLine <- getCurrentLine h
                           prevLine <- getPrevLine h
                           --  putStrLn $ "*** " ++ show start ++ " " ++ show end ++ " " ++ show mid ++ " " ++ midLine ++ ", " ++ show prevLine
                           if str `isPrefixOf` midLine && ((isNothing prevLine) || not (str `isPrefixOf` (fromJust prevLine)))
                              then return $ Just midLine
                              else if str < midLine
                                      then search (Chunk h start mid) str
                                      else search (Chunk h mid end) str
           where mid = (start + end) `div` 2

sgrep :: Handle -> String -> IO ()
sgrep h s = do
        len <- hFileSize h
        match <- search (Chunk h 0 len) s
        --  putStrLn $ show match
        c <- hGetContents h
        putStrLn . unlines $ takeWhile (isPrefixOf s) (lines c)

main :: IO ()
main = do
        args <- getArgs
        let s = head args
        putStrLn s
        let fname = head $ tail args
        withFile fname ReadMode (\h -> sgrep h s)


texts: Shell Sort Comparisons/Exchanges Counter

texts:
I need to analyze shell-sort. Currently I am working with it having an increment of N/2. I will then go on to try more efficient increments.

However, my count for comparisons/exchanges seems too low for an array of 2000 elements. I've tried changing it around some but still everything seems too low. Could someone look over my code and see if my counters are in the right places?

public class Sort {
    static int exchanges= 0;
    static int comparisons= 0;

    public static void SegmentedInsertionSort (AnyType[] array, int N, int gap)
    {
        for (int index = gap ; index < N ; index++)
        {
            AnyType temp;
            int j = index - gap;
            while (j >= 0)
            {
                  comparisons++;
                  if (array[j].isBetterThan(array[j+gap]))
                  {
                       temp = array[j];
                       array[j] = array[j + gap];
                       array[j + gap] = temp;
                       j = j - gap;
                       exchanges++;
                  }
                  else j = -1;
            }
        }
    }

    public static void shellSort (AnyType[] array)
    {
        int N = 2000;
        int gap = N/2;
        while (gap > 0)
        {
            SegmentedInsertionSort(array, N, gap);
            gap = gap / 2;
        }
    }
}

Also, I know there are other ways to code this, but the pseudo-code template I was given by my professor looked like this.


texts: Static quiz module with predefined answers

texts:
I was building a quiz module for one website. It is a simple true/false statements where you first choose the answer, the correct answer is displayed, and then you can move forward to the next question.

For better understanding, please find working code snippet here.

I need mentor guidance in order to make my existing code shorter and optimized.

Here is the jQuery code for this quiz module:

var flag = $('.quiz ul'),
    currentPosition = 0,
    currentQuestion = 0,
    slideWidth = 200,
    option = $('.flag'),
    tryCTA = $('.CTAtry'),
    nextQuestion = $('.next'),
    answer = $('span.answer')
    questionWrapper = $('.quiz ul'),
    totalQuestions = $('.quiz ul li').length,
    answers = ["True","False","False"];

//Set UL width
questionWrapper.css('width',totalQuestions*slideWidth)

  option.on('click',function(e) {
      e.preventDefault();
      var nextCTA = $(this).parent().next(nextQuestion).length,
          optionWrapper = $(this).parent();
      if(nextCTA) {
          optionWrapper.next(nextQuestion).show();
      } else {
          tryCTA.show();
      }
      optionWrapper.parent().find(answer).html(answers[currentQuestion]).show();
      optionWrapper.hide();
  });

  nextQuestion.on('click',function(e){
      e.preventDefault();
      currentPosition = currentPosition+1;
      $(this).parent().parent().animate({
          'marginLeft' : slideWidth*(-currentPosition)
      });
      currentQuestion++;
  });

  tryCTA.on('click',function(e) {
      e.preventDefault();
      resetQuiz(e);
      $(this).hide();
  })

  function resetQuiz(e) {
      $('.quiz ul').animate({
           opacity: 0
      },0)
      .animate({
           opacity: 1
       },500)

      $('span.answer').html(" ");
      $('.quiz ul').css('margin-left','0');
      $('.options').show();
      $('.next').hide();
      currentPosition = 0;
      currentQuestion = 0;
  }

HTML:

Writing Object Oriented JavaScript is not a FUN.

            True
            or
            False

        Next

Let's give it a try! No harm in learning anything NEW.

            True
            or
            False

        Next

Some code running !

            True
            or
            False

Try Again!


texts: Displaying JSON data from a server in a UICollectionView

texts:
This code pulls JSON from a server and delivers some data like imageURL, titleString and videoURL. Then it places them in a UICollectionView and displays them.

import UIKit
import Alamofire

class vcWatch: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var myActivityIndicator: UIActivityIndicatorView!
@IBOutlet weak var myCollectionView: UICollectionView!

var images:[String] = []
var videos:[String] = []
var lableTitles:[String] = []

let link = "http://alifetouched.com/lib/videos.json.php"

override func viewDidLoad() {
    super.viewDidLoad()

    myActivityIndicator.isHidden = false
    myActivityIndicator.startAnimating()
    loadImages()
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return images.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell:cvCell = collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as! cvCell

    // Videos
    let requestURL = URL(string:self.videos[indexPath.row])
    let request = URLRequest(url: requestURL!)

    // Images
    let imageString = self.images[indexPath.row]
    let imageUrl = NSURL(string: imageString)
    let imageData = NSData(contentsOf: imageUrl! as URL)

    cell.videoCell.loadRequest(request)
    cell.labelCell.text = self.lableTitles[indexPath.row]

    if(imageData != nil){
        cell.imageCell.image = UIImage(data: imageData! as Data)
    }

    return cell
}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath){
    print("User Tapped: \(indexPath.row)")
}

func loadImages() {

    Alamofire.request(link)
        .validate()
        .responseJSON { (response) in

            guard response.result.isSuccess else {
                print("Error with response: \(response.result.error)")
                return
            }

            guard let dict = response.result.value as? Dictionary <String,AnyObject> else {
                print("Error with dictionary: \(response.result.error)")
                return
            }

            guard let dictData = dict["VideoJSON"] as? [Dictionary <String,AnyObject>] else {
                print("Error with dictionary data: \(response.result.error)")
                return
            }

            for data in dictData {
                self.videos.append(data["media_url"] as! String)
                self.images.append(data["icon_url"] as! String)
                self.lableTitles.append(data["title"] as! String)
            }

            self.myCollectionView.reloadData()
            self.myActivityIndicator.stopAnimating()
            self.myActivityIndicator.isHidden = true

            return

    }
}


texts: Could random unique selection using while cause an infinite loop?

texts:
I recently came across code that looked something like this (generates 4 random numbers in an array, this is not the actual code, I just wrote this up now, so it's untested):

var uniqueNumbers = new Array();
var count = 4;
var max = 10;

function main() {
    for (var i = 0; i < count; i++) {

        do {
            var tempNum = Math.floor(Math.random() * max); //number 0-9
        } while (arrayContains(uniqueNumbers, tempNum))

        uniqueNumbers.push(tempNum);
    }
}

function arrayContains(a, val) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] == val) return true;
    }
    return false;
}

Is it possible that the while loop could possibly be infinite (or at least take a lot of time)? In the way that it just so happens that we continuously randomly choose a number that happens to be in the array? I imagine the probability of this happening would go up as count increases. It's kind of reminding me of bogosort.

I would think that this would be improved by selecting from a diminishing 'pool' of numbers, instead of selecting randomly, something like:

var uniqueNumbers = new Array();
var count = 4;
var max = 10;
var pool = new Array();

function main() {
    createPool();
    for (var i = 0; i < count; i++) {
        if (var tempNum = selectFromPool()) {
            uniqueNumbers.push(tempNum);
        }
    }
}

function createPool() {
    for (var i = 0; i < max; i++) {
        pool.push(i);
    }
}

function selectFromPool() {
    if (pool.length <= 0) return false;

    var selectedIndex = Math.floor(Math.random() * pool.length);
    var selectedValue = pool[selectedIndex];

    pool = pool.slice(selectedIndex, selectedIndex+1);

    return selectedValue;
}

Is this a better, less fragile way of doing it? Or is there some proof that the while loop will never be infinite because of the pseudo-random nature of computer generated random numbers?


texts: What does the Bob say? (clojure version)

texts:
I'm doing the exercices from clojureacademy.
Here are the instructions for this one.

  Bob is a lackadaisical teenager. In conversation, his responses are very limited.

  Returns "Whatever." if given phrase is one of the following inputs:

  "Tom-ay-to, tom-aaaah-to."
  "Let's go make out behind the gym!"
  "It's OK if you don't want to go to the DMV."
  "Ending with ? means a question."
  "1, 2, 3"

  Returns "Woah, chill out!" if given phrase is one of the following inputs:

  "WATCH OUT!"
  "WHAT THE HELL WERE YOU THINKING?"
  "ZOMG THE %^@#$(^ ZOMBIES ARE COMING!!11!!1!"
  "1, 2, 3 GO!"
  "I HATE YOU"

  Returns "Sure." if given phrase is one of the following inputs:

  "Does this cryogenic chamber make me look fat?"
  "4?"

  Returns "Fine. Be that way!" if given phrase is one of the following inputs:

  ""
  " "

Here is my code in src/ex1_bob/core.clj:

(ns ex1-bob.core
  (:gen-class))

; responses
; =======================
(def whatever "Whatever.")
(def chill-out "Woah, chill out!")
(def sure "Sure.")
(def fine "Fine. Be that way!")

; triggers
; =======================
(def sure-triggers
  ["Does this cryogenic chamber make me look fat?" "4?"])
(def whatever-triggers
  ["Tom-ay-to, tom-aaaah-to."
   "Let's go make out behind the gym!"
   "It's OK if you don't want to go to the DMV."
   "Ending with ? means a question."
   "1, 2, 3"])
(def chill-out-triggers
  ["WATCH OUT!"
   "WHAT THE HELL WERE YOU THINKING?"
   "ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!"
   "1, 2, 3 GO!"
   "I HATE YOU"])

(defn has-phrase
  "return `true` if the given phrase is found in the collection, `false` otherwise"
  [phrase coll]
  (if (some #(= phrase %) coll)
    true
    false))

(defn response-for
  "return `true` if the given phrase is found in the collection, `false` otherwise"
  [phrase]
    (cond
      (has-phrase phrase whatever-triggers)  whatever
      (has-phrase phrase chill-out-triggers) chill-out
      (has-phrase phrase sure-triggers)      sure
      (= (clojure.string/trim phrase) "")    fine))

I also wrote some tests in test/ex1_bob/core_test.clj:

(ns ex1-bob.core-test
  (:require [clojure.test :refer :all]
            [ex1-bob.core :refer :all]))

; This does not work because `is` is a macro, and it seems it does not like to
; be used in a `map` or with `comp`.
;
; (deftest non-working-response-for-chill-out-triggers
;   (doall (map (comp is #(= % chill-out) response-for) chill-out-triggers)))

(deftest response-for-chill-out-triggers
  (is (every? #(= % chill-out) (map response-for chill-out-triggers))))

(deftest response-for-whatever-triggers
  (is (every? #(= % whatever) (map response-for whatever-triggers))))

(deftest response-for-sure-triggers
  (is (every? #(= % sure) (map response-for sure-triggers))))

(deftest response-for-empty-string
  (is (every? #(= % fine) (map response-for [""]))))

Two things make me a bit unhappy about this code:

the has-phrase function seems a bit silly. Do I really have to write a function to return true/false if an element is found in a collection? I feel that there must be a function that does this already
I first wrote my unit test with:

(deftest non-working-response-for-chill-out-triggers
  (doall (map (comp is #(= % chill-out) response-for) chill-out-triggers)))

The idea is to have one assertion for each item, which I assumed would give me a better error message in case of a failure (because I know which item failed). But it seems that is is a macro and somehow, the interpreter doesn't like this.


texts: Slow Erlang code to find Pythagorean triplets

texts:
Why does this Erlang code take about one minute on my machine?

On Pascal something like this took less then second on my machine.

What I can do to speed it up?

-module(slow).
-export([slow/0]).

pyth(N) ->
    [{A, B, C} ||
        A <- lists:seq(1, N - 2),
        B <- lists:seq(A + 1, N - 1),
        C <- lists:seq(B + 1, N),
        A + B + C =< N,
        A * A + B * B == C * C].

slow() -> io:format("~p\n", [pyth(1000)]).


texts: Check whether an integer's leftmost bits are ones in Rust

texts:
I'm trying to validate if an integer represents a valid IPv6 mask, which boils down to checking if all the left-most bits of an u128 are 1s, and all the right-most bits are 0s. For instance:

0 is valid
0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff is valid
0xffff_ffff_ffff_ffff_0000_0000_0000_0000 is valid
0xffff_ffff_fff8_0000_0000_0000_0000_0000 is valid
0xffff_ffff_fffe_0000_0000_0000_0000_0000 is valid

but:

1 is invalid (its representation is 0x0000_0000_0000_0000_0000_0000_0000_0001)
0x0fff_ffff_ffff_ffff_ffff_ffff_ffff_ffff is invalid
0xffff_ffff_fff1_0000_0000_0000_0000_0000 is invalid

Here is the function:

/// Check whether the given integer represents a valid IPv6 mask.
/// A valid IP mask is an integer which left-most bits are 1s, and right-most bits are 0s.
fn is_valid_ipv6_mask(value: u128) -> bool {
    // flag to check if we're currently processing 1s or 0s
    let mut count_ones = true;

    // check each byte starting from the left.
    for byte_index in (0..=15).rev() {
        let x = (value >> (byte_index * 8)) & 0xff;
        match x {
            // We're processing 1s and this byte is 0b1111_1111
            0xff if count_ones => continue,
            // We're processing 0s and this byte is 0b0000_0000
            0x00 if !count_ones => continue,
            // We're processing 1s and this byte is 0b0000_0000.
            // That means all the remaining bytes should be 0 for this integer
            // to be a valid mask
            0x00 if count_ones => {
                count_ones = false;
                continue;
            }
            // We're processsing 1s and this byte has at least a 1, so we have
            // to check bit by bit that the left-most bits are 1s and the
            // right-most bits are 0s
            byte if byte > 0 && count_ones => {
                let mut bit_index = 7;
                while (byte >> bit_index) & 1 == 1 {
                    // This does not overflow, because we now this byte has at
                    // least a 0 somewhere
                    bit_index -= 1
                }
                // At this point, all the bits should be 0s
                count_ones = false;
                for i in 0..bit_index {
                    if (byte >> i) & 1 == 1 {
                        return false;
                    }
                }
            }
            // Any other case is an error
            _ => return false,
        }
    }
    true
}

And to test it:

fn main() {
    assert!(is_valid_ipv6_mask(0));
    assert!(is_valid_ipv6_mask(
        0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff
    ));
    assert!(is_valid_ipv6_mask(
        0xffff_0000_0000_0000_0000_0000_0000_0000
    ));
    assert!(is_valid_ipv6_mask(
        0xff80_0000_0000_0000_0000_0000_0000_0000
    ));
    assert!(!is_valid_ipv6_mask(
        0xff01_0000_0000_0000_0000_0000_0000_0000
    ));
    assert!(!is_valid_ipv6_mask(
        0xffff_0000_ffff_ffff_ffff_ffff_ffff_ffff
    ));
}

Link to playground.

The problem is that have the feeling that there must be a much simple solution to this problem. After all, bit operations are what computers do, I can't believe there's not more concise and more efficient way to check if an integer is all 1s then all 0s.


texts: Better way to create directories using File

texts:
I have this code that generally creates directories within a directory.

File  userFolder = new File(rootPath+"/media/"+userBean.getUsername());
    File  userPhotosDir = new File(rootPath+"/media/"+userBean.getUsername()+"/photos");
    File  userAudioDir = new File(rootPath+"/media/"+userBean.getUsername()+"/tracks");
    userFolder.mkdir();
    userPhotosDir.mkdir();
    userAudioDir.mkdir();

When I this code runs it will generally look like this

The userFolder

\media\somename

The Photos folder

\media\somename\photos

The Audio Folder

\media\somename\folder

Where the photos and audio folder are inside the somename folder. while the somename folder is inside the media folder


texts: Applies the Largest Remainder Method to a number property in a list of objects

texts:
I need to round BigDecimal numbers according to the Largest Remainder Method (LRM). Please reference this SO post with this answer. Here's my version of the algorithm in Java:

public class LargestRemainderMethod {

    public static List<BigDecimal> roundValues(List<BigDecimal> values, int roundTo, BigDecimal desiredSum) {
        // 1. Sort by largest remainder
        values.sort((d1, d2) ->
            -d1.remainder(BigDecimal.ONE.divide(BigDecimal.TEN.pow(roundTo))).
            compareTo(d2.remainder(BigDecimal.ONE.divide(BigDecimal.TEN.pow(roundTo)))));

        // 2. Rounding everything down
        List<BigDecimal> roundedValues = new ArrayList<BigDecimal>(values.size());
        for (BigDecimal value : values) {
            roundedValues.add(value.setScale(roundTo, RoundingMode.DOWN));
        }

        // 3. Now round up values until desired sum is achieved or we have
        //    no other values to round up
        for (int i = 0; i < values.size(); i++) {

            BigDecimal roundedSum = roundedValues.stream().reduce(BigDecimal.ZERO, BigDecimal::add);

            if (roundedSum.compareTo(desiredSum) != 0) {
                roundedValues.set(i, values.get(i).setScale(roundTo, RoundingMode.UP));
            }
        }
        return roundedValues;
    }
}

I apply LRM to a list of objects with a BigDecimal value. For example:

List<BigDecimal> fractionsOfOwnership =
    owners.stream()
          .map(Owner::getFractionOfOwnership)
          .collect(Collectors.toList());

List<BigDecimal> roundedValues = LargestRemainderMethod.roundValues(fractionsOfOwnership, 1, new BigDecimal("1.0"));

Next, for each owner, I need overwrite the original fractionOfOwnership with the corresponding rounded value determined by the LRM roundedValues method.

Currently, I sort the owners as I know they'll be sorted in LargestRemainderMethod.roundValues. Then, I iterate through the owners list setting the rounded values using the same index.

owners.sort((o1, o2) ->
        -o1.getFractionOfOwnership().remainder(BigDecimal.ONE.divide(BigDecimal.TEN.pow(roundTo))).
        compareTo(o1.getFractionOfOwnership().remainder(BigDecimal.ONE.divide(BigDecimal.TEN.pow(roundTo)))));
for (int i = 0; i < owners.length; i++) {
     owners.get(i).setFractionOfOwnership(roundedValues.get(i));
 }

But this violates DRY. How can this be improved such that I'm not duplicating code?


texts:
Is this a good way to prevent two sequential numbers from repeating, or is there a better, more efficient way of doing this? By efficient, I mean a less CPU and memory consuming process.

while (random === lastrandom) {
    random = Math.floor(Math.random() * 3) + 1;
}
lastrandom = random;


texts: PHP & Mysqli Code - Is this code safe for a simple search?

texts:
I am writing some code to search my database and show results. Is the below code ok and safe enough? new to PHP and Mysqli so really appreciate any help that I can get on this subject. Thanks

<?php

    $conn = mysqli_connect("localhost", "root", "", "tutorial");

    if(mysqli_connect_errno()){
        echo "Failed to connect: " . mysqli_connect_error();
    }

    error_reporting(0);

    $output = '';

    if(isset($_GET['q']) && $_GET['q'] !== ' '){
        $searchq = $_GET['q'];

        $q = mysqli_query($conn, "SELECT * FROM search WHERE keywords LIKE '%$searchq%' OR title LIKE '%$searchq%'") or die(mysqli_error());
        $c = mysqli_num_rows($q);
        if($c == 0){
            $output = 'No search results for "' . $searchq . '"';
        } else {
            while($row = mysqli_fetch_array($q)){
                $id = $row['id'];
                $title = $row['title'];
                $desc = $row['description'];
                $link = $row['link'];

                $output .= '

' . $title . '

' . $desc . '

                            ';
            }
        }
    } else {
        header("location: ./");
    }
    print("$output");
    mysqli_close($conn);

?>


texts: Displaying a person's personal information with formatting

texts:
I am learning C# from a book, and there is an exercise as follows:

  Write a program that has a person enter full name, age, and phone
  number. Display this information with formatting. Also display the
  person's initials.

I wrote some code and I feel that it could be improved, so I ask anyone to comment on it.

using System;
using System.Collections.Generic;

internal class Person
{
    public string fname;
    public string mname;
    public string lname;
    public int age;
    public string phnumber;

    public Person()
    {
        fname = KeyInput.keyIn("\n\nPlease enter your first name");
        if (fname.ToLower() == "exit") return;

        mname = KeyInput.keyIn("\nPlease enter your middle name");
        lname = KeyInput.keyIn("\nPlease enter your last name");

        while (true)
        {
            try
            {
                age = Convert.ToInt32(KeyInput.keyIn("\nPlease enter your age"));
                break;
            }

            catch (ArgumentException)
            {
                Console.WriteLine("No value was entered");
            }

            catch (FormatException)
            {
                Console.WriteLine("You didn't entered a valid number");
            }

            catch (Exception e)
            {
                Console.WriteLine("Something went wrong with the conversion.");
            }
        }

        phnumber = KeyInput.keyIn("\nPlease enter your  phone number");
    }

    public void personDataDisplay()
    {
        Console.WriteLine("\nYour name is: " + fname + " " + mname[0] + "." + " " + lname);
        Console.WriteLine("Your initials are: " + fname[0] + mname[0] + lname[0]);
        Console.WriteLine("Your age is: " + age);
        Console.WriteLine("Your phone number is: " + phnumber + "\n");
    }
}

internal class KeyInput
{
    public static string keyIn(string scrtext)
    {
        Console.WriteLine(scrtext);
        string buffer = Console.ReadLine();
        return buffer;
    }
}

internal class MyApp
{
    public static void Main()
    {
        Console.WriteLine("Please enter data for person(s). Enter EXIT to end.");

        List<Person> list_persons = new List<Person>();

        while (true)
        {
            Person person = new Person();
            list_persons.Add(person);

            if (person.fname.ToLower() == "exit")
                break;
        }

        foreach (Person person in list_persons)
        {
            if (person.fname.ToLower() == "exit")
                break;

            person.personDataDisplay();
        }
    }
}


texts: Socket.io Node.js Object Oriented Code Structure Approach

texts:
following application:
Users can join Rooms. A Gameroom inherits from Room and has a queue where Users can queue for a game. If enough people queue they get thrown into a game lobby. Lobby also inherits from Room. Rooms implement chat functionality which should be used in Gamerooms and Lobbies aswell.

Right now I am passing the io Object to the instantiations and use it to listen to events specific to their class features.

What improvements can I do? Why is this a bad or good design choice? What alternatives are there? What is there to consider?
Should I split  the classes "Room", "Gameroom" and "Lobby" into a more distinct Model & Controller?

UML Diagram

Server instantiates the Rooms.
Server.js

const io = socket.listen(
    http.createServer(app).listen(8080)
  );

console.log('Server listening..');

app.get('/', function (req, res) {
    res.sendFile(__dirname + '/test.html');
  });

var main = new Room('', io);
var a = new Gameroom('a', io);
var b = new Gameroom('b', io);

Room is the parent class, but can also be instantiated. It should be a root channel where everyone joins when they login.
Room.js

class Room {
  constructor(name, io) {
    this.name = name;
    this.users = [];
    this.namespace = io.of('/' + name);
    this.listenOnRoom();
  }

  listenOnRoom() {
    this.namespace.on('connection', (socket) => {
      ...

      socket.on('disconnect', (msg) => {
        ...
      });

      socket.on('chatMessage', (msg) => {
        ...
      });
    });
  }
}
module.exports = Room;

Gameroom adds the ability to queue for a game.
Gameroom.js

class Gameroom extends Room {
  constructor(name, io) {
    super(name, io);
    this.io = io;
    this.queue = [];
    this.lobbies = [];
    this.listenOnGameroom();
  }

  listenOnGameroom() {
    this.namespace.on('connection', (socket) => {

      socket.on('userJoinQueue', () => {
        ...
        this.lobbies.push(new Lobby(this.name ,lobbyId, participants, this.io));
      });

      socket.on('userLeaveQueue', () => {
        ...
      });

      socket.on('userLeaveLobby', () => {
        ...
      });
    });
  }
}

module.exports = Gameroom;

Lobby is instantiated by the Gameroom when there are enough players in the queue.
Lobby.js

class Lobby extends Room {
  constructor(gameroom, name, users, io) {
    super(gameroom + '/' + name, io);
    this.users = users;
    this.readyUsers = [];
    this.listenOnLobby();
  }

  listenOnLobby() {
    this.namespace.on('connection', (socket) => {

      socket.on('userReady', () => {
        ...
      });

      socket.on('userUnready', () => {
        ...
      });
    });
  }
}

module.exports = Lobby;


texts:
I was writing a little coding kata, and wanted to have a hook which managed a list of names. The hook should allow adding a name to the list, and also make the list available to the component.

I didn't want to bring in a state management library, or complicate the code with having to useDispatch or anything like that. I also didn't want to bring in a package that explicitly enables a useSharedState or useGlobal thing. Here's what I came up with.

import { useState } from 'react';

let list: string[] = []; // Force a single instance of a list, even if Hook is used in multiple places

const useNameList = () => {
    const [, _setList] = useState<string[]>(list);
    const [lastSelectedItem, setLastSelectedItem] = useState<string | null>(null);

    return {
        add: (name: string) => {
            list = [...list, name];
            // Components are delayed on detecting state updates if you don't explicitly update the hook state too...
            _setList(list);
        },
        names: list
    }
};

export default useNameList;

By setting the list up outside the hook, it forces there to be one instance. However, I still need to setList within a useState; without doing that, there was some buggy stuff happening across different components.


texts: Is there a better way to handle errors in these functions?

texts:
I'm creating a GOLang Linux distribution installer. The architecture is straight forward. I have N parameters and uses them in N installation steps. Summarizing:

Every step implements a interface with the Run method.
For each step S, do S.Run(parameters), if failed, handle the error.

The complete source code is here: https://github.com/Munix-Developers/munix-standalone-installer/blob/master/installer/partitions-step.go
I've created a Partition Step. Used to create the desired partitions on the disk. The main loop for the step is as follows:
func (p PartitionsStep) Run(c parser.InstallConfig) error {
    log.Println("starting partition step")
    var err error = nil

    for _, d := range c.Storage.Devices {
        log.Printf("creating gpt label for %s", d.Device)
        err = createGptLabel(d)

        if err != nil {
            return err
        }

        for _, p := range d.Partitions {
            err = createPartition(d, p)
            if err != nil {
                return err
            }

        }

        err = discoverPartitionDevices(&d)
        if err != nil {
            return err
        }
    }

    return nil
}

Looking at this code, I've noticed that there is too many "if err != nil; return error". In the inner functions there are more if statements like that, for example in the discoverPartitionsDevice function:
// Since parted doesn't returns which is the device that was created, we need to find it manually. This function searches
// for partitions where the label starts with "mx" and exists in the configuration
func discoverPartitionDevices(d *parser.DeviceConfig) error {
    blkidOut, err := runBlkid()
    if err != nil {
        return err
    }

    sort.SliceStable(d.Partitions, func(i, j int) bool {
        return d.Partitions[i].Mount <= d.Partitions[j].Mount
    })

    for _, line := range strings.Split(blkidOut, "\n") {
        line = strings.ReplaceAll(line, ": PARTLABEL=", " ")
        line = strings.ReplaceAll(line, "\"", "")
        data := strings.Split(line, " ")

        err = proccessBlkidLine(d, data)
        if err != nil {
            return err
        }
    }

    return nil
}

So, is there a better way to handle this type of error in GOLang?


texts:
I want to parse a CSV file and store the data using the istream >> operator but I am running into big performance issues.

Here is the current version:

#include <vector>
#include <sstream>
#include <fstream>
#include <string>
#include <iostream>

template <class T>
class   CSV
{

    std::vector<std::vector<T>> _data;
    size_t _width;
    size_t _height;

public:

    CSV(const std::string& filepath)
    {
        std::ifstream file(filepath);
        if (!file)
            throw std::exception();

        for (std::string line; std::getline(file, line);)
        {
            std::stringstream ss1(line);
            std::vector<T> row;

            for (std::string field; std::getline(ss1, field, ',');)
            {
                std::stringstream ss2(field);
                T item;

                ss2 >> item;
                row.push_back(item);
            }
            _data.push_back(row);
        }
        _height = _data.size();
        if (!_height)
            throw std::exception();
        _width = _data[0].size();

        for (auto& row : _data)
            if (row.size() != _width)
                throw std::exception();
    }

    size_t  Width(void)
    {
        return _width;
    }
    size_t  Height(void)
    {
        return _height;
    }

    const std::vector<std::vector<T>>   &Data(void)
    {
        return _data;
    }
};

It works but it's slow because I start by making a copy of each line in the file. I then make a copy of that line inside of a stringstream. I then parse each field in that line and make a copy of it. I then make a copy of that inside another stringstream, and finally I extract the data from the stringstream.

Basically there is too much copying, but I honestly don't know how to avoid it with stringstreams. I know there are other ways to parse things that are not stringstreams but then I miss out on using the >> operator and the point of making a templated CSV parser.

For an idea of its speed I have an 80MB file and it takes 11 seconds to parse using CSV<int>. I also have -03 turned on and am using clang++.


texts: Python implementation of Kahn's Algorithm

texts:
Please provide any suggestions on the below code for Kahn's algorithm. Can it be implemented in a better manner, or be improved:

def kahn(graph):
    in_degree = {u : 0 for u in graph}
    for vertices, neighbors in graph.items():
        in_degree.setdefault(vertices, 0)
        for neighbor in neighbors:
            in_degree[neighbor] = in_degree.get(neighbor, 0) + 1

    no_indegree_vertices = {vertex for vertex, count in in_degree.items() if count == 0}

    topological_sort = []
    while no_indegree_vertices:
        vertex = no_indegree_vertices.pop()
        topological_sort.append(vertex)
        for neighbor in graph.get(vertex, []):
            in_degree[neighbor] -= 1
            if in_degree[neighbor] == 0:
                no_indegree_vertices.add(neighbor)

    if len(topological_sort) != len(in_degree):
        print("Graph has cycles; It is not a directed acyclic graph ... ")
        return None
    else:
        return topological_sort

Test Data:

test_graph1 = {
    'A' : set(['B','S']),
    'B' : set(['A']),
    'C' : set(['D','E','F','S']),
    'D' : set(['C']),
    'E' : set(['C','H']),
    'F' : set(['C','G']),
    'G' : set(['F','S']),
    'H' : set(['E','G']),
    'S' : set(['A','C','G'])
}

test_graph2 = {
    'A': [],
    'B': ['A'],
    'C': ['B']
}

test_graph3 = {
    5: [2],
    5: [0],
    4: [0],
    4: [1],
    2: [3],
    3: [1]
}

test_graph4 = {
    1: [2],
    2: [3],
    4: [2],
    5: [3]
}


texts:
I have some code that allows for SQL reuse for C#. I'm pretty happy with it, but the fact that I can't find anything similar on the web makes me think I'm going about it the wrong way. I have a GitHub repo with a Visual Studio solution, and the code is repeated down below.

Here's the use case:

I'm working on a fairly standard C# and SQL Server project where we're generating reports. Each report is essentially the results of SQL query, displayed in HTML in the browser. I'd rather not use an ORM like Entity Framework, since we need to exactly control the SQL for performance reasons (e.g. use SQL server windowing functions, table hints, etc).

However, many of the reports are similar, just slicing and dicing by different attributes, so there's a desire for code reuse. SQL Server has stored procedures, views, and functions, but the consensus seems to be that you'll get into trouble trying to use them to create abstractions. To get around this I'm trying to use C# to reuse SQL code.

I'm essentially using Visual Studio's T4 text templates to generate SQL files at development time. I'm then passing the SQL to Stack Exchange's Dapper.NET project to handle variable substitution, issuing the query, and POCO [de]serialization.

Given a query like this, in the template file CuteAnimalsByLocation.tt:

<#@ output extension=".sql" #>
select * from animals a
where a.IsCute = 1 and a.IsFuzzy = 1 and a.Location = @location

And this file, DeadlyMachinesByLocation.tt:

<#@ output extension=".sql" #>
select * from DeadlyMachines m
where m.IsLethal = 1 and m.HasExplosives = 1 and m.Location = @location

I can reuse the above queries in a more complex query by writing the following, AnimalsInPeril.tt:

<#@ output extension=".sql" #>

WITH
CuteAnimalsInLocation as
(
    <#@ include file="CuteAnimalsByLocation.tt" #>
),
DeadlyMachinesInLocation as
(
    <#@ include file="DeadlyMachinesByLocation.tt" #>
)
select a.* from CuteAnimalsInLocation a
inner join DeadlyMachinesInLocation m on a.Location = m.Location

I can run all 3 of these queries like this: (assuming the POCOs Animal and DeadlyMachine exist; they're just POCOs that map to the table schemas):

using (var connection = new SqlConnection(ConnectionString))
{
    connection.Open();
    var queryParams = new { Location = "NorthAmerica" };

    IEnumerable<Animal> animalsNeedingHelp =
        connection.QueryFromFile<Animal>("AnimalsInPeril", queryParams);
    IEnumerable<Animal> cuteAnimals =
        connection.QueryFromFile<Animal>("CuteAnimalsByLocation", queryParams);
    IEnumerable<DeadlyMachine> deadlyMachines =
        connection.QueryFromFile<DeadlyMachine>("DeadlyMachinesByLocation", queryParams);
}

connection.QueryFromFile is defined as this, and depends on Dapper:

public static class DapperFileExtensions
{
    public static IEnumerable<TReturn> QueryFromFile<TReturn>(this IDbConnection cnn, string file, object params = null)
    {
        var sql = File.ReadAllText(file + ".sql");
        return cnn.Query<TReturn>(sql, params);
    }
}

Can anyone see problems with this approach? I guess the only thing I can think of is that I could add caching around the File.ReadAllText call.


texts:
TL;DR: The algorithm receives a string as input, allocate another string to be the final digest, and start working on them. For each char on the digest (a null character on a first moment), it XORs it with every character from the original string, also XORing it with a set of "random bytes" that are specified in the beginning of the code.

Here are some results:

  "000" = qpktluvsqpktluvs; "001" = bcygoiwnccxfohxn;

  "abc" = ayedeufryzdfftds; "cba" = cqgleoxlarrnfnvm;

  "aaaaa" = hingixcphingixcp; "aabaa" = aprndovlapgneovk;

Am I mathematically getting the full potential of the performance I'm using? How good would you say it is compared to other hashing algorithms? Thanks a lot for reading!
This is my first hashing algorithm. My goal is to be simple and performatic. How can I improve it?

#define HASH_LENGTH 16
char *hash(char *input){
    // Alphabet and length
    const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    const int alphabetLen = sizeof(alphabet)/sizeof(char) - 1;

    // Randomization variables and length
    const char vars[] = {
        0xA6,
        0xC1,
        0x5E,
        0x31,
        0xF5,
        0x88,
        0xA1,
        0xE2
    };
    const int varsLen = sizeof(vars)/sizeof(char);

    // Digest (where the hash is made)
    char *digest = (char*)malloc(sizeof(char) * (HASH_LENGTH + 1));

    // Input length calculation
    int inputLen = 0;
    while(input[inputLen] != '\0') inputLen++;

    // Digest cleaning
    int i;
    for(i = 0; i < HASH_LENGTH; i++){
        digest[i] = 0;
    }

    // Hashing process
    int j;
    for(i = 0; i < HASH_LENGTH; i++){
        // XORs digest[i] with vars[input[j]]
        for(j = 0; j < HASH_LENGTH; j++){
            digest[i] ^= vars[input[j % inputLen] % varsLen];
        }
        // XORs digest[i] with input[i] + vars[i]
        digest[i] ^= input[i % inputLen] + vars[i % varsLen];
    }

    // Translates digest to desired alphabet
    for(i = 0; i < HASH_LENGTH; i++){
        j = digest[i] > 0 ? 1 : -1;
        digest[i] = alphabet[digest[i] * j % alphabetLen];
    }
    // Finalizes digest string
    *(digest + HASH_LENGTH) = '\0';

    return digest;
}

This is how the function is called:

printf("%s", hash("foo"));


texts:
I create login form with session with four files:

connection.php
login.php
plan.php
logout.php

Please check my code and tell about any smokestack.

Database educate (create table users)

CREATE TABLE users(
id INT AUTO_INCREMENT,
username VARCHAR(50) NOT NULL,
password VARCHAR(100) NOT NULL,
PRIMARY KEY(id) );

Connection.php

<?php
$dsn = 'mysql:host=localhost;dbname=educate'; //Data source Name
$username = 'root';
$password = '';
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND=> 'SET NAMES utf8');

 $conn = new PDO($dsn, $username, $password,$options);
 ?>

login.php

<?php
session_start();
if(!empty($_SESSION['username'])) {
header('location:plan.php');
}
require 'connection.php';

if(isset($_POST['login'])) {

$user = $_POST['username'];
$pass = $_POST['password'];

if(empty($user) || empty($pass)) {
$message = 'All field are required';
} else {
$query = $conn->prepare("SELECT username, password FROM users WHERE
username=? AND password=? ");
$query->execute(array($user,$pass));
$row = $query->fetch(PDO::FETCH_BOTH);

if($query->rowCount() > 0) {
  $_SESSION['username'] = $user;
  header('location:plan.php');
} else {
  $message = "Username/Password is wrong";
}

}

}
?>

<!DOCTYPE html>

<?php
if(isset($message)) {
echo $message;
}
?>
<form action="#" method="post">
Username: <input type="text" name="username" placeholder="username">

Password: <input type="password" name="password" placeholder="password">

<input type="submit" name="login" value="Login">

</form>

logout.php

<?php
session_start();
session_destroy();
header('location: login.php');
?>

plan.php

<?php
session_start();

if(isset($_SESSION['username'])) {
echo "Welcome ".$_SESSION['username']."
";
} else {
header('location: login.php');
}

?>
Logout


texts:
I'm working on an old application written in JavaScript. It's absolutely littered with console.* messages some of which are useful for development purposes.

At the very least I'd like to switch these off when a production flag is set. I would also like to stub off any unsupported console methods (trace on IE for example). Note: Assume that we will always have ES5 support.

Concerns:

I call into the initializer as soon as the constructor is instantiated. I like the idea of having a separate initializer method because it can be swapped out. I don't however like the idea that subsequent calls can be made. Any thoughts on this? I've seen it used a lot in Backbone's source.
As you can see I've tried to keep the production flag separate from the general 'enabled' flag. When in production I noop all of the methods instead of wrapping them (or nooping them if unsupported). Perhaps there's a better way of catching all calls to console (like a jasmine style spy) in production?
My hope with wrapping each supported method was to have a way of injecting pre-conditions/formatting before it's fired off. I also use this as an opportunity to check flags like enable. Is this over-contrived?

var Logger = function () {
    this._methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml',
        'error', 'exception', 'group', 'groupCollapsed', 'groupEnd',
        'info', 'log', 'markTimeline', 'profile', 'profiles',
        'profileEnd', 'show', 'table', 'time', 'timeEnd',
        'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
    ];

    this.initialize.apply(this, arguments);
};

var console = window.console, p = Logger.prototype;

p.initialize = function (options) {
    var noop = function () {};

    this.options = options || {};

    this._enabled = !this.options.production;

    this._methods.forEach(function (method) {
        if (this.options.production) {
            this[method] = noop;
        } else {
            this[method] = console[method] ? this._wrap(method) : noop;
        }
    }.bind(this));
};

p._wrap = function (method) {
    return function () {
        if (this._enabled) {
            return console[method].apply(console, arguments);
        }

        return false;
    };
};

p.enable = function () {
    if (!this.options.production) {
        this._enabled = true;
    }
};

p.disable = function () {
    this._enabled = false;
};


texts:
I have been updating my build tools to optionally use autotools (autoconfig/automake/libtool etc.).

As part of this change I have written a couple of M4 macros. This not being something I have done before, any input is appreciated on style or if things can be done better.

This macro checks to see if the YAML libraries are installed:

AC_DEFUN([AX_FUNC_THOR_USE_YAML],
[
    AC_ARG_WITH(
        [yamlroot],
        AS_HELP_STRING([--with-yamlroot=<location>], [Directory of YAML_ROOT])
    )
    AC_ARG_ENABLE(
        [yaml],
        AS_HELP_STRING([--disable-yaml], [Disable yaml serializsation])
    )
    AS_IF(
        [test "x$enable_yaml" != "xno"],

        ORIG_LDFLAGS="${LDFLAGS}"
        if test "${with_yamlroot}" != ""; then
            LDFLAGS="$LDFLAGS -L$with_yamlroot/lib"
        fi

        AC_CHECK_LIB(
            [yaml],
            [yaml_parser_initialize],
            [
                AC_DEFINE([HAVE_YAML], 1, [When on Yaml Serialization code will be compiled])
                with_yamllib=-lyaml
            ],
            [AC_MSG_ERROR([

Error: Could not find libyaml

You can solve this by installing libyaml
    see http://pyyaml.org/wiki/LibYAML

Alternately specify install location with:
    --with-yamlroot=<location of yaml installation>

If you do not want to use yaml serialization then it
can be disabled with:
    --disable-yaml

                ], [1])]
        )

        LDFLAGS="${ORIG_LDFLAGS}"
    )
])

If YAML is detected, then no problems. If the configure script cannot find them, the error message is generated with three options:

Disable the use of YAML
Provide the location where YAML is installed (not default)
Instructions on how to install


texts: Marking items as selected in Angular directives

texts:
I am new to Angular and feel that I'm doing mistakes and reinventing the wheel. Could you please review my code and share your ideas about how it can be improved. Demo

The problem is very common. I have a list of items (countries) that can be loaded inside a directive controller. I have an Id of selected item (selected). I want to select a country when clicked on.

My questions are:

Is it a good practice to load countries in the countries directive controller? Or maybe should it be loaded in the MainCtrl and bind to directive?
If I need only countryId is it good to store only this Id in the MainCtrl model? Or maybe should I store the country object with id and name?
How the countrySelectController can be improved? Does it smell bad? How should select() be organized?

app.js:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.model = {
    country: "USA"
  };
});

app.directive('countrySelect', function() {
  return {
    restrict: 'E',
    replace: true,
    scope: {
      selected: '='
    },
    templateUrl: 'countrySelect.html',
    controller: 'countrySelectController'
  };
});

app.controller('countrySelectController', function($scope) {
  function load(){
    // will be loaded from service
    return [
      {id: 'USA', name: 'United States of America'},
      {id: 'RU', name: 'Russian Federation'},
      {id: 'CHN', name: 'China'}
    ];
  };

  function markAsSelected(countryId){
    angular.forEach($scope.countries, function(country){
      country.selected = country.id === countryId;
    });
  }

  $scope.countries = load();
  markAsSelected($scope.selected);

  $scope.select = function(country){
    $scope.selected = country.id;
    markAsSelected($scope.selected);
  }
});

CountrySelect.html:

    {{country.id}} - {{country.name}} | {{country.selected}}


texts:
I have custom cell of tableview which is used as header as well as normal cell.

In custom cell I have this properties

public var btnReplyTappedClousre:((CommentCell) -> (Void))?
public var btnBulbTappedClousre:((CommentCell) -> (Void))?
public var btnOtherReplyTapped:((CommentCell) -> (Void))?

And  Call it with

@IBAction func btnReplyTapped(_ sender: Any) {
    self.btnReplyTappedClousre?(self)
}

//--------------------------------------------------------------------------------

@IBAction func btnBulbTapped(_ sender: Any) {
    self.btnBulbTappedClousre?(self)
}

//--------------------------------------------------------------------------------

@IBAction func btnViewPreviousReplyTapped(_ sender: Any) {
    self.btnOtherReplyTapped?(self)
}

In view Controller i have implemented that closure

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell =  tableView.dequeueReusableCell(withIdentifier: StoryBoard.Cells.CommentCell, for: indexPath) as! CommentCell
    cell.isForHeaderCell = false
    cell.btnReplyTappedClousre = {[weak self] (cell) in
        self?.btnViewAllReplyTapped(cell)
    }
    cell.btnBulbTappedClousre = {[weak self] (cell) in
        self?.btnBulbTapped(cell)
    }
    return cell
}

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell =  tableView.dequeueReusableCell(withIdentifier: StoryBoard.Cells.CommentCell) as! CommentCell
    cell.isForHeaderCell = true

    cell.btnReplyTappedClousre = {[weak self] (cell) in
        self?.btnViewAllReplyTapped(cell)
    }
    cell.btnBulbTappedClousre = {[weak self] (cell) in
        self?.btnBulbTapped(cell)
    }

    cell.btnReplyTappedClousre = {[weak self] (cell) in
        self?.btnReplyTapped(cell)
    }

    return cell

}

Is there any better way to do it ? Or can i improve it ?


texts:
the requirement for our search query is to look for all search words in the beginning of vehicle manufacturer, model and variant name. Case insensitive. The word being a string of characters separated by space.

E.g. when search for "AU A3 TDI" you would find a vehicle with the following attributes: Vehicle { ManufacturerName = "Audi", ModelName = "A3", Name = "2.0L TDI" }

...but would not return this vehicle:
Vehicle { ManufacturerName = "Renault", ModelName = "A3", Name = "2.0L TDI" } because no words start with au.

I'm using specification with LINQ Expression and the code I wrote works fine and is tested however I believe it smells a bit. It's not very readable IMHO but most importantly, there might be a clear performance improvement you could point out?

public string[] SearchTerms = searchText.Split();

Expression<Func<SearchVehicleVariant, bool>> expression =
c =>
SearchTerms.All(
    s =>
    string.Format(
        " {0} {1} {2}",
        c.ManufacturerName != null ? c.ManufacturerName.ToUpper() : string.Empty,
        c.ModelName != null ? c.ModelName.ToUpper() : string.Empty,
        c.Name != null ? c.Name.ToUpper() : string.Empty).Contains(
            string.Concat(" ", s.Trim().ToUpper())));


texts:
I am learning jQuery/JavaScript best practices and am attempting to put them into practice. My overall goal is to have lots of small, independent .js files which contain specific functionality and will not intrude or collide with other files, then concat/minify them for production as one file; basing some concepts off of John Papa's AngularJS Style Guide.

I'm trying to understand IIFEs and jQuery delegate event handling. I am not sure if this is the best way to do this, but my attempt here is to isolate a specific event handler in its own contained block. If an IIFE is used, does this event remain registered/delegated to the span or does the IFFE invoke once and the event is no longer registered?

I'm not worried about the code working but more concerned with learning how to structure jQuery Event Delegates in a modular way using the example below.

(function(window, document, $){
   var $icon = $('.icon');

   $icon.on('click', 'span', function() {
      var me = this;
      me.toggleClass('open');
   });

})(window, document, jQuery);


texts:
Can anyone advise on how to use the SymPy TensorProduct function without having to explicitly indicate the full sequence of objects to take the product of. Below (for the simple case N=3) you can see one of my attempts. But the tensor products are still not coinciding, hence I am still having to write out the full sequence to get the correct answer.

import scipy
from numpy import*
import math
from sympy import I, Matrix, symbols
from sympy.physics.quantum import TensorProduct

N = 3

x = array([1/(math.sqrt(2)),1/(math.sqrt(2))])

V =[]
for i in range(1,N+1):
    V.append(x)

V = array(V)

TP1 = TensorProduct(V[0],V[1],V[2])
TP2 = TensorProduct(V[:])

print TP1
print TP2

Thanks for any assistance.


texts:
IntelliJ warns me that I should avoid using return. If sender is empty, the function should not continue parsing the bytes.
The return value of keyType() is an Option.
What is a better way to return Left in case of an error, without using a return statement?
object TransactionV3 {
  private val longLength = 8

  private def parsePublicKeyAccount(bytes: Array[Byte], start: Int): Option[PublicKeyAccount] = {
    val keyTypeId = bytes(start)

    keyType(keyTypeId) map {
      accountKeyType => PublicKeyAccount(accountKeyType, bytes.slice(start + 1, start + 1 + accountKeyType.length))
    }
  }

  def parseBase(bytes: Array[Byte], start: Int): Either[ValidationError, (Long, PublicKeyAccount, PublicKeyAccount, Long)] = {
    val timestamp = Longs.fromByteArray(bytes.slice(start, start + longLength))

    val senderMaybe = parsePublicKeyAccount(bytes, start + longLength)
    if (senderMaybe.isEmpty) {
      return Left(InvalidPublicKey("Invalid sender key type"))
    }
    val sender = senderMaybe.get

    val sponsorMaybe = parsePublicKeyAccount(bytes, start + 9 + sender.keyType.length)
    if (sponsorMaybe.isEmpty) {
      return Left(InvalidPublicKey("Invalid sponsor key type"))
    }
    val sponsor = sponsorMaybe.get

    val s1 = start + longLength + 2 + sender.keyType.length + sponsor.keyType.length
    val feeAmount = Longs.fromByteArray(bytes.slice(s1, s1 + longLength))

    Right(timestamp, sender, sponsor, feeAmount)
  }
}


texts:
I have data like:

var data =
    [{
        "date":"1-1-2013",
        "answer":"yes"
    },{
        "date":"1-1-2013",
        "answer":"no"
    },{
        "date":"2-1-2013",
        "answer":"no"
    },{
        "date":"2-1-2013",
        "answer":"no"
    },{
        "date":"2-1-2013",
        "answer":" "       //this is not answered!
    },,{
        "date":"2-1-2013",
        "answer":"no"
    }];

I need to return[array] percentages of responses for that day(groupedBy) which have a value of “yes” for the “answer”.

For above the result is: [50, 0...]

I have written this below code, it works but i believe it can be simplified a lot.

var freshData =  _.map(data,function(key){
    if (key.answer == "") return false;
    return key;

});

var reducedData = _.filter(freshData, function(n) {
    return n != false;
});

var groups = _.groupBy(reducedData, function(value){
        return value.date + '#' + value.answer;
});

var result = _.map(groups,function(key){
    if (key[0].answer == "") return false;
    return {
        date : key[0].date,
        answer : key[0].answer,
        length :key.length
    };
});

var result2 = _.chunk(result,2);

var result3 =  _.map(result2,function(key){
    return {
        date:key[0].date,
        yes:key[0].length,
        no:key[1].length,
        percentage : (key[1].length/(key[0].length + key[1].length) * 100)
    }
});

var result4 =  _.map(result3,function(key){
return  key.percentage;
});

console.log(result4);

I need to use lodash.
Thanks.


texts:
My goal is to create a URL query params from std::map<std::string, std::string>. For example, we call to_query_params( {{"one","1"},{"two","2"}} ) and we get ?one=1&two=2.

Is this a good way of doing it?

std::string to_query_params(std::map<std::string, std::string> map)
{
    if (map.empty()){
        return "";
    }
    auto map_beg = std::begin(map);
    auto concat = [](const decltype(map)::value_type& a){
                        return a.first+"="+a.second;
                    };
    std::string result("?"+concat(*map_beg));
    std::for_each(std::next(std::begin(map)),
                  std::end(map),
                  [&](decltype(map)::value_type param){
                      result+="&"+concat(param);
                  });
    return result;
}


texts:
Here is my code of serialize and de-serialize a binary tree, looking for advice. One issue in my mind which I cannot resolve is, I am using a global variable index, wondering if more elegant solutions in Python 2.7 -- since in Python there is no solution to pass a reference as Java/C++ did.

index = 0
class Node:
    def __init__(self, value, left, right):
        self.value = value
        self.left = left
        self.right = right
    @staticmethod
    def serialize(root, output):
        if not root:
            output.append('#')
            return
        output.append(root.value)
        Node.serialize(root.left, output)
        Node.serialize(root.right, output)
        return output
    @staticmethod
    def deserialize(source):
        global index
        if source[index] == '#':
            index += 1
            return None
        value = source[index]
        index += 1
        left = Node.deserialize(source)
        right = Node.deserialize(source)
        return Node(value, left, right)

if __name__ == "__main__":
    root = Node('a', Node('b', None, None), Node('c', Node('e', Node('g', None, None), None), Node('f', None, None)))
    result = []
    Node.serialize(root, result)
    print result
    new_root = Node.deserialize(result)
    result2 = []
    Node.serialize(new_root, result2)
    print result2


texts:
I am starting to learn Haskell, so I coded a naive solution to the primality test and summation of primes (Project Euler Problem 10: sum of all primes under 2 million) . As I have an imperative programming background, can you tell me if my code is functional enough?

isqrt :: Int -> Int
isqrt n = floor(sqrt(fromIntegral n))
factors n = filter (\i -> n `mod` i == 0) [1..(isqrt(n))]
is_prime n = (factors n) == [1]
main = print (sum (filter is_prime [2..2000000]))


texts:
Here is my program that calculates tuition cost for the next five years. I have had some review on it so far, but I am seeking more. Please keep in mind I am new to programming, so I may require a few extra steps to understand something. Thanks in advance!

Version 1.0 is here

RESIDENCY_COST = {
                    "I": 10000,
                    "O": 24000,
                    "G": 40000,
                 }

cost_of_tuition = None
while True:
    residency = raw_input('Please input your type of residency, I for in-state, O for out-of-state, and G for graduate: ')
    try:
        cost_of_tuition = RESIDENCY_COST[residency]
        break
    except KeyError:
        print ('Please enter I, G or O ONLY.')

years = []
tuition_increase = []
academic_year = []
academic_year_inc = []

for _ in range(5):
    intMath = cost_of_tuition * 0.03
    tuition_increase.append(intMath)
    fnlMath = intMath + cost_of_tuition
    years.append(fnlMath)
    cost_of_tuition = fnlMath
    academic_year.append("${:,.2f}".format(fnlMath))
    academic_year_inc.append("${:,.2f}".format(intMath))
    total_tuition_increaseSum = sum(tuition_increase)
    total_tuition_increase = "${:,.2f}".format(total_tuition_increaseSum)

print('UNDERGRADUATE TUITION FOR THE NEXT FIVE YEARS ')
print('ACADEMIC YEAR          TUITION       INCREASE ')
print('-------------     ------------       -------- ')

for i, year in enumerate(range(16, 21)):
    print('{}-{}             {}        {}'.format(year + 2000, year + 1,
                                                  academic_year[i],
                                                  academic_year_inc[i]))

print('TOTAL TUITION INCREASE              ' + total_tuition_increase)


texts:
Interested to hear your thoughts on this Secret Santa pairs picker.

It's pretty standard but I'll explain the rules all the same:

All names go into a hat
Each person picks a name from the hat and buys a small present for that person as a Christmas gift

No one should pick their own name from the hat so in this circumstance they should replace the name and pick another one

This becomes problematic in real life because if someone picks their own name and puts it back they have more information about who can or cannot have their name. As such, it's a prime candidate for some computational intervention.

The Worksheet (codename Sheet1) is simple. It contains a ListObject named "Names" and a button linked to the following Sub.

Option Explicit

Public Sub GenerateSecretSantaPairs()

    Dim namesRange As Range
    With Sheet1.ListObjects("Names")
        Set namesRange = Intersect(.DataBodyRange, .DataBodyRange.Columns(1))
    End With

    Dim hat As Scripting.Dictionary
    Set hat = New Scripting.Dictionary

    'fill the hat with names
    Dim r As Range
    For Each r In namesRange
        hat.Add Key:=r.Value, Item:=r.Value
    Next r

    'retain original names (in order) in an array
    Dim originalNames As Variant
    originalNames = hat.Keys

    Dim partnerNames As Variant
    ReDim partnerNames(0 To hat.Count - 1)

    Dim i As Long
    For i = 0 To hat.Count - 1
        Do
            'pick a random person from the hat
            Dim selectedName As String
            selectedName = hat.Keys(Application.WorksheetFunction.RandBetween(0, hat.Count - 1))

        Loop While originalNames(i) = selectedName And hat.Count <> 1 'try again if picked yourself unless you are the only person left in the hat

        'assign partner and remove from hat
        partnerNames(i) = selectedName
        hat.Remove selectedName

        'if last person has picked themselves then run the sub again
        If partnerNames(i) = originalNames(i) Then
            GenerateSecretSantaPairs
            Exit Sub
        End If
    Next i

    'ouput pairs
    namesRange.Offset(0, 1).Value = Application.Transpose(partnerNames)
End Sub


texts:
I wrote this function that will toggle a class of a targeted element. Applying the class js_class_toggle to any element will trigger the function when clicking on it.

To define what the target element is and the class you want to toggle is, you have to add data-class-toggle="target_element_id.className" to the element. You can also add this to any element on the page and it will work the same since its targeting the element by its id.

For example:

    This element will have a class toggled

JS:

$(document).on("click", ".js_class_toggle", function(e){

    //Set variables
    var element = $(e.currentTarget),
        elementsClasses = element.attr('data-class-toggle'),
        elementsClassesSplit = elementsClasses.split('.'),
        targetElement = elementsClassesSplit[0],
        targetClass = elementsClassesSplit[1];

    //Toggle the class
    $("#"+targetElement).toggleClass(targetClass);
});

Here is a working example of it: https://jsfiddle.net/fxo1a5w3/2/

What i will work on next is to be able to have multiple toggles in the same request, for example:

    This element will have its class toggled

But before that i want to know if there is a better way of doing what i have done so far. The goal is for it to be a function that can be used in any project.


texts: Entity Relationship Diagram for Grade Calculator

texts:
I was wondering if anyone would be able to review my Grade Calculator for a course ERD? I'm looking for ways to improve the current design (if any improvements need to be made that is) and if anyone could review the current MySQL query which is there. In order for this to be reviewed I was told I needed an SQL query to accompany it.

SELECT
    `yearGroup`.`id` AS `year_group_id`,
    `yearGroup`.`year` AS `year_group`,
    CONCAT(
    TRUNCATE
        (
            COALESCE(
                SUM(
                    `assignment`.`percentage_achieved` *(
                        `assignment`.`percentage_weighting` / 100
                    )
                ),
                0
            ) /(
            SELECT
                COUNT(*)
            FROM
                `unit`
            WHERE
                `unit`.`year_group_id` = `yearGroup`.`id`
        ),
        2
        ),
        '%'
) AS `grade`
FROM
    `assignment`
RIGHT JOIN `unit` ON `unit`.`id` = `assignment`.`unit_id`
RIGHT JOIN `yearGroup` ON `yearGroup`.`id` = `unit`.`year_group_id`
WHERE
    `yearGroup`.`course_id` = 1
GROUP BY
    `yearGroup`.`id`


texts: Case insensitively removing a substring, efficiently

texts:
I am going through the CodingBat exercises for Java. I have just completed this one:

  Given two strings, base and remove, return a version of the base string where all instances of the remove string have been removed (not case sensitive). You may assume that the remove string is length 1 or more. Remove only non-overlapping instances, so with xxx removing xx leaves x.

I wanted to try using a StringBuilder to solve this because I have not done so before. Here is my code:

public String withoutString(String base, String remove){

    String removeLo = remove.toLowerCase();
    String removeHi = remove.toUpperCase();

    int rL = remove.length();

    StringBuilder s = new StringBuilder(base);

    for (int i = 0; i < s.length(); i++) {
        int j = s.indexOf(remove, i);

        if (j < 0) {
            break;
        } else {
            s.delete(j, j + rL);
        }
    }

    for (int i = 0; i < s.length(); i++) {
        int j = s.indexOf(removeLo, i);

        if (j < 0) {
            break;
        } else {
            s.delete(j, j + rL);
        }
    }

    for (int i = 0; i < s.length(); i++) {
        int j = s.indexOf(removeHi, i);

        if (j < 0) {
            break;
        } else {
            s.delete(j, j + rL);
        }
    }
    return s.toString();
}

The code repeats the for loop 3 times in order to search for the unaltered, lower case, and upper case versions of remove. My questions are:

Is it possible to reduce this down to one for loop, and is that practical (with good readability)?
The test strings involve digits. Is it problematic to be 'converting' these to lower and/or upper cases? Should I deal with those before testing the alphabetic strings?
The following test cases are the ones that require all three for loops:

withoutString("xxx", "x")
withoutString("1111", "1")
withoutString("MkjtMkx", "Mk")
withoutString("Hi HoHo", "Ho")

The rest of the tests work without the first for loop (unaltered remove). The second two make sense, because the remove string uses upper and lower case, but the first two don't follow this. I have used the debugger in Eclipse but I still can't figure this out. Can you please explain?


texts:
I am working on a project to get dice probability that requires 4 decimals places. My code works great, until the dice become huge (as I use in the example below). I am wondering if there is a way to make the process less laborious.
I should specify that I do already know that the choices list ending up so large is the performance issue.  I am looking for ways to improve performance.
An explanation of my code is:

We have \$n\$ dice each with \$f\$ faces and a target \$t\$. I want to know all the combinations of these dice to total \$t\$.
When: \$n = 2\$, \$f = 6\$ and \$t = 10\$, the following are the possible combinations:

4, 6
5, 5
6, 4

meaning poss_combinations returns \$3\$.

from itertools import product

dice = 10
faces = 10
number = 50

def poss_combinations(dice, faces, number):
    choices = list(product(range(1, faces+1), repeat=dice))
    count = 0
    for i in choices:
        if sum(i) == number:
            count += 1
    return count

answer = poss_combinations(dice, faces, number) / float(faces**dice)

return round(answer,4)


texts: Notify owner of post and other commenters

texts:
I have a rails4 app. When a user comments on a post it should send a notification to all the guys who commented on the post and to the post creator. I have a working method in the controller, but it's kinda ugly and I'd like to refactor it.

Could somebody tell me what the rails convention for refactoring this?

Comment belongs_to :post, post has_many :comments

create#comment action

    if @post_comment.save
      ((@post.users + [@post.user]).uniq - [current_user]).each do |post_commenter|
        Notification.create(recipient_id: post_commenter.id, sender_id: current_user.id, notifiable: @post_comment.post, action: "commented")
    end
    ....
end


texts: Program to see how many points lie strictly inside a convex polygon

texts:
The program takes in a set of coordinates that defines the polygon. It then takes in a set of points. The idea is to find out how many of these points lie strictly inside the convex polygon (not on the edge or outside). First the program checks if the first set of points form a convex polygon or not. If yes, the program proceeds. Then each point is checked to see if it is strictly inside the convex polygon. If yes, count variable is increased. Here is the code:

#include <iostream>
#include <vector>

// Calculate perpendicular dot product
int perdot(const std::pair<int, int> a, const std::pair<int, int> b, const std::pair<int, int> c)
{
    int ab_x = b.first - a.first;
    int ab_y = b.second - a.second;
    int ac_x = c.first - a.first;
    int ac_y = c.second - a.second;
    int per_dot = ab_x * ac_y - ab_y * ac_x;
    if(per_dot < 0)
    {
        return -1;
    }
    else if(per_dot > 0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

// Check if given set of points form a convex polygon
bool is_convex(const std::vector<std::pair<int, int>>& convex_polygon)
{
    int n = convex_polygon.size();
    int sense = perdot(convex_polygon[n - 1], convex_polygon[0], convex_polygon[1]);
    for(int i = 0; i < n - 1; i++)
    {
        int new_sense;
        if(i == (n - 2))
        {
            new_sense = perdot(convex_polygon[i], convex_polygon[i + 1], convex_polygon[0]);
        }
        else
        {
            new_sense = perdot(convex_polygon[i], convex_polygon[i + 1], convex_polygon[i + 2]);
        }
        if(sense == 0)
        {
            sense = new_sense;
        }
        if(new_sense == (-sense) && sense != 0)
        {
            return false;
        }
    }
    return true;
}

// Check if a point is STRICTLY inside the convex polygon
bool is_inside(const std::vector<std::pair<int, int>>& convex_polygon, const std::pair<int, int> point)
{
    int n = convex_polygon.size();
    int sense = perdot(convex_polygon[n - 1], point, convex_polygon[0]);
    if(sense == 0)
    {
        return false;
    }

    for(int i = 0; i < n - 1; i++)
    {
        int new_sense;
        new_sense = perdot(convex_polygon[i], point, convex_polygon[i + 1]);
        if(new_sense == (-sense) || new_sense == 0)
        {
            return false;
        }
    }
    return true;
}

// Count the number of points STRICTLY inside the convex polygon
int p_inside(const std::vector<std::pair<int, int>>& convex_polygon, const std::vector<std::pair<int, int>>& points)
{
    int count = 0;
    for(auto point : points)
    {
        bool inside = is_inside(convex_polygon, point);
        if(inside)
        {
            count++;
        }
    }
    return count;
}

// Main
int main()
{
    int k, n;
    std::cin >> k >> n;
    std::vector<std::pair<int, int>> convex_polygon(k);
    std::vector<std::pair<int, int>> points(n);
    for(size_t i = 0; i < convex_polygon.size(); i++)
    {
        int x, y;
        std::cin >> x >> y;
        convex_polygon[i] = {x, y};
    }
    bool convex = is_convex(convex_polygon);
    if(!convex)
    {
        std::cout << "Input not convex...Exiting" << std::endl;
        return 0;
    }

    for(size_t i = 0; i < points.size(); i++)
    {
        int x, y;
        std::cin >> x >> y;
        points[i] = {x, y};
    }

    int count = p_inside(convex_polygon, points);
    std::cout << "Points inside: " << count << std::endl;
    return 0;
}

1) Should std::pair be passed as reference? Is there an exact criteria to see if a given object is large enough to be passed as reference?

2) Is the use of const correct?

3) What other improvements can be made?

4) I am planning to test it extensively using Catch2 framework. I am learning this framework myself. What suggestions do you have to maintain professional test quality?


texts:
I am new to programming. I have written a solution in two different ways, but would like to know what is considered a better solution, and why.

Additionally, in terms of performance, why would one be considered better?

Solution 1:

function titleCase(str) {
  str = str.toLowerCase();
  str = str.split("");
  str[0] = str[0].toUpperCase();
  for(i = 1; i<str.length; i++){
    if(str[i+1] == " "){
      str[i+2] = str[i+2].toUpperCase();
    }
  }
  str = str.join("");
  return str;
}

Solution 2:

function titleCase(str) {
  str = str.toLowerCase();
  str = str.split(" ");
  str = str.map(function(val){
    val = val.charAt(0).toUpperCase() + val.slice(1);
    return val;
  });
  str = str.join(" ");
  return str;
}


texts: Moving files to an output directory, with instructions on missing files

texts:
I have some files such as .\image_1_01.bmp that will be created elsewhere. I am then moving these files to an output directory. If any are missing I inform the user that it's missing and instruct them to check the logs.

Given how similar all the code is, can I make this code shorter?

if not os.path.exists(".\image_1_01.bmp"):
    print('image_1_01.bmp not generated\n' 'for more info check the log file' )
    return 1
else:
    shutil.move(".\image_1_01.bmp", output_directory)

if not os.path.exists(".\image_1_01.raw"):
    print('image_1_01.raw not generated\n' 'for mor info check the log file' )
    return 1
else:
    shutil.move(".\image_1_01.raw", output_directory)

if not os.path.exists(".\image_1_01_hist.csv"):
    print('image_1_01_hist.csv not generated\n' 'for mor info check the log file' )
    return 1
else:
    shutil.move(".\image_1_01_hist.csv", output_directory)

if not os.path.exists(".\image_1_02.bmp"):
    print('image_1_02.bmp not generated\n' 'for more info check the log file' )
    return 1
else:
    shutil.move(".\image_1_02.bmp", output_directory)

if not os.path.exists(".\image_1_02.raw"):
    print('image_1_02.raw not generated\n' 'for mor info check the log file' )
    return 1
else:
    shutil.move(".\image_1_02.raw", output_directory)

if not os.path.exists(".\image_1_02_hist.csv"):
    print('image_1_02_hist.csv not generated\n' 'for mor info check the log file' )
    return 1
else:
    shutil.move(".\image_1_02_hist.csv", output_directory)

if not os.path.exists(".\scan_stats.csv"):
    print('scan_stats.csv not generated\n' 'for mor info check the log file' )
    return 1
else:
    shutil.move(".\scan_stats.csv", output_directory)

if retcode != 0:
    sys.exit(1)
else:
    print("Test case is not suitable for your configuration")
    sys.exit(2)

if __name__ == '__main__':
    exit( generic() )`


texts:
I'm new in OCaml and just want to be sure that I write code in "ocaml way". My other first programs in OCaml was imperative and looks like python-code. So I decided to write simple code and share it for review.

let print lst =
    List.map string_of_int lst
        |> String.concat " "
        |> print_endline
;;

let rec sort lst =
    let sorted = match lst with
    | hd1 :: hd2 :: tl ->
        if hd1 > hd2 then
            hd2 :: sort (hd1 :: tl)
        else
            hd1 :: sort (hd2 :: tl)
    | tl -> tl
    in
    if lst = sorted then
        lst
    else
        sort sorted
;;

let () =
    let lst1 = [3; 4; 2; 1] in
    print lst1;
    sort lst1 |> print;

    let lst2 = [5; 6; 7; 0; 1; 4; 2; 9; 3; 8] in
    print lst2;
    sort lst2 |> print;
;;

Result:

3 4 2 1
1 2 3 4
5 6 7 0 1 4 2 9 3 8
0 1 2 3 4 5 6 7 8 9


texts:
Whenever a button is clicked, the following need to be performed:

All siblings of the clicked button get toggled
All edit_button get toggled, except for the edit_button within the same span as the clicked button (note: the excluded edit_button can be the same as the clicked button)

The JavaScript is working in the way I want it to, but I am curious if there's another better way to achieve the second requirement.

Note: save_button and cancel_button are hidden when first loaded.

$(function() {
  $('.edit_button, .save_button, .cancel_button').click(function() {
    $(this).toggle();
    $(this).siblings('button').toggle();
    $('div#personal_info').find('button.edit_button').not($(this).parent().find('button.edit_button')).toggle();
  });
});

    <button class="edit_button">Edit</button><button class="cancel_button">Cancel</button><button class="save_button">Save Changes</button>

    <button class="edit_button">Edit</button><button class="cancel_button">Cancel</button><button class="save_button">Save Changes</button>

    <button class="edit_button">Edit</button><button class="cancel_button">Cancel</button><button class="save_button">Save Changes</button>


texts: Button click handlers for a JavaScript text-based adventure game

texts:
I'm pretty new to JavaScript, and I'm trying to created a text-based game. I've written a few scenarios and based on the player's decision I have different scenarios written out. As of now I have the code written and it works but I feel like I can be more efficient with an if else statement in my js.

Here's what I have so far in terms of player decisions.

 $(document).ready(function(){

        $(".sit_1, .sit_2, .sit_3a, .sit_3b, .sit_4a").hide();
        $(".choice_1, .choice_2a, .choice_2b, .choice_3a, .choice_3b, .choice_4a, .choice_4b").hide();
        $(".sit_1").fadeIn(2000);
        $(".choice_1").fadeIn(4000);

        $(".choice_1").click(function(){
         $(".sit_1").hide();
         $(".choice_1").hide();
         $(".sit_2").fadeIn(4000);
         $(".choice_2a").fadeIn(8000);
         $(".choice_2b").fadeIn(8000);

         });

        $(".choice_2a").click(function(){
         $(".sit_2").hide();
         $(".choice_2a").hide();
         $(".choice_2b").hide();
         $(".sit_3a").fadeIn(4000);

         });

        $(".choice_2b").click(function(){
         $(".sit_2").hide();
         $(".choice_2a").hide();
         $(".choice_2b").hide();
         $(".sit_3b").fadeIn(4000);
         $(".choice_3a").fadeIn(4000);
         $(".choice_3b").fadeIn(4000);

         });

        $(".choice_3a").click(function(){
         $(".sit_3b").hide();
         $(".choice_3a").hide();
         $(".choice_3b").hide();
         $(".sit_4a").fadeIn(3000);
         $(".choice_4a").fadeIn(4000);
         $(".choice_4b").fadeIn(4000);

         });

        });

         You are lost in the woods.

         You find a cave. Do you go inside or go look for food?

         You walk into the cave.

         You walk away from the cave, to search for food. You find berries. Do you eat them or not?

         You eat the berries.

     <input type="button" class="choice_1" value="Continue on...">

     <input type="button" class="choice_2a"value="Go inside">

     <input type="button" class="choice_2b" value="Look for food">

     <input type="button" class="choice_3a" value="Eat the berries">

     <input type="button" class="choice_3b" value="Don't eat the berries">

Not sure how clear this is but I basically want all my situations (sit_) to be hidden along with the player choices (choice_) until the player presses a button or makes a choice and then the old situations along with the old choices will disappear to make way for the new situations and choices.

As I said this code does work but I feel like I can make it more efficient with an if/else statement but I'm not sure how to go about it. Any help would be greatly appreciated.

Also, should I make the choices into an array to make it easier?


texts:
I have an event recurring on the first friday of the month (at 7pm), and I need to output the date of the next first friday coming up.

This is the first bit of PHP I've written, and I was wondering if there is a better way to implement this? Server is running PHP 5.3

Here's what I wrote:

$todays_date = strtotime('today');
$first_friday = strtotime('first friday of this month');

if ($todays_date > $first_friday) {
  $next_month = date('M j', strtotime('first friday of next month'));
  echo 'Friday, '.$next_month;
} elseif ($todays_date == $first_friday) {
  echo 'Today';
} else {
  $this_month = date('M j', strtotime('first friday of this month'));
  echo 'Friday, '.$this_month;
}

And here is a suggested improvement offered by someone else, which also introduced me to ternary operators:

$today = new DateTime();
$this_months_friday = new DateTime('first friday of this month');
$next_months_friday = new DateTime('first friday of next month');
echo ($today < $this_months_friday) ? 'Friday, '.$this_months_friday->format('M j').' at 7pm' : 'Friday, '.$next_months_friday->format('M j').' at 7pm';

I had looked all over for a short way to do this and was only running into very large and complicated answers. Both my way and the answer provided by someone else are much much shorter and more readable.


texts: Bash: change git remote from SSH to HTTPS within a given dir

texts:
The code takes a user input dir path, then looks for git remote url that is still using SSH, and the repo is belong to an fixed Organisation. Then it will convert these repos' git remote url from SSH to HTTPS.

Goal is to let users (on Linux or Mac) effortlessly convert all dir containing the Organisation's code to use HTTPS instead of SSH.

My senior programmer said problems in the code are so many that he has to sit down with me next week to talk through! Please help me to spot problems before embarrassment starts. Thank you

#!/usr/bin/env bash

# This script loops through all directories within the given path,
# and run a conversion script to convert Git CLI auth type.
GITHUB_USERNAME='Mock-Technology'

converter () {
  # This function will convert origin url from SSH style to HTTPS style, for the
  # git containing local directory

  if [[ -z $GITHUB_USERNAME ]]; then
    GITHUB_USERNAME='Mock-Technology'
  fi

  echo "-- converter starting..."
  cd "$1" || exit
  if [[ ! -f "config" ]]; then
    echo "This directory does not contain Git, exitting..."
    return
  else
    origin_str=$(cat "config")
  fi

  repo_url=$(echo "$origin_str" | sed -Ene's#.*(git@[^[:space:]]*).*#\1#p')
  if [[ -z "$repo_url" ]]; then
    echo "-- ERROR:  Could not identify Repo url."
    if [[ $origin_str == *"https"* ]]; then
      echo "   This repo is already using HTTPS instead of SSH."; else
      echo "   Valid remote URL was not found!"
    fi
    return
  fi
  echo "-- Confirmed: It is using SSH..."

  user_name=$(echo "$repo_url" | sed -Ene's#git@github.com:([^/]*)/(.*).git#\1#p')
  if [[ -z "$user_name" ]]; then
    echo "-- ERROR:  Could not identify User."
    return
  elif [ "$user_name" != "$GITHUB_USERNAME" ]; then
    echo "-- WARNING: The repo does not belong to '$GITHUB_USERNAME', ignoring..."
    return
  fi
  echo "-- User name extracted: $user_name"

  repo_name=$(echo "$repo_url" | sed -Ene's#git@github.com:([^/]*)/(.*).git#\2#p')
  if [[ -z "$repo_name" ]]; then
    echo "-- ERROR:  Could not identify Repo."
    return
  fi
  echo "-- Repo name extracted: $repo_name"

  new_url="https://github.com/$user_name/$repo_name.git"
  echo "-- Changing repo url from: "
  echo "  '$repo_url'"
  echo "      to "
  echo "  '$new_url'"
  echo ""

  change_cmd="git remote set-url origin $new_url"
  eval "$change_cmd"
  echo "-- Success!"

}

validate_path() {
  # this module validates input path against empty string and non-existing path
  if [[ -z $1 ]]; then
    echo "path is empty string, existting..."
    exit
  fi

  if [[ ! -d $1 ]]; then
    echo "path does not exist, exitting..."
    exit
  fi
  echo "-- path validation check passed..."
}

loop_subdirectories() {
  # visits subfolders and try to find any ".git" directory
  # It invokes converter func for each ".git" directory found
  while read -r dir; do
    converter "$dir"
  done <<< "$(find "$1" -name .git -type d)"

}

read -p "Enter path: " path
validate_path "$path"
loop_subdirectories "$path"


texts: Java - How to represent the result of an operation

texts:
Introduction

In my Java application, I need to represent the result of an operation. This can either be OK or ERROR + an error message.

Background

I have a class to verify the integrity of a directory (e.g. to check that a few conditions hold). If it finds out the directory is corrupted, it should return a description of the error, such as:

Unexpected file - [filename].
Unexpected number of files - expected [X], actual [Y].

The callers of the class don't know anything about the directory and the conditions. They are only interested to know if the directory is OK or not, and in that case, to get an appropriate error message.

The Result class was intended as a way to transmit the results of the verification.

I chose not to throw exceptions as (to me) that seemed more convenient for reporting errors in the verification process. It seemed inappropriate to intermix those two situations (e.g. the directory was found invalid vs. an error occurred while verifying the directory).

The current solution

I have so far been able to come up with the following class.

public class Result
{
    private static enum State { OK, ERROR };

    private State state;
    private String errorMessage;

    private Result(State state, String errorMessage)
    {
        this.state = state;
        this.errorMessage = errorMessage;
    }

    public static Result ok()
    {
        return new Result(State.OK, null);
    }

    public static Result error(String errorMessage)
    {
        return new Result(State.ERROR, errorMessage);
    }

    public boolean isOK()
    {
        return (this.state == State.OK);
    }

    public String getErrorMessage()
    {
        return errorMessage;
    }
}

The client code then looks like this:

Result result = Result.ok();
Result result = Result.error("Could not ...");

if (result.isOK())
    ...
else
{
    String errorMessage = result.getErrorMessage();
    ...
}

This has the benefit that when creating a result, the client only has to deal with error messages in case of an error.

On the other hand, the API does not prevent the client code to ask for an error message in case of an OK result. That does not feel right.

I also don't like the way the information about valid states (OK/ERROR) gets dupplicated into:

the internal enumeration,
the public static methods.

What do you think about my implementation? How would you design the class?


texts:
I have the following UserServiceProvider and I'm wondering whether so much dependency injection is overkill:

use
Illuminate\Support\ServiceProvider,
App\Repositories\Eloquent\User\EloquentUserRepository,
App\Repositories\Eloquent\Profile\EloquentProfileRepository,
App\Repositories\Eloquent\Seller\EloquentSellerRepository,
App\Repositories\Eloquent\AppResponse\EloquentAppResponseRepository,
App\Repositories\Eloquent\AppRequest\EloquentAppRequestRepository,
App\Repositories\Eloquent\Model\EloquentModelRepository,
App\Repositories\Eloquent\Maker\EloquentMakerRepository,
Cartalyst\Sentry\Sentry,
App\Services\Cache\Decorators\UserCacheDecorator,
App\Services\Cache\Laravel\LaravelCache,
App\Entities\Entities\Profile\ProfileEntity,
App\Entities\Entities\Seller\SellerEntity,
App\Entities\Entities\AppRequest\AppRequestEntity,
App\Entities\Entities\AppResponse\AppResponseEntity,
App\Entities\Entities\Model\ModelEntity,
App\Entities\Entities\Maker\MakerEntity,
Profile,
Seller,
AppResponse,
AppRequest,
Model,
Maker;

class UserServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind('App\Repositories\Interfaces\UserRepositoryInterface', function($app)
        {
            $user = new EloquentUserRepository(
                new Sentry(),
                new ProfileEntity(
                    new EloquentProfileRepository(
                        new Profile()
                        )
                    ),
                new SellerEntity(
                    new EloquentSellerRepository(
                        new Seller()
                        )
                    ),
                new AppRequestEntity(
                    new EloquentAppRequestRepository(
                        new AppRequest()
                        )
                    ),
                new AppResponseEntity(
                    new EloquentAppResponseRepository(
                        new AppResponse()
                        )
                    ),
                new ModelEntity(
                    new EloquentModelRepository(
                        new Model()
                        )
                    ),
                new MakerEntity(
                    new EloquentMakerRepository(
                        new Maker()
                        )
                    )
                );
            return new UserCacheDecorator(
                $user,
                new LaravelCache($app['cache'], 'user')
                );
        });
    }
}

I do need all these entities in my UserEntity. Is this normal or should I start reducing the number of injections?