texts: Rounding a number up to the nearest multiple of a power of 2

texts:
I'm doing some programming challenges over at CodeEval and came across a pretty straight forward simple one:

  Given numbers x and n, where n is a power of 2, print out the smallest multiple of n which is greater than or equal to x. Do not use division or modulo operator.

So the input looks something like this: 13, 8 first number being x second number being n. My first instinct was to use a while loop and return the result of multiplying the number once the loop hits the correct result, so:

 8 * 0 = 0
 8 * 1 = 8
 8 * 2 = 16; break because it's greater then 13

My question is, is it considered bad form to use float("inf") instead of a set number to multiply up to?

import sys

def multiply(x, y):
    max_multiple_try = 0
    while max_multiple_try != float("inf"):
        res = x * max_multiple_try
        if res != x and res >= y:
            return res
        else:
            max_multiple_try += 1

if __name__ == '__main__':
    with open(sys.argv[1]) as data:
        for line in data.readlines():
            numbers = line.rstrip().split(",")
            print(multiply(int(numbers[1]), int(numbers[0])))


texts: Haskell/Yesod - Butchering use of MaybeT

texts:
The following is some code that is used to provide the frontend with certain parameters when rendering a form. The parameters are conditional based around what data is being changed, getNewSaleFormOptions provides a way of quering these options using a GET request and url params (ie /sales/new?dealership=11&vehicle=2), and another getEditSaleFormOptions when returning to edit, but through the entity id, ie /sales/1 (this will pull necessary data, dealership, vehicle, from Sale 1).

I've tried to use MaybeT here to simplify a lot of the calls that return m (Maybe a), though its possible i'm not using it in the most efficient way. There are lots of MaybeT and runMaybeT calls (though this might be okay), and a few spots where there is duplicated code... I'm just not sure of the best way to eliminate them.

{-# LANGUAGE GADTs            #-}
{-# LANGUAGE FlexibleContexts #-}

module Forms.SaleForm
  ( SaleFormOptions(..)
  , getNewSaleFormOptions
  , getEditSaleFormOptions
  ) where

import           Control.Monad (join)
import           Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT)
import qualified Data.Aeson as Aeson
import           Data.Aeson ((.=), ToJSON)
import qualified Data.Maybe as M
import           Data.Text (Text)
import           Database.Esqueleto (SqlPersistT, get)
import           Yesod.Core (MonadHandler(..), PathPiece(..))

data SaleFormOptions = SaleFormOptions
  { saleFormOptionsCampaigns :: Maybe MarketingCampaigns
  , saleFormOptionsDiscountElegible :: Bool
  }

instance ToJSON SaleFormOptions where
  toJSON SaleFormOptions{..} =
    Aeson.object [ "campaigns" .= saleFormOptionsCampaigns
                 , "discount_elegible" .= saleFormOptionsDiscountElegible
                 ]

getNewSaleFormOptions :: MonadHandler m => Key User -> SqlPersistT m SaleFormOptions
getNewSaleFormOptions userKey = NewTenancyFormFields <$> campaigns <*> discountElegible
 where
    campaigns =
      runMaybeT (MaybeT . fetchCampaigns userKey =<< lookupIdGetParamM "dealership")

    discountElegible =
      M.fromMaybe False <$> runMaybeT (MaybeT . fmap Just . isDiscountElegible =<< lookupIdGetParamM "vehicle")

getEditSaleFormOptions
  :: MonadHandler m
  => Key User
  -> Key Sale
  -> SqlPersistT m SaleFormOptions
getEditSaleFormOptions userKey saleKey = do
  sale <- get saleKey
  EditTenancyTenantFormFields <$> fmap join (mapM (fetchCampaigns userKey) (saleDealership <$> sale))
                              <*> (M.fromMaybe False <$> mapM isDiscountElegible (saleVehicle <$> sale))

fetchCampaigns :: MonadHandler m => Key User -> Key Dealership -> SqlPersistT m (Maybe MarketingCampaigns)
fetchCampaigns userKey dealershipKey = do
  enabled <- campaignsEnabled userKey dealershipKey
  if enabled then Just <$> getCampaigns dealershipKey
             else return Nothing

isDiscountElegible :: MonadHandler m => Key Vehicle -> SqlPersistT m Bool
isDiscountElegible vehicleKey = M.fromMaybe False <$> runMaybeT checkElegible
  where
    checkElegible = do
      vehicle <- MaybeT (get vehicleKey)
      vehicleHasDiscount <$> (MaybeT . get $ vehicleManufacturer vehicle)
                         <*> pure vehicle

lookupIdGetParamM
  :: (PathPiece (Key a), MonadHandler m)
  => Text
  -> MaybeT m (Key a)
lookupIdGetParamM = MaybeT . lookupIdGetParam

And this is the code for lookupIdGetParam:

lookupIdGetParam :: (PathPiece (Key a), MonadHandler m) => Text -> m (Maybe (Key a))
lookupIdGetParam name = do
  mraw <- lookupGetParam name
  case mraw of
    Nothing  -> return Nothing
    Just raw -> return (fromPathPiece raw)


texts:
I have demonstrated promise chaining where promise's p1,p2,p3 has to be resolved synchronously.

The code below is using angular.js 1, and here P3 is resolved then P2 and then P1.

<script type="text/javaScript">
            angular.module("myApp",[]);
            angular.module("myApp").controller("myCtrl",myCtrl);
            angular.module("myApp").factory("demoService",demoService);

            demoService.$inject = ["$q","$timeout"];
            myCtrl.$inject = ["$scope","demoService"];

            function myCtrl($scope,demoService){
                var vm = this;
                vm.init = init;

                vm.myList = [];

                function init(){
                    var p1 = demoService.get1000();
                    var p3 = demoService.get3000();
                    var p2 = demoService.get2000();

                    p3.then(function(obj){
                        vm.myList.push(obj.name);
                        console.log(obj.name);
                        return p2;
                    }).then(function(obj){
                        vm.myList.push(obj.name);
                        console.log(obj.name);
                        return p1;
                    }).then(function(obj){
                        vm.myList.push(obj.name);
                        console.log(obj.name);
                    });
                } // end of init
            } // end of myCtrl

            function demoService($q,$timeout){
                var obj = {};
                obj.get1000 = get1000;
                obj.get2000 = get2000;
                obj.get3000 = get3000;

                return obj;

                function get1000(){
                    var deferred = $q.defer();
                    var INTERVAL = 1000;
                    $timeout(function() {
                        deferred.resolve({ "name" : INTERVAL });
                    }, INTERVAL);
                    return deferred.promise;
                }

                function get2000(){
                    var deferred = $q.defer();
                    var INTERVAL = 2000;
                    $timeout(function() {
                        deferred.resolve({ "name" : INTERVAL });
                    }, INTERVAL);
                    return deferred.promise;
                }

                function get3000(){
                    var deferred = $q.defer();
                    var INTERVAL = 3000;
                    $timeout(function() {
                        deferred.resolve({ "name" : INTERVAL });
                    }, INTERVAL);
                    return deferred.promise;
                }

            } // end of demoService
</script>

So, my question is, Is there any better way of doing the above operation ? Also please review my code.


texts: Codeigniter - in the view or in the controller?

texts:
Is this correct? Or am I overloading the responsibilities of the view?

            Estado
                Prioridad
                Responsable
                Categoría
                Solicitud
                Creado
                Cerrado

            <?php
                 $class = '';
                 $label = '';
                 foreach ($solicitud as $key => $value) {
                     if( $value['priority'] > 0 && $value['priority'] < 4 ) $class = 'badge-important';
                     if( $value['priority'] > 4 && $value['priority'] < 7 ) $class = 'badge-info';
                     if( $value['priority'] > 7 ) $class = 'badge-warning';

                     if( $value['id'] == 1 ) $label = 'label-info';
                     if( $value['id'] == 2 ) $label = 'label-success';
                     if( $value['id'] == 3 ) $label = 'label-danger';

                    echo '
';
                    echo '  '.ucfirst($value['status']).'	';
                    echo '   '.$value['priority'].'	';
                    echo '   '.$value['sname'].' '.$value['last_name'].'	';
                    echo '   '.$value['name'].'	';
                    echo '   '.$value['message'].'	';
                    echo '   '.$value['created'].'	';
                    echo ''.(( $value['closed'] )  ? $value['closed'] : 'pendiente').'	';
                    echo '
';

                 } ?>


texts: Improving constexpr invoke function C++17, alternative to std::invoke

texts:
I've learned that in C++17, std::invoke isn't constexpr. To make a constexpr version, I could copy the implementation provided here: https://en.cppreference.com/w/cpp/utility/functional/invoke , OR I can complicate things by making my own version that relies on SFINAE, which may potentially be slow or have errors (which hopefully you'll help me fix).
Below is my version:
template<std::size_t N> struct theCharArray{
  unsigned char theChar[N];
};

template<class T> struct hasType;

template<class T, class U, class... Args> auto overloadInvoke(T f, U t1, Args&&... args)
-> theCharArray<(sizeof( hasType<decltype((static_cast<U&&>(t1).*f )(static_cast<Args&&>(args)...))>* ),1 )>;

template<class T, class U, class... Args> auto overloadInvoke(T f, U t1, Args&&... args)
-> theCharArray<(sizeof( hasType<decltype((t1.get().*f)(static_cast<Args&&>(args)...))>* ),2 )>;

template<class T, class U, class... Args> auto overloadInvoke(T f, U t1, Args&&... args)
-> theCharArray<(sizeof( hasType<decltype(((*static_cast<U&&>(t1)).*f)(static_cast<Args&&>(args)...))>* ),3 )>;

template<class T, class U> auto overloadInvoke(T f, U t1)
-> theCharArray<(sizeof( hasType<decltype(static_cast<U&&>(t1).*f)>* ),4 )>;

template<class T, class U> auto overloadInvoke(T f, U t1)
-> theCharArray<(sizeof( hasType<decltype(t1.get().*f)>* ),5 )>;

template<class T, class U> auto overloadInvoke(T f, U t1)
-> theCharArray<(sizeof( hasType<decltype((*static_cast<U&&>(t1)).*f)>* ),6 )>;

template <class T, class Type, class T1, class... Args>
constexpr decltype(auto) invoke(Type T::* f, T1&& t1, Args&&... args){
    constexpr auto chooseFxn = sizeof(overloadInvoke(f, t1, static_cast<Args&&>(args)...));
    if constexpr(chooseFxn == 1){
        return (static_cast<T1&&>(t1).*f )(static_cast<Args&&>(args)...);
    } else if constexpr(chooseFxn == 2){
        return (t1.get().*f)(static_cast<Args&&>(args)...);
    } else if constexpr(chooseFxn == 3){
        return ((*static_cast<T1&&>(t1)).*f)(static_cast<Args&&>(args)...);
    } else if constexpr(chooseFxn == 4){
        return static_cast<T1&&>(t1).*f;
    } else if constexpr(chooseFxn == 5){
        return t1.get().*f;
    } else {
        return (*static_cast<T1&&>(t1)).*f;
    }
}

template< class F, class... Args>
constexpr decltype(auto) invoke(F&& f, Args&&... args){
    return static_cast<F&&>(f)(static_cast<Args&&>(args)...);
}

I test the code here. How the SFINAE works is it checks all possible ways to invoke the arguments, and returns a struct whose size is determined by which invocation is well-formed, which I use to take the size of.
How I tested the code:
struct Foo {
    Foo(int num) : num_(num) {}
    void print_add(int i) const { std::cout << num_+i << '\n'; }
    int num_;
};

void print_num(int i)
{
    std::cout << i << '\n';
}

struct PrintNum {
    void operator()(int i) const
    {
        std::cout << i << '\n';
    }
};

int main()
{
    invoke(print_num, -9);
    invoke([]() { print_num(42); });
    const Foo foo(314159);
    invoke(&Foo::print_add, foo, 1);
    std::cout << "num_: " << invoke(&Foo::num_, foo) << '\n';
    invoke(PrintNum(), 18);
}


texts: Haskell - saving content of HTTP request in selected file

texts:
As a Haskell beginner I'm currently playing around the IO monad and prepared simple program which gets from the user two information:

URL (http)
Output file path

Then it performs GET request to the provided URL and stores the result in the selected file. HTTP status code of the response is displayed on the standard output
Could you please suggest how such code could be improved? Maybe some places when point-free style can be used? I also feel that the part with confirmation of file overwriting is not very elegant.
import System.IO
import Network.HTTP
import System.Directory

getUrl :: IO String
getUrl = putStr "URL: " >> hFlush stdout >> getLine

confirmOverideOrGetNewPath :: String -> IO String
confirmOverideOrGetNewPath filepath = do
    putStr $ "File " ++ filepath ++ " exists. Override? [y/n] "
    hFlush stdout
    decision <- getLine
    let shouldOverride = (if decision == "y" then True else False)
    case shouldOverride of True -> return filepath
                           False -> putStrLn "\nProvide other path" >> getOutputFilepath

getOutputFilepath :: IO String
getOutputFilepath = do
    putStr "Output file path: "
    hFlush stdout
    filepath <- getLine
    file_exists <- doesFileExist filepath
    case file_exists of True -> confirmOverideOrGetNewPath filepath
                        False -> return filepath

performGetRequest :: String -> IO (String, Int)
performGetRequest url = do
        rsp <- Network.HTTP.simpleHTTP (getRequest url)
        content <- getResponseBody rsp
        responseCode <- getResponseCode rsp
        return (content, responseCodeToInt responseCode)
    where
        responseCodeToInt :: ResponseCode -> Int
        responseCodeToInt code = let (x,y,z) = code in read (mconcat $ show <$> [x,y,z]) :: Int

saveContentToFile :: FilePath -> String -> IO ()
saveContentToFile = writeFile

printHttpStatusCode :: Int -> IO ()
printHttpStatusCode statusCode = putStrLn ("\nStatus code: " ++ show statusCode)
                                 >> putStrLn "Content saved into file"

main :: IO ()
main = do
    url <- getUrl
    filepath <- getOutputFilepath
    (content, statusCode) <- performGetRequest url
    saveContentToFile filepath content
    printHttpStatusCode statusCode


texts:
I have the following code block which I'd like to refactor into a method, I just don't see a good way to get the following code into a method which doesn't have multiple responsibilities.  Here is the code block:

int maxResults = pageable.getMaxResults(userPrefs);
int firstResult;

if (pageData.isLastPage()) {
    int count = getCountFromDb(); //'Heavy' cost associated with this, so we only
                                  //determine the count if they are on the last page...
    firstResult = getFirstResult(count, maxResults);
    if (count > 0) {
        boolean isFinalPageFull = (count % maxResults) == 0;
        int pageNum = count / maxResults;
        pageData.setPageNumber((isFinalPage) ? pageNum - 1 : pageNum;
    }
} else {
    firstResult = maxResults * pageNumber;
}

I'd like to move this out into a method or two, but I need to  only do this count one time.  This limitation is clouding my vision, as I can't think of any function which follows the Single Responsibility Principle.  Anything I can do to achieve my goal?


texts: filtering element of one List from another in Scala with different tuple structure

texts:
I am trying to understand the best way to write this. This is part of my organization work so can't disclose it fully here like why such requirement. So Apologies for that.
I have ListA and ListB.
val ListA: List[((String, String), Int)] = List(
  (("A", "B"), 1),
  (("C", "D"), 2),
  (("E", "F"), 5),
  (("E", "F"), 4),
  (("E", "F"), 3)
)
val ListB: List[(String, String)] = List(
  ("A", "B"),
  ("E", "F")
)

We need to search id in ListA that contain ListB element. For example tuple ("A", "B") is present in ListA with (("A", "B"), 1), . so output would be List(1). This process would repeat again once we fetch first match. if no match is found then List(0) would be output. Also both lists are sorted on priority. ListB drives the main priority and after that in case of repeating values the List A does it. And lists are already ordered.
I wrote this.
val result = ((for {
  a <- ListB
  m <- ListA.filter(_._1 == a).map(_._2)
} yield m):::List(0)).slice(0,1)

slice is used because we need List with first match. as ListB is already sorted on priority. Also We are going to repeat this process again by removing already matched id from ListA. But for now please ignore like how we remove these elements and re-iterate.
So new iteration would be on
val ListA: List[((String, String), Int)] = List(
    //  (("A", "B"), 1), This will not be part of second iteration as we already matched it in first iteration.
      (("C", "D"), 2),
      (("E", "F"), 5),
      (("E", "F"), 4),
      (("E", "F"), 3)
    )
    val ListB: List[(String, String)] = List(
      ("A", "B"),
      ("E", "F")
    )

Output of

iteration 1 is List(1)
iteration 2 is List(5)
iteration 3 is List(4)
iteration 4 is List(3)
iteration 5 is List(0)

I would just like to understand that
"Is it right way to code where we search one list element in another".
"Do we have some scala library that can be used here like ListA.filter(ListB.contains(_._1)) --> this needs us to write full filter case method so it wont work like this"


texts: Merging Two Sorted Lists in Python In Linear Time

texts:
I am trying to implement a merge of two sorted lists of integers in Python using only the basic list abstract data type operations. That is, I do not want to use sorted() which comes with Python.

Could someone tell me if this code is alright? Also, am I correct to understand that it is linear to the core? That is, it uses no Python operation that is non-linear in time?

 def mergeSortedLists(list1, list2):
     list3 = []
     while list1 and list2:
         if list1[len(list1) - 1] > list2[len(list2) - 1]:
             list3.append(list1.pop())
         else:
             list3.append(list2.pop())
     return list3 + list1 + list2


texts: Managing multiple sockets in a network client in Python

texts:
I'm writing a small FIX client in Python (2.7, constraint I cannot waive for now, unfortunately).

There will be multiple sockets, connecting to different ports, so I thought I'd create a SocketManager to keep a list of sockets and have select.epoll register() them all.

Each socket is wrapped by a ThinSocketWrapper class, which basically adds a lock, two string buffers (to receive and send) and a Queue (to receive messages):

class ThinSocketWrapper(socket):

    def __init__(self, *args, **kwargs):
        self.BUFLEN = 4096
        self.lock = RLock()

        self.recvBuffer = ''
        self.sendBuffer = ''

        self.recvQueue = kwargs.pop('recvQueue')
        super(ThinSocketWrapper, self).__init__(*args, **kwargs)

Questions:

The queue is created by the caller and passed in as an argument. This seems a bit messy to me. Would it be better to create the queue from within this class and make it accessible (e.g. through a getRecvQueue method)?
The same way I could create a sendQueue in ThinSocketWrapper and make it accessible through getSendQueue(). The purpose of this queue is that it will be swept by a background thread looking for messages to send. Where should this thread live? Within the ThinSocketWrapper class? Are there better ways of sweeping a queue? Like a select.epoll for queues?

The SocketManager is basically a thread, whose main loop looks like this:

class SocketManager(Thread):

    def run(self):
        while True:
            try:
                events = self.epoll.poll(TIMEOUT)
            except IOError as e:
                if e.errno == errno.EINTR:
                    continue

            for socket, event in events:
                try:
                    if event & (select.EPOLLIN | select.EPOLLPRI):
                        self.readEvent(socket)
                    elif event & select.EPOLLOUT:
                        self.writeEvent(socket)
                    elif event & (select.EPOLLHUP | select.EPOLLERR):
                        self.unregister(socket)
                except:
                    socket.close()
                    self.unregister(socket)

readEvent is defined as follows:

    def readEvent(self, socket):
        try:
            while True:
                data = socket.recv(socket.BUFLEN)
                if not data:
                    raise RuntimeError('Socket closed (read)')
                socket.recvBuffer += data
        except socket.error as e:
            if e.errno != errno.EAGAIN:
                raise
            socket.recvQueue.append(socket.recvBuffer)
            socket.recvBuffer = ''

At the end, when we're done receiving, we basically convert whatever we received in pseudo-messages, that is we copy everything in recvBuffer to recvQueue. I say "pseudo" because it might well be that the endpoint sends us multiple messages back to back, which would be impossible to split unless we look at the content: in that situation, we would end up with multiple messages in the same item of the queue.

This tells me that packing what has been received into messages is not this class' responsibility (in fact it should be a layer higher, from the point of view of the networking stack). What would be a nicer alternative?


texts: ARC 067 - read ints and find the best choices

texts:
I just started learning Rust, and this is my solution to a problem from Atcoder's Regular Contest #067, D - Walk and Teleport.

The problem can be summarized as follows:

There are N towns in a line, and you are about to visit all of them.
Town i is located at the point with coordinate xi.
You can travel either by walking or by teleporting. (You can combine them)

Walking costs you a * |Δx|, where a is a constant given and Δx is the distance you are about to travel.
Teleporing to any location costs you b, regardless of the distance you travel.

Given a, b and a sorted list of coordinates (xi), find the minimum cost to travel all towns.

Input is given in the form of

N a b
x1 x2 ... xN

where N is the number of cities and a, b, xi is what described above. Again, xi is sorted. All a, b, xi are integers in the range of [1, 109].

My speculation is that you can just travel from left to right, and choose the cheaper way to travel to the next town (a*(xj+1-xj) versus b).

This is my code.

use std::io;
use std::cmp::min;

fn main (){
    let input_one = read_ints();
    let a = input_one[1]; let b = input_one[2];
    let xs = read_ints();
    println!("{}", solve(&a,&b,&xs));
}

fn distances(xs:&[u64]) -> Vec<u64>{
    // Find the distances between adjacent towns
    xs.iter().zip(xs.iter().skip(1)).map(|(a,b)| b-a).collect()
}

fn solve(a:&u64, b:&u64, xs:&[u64]) -> u64 {
    let dists = distances(xs);
    dists.iter().fold(0, |acc,dist| {
        acc + min(a*dist, *b)
    })
}
fn read_ints() -> Vec<u64> {
    get_line().trim().split_whitespace().map(|n| n.parse().unwrap()).collect()
}

fn get_line() -> String {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).ok();
    buf
}

As I'm new to Rust, my main concern is the idiomaticness of the code. I've been writing Haskell and Python and there are many "it works but I'm not sure if I'm doing it right" moments. (Like, &[u64]'s were &Vec<u64> just until I was about to post this question.)

Any comments, including styles, naming, "loop is preferred", or anything are very much appreciated. Thank you.


texts: Fetching weather data from the OpenWeatherMap API

texts:
I am trying to fetch weather data from the OpenWeatherMap API. The responded JSON will be deserialized into a object which has the same structure of the JSON, then we need to transform this object into another class to meet our needs.

Following is the class which the JSON returned by OpenWeatherMap will be deserialized:

public class OpenWeatherMapResponse implements Serializable {

    private static final long serialVersionUID = 8841521123253407726L;

    private City             city;
    private int              cod;
    private Item[]           list;

    // lots of accessors

    public class static Item {
        // members of inner class Item
    }

    public class static Weather {
        // members of inner class Weather
    }
}

The following is a snippet of the second class. This class has a constructor which takes a OpenWeatherMapResponse and use the value in the response to construct the object will actually be used by my system:

public class CityWeather implements Serializable {

    private static final long serialVersionUID = -4883661697465418806L;

    private static final String ISO8601_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private double            temp;
    private double            minTemp;
    private double            maxTemp;
    private long              weatherId;
    private String            weatherName;
    private String            weatherDesc;

    public CityWeather() {}

    public CityWeather(OpenWeatherMapResponse openWeatherResponse) {

        Item[] list = openWeatherResponse.getList();
        Weather weather = findWeather(list);  // Get the first element of the Weather list

        // OpenWeatherMap doesn't provide API for fetching a specific day's forecast, so we have to build a day's weather data by assembling ourselves.
        Date tomorrow = getDateOfTomorrow();
        double tempMax = 0.0, tempMin = 99.0;
        List<Double> temps = new ArrayList<Double>();
        for (Item item : list) {
            Date dt = null;
            if((dt = parseDtTxt(item.getDt_txt())) == null) {
                continue;
            }

            // We only use weather data in recent 24 hours.
            if (dt.after(tomorrow)) {
                break;
            }

            Main main = item.getMain();
            temps.add(main.getTemp());
            tempMax = Math.max(tempMax, main.getTemp_max());
            tempMin = Math.min(tempMin, main.getTemp_min());
        }

        this.weatherId = weather.getId();
        this.weatherName = WeatherType.fromId((int) weather.getId()).name();
        this.weatherDesc = weather.getDescription();
        this.temp = calculateMean(temps);
        this.maxTemp = tempMax;
        this.minTemp = tempMin;
    }

    // lots of accessors

    // Parse the datetime string
    private Date parseDtTxt(String dtTxt) {
        try {
            return new SimpleDateFormat(ISO8601_FORMAT).parse(dtTxt);
        } catch (ParseException ex) {
            return null;
        }
    }

    private Date getDateOfTomorrow() {
        Calendar temp = Calendar.getInstance();
        temp.add(Calendar.DATE, 1);
        return temp.getTime();
    }

    private Weather findWeather(Item[] list) {
        for (Item item : list) {
            if (item.getWeather() !=null && item.getWeather().length > 0) {
                return item.getWeather()[0];
            }
        }
        return null;
    }

    private double calculateMean(List<Double> numbers) {
        if (isEmpty(numbers)) return 0;

        double sum = 0;
        for (double d : numbers) {
            sum += d;
        }
        return sum/numbers.size();
    }
}

As you can see, although this CityWeather looks like a data object, there is quite a little logic in this class to initialize its attributes.

Is this a good practice? If not, how should I modify my code?


texts: Generating time series for generator ON or OFF

texts:
Want to create time series for the nuclear power plant performance using the equation for Time to fail and time to repair for 8736 hours in the year so that I have the time series in hours when the generator is operating in when is not. The starting condition is that the generator is operating on the first hour.

For sure there is a more elegant solution for simulating this I'm just not able to find it. Any comment or help will be appreciated. The code is working but I think there is a better solution

TTF<-2940 # MEDIUM TIME TO FAIL(hours)
MTTR<-60 # MEDIUM TIME TO REPAIR (hours)
TTF<--MTTF*log(runif(100))# equation for Time to fail
TTR<--MTTR*log(runif(100))# equation for Time to repair
mix<-rep(0,length(TTF)+length(TTR))
sw<-rep(0,length(TTF)+length(TTR))
for(i in 1:length(TTF)){
mix[2*i-1]<-TTF[i]
sw[2*i-1]<-1
mix[2*i]<-TTR[i]
}
cmix<-cumsum(mix)
ccmix<-cbind(cmix[1:which(cmix>8736)],sw[1:which(cmix>8736)])
ccmix[dim(ccmix)[1],1]<-8736

G1<-round(ccmix)
# transform binary values
G1[,2][G1[,2] == 1] <- 400 # 400 MW is the capacity of power plant

G1 <- cbind(G1, c(G1[1,1], diff(G1[,1])))
a1 <- rep(G1[,2], G1[,3]) ## GENERATING 8736 Values

So the desired output are 8736 values of 400 when is ON and 0 when is OFF. Finally I need to simulate 100000 years of generation.


texts:
I'm relatively new to NodeJS and Express, and I've recently run into the pyramid of Doom while doing stuff that requires multiple steps.

I've found that promises are very promising indeed. But I definitely need opinions on various aspects of my approach to routes as a whole.

Here's the full code:

I'm not very sure about this constructor whose only responsibility is basically to hold the promised steps and pipe the same input regardless of the results.

function SignupDoctorPostRequest(data) {
    this.validatePlanId = function() {
        return SubscriptionService.hasValidPlan(data.plan);
    };

    this.createUser = function () {
        return UserService.save(data);
    };

    this.subscribeUser = function () {
        return SubscriptionService.create(data);
    };
}

My intent is revealed when we look at the route, where we see the data is only the body of the request.

router.post('/', function (rq, response) {
    var validation = SignupDoctorPostSchema.validate(rq.body); // This is a Joi Schema validation.

    if(validation.error) {
        response.
          status(422).
          json({
            status: 'fail',
            data: joiful.parseValidationError(validation.error) // this is only method I use to parse joi validations into a more consistent object.
          });
        return;
    }

    var request = new SignupDoctorPostRequest(validation.value);

    request.validatePlanId()
    .then(request.createUser)
    .then(request.subscribeUser)
    .then(
        function Success (authenticatedUser) {
          response.status(201).json({});
        }
    )
    .catch(
        function Fail (fail) {
          var statusCode = fail.type === 'Validation' ? 422 : 500;
          var responseStatus = fail.type === 'Validation' ? 'fail' : 'error';
          var responseData = fail.type === 'Validation' ? fail.details : fail.message;

          response.
            status(statusCode).
            json({
              status: responseStatus,
              data: responseData
            });
        }
    );
});

Lastly, I need feedback on handling my responses because I'm responding eagerly if validation fail and then again if the the process fails, I think this is sort of smelly.


texts:
I want to group the elements in an arbitrary long list into pairs and implemented the following so far:

(defun group-pairwise (numbers)
  "Returns a list with the elements of NUMBERS grouped in pairs."
  (cond ((null numbers) nil)
        ((null (rest numbers)) nil)
        (t (append (list (list (first numbers) (second numbers)))
                   (group-pairwise (rest numbers))))))

It works, i.e.

> (group-pairwise '(3 6 0))
((3 6) (6 0))

but I found (append (list (list (first numbers) (second numbers) a bit cumbersome. Is there any way to express it more elegant?

Furthermore, I want in my later code not only to return the list of pairs but to perform an action on each pair. To keep the recursion pattern unchanged I was thinking about using progn instead of append , e.g.

(defun generate-graph-of-digits%%% (numbers &optional (graph *pe79-graph*))
  "Returns a graph structure of NUMBERS."
  (cond ((null numbers) nil)
        ((null (rest numbers)) nil)
        (t (progn
             (add-edge-between-vertexes graph (first numbers) (second numbers))
             (generate-graph-of-digits%%% (rest numbers))))))

add-edge-between-vertexes being defined in the cl-graph package.

I am unsure about the usage of progn. Is it recommended to use it here?


texts:
This Python script extracts data from txt files containing raw numerical data, notably the increase average, the relative evolution and the standard deviation of the values, all of these values require a period on which they are calculated, this period is set via the command line.

#! /usr/bin/env python3

import statistics
import sys

if len(sys.argv) != 2:
    print("""SYNOPSIS
    ./%s period

DESCRIPTION
    period the number of days defining a period""" % (sys.argv[0]))
    exit(1)
increases = []
period = int(sys.argv[1])
values = []

def check_length(array):
    if len(array) > period:
        array.pop(0)

def mean(data):
    """Return the arithmetic mean of data."""
    return round(sum(data) / len(data), 2)

def calculate_g():
    increase = 0
    try:
        increase = (values[-1] * 10000 - values[-2] * 10000) / 10000
    except IndexError:
        pass
    if increase > 0:
        increases.append(increase)
    else:
        increases.append(0)
    if len(values) < period + 1:
        print("g=nan ", end="")
    else:
        increases_average = mean(increases[1:])
        print("g=%.2f " %  (increases_average), end="")

def calculate_r():
    if len(values) < period + 1:
        print("r=nan% ", end="")
        return "nan"
    else:
        evolution = round((values[period] - values[0]) * 100 / values[0])
        print("r=%.0f%% " %  (evolution), end="")
        return (1, -1)[evolution < 0]

def _ss(data):
    """Return sum of square deviations of sequence data."""
    average = mean(data)
    ss = sum((x-average)**2 for x in data)
    return ss

def stddev():
    """Calculates the population standard deviation by default."""
    n = len(values)
    if n < period:
        print("s=nan", end="")
    else:
        ss = _ss(values[-(period):])
        print("s=%.2f" % (round((ss / period) ** 0.5, 2)), end="")

def main():
    line = input()
    prev_sign = 0
    say = ""
    switch = 0
    while line != "STOP":
        values.append(float(line))
        calculate_g()
        sign = calculate_r()
        stddev()
        if sign != "nan":
            if sign == prev_sign * -1:
                say = " a switch occurs"
                switch += 1
            else:
                say = ""
            prev_sign = sign
        print("%s" % (say))
        check_length(values)
        check_length(increases)
        line = input()
    print("STOP\nGlobal tendency switched %i times" % (switch))

if __name__ == "__main__":
    main()

and here is sample data:

27.7
31.0
32.7
34.7
35.9
37.4
38.2
39.5
40.3
42.2
41.3
40.4
39.8
38.7
36.5
35.7
33.4
29.8
27.5
25.2
24.7
23.1
22.8
22.7
23.6
24.3
24.5
26.7
27.0
27.4
29.8
29.4
31.5
29.6
29.8
28.9
28.7
27.2
25.7
26.0
25.2
21.6
20.3
21.1
20.4
19.8
19.1
19.6
21.2
21.0
21.4
24.0
25.5
25.5
26.4
29.4
32.1
31.4
32.3
35.2
38.3
36.6
38.4
39.9
40.5
39.4
39.0
40.5
42.1
38.7
37.5
38.1
36.5
35.4
STOP

I'm pretty sure my code isn't that clean since i'm pretty new to Python and I would like to know good practices.


texts: Brute Force N Body Implementation in C++

texts:
I have wrote the following code in C++ for the n-body problem. This code is sequential as later on I am planning to parallelize it using OpenMP. I want to know whether I have wrote the correct implementation, if there are some errors or bugs, or if this is an invalid approach.

#include <iostream>
#include <ctime>
#include <math.h>
using namespace std;
#define N 100
#define G 6.673e-11
#define TIMESTAMP 1e11
struct Particle{
    double rx, ry;//position components
    double vx, vy;//velocity components
    double fx, fy;//force components
    double mass;//mass of the particle

};
Particle Update(Particle p, double timestamp)
{
    p.vx += timestamp*p.fx / p.mass;
    p.vy += timestamp*p.fy / p.mass;
    p.rx += timestamp*p.vx;
    p.ry += timestamp*p.vy;
    return p;
}
void PrintParticle(Particle p)
{
    printf("rx == %f ry == %f vx == %f vy == %f mass == %f\n", p.rx,p.ry,p.vx,p.vy,p.mass);
}
//Reset the forces on particle
Particle ResetForce(Particle p)
{
    p.fx = 0.0;
    p.fy = 0.0;
    return p;
}
//Add force to particle a by particle b
Particle AddForce(Particle a,Particle b)
{
    double EPS = 3E4;      // softening parameter (just to avoid infinities)
    double dx = b.rx - a.rx;
    double dy = b.ry - a.ry;
    double dist = sqrt(dx*dx + dy*dy);
    double F = (G * a.mass * b.mass) / (dist*dist + EPS*EPS);
    a.fx += F * dx / dist;
    a.fy += F * dy / dist;
    return a;

}

int main()
{
    Particle particles[N];
    srand(time(NULL));
    //randomly generating N Particles
    for (int i = 0; i < N; i++){
        double rx = 1e18*exp(-1.8)*(.5 - rand());
        particles[i].rx = rx;
        double ry = 1e18*exp(-1.8)*(.5 - rand());
        particles[i].ry = ry;
        double vx = 1e18*exp(-1.8)*(.5 - rand());
        particles[i].vx = vx;
        double vy = 1e18*exp(-1.8)*(.5 - rand());
        particles[i].vy = vy;
        double mass = 1.98892e30*rand()*10 + 1e20;
        particles[i].mass = mass;

    }

    int numberofiterations = 10;
    int count = 0;
    while (count < numberofiterations){
        for (int i = 0; i < N; i++)
        {
            particles[i] = ResetForce(particles[i]);
            for (int j = 0; j < N; j++)
            {
                if (i != j)
                {
                    particles[i] = AddForce(particles[i], particles[j]);
                }

            }
        }
        //loop again to update the time stamp here
        for (int i = 0; i < N; i++)
        {
            particles[i] = Update(particles[i], TIMESTAMP);
        }
        for (int i = 0; i < N; i++)
        {
            PrintParticle(particles[i]);
        }
        count++;
    }

    return 0;
}


texts:
Here is the code I invoke as Lua script in Redis. I use Redis sorted set to store game scores. This function is used to get some kind of overview of leaderboard. It returns id, score and rank of:

first 3 results
2 above player
player
2 below player
worst 3

It works as I wanted but I don't write much Lua code so review from expert would be nice. Parameters passed to script:

keys[1] = lb_id used as redis key
keys[2] = member (player id)
argv[1] = order (true -> desc)

And the script itself:

local myRank = 0
if (ARGV[1])
then
    myRank = redis.call('ZREVRANK', KEYS[1], KEYS[2])
else
    myRank = redis.call('ZRANK', KEYS[1], KEYS[2])
end
-- get total number of scores in lb
local total = redis.call('ZCARD', KEYS[1])
-- prepare array for response
local result = {}
--get top 3 playes
local head = {}
if (ARGV[1])
then
    head = redis.call('ZREVRANGE',KEYS[1], 0, 2, 'WITHSCORES')
else
    head = redis.call('ZRANGE',KEYS[1], 0, 2, 'WITHSCORES')
end

-- redis returns rank inside of range as index of array (0 based)
-- we need to inject proper rank into response so backend could use it
-- as it's return as list of strings (id, score, id, score...)
-- just add rank every 2 lines

for k,v in pairs(head) do
    if (k%2 == 0)
    then
        result[#result + 1] = v
        result[#result + 1] = k/2
    else
        result[#result + 1] = v
    end
end
--get players around me (ranks -/+ 2) including player
-- -1 is because we get 2 players above and rank in response is 0 indexed
local s = -1
local myLocal = {}
if (ARGV[1])
then
    myLocal = redis.call('ZREVRANGE', KEYS[1], myRank - 2, myRank + 2, 'WITHSCORES')
else
    myLocal = redis.call('ZRANGE', KEYS[1], myRank - 2, myRank + 2, 'WITHSCORES')
end
for k,v in pairs(myLocal) do
    if (k%2 == 0)
    then
        result[#result + 1] = v
        result[#result + 1] = myRank + s
        s = s + 1
    else
        result[#result + 1] = v
    end
end
-- get last 3 players
-- do this if player is not one of last ones
if (myRank < total -3)
then
    -- -2 is because we get 3 players above and rank in response is 0 indexed
    s = -2
    local tail = {}
    if (ARGV[1])
    then
        tail = redis.call('ZREVRANGE', KEYS[1], total - 3, total, 'WITHSCORES')
    else
        tail = redis.call('ZRANGE', KEYS[1], total - 3, total, 'WITHSCORES')
    end
    for k,v in pairs(tail) do
        if (k%2 == 0)
        then
            result[#result + 1] = v
            result[#result + 1] = total + s
            s = s + 1
        else
            result[#result + 1] = v
        end
    end
end
return result

Isn't this too heavy for Redis script? Is there a better way to inject numeric rank value into response?


texts:
I have no much experience with C++, so it is about time to start actually doing something about it. All in all, I coded this tiny unit test library:

assert.h:

#ifndef ASSERT_H
#define ASSERT_H

#include <iostream>

#define ASSERT(CONDITION) assert(CONDITION, #CONDITION, __FILE__, __LINE__);
#define REPORT            assert.report();
#define TOTAL_ASSERTIONS  assert.get_total_number_of_assertions()
#define FAILED_ASSERTIONS assert.get_number_of_failed_assertions()

class Assert {
public:
    bool operator()(const bool condition,
                    const char *const condition_text,
                    const char *const file_name,
                    const int line_number);

    size_t get_total_number_of_assertions() const;
    size_t get_number_of_failed_assertions() const;
    void report() const;

private:
    size_t m_total_assertions;
    size_t m_failed_assertions;
};

// Can't think of anything better than a global.
extern Assert assert;

#endif  // ASSERT_H

assert.cpp:

#include "assert.h"
#include <iostream>

bool Assert::operator()(const bool condition,
                        const char *const condition_text,
                        const char *const file_name,
                        const int line_number)
{
    if (!condition)
    {
        m_failed_assertions++;
        std::cerr << "'" << condition_text << "' is not true in file "
                  << "'" << file_name << "' at line " << line_number << "."
                  << std::endl;
    }

    m_total_assertions++;
    return condition;
}

size_t Assert::get_number_of_failed_assertions() const
{
    return m_failed_assertions;
}

size_t Assert::get_total_number_of_assertions() const
{
    return m_total_assertions;
}

void Assert::report() const
{
    std::cout << "[TOTAL ASSERTIONS: "
              << m_total_assertions
              << ", FAILED ASSERTIONS: "
              << m_failed_assertions
              << ", PASS RATIO: ";

    if (m_total_assertions == 0)
    {
        std::cout << "N/A";
    }
    else
    {
        std::cout << ((float) m_failed_assertions) / m_total_assertions;
    }

    std::cout << "]" << std::endl;
}

Assert assert;

main.cpp:

#include "assert.h"

static bool shit()
{
    return true;
}

int main(int argc, char** argv) {
    ASSERT(3 == 3)
    ASSERT(4 == 2)
    ASSERT(2 != 1)
    ASSERT(shit() && false)
    ASSERT(4 & 0)
    REPORT
    std::cout << TOTAL_ASSERTIONS << std::endl;
    std::cout << FAILED_ASSERTIONS << std::endl;
    return 0;
}

So, what should I fix in order to get to more idiomatic use of the language?


texts: Parsing and saving JSON result from GoEuro API

texts:
I am new to python so I decided to write a script that parses a json array and writes data in a file.

I wrote the code that does that but I think it can be done way better, So I was hoping to get feedback on how this code can be enhanced and more inline with python best practices.

from urllib2 import urlopen
import json

def get_json(url):
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)

url = ("http://api.goeuro.com/api/v2/position/suggest/en/Berlin")
json_array = get_json(url)

f = open('data.txt', 'w')

for x in json_array:
    gp = x["geo_position"]
    l = gp["latitude"]
    o = gp["longitude"]
    f.write(unicode(x["_id"]).encode("utf-8") +", " +     unicode(x["name"]).encode("utf-8") + ", " + unicode(x["type"]).encode("utf-8")+ ", " + unicode(l).encode("utf-8") + ", " + unicode(o).encode("utf-8") + unicode("\n").encode("utf-8"))

f.close()

Also, what is the best way for not having an empty new line at the end of the file ?


texts:
I have a school project to create a program that works the same as the Linux cat. The code works, but I just need find out where I can Improve it or handle errors. The program has 3 .c files and 1 header file. I'm also not allowed to use system functions; I have to use read(), close(), open() and write() and while loop only.

ft_read.c

#include "ft_read_file.h"

 int    ft_len(char *str)
 {
     int    i;

     i = 0;
     while (str[i] != '\0')
     i++;
     return (i);
  }

  void  ft_error(char *file_name)
  {
       ft_writeln(1, file_name, ft_len(file_name));
       ft_writeln(1, ": ", 2);
       ft_writeln(1, file_name, ft_len(file_name));
       ft_writeln(1, ":", 1);
       ft_writeln(1, " No such file or directory", 26);
       ft_writeln(1, ".\n", 2);
   }

   int  ft_read(int files, char **file_name)
   {
       int  fd;
       int  i;
       char buf[4096];
       int  size;

       fd = 1;
       i = 1;
       size = 0;
       while (i < files)
       {
           fd = open(file_name[i], O_RDONLY);
           if (fd == -1)
           {
               ft_error(file_name[i]);
                return (1);
            }
             size = read(fd, buf, 4095);
             buf[4095] = '\0';
             ft_writeln(1, buf, size);
             close(fd);
             i++;
          }
          return (0);
     }

main.c

#include "ft_read_file.h"

int main(int argc, char **argv)
{
    if (argc >= 1)
        ft_read(argc, argv);
    return (0);
 }

ft_writeln.c

#include "ft_read_file.h"

void    ft_writeln(int fd, void *buf, int size)
{
       write(fd, buf, size);
}


texts: PyOpencv code that displays color, b/w and canny images input from single live webcam camera

texts:
I have e single live webcam camera. I have displayed one color image, black and white image and canny edge image. Do you think I should put a scrollbar for the canny edge detection amount to make it a standard program or current threshold is fine?

import cv2
import cv
import numpy as np
import matplotlib.image as mpimg
from matplotlib import pyplot as plt

cam = cv2.VideoCapture(0)
cv2.namedWindow("test")

img_counter = 0

while True:
    ret, color = cam.read()

    edges = cv2.Canny(color, 50,500)
    gray = cv2.cvtColor(color,cv2.COLOR_RGB2GRAY)
    grey_3_channel = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
    edges_3_channel = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
    #blank_image = np.zeros((color.height*3,color.width*3,3), np.uint8)

    horiz = np.hstack((color, grey_3_channel,edges_3_channel))

    cv2.imshow('HORIZONTAL', horiz)

    if not ret:
        break
    k = cv2.waitKey(1)

    if k%256 == 27:
        # ESC pressed
        print("Escape hit, closing...")
        break

cam.release()

cv2.destroyAllWindows()


texts: Method for creating and traversing a BST while also getting its depth and width

texts:
This is a class for creating and traversing a BST while also getting its depth and width. I feel like this can be factored down into something more elegant and shorter I also feel like the overall design can be improved.

class BinaryNode {
  constructor(val) {
    this.val = val
    this.left = null
    this.right = null
  }
}

class BinaryTree {
  constructor(traversal) {
      this.traversal = traversal
    }
    * inorder(node) {
      if (node === undefined) node = this.root;
      if (!node) {
        return;
      }
      if (node) {
        yield* this.inorder(node.left)
        yield node.val;
        yield* this.inorder(node.right)
      }
    }

  * preorder(node) {
    if (node === undefined) node = this.root;
    if (!node) {
      return;
    }
    if (node) {
      yield node.val;
      yield* this.preorder(node.left)
      yield* this.preorder(node.right)
    }
  }

  * postorder(node) {
    if (node === undefined) node = this.root;
    if (!node) {
      return;
    }
    if (node) {
      yield* this.preorder(node.left)
      yield* this.preorder(node.right)
      yield node.val
    }
  }

  [Symbol.iterator]() {
    return this[this.traversal]()
  }
  length() {
    const len = node => {
      if (!node) return 0;
      return 1 + len(node.left) + len(node.right);
    }
    return len(this.root)
  }

  height() {
    const hi = node => {
      if (!node) return 0;
      return 1 + Math.max(hi(node.left), hi(node.right))
    }
    return hi(this.root)
  }

  diameter() {
    let max = 0;
    dfs(this.root)
    return max

    function dfs(node) {
      if (!node) return -1;
      let left = dfs(node.left) + 1
      let right = dfs(node.right) + 1
      max = Math.max(max, left + right)
      return Math.max(left, right);
    }
  }
}

class BST extends BinaryTree {
  constructor(traverse) {
    super(traverse)
    this.string = '';
  }
  deseralize() {
    let data = this.string.split(" ")
    return this.deseralizer(data)
  }
  deseralizer(data) {
    let val = data.shift()
    if (!data.length || val === '#') {
      return null;
    } else {
      let node = new BinaryNode(val)
      node.left = this.deseralizer(data)
      node.right = this.deseralizer(data)
      return node;
    }
  }

  seralize(node) {
    this.root = node;
    this.string = ''
    this.seralizer(node)
    return this.string
  }
  seralizer(node) {

    if (!node) {
      this.string += '# '
    } else {

      this.string += node.val + ' '
      this.seralizer(node.left)
      this.seralizer(node.right)

    }
  }

}

var tree = new BST('preorder');

let root = {
  "val": 1,
  "right": {
    "val": 3,
    "right": {
      "val": 5,
      "right": null,
      "left": null
    },
    "left": {
      "val": 4,
      "right": null,
      "left": null
    }
  },
  "left": {
    "val": 2,
    "right": null,
    "left": null
  }
}
console.log('seralize: ', tree.seralize(root))
console.log('deseralize: ', tree.deseralize())
for (let i of tree) {
  console.log('preorder', i)

}
console.log('preorder', [...tree])


texts:
I'm trying to write a concise linked list implementation in C and so far it looks pretty good. I'd like some pointers (pun) on how I can improve what I've got in terms of naming, consistency, efficiency, and anything else that's relevant.

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int data;
   struct node *next;
}node_t;

int length(node_t *head){
    int length = 0;
    for(node_t *cur = head; cur; cur = cur->next)
        length++;
    return length;
}

void printList(node_t *head){
    for(node_t *cur = head; cur; cur = cur->next)
        printf("%d\n", cur->data);
}

void deleteList(node_t **head){
    node_t *current = *head, *next;
    while (current != NULL) {
        next = current->next;
        free(current);
        current = next;
    }
   *head = NULL;
}

void deleteNode(node_t *node, node_t *head){
    node_t *cur = head;
    while (cur->next != node)
        cur = cur->next;
    cur->next = node->next;
    free(node); node=NULL;
}

node_t *getNode(int key, node_t *head){
    node_t *node = head;
    while(node){
        if (node->data == key){ return node; }
        else { node = node->next; }
    }
    return NULL;
}

node_t *insert(int key, node_t *head){
    node_t *cur = head;
    while(cur->next)
        cur = cur->next;
    node_t *new = malloc(sizeof(node_t));
    if (new == NULL){ exit(-1); }
    new->data = key;
    new->next = NULL;
    cur->next = new;
    return new;
}

node_t *createList(int key) {
    node_t *head = malloc(sizeof(node_t));
    if (head == NULL){ exit(-1); }
    head->data = key;
    head->next = NULL;
    return head;
}

int main(){
    node_t *head = createList(1);
    insert(2, head);
    node_t *nodeA = insert(3, head);
    insert(4, head);
    printf("1) Printing list:\n");
    printList(head);
    node_t *nodeB = getNode(4, head);
    deleteNode(nodeA, head);
    deleteNode(nodeB, head);
    printf("2) Printing list:\n");
    printList(head);
    deleteList(&head);
    printf("3) Printing list:\n");
    printList(head);
    return 0;
}


texts: Execution flow diagram (call-stack) of recursive count-down

texts:
I have this code:

public class RecurLoopTest {

    public static void main(String[] args) {

     printit(2);

    }

    private static int printit(int n){

        if(n>0){
            printit(--n);
        }

      System.out.print(n+",");

      return n;
   }
}

I have drawn a execution flow/memory flow diagram for above program.  Is this diagram correct or do I need some changes to make it correct?

What I have drawn looks like this:

Link to edit diagram

Link to view diagram


texts: How can I make this function that checks whether a number is a palindrome better?

texts:
I have this code:
export function is_palindrome(num: number): boolean {
    return [...num.toString()].reverse().join("") === num.toString();
}

which checks if a number is a palindrome(i.e 9009 reversed is still 9009), I do this by using the spread operator on num.toString(), reversing the array, joining it, and then comparing it to num.toString() which works but surely there must be a better way to do this.


texts: Refusing to use a common template engine

texts:
As the title says, I refuse to use a common template engine. I have my reasons, so instead of doing this:

test

{CommonParam}

I do this:

function listBlock($array){
echo '
';
foreach($array as $foo){
echo '
' . '' . $foo['text'] .
';
}
echo '
'
}

// now we'd call listBlock($myarray)

My question is quite simple... as I'm actually developing my own custom framework, I know it's a bit difficult to maintain this code, but it works great. Is this a good practice?


texts:
I made a bigint class that can add unsigned unlimited precision integers by splitting number into chunks less than 9999, and if a part is bigger than 9999 I take mod 10000 and carry 1 to the next part.

The adding function looks a bit messy as I had to make adjustments for the algorithm if rhs has more/less digits than lhs. Is there a way to make this programm more compact and readable?

class bigint
{
    std::vector<int> parts;
public:
    bigint(unsigned long long n);
    friend std::ostream& operator<<(std::ostream& os, const bigint& n);
    bigint& operator+=(bigint n);
};

bigint::bigint(unsigned long long n)
{
    while(n != 0)
    {
        parts.push_back(n%10000);
        n/=10000;
    }
}

std::ostream& operator<<(std::ostream& os, const bigint& n)
{
    for(auto it = n.parts.rbegin(); it != n.parts.rend(); ++it)os << (*it);
    return os;
}

bigint& bigint::operator+=(bigint n)
{
    auto a = parts.begin(), b = n.parts.begin();
    int carry = 0;
    while(a != parts.end() && b != n.parts.end())
    {
        *a+=*b+carry;
        carry = 0;
        if(*a > 9999)
        {
            *a = *a%10000;
            carry = 1;
        }
        ++a; ++b;
    }

    // If rhs has more digits than lhs
    if(a == parts.end() && b != n.parts.end())
    {
        while(b != n.parts.end())
        {
            parts.push_back(0);
            a = --parts.end();
            *a+=*b+carry;
            carry = 0;
            if(*a > 9999)
            {
                *a = *a%10000;
                carry = 1;
            }
            ++a; ++b;
        }
    }

    // If lhs has more digits than rhs
    if(b == n.parts.end() && a != parts.end())
    {
        while(a != n.parts.end() && carry == 1)
        {
            *a+=carry;
            carry = 0;
            if(*a > 9999)
            {
                *a = *a%10000;
                carry = 1;
            }
            ++a;
        }
    }
    if(carry == 1)parts.push_back(1);
    return *this;
}


texts: Filter options of select box using input box value

texts:
I have a select box with some options in it and a input box. I have to filter the values of select box on the basis of the keyword entered in the text box.

JavaScript

function filter() {
    var keyword = document.getElementById("search").value;
    var select = document.getElementById("select");
    for (var i = 0; i < select.length; i++) {
        var txt = select.options[i].text;
        if (txt.substring(0, keyword.length).toLowerCase() !== keyword.toLowerCase() && keyword.trim() !== "") {
            select.options[i].style.display = 'none';
        } else {
            select.options[i].style.display = 'list-item';
        }
    }
}

HTML

        <input type="text" id="search" name="search" style="margin: 10px;width: 165px;" onkeyup="filter()">

        <select id="select" size="10" style="margin: 10px; width: 165px;height: 170px;">
            <option>Cupcake</option>
            <option>Cunut</option>
            <option>Eclair</option>
            <option>Froyo</option>
            <option>Gingerbread</option>
            <option>Honeycomb</option>
            <option>Ice Cream Sandwich</option>
            <option>Jelly Bean</option>
            <option>KitKat</option>
            <option>Lollipop</option>
            <option>Marshmallow</option>
            <option>Nougat</option>
        </select>

Is this the right way for this task?

Here is the working code for the scenario.


texts: Finding all possible paths between two points in a grid using recursion

texts:
I'm trying to find all possible paths made of 0 from bottom left to top right, only by moving either up or to the right. The input file contains a grid of characters, where 1 represents an obstacle and 0 represents a vacant cell.

The problem I have is the code not finishing/ taking too long. The code works correctly with smaller inputs like this, but on a large file with 5000 rows and 5000 characters in each row it never finishes even after 20 minutes.

import sys
sys.setrecursionlimit(900000000)

file_e = open('file.txt','r')
file = file_e.readlines()
file_e.close()
file.reverse()
for index,line in enumerate(file):
    file[index] = line.split(' ')
print(len(file)-1, len(file[0])-1)
def end(file,y,x):

    if y == len(file)-1 and x == len(file[0])-1: return 1

    try:
        if file[y+1][x] == '0': up = True
    except: pass
    try:
        if file[y][x+1] == '0': right = True
    except: pass

    try:
        if up == True and right == True: return end(file,y+1,x) + end(file,y,x+1)
    except: pass

    try:
        if up == True: return end(file,y+1,x)
    except: pass

    try:
        if right == True: return end(file,y,x+1)
    except: pass

    if file[y+1][x] == '1' or file[y][x+1] == '1':
        return 0

print(end(file,0,0))


texts:
During an interview I was asked to consider the following:

  You are trying to find an instance of an error code within a number of log files within a directory. The goal is to count the number of times that the error code appears within the specified files.

For the written function, it was to be passed the following arguments (the directory and general file naming convention were known):

  [TimeStamp]: String

  [ErrorCode]: String

Afterward I went home and coded up a basic implementation of a single file search algorithm with, I believe, O(1) search time after the files are parsed. Does this implementation make sense, and is it correct in terms of Java 8?

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
/**
 * Created by Brendan on 5/13/2016.
 *
 * A quick implementation of an interview File Search algorithm.
 * Parses the file into a hash map so that occurrences of a phrase
 * can be quickly looked up.
 */
public class FileSearch {
    public static void main(String[] args) {
        Map<String, Long> wordMap = new HashMap<>();
        try {
            wordMap = populateWordMap("C:\\Projects\\logs\\app-log.log");
        } catch(IOException e) { }

        System.out.println("Total unique words found: " + wordMap.size());
        System.out.println("Most popular word: " + findMostPopularWord(wordMap));
    }

    private static String findMostPopularWord(Map<String, Long> wordMap) {
        return wordMap.entrySet()
                        .stream()
                        .max(Map.Entry.comparingByValue())
                        .get().getKey();
    }

    private static Map<String, Long> populateWordMap(String filePath) throws IOException {
        return Files.lines(Paths.get(filePath))
                .map((wholeLine) -> wholeLine.split(" "))
                .map((lineArray) -> mapWordsInLine(lineArray))
                .map(Map::entrySet)
                .flatMap(Collection::stream)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (m1, m2) -> m1 + m2));
    }

    private static Map<String, Long> mapWordsInLine(String[] lineArray) {
        return Arrays.stream(lineArray)
                    .collect(Collectors.groupingBy(String::toString, Collectors.counting()));
    }
}


texts:
I'm learning to Jinja2 and what's important in this case isn't speed but i18n translations and functionality. With Python 2.7, Jinja2 and not Django seems to preferred way to go, so I'm rewriting much of my project to use Jinja2 templates. We already had plenty of translations in .mo and .po files and wanted to keep use of those and we also want to make use of django's translation package. I found a way to use the Django translation libraries with Jinja2.

Could you review this code and comment if I can use it this way? My SDK is Google App Engine.

import jinja2
from django.utils import translation
from django.utils.translation import gettext, ngettext, ugettext, ungettext, get_language, activate
class DjangoTranslator(object):

    def __init__(self):
        self.gettext = gettext
        self.ngettext = ngettext
        self.ugettext = ugettext
        self.ungettext = ungettext
from jinja2 import Environment, FileSystemLoader
class DjangoEnvironment(jinja2.Environment):

    def get_translator(self, context):
        return DjangoTranslator()

jinja_environment = DjangoEnvironment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.i18n'])
jinja_environment.install_gettext_translations(translation)


texts:
I'm somewhat new to Scala and am not sure if I'm doing things in a very Scala-esque way.

In particular, I'm not sure if I'm using Option correctly, since by calling .isDefined, I'm basically just doing ye olde Java null check. Also, the getMethodAndAnnotationFromInfaces method could probably be done better.

Please point out ways in which I could better leverage language features in the below code:

for (val method <- clazz.getMethods) {
        val methodAndAnnotation = method.getAnnotation(annotationType) match {
            case annotation: MessageHandler => Some((method, annotation))
            case _ => getMethodAndAnnotationFromInterfaces(clazz.getInterfaces, method, annotationType)
        }

        if (methodAndAnnotation.isDefined){
            // do something
        }
    }

getMethodAndAnnotationFromInterfaces function:

def getMethodAndAnnotationFromInterfaces(interfaces: Array[java.lang.Class[_]], method: Method, annotationType: Class[_ <: java.lang.annotation.Annotation])
    : Option[(Method, java.lang.annotation.Annotation)] = {

    @tailrec
    def getMethodAndAnnotationFromInterfacesInner(interfaces: Array[java.lang.Class[_]], acc: Option[(Method, java.lang.annotation.Annotation)])
        : Option[(Method, java.lang.annotation.Annotation)] = {
        interfaces.length match {
            case 0 => acc
            case _ =>
                try {
                    interfaces.head.getMethod(method.getName, method.getParameterTypes: _*) match {
                        case newMethod: Method =>
                            val newAnnotation = newMethod.getAnnotation(annotationType)
                            if (newAnnotation != null && acc.isDefined) {
                                throw new RuntimeException("The annotation is applied to the method in more than one interface of the class.")
                            }
                            getMethodAndAnnotationFromInterfacesInner(interfaces.tail, Some((newMethod, newAnnotation)))
                        case _ => getMethodAndAnnotationFromInterfacesInner(interfaces.tail, acc)
                    }
                } catch {
                    case e: NoSuchMethodException => getMethodAndAnnotationFromInterfacesInner(interfaces.tail, acc)
                }
        }
    }

    getMethodAndAnnotationFromInterfacesInner(interfaces, None)
}


texts:
I'm crawling Flickr for data for my university research project. However it's very slow and I'm not sure what it is exactly.  It could be the FileWriter slowing it down. Any advice on speeding it up?

try {

    String userID = file.getUserIDFromList(i);

    System.out.println(i + "." + " " + userID);//to screen

    String urlString = "https://api.flickr.com/services/rest/?method=flickr.people.getPublicGroups&api_key=myAPIKey&user_id=" + userID;
    System.out.println(urlString);
    //print userID to file
    file.writeGroupID(userID);
    Collection<Group> groupNames = people.getPublicGroups(userID);

    String groupCount = Integer.toString(groupNames.size());
    //write number of groups to the file
    file.writeFile(groupCount);

    Iterator<Group> iteratorDetails = groupNames.iterator();
    //iterate over list to get each group's details

    while (iteratorDetails.hasNext()) {
        Group groupName = (Group)iteratorDetails.next();

        //get group name
        String name = groupName.getName();

        //get group id
        String id = groupName.getId();

        GroupsInterface groupInter = flickr.getGroupsInterface();

        Group gInfo = groupInter.getInfo(id);

        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
        DocumentBuilder b = f.newDocumentBuilder();
        Document doc = b.parse(urlString);

        doc.getDocumentElement().normalize();
        NodeList items = doc.getElementsByTagName("group");
        Node n = items.item(poolCounter);
        Element e = (Element) n;

        //get total photos in group
        String numberOfPhotos = e.getAttribute("pool_count");
        //get members in the group
        int numberOfMembers = gInfo.getMembers();

        //write group details to file
        file.writeFile("\t" + name + " " + numberOfPhotos + " photos" + ", " + numberOfMembers + " members");
        System.out.println("\t" + name + " " + numberOfPhotos + " photos" + ", " + numberOfMembers + " members");
        poolCounter++;
    }
    file.newLine();
}


texts:
I wanted to make my assets semi-dynamically so I made this utility class for it:

Assets PHP class:

<?php

    class Assets {

        private static $paths = array(
            'CSS' => '/assets/css/',
            'JS' => '/assets/js/',
            'FONTS' => '/assets/fonts/',
            'IMAGES' => '/assets/images/'
        );

        public static function get($file) {
            $fileType = pathinfo($file, PATHINFO_EXTENSION);

            switch (strtolower($fileType)) {
                case "css":
                    return self::$paths['CSS'] . $file;
                case "js":
                    return self::$paths['JS'] . $file;
                case "otf":
                case "eot":
                case "ttf":
                case "woff":
                case "woff2":
                case "svg":
                    return self::$paths['FONTS'] . $file;
                case "png":
                case "gif":
                case "jpg":
                    return self::$paths['IMAGES'] . $file;
                default:
                    throw new InvalidArgumentException("Filetype is not supported.");
            }
        }
    }
?>

Usage:

<link href="<?php echo Assets::get('bootstrap.css') ?>" rel="stylesheet">
<script type="application/javascript" src="<?php echo Assets::get('jquery.js') ?>"></script>

Is this efficient and how can I make it better, more dynamically and further.
Also I want to note I made this also to shorten my asset urls.


texts:
I have a simple application that reads a couple of csv files and outputs the input into catalogues for the website.  However, users have a habit of opening the csv files and inserting extra columns etc and it causes obvious issues, I have tried to tell people not mess with the files with no success, so i thought i would come up with a way round it.  Is there a better way of doing it than this?

    private static List<CatalogueLine> ImportCatalogueLines()
    {
        List<CatalogueLine> tempCatalogueLines = new List<CatalogueLine>();

        try
        {
            using (StreamReader reader = new StreamReader(ConfigurationManager.AppSettings["catalogue-lines-import-file"]))
            {
                int? catCodeColumn = null;
                int? prodCodeColumn = null;

                // Validate the column headers
                string[] header = reader.ReadLine().ToLower().Split(',');

                for (int i = 0; i < header.Length - 1; i++)
                {
                    if (header[i] == "catcode")
                        catCodeColumn = i;

                    if (header[i] == "prodcode")
                        prodCodeColumn = i;
                }
                if (catCodeColumn.HasValue == false || prodCodeColumn.HasValue == false)
                {
                    Console.WriteLine("Unable to validate the column headers, cancel the import.");
                    return tempCatalogueLines;
                }

                // Loop the rest of the lines.
                while (!reader.EndOfStream)
                {
                    // Split the line
                    string[] catalogueLine = reader.ReadLine().Split(',');
                    tempCatalogueLines.Add(new CatalogueLine
                    { CatCode = catalogueLine[(int)catCodeColumn], ProdCode = catalogueLine[(int)prodCodeColumn] });
                    Console.Write($"\rImporting Catalogue Lines:\t{ catalogueLine[(int)prodCodeColumn] } ");
                }
            }
            Console.Write($"\rImporting Catalogue Lines:\tCompleted.                    ");
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine($"{ e.Message }");
            return tempCatalogueLines;
        }
        catch (IOException e)
        {
            Console.WriteLine($"{ e.Message }");
            return tempCatalogueLines;
        }
        return tempCatalogueLines;
    }


texts: Object with highest count in a Groovy list

texts:
I have a list of Parcel objects and am trying to write a closure that picks the parcel object with highest count:

class Parcel {
int id,
int count,
String sender,
String recipient
Parcel(int _id, int _count) {
 id = _id
 count = _count
 }
}

def parcels = [new parcel(1,5), new parcel(2,1), new parcel(3,3), new parcel(4,2), new parcel(5,4) ]

I have tried the below code which works fine:

parcels.sort{it.count}
parcels.reverse().first()

Is there a better way to pick the parcel with the highest count?


texts: Creating a array of custom objects from JSON, sent using PHP from a MySQL database

texts:
I'm using PHP to send data in JSON to create an array of custom objects in Swift. I've been told retrieveData() is bad code because it's in an infinite loop. I'm not sure on how to clean it up so it can be more efficient. On a side note, is there a way I can save the custom objects in an array that is easier to save to UserDefaults without NSCoder?

The app is basically a blog reader. It gets data from a server's database and displays it in a tableview.

MainController.swift

var jsonArray: NSMutableArray = []
var mainArray = [Blog]()

// Retrieving Data from Server
func retrieveData() {

    let getDataURL = "http://example.com/receiving.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {
        let data: Data = try Data(contentsOf: url as URL)
        jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

        // Looping through jsonArray
        for i in 0..<jsonArray.count {

        // Create Blog Object
        guard let bID: String = (jsonArray[i] as AnyObject).object(forKey: "id") as? String,
            let bName: String = (jsonArray[i] as AnyObject).object(forKey: "blogName") as? String,
            let bStatus1: String = (jsonArray[i] as AnyObject).object(forKey: "blogStatus1") as? String,
            let bStatus2: String = (jsonArray[i] as AnyObject).object(forKey: "blogStatus2") as? String,
            let bURL: String = (jsonArray[i] as AnyObject).object(forKey: "blogURL") as? String,
            let bType: String = (jsonArray[i] as AnyObject).object(forKey: "blogType") as? String,
            let bDate: String = (jsonArray[i] as AnyObject).object(forKey: "blogDate") as? String,
            let bPop: String = (jsonArray[i] as AnyObject).object(forKey: "blogPop") as? String

            else {
                print("Error: (Creating Game Object)")
                return
            }

            // Add Blog Objects to mainArray
            mainArray.append(Blog(blogName: bName, andBlogStatus1: bStatus1, andBlogStatus2: bStatus2, andBlogURL: bURL, andBlogID: bID, andBlogType: bType, andBlogDate: bDate, andBlogPop: bPop))
        }
    }
    catch {
        print("Error: (Retrieving Data)")
    }
    myTableView.reloadData()
}

Blog.swift - Handles the Blog custom objects that it gets from retrieveData

import UIKit

class Blog: NSObject {

// Strings
var blogName: String
var blogStatus1: String
var blogStatus2: String
var blogURL: String
var blogID: String
var blogType: String
var blogDate: String
var blogPop: String

// Converting Strings into Objects
init(blogName bName: String,
     andBlogStatus1 bStatus1: String,
     andBlogStatus2 bStatus2: String,
     andBlogURL bURL: String,
     andBlogID bID: String,
     andBlogType bType: String,
     andBlogDate bDate: String,
     andBlogPop bPop: String)
{
    self.blogName = bName
    self.blogStatus1 = bStatus1
    self.blogStatus2 = bStatus2
    self.blogURL = bURL
    self.blogID = bID
    self.blogType = bType
    self.blogDate = bDate
    self.blogPop = bPop
    super.init()
  }
}


texts: Instantaneous validation of form field length

texts:
Since I have a function which can be done in few ways as usual, I was wondering which way is the best to achieve the form validation where I have only one input field, and I am showing a warning on keyup if the number of characters are in between 1 and 3 as well as enabling disabling submit button based on number of characters. Here is the fiddle. So I have two functions:

var myFunction = function () {
    var input = document.getElementById("input");
    var warning = document.getElementById("warning");
    var button = document.getElementById("button");

    if (input.value.length >= 1 && input.value.length <= 3){
        warning.style.display = 'block';
    }
    else {
        warning.style.display = 'none';
    }

    if(input.value.length > 3){
        button.disabled = false;
    }
    else {
        button.disabled = true;
    }
}

Here I have two if else statements, so I was wondering what would be the cleanest way to achieve the same thing? The only thing I could come up with was this function:

var alternative = function () {
    var input = document.getElementById("input");
    var warning = document.getElementById("warning");
    var button = document.getElementById("button");
    warning.style.display = 'none';
    button.disabled = true;

    if (input.value.length >= 1 && input.value.length <= 3)
        warning.style.display = 'block';

    if(input.value.length > 3)
        button.disabled = false;
}

But I am not sure what is the best approach performance wise, since in the second function I have states that will always be the same on calling the function and then changing them based on conditions and in the first one I first check the conditions and then manipulate the elements?


texts:
I designed the code and it works quite well for images of lower res. However my program takes a lot of time and ram to display higher res images (occupies 2GB RAM for 4k images and takes 20 minutes). This program currently only processes files in .png format.

#------------------------------------
import matplotlib.pyplot as plt
import skimage
from skimage import color
import numpy as np
#------------------------------------
x=plt.imread("s2.png")    #the file name
#x=color.rgba2rgb(x)
y=x
n=int(input())     #"n" is the level of blurring(typical values=5,10,20,50)
le=y.shape[0]
bd=y.shape[1]
#------------------------------------
def frame(y):
    y2=np.ones(shape=(le+(2*n),bd+(2*n)))
    for i in range(0,le):
        for j in range(0,bd):
            y2[(i+n),(j+n)]=y[i,j]
    return(y2)
#------------------------------------
#print((frame(y[:,:,0])).shape)

p=(2*n)+1
def kernel(p):

    k=np.zeros(shape=(p,p))
    for i in range(0,p):
        for j in range(0,p):
            k[i,j]=1.00005**(-(n-i)**2-(n-j)**2)
    k=k/(np.sum(k))
    return(k)
#print(kernel(p).shape)
#------------------------------------

def blur(arr,k,y2):
    z=np.zeros(shape=(le,bd))
    for i in range(0,le):
        for j in range(0,bd):
            z[i,j]=np.sum(k*(y2[i:(i+n+2+n-1),j:(j+n+2+n-1)]))

    return(z)
#------------------------------------
r=blur(y[:,:,0],kernel(p),frame(y[:,:,0]))
g=blur(y[:,:,1],kernel(p),frame(y[:,:,1]))
b=blur(y[:,:,2],kernel(p),frame(y[:,:,2]))

x2=(np.array([r.transpose(),g.transpose(),b.transpose()])).transpose()
plt.imshow(x2)
plt.show()


texts:
I am rendering a list from an array of objects. I want to check the correctness of the array before rendering. For that I am using typeof and null.

In real situation the list comes from the API.

Is it the correct way? and is there any better way to do it?

const activeEvents = [{
  id: '1',
  title: 'event 1'
}, {
  id: '2',
  title: 'event 2'
}]

function App() {
  return (

 List

      { typeof activeEvents === 'object' &&
      activeEvents !== null &&
      activeEvents.map(event => (

 { event.title }

       ))}

);
}

ReactDOM.render( <
  App / > ,
  document.getElementById('root')
);


texts: A function that opens and returns the contents of a file and some tests for it

texts:
I have the files "locale/{languageCode}.json" saved as part of the project, the reason that I made the read synchronous is because I think it is better that the internationalisation library I am using is initialised with the correct locale (rather than an async read, then dealing with promise resolution and updating the i18n settings with the new data when it arrives).
I plan to move the contents of the file into redis later, to reduce disc I/O, but right now I would like to focus on the usefulness of my tests, and ways this could be improved.
I am stubbing the readFileSync method because I don't think my tests should actually be doing disc I/O, as well as the logging function because I don't think the tests should actually write anything to the log file.
getLocale.ts
import fs from 'fs';
import {logger} from './logging/logger';

export const getLocale = (locale: string) : string => {
  const path = `${process.cwd()}/locales/${locale}.json`;
  try {
    return fs.readFileSync(path, 'utf-8');
  }
  catch(err) {
    logger.error(err);
  }
};

getLocale_spec.ts
import {expect} from 'chai';
import {getLocale} from '../../src/server/getLocale';
import sinonTest from 'sinon-test';
import fs from 'fs';
import sinon from 'sinon';
import {logger} from '../../src/server/logging/logger';

const test = sinonTest(sinon);

describe('getLocale', () => {
  it('opens the correct locale file', test(function () {
    const fsStub = this.stub(fs, 'readFileSync').returns('fake locale text');
    const result = getLocale('testLocale');
    expect(fsStub.calledWith('testLocale'));
    expect(result).to.equal('fake locale text');
  }));

  it('logs an error when locale file throws during open', test(function () {
    const fsStub = this.stub(fs, 'readFileSync').throws();
    const loggerStub = this.stub(logger, 'error');
    getLocale('testLocale');
    expect(fsStub.calledWith('testLocale'));
    expect(loggerStub.called).to.be.true;
  }));
});


texts:
I am currently in a challenge with my buddy to see who can code a simple paint program in the least lines. The only requirement, is that the program must include an eraser. How can I possibly shorten this code, while still using proper, beautiful syntax?

import sys, pygame
from pygame.locals import *
pygame.init() #Starts pygame
screen = pygame.display.set_mode((1000,720)) #window, and sets the size
screen.fill((255,255,255)) # Fills background color
brush = pygame.image.load("brush.jpg") #Loads the image into a variable
eraser = pygame.image.load("white.png") #Loads the image into a variable
brush = pygame.transform.scale(brush, (10,10)) #Scales the image into a more useable
eraser = pygame.transform.scale(eraser, (100,100)) #Scales the image into a more
clock = pygame.time.Clock() #Makes a clock to track the ticks within the game
z = 0
while True:
    clock.tick(60) #Limits the ticks to 60 (FPS)
    x,y = pygame.mouse.get_pos() #Sets two variables for the mouse position
    for event in pygame.event.get(): #Recieves events
        if event.type == QUIT: #Checks if the event is a QUIT event
            pygame.quit()  ##Quits##
            sys.exit()     ##Quits##
        elif event.type == MOUSEBUTTONDOWN:
            z = 1 #If you press the mouse button down, it sets the screen blit to true
        elif event.type == MOUSEBUTTONUP:
            z = z - 1 #Does the opposite of the above elif statement
        if z == 1: #Cheks if the variable z is true, if it is; updates the screen with the brush
            screen.blit(brush,(x-5,y-5))
        if event.type == KEYDOWN:
            screen.blit(eraser,(x-5,y-5))

    pygame.display.update()


texts:
I am writing a Sudoku solver in C, but am having problems with how long it takes to run. It can solve easier puzzles but once I put in one a little more difficult it runs and runs and never stops.

int solver (int x, int y)
{
  int a;
  int b;
  int i;
  int j;

  printf("Depth: %d\n", counter);

  for (a=1; a<10; a++)
  {
    if (checkEverything(x, y, a))
    {
      board[x][y] = a;
      counter++;

      if (counter == 81)
      {
        return true;
      }

      if (counter > 200 || counter < -10) {
        return false;
      }

      for (i=0; i<9; i++)
      {
        for (j=0; j<9; j++)
        {
          if (board[i][j] == 0)
          {
            if (solver(i, j))
            {
              return true;
            }
          }
        }
      }

      counter--;
      //printf("%d", a);
    }
  }

  //printf("No Solution1");
  board[x][y] = 0;
  return false;
}


texts: Matlab tic and toc commands implemented in C++

texts:
I need to time a few functions that I'm implementing, so I decided to implement a way of timing even multiple or sub calls based on the stack data structure and on the tic and toc commands of Matlab.

tictoc.h

#include <assert.h>
#include <cmath>
#include <ctime>
#include <iostream>
#include <stack>

static std::stack<std::clock_t> starting_times;

void start_timer()
{
    starting_times.push(std::clock());
}

int stop_timer(bool print, const char* to_execute = "")
{

    assert(!starting_times.empty());

    double milliseconds = (std::clock() - starting_times.top()) / (double)(CLOCKS_PER_SEC / 1000);
    starting_times.pop();

    if (print) {

        // minutes
        if (milliseconds >= 60 * 1000) {

            double m = milliseconds / 1000 / 60;
            double s = std::fmod(m, 60);
            double ms = std::fmod(s, 1000);

            std::cout << "Time elapsed '"
                      << std::lrint(m) << "m, "
                      << std::lrint(s) << "s and "
                      << std::lrint(ms) << "ms' "
                      << to_execute << "\n";

        } else if (milliseconds >= 1000) {
            std::cout << "Time elapsed '"
                      << std::lrint(milliseconds / 1000) << "s and "
                      << std::lrint(std::fmod(milliseconds, 1000)) << "ms' "
                      << to_execute << "\n";
        } else {
            std::cout << "Time elapsed '" << milliseconds << "ms' " << to_execute << "\n";
        }
    }

    return milliseconds;
}

to_execute is just a string that is eventually passed to describe which functions has just stopped being executed.

Of course, as you can observe from this code, I'm not expecting the functions to last more than 60 minutes, but if you think it's a good idea to add it, feel free to suggest a way to do it.

Of course, I've already tried the code and it seems to work.

Here's a simple runnable example that could use these functions:

main.cpp

#include "tictoc.h"
#include <iostream>

int main(const int argc, const char** argv)
{

    start_timer();

    int sum = 0;
    for (int i = 0; i < 10000; ++i) {
        sum += i;
    }

    std::cout << "sum = " << sum << "\n";

    stop_timer(true, "to execute the sum from 0 to 999");

    return 0;
}

Now put this and tictoc.h above in the same folder and compile with C++11, assuming you have it:

g++ -std=c++11 main.cpp -o main

Run executable main as:

./main


texts:
I started learning from the book: head first design patterns. As I am trying out different programs in the book, I am compiling them in this one demo app. Below is the code for its driver function. Can anyone guide me with any improvements to the program (related to style, programming, formatting, how to test, is it better to have try/catch/finally or throw exceptions and stuff like that or anything else) in this driver code?

Demo Driver Code:

package com.aviralgarg;

import java.util.Scanner;

import static com.aviralgarg.strategy.Main.runDuckSimulator;

public class Main {
    public static void main(String[] args) {

        try {
            demoLoop();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.err.println("Something went horribly wrong!");
        }
    }

    private static void demoLoop() {
        while (true) {
            showOptions();

            Scanner scanner = new Scanner(System.in);
            int option = scanner.nextInt();

            switch (option) {
                case 0 -> System.exit(0);
                case 1 -> showDesignPrinciples();
                case 2 -> runDuckSimulator();
                default -> System.err.println("Please select a valid option.");
            }

            showHorizontalLine();
        }
    }

    private static void showHorizontalLine() {
        System.out.println("------------------------------------------------------------------------------------");
    }

    private static void showOptions() {
        System.out.println("\nPick one of the following options:" +
                "\n\t1. Show design principles" +
                "\n\t2. Strategy pattern - Run the Duck Simulator" +
                "\n\t0. Exit");
    }

    private static void showDesignPrinciples() {
        System.out.println("Design Principles:" +
                "\n1. Identify the aspects of your application that vary and separate them from what stays the same." +
                "\n2. Program to an interface, not an implementation." +
                "\n3. Favor composition over inheritance." +
                "\n\n");
    }
}

Entire repository can be found here: https://github.com/aviral-garg/design-patterns. Any improvement in rest of those functions would be appreciated as well. Or I can just ask a separate question for that since the strategy design pattern is split into several different files and is quite abstracted away from this driver code.


texts:
This is a Leetcode problem:

  Implement pow(x, n), which calculates x raised to the power n (\$x^n\$).

  Note -

  -100.0 < x < 100.0
  n is a 32-bit signed integer, within the range [\$-2^{31}\$, \$2^{31}\$ − 1]

def pow(x, n):
    if n == 0:
        return 1
    if x == 0 and n < 0:
        return
    result = 1
    if n > 0:
        while n > 0:
            pre_result = result
            result *= x
            if pre_result == result or pre_result == -result:
                if result >= 0:
                    return result
                if n % 2 == 0:
                    return -result
                else:
                    return result
            n -= 1
        return result
    else:
        while n < 0:
            pre_result = result
            result /= x
            if pre_result == result or pre_result == -result:
                if result >= 0:
                    return result
                if n % 2 == 0:
                    return -result
                else:
                    return result
            n += 1
        return result

NOTE - My solution is \$O(n)\$.

Here are some example inputs/outputs:

#print(pow(2.00000, 10))

>>> 1024.0

#print(pow(2.10000, 3))

>>> 9.261

#print(pow(2.00000, -2))

>>> 0.25

#print(pow(-1.00000, -2147483648))

>>> 1.0

Here are the times taken for each output:

#%timeit pow(2.00000, 10)

>>> 1.88 µs ± 14 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

#%timeit pow(2.10000, 3)

>>> 805 ns ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

#%timeit pow(2.00000, -2)

>>> 643 ns ± 9.55 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

#%timeit pow(-1.00000, -2147483648)

>>> 594 ns ± 20 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

So, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts:
Any suggestions how I could simplify this LINQ query?

from type in assembly.GetTypes()
where type.IsPublic && !type.IsSealed && type.IsClass
where (from method in type.GetMethods()
       from typeEvent in type.GetEvents()
       where method.Name.EndsWith("Async")
       where typeEvent.Name.EndsWith("Completed")
       let operationName = method.Name.Substring(0, method.Name.Length - "Async".Length)
       where typeEvent.Name == operationName + "Completed"
       select new { method, typeEvent }).Count() > 0
select type;

assembly is of type System.Reflection.Assembly.
If you need more information, just ask.


texts:
This is a text-based RPG game I've made in C++ and would love some review on it. I am a 100% complete newbie with maybe 2 weeks of C++ experience so I'd love some lessons on what I did wrong and how I can improve! I mainly just use a lot of switch statements and if statements.

If there is anything wrong or things that could change and improve I'd very much appreciate if you could walk me through what was wrong, why it was wrong and how to prevent it from happening again. I really don't know a lot of C++ terms so ELIF would be awesome.

Here's my simple main.cpp. I think that's called a constructor and I'm using it to call my MeadowGiant.cpp down the road.

#include <iostream>
#include <string>
#include "MeadowGiant.h"

int main()
{
MeadowGiant obj1;
}

MeadowGiant.h

#define MEADOWGIANT_H

class MeadowGiant
{
public:
    MeadowGiant();
protected:
};

#endif

MeadowGiant.cpp

#include "MeadowGiant.h"
#include <iostream>
#include <string>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

MeadowGiant::MeadowGiant()
{
int trail, caveEnter;
int fight1;
int loot;
int goblinAttack, goblinHP, HP, attack, action1, ability;
goblinAttack = 5;
goblinHP = 10;
HP = 100;

std::cout << -Insert story narrative- Choose a trail to go down.\n";
std::cin  >> trail;

    if(trail==1)
    {
    std::cout << "-Insert story narrative- Come across a cave. Do you go in?\n";
    std::cin  >> caveEnter;

        if(caveEnter==1)
        {
        std::cout << "You are ambushed by a goblin. Run or fight?\n";
        std::cin >> fight1;

        goblinFight:
        loot = rand() % 4 + 1;
        srand(time(NULL));

        if(fight1==1)
        {
        std::cout   << "Your HP: " << HP << std::endl;
        std::cout   << "Enemy HP: " << goblinHP << std::endl;
        std::cout   << "What do you do?\n
                    << "[1] Attack [2] Run \n";
        std::cin    >> action1;
        }
            if(goblinHP<=0)
            {
            std::cout << "You have slain the goblin!\n"
                      << "You head towards the chest and take the spoils\n"
                      << "of battle!\n";
                 switch(loot)
            {
            case 1: std::cout << "You find a bastard sword!\n";
                              attack = attack + 7;
                              goto exitCave;
            case 2: std::cout << "You find an Enchanted Staff!\n";
                              attack = attack + 10;
                              goto exitCave;
            case 3: std::cout << "You find an Obsidian Dagger!\n";
                              attack = attack + 9;
                              goto exitCave;
            case 4: std::cout << "You find a Holy Mace!\n";
                              attack = attack + 10;
                              goto exitCave;
            }
    else if(action1==1)
    {
    std::cout   << "You successfully hit the goblin!\n"
                << "He strikes back!\n";
    attack = rand() % 10 + 1;
    srand(time(NULL));

    goblinHP = goblinHP - attack;
    HP = HP - goblinAttack;
    goto goblinFight;
    }
    else if(action==2)
    {
    std::cout   << "You take the cowards way out and leave the cave.\n";
    goto exitCave;
    }
    }
else if(caveEnter==2)
{
exitCave:
std::cout << "You have exited the cave.\n";
}
else
{
goto exitCave;
}
}
}

The format of my actual code doesn't look like this in my IDE. The code is the same, but the tabs are much cleaner in my compiler so if that's an issue, I'm already on it.


texts: (de)serializing c++ object almost automagically

texts:
Here's one way to solve the serialization problem in c++20, using a json library:
#include <functional>

#include <unordered_map>

#include "json.hpp"

namespace nlm = nlohmann;

class properties
{
  struct property_info
  {
    std::function<void(nlm::json const&)> deserializor;
    std::function<nlm::json()> serializor;
  };

  std::unordered_map<std::string_view, property_info> reg_;

public:
  //
  nlm::json state() const;
  void state(nlm::json const&);

  //
  template <typename U, typename ...A>
  auto register_property(std::string_view const& k, U& v, A&& ...a)
  {
    static_assert(!(sizeof...(a) % 2));
    static_assert(!(std::is_const_v<U>));

    reg_.try_emplace(k,
      [&v](nlm::json const& j){v = j.get<U>();},
      [&v]{return nlm::json(v);}
    );

    if constexpr (sizeof...(a))
    {
      register_property(std::forward<A>(a)...);
    }

    return [this](auto&& ...a)
      {
        return register_property(std::forward<decltype(a)>(a)...);
      };
  }

  auto get(std::string_view const& k)
  {
    return reg_.find(k)->second.serializor();
  }

  template <typename U>
  void set(std::string_view const& k, U&& v)
  {
    reg_.find(k)->second.deserializor(std::forward<U>(v));
  }
};

nlm::json properties::state() const
{
  nlm::json r(nlm::json::object());

  for (auto i(reg_.cbegin()), cend(reg_.cend()); cend != i; i = std::next(i))
  {
    r.emplace(i->first, i->second.serializor());
  }

  return r;
}

void properties::state(nlm::json const& e)
{
  assert(e.is_object());
  auto const cend(reg_.cend());

  for (auto i(e.cbegin()), ecend(e.cend()); ecend != i; i = std::next(i))
  {
    auto& key(i.key());

    if (auto const j(std::as_const(reg_).find(key)); cend != j)
    {
      j->second.deserializor(i.value());
    }
  }
}

Example:
int main()
{
  struct S: properties
  {
    bool b{};
    int i{};

    S()
    {
      register_property("b", b)("i", i);
    }
  } s;

  s.set("b", true);
  s.set("i", 11.1);

  std::cout << s.get("b") << std::endl;
  std::cout << s.state() << std::endl;
}

2 functors for (de)serializing are generated for each registered property. If state is requested or set, these are executed accordingly. Obvious improvements are certain checks, getters/setters, instead of references. I think this is a nice quick solution for simple cases.
https://wandbox.org/permlink/J0vdLOTp5x6xvF9s


texts: Improve this image file browser (remove redundancy)?

texts:
Let me start by saying that the code works as is but I think it has a lot of redundancy. It is written this way as I kept getting nullpointerexceptions if I try to put the fileCounter > gameDiff if/else inside one for loop.

The program allows a user to create directories and add images to them. It will also display a certain number of images based on the users selection. If the user's chosen directory doesn't have enough images, it drops back to the default directory to add more.

String userDir = cboImages.getSelectedItem().toString();
File filePath = new File(baseDir + "/" + userDir + "/");

comboFile = filePath.listFiles();
int fileCounter = 0;
for (int ctr = 0; ctr < comboFile.length; ctr++) {
    if (comboFile[ctr].isFile()) {
        fileCounter++;
    }
}

filePath = new File(baseDir + "/default/");
defaultFile = filePath.listFiles();

List<File> listShuffle = Arrays.asList(comboFile);
List<File> defaultShuffle = Arrays.asList(defaultFile);
Collections.shuffle(listShuffle);
Collections.shuffle(defaultShuffle);

if(fileCounter > gameDiff){
    for (int ctr = 0; ctr < gameDiff; ctr++) {

        Card card = new Card();
        card.setbackImage(new ImageIcon(cardBackImage));

        Image img = null;

        if (listShuffle.get(ctr).isFile()) {
            img = new ImageIcon(listShuffle.get(ctr).getPath()).getImage();
        }
        Image dimg = img.getScaledInstance(144, 216, Image.SCALE_SMOOTH);
        card.setfrontImage(new ImageIcon(dimg));

        // Populate card with db results
        cardsList.add(card);
    }
}
else{
    for (int ctr = 0; ctr < gameDiff; ctr++) {

        Card card = new Card();
        card.setbackImage(new ImageIcon(cardBackImage));

        Image img = null;

        if (ctr < listShuffle.size()) {
            if (listShuffle.get(ctr).isFile()) {
                if (fileCounter <= gameDiff) {
                    img = new ImageIcon(listShuffle.get(ctr).getPath()).getImage();
                }
            }
        } else if (ctr < gameDiff) {
            if (defaultShuffle.get(ctr).isFile()) {
                img = new ImageIcon(defaultShuffle.get(ctr).getPath()).getImage();
            }
        }

        Image dimg = img.getScaledInstance(144, 216, Image.SCALE_SMOOTH);
        card.setfrontImage(new ImageIcon(dimg));

        // Populate card with db results
        cardsList.add(card);
    }
}

Using two separate groups insures that the chosen directory images get added.