texts:
First off, I know there are other solutions and practices but I'm referring to MS proposed code from .NET documentation.

It goes like this:

client.Connect(anEndPoint);

bool blockingState = client.Blocking;
try
{
    byte [] tmp = new byte[1];

    client.Blocking = false;
    client.Send(tmp, 0, 0);
    Console.WriteLine("Connected!");
}
catch (SocketException e)
{
    // 10035 == WSAEWOULDBLOCK
    if (e.NativeErrorCode.Equals(10035))
        Console.WriteLine("Still Connected, but the Send would block");
    else
    {
        Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode);
    }
}
finally
{
    client.Blocking = blockingState;
}

 Console.WriteLine("Connected: {0}", client.Connected);

I've tried using it in my TCP client to detect disconnection from server. My problems is that on some occasions it detects disconnect where server does not, so on server I have connection left hanging while client reconnects.

I'm asking anyone who tried using this method to share experiences and maybe help make it more robust.


texts:
I'm creating an API endpoint to create and delete associations, essential creating and deleting records of a join model.

The code below doesn't seem idiomatic or pragmatic at all. What's the best way to create 2 endpoints, POST and DELETE for the same route?

module API
  module V1
    class UserActivities < Grape::API
      include API::V1::Defaults

      format :json

      namespace :users do

        route_param :user_id do
          resource :activities do
            desc 'Create User + Activity associations'
            route_param :activity_id do
              post do
                #pyramid of doom
              end
            end
          end

          resource :activities do
            desc 'Delete User + Activity associations'
            route_param :activity_id do
              delete do
                #pyramid of doom
              end
            end
          end
        end
      end
    end
  end
end

This generates the following routes:

   POST  |  /api/:version/users/:user_id/activities/:activity_id(.:format)  |  v1  |  Create User + Activity associations
 DELETE  |  /api/:version/users/:user_id/activities/:activity_id(.:format)  |  v1  |  Delete User + Activity associations

But is there a better way to do this using Grape?


texts:
I've created this script and I want to use it for website navigation in my project. As my knowledge of jQuery is quite poor, I'm not sure that code is correct and enough optimized. Could you help me to find out if there are any ways to optimize the code, and indicate mistakes I've made?

$(function () { //scroll to the section, section's id is equal to li href attribute
    $("li a").click(function () {
        var liC = $(this).attr("href");
        var liD = $("#" + liC).offset().top;
        $("html, body").stop().animate({
            scrollTop: liD
        }, 'slow');
        return false;
    });

    $(window).scroll(function () { //on scrolling defines the closets section gets it's id finds li item the href of which is equal to section's id and adds padding to it

        $('.dober').each(function () {
            var hRt = $(this).attr('id');
            if ($(this).offset().top <= $(window).scrollTop()) {

                $('li a').css({ padding: 0 });
                $('a[href=' + hRt + ']').css({
                    padding: 10
                });

            } else {

                 $('a[href=' + hRt + ']').css({
                    padding: 0
                });
            }
        });
    });
});


texts: Object-oriented JavaScript and Google Maps objects memory management

texts:
I have to draw various instances of HeatMaps, Winds and Polylines. Each layer will have one HeatMap, 1000+ Wind arrows and 3000+ Polylines.

The websocket pushes the data into the mapData structure where the data is stored for later manipulation of objects.

Each layer takes around 400MB of memory. Since I have to draw multiple layers of the object, I need to delete and release the memory of each object created.

Here's my deleting function, deleteMapLayer():

this.mapData.deleteMapLayer = function deleteMapLayer() {

for (var index in self.mapData.wind.data) {
    self.mapData.wind.data[index].setMap(null);
}

self.mapData.wind.data = null;
delete self.mapData.wind.data;

self.mapData.wind = null;
delete self.mapData.wind;

self.mapData.alarm.heatMapInstance.setMap(null);

self.mapData.alarm.data = null;
delete self.mapData.alarm.data;

self.mapData.alarm = null;
delete self.mapData.alarm;

for (var index in self.mapData.gasConcentration.data) {
    self.mapData.gasConcentration.data[index]
        .setMap(null);
}

self.mapData.gasConcentration.data = null;
delete self.mapData.gasConcentration.data;

self.mapData.gasConcentration = null;
delete self.mapData.gasConcentration;

};


texts:
I'm very new to Haskell, I've read most of learnyouahaskell.com and played around with some simple things, but this is probably the most 'complicated' bit of Haskell I've written so far. I have an implementation in PHP that does basically the same thing, but it is much much faster.. I'm guessing my bottleneck here is that randomRIO takes a long time to return a value, is there any way to increase the speed, or get an array of values instead of grabbing them one at a time?

That aside, any other tips and/or suggestions about improving my implementation would be very helpful!

module Main where

import System.Environment
import System.Exit
import System.Random (randomRIO)
import Control.Monad (replicateM)
import qualified Data.Map as M

import Text.Regex.Posix

main :: IO ()
main = do
    args <- getArgs
    let helpOnly = "-h" `elem` args
    if helpOnly
        then putStrLn usage
        else do
        password <- generatePassword ("-w" `elem` args)
        putStrLn password
    exitSuccess

usage :: String
usage = unlines [
        "",
        "Usage: [ -w, --with-symbols ] [ -h, --help ]",
        "",
        "By default, generates a 16 character password that does not include symbols.",
        "",
        "-w, --with-symbols  include symbols",
        "-h, --help          print a brief help message"
        ]

symbols :: String
symbols = "!$%^&*()-_=+[{]};:@#~,<.>/?"

randomReplace :: String -> String -> IO String
randomReplace [] subject = return subject
randomReplace (replacement:rs) subject = do
    randomIndex <- randomRIO (0, length subject - 1) :: IO Int
    let hash = zip [0 .. length subject - 1] subject
    (randomReplace rs . map snd . M.toList .  M.insert randomIndex replacement . M.fromList) hash

generatePassword :: Bool -> IO String
generatePassword withSymbols = do
    let passwordLength = 500 -- obviously you wouldn't use 500 as a default here, but I'm just benchmarking
    numDigits <- randomRIO (1, passwordLength) :: IO Int
    digits <- replicateM numDigits (randomRIO (1, 9) :: IO Int)
    numUppercase <- randomRIO (1, passwordLength) :: IO Int
    uppercaseLetters <- replicateM numUppercase (randomRIO ('A', 'Z') :: IO Char)
    p1 <- replicateM passwordLength (randomRIO ('a', 'z') :: IO Char)
    p2 <- randomReplace (concatMap show digits) p1
    p3 <- randomReplace uppercaseLetters p2
    password <- if withSymbols
        then do
            numSymbols <- randomRIO (1, passwordLength) :: IO Int
            symbolsToReplace <- replicateM numSymbols ((randomRIO (0, length symbols - 1) :: IO Int) >>= (\x -> return $ symbols !! x))
            randomReplace symbolsToReplace p3
        else return p3
    if (password =~ "[a-z]" :: Bool) && (password =~ "[A-Z]" :: Bool) && (password =~ "[0-9]" :: Bool) -- we knows symbols are in there since it went last
        then return password
        else generatePassword withSymbols


texts: interface design for allowing custom parameter struct, falling back on defaults

texts:
Right now I have an awkward setup, but don't really know what the cleaner solution would look like. The parameter struct is defining the action keys for a simple fly camera. Right now it looks like this:

struct FlyCameraKeyParams {
    virtual int flyForwardKey() const = 0;
    virtual int flyBackwardKey() const = 0;
    // ... and others ...
};

struct FlyCameraDefaultKeyParams : public FlyCameraKeyParams {
    virtual int flyForwardKey() const override { return 'W'; }
    virtual int flyBackwardKey() const override { return 'S'; }
    // ...
};

The question is how to most conveniently allow this to be specified. I don't think it makes much sense to allow switching the control keys mid execution, so I'm leaning toward a template. But that feels unnecessary. Currently, though, I have this ridiculous pointer bool approach:

class FlyCamera {
public:
    FlyCamera(/* position, gaze, etc params */,
              FlyCameraKeyParams *keyParams = nullptr,
              bool deleteKeyParams = true) {
        if (!keyParams) {
            mKeyParams = new FlyCameraDefaultKeyParams();
            mDeleteKeyParams = true;
        }
        else {
            mDeleteKeyParams = deleteKeyParams;
        }
    }

    virtual ~FlyCamera() {
        if (mKeyParams && mDeleteKeyParams) delete mKeyParams;
    }

protected:
    FlyCameraKeyParams *mKeyParams = nullptr;
    bool mDeleteKeyParams = true;
};

In theory the user could just issue a new CustomKeyParams() in the construction of the FlyCamera and forget about it, and if they really need to own the memory then they could by setting the boolean at the end to false. But there's no reason for this, so should I just do:

template <class KeyParams = FlyCameraDefaultKeyParams>
class FlyCamera {
public:
    static_assert(std::is_base_of<FlyCameraKeyParams, KeyParams>::value,
                  "Template parameter KeyParams must inherit from FlyCameraKeyParams");

    FlyCamera(/* no key params arg here */) {
        mKeyParams = new KeyParams();
    }

    virtual ~FlyCamera() {
        if (mKeyParams) delete mKeyParams;
    }

protected:
    FlyCameraKeyParams *mKeyParams = nullptr;
};

I want to allow users to e.g. implement using the actual arrow keys if they don't want to use WASD. Are there any cleaner alternatives that come to mind?


texts: Functional, recursive FizzBuzz in JavaScript

texts:
I was talking to a coworker about over engineering things, which somehow lead to me over engineering the hell out of fizzbuzz. I went for a functional recursive solution in JavaScript. What do you think?

Full disclosure: my knowledge of functional programming begins and ends at "functions are king" and "no side effects" so I would LOVE some feedback regarding functional programming. But please point out other inefficiencies as well.

fizzbuzz();

function fizzbuzz() {
    var i = 1;
    var result = [];

    (function loop() {
        var str = '';
        str += fizz(i);
        str += buzz(i);

        result.push(ifFalsy(str, i));

        if (isLt100(i++)) {
            loop();
        }
    })();

    print(result.join(', '));
}

function fizz(num) {
    return isDivBy3(num) ? 'fizz' : '';
}

function buzz(num) {
    return isDivBy5(num) ? 'buzz' : '';
}

function isDivBy3(num) {
    return num % 3 === 0;
}

function isDivBy5(num) {
    return num % 5 === 0;
}

function isLt100(num) {
    return num < 100;
}

function ifFalsy(value, fallback) {
    return !value ? fallback : value;
}

function print(str) {
    console.log(str);
}


texts: A recursive function that performs a binary search

texts:
I created a recursive function that uses binary search to just return true if it finds the value and false if it does not.

I'm new to recursion and binary search so please let me know where I can improve upon.

/**
* Uses binary search O(log n). Returns true if the values is in the value array false if it's not. Recursive
*/
bool binarySearch( int value, int values[], int left, int right ) {

    //keep track of when the array will be empty and return false
    if ( right < left ) {
        return false;
    }

    //Find the middle of the array
    int mid = ( left + right ) / 2;

    //compare the value to the middle of the array. If it's a match return true, else move the left position and right position accordingly
    if( value == values[ mid ] ) {
        return true;
    } else if ( value < values[ mid ] ) {
        right = mid - 1;
    } else {
        left = mid + 1;
    }

    //return the function
    return binarySearch( value, values, left, right );
}


texts: Categorization algorithm for discrete variables

texts:
I am trying to categorize some data. For that I check the distribution of the data. Then I split based on the number of appearance of each value.
The algorithm I have is working so far but really slow. I am looking to improve the speed.
The speed is important on this one because I treat a lot of different data using the same structure and the data is a bit large (140k rows)

def RamsesIdCategory(data):
    # handling Ramses Id:
    print('Starting Ramses Id')
    valueRamses = data['Ramses Trade Id'].unique()
    countRamses = data['Ramses Trade Id'].value_counts()
    for value in valueRamses:
        if countRamses.get(value) < 2:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id'] == value] = 1
        elif 2 <= countRamses.get(value) < 5:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id'] == value] = 2
        elif 5 <= countRamses.get(value) < 10:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id'] == value] = 3
        elif 10 <= countRamses.get(value) < 20:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id']== value] = 4
        elif 20 <= countRamses.get(value) < 32:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id']== value] = 5
        else:
            data['Ramses Trade Id'].loc[data['Ramses Trade Id'] == value] = 6
    print('finished Ramses Id')
    return data

EDIT : I reworked my code as I knew there was the problem with the loop doing too much iterations over my rows. Here is the new version :

def RamsesIdCategory(data):
    # handling Ramses Id:
    print('Starting Ramses Id')
    valueRamses= data['Ramses Trade Id'].value_counts()
    for i in data.index:
        if valueRamses.get(data.get_value(i,'Ramses Trade Id'))<2:
            data.set_value(i,'Ramses Trade Id',1)
        elif 2<=valueRamses.get(data.get_value(i,'Ramses Trade Id'))<5:
            data.set_value(i, 'Ramses Trade Id', 2)
        elif 5 <= valueRamses.get(data.get_value(i, 'Ramses Trade Id')) < 10:
            data.set_value(i, 'Ramses Trade Id', 3)
        elif 10<= valueRamses.get(data.get_value(i, 'Ramses Trade Id')) < 20:
            data.set_value(i, 'Ramses Trade Id', 4)
        elif 20 <= valueRamses.get(data.get_value(i, 'Ramses Trade Id')) < 32:
            data.set_value(i, 'Ramses Trade Id', 5)
        else:
            data.set_value(i, 'Ramses Trade Id', 6)
     return(data)

I iterrate over my whole dataset once and do a single select and modification instead of trying to do a multiple modification on the entire dataframe for each different value. It is 100 time faster as it ran in few sec vs 50min


texts: Functions asking for user input, with default prompts

texts:
I succeeded in the first part of the exercise, this attempt is the second part. I am not sure I have accomplished the goal, and would appreciate the input of more knowledgeable minds. As always, critiques of my techniques welcome.

This is an exercise from the book titled 'Beginning C++ through Game Programming' by Michael Dawson.

Challenge me, despite my novice level of understanding.

The exercise:

  Using default arguments, write a function that asks the user for a number and returns that number. The function should accept a string prompt from the calling code. If the caller doesn't supply a string for the prompt, the function should use a generic prompt.

  Next, using function overloading, write a function that achieves the same results.

My code:

// Chapter 05, Exercise 03: Beginning C++ through Game Programming

/*  Using default arguments, write a function that asks the user for a
    number and returns that number. The function should accept a string
    prompt from the calling code. If the caller doesn't supply a string
    for the prompt, the function should use a generic prompt.

    Next, using function overloading, write a function that achieves
    the same results.
*/

#include <iostream>
#include <string>

int askNumberFn(int number, std::string prompt = "Please enter a number, now: "); // default arguments must come last, in order of excecution
std::string askNumberFn(std::string prompt = "Please type a number, now: "); // default parameters must be different in order to overload Fn

char exitTimeFn();

int main()
{
    askNumberFn("Please type a number: "); // We require the calling code to return a prompt
    askNumberFn(); // We also require the Fn to return a default prompt

    int number = 0;
    number = askNumberFn(number, "Please enter a number: "); // To prove we have overloaded the FN, we require the Fn to also return an int

    number = 0; // We return the value of number to zero, in order to remove any doubt, if we input the same number again
    number = askNumberFn(number); // Lastly, we have to prove our overloaded Fn displays a default prompt

    exitTimeFn();
    return 0;
}

int askNumberFn(int number, std::string prompt)
{
    std::cout << prompt;
    std::cin >> number;
    std::cout << "You entered the number: " << number << std::endl;
    return number;
}

std::string askNumberFn(std::string prompt)
{
    std::string word;
    std::cout << prompt;
    std::cin >> word;
    std::cout << "You typed the number: " << word << std::endl;
    return word;
}

char exitTimeFn()
{
    char exitNow;
    std::cout << "Press 'x' to exit: ";
    std::cin >> exitNow;
    return exitNow;
}


texts:
This is a Python script that generates a grid of random HTML colors.  It works by reading random data from /dev/urandom and then encoding it as a hexadecimal string.  This string is spit into individual values that will be represented as a color.

I am wanting to know if this is the best way to generate random values for this task.  Would it be better to use the random module?  Or is my method more beneficial for this task?

WIDTH = 64
HIGHT = 5

def chunks(l, n):
   return [l[i:i+n] for i in range(0, len(l), n)]
data = file("/dev/urandom").read(HIGHT*WIDTH*3).encode("hex")
colors = ""
count = 0
for byte in chunks(data, 6):
   if count == WIDTH:
       colors+="
"
       count=0
   count+=1
   colors+="""
&#x25a0;
""" % (byte)
file("colors.html", "w").write(colors)

This is the output:


texts:
I'm a Java guy in a JavaScript world, and I'm used to certain things about Java Strings that just aren't there for in JavaScript. Some of this I can accept, for example Strings are freaking everywhere for some reason.

Now I realize this could be simply implemented with return this.indexOf(needle) === 0; (or, even more JavaScripty, return this.indexOf(needle); but the flaw in that is that it will search the entire (potentially somewhat lengthy, you never know) String in its endeavor to find the index, when I really only care if its non-zero.

My current solution, which passes my testing so far, is thus. I'm open to all feedback, but I'm most interested in

Breaks from conventional JavaScript (the bad stuff, the smells)
Corner-cases this fails for
To a reasonable extent, style

I've also decided to tack it onto the class itself (I have to admit, I like being able to do that!) Is that bad practice?

String.prototype.startsWith = function(needle) {
    // This was dubious, if only because most times "" gets passed
    // it's by mistake... but decided since it was technically correct
    // that it should stay
    if(needle === "") return true;
    // but in all other cases, falsey values were considered false
    if(!needle) return false;

    // our mission, to find the needle in the haystack - is this tacky?
    var haystack = this;

    // primarily here to prevent AIOOBEs in the loop - is this the most
    // JavaScripty way to preempt that error?
    if(needle.length > haystack.length) {
        return false;
    }
    // I've read that 'i' is not scoped to this for loop, and that I would
    // need let instead. I must support older browsers, is there a better
    // way to do this?
    for(var i = 0; i < needle.length; i++) {
        if(haystack.charAt(i) !== needle.charAt(i)) {
            return false;
        }
    }
    return true;

}


texts: Processing database data into a multidimensional array

texts:
The purpose of this code is to get data from the database and output it into a multidimensional array in JSON for my web app. But my gut instinct is telling me this code is way too messy and just generally badly written.

// Structure of user_medication http://i.imgur.com/gTrZm7B.png

public function getUserMedication($data, $success, $fail){
        Permission::required(1, function() use($data, $success, $fail){
                $user = $data["user"];
                if(!$this->isUserUIDValid($user)){
                        $fail(["detail"=>"user does not exist!"]); return;
                }
                $medicationDates = $this->database->rowQuery("SELECT * FROM (SELECT *, id AS date_id FROM user_medication_dates WHERE user_uid = ? ORDER BY date DESC LIMIT 2) AS umd LEFT JOIN user_medication AS um ON umd.date = um.date ORDER BY umd.date DESC", array($data["user"]));
                $processedMedications = [];
                foreach ($medicationDates as $key => $value) {
                        if(!isset($processedMedications[$value["date_id"]])){
                                $processedMedications[$value["date_id"]]["date"] = $value["date"];
                        } elseif(!isset($processedMedications[$value["date_id"]][$value["time"]])){
                                $processedMedications[$value["date_id"]][$value["time"]] = [];
                        }
                        $processedMedications[$value["date_id"]][$value["time"]][] = $value;
                }
                $success($processedMedications);
        });
}

/* The output in JSON;

{
   "status":"success",
   "data":{
      "96":{
         "date":"2015-05-30",
         "am":[
            {
               "id":"90",
               "date":"2015-05-30",
               "user_uid":"553669eea746d",
               "date_id":"96",
               "medication":"test",
               "dose":"1",
               "quantity":"2",
               "time":"AM"
            }
         ],
         "pm":[
            {
               "id":"91",
               "date":"2015-05-30",
               "user_uid":"553669eea746d",
               "date_id":"96",
               "medication":"another",
               "dose":"1",
               "quantity":"2",
               "time":"PM"
            }
         ]
      }
   }
}

*/


texts: Find the min and max elements of a collection, and check whether it is sorted

texts:
The function I propose allows to find the minimum and maximum values of a collection and to check that it is sorted up to a certain element. Basically it is a combination of std::minmax_element and std::is_sorted_until in a single pass function, without any significant overhead compared to a call to std::minmax_element.

template<typename ForwardIterator, typename Compare = std::less<>>
auto minmax_element_and_is_sorted_until(ForwardIterator first, ForwardIterator last,
                                        Compare compare={})
    -> decltype(auto)
{
    // Function-local result type, only the names of the
    // data members matter
    struct result_type
    {
        ForwardIterator min;
        ForwardIterator max;
        ForwardIterator sorted_until;
    } result = { first, first, last };

    // 0 or 1 elements
    if (first == last) return result;
    auto next = std::next(first);
    if (next == last) return result;

    // While it is sorted, the min and max are obvious
    auto current = first;
    while (not compare(*next, *current)) {
        ++current;
        ++next;

        // The range is fully sorted
        if (next == last) {
            result.max = current;
            return result;
        }
    }

    // The range is not sorted, use a regular minmax_element algorithm
    result.min = first;
    result.max = current;
    result.sorted_until = next;

    auto tmp = std::minmax_element(next, last, compare);
    if (compare(*tmp.first, *result.min)) {
        result.min = tmp.first;
    }
    if (not compare(*tmp.second, *result.max)) {
        result.max = tmp.second;
    }
    return result;
}

The algorithm minmax_element was introduced in Boost a long time ago before making its way into C++11. Its principal advantage is that finding both the min and max element of a collection only costs at most \$max(\lfloor \frac{3}{2}(N−1) \rfloor, 0)\$ comparisons vs. approximately \$2N\$ comparisons with separate calls to std::min_element and std::max_element.

The algorithm minmax_element_and_is_sorted_until takes the optimization logic one step further and allows to also find until which element a collection is sorted with virtually no additional comparison, while a separate call to std::is_sorted_until would have added another \$O(n)\$ comparisons.

While a bit obscure, this algorithm notably helps to optimize counting sort: some flavours of this sorting algorithm first need to know the minimal and maximal values of the collection to sort. In such a case, checking for free whether the collection is sorted allows to return early when the collection is already sorted, which is always something nice to have since it's free.

Do you think anything could be improved with this algorithm, be it a matter of correctness, style or performance?


texts: Is there a better way to walk a directory tree?

texts:
I just started to learn Haskell, and i wrote a function that walks the directory tree recursively and pass the content of each directory to a callback function:

The content of the directory is a tuple, containing a list of all the sub-directories, and a list of file names.
If there is an error, the error is passed to the callback function instead of the directory content (it use Either).

So here is the type of the callback function:

callback :: FileName -> Either IOError ([FileName], [FileName]) -> IO ()

And here is the type of my walk function:

walk :: FilePath -> (FilePath -> Either IOError ([FilePath], [FilePath]) -> IO ()) -> IO ()

And here is my complete code:

module Test where
import System.FilePath ((</>))
import Control.Monad (filterM, forM_, return)
import System.IO.Error (tryIOError, IOError)
import System.Directory (getDirectoryContents, doesFileExist, doesDirectoryExist)

myVisitor :: FilePath -> Either IOError ([FilePath], [FilePath]) -> IO ()
myVisitor path result = do
    case result of
        Left error -> do
            putStrLn $ "I've tryed to look in " ++ path ++ "."
            putStrLn $ "\tThere was an error: "
            putStrLn $ "\t\t" ++ (show error)

        Right (dirs, files) -> do
            putStrLn $ "I've looked in " ++ path ++ "."
            putStrLn $ "\tThere was " ++ (show $ length dirs) ++ " directorie(s) and " ++ (show $ length files) ++ " file(s):"
            forM_ (dirs ++ files) (\x -> putStrLn $ "\t\t- " ++ x)
    putStrLn ""

walk :: FilePath -> (FilePath -> Either IOError ([FilePath], [FilePath]) -> IO ()) -> IO ()
walk path visitor = do
    result <- tryIOError listdir

    case result of
        Left error -> do
            visitor path result

        Right (dirs, files) -> do
            visitor path result
            forM_
                (map (\x -> path </> x) dirs)
                (\x -> walk x visitor)

    where
        listdir = do
            entries <-  (getDirectoryContents path) >>= filterHidden
            subdirs <- filterM isDir entries
            files <- filterM isFile entries
            return (subdirs, files)
            where
                isFile entry = doesFileExist (path </> entry)
                isDir entry = doesDirectoryExist (path </> entry)
                filterHidden paths = do
                    return $ filter (\path -> head path /= '.') paths

main :: IO ()
main = do
    walk "/tmp" myVisitor
    walk "foo bar" myVisitor
    putStrLn "Done :-/"

As you can see, there is a lot of code and i import a lot of things...
I'm sure there is a better way to do that, and i'm interested in any
{idea,hint,tip} to improve this piece of code.

Thanks in advance :-)


texts: HackerRank: Fraudulent activity notification

texts:
I wanted to get some constructive feedback on my solution to the Fraudulent Activity Notification problem from HackerRank:

  HackerLand National Bank has a simple policy for warning clients about possible fraudulent account activity. If the amount spent by a client on a particular day is greater than or equal to 2× the client's median spending for a trailing number of days, , they send the client a notification about potential fraud. The bank doesn't send the client any notifications until they have at least that trailing number of prior days' transaction data.

  Given the number of trailing days d and a client's total daily expenditures for a period of n days, find and print the number of times the client will receive a notification over all n days.

  For example, d = 3 and expenditures = [10, 20, 30, 40, 50]. On the first three days, they just collect spending data. At day 4, we have trailing expenditures of [10, 20, 30]. The median is 20 and the day's expenditure is 40. Because 40 ≥ 2 × 20, there will be a notice. The next day, our trailing expenditures are [20, 30, 40] and the expenditures are 50. This is less than 2 × 30 so no notice will be sent. Over the period, there was one notice sent.

  Input Format

  The first line contains two space-separated integers n and d, the number of days of transaction data, and the number of trailing days' data used to calculate median spending.
  The second line contains n space-separated non-negative integers where each integer i denotes expenditure[i].

  Constraints

  1 ≤ n ≤ 2×105
  1 ≤ d ≤ n
  0 ≤ expenditure[i] ≤ 200

I believe having the a sort in there in raising the timeout for some problems.
How would you solve it without a sort? Sorting while inserting has a much higher complexity...

#include <bits/stdc++.h>
#include <array>

using namespace std;

vector<string> split_string(string);

// Complete the activityNotifications function below.
int activityNotifications(vector<int> expenditure, int d) {
  int result=0;
  int dq_idx=0;
  double median=0;
  vector<int> dq;
  for (int i =0; i< expenditure.size()-1; i++){
    if (dq_idx >= dq.size()){
      dq.push_back(expenditure[i]);
    }else {
      dq.at(dq_idx) = expenditure[i];
    }
    dq_idx=(dq_idx+1) %d;

    if (dq.size()>=d){
      sort(dq.begin(), dq.end());
      if (d %2 ==0){
        median = 2* (dq[d/2 -1 ] + dq[(d/2)])/2;
      }else {
        median = 2 * dq[d%2];
      }
      if ((float)expenditure[i+1] >= median) {
        result++;
      }
    }
  }
  return result;
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string nd_temp;
    getline(cin, nd_temp);

    vector<string> nd = split_string(nd_temp);

    int n = stoi(nd[0]);

    int d = stoi(nd[1]);

    string expenditure_temp_temp;
    getline(cin, expenditure_temp_temp);

    vector<string> expenditure_temp = split_string(expenditure_temp_temp);

    vector<int> expenditure(n);

    for (int i = 0; i < n; i++) {
        int expenditure_item = stoi(expenditure_temp[i]);

        expenditure[i] = expenditure_item;
    }

    int result = activityNotifications(expenditure, d);

    fout << result << "\n";

    fout.close();

    return 0;
}

vector<string> split_string(string input_string) {
    string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
        return x == y and x == ' ';
    });

    input_string.erase(new_end, input_string.end());

    while (input_string[input_string.length() - 1] == ' ') {
        input_string.pop_back();
    }

    vector<string> splits;
    char delimiter = ' ';

    size_t i = 0;
    size_t pos = input_string.find(delimiter);

    while (pos != string::npos) {
        splits.push_back(input_string.substr(i, pos - i));

        i = pos + 1;
        pos = input_string.find(delimiter, i);
    }

    splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

    return splits;
}


texts: Iterative implementation of K of N variations

texts:
Objective:

  Print all combinations with repetition of k elements out of a set of n elements.

using System;

namespace Chapter10Exercise2
{
    class KofNCombinationsIterative
    {
     static int[] combination;
     //-------------------------------------------------------------------------

        static void Main(string[] args)
        {
            Console.WriteLine("Type n:");
            int n = int.Parse(Console.ReadLine());

            Console.WriteLine("Type k:");
            int k = int.Parse(Console.ReadLine());

            FindCombinations(n, k);
        }
        //----------------------------------------------------------------------

        /*
            Method: FindCombinations(int n, int k)

            It prints the combinations of k elements
            in a set of n elements.

            It increments the values of an array of size k
            from 1 to n, starting from the last element.
        */
        private static void FindCombinations(int n, int k)
        {
            combination = new int[k];
            int initialValue = 1;
            InitializeArray(combination, initialValue);
            int valueAfterOverflow = 1;

            while (true)
            {
                // print current combination
                PrintCombination();

                // increase value at current index
                int index = k - 1;
                ++combination[index];

                // go to the next index
                while (combination[index] > n)
                {
                    ++valueAfterOverflow;
                    combination[index] = valueAfterOverflow;
                    --index;

                    // if current index is < 0 exit
                    if (index < 0)
                    {
                        return;
                    }
                    ++combination[index];
                }
            }
        }
        //----------------------------------------------------------------------

        /*
            Method: PrintCombination()

        */
        private static void PrintCombination()
        {
            Console.Write("(");
            for (int i = 0; i < combination.Length; ++i)
            {
                Console.Write(combination[i]);

                if (i < combination.Length - 1)
                {
                    Console.Write(", ");
                }
            }
            Console.WriteLine(")");
        }
        //----------------------------------------------------------------------

        /*
            Method: InitializeArray(int[] arr, int initialValue)

        */
        static void InitializeArray(int[] arr, int initialValue)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                arr[i] = initialValue;
            }
        }
    }
}

Input:

  Type n: 3
   Type к: 2

Output:

  (1 1), (1 2), (1 3), (2 2), (2 3), (3 3)

I've been trying to get rid of the variable valueAfterOverlow to no avail, is there a way to use some of the already defined variables: index, n and k to update the value after overflow?

Is the complexity: $$O(n^k)$$ ,i.e. n-incrementations of k variables (plus some additional work)?

Is there more effective iterative algorithm?


texts: Could someone check the Minimax Algorithm correctly implemented?

texts:
I'm working on AI tic-tac-toe that computer make a move and I wanted to know that I correctly implemented the minimax algorithm. Please someone check my code to identify a problem or any kind of bug. Any help would be greatly appreciated.

I wanted to know that my code is correctly running the minimax algorithm according to this image.

test-cases-for-tic-tac-toe

from math import inf as infinity

def winner(game, turn):
    win_game = [
        [game[0][0], game[0][1], game[0][2]],
        [game[1][0], game[1][1], game[1][2]],
        [game[2][0], game[2][1], game[2][2]],
        [game[0][0], game[1][0], game[2][0]],
        [game[0][1], game[1][1], game[2][1]],
        [game[0][2], game[1][2], game[2][2]],
        [game[0][0], game[1][1], game[2][2]],
        [game[2][0], game[1][1], game[0][2]],
    ]
    if [turn, turn, turn] in win_game:
        return True
    else:
        return False

def draw(game):
    """ Check whether the board is full """
    counter = 0
    for i in range(3):
        for j in range(3):
            if game[i][j] == "X" or game[i][j] == "O":
                counter+=1
    return counter == 9

def game_over(game, turn):
    return winner(game, turn) or draw(game)

def available_moves(game):
    cell = []
    for i in range(3):
        for j in range(3):
            if not(game[i][j] == "X" or game[i][j] == "O"):
                cell.append([i, j])
    return cell

def minimax(game, turn):
    if winner(game, "X"):
        return 1
    elif winner(game, "O"):
        return -1
    elif draw(game):
        return 0

    moves = available_moves(game)
    print(moves)

    if turn == "X":
        value = -infinity
        for move in moves:
            tmp = game[:][:]
            tmp[move[0]][move[1]] = "X"
            value = max(value, minimax(game, "O"))
            tmp[move[0]][move[1]] = None
            x, y = move[0], move[1]
    else:
        value = infinity
        for move in moves:
            tmp = game[:][:]
            tmp[move[0]][move[1]] = "O"
            value = min(value, minimax(game, "X"))
            tmp[move[0]][move[1]] = None
            x, y = move[0], move[1]
    return value

if __name__ == '__main__':

    game = [
        ["O", None, None],
        ["O", "X", "X"],
        [None, "O", "X"]]

    print(minimax(game, "X"))


texts:
This is from an exercise I've done:

We want to implement a priority queue system to plan the execution of the system processes. An array of MAXPRI represents the priorities of the system, where 0 is the highest priority and MAXPRI-1 is the lowest priority.  Each position i in the array will contain a dynamic linked list where the first element of this is the priority i process that must be executed (provided there are no processes available in the previous i-1 positions). Implement the following operations:

Create. Initialize array.

AddProcess. Given a priority and a process identifier, it adds the process to the end of the corresponding list.

ExecuteProcess. Remove from the list the most priority process. If there are no processes to execute, it will be indicated with a warning message.

Search. Given a process identifier it returns the priority of this one. If the id of the process does not exist, -1 will be returned.

Display. Go through the structure to show the existing processes that are available for execution sorted by priority (highest first).

main.c, linkedListArray.c, linkedListArray.h

#include "linkedListArray.h"

void Create(Node **queue)
{
    for (int i = 0; i < MAXPRI; i++) {
        queue[i] = NULL;
    }
}

void Push(Node **queue, int pri, int id)
{
    Node *new_node = malloc(sizeof(Node));
    if (new_node != NULL) {
        new_node->id = id;
        new_node->next = NULL;
        if (queue[pri] == NULL) {
            queue[pri] = new_node;
        }
        else {
            Node *aux = queue[pri];
            while (aux->next != NULL) {
                aux = aux->next;
            }
            aux->next = new_node;
        }
    }
}

void Execute(Node **queue)
{
    bool end = false;
    int i = 0;

    while (!end && i < MAXPRI) {
        if (queue[i] != NULL) {
            Node *aux = queue[i];
            queue[i] = queue[i]->next;
            free(aux);
            end = true;
        }
        i++;
    }
    if (!end) {
        printf("There are no processes\n");
    }
}

int Search(Node **queue, unsigned int id)
{
    int pri = -1;
    Node *aux;

    for (int i = 0; i < MAXPRI  &&  pri == -1; ++i) {
        aux = queue[i];
        while (aux != NULL  &&  pri == -1) {
            if (aux->id == id) {
                pri = i;
            }
            else
                aux = aux->next;
        }
    }
    return pri;
}

void Output(Node *head)
{
    for (Node *current = head; current != NULL; current = current->next) {
        if (current->next != NULL)
            printf ("%d -> ", current->id);
        else
            printf ("%d", current->id);
    }
}

void Display(Node **queue)
{
    for (int i = 0; i < MAXPRI; i++) {
        printf ("Priority queue %d: ", i);
        Output(queue[i]);
        putchar('\n');
    }
    putchar('\n');
}


texts: Is this a decent way to create an EntityManager?

texts:
I'm pretty new to C++.  I'm trying to design a EntityManager system, and so far this is what I have:

#ifndef ENTITY_MANAGER
#define ENTITY_MANAGER

#include "Entity.h"
#include "Airplane.h"
#include "Runway.h"
#include "Customer.h"
#include <unordered_map>

class EntityManager
{
private:
    typedef std::unordered_map<int, Entity*> EntityMap;

    EntityMap entityMap;
public:
    /*
    Gets an instance of the EntityManager
    */
    static EntityManager* instance();

    /*
    Creation and Deletion
    */

    /*
    Registers an Entity
    */
    void registerEntity(Entity* entity)
    {
        entityMap.insert(std::pair<int, Entity*>(entity->getId(), entity));
    }

    /*
    Removes an Entity by its ID
    */
    void removeEntity(int id)
    {
        entityMap.erase(id);
    }

    /*
    Removes an Entity by its instance
    */
    void removeEntity(Entity* entity)
    {
        removeEntity(entity->getId());
    }

    /*
    Gets an Entity by its id
    */
    Entity* getById(int id)
    {
        return entityMap.at(id);
    }

    /*
    Gets all the Airplanes
    */
    std::set<Airplane*> getAirplanes()
    {
        std::set<Airplane*> result;
        for (std::unordered_map<int, Entity*>::iterator it = entityMap.begin(); it != entityMap.end(); it++)
        {
            Entity* e = it->second;
            Airplane* plane = dynamic_cast<Airplane*>(e);
            if (plane)
            {
                result.insert(plane);
            }
        }
        return result;
    }

    /*
    Gets all the Runways
    */
    std::set<Runway*> getRunways()
    {
        std::set<Runway*> result;
        for (std::unordered_map<int, Entity*>::iterator it = entityMap.begin(); it != entityMap.end(); it++)
        {
            Entity* e = it->second;
            Runway* runway = dynamic_cast<Runway*>(e);
            if (runway)
            {
                result.insert(runway);
            }
        }
        return result;
    }

    /*
    Gets all the Customers
    */
    std::set<Customer*> getCustomers()
    {
        std::set<Customer*> result;
        for (std::unordered_map<int, Entity*>::iterator it = entityMap.begin(); it != entityMap.end(); it++)
        {
            Entity* e = it->second;
            Customer* customer = dynamic_cast<Customer*>(e);
            if (customer)
            {
                result.insert(customer);
            }
        }
        return result;
    }
};
#endif

A little background:

Entity is my base class, which handles assigning itself an id, etc.
Airplane is a subclass of Entity, which has methods that describe its size, fuel, etc
Runway is a subclass of Entity, which also has methods to describe its size
Customer is a subclass of Entity, which has methods describing its AI state, etc

I'm looking for any help I can get in things like code correction and design flaws.


texts: Generating a histogram efficiently from the datasets in a Map

texts:
I have a map in which I store total bytes as the key and count of users as the value:

Map<Integer, Integer> userHistogramInfo = new HashMap<Integer, Integer>();

Now I need to make a histogram as mentioned below:

How many users have data with 200,000 bytes (200 kilo bytes)
How many users have data with 500 bytes
How many users have data with 200 bytes
How many users have data with 100 bytes

As an example it might be possible that 100 million users have data of 500 bytes. I need to make a histogram of current data usage of the users.

We can define a certain bucket size under which I need to find out how many users have data within that bucket.

public void generateHistogram(Map<Integer, Integer> userHistogramInfo) {
    int[] definitionInBytes = { 10, 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480, 40960, 81920 };
    long[] buckets = new long[definitionInBytes.length];
    System.out.println("Below is the Histogram List sorted on the bytes: \n");
    System.out.println("BytesStored           Number");
    SortedSet<Integer> keys = new TreeSet<Integer>(userHistogramInfo.keySet());
    for (Integer key : keys) {
        Integer value = userHistogramInfo.get(key);
        System.out.println(key + "                      " + value);
    }

    System.out.println();
    for (Integer time : userHistogramInfo.keySet()) {
        for (int i = definitionInBytes.length - 1; i >= 0; i--) {
            if (time >= definitionInBytes[i]) {
                buckets[i] += userHistogramInfo.get(time);
                break;
            }
        }
    }
    for (int i = 0; i < definitionInBytes.length; i++) {
        String period = "";
        if (i == definitionInBytes.length - 1) {
            period = "greater than " + definitionInBytes[i] + " bytes";
        } else {
            period = "between " + (definitionInBytes[i] + 1) + " and " + definitionInBytes[i + 1] + " bytes";
        }
        System.out.println(buckets[i] + " came back " + period);
    }
}

Is there any better way of doing this and making the histogram? I need to get a break down of how many users have x bytes of data. I am doing the right thing by choosing the bucket size?


texts:
I am trying to capture screenshots as fast as possible from when it's displayed, meaning that I want the latency to be minimal.

Currently, I am using user32.dll to capture a window.  So, if I have a game, I capture that window along with borders and everything. It's very fast, but I wonder if hooking into the API (DirectX) and getting the buffer will be faster than this (I don't know how to do that, though).

Here's how I'm doing it:

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect);
    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);

private static MemoryStream PrintWindow(string prcname)
{
    IntPtr hwnd;
    using (var proc = Process.GetProcessesByName(prcname)[0])
    {
        hwnd = proc.MainWindowHandle;
    }
    Rect rc;
    NativeMethods.GetWindowRect(hwnd, out rc);
    using (Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
    {
        using (Graphics gfxBmp = Graphics.FromImage(bmp))
        {
            IntPtr hdcBitmap = gfxBmp.GetHdc();
            try
            {
                NativeMethods.PrintWindow(hwnd, hdcBitmap, 0);
            }
            finally
            {
                gfxBmp.ReleaseHdc(hdcBitmap);
            }
        }
        MemoryStream ms = new MemoryStream();
        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        return ms;
    }
}

I give it a process name and it will hook to that certain window.  And as I've said, it's not slow; it's fast. But I think it may be slower than what can be achieved, especially since the actual render of the game is often different from the screen (for example, 30FPS on the game, and it's 60HZ on the screen, meaning 50% of the images will be duplicates).

Any ideas about this?


texts: Extract and sort all numbers that appear after ',

texts:
I am currently learning Python and I wrote the following code.
The code searches the string for all digits that appear after ',, sorts them and joins them into a string.
I have a strong feeling that it can be shortened...
Can anyone suggest how?

s = "'bhhd',12 'kjubk',2 'bjki',98 'khjbjj',4"
res = re.findall(r"(',)(\d+)", s)
all = []
for r in res:
   all.append(r[1])

print(",".join(sorted(all, key=int)))


texts:
In a recent project my backend architecture consists of

Repositories (talking to database)
Services (handling business logic)
Controllers (handling incoming REST calls and providing according responses to the client)

I introduced DTO classes for representing the data that is returned by the controllers when a client calls a REST route. Because the services work with Entities, I need to somehow map those to my DTOs. The DTOs contain most of the properties of the according Entity, but can define additional properties as well.
First of all, I have the following Entities:
Image Entity
@Entity()
export class Image {
    id: number;
    name: string;

    @ManyToOne(...)
    parentFolder: Folder;

    @ManyToMany(...)
    tags: Tag[];
}

Tag Entity
@Entity()
export class Tag {
    id: number;
    label: string;

    @ManyToMany(...)
    images: Image[];
}

As you can see, there are also some relations (ManyToOne, ManyToMany), so my Entities contain references to other Entities. Same for according DTOs.
Next, you can see my shortened ImageController. In the method findOne, a service is asked to look for an Entity with given id in the database.
Image Controller
@Controller('image')
export class ImageController {
    constructor(
        private readonly imageService: ImageService,
        private readonly imageEntityToDtoMapper: ImageEntityToDtoMapper
    ) { }

    @Get(':id')
    async findOne(@Param('id') id): Promise<ImageDto> {
        const image: Image = await this.imageService.findOne(id);
        return this.imageEntityToDtoMapper.map(image);
    }
}

In order to let the controller return a DTO, the result is mapped by an ImageEntityToDtoMapper.
ImageEntityToDtoMapper
@Injectable()
export class ImageEntityToDtoMapper {
    constructor(
        private readonly folderService: FolderService,
        private readonly folderEntityToDtoMapper: FolderEntityToDtoMapper,
        @Inject(forwardRef(() => TagEntityToDtoMapper))
        private readonly tagEntityToDtoMapper: TagEntityToDtoMapper
    ) { }

    async map(entity: Image): Promise<ImageDto> {
        if (entity) {
            const parentFolderPath = await this.folderService.buildPathByFolderId(entity.parentFolder.id);
            const absolutePath = `${parentFolderPath}${path.sep}${entity.name}`;

            const dto = new ImageDto();
            dto.id = entity.id;
            dto.name = entity.name;
            dto.absolutePath = absolutePath;
            dto.parentFolder = await this.folderEntityToDtoMapper.map(entity.parentFolder);
            dto.tags = await this.tagEntityToDtoMapper.mapAll(entity.tags);
            return dto;
        }
    }
}

And here are my questions, all regarding ImageEntityToDtoMapper:

Beside simply mapping properties id and name from one class to the other, I'm also "calculating" absolutePath, which is not contained in the original Entity, but only in DTO. Is this mapper class the correct place for that?
Furthermore, for that reason I need to inject the FolderService to the mapper, which seems not quite correct to me...

Because of the ImageEntities' relations to Folder and Tag, I need to call their mapper classes from the ImageEntityToDtoMapper. Is this the correct way to do it?

Because I need to inject other Entities' mappers, I have a circular dependency between ImageEntityToDtoMapper and TagEntityToDtoMapper. And in my whole project, I have more cases where multiple mappers depend on each other.
Although the library (NestJS) I'm using offers a way to handle this by using forwardRef, I would like to avoid those circular dependencies. Could you think of any possibility?


texts: Checking if IDs in array are not null and adding them into new array

texts:
My view object:

{
    description: "2tik 2tags"
    id: 100
    portfolio: "TSLA"
    term_id_1: 260751
    term_id_2: 285493
    term_id_3: null
    ticker_1: "GOOG"
    ticker_2: "TSLA"
    ticker_3: ""
    timespan: "ld"
    top: ""
}

I need to grab the term_ids and stick them into a new array, but only if they are not null.

What I'm currently using:

function reSelectTags(view) {
    console.log('view',view);
    // Seperate term_ids:
    var term_ids = [];

    if (view.term_id_1 != null) {
        term_ids.push(view.term_id_1);
    }

    if (view.term_id_2 != null) {
        term_ids.push(view.term_id_2);
    }

    if (view.term_id_3 != null) {
        term_ids.push(view.term_id_3);
    }

    console.log('term_ids',term_ids);
}

This gets the job done, but I'm wondering if there is a better, cleaner way, perhaps on 1 or 2 lines that could accomplish this as well.


texts:
I want to create an XML format in which I will define data objects for a game I am currently working on.

The base idea is that I will have Elements which can be combined in other Elements, Items or Spells.

A primal element is an element which is directly available.
If an element is not primal then in order to create it, it must be combined from other elements so it will have a recipe definition (list of components required to combine in order to create the specific entity).

Items and Spells also need to have a recipe.

As of now I created the sample XML:

<TechTree>

    <ElementDefinitions>
        <Element name="Fire" primal="true"/>
        <Element name="Earth" primal="true"/>
        <Element name="Nature" primal="true"/>
        <Element name="Mana" primal="true"/>

        <Element name="Lava">
            <Component>Fire</Component>
            <Component>Fire</Component>
            <Component>Earth</Component>
        </Element>

        <Element name="Grass">
            <Component>Nature</Component>
            <Component>Mana</Component>
            <Component>Earth</Component>
        </Element>

    </ElementDefinitions>

    <ItemDefinitions>
        <Item name="ManaPotion">
            <Component>Mana</Component>
            <Component>Grass</Component>
            <Component>Nature</Component>
        </Item>
    </ItemDefinitions>

    <SpellDefinitions>
        <Spell name="FireSpell">
            <Component>Fire</Component>
            <Component>Fire</Component>
            <Component>Mana</Component>
        </Spell>

        <Spell name="HealingSpell">
            <Component>Nature</Component>
            <Component>Nature</Component>
            <Component>Mana</Component>
        </Spell>

        <Spell name="MoltenArmor" selection="ordered">
            <Component>Lava</Component>
            <Component>Nature</Component>
            <Component>Mana</Component>
        </Spell>

        <Spell name="RestoreMana">
            <Component>Mana</Component>
            <Component>Mana</Component>
            <Component>Mana</Component>
        </Spell>

    </SpellDefinitions>

</TechTree>

As of now there aren't too many attributes, but in the future the entities will have all kind of attributes (damage, effect, usable conditions etc) so I need to have a format that would allow me to extend, for instance, all items but not spells or elements.

I will enforce with an XML schema that components used in the recipe must be already defined. So writing Air as a component without firstly defining it will yield an error.

Although as of now all recipes have 3 elements in the future I might decide to create some with a different number.

I would greatly appreciate feedback or tips on how can I improve the format.


texts:
I'm trying to write a program where computer attempts to guess a number entered by user. Computer should keep asking until guessed number will be equal to user number.

If you know what can be improved to make this code more readable, if implementation of the binary search algorithm is efficient, let me know!

#include <cstdlib>
#include <iostream>

int main() {
    std::srand(time(nullptr));
    constexpr int MIN = 1;
    constexpr int MAX = 100;
    std::cout << "Choose a number from " << MIN << " to " << MAX << "\n";
    int number;
    std::cin >> number;
    int high = MAX;
    int low = MIN;
    int guess = (high + low) / 2;
    char lessThan = std::rand() % 2 == 0 ? 'y' : 'n';
    char greaterThan = std::rand() % 2 == 0 ? 'y' : 'n';
    while (greaterThan == lessThan)
        greaterThan = std::rand() % 2 == 0 ? 'y' : 'n';
    while (guess != number) {
        if (lessThan == 'y' && greaterThan == 'n') {
            std::cout << "Is your number less than " << guess << "? [y|n]\n";
            std::cin >> lessThan;
            if (lessThan == 'y') {
                high = guess - 1;
                greaterThan = 'n';
            } else if (lessThan == 'n') {
                low = guess + 1;
                greaterThan = 'y';
            }
        } else if (greaterThan == 'y' && lessThan == 'n') {
            std::cout << "Is your number greater than " << guess << "? [y|n]\n";
            std::cin >> greaterThan;
            if (greaterThan == 'y') {
                low = guess + 1;
                lessThan = 'n';
            } else if (greaterThan == 'n') {
                high = guess - 1;
                lessThan = 'y';
            }
        }
        guess = (high + low) / 2;
    }
    std::cout << "I guessed!\n";
    return 0;
}


texts: Calculation in Concern module using Rails

texts:
I wrote the following Concern module. Is it good practice to perform all the calculations in the included scope? How can it be improved?

module Pagination
  module Helper
    extend ActiveSupport::Concern

    included do
      class << self
        def paged(params, custom_per_page = nil, custom_page = nil)
          per_page = params[:per_page] =
            custom_per_page || normalize_per_page(params[:per_page].to_i)
          page = normalize_page(self.all.size,
            custom_page || params[:page].to_i, per_page)

          self.paginate(page: page, per_page: per_page)
        end

        def default_per_page
          Reader::Application.config.custom.default_per_page_pagination
        end

        protected

        def normalize_per_page per_page
          if per_page < 1 || per_page > default_per_page
            return default_per_page
          end
          per_page
        end

        def normalize_page(size, page, per_page)
          if ((page - 1) * per_page) >= size
            page = (size / per_page.to_f).ceil
          end
          page > 0 ? page : 1
        end
      end
    end
  end
end

ActiveRecord::Base.send(:include, Pagination::Helper)


texts: Get default value from query params + repeating code

texts:
The main goal of this task is to take values from the query parameter and put it in inputu. The first problem is that I don't know much about how to do it so that the code doesn't repeat itself and I don't know how specifically I could improve the code so that multiple things don't happen again.
Next, the function should contain a simple validation of min max to prevent them from entering silliness from the query parameter.
getFromQuery = props => {
    const { limitValues } = props;
    const parsed = queryString.parse(location.search);

    const validation = (value, min, max) => {
        if (value < min) {
            return min;
        } else if (value > max) {
            return max;
        }
        return value;
    };

    if (parsed.price) {
        const defautPrice = limitValues.find(item => item.sliderType === 'PRICE');
        props.inputs.PRICE = validation(parsed.price, defautPrice.minValue, defautPrice.maxValue);
    }

    if (parsed.savings) {
        const defautSavings = limitValues.find(item => item.sliderType === 'SAVINGS');
        props.inputs.SAVINGS = validation(parsed.savings, defautSavings.minValue, defautSavings.maxValue);
    }

    if (parsed.maturity) {
        const defautMaturity = limitValues.find(item => item.sliderType === 'MATURITY');
        props.inputs.MATURITY = validation(parsed.maturity, defautMaturity.minValue, defautMaturity.maxValue);
    }
};


texts:
This code acts as an infinite generator of prime numbers.

As new prime numbers are found, they are added to a set. Then, a number x is found to be prime if none of the numbers in the prime set are factors of x. Only the primes less than or equal to the square root of x need to be checked.

import itertools
from math import sqrt

class stream:
    """ Class of infinite streams. """

    def prime():
        """ Stream of prime numbers. """
        prime_set = {2} # Set of prime numbers that have been found
        yield 2 # First prime
        for x in itertools.count(3, 2): # Check odd numbers, starting with 3
            primes_below_sqrt = {i for i in prime_set if i <= sqrt(x)}
            for prime in primes_below_sqrt:
                if x % prime == 0:
                    break # x is divisible by a prime factor, so it is not prime
            else:
                prime_set.add(x) # x has been shown to be prime
                yield x

Using the itertools recipe:

def take(iterable, n):
    """ Returns first n items of the iterable as a list. """
    return list(itertools.islice(iterable, n))

Output:

>>> take(stream.prime(), 10)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]


texts:
I have this rather verbose piece of code. How can I get it shorter and simpler?

This function aggregate results of test by population and by different keys:

def aggregate(f):
  """ Aggregate population by several keys """
  byMerchant  = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0]))
  byPlat      = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0]))
  byDay       = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0]))
  byAffiliate = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0]))
  byCountry   = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0]))
  byType      = col.defaultdict(lambda: col.defaultdict(lambda: [0,0,0,0]))
  byPop       = col.defaultdict(lambda: [0,0,0,0])
  for line in f:
    fields = line.strip().split("^A")
    if fields[2] == '\\N':  continue

    day          = fields[0]
    popid        = int(fields[1])
    affiliate_id = int(fields[2])
    merchant_id  = int(fields[3])
    clicks       = int(fields[4])
    displays     = int(fields[5])
    sales        = float(fields[6])
    gross        = float(fields[7])

    merchant_plat = partners_info[merchant_id][1]
    merchant_name = partners_info[merchant_id][0]

    publisher_name    = publisher_info[affiliate_id][0]
    publisher_country = publisher_info[affiliate_id][1]
    publisher_type    = publisher_info[affiliate_id][2]

    data = [clicks,displays,sales,gross]
    for k in xrange(len(data)):
      byMerchant[merchant_name][popid][k]    += data[k]
      byPlat[merchant_plat][popid][k]        += data[k]
      byAffiliate[publisher_name][popid][k]  += data[k]
      byCountry[publisher_country][popid][k] += data[k]
      byDay[day][popid][k]                   += data[k]
      byType[publisher_type][popid][k]       += data[k]
      byPop[popid][k]                        += data[k]

return byPop, byMerchant, byPlat, byDay, byAffiliate, byCountry, byType


texts: How to optimize bitwise get/set/clear of ranges of bits on 8-bit integers in JavaScript?

texts:
I have been working for a few days on writing get, set, and clear bitwise functions in JavaScript to clear not individual bits from an integer n, but to clear entire ranges of bits in n.
For example, using the functions below, I would expect this behavior:
getNumBits(0b101) // 3
getNumBits(0b10100000) // 8

// getBitRange(integer, startIndex, size)
getBitRange(0b101110010001111, 1, 4) // 1110
getBitRange(0b101110010001111, 5, 7) // 1

// setBitRange(integer, startIndex, value)
setBitRange(0b101110010001111, 5, 0b1001) // 0b101111001001111

// clearBitRange(integer, startIndex, size)
clearBitRange(0b101110010001111, 5, 5) // 0b101110000001111
clearBitRange(0b101110010001111, 2, 3) // 0b100000000001111

How can I optimize these functions by removing or reordering any of the operations? Can we cut out any steps? I did my best to figure out how to just barely implement the function, but I am no master at bit operations yet. Wondering if one could rewrite these 4 functions to make them more optimal. Please keep each instruction on its own line so it's easier to see :)
function getNumBits(n) {
  let i = 0
  while (n) {
    i++
    n >>= 1
  }
  return i
}

function getBitRange(n, l, s) {
  let r = 8 - l - s
  let p = 1 << p
  let o = p - 1
  let ol = o << r
  let or = o >> l
  let om = or & ol
  let x = n & om
  return x >> r
}

function setBitRange(n, i, x) {
  let o = 0xff // 0b11111111
  let c = getNumBits(x)
  let j = 8 - i // right side start
  let k = j - c // right side remaining
  let h = c + i
  let a = x << k // set bits
  let b = a ^ o // set bits flip
  let d = o >> h // mask right
  let q = d ^ b //
  let m = o >> j // mask left
  let s = m << j
  let t = s ^ q // clear bits!
  let w = n | a // set the set bits
  let z = w & ~t // perform some magic https://stackoverflow.com/q/8965521/169992
  return z
}

function clearBitRange(n, i, c) {
  let s = i + c
  let r = 8 - s
  let p = 1 << 8
  let o = p - 1
  let j = o >> i
  let k = o << r
  let h = j & k
  let g = ~h
  let z = n & g
  return z
}

This is only concerned with 8-bit numbers.


texts:
Find the maximum sum of subarray with Kadane's algorithm

//test case
int maxKanade, startKanade, endKanade;
maxKanade = Kadane(new List<int>() { 2, -4, 6, -3, 9 }, out startKanade, out endKanade);
Debug.WriteLine("{0} {1} {2}", maxKanade, startKanade, endKanade);
maxKanade = Kadane(new List<int>() { 3, 4, 6, -3, -9 }, out startKanade, out endKanade);
Debug.WriteLine("{0} {1} {2}", maxKanade, startKanade, endKanade);
//test case end

public static int Kadane(List<int> input, out int start, out int end)
{
    //from wiki https://en.wikipedia.org/wiki/Maximum_subarray_problem
    //def max_subarray(A):
    //max_ending_here = max_so_far = 0
    //for x in A:
    //    max_ending_here = max(0, max_ending_here + x)
    //    max_so_far = max(max_so_far, max_ending_here)
    //return max_so_far
    start = 0;
    int s = 0;
    end = 0;
    int count = 0;
    int max_ending_here = 0, max_so_far = 0;
    foreach(int i in input)
    {
        if (max_ending_here + i > 0)
        {
            max_ending_here += i;
        }
        else
        {
            // if go negative basically take a fresh start
            max_ending_here = 0;
            s = count + 1;
        }
        if (max_so_far < max_ending_here)
        {
            max_so_far = max_ending_here;
            end = count;
            start = s;
        }
        count++;
    }
    return max_so_far;
}


texts:
#include <stdio.h>
#include <stdint.h>
#include <assert.h>

typedef uint8_t byte;
typedef struct
{
    byte i, j;
    byte S[256];
} Rc4State;

void swap(byte *a, byte *b)
{
    byte temp = *a;
    *a = *b;
    *b = temp;
}

/*Initialization & initial permutation
also initialize i&j counters in state for stream generation*/
void initState(const byte K[256], int keylen, Rc4State *state)
{
    byte T[256];
    assert(keylen>=1 && keylen<=256);
    int i;
    for(i = 0; i < 256; i++) {
        state-> S[i] = i;
        T[i] = K[i % keylen];
    }

    //Initial permutation of S
    byte *S = state->S;
    int j = 0;
    for(i = 0; i < 256; i++) {
        j = (j + S[i] + T[i]) % 256;
        swap(&S[i], &S[j]);
    }

    //Initialize counters in state
    state->i = state->j = 0;
}

/*Encrypt/Decrypt text by XORing with next byte of keystream*/
byte crypt(byte text, Rc4State *state)
{
    byte t, k;
    byte *i = &(state->i), *j = &(state->j);
    byte *S = state->S;
    *i = (*i+1) % 256;
    *j = (*j+S[*i]) % 256;
    swap(&S[*i], &S[*j]);
    t = (S[*i] + S[*j]) % 256;
    k = S[t];

    return text ^ k;
}

I considered removing the %256 since it's implied in unsigned 8 bit arithmetic but left it in for clarity.

I asked this on SO.

Any comments would be appreciated.


texts: NewPolish - unconventional translator in Python

texts:
Hello everyone!
In today's assignment I had to complete a rather unusual translator, take a look at my solution, tell me what I can do to make it better and show off yours!
Write a function that translates some text into New Polish and vice versa. Polish is translated into New Polish by taking the last letter of each word, moving it to the beginning of the word and adding ano at the beginning. Tom has a cat' becomes ['Anomto anosha anoa anotca'].
def new_polish_translator(input):

    result = ''

    content = input.replace(',', '').replace('.', '').replace('?', '').replace('-', '')

        #Dzieli na linie bez wchodzenia do nowej linii (\n)
    lines = [line.rstrip() for line in content.split("\n")]
    lines = [line for line in lines if len(line) > 0]

        #sprawdza czy nie jest przetlumaczony
    if all(line[-3::] == 'ano' for line in lines for word in line.split(' ')):
        result = ' '.join(lines)

        #sprawdza czy nie jest
    else:
        result = ' '.join('ano' + word[-1] + word[0:-1] for line in lines for word in line.split(' '))
        result = result.capitalize()

    return result

new_polish_translator("Tom has a cat")

result:
'Anomto anosha anoa anotca'

Have a great day!


texts:
I'm curious if there's any way I can substantially improve its speed (it runs through >200k rows). I think I'll most likely need this once, so please bear with me since it probably looks terrible.

Thanks for reading!

Code I would like reviewed:

Option Explicit

Public Sub RemoveDuplicates()
    Dim r As Range
    Dim rBefore As Range
    Dim wsSource As Worksheet
    Dim ws As Worksheet
    Dim c As Range
    Dim c_ As Range
    Dim v As Variant
    Dim v_ As Variant
    Dim dupCount As Long
    Dim xlApp As Application
    Dim i As Long
    Dim size As Long

    Set xlApp = Excel.Application
    With xlApp
        .ScreenUpdating = False
        .DisplayStatusBar = True
        .StatusBar = "Running Script..."
    End With

    Set wsSource = xlApp.ThisWorkbook.Worksheets("source")
    Set rBefore = wsSource.Range(wsSource.Cells(2, 1), wsSource.Cells(wsSource.UsedRange.Rows.Count, 1))

    Set ws = xlApp.ThisWorkbook.Worksheets("testSheet")
    Set r = ws.Range(ws.Cells(2, 1), ws.Cells(ws.UsedRange.Rows.Count, 1))
    size = r.Count
    i = 1
    For Each v In r
        Set c = v

        DoEvents
        dupCount = 0
        For Each v_ In r
            Set c_ = v_

            DoEvents
            If CStr(c.Value) = CStr(c_.Value) Then
                dupCount = dupCount + 1
                If dupCount > 1 Then
                    c_.Rows(c_.Row).EntireRow.Delete
                End If
            End If
        Next
        xlApp.StatusBar = Format(i & " out of " & size) & " Rows Complete"
        i = i + 1
    Next

    With xlApp
        .ScreenUpdating = True
        .DisplayStatusBar = False
        .DisplayAlerts = False
        .ThisWorkbook.Save
        .DisplayAlerts = True
        .ThisWorkbook.Close
    End With
End Sub


texts: Simple Tip Calculator with JavaScript Console App

texts:
Simple console tip calculator app in JavaScript. I would like to get some feedback on improving my code. Thank you beforehand.

Source code:

//header
const headerMessage = () => {
  console.log('Tip Calculator')
}

//service quality
const serviceQuality = (billEntered, userOption ) => {
  const userInput = Number(userOption);
  switch(userInput){
    case 1:
      return (billEntered * 0.3)
      break;
    case 2:
      return(billEntered * 0.2)
      break;
    case 3:
      return(billEntered * 0.1)
      break;
    case 4:
      return(billEntered * 0.05)
      break;
   }
}

const tipCalulcator = () => {
  headerMessage()
  const enterBill = prompt('Please tell me bill amount: $ ');
  console.log(`Bill amount was $ ${enterBill}`)
  console.log(`How was your service ? Please enter number of the options`)
  const enterOption = prompt(`  1) Outstanding (30%)
  2) Good (20%)
  3) It was ok (10%)
  4) Terrible (5%)`)

  const result = serviceQuality(enterBill, enterOption);
  console.log(`Tip amount ${result}`)
  const total = Number(enterBill) + result;
  console.log(`Overall paycheck ${total}`)
}

tipCalulcator();


texts: Am I dynamic filtering correctly in Django?

texts:
I needed a way to get URL parameters and put them and their values into a query set's .filter() if they exist. After a day of piecing together information from the Interwebs, I have a working solution to my problem. However, is it the best way to do this? I feel it can be improved or streamlined, but my tiny brain is failing me:

In utilities.py:

def get_filters(url, allowed):
    query = parse.urlsplit(url).query
    pack = dict(parse.parse_qsl(query))
    translated = {}

    for pk, pv in pack.items():
        for ak, av in allowed.items():
            if pk == ak:
                translated[av] = pv

    return translated

In views.py:

from utilities import get_filters

people = Person.objects.all()
url = request.get_full_path()

allowed_filters = {
    'location': 'person_location',
    'role': 'person_role',
}

filters = get_filters(url, allowed_filters)

if filters:
    filtered_query = people.filter(**filters)
else:
    filtered_query = people

if ('search' in request.GET) and request.GET['search'].strip():
    query_string = request.GET['search']
    query_search = get_query(query_string, ['person_first_name', 'person_last_name'])
    query_results = filtered_query.filter(query_search)
else:
    query_results = filtered_query

It does everything I need it to: if a URL parameter is in the allowed list, it takes that parameter and value, packs it into a dictionary, and shoves it into filter() to be unpacked by the interpreter.

This way whenever I want to add a new filter, I just add it in the allowed list and I don't have to touch anything else. I did it this way so I could use an alias like special_id=3 in the URL to target a relationship like person__special__special_id=3 without the URL getting cluttered like the Django admin side does.

Any suggestions for improving this?


texts: Date composition from day, month and year input

texts:
I need to concatenate 3 input fields into a string which is formatted as a date dd-mm-yyyy, using type="date" or new Date() will not work in my scenario because Firebase doesn't allow it for some reason. I came up with a rather ugly solution, but I'm not quite sure how to improve it. delete is bad for performance, but I think that it is needed because I need to completely remove the properties from the object once they've been used.

$scope.addWeek = function(week) {

  var startDate = '' + week.startDate.day + '-' + week.startDate.month + '-' + week.startDate.year,
      endDate = '' + week.endDate.day + '-' + week.endDate.month + '-' + week.endDate.year;

  week.startDate = startDate;
  week.endDate = endDate;

  delete week.startDate.day;
  delete week.startDate.month;
  delete week.startDate.year;
  delete week.endDate.day;
  delete week.endDate.month;
  delete week.endDate.year;
}

The week object looks like this:

week = {
  number: 32,
  startDate: {
    day: 01,
    month: 07,
    year: 2015
  },
  endDate: {
    day: 08,
    month: 09,
    year: 2016
  }
}

After we're done it needs to look like this:

week = {
  number: 32,
  startDate: 01-07-2015,
  endDate: 08-09-2016
}

Any suggestions on how to improve it?


texts: Please check if these two methods for inheritance and initialization are good or bad

texts:
I am new to JavaScript.  I know that many inheritance and initialization methods have been written and use some advance features like Object.create:

Simple JavaScript Inheritance

Why Prototypal Inheritance Matters

For practice, I wrote my own methods for inheritance and initialization.  I have no idea if my code is good or if it could be improved.  Could someone help me and give me some advice?

function Class() {};

Class.prototype.create = function () {
    var constr = this.constructor;
    var instance = new constr();

    for (var i = 0; i < arguments.length; i++) {
        var props = arguments[i];
        for (var name in props){
            instance[name] = props[name];
        }
    }

    return instance;
}

Class.prototype.extend = function () {
    var constr = this.constructor;
    var proto = this.constructor.prototype;

    function ProtoClas() {};

    var prototype = ProtoClas.prototype = (function (proto) {
        function F() {};
        F.prototype = proto;
        return new F();
    })(proto);

    ProtoClas.prototype.constructor = ProtoClas;

    for (var i = 0; i < arguments.length; i++) {
        var props = arguments[i];
        for (var name in props){
            prototype[name] = props[name];
        }
    }

    return new ProtoClas();
}

Class.extend = function () {
    var args  = Array.prototype.slice.call(arguments);
    return this.prototype.extend.apply(new this(), args);
}

Class.create = function () {
    var args  = Array.prototype.slice.call(arguments);
    return this.this.prototype.create.apply(this, args);
}

I then generate a new Class and an instance through this Class:

var Person = Class.extend({
    say: function () {
        console.log("Hello");
    },
    walk: function () {
        console.log("walk");
    }
});

var person = Person.create({
    name:'lee'
})

console.log(Person);
console.log(person);


texts:
I was playing with JS and wanted to create an isEven(n) function that returns true if it is even and false otherwise.

Here is what I did:

function isEven(n){
  return n % 2 ? false : true;
}

print(isEven(6));
//-> true
print(isEven(-3));
//-> false

My question is:

Is this good code? How is JS interpreting this code?

I'm assuming JS returns true if n % 2 equals to 1 and false if 0.

Is this a good solution or would you prefer writting something else like:

function isEven(n){
   return (n % 2 == 0) ? true : false;
}
print(isEven(6));
//-> true
print(isEven(-3));
//-> false


texts:
I have a form that consists of about 60 fields that all update when choosing a different customer from a drop down. I feel like my current way is not the best way as it takes about 30 seconds to update when changing customers.  Currently I have:

Private Sub ClientSelection_AfterUpdate()

On Error GoTo errhandler

Dim dbTemp As DAO.Database
Dim rsTemp As DAO.Recordset
Dim strSQL As String

DoCmd.Hourglass True

sYear = Me.YearSelection.Value
    Me.CustomerID = Me.CustomerSelection.Column(0)
    CustomerID = Mid(Me.CustomerID.Value, 2, 36)

Set dbTemp = CurrentDb()
Set rsTemp = dbTemp.OpenRecordset("SELECT Field1 FROM Table where CustomerID = '" & CustomerID & "' and MonthYear = #01/01/" & sYear & "#")
Set rsTemp2 = dbTemp.OpenRecordset("SELECT Field1 FROM Table where CustomerID = '" & CustomerID & "' and MonthYear = #02/01/" & sYear & "#")

Me.JanCharges.Value = rsTemp("Charges")
Me.FebCharges.Value = rsTemp2("Charges")

rsTemp.Close
rsTemp2.Close
Set rsTemp = Nothing
Set rsTemp2 = Nothing
Set dbTemp = Nothing

Exit_ClientSelection_AfterUpdate:
Exit Sub

errhandler:
 MsgBox "Error " & Err.Number & ": " & Err.Description & " in " & _
   VBE.ActiveCodePane.CodeModule, vbOKOnly, "Error"
    Resume Exit_ClientSelection_AfterUpdate

End Sub

Both of these commands basically happen 60 times (5 categories consisting of 12 fields(months)).  Then even further down I close all the recordsets and set them to Nothing.  All of this works just takes a little longer than I want.  What is a more efficient to accomplish this?


texts: PHP implementation of "depth-first search" on the graph data structure

texts:
As I am a totally self-taught 'person writing code', I decided to learn algorithms with one online course that taught them using Java for demonstrative purposes. The first topic I covered is the graph data structure and API.

I undertook to rewrite Java examples into PHP for training purposes. I would be really grateful if you could review this code and point to its biggest shortcoming.

It was not always possible to reproduce certain behaviours and data structure that are found in Java so I had to resort to some workarounds.

Here is the code with explanations:

/**
* Bag stores all vertices adjacent to a given vertex.
* It's here to imitate Java's 'Bag' data structure
*/
class Bag implements IteratorAggregate
{
    public $vs = array();

    public function getIterator()
    {
        return new ArrayIterator($this->vs);
    }
}

-

class Graph
{

    private $V;

    /* Adjacent vertices */
    private $adj = array();

    /**
    * @param int $V The total number of vertices in the graph
    */
    public function __construct($V)
    {
        $this->V = $V;
        for ($v = 0; $v < $V; $v++) {
            $this->adj[$v] = new Bag;
        }
    }

    /**
    * Throw all adjacent vertices of a given vertex into this vertex' Bag.
    * This will create 'edges' - connection between vertices.
    *
    * @param int $v Vertex to connect
    * @param int $w Vertex to connect
    */
    public function addEdge($v, $w)
    {
        $this->adj[$v]->vs[] = $w;
        $this->adj[$w]->vs[] = $v;
    }

    /**
    * @return Bag All ajacent vertices of a given vertex
    */
    public function returnBag($v)
    {
        return $this->adj[$v];
    }

    public function returnAllVertices()
    {
        return $this->adj;
    }

}

-

class DepthFirstPath
{
    private $marked = array();

    /* This array stores parent-link representation  of a tree rooted at $s (source) */
    private $edgeTo = array();

    private $s;

    /**
    * @param Graph $G An instance of the graph
    * @param int $s Source vertex to start the recursive traversal from
    */
    public function __construct(Graph $G, $s)
    {
        $allVertices = $G->returnAllVertices();

        /* Set all verices in the graph as unvisited/unmarked */
        foreach($allVertices as $key => $value) {
            $this->marked[$key] = false;
            foreach($value->vs as $v) {
                $this->marked[$v] = false;
            }
        }

        $this->s = $s;
        $this->dfs($G, $s);

    }

    /**
    * 'Depth-first search'
    *
    * A recursive function that will visit all adjacent vertices of each vertex
    * and mark each of them as 'visited'
    */
    private function dfs(Graph $G, $v)
    {
        $this->marked[$v] = true;
        $adjToV = $G->returnBag($v);
        foreach($adjToV as $w) {
            if ( ! $this->marked[$w] ) {
                $this->dfs($G, $w);
                $this->edgeTo[$w] = $v;
            }
        }
    }

    public function hasPathTo($v)
    {
        return $this->marked[$v];
    }

    /**
    * Find a path from the source to a given vertex
    */
    public function pathTo($v)
    {
        if ( ! $this->hasPathTo($v)) {
            return null;
        }

        $path = new \SplStack;
        for ($x = $v; $x != $this->s; $x = $this->edgeTo[$x]) {
            $path->push($x);
        }
        $path->push($this->s);
        return $path;
    }
}

This is how the client might use it (feel free to copy, paste and try it):

$graph = new Graph(10);
$graph->addEdge(1,2);
$graph->addEdge(2,3);
$graph->addEdge(3,4);
$graph->addEdge(1,6);
$graph->addEdge(8,9);

$path = new DepthFirstPath($graph, 1);
$path->pathTo(4);

What have I done wrong, what could I improve, what rules have I violated ?


texts: "Stack Exchange page visits" alike implementation

texts:
The objective is to increment the page visits by one. The user should not be able to do this by refreshing. The number of visits can be incremented only if the user's last visit was later than 10 minutes or none at all.  This should work regardless of multiple users behind the same IP or router.

Does this need any improving?

Stack Exchange page views works like this.

//Is data storage available?
if(typeof(Storage)!=="undefined")
  {
    var tenMinutes = 3600 * 10; //10 minutes
    var now = new Date();
    var visits = JSON.parse(localStorage.getItem('visits')); //Get visits array from local storage
    var currentVisit = {id:$scope.ad.id, datetime:now};
    var duplicate = false;

    //There is no older visits, user is new here
    if(!visits){
        visits = [currentVisit];
        addViewForID(currentVisit.id);
    }
    else{
        //Check for duplicate visit
        angular.forEach(visits, function(visit){
            if (visit.id == currentVisit.id) {

                duplicate = true;
                var visitTime = new Date(visit.datetime);
                var deltaTime = Math.abs(now.getTime() - visitTime.getTime());
                var deltaDays = Math.ceil(deltaTime / (1000 * 3600 * 24));

                if (deltaDays > 1 || (deltaDays == 1 && deltaTime > tenMinutes))
                    visit.datetime = now;
            }

        })

        //First time visiting this page
        if (!duplicate){
            visits.push(currentVisit);
            addViewForID(currentVisit.id);
        }

    }

    //Save visits array in local storage
    localStorage.setItem('visits', JSON.stringify(visits));
}

function addViewForID(id){
    FData.incrementVisitsForID(id);
}


texts: Data Structures C# Dictionary and user has a property that is a list

texts:
I am about to post a question to Stack Overflow about how to do a better job adding a number to the list inside the User class. But I feel if I refactored this I might solve my problem with coupling my data like this. So I am open to suggestions.

Ideone

public static void addOrUpdate(Dictionary<int, User> dic, int key, User user)
{
    //sets a new user data and just replaces it in the dictionary
    //var used = new User { ID = "id1", Name = "Harry" };
    var used = new User{ ID = "id3", Name = "Henry" ,AddressBook = new List<ContactNumber>(){new ContactNumber(3111),new ContactNumber(4444)}};

    if (dic.TryGetValue(key, out user))
    {
        // yay, value exists!
        dic[key] = used;

    }
    else
    {
        // darn, lets add the value
        dic.Add(key, used);
    }
}


texts: SQL: Search for a keyword in several columns of a table

texts:
I want to perform a search in several columns of a table. I use the following query:

select *
from Tabela t
inner join "TabelaPai" tp on tp."ID" = t."RefTabelaPai" and tp."RefProject" = 'projectid'
where not t."Deleted"
 and (t.Col1 ~ '.*__param1__.*' or t.Col2 ~ '.*__param1__.*' or t.Col3 ~ '.*__param1__.*'
   or t.Col4 ~ '.*__param1__.*' or t.Col5 ~ '.*__param1__.*' or t.Col6 ~ '.*__param1__.*'
   or t.Col7 ~ '.*__param1__.*' or t.Col8 ~ '.*__param1__.*' or t.Col9 ~ '.*__param1__.*');

This will search for the keyword __param1__ in any of the columns and it's working fine.

But I don't like the way the query looks like. Any suggestion on how to refactor the query so it can look 'prettier' (without those ~ '.*__param1__.*' repetitions, for example)?

Edit: A little of context about the query:

What leads to this usage is that I can parameterize the data in the table. For example, I have a column in a table where scripts are saved. My application allows the users to parametrize the script using something like __param1__. If the user wants to rename the parameter I'll have to search for the usage of the parameter in every column that is parameterizable, and this is the query that finds where the parameter is used.


texts: jQuery toggle class and content on click of link

texts:
The following code is working exactly as it is expected to work, the thing is that I'm sure that it can be written in a more efficient and less verbose way, any reviews?

JavaScript:

$(document).ready(function() {
    $('.hidden-content').hide();
    $(".hidden-content-reveal").click(function() {
        var $i = $(this).children();
        if ($i.is(".angle-down")){
            $i.removeClass("angle-down");
            $i.addClass("angle-up");
        } else {
            $i.removeClass("angle-up");
            $i.addClass("angle-down");
        }
        return false;
    });
});

HTML:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Nulla facilisi. Cras non egestas lectus. Duis malesuada eleifend neque, eget tincidunt elit convallis sed.Nulla facilisi. Cras non egestas lectus.


texts:
I'd appreciate any help just refining this working code. It has a bit of a weird context, but basically it's for a gallery style site that has hundreds of pages, but needs new navigation buttons. Unfortunately there's no way to add these buttons without adding them for over 300+ pages manually, or using a javascript like this.

Let's say we have a URL like the following (this coincides with the site's URL structure):

http:/test.com/10-funny-pictures/

The script links next button that links to http:/test.com/10-funny-pictures/2/, and hides the last button.

If the last page in the gallery is http:/test.com/10-funny-pictures/10/, then it sets the last button to link to http:/test.com/10-funny-pictures/9/. But on the last page of a gallery, there is a javascript inserted on that last page that holds the URL of a new gallery to send the user to when the click next, that URL is passed to the main JavaScript and then the next button links to that rather than http:/test.com/10-funny-pictures/11/ (which doesn't exist).

It's messy, but the JSFiddle is right here, any help making the code more efficient would be appreciated. I just kind of made it but I'm not good at doing things the best way when I code.

Last

Next

    #lastbutton {
display: inline-block;
width: 80px;
height: 20px;
background-color: #0a72c2;
color: #ffffff;
text-decoration: none;
text-align: center;
padding: 8px;
font-size: 16px;
}

#nextbutton {
display: inline-block;
width: 80px;
height: 20px;
background-color: #0a72c2;
color: #ffffff;
text-decoration: none;
text-align: center;
padding: 8px;
font-size: 16px;
}

#leftcontainer {
margin-top: 30px;
float: left;
text-align: center;
width: 50%;
}

#rightcontainer {
margin-top: 30px;
text-align: center;
float: right;
width: 50%;
}


texts: Search every char from a string for every char in another

texts:
I am adding a feature to a program that will let the user add new dictionaries as a file to the file folder to be used as a note taking repository. I just got the code finished for creating the file name from user input, however it feels as if there should be a smarter way to perform the task than what I have done.

The following is what I have come up with that does work but I don't know if I should be doing this in a shorter method with either a built in function or a smarter one-liner.

Can you explain any ways that you think this could be improved? I have searched for other solutions but they were not well explained enough that I could understand them very clearly.

EDIT: Added my imports to code. Note: the print statement at the bottom was just to test the result of the code and see it in console. It will be changed to return when I finish up the rest of the program.

from tkinter import *
import sys
import time
import tkinter.messagebox
import tkinter.simpledialog
import json

finalFilename =''
def new_lib_prompt(event=None):
    finalFilename =''
    name_of_new_library = tkinter.simpledialog.askstring('Create New Note Library', 'Alphanumeric lowercase and "_" only', initialvalue = "Name_Here")
    from string import ascii_letters,digits
    validFilenameChars = "-_.() %s%s" %(ascii_letters, digits)
    stringofnewname = str(name_of_new_library)
    stringofvalid = str(validFilenameChars)
    for i in stringofnewname:
        if i in stringofvalid:
            if i == ' ':
                new_i = '_'
                finalFilename += ''.join(new_i)
            else:
                lower_i = i.lower()
                finalFilename += ''.join(lower_i)
        else:
            pass
    print (finalFilename)

EDIT: 04/21/2017 2:30 PM

Thanks for all the great feedback everyone and thanks to holroy for his very useful and thought out response. If anyone is interested here is the solution I was looking for after taking advice from a few answers.

valid_filename = '' # will be using this in another function later
def new_lib_prompt(event=None):
    global valid_filename
    a_name = tkinter.simpledialog.askstring('Create New Note Library',
                                            'Alphanumeric lowercase and "_" only',
                                            initialvalue = "Name_Here")
    VALID_CHARS = '-_.() {}{}'.format(ascii_letters, digits)
    valid_filename = (''.join(c for c in a_name if c in VALID_CHARS)).replace(' ', '_').lower()


texts: qos method call using DateTime and Stopwatch

texts:
I need to limit method call to 80 times per second (for each connectionId).

My initial version:

private const int MAX_TRANSACTIONS_PER_PERIOD = 80;
private const int PERIOD_IN_MS = 1000;
private Queue<DateTime>[] times = new Queue<DateTime>[10]
{
    new Queue<DateTime>(100),
    new Queue<DateTime>(100),
    new Queue<DateTime>(100),
    new Queue<DateTime>(100),
    new Queue<DateTime>(100),
    new Queue<DateTime>(100),
    new Queue<DateTime>(100),
    new Queue<DateTime>(100),
    new Queue<DateTime>(100),
    new Queue<DateTime>(100)
};

private int ExecTransWithStats(int connection_id, string name, string parameters_string, byte[] bytes)
{
    DateTime nowTime = DateTime.Now;
    while (times[connection_id].Count > 0 && (nowTime - times[connection_id].Peek()).TotalMilliseconds >= PERIOD_IN_MS)
    {
        times[connection_id].Dequeue();
    }
    if (times[connection_id].Count >= MAX_TRANSACTIONS_PER_PERIOD)
    {
        Thread.Sleep(PERIOD_IN_MS - (int) (nowTime - times[connection_id].Dequeue()).TotalMilliseconds);
    }
    times[connection_id].Enqueue(DateTime.Now);

    return ExecTrans(connection_id, name, parameters_string, bytes);
}

I've decided to replace DateTime with Stopwatch just because I don't need to store entire Date.  I only need to store how many milliseconds elapsed:

private const int MAX_TRANSACTIONS_PER_PERIOD = 80;
private const int PERIOD_IN_MS = 1000;
private Queue<long>[] times = new Queue<long>[10]
{
    new Queue<long>(100),
    new Queue<long>(100),
    new Queue<long>(100),
    new Queue<long>(100),
    new Queue<long>(100),
    new Queue<long>(100),
    new Queue<long>(100),
    new Queue<long>(100),
    new Queue<long>(100),
    new Queue<long>(100)
};

private Stopwatch workingTime = Stopwatch.StartNew();

private int ExecTransWithStats(int connection_id, string name, string parameters_string, byte[] bytes)
{
    long nowTime = workingTime.ElapsedMilliseconds;
    while (times[connection_id].Count > 0 && (nowTime - times[connection_id].Peek()) >= PERIOD_IN_MS)
    {
        times[connection_id].Dequeue();
    }
    if (times[connection_id].Count >= MAX_TRANSACTIONS_PER_PERIOD)
    {
        Thread.Sleep(PERIOD_IN_MS - (int) (nowTime - times[connection_id].Dequeue()));
    }
    times[connection_id].Enqueue(workingTime.ElapsedMilliseconds);

    return ExecTrans(connection_id, name, parameters_string, bytes);
}

Am I correct that version with Stopwatch is better? It has much better precision, but I'm ok  with having precision of DateTime (10-15 ms). Do I pay for extra precision (which I don't actually need)?


texts: Simplifying a series of type checks and casts in a generic method

texts:
The if/else statements below are not good. How can I improve this method?

public T GetContentByNodeIdSync<T>(Guid nodeId)
{
    var data = m_CMSCatalog.GetContentByNodeId(nodeId);

    if (typeof(T) == typeof(WebFolder))
    {
        var model = (WebFolderDTO)data;
        return Mapper.Map<WebFolderDTO, T>(model);
    }
    else if (typeof(T) == typeof(ContentListItem))
    {
        return Mapper.Map<ContentListItemDTO, T>((ContentListItemDTO)data);
    }
    else if (typeof(T) == typeof(Image))
    {
        return Mapper.Map<ImageDTO, T>((ImageDTO)data);
    }
    else if (typeof(T) == typeof(File))
    {
        return Mapper.Map<FileDTO, T>((FileDTO)data);
    }
    else if (typeof(T) == typeof(Folder))
    {
        return Mapper.Map<FolderDTO, T>((FolderDTO)data);
    }
    else if (typeof(T) == typeof(WebRoot))
    {
        return Mapper.Map<WebRootDTO, T>((WebRootDTO)data);
    }
    else if (typeof(T) == typeof(Article))
    {
        var model = (ArticleDTO)data;
        return Mapper.Map<ArticleDTO, T>(model);
    }
    else if (typeof(T) == typeof(WebContent))
    {
        var model = (WebContentDTO)data;
        return Mapper.Map<WebContentDTO, T>(model);
    }
    return default(T);
}


texts:
This is a simple implementation of a parenthesis-matcher. Given an expression, I want to find out if it is balanced.For example, the expression '{{[[()]]}}' is balanced while '{]{{}}]]' is not. I will output a simple 'NO' is the expression is not balanced and 'YES' if it is.

The algorithm is to push every opening parenthesis into a stack and match it against every closing when when pop-ed.

#include <iostream>
#include <vector>
#include <set>
#include<stack>
#include <utility>
#include <string>

bool contains(std::set<char> & inset, char elem){
  return inset.find(elem) != inset.end();
}

bool charmatch(char a,char b){
  return ((a == '(' && b == ')') ||
          (a == '{' && b == '}') ||
          (a == '[' && b == ']'));
}

void process(std::string inputArg){
  std::vector<char> input(inputArg.begin(), inputArg.end());

  std::set<char> openParen;
  openParen.insert('(');openParen.insert('{');openParen.insert('[');

  std::set<char> closeParen;
  closeParen.insert(')');closeParen.insert('}');closeParen.insert(']');

  std::stack<char> exprStack;
  for (auto i : input){
    char inputChar = i;
    if (contains(openParen, inputChar))
      {
        exprStack.push(inputChar);
        continue;
      }

    else if (exprStack.empty() || !charmatch(exprStack.top(),inputChar)){
      std::cout << "NO" <<std::endl;
      return;
    }

    exprStack.pop();

  }
  if (exprStack.empty())  {std::cout << "YES" << std::endl; return;}
  else {std::cout << "NO" << std::endl; return;}
}

int main()
{
  std::vector<char> input;
  int num;std::string inputString;
  std::cin >> num;
  for (int i = 0; i < num; i++){
      std::cin >> inputString;
        process(inputString);
    }
  return 0;
}

I'm practicing Data Structures questions on HackerRank, any suggestions to improve code quality appreciated!


texts:
Sometimes, I need to map from a Domain entity to a ViewModel - to display information.

Other times, I need to map from a ViewModel to a Domain entity - for persistance of data.

Is this kosher or does this code smell?

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    MapObjects();
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

private void MapObjects()
{
    Mapper.CreateMap<UserModel, User>();

    Mapper.CreateMap<ProductBrandModel, ProductBrand>();
    Mapper.CreateMap<ProductBrand, ProductBrandModel>();

    Mapper.CreateMap<ProductCategoryModel, ProductCategory>();
    Mapper.CreateMap<ProductCategory, ProductCategoryModel>();
}