texts: Repurposing UITableView infinite scroll configuration/properties

texts:
Had my first go at implementing infinite scrolling for UITableView's in my iOS app last night, and I noticed I ended up copying/pasting quite a bit of boilerplate from one VC to the next (if I wanted infinite scroll on it).

By the way, I'm fairly new to iOS, so this question is probably more broad than just specifically keeping infinite scroll config DRY...

I have properties like these:

@property(nonatomic) int checkins_page;
@property(nonatomic) int checkins_total;
@property(nonatomic) int checkins_total_pages;
@property(nonatomic) BOOL checkins_load_more;
@property(nonatomic) int watchlist_page;
@property(nonatomic) int watchlist_total;
@property(nonatomic) int watchlist_total_pages;
@property(nonatomic) BOOL watchlist_load_more;

I have two UITableViews in this VC, so that's fun.

Then I have a delegate method:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{

    if(scrollView == self.checkinsTableView && !self.checkins_load_more){
        return;
    }
    if(scrollView == self.watchlistTableView && !self.watchlist_load_more){
        return;
    }
    CGFloat height = scrollView.frame.size.height;

    CGFloat contentYoffset = scrollView.contentOffset.y;

    CGFloat distanceFromBottom = scrollView.contentSize.height - contentYoffset;

    if(distanceFromBottom < height)
    {
        if(scrollView == self.checkinsTableView){
            self.checkins_load_more = NO;
            if(self.checkins_page < self.checkins_total_pages){
                self.checkins_page++;
                [self downloadCheckins];
            }
        }
        if(scrollView == self.watchlistTableView){
            self.watchlist_load_more = NO;
            if(self.watchlist_page < self.watchlist_total_pages){
                self.watchlist_page++;
                [self downloadWatchlist];
            }
        }
    }
}

Now I'm seeing a lot of this stuff could be abstracted...somewhere...somehow, maybe into a more general purpose infinite scroll VC, but like I'm said, quite new to iOS, so I'm not sure the best way to go about reducing this boilerplate code.

Any advice/pointers would be appreciated on how to clean it up slightly?


texts: Select value based on condition on dataframe

texts:
I have some data in data frame and would like to return a value based on specific conditions.  It is highly time consuming.

I tried three methods:

Method 1:
Without dataframe, this is the simple logic I have and it is super fast.

@numba.vectorize(['float64(float64, float64)'])
def Method1(a,b):
    x=0.0
    y=0.0
    z=0.0

    if (a <= 0.002):
        x=0.5
        y=2500
        z=20000
    elif (a <= 0.003):
        x=0.3
        y=2500
        z=15000
    elif (a <= 0.005):
        x=0.2
        y=1000
        z=10000
    else:
        return 0.0

    return min(max(x*b,y),z)

%timeit Method1(0.001,200000)

Method 2 - Input the condition data as a dataframe and run the function

dict = {'amin':[0.000,0.002,0.003],
       'amax':[0.002,0.003,0.005],
       'dfx':[0.5,0.3,0.2],
       'dfy':[2500,2500,1000],
       'dfz':[20000,15000,10000]}
df=pd.DataFrame(dict)

@numba.vectorize(['float64(float64, float64)'])
def Method2(a,b):
    x=0.0
    y=0.0
    z=0.0

    x=df[(a<=df.amax) & (a>=df.amin)]['dfx'].values
    y=df[(a<=df.amax) & (a>=df.amin)]['dfz'].values
    z=df[(a<=df.amax) & (a>=df.amin)]['dfy'].values

    if (len(x)==0) or (len(y)==0) or (len(z)==0):
        return 0.0
    else:
        return min(max(x[0]*b,y[0]),z[0])
%timeit Method2(0.001,200000)

Method 3 - looped the rows of the df

def Method3(a,b):
    for index,row in df.iterrows():
        if (mPD >= row['amin']) & (mPD <= row['amax']):
            return min(max(row['dfx']*b,row['dfy']),row['dfz'])
    return 0.0
%timeit Method3(0.001,200000)

Method 1 gets finished in 1.2 micro seconds

Method 2 takes 2.47 milli seconds (1000 times slower than the Method 1)

Method 3 takes ~80 micro seconds

Please help me how to improve the performance of Method 2 / 3.
Also, please let me know why Method 3 is faster?

P.S. I plan to use Numba so cannot use lambda in the functions.


texts:
So, I coded a program which asks you the number of integers and the integers the user wants to sort in descending order. The program works but I feel like it is very inefficient. If I were to receive high amount of numbers the program would have to do so much processing. Therefore, how can I improve my code in simple ways? (Open to any criticism)

import java.util.Scanner;

public class Main {
private static Scanner scanner = new Scanner(System.in);
private static Scanner scanner2 = new Scanner(System.in);

public static void main(String[] args) {
    System.out.println("How many integers do you want to sort?");
    int[] IntArray = getIntegers(scanner.nextInt());
    IntArray = sortIntegers(IntArray);
    printIntegers(IntArray);

}

public static int[] getIntegers(int number) {
    System.out.println("Enter " + number + " integers.");
    int[] values = new int[number];

    for (int i = 0; i < values.length; i++) {
        values[i] = scanner2.nextInt();
    }
    return values;
}

public static int[] sortIntegers(int[] array){
    int[] unsortedArray = new int[array.length];
    for(int i = 0; i < unsortedArray.length; i++){
        unsortedArray[i] = array[i];
    }

    for(int n = 0; n < unsortedArray.length - 1; n++) {
        for (int j = 0; j < unsortedArray.length - 1; j++) {
            if (unsortedArray[j] < unsortedArray[j + 1]) {
                int k = unsortedArray[j];
                unsortedArray[j] = unsortedArray[j + 1];
                unsortedArray[j + 1] = k;
            }
        }
    }
    return unsortedArray;
}

public static void printIntegers(int[] array){
    for(int i = 0; i < array.length; i++){
        System.out.println(array[i]);
    }
}
}


texts: Pandas iteration over rows for features calculation

texts:
I have a pandas data frame and I want to calculate some features based on some short_window, long_window and bins values. More specifically, for each different row, I want to calculate some features. In order to do so, I move one row forward the df_long = df.loc[row:long_window+row] such as in the first iteration the pandas data frame for row=0 would be df_long = df.loc[0:50+0] and some features would be calculated based on this data frame, for row=1 would be df_long = df.loc[1:50+1] and some other features would be calculated and continues.

from numpy.random import seed
from numpy.random import randint
import pandas as pd
from joblib import Parallel, delayed

bins = 12
short_window = 10
long_window = 50

# seed random number generator
seed(1)

price = pd.DataFrame({
    'DATE_TIME': pd.date_range('2012-01-01', '2012-02-01', freq='30min'),
    'value': randint(2, 20, 1489),
    'amount': randint(50, 200, 1489)
})

def vap(row, df, short_window, long_window, bins):

    df_long = df.loc[row:long_window+row]
    df_short = df_long.tail(short_window)

    binning = pd.cut(df_long['value'], bins, retbins=True)[1]
    group_months = pd.DataFrame(df_short['amount'].groupby(pd.cut(df_short['value'], binning)).sum())

    return group_months['amount'].tolist(),  df.loc[long_window + row + 1, 'DATE_TIME']

def feature_extraction(data, short_window, long_window, bins):

    # Vap feature extraction
    ls = [f"feature{row + 1}" for row in range(bins)]
    amount, date = zip(*Parallel(n_jobs=4)(delayed(vap)(i, data, short_window, long_window, bins)
                                                for i in range(0, data.shape[0] - long_window - 1)))
    temp = pd.DataFrame(date, columns=['DATE_TIME'])
    temp[ls] = pd.DataFrame(amount, index=temp.index)
    data = data.merge(temp, on='DATE_TIME', how='outer')

    return data

df = feature_extraction(price, short_window, long_window, bins)

I tried to run it in parallel in order to save time but due to the dimensions of my data, it takes a long of time to finish.

Is there any way to change this iterative process (df_long = df.loc[row:long_window+row]) in order to reduce the computational cost? I was wondering if there is any way to use pandas.rolling but I am not sure how to use it in this case.

Any help would be much appreciated!
Thank you


texts:
Below is some code I have written today to test out some bits I have learnt. It isn't much nor is it spectacular. Please critique and let me know what I could/should have done differently or anything I could do to improve it so far.

package easy8;

import java.util.Scanner;

public class song99bottles {

public static void main(String[] args) {

// Declare a reference variable of type song99bottles - new object
song99bottles go = new song99bottles();
// calls the method "queston" for object "go".
go.question();

}

public void question(){

    song99bottles start = new song99bottles();

    String answer;

    System.out.println("Would you like to hear a nursery rhyme?\nPlease enter yes or no:");
    Scanner input = new Scanner(System.in);
    answer = input.next();
    if(answer.equalsIgnoreCase("yes")){
        start.lyrics();
    } else{
        System.out.println("Bye");
    }

}

public void lyrics() {

    int peeps  = 10;
    String intro = "There were ";
    String intro2 = " in the bed and the little one said rollover";
    String fall = "\nSo they all rolled over and 1 fell out.";
    String end = "And the little said 'I'm lonely'.";

    while (peeps > 0){
        System.out.println( intro + peeps + intro2 + fall);
        peeps--;
        if (peeps == 1){
            System.out.println(end);
            return;
                        }
    }

}

}


texts:
The problem is to divide a list into n parts according to a predicate. I found recursive solution but I am sure that a more elegant solution also exists.

def repeatedSpan[T](col: Iterable[T], pred: T => Boolean): List[Iterable[T]] = {
  if (col.isEmpty) Nil
  else {
    val (a, b) = col.span(pred)
    if (a.isEmpty) b.take(1) :: repeatedSpan(b.tail, pred)
    else a :: repeatedSpan(b, pred)
  }
}

scala> repeatedSpan(List(1, 2, 3, 1, 4, 5, 6, 1, 7), (a: Int) => a != 1)
res9: List[Iterable[Int]] = List(List(1), List(2, 3), List(1), List(4, 5, 6), List(1), List(7))


texts: Refactor C# code for creating XML to not use intermediate dictionary

texts:
If have the following code that via an SQL query retrieves data from a database in the form:

Id      subschemaName  locusName
MLST    MLST           LMO0558
MLST    MLST           LMO0563
MLVST   MLVST          LMO1305
MLVST   MLVST          LMO1089

And I want to turn this into an XML like:

<ResponseSubschemas>
    <organism>LMO</organism>
    <Subschemas>
        <Subschema>
            <id>MLST</id>
            <name>MLST</name>
            <loci>
                <locus>LMO0558</locus>
                <locus>LMO0563</locus>
            </loci>
        </Subschema>
        <Subschema>
            <id>MLVST</id>
            <name>MLVST</name>
            <loci>
                <locus>LMO1305</locus>
                <locus>LMO1089</locus>
            </loci>
        </Subschema>
    </Subschemas>
</ResponseSubschemas>

I do this by using a dictionary but it is the first time I'm using C# and I'm sure there must be a more efficient way of doing this in one go?

string subschemaSQL =   "SELECT subschema.Id, subschema.name as subschemaName, locus.Name as locusName " +
                        "FROM subschema " +
                        "LEFT JOIN subschemamembers ON subschemamembers.SubSchemaID = subschema.PrimKey " +
                        "LEFT JOIN locus ON subschemamembers.LocusID = locus.ID " +
                        "WHERE  subschema.OrganismID = ? " +
                        "ORDER BY subschema.Id, locusName";

XElement rootNode = new XElement("ResponseSubschemas",
    new XElement("organism", organismID),
    new XElement("Subschemas"));
XElement subschemasNode = rootNode.Element("Subschemas");

DbDataReader subschemaReader = conn.Query(subschemaSQL, organismID);

Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
while (subschemaReader.Read())
{
    string subschemaDbID = (string)subschemaReader["Id"];
    XElement subschemaNode = new XElement("Subschema",
        new XElement("id", subschemaDbID),
        new XElement("name", subschemaReader["subschemaName"])
    );
    subschemasNode.Add(subschemaNode);
    string locusName = (string)subschemaReader["locusName"];
    if (dictionary.ContainsKey(subschemaDbID))
    {
        dictionary[subschemaDbID].Add(locusName);
    }
    else
    {
        dictionary.Add(subschemaDbID, new List<string> { locusName });
    }
}

IEnumerable<XElement> subschemaNodes = from element in
                                       subschemasNode.Elements("Subschema")
                                       select element;
foreach (XElement subschemaNode in subschemaNodes)
{
    string subschemaID = subschemaNode.Element("id").Value;
    XElement lociNode = new XElement("loci");
    foreach (string locusName in dictionary[subschemaID])
    {
        XElement locusNode = new XElement("locus", locusName);
        lociNode.Add(locusNode);
    }
    subschemaNode.Add(lociNode);

}

responseXml = rootNode.ToString();


texts:
I've decided to make a wrapper class for the java.util.Properties class since, in its current state, it only allows for storing and reading String values.

Is there any way I can improve the following code?

public final class Prefs {

    private static final Properties properties = new Properties();
    private static OutputStream out;
    public static final File test = new File("settings.properties");

    public static void main(String[] args) throws IOException {
        try {
            set("hello", "5");

            int hello = get("hello", 1337);
            System.out.println(hello == 5);

            set("hello", "34");
            hello = get("hello", 1337);
            System.out.println(hello == 34);

            remove("hello");
            hello = get("hello", 1337);
            System.out.println(hello == 1337);
        } finally {
            save();
        }
    }

    static {
        try {
            if (!test.exists()) {
                test.createNewFile();
            }
            properties.load(new FileInputStream(test));
            out = new FileOutputStream(test);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static <T> T get(String key, T defaultValue) {
        if (!properties.containsKey(key)) {
            return defaultValue;
        }
        String value = properties.getProperty(key);
        if (defaultValue instanceof Long) {
            return (T) new Long(value);
        } else if (defaultValue instanceof Integer) {
            return (T) new Integer(value);
        } else if (defaultValue instanceof Short) {
            return (T) new Short(value);
        } else if (defaultValue instanceof Byte) {
            return (T) new Byte(value);
        } else if (defaultValue instanceof Double) {
            return (T) new Double(value);
        } else if (defaultValue instanceof Float) {
            return (T) new Float(value);
        } else if (defaultValue instanceof Boolean) {
            return (T) new Boolean(value);
        }
        return (T) value;
    }

    public static void set(String key, String value) {
        properties.setProperty(key, "" + value);
    }

    public static void remove(String key) {
        properties.remove(key);
    }

    private static final ReentrantLock lock = new ReentrantLock();

    public static void save() {
        lock.lock();
        try {
            properties.store(out, "");
            out.flush();
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}


texts: Shorthand and nicer python syntax for four options clicking a button

texts:
I have a var af_button which is a button on UI. It can be either selected or deselected, so in that case I have four possibilities, which I have implemented. I don't like this implementation, so what would be a more pythonic way of implementing this?

af_button = squishtest.waitForObject("{text='AF' type='QPushButton' unnamed='1' visible='1'}")
if state == 'click':
    if af_button.checked == 1:
        pass
    else:
        squishtest.clickButton(squishtest.waitForObject(af_button))
else:
    if af_button.checked == 0:
        pass
    else:
        squishtest.clickButton(squishtest.waitForObject(af_button))


texts:
My application has a whole chain of Observables running through it, and recently I found that something was slowing down my (hot) source, but I couldn't work out where.

Obviously, with everything running in series by default, a good first step was to introduce some 'parallelism', so after having done battle with my own implementation, I discovered that ObserveOn did what I wanted: allow a source to 'carry on' while a subscriber did whatever.

But that didn't solve my problem of knowing where the slow bits were. Which lead me to trying to invent a Buffered function which does the buffering, but also tells me how long the buffer is.

I'm aware that this doesn't do all the fancy Rx business of giving you the choice of which scheduler and all that, but for my purposes currently Task is good enough (unless you tell me otherwise):

This is the tuple used to return data in:

public class WithBufferSize<T>
{
    public readonly T Value;
    public readonly int BufferSize;
    public WithBufferSize(T value, int bufferSize)
    {
        Value = value;
        BufferSize = bufferSize;
    }
}

Here is the function:

public static IObservable<WithBufferSize<T>> Buffered<T>(this IObservable<T> source)
{
    return Observable.Create<WithBufferSize<T>>(observer =>
    {
        var buffer = new BlockingCollection<T>();
        Exception exception = null;
        bool completed = false;
        var task = new Task(() =>
        {
            foreach(var t in buffer.GetConsumingEnumerable())
                observer.OnNext(new WithBufferSize<T>(t, buffer.Count));
            if(exception != null)
                observer.OnError(exception);
            else if(completed)
                observer.OnCompleted();
        }, TaskCreationOptions.LongRunning);
        task.Start();
        var subscription = source.Subscribe(t => buffer.Add(t),
        ex =>
        {
            exception = ex;
            buffer.CompleteAdding();
        },
        () =>
        {
            completed = true;
            buffer.CompleteAdding();
        });
        return new CompositeDisposable(
            subscription,
            Disposable.Create(() => buffer.CompleteAdding()));
    }).Publish().RefCount();
}

I originally used Materialise, but switched to using flags because it creates less objects.


texts: Finding the largest word in the given String

texts:
If there are two or more words that are the same length, return the first word from the string with that length. I am a beginner. Could anyone highlight good and bad parts of the following program.Also, had it been last word from the string with that length, would it give different result in Chrome and Firefox because of it being unstable in Chrome ?

function LongestWord(sen) {

var arr2=[];
var arr =sen.split(" ");
var arr1=arr;
arr.sort(function (a,b){

if(a.length<b.length){
    return -1;
}
else if(a.length===b.length){
    return 0;
}
else return 1;
});

var len =arr[arr.length-1].length;
for(var i =0 ; i<arr1.length;i++)
  {
     if(arr1[i].length===len)
    {
    arr2.push(arr[i]);
    break;
     }

    }
  return(arr2.pop());

}


texts: Transforming tuple with (int month, int year) in string "mm/yyyy"

texts:
I would like to improve the following code:

    result = database.execute(script, fetch="0") # (6, 2016) for example
    month = str(result[0])
    year = str(result[1])
    if len(month) == 1:
        month = "0" + month
    return "%s/%s" % (month, year)

I'm feeling that my code is dumb, and could be more intelligent.

Python version 2.6.


texts: Test Driven Development in JS and Sinon Stub

texts:
I am going through some TDD and BDD tutorials which guide one through implementing a simple beverage-ordering system. While I think I understand the material, I am still wondering about some intricacies. In particular, it seems that my sinon.stub() line is not really doing anything.

I am soliciting comments on this code. Any suggestions for improvements are welcome. Those related to the test-driven development are especially so. How am I doing?

test.js

'use strict';
require("babel-register");

var chai = require('chai');
var expect = chai.expect;
var sinon = require('sinon');
var orderSystemWith = require('../lib/orders');

//describe is used to display features
//context is used to display scenarios
//it is used to describe tests within a feature/scenario
describe('Customer displays order', function () {
    beforeEach( () => {
        this.orderDAO = {
            byId: sinon.stub()
        };
        this.orderSystem = orderSystemWith(this.orderDAO);
    })
    context('Given that the order is empty', () => {
        beforeEach( () => {
            this.orderId = 'some empty order id';
            this.orderDAO.byId.withArgs(this.orderId).returns([]);
            this.result = this.orderSystem.display(this.orderId);
        })
        it('will show no order items', () => {
            expect(this.result).to.have.property('items').that.is.empty;
        });
        it('will show 0 as the total prince', () => {
            expect(this.result).to.have.property('totalPrice').that.is.equal(0);
        });
        it('will only be possible to add a beverage', () => {
            expect(this.result).to.have.property('actions').that.is.deep.equal([{
                action:'append-beverage',
                target: this.orderId,
                parameters: {
                    beverageRef: null,
                    quantity: 0
                }
            }])
        });
    });

    context('Given that the order contains beverages', function(){

        it('will show one item per beverage');
        it('will show the sum of unit prices as total prince');
        it('will be possible to place the order');
        it('will be possible to add a beverage');
        it('will be possible to remove a beverage');
        it('will be possible to change the quantity of a beverage');
    });

    context('Given that the order has pending messages', function(){
        it('will show the pending messages');
        it('there will be no more pending messages');
    })

});

orders.js

var order = function (orderDAO) {
    return {
        display: (orderID) => {return {
            "items": [],
            "totalPrice": 0,
            "actions": [{
                action:'append-beverage',
                target: orderID,
                parameters: {
                    beverageRef: null,
                    quantity: 0
                },
            }],
        }},
    }
}

module.exports = order

Testing results:

  Customer displays order
    Given that the order is empty
      ✓ will show no order items
      ✓ will show 0 as the total prince
      ✓ will only be possible to add a beverage
    Given that the order contains beverages
      - will show one item per beverage
      - will show the sum of unit prices as total prince
      - will be possible to place the order
      - will be possible to add a beverage
      - will be possible to remove a beverage
      - will be possible to change the quantity of a beverage
    Given that the order has pending messages
      - will show the pending messages
      - there will be no more pending messages

  3 passing (249ms)
  8 pending


texts:
I made this small class the allows me to navigate large arrays using something like: key1/key2/key3

I made this because I was creating large arrays to hold my classes configs and needed a simpler way of accessing the data.

Here is the project:
 - https://github.com/AntonioCS/settingsManager

The class is here:

<?php

namespace SettingsManager;

/**
 * To ease access of config data
 *
 */
class settingsManager {

    /**
     * Where that data will be held
     * @var array
     */
    private $_data = array();

    /**
     * To speed up access
     * @var array
     */
    private $_cache = array();

    /**
     * To use or not to use the cache (that is the question!!)
     * @var bool
     */
    private $_useCache = true;

    /**
     * Allow the settings to be changed
     * @var bool
     */
    private $_allowChange = false;

    /**
     * Initialize the class and set the settings data
     *
     * @param array $data
     * @param bool $allowChange - Default false
     * @param bool $useCache - Default true
     */
    public function __construct($data, $allowChange = false, $useCache = true) {
        $this->_data = $data;
        $this->_allowChange = $allowChange;
        $this->_useCache = $useCache;
    }

    /**
    * Access the _config property and return specified section
    *
    * @param string $section - Example: section/config
    * @return mixed
    *
    * @throws OutOfBoundsException
    */
    public function get($section) {
        if ($this->_useCache && isset($this->_cache[$section]))
            return $this->_cache[$section];

        return $this->_engine($section);
    }

    /**
     * If allowed this will set the given section to the given value
     *
     * @param string $section
     * @param mixed $value
     * @return mixed
     *
     * @throws OutOfBoundsException
     * @throws TryToChangeImmutableObjectException
     */
    public function set($section, $value) {
        return $this->_engine($section, $value);
    }

    /**
     * Check and see if section exists
     *
     * @param string $section
     * @return bool
     */
    public function exists($section) {
        try {
            $this->get($section);
        }
        catch (\OutOfBoundsException $e) {
            return false;
        }

        return true;
    }

    /**
     * Clear cache
     */
    public function clearCache() {
        $this->_cache = array();
    }

    /**
     * Get/Set a value from the settings property
     *
     * @param string $section
     * @param mixed $value
     * @return mixed
     *
     * @throws \OutOfBoundsException
     * @throws TryToChangeImmutableObjectException
     */
    private function _engine($section, $value = null) {

        if ($value && !$this->_allowChange)
            throw new TryToChangeImmutableObjectException();

        $sections = explode('/',$section);
        $tempSectionData = &$this->_data;

        foreach ($sections as $currentSection) {
            if (!isset($tempSectionData[$currentSection])) {
                throw new \OutOfBoundsException($section . ' - ' . $currentSection);
            }

            $tempSectionData = &$tempSectionData[$currentSection];
        }

        if ($value) {
            $tempSectionData = $value;
            if ($this->_useCache && isset($this->_cache[$section]))
                unset($this->_cache[$section]);
        }

        return $tempSectionData;
    }
}

class TryToChangeImmutableObjectException extends \Exception {}

So a simple use case would be:

<?php

$_testData = array(
        'data' => 1,
        'data2' => array(
            'date3' => 4
            )
    );

$object = new SettingsManager\settingsManager($_testData);

echo $object->get('data2/date3'); //Should echo 4

Any comments or suggestions?


texts:
Wrapper:

internal static class Cache
{
    private static ObjectCache InternalCache
    {
        get
        {
            return MemoryCache.Default;
        }
    }

    private static T CacheOrGetExisting<T>(string key, Func<T> valueFactory)
    {
        T value;
        object uncastedValue = InternalCache.Get(key);

        if (uncastedValue == null)
        {
            value = valueFactory();
            InternalCache.Set(key, value, DateTimeOffset.UtcNow.AddHours(1));
        }
        else
        {
            value = (T)uncastedValue;
        }

        return value;
    }

    public static decimal Foo
    {
        get
        {
            return CacheOrGetExisting("foo", () =>
                {
                    return 5m; // data access here
                });
        }
    }

    public static Bar Bar
    {
        get
        {
            return CacheOrGetExisting("bar", () =>
                {
                    return new Bar(); // data access here
                });
        }
    }
}

Usage in a Controller:

model.Foo = Cache.Foo;

One thing I'm not sure of: is the readonly property necessary for InternalCache or can I write private static ObjectCache InternalCache = MemoryCache.Default;?

I'm not worried about the tiny chance of multiple calls to the same uncached object causing multiple value = valueFactory(); and I'm also not worried about stale data. The main goal is to cache some informational data that is simply displayed on the screen, instead of retrieving it every request.

I've tested this with an expiration of 1 minute and a class that gets DateTime.Now on creation, and it worked fine, so I believe the code is bug-free.


texts:
Inputs are two sorted lists (of the same length) of numbers. I would like to return a new merged, sorted new list. I have written the following code, but most lines are used to deal with the end case. I am wondering if there is any better way to write it.

def merge(array1,array2):
    result = [0]*len(array1)*2

    i = 0 # left index
    j = 0 # right index

    for k in range(0,len(result)):
        # when none of the pointer is at the end of the list
        if i != len(array1)-1 and j != len(array2)-1:
            if array1[i] < array2[j]:
                result[k] = array1[i]
                i = i + 1
            elif array1[i] > array2[j]:
                result[k] = array2[j]
                j = j + 1
        # the following codes are used to deal with the end cases.
        # possible to write it more compactly?
        elif i == len(array1)-1:
            if j > len(array2)-1:
                result[-1] = array1[-1]
                return result
            elif array1[i] < array2[j]:
                result[k] = array1[i]
                result[k+1:] = array2[j:]
                return result
            else:
                result[k] = array2[j]
                j = j + 1
        elif j == len(array2)-1:
            if i > len(array1)-1:
                result[-1] = array2[-1]
            elif array2[j] < array1[i]:
                result[k] = array2[j]
                result[(k+1):] = array1[i:]
                return result
            else:
                result[k] = array1[i]
                i = i + 1

    return result


texts:
I'm very new to the JavaScript, and hence I would like to get a feel on the language by writing some of the basic programs. One of those is the following visualization of the Bubble Sort:

Code:

<!DOCTYPE html>

Bubble sort: visualization

    <button onclick=CreateBarPlot()>Generate data</button>
    <button onclick=bubble_sort()>Sort</button>

To run it, see the JSFiddle

What can be improved?


texts:
Sometimes I download a Python script (from a trusted source), and can't run it because of missing dependencies, which I have to install one by one (no requirements.txt is provided). I'm looking for a way to automate this process. It's similar to this question, but I'd like to infer the requirements automatically. I.e. given the script, install  all the packages it's importing.

If myscript.py looks like:

import pandas
import tensorflow as tf
from keras.models import Sequential

Then after running the script (e.g. bash extract_requirements.sh myscript.py) pandas, tensorflow, and keras will be installed.

Of course, a script can call another script, which has its own dependencies, package names don't always match to import names etc. So it's not a perfect solution, but better than nothing.

What I'm using now is a command-line script:

#!/env bash

set -u

usage() {
    echo "$0" '[-d] <MY_SCRIPT>'
    cat <<-EOF
        options:
        -d    Dry-run. Print package names without installing.
EOF
    exit 1;
}

(( $# == 0 )) && usage
dry=0
if [[ "$1" == '-d' ]]; then
    dry=1
    shift
fi
(( $# != 1 )) && usage

script="$1"
imports1=$(egrep '^\s*from\s+[a-zA-Z_.-]+\simport' "$script" | cut -f2 -d' ' | cut -f1 -d'.')
imports2=$(egrep '^\s*import\s+[a-zA-Z_-]+' "$script" | cut -f2 -d' ')
all=$(printf "$imports1\n$imports2" | sort -u)
if (( dry )); then
    echo "$all" | xargs -L 1 echo
else
    echo "$all" | xargs -L 1 sudo pip install
fi

set +u

I was wondering if I'm missing some import cases, and more importantly, whether there's a simpler, more python-ic, solution.


texts: Multiple regex matches to correct OCR output

texts:
Using OCR, my program reads the current selection for each of these categories: format, invert color? and storage. The OCR result will always have inconsistent error here and there, which is why I need a Regex match and return the correct wording for each selection:

//format
private Regex bmp8 = new Regex(".bmp.8....");
private Regex bmp24 = new Regex(".bmp.24....");
private Regex png24 = new Regex(".png.24....");
private Regex raw = new Regex("raw");
private Regex ts = new Regex("....setup");
private Regex csv = new Regex(".csvd...");

//invert color?
private Regex yes = new Regex("y.s");
private Regex no = new Regex("n.");

//storage
private Regex intrnl = new Regex(".nte...");
private Regex erase = new Regex("e.ase");
private Regex transfer = new Regex("t.ansf.");
private Regex usbdev = new Regex("usbdev.");

private string CheckStorage(string input)
{
    if (intrnl.IsMatch(input))
    {
        return "Internal";
    }

    else if (erase.IsMatch(input))
    {
        return "Erase";
    }

    else if (transfer.IsMatch(input))
    {
        return "Transfer";
    }

    else
    {
        return "USB Device";
    }
}

private string CheckInvertColor(string input)
{
    if (yes.IsMatch(input))
    {
        return "Yes";
    }

    else
    {
        return "No";
    }
}

private string CheckFormat(string input)
{
    if (bmp8.IsMatch(input))
    {
        return "bmp(8-bit)";
    }

    else if (bmp24.IsMatch(input))
    {
        return "bmp(24-bit)";
    }

    else if (png24.IsMatch(input))
    {
        return "png(24-bit)";
    }

    else if (raw.IsMatch(input))
    {
        return "Raw";
    }

    else if (ts.IsMatch(input))
    {
        return "Trace & Setup";
    }

    else
    {
        return "csv Data";
    }
}

I am sure there is a better way to tidy up this code, perhaps using List<>?


texts:
I am using DB::table to search through a table that has a field called 'data' that has a substring "status:None" and replace that substring with "status:".$accepted.  $accepted is a variable that can be either 'Accepted' or 'Denied".  The only way I have been able to get this to work is using a query a foreach loop and another query. I am thinking there has to be a better way of doing this.  I am using DB::table because I am also using Laravel's notification system and one of the tables is named Notification, so when I use Notification::where() I get an error message because Laravel does not know which Notification to use.

I am thinking there is a way in one query to replace substring in the data field with the change to status, but have been able to figure it out.

$notifications = DB::table('notifications')
            ->where('notifiable_id', '=', Auth::user()->id)
            ->where('data', 'Like', '%"status":"None"%')
            ->get();
        foreach ($notifications as $notification){
            //todo change string to accept or reject
            if (strpos($notification->data, 'status') !== false) {
                $newString = str_replace('"status":"None"', 'status:'.$accepted, $notification->data);
                DB::table('notifications')
                    ->where('notifiable_id', '=', Auth::user()->id)
                    ->where('data', 'Like', '%"status":"None"%')
                    ->update(['data' => $newString]);
            }
        }


texts: Bubble, selection, and insertion sorting

texts:
The following programs are bubble sorting, selection sorting and insertion sorting. As most of the programs online or in books are with Arrays and not ArrayList, I am unsure if they are correct.

BubbleSort:

    public class BubbleSort {

      List<Integer> unsortedList;

      private BubbleSort() {
        unsortedList = new ArrayList<Integer>();
        unsortedList.add(0, 6);
        unsortedList.add(1, 3);
        unsortedList.add(2, 7);
        unsortedList.add(3, 4);
        unsortedList.add(4, 2);
        unsortedList.add(5, 3);
        unsortedList.add(6, 8);
    }

    private void sortData() {
        ArrayList<Integer> tempList = (ArrayList<Integer>) this.unsortedList;
        int size = unsortedList.size();
        int counter = size;
        do {

            for (int i = 0; i < size-1; i++) {

                if (unsortedList.get(i) > unsortedList.get(i + 1)) {

                    Integer temp1= unsortedList.get(i + 1);
                    Integer temp2= unsortedList.get(i);
                    unsortedList.set(i,temp1);
                    unsortedList.set(i+1,temp2);

                }
            }
            size = size - 1;
        } while (size != 1);
    }

    public static void main(String arg[]) {

        BubbleSort obj = new BubbleSort();
        obj.sortData();

        for(Integer i:obj.unsortedList){
            System.out.println(i);
        }
    }}

SelectionSort:

    public class SelectionSort {

    List<Integer> unsortedList;

    private SelectionSort() {
        unsortedList = new ArrayList<Integer>();
        unsortedList.add(0, 16);
        unsortedList.add(1, 3);
        unsortedList.add(2, 7);
        unsortedList.add(3, 4);
        unsortedList.add(4, 12);
        unsortedList.add(5, 3);
        unsortedList.add(6, 8);
        unsortedList.add(7, 18);
        unsortedList.add(8, 81);
        unsortedList.add(9, 2);
    }

    public void sortData() {

    int totalPass = unsortedList.size();
    int listLength = totalPass;

    for (int i = 0; i <= totalPass - 1; i++) {
        int pointerSmallPosition=i;
        for (int j = i; j < listLength-1; j++) {

            if (unsortedList.get(pointerSmallPosition) > unsortedList.get(j + 1)) {
                pointerSmallPosition=j + 1;
            }
        }

        int temp1= unsortedList.get(i);
        int temp2= unsortedList.get(pointerSmallPosition);
        unsortedList.set(i,temp2);
        unsortedList.set(pointerSmallPosition,temp1);
    }

}

public static void main(String arg[]) {

    SelectionSort obj = new SelectionSort();
    obj.sortData();

    for (Integer i : obj.unsortedList) {
        System.out.println(i);
    }
}}

InsertionSort:

 public class InsertionSort {

    List<Integer> unsortedList;

    public InsertionSort(){
        unsortedList = new ArrayList<Integer>();
        unsortedList.add(0, 6);
        unsortedList.add(1, 3);
        unsortedList.add(2, 7);
        unsortedList.add(3, 4);
        unsortedList.add(4, 2);
        unsortedList.add(5, 3);
        unsortedList.add(6, 8);
    }

    public static void main(String arg[]){

        InsertionSort obj=new InsertionSort();
        obj.sortData();

        for(Integer i:obj.unsortedList){
            System.out.println(i);
        }

    }

    private void sortData() {

        int size = unsortedList.size();
        int sortedSize=0;
        for(int i=1;i<size-1;i++){
            int j=i;
            do{
                if(unsortedList.get(j)<unsortedList.get(j-1)){
                    int small=unsortedList.get(j);
                    int large=unsortedList.get(j-1);
                    unsortedList.set(j-1, small);
                    unsortedList.set(j, large);
                }
                j--;
            }while(j>sortedSize);

        }}}


texts: Create a dictionary which saves its data to file

texts:
Task:

The task requires creating a class (say, ConfigDict) which inherits from the dict class.

It is supposed to save its keys and values in a file.
If a file does not exist, the instance of ConfigDict should be able to create it.

Examples:

For instance, the following code:

fh=open("config.txt","w")
fh.write("key1 = 5\n")
fh.write("key2 = 3\n")
fh.close()
cd=ConfigDict("config.txt")
cd.items()

would generate an output dict_items([('key1', '5'), ('key2', '3')]).

If a file does not exists, it should be possible for the instance to create it and save its data inside it.

dd=ConfigDict("test.txt")
dd["keyA"] = 'testA'
dd["keyB"] = 'testB'
dd.items()

The above lines would produce dict_items([('keyA', 'testA'), ('keyB', 'testB')]) (and a print message).

My attempt:

I will greatly appreciate any comments.

class ConfigDict(dict):
    def __init__(self,file):
        self.file = file

        try: #check if file exists
            with open(self.file,"r+") as fh:
                for line in fh:
                    key, item = line.replace(" ", "").rstrip().split("=")
                    dict.__setitem__(self,key,item)

        except:
            print("creating "+file)
            fh=open(self.file,"w")
            fh.close()

    def __setitem__(self,key,item):
        dict.__setitem__(self,key,item) #to avoid infinite loop
        lines = open(self.file).read().splitlines()

        for index, line in enumerate(lines):
            if line.replace(" ", "").rstrip().split("=")[0] == key:
               lines[index] = str(key)+" = "+str(item)
            else:
                lines.append(str(key)+" = "+str(item))

        open(self.file,'w').write('\n'.join(lines))

Corrected version

import os

class ConfigDict(dict):
    def __init__(self,file):
        self.file = file
        if os.path.isfile(self.file):
            with open(self.file,"r") as fh:
                for line in fh:
                    key, item = line.replace(" ", "").rstrip().split("=")
                    dict.__setitem__(self,key,item)

    def __setitem__(self,key,item):
        dict.__setitem__(self,key,item)
        with open(self.file, 'w') as save_file:
            for key, value in self.items():
                save_file.write("{} = {}\n".format(key, value))


texts:
I implemented merge sort with C++ and would like to get some feedback.
#include <iterator>
#include <vector>

template<typename It>
std::vector<typename It::value_type> merge(const It begin, const It mid, const It end)
{
    std::vector<typename It::value_type> v;
    It it_l{ begin }, it_r{ mid };
    const It it_mid{ mid }, it_end{ end };

    while (it_l != it_mid && it_r != it_end)
    {
        v.push_back((*it_l <= *it_r) ? *it_l++ : *it_r++);
    }

    v.insert(v.end(), it_l, it_mid);
    v.insert(v.end(), it_r, it_end);

    return std::move(v);
}

template<typename It>
void merge_sort(It begin, It end)
{
    auto size = std::distance(begin, end);
    if (size < 2)
        return;

    auto mid = std::next(begin, size / 2);
    merge_sort(begin, mid);
    merge_sort(mid, end);

    auto &&v = merge(begin, mid, end);
    std::move(v.cbegin(), v.cend(), begin);
}

Usage:
std::vector<int> v{ 8, 4, 1, 9, 16, 3 };
merge_sort(v.begin(), v.end());

Is there anything I should avoid? Any mistakes in the algorithm or implementation? It should work with other containers (e.g. std::list) as well.


texts:
I'm new to Rails/Ruby and I would like to get feedback on my little ApplicationController which is able to detect the visitor's language. I'm especially interested in optimizations on the control structure in the set_locale method (2 nested if statements and 3 assignments to one variable). I'm using the http_accept_language gem.

class ApplicationController < ActionController::Base
  AVAILABLE_LANGUAGES = %w{de en}

  before_filter :set_locale
  protect_from_forgery

  def set_locale
    if params[:locale].nil?
      if preferred_language = request.preferred_language_from(AVAILABLE_LANGUAGES)
        I18n.locale = preferred_language
      else
        I18n.locale = I18n.default_locale
      end
    else
      I18n.locale = params[:locale]
    end
  end

  def default_url_options(options={})
    logger.debug "default_url_options is passed options: #{options.inspect}\n"
    { :locale => I18n.locale }
  end
end


texts: Identifying array elements, rearranging them, and replacing them

texts:
I am completing the CodingBat exercises for Java, and, having learnt from the answers to the previous one, I completed the one that follows:

  Return a version of the given array where all the 10s have been removed. The remaining elements should shift left towards the start of the array as needed, and the empty spaces a the end of the array should be 0. So {1, 10, 10, 2} yields {1, 2, 0, 0}. You may modify and return the given array or make a new array.

Here is my code:

public int[] withoutTen(int[] nums) {

    int slow = 0;

    for (int fast = 0; fast < nums.length; fast++) {
        if (nums[fast] != 10) {
            nums[slow] = nums[fast];
            slow++;
        }
        if (fast == nums.length-1) {
            for (int i = fast; i >= slow; i--) {
                nums[i] = 0;
            }
        }
    }
    return nums;

}

Please bear in mind I am doing these without importing anything extra like java.util.Arrays etc., as, primarily, this is not accepted by the assessor and, secondarily, I want to get to grips with arrays without importing anything extra yet.

I was taking influence from the comments I received on the previous question, by using a fast and slow variable for looping through the array, and limiting the code to one main for loop, for the sake of making my code generally better and putting efficiency into practice.

How could this be optimised? Is it ok to begin another loop only for the circumstance of fast reaching the last element in the array? It feels like I am repeating myself by saying "if we get to the last element..." because we absolutely will do anyway.

I played around with setting fast outside the loops, so that the second for loop can begin after the first (as opposed to nesting it). At that point, fast would be set to the last value anyway from having completed the previous loop, but more and more values would be set outside the loops. Which way makes more sense?


texts:
Haskell newbie here. Wanted to improve my skills by re-implementing an esolang I designed back in 2011 called TinCan. If there are things that are perhaps badly coded or unclear things due to my inexperience with the language then I would love to know about them so I can move forward in my Haskell usage.

{-# LANGUAGE OverloadedStrings #-}

import qualified Data.Text as T
import Text.Read
import Data.Char
import Data.Map (Map)
import qualified Data.Map as Map

data Token = Dollar | At | Ampersand | Variable Char | Value Int deriving (Eq, Show)

data Program = Program { program :: [(Token, Token, Token)]
                       , len :: Int
                       , currentLine :: Int
                       , pc :: Int
                       , stack :: [Int]
                       , executionFinished :: Bool
                       , variables :: Map Char Int
                       } deriving (Show)

stripLines :: [String] -> [String]
stripLines = filter (\x -> ((==40) . length) x && (head x == '#') && (last x == '#'))

removeHash :: String -> String
removeHash = filter (/='#')

toToken :: String -> Token
toToken t = case readMaybe t :: Maybe Int of
    Just i -> Value i
    Nothing -> if (length t == 1 && (t !! 0) `elem` ['A'..'Z'])
               then Variable (t !! 0)
               else (case t of
                    "$" -> Dollar
                    "@" -> At
                    "&" -> Ampersand
                    _ -> error ("Could not parse '" ++ t ++ "'"))

clean :: T.Text -> Token
clean = toToken . T.unpack . T.strip

tokenize [x,y,z] = (clean x, clean y, clean z)
tokenize _ = error "Could not tokenize"

tokenizeLine :: String -> (Token, Token, Token)
tokenizeLine line = if (size == 3) then (tokenize split) else (error line)
    where size = length split
          split = T.splitOn "," (T.pack line)

getVariable :: Program -> Char -> Int
getVariable p = ((variables p) Map.!)

tokenToInt :: Program -> Token -> Int
tokenToInt p t = case t of
    Dollar -> currentLine p
    At -> pc p
    Ampersand -> currentLine p + 1
    Variable c -> getVariable p c
    Value i -> i

updateVariable :: Program -> Char -> Int -> Program
updateVariable p c i = p { variables = Map.insert c i (variables p) }

jump :: Int -> Program -> Program
jump i p
    | i >= len p || i < 0 = p { currentLine = i, executionFinished = True }
    | otherwise = p { currentLine = i }

push :: Int -> Program -> Program
push i p = p { stack = i : stack p }

executeLine :: Program -> (Token, Token, Token) -> Program
executeLine p (a,(Variable b),c) =
    if pushToStack
    then jump (currentLine p + 1) $ push diff $ updateVariable p b diff
    else if diff <= 0
         then jump address $ updateVariable p b diff
         else jump (currentLine p + 1) $ updateVariable p b diff
            where diff = value - differential
                  differential = tokenToInt p a
                  value = getVariable p b
                  pushToStack = address == -1
                  address = tokenToInt p c
executeLine _ _ = error "Could not execute line."

executeProgram :: Program -> Program
executeProgram p = executeLine p line
    where line = program p !! currentLine p

generateProgram :: [String] -> Program
generateProgram xxs = Program (map tokenizeLine xxs) (length xxs) 0 0 [] False (Map.fromList $ zip ['A'..'Z'] (repeat 0))

main = readFile "countdown.txt" >>= putStrLn . reverse . map chr . stack . until executionFinished executeProgram . generateProgram . map removeHash . stripLines . lines


texts: Conversion from RGB to CIELAB with a complex formula

texts:
let deltaF: TransformBlock = { f in
        let transformation = (f > pow((6.0/29.0), 3.0)) ? pow(f, 1.0/3.0) : (1/3) * pow((29.0/6.0), 2.0) * f + 4/29.0

        return (transformation)
    }

Says here that this expression is too complex to be solved in reasonable time. Is there any way to simplify it?

This code is meant to convert RGB colors into CIELAB colors. I've done some research online and couldn't find an updated version of that code.

func CIE_LAB() -> (l: CGFloat, a: CGFloat, b: CGFloat, alpha: CGFloat) {
    // Get XYZ
    let xyzT = xyz()
    let x = xyzT.x/95.047
    let y = xyzT.y/100.000
    let z = xyzT.z/108.883

    // Transfrom XYZ to L*a*b
    let deltaF: TransformBlock = { f in
        let transformation = (f > pow((6.0/29.0), 3.0)) ? pow(f, 1.0/3.0) : (1/3) * pow((29.0/6.0), 2.0) * f + 4/29.0

        return (transformation)
    }
    let X = deltaF(x)
    let Y = deltaF(y)
    let Z = deltaF(z)
    let L = 116*Y - 16
    let a = 500 * (X - Y)
    let b = 200 * (Y - Z)

    return (L, a, b, xyzT.alpha)
}


texts: PHP / Laravel - Using Python to image manipulation

texts:
I have a simple job class in Laravel, that:

Get all the images in a folder /original
Perform some image manipulation on each image
Save each image in a new folder /preprocessed

All of these steps are added to a queue.

However, I have taken an alternative approach and is using python to do the actual image manipulation

This is my code:

$images = Storage::allFiles($this->document->path('original'));

foreach ($images as $key => $image) {
    $file = storage_path() . '/app/' . $image; //token/unique_id/original/1.jpg
    $savePath = storage_path() . '/app/' . $this->document->path('preprocessed');

    $filename = $key . '.jpg';

    //Scale and save the image in "/preprocessed"
    $process = new Process("python3 /Python/ScaleImage.py {$file} {$savePath} {$filename}");
    $process->run();

    // executes after the command finishes
    if (!$process->isSuccessful()) {
        throw new ProcessFailedException($process);
        return false;
    }
}

In my python file ScaleImage.py, I simply perform some image manipulation and saves the image to the /preprocessed folder.

    def set_image_dpi(file)

        //Image manipulation - removed from example

        //save image in /preprocessed
        im.save(SAVE_PATH + FILE_NAME, dpi=(300, 300))

        return SAVE_PATH + FILE_NAME

    print(set_image_dpi(FILE_PATH))

Above code works.

In the future, I might need to do even more image manipulation such as (noise removal, skew correction, etc.)

My final goal is to use Tesseract OCR on the preprocessed image to grap the text content of the image.

Now I am sure I could achieve similar stuff with for example ImageMagick  in PHP.

However, I've read the for image processing and OCR, Python's performance is a lot better.

Is above approach a good idea? Anything that can be improved?


texts: Parsing XML with double nested tags using mindom

texts:
I want to retrieve id and name per skill. It works but is it well done? I would like to stay with minidom but all advices will be appreciated.

# This is only part of XML that interesting me:
# <skill>
#   <id>14</id>
#   <skill>
#     <name>C++</name>
#   </skill>
# </skill>
# <skill>
#   <id>15</id>
#   <skill>
#     <name>Java</name>
#   </skill>
# </skill>

skills = document.getElementsByTagName('skill')

for skill in skills:
    try:
        id_ = skill.getElementsByTagName('id')[0].firstChild.nodeValue
        name = skill.getElementsByTagName('name')[0].firstChild.nodeValue

        my_object.create(name=name.strip(),
                         id=id_.strip())
    except IndexError:
        pass


texts: A Brushfire algorithm to generate a distance map in a grid

texts:
I'm working on implementing a goal-based pathfinding.
first step is to set a goal and calculate the shortest walkable distance between the goal and all points in the grid, using a brushfire algorithm.

I'm worried about two things here, readability and efficiency, since this is for an RTS game.

    int[] GenerateHeatMap(IGrid grid, GridPoint goal)
    {
        var heatMap = new int[grid.Cells.Length];
        var unexploredPoints = new List<GridPoint>();
        var openPoints = new List<GridPoint>();
        for (int i = 0; i < grid.Width; i++)
        {
            for (int j = 0; j < grid.Height; j++)
            {
                unexploredPoints.Add(new GridPoint(i, j));
            }
        }

        var currentDistance = 0;
        heatMap[grid.IndexOf(goal)] = currentDistance;
        openPoints.Add(goal);
        unexploredPoints.Remove(goal);
        while (openPoints.Count > 0)
        {
            currentDistance++;
            var newOpenPoints = new List<GridPoint>();
            foreach (var currentPoint in openPoints)
            {
                for (int i = -1; i < 2; i++)
                {
                    for (int j = -1; j < 2; j++)
                    {
                        var point = new GridPoint(currentPoint.x + i, currentPoint.y + j);
                        if ((i == 0 && j == 0) || !unexploredPoints.Contains(point) || newOpenPoints.Contains(point) || !grid.PointToCell(point).CanCross) continue;
                        heatMap[grid.IndexOf(point)] = currentDistance;
                        newOpenPoints.Add(point);
                        unexploredPoints.Remove(point);
                    }
                }
            }
            openPoints.Clear();
            openPoints.AddRange(newOpenPoints);
        }
        return heatMap;
    }

For clarity here the definition of GridPoint

public struct GridPoint
{
    public GridPoint(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
    public readonly int x;
    public readonly int y;
}

What can I do to improve this?


texts: Selecting element from a collection based on bitwise-and result

texts:
I need to improve this section of code:

    uint32_t to_handle = 0;
    uint32_t test_const1 = Constraint3::VAL1 + Constraint3::VAL2;
    uint32_t test_const2 = Constraint1::VAL2 + Constraint1::VAL4 + Constraint1::VAL8;
    uint32_t test_const3 = Constraint2::VAL1 +  Constraint2::VAL2 + Constraint2::VAL4;

    to_handle = test_const1;

    for(ConstraintsContainer_t::iterator it = constraints_.begin(); it != constraints_.end(); ++it) {
        if( ( ((*it).get() & to_handle) == (*it).get() ) &&
                ( ((*it).get() & test_const2) == (*it).get() ) &&
                ( ((*it).get() & test_const3) == (*it).get() ) ) {
            choosen_.push_back((*it));
            to_handle -= (*it).get();
        }
    }

Here are declarations:

    namespace Constraint1 {
    typedef enum {
        NONE            = 0x00000000,
        VAL1            = 0x00000001,
        VAL2            = 0x00000002,
        VAL4            = 0x00000004,
        VAL8            = 0x00000008,
        ALL             = 0xFFFFFFFF
    } Type;
    }
    namespace Constraint2 {
    typedef enum {
        NONE            = 0x00000000,
        VAL1            = 0x00000001,
        VAL2            = 0x00000002,
        VAL4            = 0x00000004,
        VAL8            = 0x00000008,
        ALL             = 0xFFFFFFFF
    } Type;
    }
    namespace Constraint3 {
    typedef enum {
        NONE            = 0x00000000,
        VAL1            = 0x00000001,
        VAL2            = 0x00000002,
        VAL4            = 0x00000004,
        VAL8            = 0x00000008,
        VAL16           = 0x00000010,
        VAL32           = 0x00000020,
        ALL             = 0xFFFFFFFF
    } Type;
    }
    typedef std::vector  > ConstraintsContainer_t;
    ConstraintsContainer_t constraints_;
    ConstraintsContainer_t choosen_;

The goal is to select elements from a collection by performing a bitwise-and on them.

Order of insertion in that vector matters and number of element should reach about 100. It's currently taking about 50 microseconds to complete this section of codes, I'd need to make it 10-20 microseconds if possible.

Here is the source code on a live workspace if it helps:
http://coliru.stacked-crooked.com/view?id=356a9d8c94bddf6721f98bbc44c74fec-71380fc8ea55c1ab9f744d79fff5379c

I've tryed to use boost multi_index_containers, but it'd require to get this to work:
https://stackoverflow.com/questions/16101886/boost-multi-index-container-with-composite-key-and-logical-and-comparison

Any help is appreciated!


texts: Get the total counted stock take lines for each hour between two dates

texts:
I have the following table structure:

Tables

stocktakebinline
stocktakebinlinebatch

A stocktakebinline has a one to many relationship with stocktakebinlinebatch. A line consists of many batches.

Columns

stocktakebinline

lineid | reference
-------+----------
1      | Product A
2      | Product B
3      | Product C

stocktakebinlinebatch

id | lineid | batchnumber | instock | countedstocklevel | counteddate
---+--------+-------------+---------+-------------------+------------
1  | 1      | Batch A     | 3.0     | null              | null
2  | 1      | Batch B     | 1.0     | 5.0               | 2017-02-15 10:14
3  | 2      | Batch C     | 2.0     | 2.0               | 2017-02-15 11:30
4  | 2      | Batch D     | 0.0     | 0.0               | 2017-02-15 11:31
5  | 2      | Batch E     | 6.0     | null              | null
6  | 3      | Batch F     | 5.0     | 5.0               | 2017-02-15 13:58

I have omitted some columns for brevity. Also, the date fields are valid psql  dates and are not strings, I have just written them that way so they are easier to read.

I am trying to calculate how many lines have been counted every hour from a given start date to now. The output will look like this:

counted | date
--------+--------
0       | 2017-02-15 09:00
1       | 2017-02-15 10:00
1       | 2017-02-15 11:00
0       | 2017-02-15 12:00
1       | 2017-02-15 13:00
0       | 2017-02-15 14:00

A line is considered counted if any of it's batches have been counted.

To achieve this, I have written the following query:

with tempCountedHours as
(
    select
        count(*) as counted,
        b.date
    from stocktakebinline l
    join
    (
        --Gets minutes and how many where counted in that hour for all lines.
        select
            lineid,
            date_trunc('hour', counteddate) as date
        from stocktakebinlinebatch
        where
            --Where the stock level is over 0 or if it is 0,
            --then only zero stocks that have been counted.
            counteddate is not null
            and (instock > 0 or (instock = 0 and countedstocklevel > 0))
        group by
            lineid,
            date_trunc('hour', counteddate)
    ) b on l.id = b.lineid
    group by
        b.date
    order by
        b.date asc
)
select
    *
from tempCountedHours
union
(
    select
        0 as counted,
        d.date
    from
    (
        --Get all of the hours between the created date of the stock take
        --and right now, except those that were counted.
        select
            date_trunc('hour', d) as date
        from generate_series(
            '2017-02-15 09:00',
            now(),
            '1 hour'::interval
        ) d
        except
        select date from tempCountedHours
    ) d
)
order by
    date asc;

To try and make some sense of this, I am using the following logic:

Get all of the hours where a line has been counted (and how many have been counted).
Get all of the hours between the two dates and exclude ones which have lines that are counted
In the end, union the two data sets and show 0 counted for hours that have not been counted and display the counted amount for hours that have been counted.

This query works fine, however it's quite large. Is there a way I can simplify this query?


texts: Get missing letters - TopCoder challenge

texts:
I'm working on a TopCoder problem which seeks to find the letters preventing an input sentence from being a pangram in all caps, alphabetical order.

MissingLetters.h

#ifndef _MISSING_LETTERS_H_
#define _MISSING_LETTERS_H_

#include <string>
#include <set>
#include <utility>

class MissingLetters {
  public:
    MissingLetters() {}
    std::string getMissingLetters(std::string sentence);
};

// Find the difference between two sets, set(lowercase(sentence)) & set([a-z])

std::string MissingLetters::getMissingLetters(std::string sentence) {
   std::set<char> sentence_set;
   std::string missing_letters = "";

   // Put each letter in the sentence into a set, O(n log n)
   for(size_t i = 0; i < sentence.size(); ++i) {
      sentence_set.insert(toupper(sentence[i]));
   }

   // For each letter [A-Z], add letters that aren't in the set, O(1)
   for(char letter='A'; letter <= 'Z'; ++letter) {

      if(sentence_set.find(letter) == sentence_set.end()) {
         missing_letters+=letter;
      }
   }

   return missing_letters;
}

#endif // _MISSING_LETTERS_H_

I'd like this to be as fast as possible. My method, getMissingLetters is currently \$O(n \log{n})\$ running-time, where \$n\$ is the length of the the sentence.

Any other implementations, including different data structures, would be great if they're faster.

Any tips?


texts: Averaging outputs of each execution of a file

texts:
The only way I could think of doing this is creating a text file and modifying it each time the program is executed and outputting the average but this has many flaws so I was wondering if it was possible to do this any other way.

int num1, num2, counter = 0;
num2 = rand();
do {
cin >> num1;
counter++;
} while(num1 != num2)

const char *path = "C:/Users/Edsheeran/AppData/Roaming/times.txt";
double x = 0;
double sum = 0;
vector<double> times;

ofstream write(path, ios::app);
if(write.is_open()) {
write << counter << endl;
};
write.close();

ifstream file(path, ios::app);
if(file.is_open())
{
    while (!file.eof()) {
        file >> x;
        times.push_back(x);
    }
}
else exit(EXIT_FAILURE);
file.close();

for (unsigned int i = 0 ; i < times.size(); i++) {
sum += times[i];
}

cout << "Your average tries to find the number is: " << sum / times.size()   << endl;


texts:
For a project I created a more detailed last row finder which looks at more than one column.

Could you provide any feed back on the code below.

Function lColCount(ws As Worksheet, Optional iWhichRow As Integer = 1) As Long
Dim sMaxCol As String
sMaxCol = Cells(iWhichRow, ws.Columns.Count).Address
lColCount = ws.Range(sMaxCol).End(xlToLeft).Column
Function`

Function lRowCount(ws As Worksheet, Optional iWhichCol As Integer = 1) As Long
Dim sMaxRow As String
sMaxRow = Cells(ws.Rows.Count, iWhichCol).Address
lRowCount = ws.Range(sMaxRow).End(xlUp).Row
End Function

Function Col_Letter(lngCol As Long) As String
Dim vArr
vArr = Split(Cells(1, lngCol).Address(True, False), "$")
Col_Letter = vArr(0)
End Function`

Sub findLast()
Dim LC As Long
Dim LR As Long
Dim LCa As String
Dim ws As Worksheet
Dim i As Integer
Dim arr() As Variant
'Assigns ws = sheet1
Set ws = Sheet1
'Sets LC = to the last column number of default row 1
LC = lColCount(ws)
'I counter = 1
i = 1
'Defines array as 1 to the last column number
ReDim arr(1 To LC)
'Loops untill I = Last column counter + 1
Do While i <> LC + 1
'Sets Lr to last row of the looping column i
LR = lRowCount(ws, i)
'Sets last row to arr(I) value loop
arr(i) = LR
'Adds 1 to I ready for next loop
i = i + 1
Loop
'Finds maximum value in array and uses that as last row
LR = Application.WorksheetFunction.Max(arr())
'Use to check the array value in the Immediate window
Dim Res As Variant
For Each Res In arr()
Debug.Print Res
Next Res
'Col_letter function finds the letter of the column number
LCa = Col_Letter(LC)
'copies range A1 sheet1 and all data to sheet2
ws.Range("A1:" & LCa & LR).Copy Sheet2.Range("A1")
End Sub


texts: Follow-up: How can we optimizing Java BigInteger operations?

texts:
This is the follow up question of How can we optimizing Java BigInteger operations?
Problem
Reduce the number to 1 in a minimal number of steps, following the rules:
If the number is even, divide it by 2.
Otherwise, increment or decrement it by 1.

Limit: s can be up to 309 digits long.
Solution
The solution I have come up with is below:
import java.math.BigInteger;

public class Solution {

    public static int solution(String s) {
        BigInteger n = new BigInteger(s);

        if ( isPrimitive(n) ) {
            return longOps(0, n.longValue());
        }

        return bigIntOps(n);
    }

    public static int bigIntOps(BigInteger n) {
        BigInteger one = BigInteger.ONE;
        BigInteger two = BigInteger.TWO;
        BigInteger four = new BigInteger("4");
        int count = 0;

        while (n.compareTo(one) == 1) {
            count++;

            if( n.and(one).byteValue() == 0 ){
                n = n.shiftRight(1);

                if ( isPrimitive(n) )
                    return longOps(count, n.longValue());

            } else if ( n.byteValue() == 3 || n.mod(four).byteValue() == 1)
                n = n.subtract(one);
            else
                n = n.add(one);
        }

        return count;
    }

    public static int longOps(int count, long n) {

        while (n > 1) {
            count++;

            // If number is divisible by 2
            if ( (n & 1) == 0 ) {

                // Check if the number is power of two
                if ((n&(n-1)) == 0)
                    return (int)Math.ceil(Math.log(n)/Math.log(2)) + count - 1;
                else
                    n = n >> 1;// Binary Division

            } else if ( n == 3 || n%4 == 1 )
                n--;
            else
                n++;
        }

        return count;
    }

    public static boolean isPrimitive(BigInteger n) {
        return n.compareTo(new BigInteger(String.valueOf(Long.MAX_VALUE))) < 0;
    }

}

Just some note from the source I collect:
"From the research, BigInteger operations are memory intensive and hence slow. Hence, the processing was divided into BigInteger processing and long processing.
A check was made at first to see if the number is long, and the processing was divided based on the number.
Check was also made in the BigInteger processing to check if the remainder was a long, and if true, further processing was done for long processing.
I found a sweet math solution to find the 2 power of number:
Math.ceil(Math.log(x)/Math.log(2))
This solution provided a single statement to find the number of steps.
Unfortunately BigInteger does not provide Math.log() functionality so this could not be implemented which could have been a great solution."

https://github.com/JavaCheatsheet/codechallenge/blob/master/src/google/Level3/Part3/README.md


texts:
This post is the result of reading through and following the LOLCODE Specification 1.2 ("smoking the manual", right?), and writing and executing my code on compileonline.com.

My "hello world" was going to be a fizzbuzz. I like it because it nicely illustrates the basics of a language - variables, operators, looping, conditionals, and the likes.

As far as naming goes, the specification allows for a wide variety, so I decided to go PascalCase all the way, so as to ease up the reading a bit - otherwise the language is a bit harsh on the eyes, to say the least.

I'm curious about how idiomatic my code is - this is my very first and probably last lolcode program. Did I overlook language constructs that would help readability? How's naming? Indentation? Any issues?

HAI 1.2

    I HAS A Fizz ITZ 3
    I HAS A Buzz ITZ 5

    IM IN YR FrootLoopz UPPIN YR Frootz TIL BOTH SAEM Frootz AN 100
      BTW Frootz runs 0 through 99

      I HAS A Froot ITZ SUM OF Frootz AN 1
        BTW Froot will run 1 through 100

      BOTH SAEM 0 AN MOD OF Froot AN PRODUKT OF Fizz AN Buzz
      O RLY?
        YA RLY
          Froot R "FizzBuzz"
        NO WAI
          BOTH SAEM 0 AN MOD OF Froot AN Fizz
          O RLY?
            YA RLY
              Froot R "Fizz"
            NO WAI
              BOTH SAEM 0 AN MOD OF Froot AN Buzz
              O RLY?
                YA RLY
                  Froot R "Buzz"
              OIC
          OIC
      OIC

      VISIBLE Froot

    IM OUTTA YR FrootLoopz

    VISIBLE "DOWN WITH FIZZBUZZ LOL"

KTHXBYE


texts: Dice roll game that generates random number

texts:
I just want to know how efficient is my code and is there any better way to do the same program in C?
Can the if statements are replaced with something else or can I merge the two loops together to get roll1 and roll2 within a single loop?

Also if there is any more tricks or things that I could have added to the program to make it more interesting. Also after reading my code, what mistake you think I am making while writing the code or what can I improve to write more efficient programs, things I should keep in mind.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <windows.h>
#include <time.h>

int main()
{
    srand(time(NULL));
    int i, roll1=0, roll2=0, NumberOfRolls, RandomNUM1[50], RandomNUM2[50];
    char nextGuess;

    puts("Welcome to the Dice Roll Game");
    puts("How many times do you want to roll a dice?");
    scanf("%d", &NumberOfRolls);

    for( i=0; i<NumberOfRolls; i++ ) {
        RandomNUM1[i] = ( rand()%6 ) + 1;
        roll1 += RandomNUM1[i];
    }

    printf("\nYou Got %d in your first roll!\n", roll1);
    Sleep(3000);
    printf("\nLet's see if you can guess the value of next roll.\n");
    printf("Will it be Higher/Lower or the same? (press H/L/S)\n");
    scanf(" %c", &nextGuess);
    nextGuess = toupper(nextGuess);

        for( i=0; i<NumberOfRolls; i++ ) {
        RandomNUM2[i] = ( rand()%6 ) + 1;
        roll2 += RandomNUM2[i];
    }

    if(nextGuess=='H'){
        if(roll1<roll2){
            printf("\nYou are such a player, you guessed it right! It's %d", roll2);
        }
        else if(roll1>roll2){
            printf("\nUh-Oh! Bad Luck! First roll was higher, It's %d", roll2);
        }
        else if(roll1==roll2){
            printf("\nUh-Oh! Bad Luck! Both the rolls are same, It's %d", roll2);
        }
    }

    if(nextGuess=='L'){
        if(roll1>roll2){
            printf("\nYou are such a player, you guessed it right! It's %d", roll2);
        }
        else if(roll1<roll2){
            printf("\nUh-Oh! Bad Luck! First roll was lower, It's %d", roll2);
        }
        else if(roll1==roll2){
            printf("\nUh-Oh! Bad Luck! Both the rolls are same, It's %d", roll2);
        }

    }

    if(nextGuess=='S'){
        if(roll1==roll2){
            printf("\nYou are such a player, you guessed it right! It's %d", roll2);
        }
        else if(roll1>roll2){
            printf("\nUh-Oh! Bad Luck! First roll was higher, It's %d", roll2);
        }
        else if(roll1<roll2){
            printf("\nUh-Oh! Bad Luck! Second roll is higher, It's %d", roll2);
        }
    }

    if( (nextGuess!='H') && (nextGuess!='L') && (nextGuess!='S') ){
            printf("\nYour input is invalid. Please enter H/L/S");
        }

    return 0;
}


texts:
I'm currently working on writing a date checker function in C and wondering how it can be improved upon.

  Q: Write a function that is passed a month, day, and year and will
  determine if that date is valid. You can assume each parameter is passed in as an
  integer.  Remember to check for leap year.

I currently have this and want to see if there are any beginner mistakes, if pointers could improve efficiency or redundancies in my code.

#include <stdio.h>
#include <stdbool.h>
bool is_valid_date(int month,int day ,int year) {
    //Validate year
    int days_on_month[]={31,28,31,30,31,30,31,31,30,31,30};
    if(year<0||year>2017) {
        //year not valid , stop validation , date is invalid
        return false;
    }
    bool isLeapYear;
    //Check for leap year , every 4 years there is a leap year
    if(year%4==0) {
        //if year is evenly divisble by 100 it must also be by 400
        if(year%100==0) {
            if(year%400==0) {
                isLeapYear=true;
            }else{
                isLeapYear=false;
            }
        }else{
            isLeapYear=true;
        }
    }
    //Validate months;
    if(month<1||month>12) {
        // not valid , stop validation , date is invalid
        return false;
    }
    //validate day
    if(month!=2) {
        //Valid Date
        if(day>=1&&day<=days_on_month[month-1]){return true;}
    }
    //February (changes no of days on leap year)
    else
    {
        if(isLeapYear) {
            if(day>=1&&day<=29){return true;}
        }else{
        if(day>=1&&day<=28){return false;}
        }
    }
    return false;
}

// test if function works
int main(void) {
    int day = 28;
    int month = 12;
    int year = 2012;
    printf("Is it true? Yes = 1 No = 0! = %d\n", is_valid_date(day, month, year));
    return 0;
}


texts: SICP - exercise 1.12 - pascal's triangle

texts:
From SICP:

Exercise 1.12: The following pattern of numbers is called Pascal’s triangle.

         1
       1   1
     1   2   1
   1   3   3   1
 1   4   6   4   1
       . . .

The numbers at the edge of the triangle are all 1, and each number inside the triangle is the sum of the two numbers above it. Write a procedure that computes elements of Pascal’s triangle by means of a recursive process.

Here is my code:

(define (pascals-triangle row col)
  ;; "The numbers at the edge of the triangle are all 1"
  (if (or (= col 0) (= col row))
      1
      (+ (pascals-triangle (- row 1)
                            (- col 1))
          (pascals-triangle (- row 1)
                            col))))

I noticed that the edges of the triangle after 1 is (probably) always the number of rows, because we always add 1 to them when we go to the next row. So I rewrote the code with a minor change.

(define (pascals-triangle row col)
  (cond ((or (= col 0) (= col row))
         1)
        ((or (= col 1) (= col (- row 1)))
         row)
      (else (+ (pascals-triangle (- row 1)
                                  (- col 1))
                (pascals-triangle (- row 1)
                                  col)))))

In my previous code, if the colum is 0, the running time is constant. Now in the revised code, it's also constant if the column is 1. And since this is recursive, I am guessing I saved a few steps. Will making small changes like that have a significant impact with my code and systems a lot larger than this?

How can I improve this code?


texts: Printing the number of ways a message can be decoded

texts:
My below solution to the following problem is exceeding the maximum recursion depth. I am looking for any improvements which i can make.

Problem

  Alice and Bob need to send secret messages to each other and are
  discussing ways to encode their messages:

  Alice: “Let’s just use a very simple code: We’ll assign ‘A’ the code
  word 1, ‘B’ will be 2, and so on down to ‘Z’ being assigned 26.”

  Bob: “That’s a stupid code, Alice. Suppose I send you the word ‘BEAN’
  encoded as 25114. You could decode that in many different ways!”
  Alice: “Sure you could, but what words would you get? Other than
  ‘BEAN’, you’d get ‘BEAAD’, ‘YAAD’, ‘YAN’, ‘YKD’ and ‘BEKD’. I think
  you would be able to figure out the correct decoding. And why would
  you send me the word ‘BEAN’ anyway?” Bob: “OK, maybe that’s a bad
  example, but I bet you that if you got a string of length 5000 there
  would be tons of different decodings and with that many you would find
  at least two different ones that would make sense.” Alice: “How many
  different decodings?” Bob: “Jillions!”

  For some reason, Alice is still unconvinced by Bob’s argument, so she
  requires a program that will determine how many decodings there can be
  for a given string using her code.

Input

Input will consist of multiple input sets. Each set will consist of a single line of at most 5000 digits representing a valid encryption (for example, no line will begin with a 0). There will be no spaces between the digits. An input line of ‘0’ will terminate the input and should not be processed.

Output

For each input set, output the number of possible decodings for the input string. All answers will be within the range of a 64 bit signed integer.

Example

Input:

25114
1111111111
3333333333
0

Output:

6
89
1

The following is my solution -

def helper_dp(input_val, k, memo):

    if k == 0:
        return 1

    s = len(input_val) - k

    if input_val[s] == '0':
        return 0

    if memo[k] != -1:
        return memo[k]

    result = helper_dp(input_val, k - 1, memo)

    if k >= 2 and int(input_val[s:s+2]) <= 26:
        result += helper_dp(input_val, k - 2, memo)

    memo[k] = result
    return memo[k]

def num_ways_dp(input_num, input_len):
    memo = [-1] * (len(input_num) + 1)
    return helper_dp(input_num, input_len, memo)

if __name__ == '__main__':
    number = input()
    while number != '0':
        print(num_ways_dp(number, len(number)))
        number = input()

Problem Link - https://www.spoj.com/problems/ACODE/


texts:
The object of the code is to prompt the user with a quiz and collect the g's, y's, 0's, and 1's and if there is more than one then the user passes (else, they fail).  I am a beginner and would like to know if there is a more efficient direction for this code to go in.

from time import sleep
print(pic1)

def check(name):
    if name.lower() == "brandon":
        print("Welcome home master")
    else:
        print("Let's find some data")
        sleep(0.5)
        print("What is your favorite color?")
        color = input("fav_color>>> ")
        if color == "":
            print("No skipping!")
            print(check(input("Enter Name Here>>> ")))
        print("What is your dream car?")
        car = input("fav_car>>> ")
        if car == "":
            print("No skipping!")
            print(check(input("Enter Name Here>>> ")))
        print("What team are you on?")
        team = input("team_name>>> ")
        if team == "":
            print("No skipping!")
            print(check(input("Enter Name Here>>> ")))
        print("Who is your best friend?")
        crush = input("best_friend>>> ")
        if crush == "":
            print("No skipping!")
            print(check(input("Enter Name Here>>> ")))
        print("What color is your shirt?")
        shirt = input("shirt_color>>> ")
        if shirt == "":
            print("No skipping!")
            print(check(input("Enter Name Here>>> ")))
        print("You got clout?")
        clout = input("clout_level>>> ")
        if clout == "":
            print("No skipping!")
            print(check(input("Enter Name Here>>> ")))
        print("Do you think you passed the test?")
        passed = input("passed?>>> ")
        if passed == "":
            print("No skipping!")
            print(check(input("Enter Name Here>>> ")))
        print("Calculating...")
        sleep(2.5)

        def add():
            color_counted = color.count("g")
            car_counted = car.count("g")
            team_counted = team.count("g")
            crush_counted = crush.count("g")
            shirt_counted = shirt.count("g")
            clout_counted = clout.count("y")
            clout_counted2 = clout.count("1")
            clout_counted3 = clout.count("0")
            passed_counted = passed.count("y")
            total = color_counted + car_counted + team_counted + clout_counted3 + passed_counted
            total = crush_counted + shirt_counted + clout_counted + clout_counted2
            return total
        if add() > 1:
            print("passed")
        else:
            print("failed")
        print("Congrats on your result!")
        sleep(100)

check(input("Enter Name Here>>> "))


texts: Stack class in Ruby to calculate maximum number, get the average, pop, push

texts:
Is the class optimized enough to accept 1 million items in the stack?

class Stack

attr_accessor :stacks

def initialize()
    @stacks = []
end

def max ()
    #first we could Think by
    #sort the stack
    #then take the last element
    #but I think it is not efficent
    if @stacks.size == 0
        return puts"Error no input"
    elsif @stacks.size == 1
        @stacks.first
    else
    return @stacks.max
    end
end

def push(value)
    @stacks.push(value)
end

def pop()
    if @stacks.size == 0
        return puts"Error no input"
    else
        @stacks.pop
    end
    return @stacks
end

end

class Extras < Stack

def average()
    if @stacks.size == 0
        return puts"Error no input"
    elsif @stacks.size == 1
        return @stacks.first
    else
        #used inject instead of loop to get more familiar with ruby
        sum = @stacks.inject(0, :+)
        lenght = @stacks.size
        averages = sum / lenght
        return averages
    end
end
end

users = Extras.new
puts users.push(1)
puts users.push(5)
puts users.push(3)
users.pop
puts users.push(10)
puts users.average


texts:
Will the below code work for adding Weekdays in all possible scenarios?
eg, If I add 4 days to a "Thursday", the result should be next "Wednesday". Adding 1 day to a "Friday", "Saturday" or "Sunday" should be the next "Monday".

I am trying to get the nth working day (weekday) after a given day.

var addOneDay=function(date) {
    var result = new Date(date.getTime());
    result.setDate(result.getDate() + 1);
    return result;
};

var addWeekDays = function(date,days) {
    var result = new Date(date.getTime());
    for (var i = 0; i < days; i++) {
        result = addOneDay(result);
        if (result.getDay()=== 6 || result.getDay()=== 0) i--;
    };
    return result;
};

var date = new Date(2016,1,18);
console.log(addWeekDays(date,4));


texts: Providing one-time calculations to frequently used methods

texts:
I'm new to JS/jQuery and wrote some JavaScript/jQuery lines to create a "pulsating" object.

I get the "pulse" effect by increasing/resizing the object and then bringing it back to its original state periodically.  I was uncomfortable with calculating the necessary values every time they are needed, so I used the first thing that came to my mind - global variables and only modify their values when the page is fully loaded.  But I also don't like that approach.

What is best practice in JavaScript/jQuery for this kind of problem, and how can I refactor my code accordingly?

Here is the code (JavaScript only, please see my link for HTML&CSS):

var elementOrigHeight;
var elementOrigWidth;
var elementIncreasedHeight;
var elementIncreasedWidth;
var elementNewTop;
var elementNewLeft;

$(document).ready(function () {
    var element = $('#circle');
    var growInPercent = 100;
    setGlobalVariables(element, growInPercent);
    var durationGetBigger = 500;
    var durationGetSmaller = 100;
    var frequency = 3;
    var pause = 3000;
    pulsate(element, durationGetBigger, durationGetSmaller,
    frequency, pause);
});

function pulsate(element, durationBigger, durationSmaller, frequency, pause) {
    for (var i = 0; i < frequency; i++) {
        getBigger(element, durationBigger);
        getSmaller(element, durationSmaller);
    }
    setTimeout(function () {
        pulsate(element, durationBigger, durationSmaller, frequency, pause)
    }, pause);
}

function getBigger(element, duration) {
    element.animate({
        width: elementIncreasedWidth,
        height: elementIncreasedHeight,
        top: elementNewTop,
        left: elementNewLeft,
        opacity: 1
    }, duration, 'linear');
}

function getSmaller(element, duration) {
    element.animate({
        width: elementOrigWidth,
        height: elementOrigHeight,
        top: 0,
        left: 0,
        opacity: 0.5
    }, duration, 'linear');
}

function setGlobalVariables(element, percent) {
    elementOrigHeight = element.height();
    elementIncreasedHeight = Math.round(elementOrigHeight*(1+percent/100));
    if (elementOrigHeight % 2 > 0) { // odd
        // make sure increased size is odd too
        elementIncreasedHeight = Math.floor(elementIncreasedHeight/2)*2+1;
    }
    else {
        elementIncreasedHeight = Math.floor(elementIncreasedHeight/2)*2
    }
    elementOrigWidth = element.width();
    elementIncreasedWidth = Math.round(elementOrigWidth*(1+percent/100));
    if (elementOrigWidth % 2 > 0) { // odd
        elementIncreasedWidth = Math.floor(elementIncreasedWidth/2)*2+1;
    }
    else {
        elementIncreasedWidth = Math.floor(elementIncreasedWidth/2)*2;
    }
    elementNewLeft = -Math.round((elementIncreasedWidth - elementOrigWidth)/2);
    elementNewTop = -Math.round((elementIncreasedHeight - elementOrigHeight)/2);
}


texts: Updating dimensions when focus is lost from any of 9 columns

texts:
How can I write this more pretty?

private void _detailSpread_OnCellFocusChange(object sender, CellFocusChangeEventArgs e)
{
    if (e.SourceCol == _detailSpread.GetColNumber("article"))
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol), _detailSpread.Rows[e.SourceRow]);
    else if (e.SourceCol == _detailSpread.GetColNumber("account"))
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol), _detailSpread.Rows[e.SourceRow]);
    else if (e.SourceCol == _detailSpread.GetColNumber("dim_1"))
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol), _detailSpread.Rows[e.SourceRow]);
    else if (e.SourceCol == _detailSpread.GetColNumber("dim_2"))
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol), _detailSpread.Rows[e.SourceRow]);
    else if (e.SourceCol == _detailSpread.GetColNumber("dim_3"))
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol), _detailSpread.Rows[e.SourceRow]);
    else if (e.SourceCol == _detailSpread.GetColNumber("dim_4"))
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol), _detailSpread.Rows[e.SourceRow]);
    else if (e.SourceCol == _detailSpread.GetColNumber("dim_5"))
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol), _detailSpread.Rows[e.SourceRow]);
    else if (e.SourceCol == _detailSpread.GetColNumber("dim_6"))
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol), _detailSpread.Rows[e.SourceRow]);
    else if (e.SourceCol == _detailSpread.GetColNumber("dim_7"))
        UpdateDimensionData(_detailSpread.GetColID(e.SourceCol), _detailSpread.Rows[e.SourceRow]);

    _detailSpread.Validate();
}


texts:
I was asked to find all the numbers that added up to 100 with no duplicates in Ruby. I float between Python, GoLang, and Ruby in a day. I am always concerned if I am doing something in the most optimal way.

require 'pp'
sumdata = [ 95, 5, 95, 5 ]

def find_sum(data)
  result = []
  processed = []
  data.each_with_index do |item, index |
    next if processed.include? index
    data.each_with_index do |other, other_index|
      next if processed.include? other_index # next if already processed
      # add tuple to list
      if item + other == 100
        result << [item, other].sort
        processed << index
        processed << other_index
      end
    end
  end
  result
end


texts:
I was tasked with writing a Matryoshka doll program that manages the following:

howManyDolls : returns an integer based on how many dolls are inside the stack
howManyWearingBabushkas : returns an integer based on how many dolls are wearing a Babushka. The boolean variable babushka determines this.
totalWeight : returns a double based on the weight of all the dolls in the stack

I would appreciate feedback on the recursion part of the code, if it's the most efficient/proper way to use recursion in this context. I am very new to recursion, so I want to make sure I am doing the best I can going forward.

public class Matryoshka {

    private String name;
    private double weight;
    private boolean babushka;

    private Matryoshka innerDoll;

    public Matryoshka(String name, double weight, boolean babushka) {
        this.name = name;
        this.weight = weight;
        this.babushka = babushka;

        this.innerDoll = null;
    }

    public Matryoshka(String name, double weight, boolean babushka, Matryoshka doll) {
        this.name = name;
        this.weight = weight;
        this.babushka = babushka;

        this.innerDoll = doll;
    }

    public String getName() { return this.name; }
    public double getWeight() { return this.weight; }
    public boolean getBabushka() { return this.babushka; }

    public boolean hasInnerDoll() {
        return this.innerDoll != null;
    }

    public Matryoshka getInnerDoll() {
        return this.innerDoll;
    }

    public int howManyDolls() {
        if(this.innerDoll == null) { return 1; }
        return 1 + this.innerDoll.howManyDolls();
    }

    public int howManyWearingBabushkas() {
        if(!this.hasInnerDoll()) { return 0; }
        if(!this.getBabushka()) { return 0 + this.getInnerDoll().howManyWearingBabushkas(); }
        return 1 + this.getInnerDoll().howManyWearingBabushkas();
    }

    public double totalWeight() {
        if(!this.hasInnerDoll()) { return this.getWeight(); }
        return this.getWeight() + this.getInnerDoll().totalWeight();
    }

}


texts: Implementation of the Stack data structure using a linked list in C++

texts:
I'm currently working on implementing overloaded operators for simplifying pop() and push() operations. Check out the //how can avoid this? comments. I've had some troubles understanding how to return a certain value without causing memory leaks due to unassigned free space: so far the only dirty and inelegant idea I've had was to create a temporary empty value of T type, so in case the top pointer contained nullptr I could return this empty value.

But how can I avoid this? Or is this actually necessary in a template type for a function with return statements?

#include <iostream>
#include <memory>
#include <string>
#include <vector>

template <typename V> using ptr = std::shared_ptr<V>;

template <typename T>
class Stack
{
private:

    class Node
    {
    private:

        T data;
        ptr<Node> next;

    public:
        Node(T _data):data{_data}, next{} {}
        T getData(){
            return data;
        }

        ptr<Node>& getNext(){
            return this->next;
        }

    };

    ptr<Node> top;

public:

    Stack() : top{} {}
    Stack(const std::shared_ptr<std::vector<T>>& vec) : top{} {
        for (auto vElement : *vec){
            push(vElement);
        }
    }

    void push(T _data){
        auto _tmp = std::make_shared<Node>(_data);
        if(top!= nullptr){
            _tmp->getNext() = top;
        }
        top = _tmp;
    }

    T pop(){

        T forSafety{}; //how can I avoid this?
        if(isEmpty()) return forSafety;
        else {
            auto _tmp = top;
            top = top->getNext();
            return _tmp->getData();
        }
    }

    T peek(){

        T forSafety{}; //how can I avoid this?
        if(!isEmpty()){
            return top->getData();
        } else return forSafety;
    }

    bool isEmpty(){
        if(top==nullptr) return true;
        else return false;
    }

    void display(){
        auto _tmp = top;
        while(_tmp!=nullptr){
            std::cout << _tmp->getData() << std::endl;
            _tmp = _tmp->getNext();
        }
    }
};

int main(int argc, char** argv)
{
    std::shared_ptr<std::vector<std::string>> names{new std::vector<std::string>{"Julia","Bob","Angela","fSociety"}};
    auto s = std::make_shared<Stack<std::string>>(names);
    s->display();
    std::cout << s->peek() << std::endl;

    while(!s->isEmpty()){
        std::cout << "Popping -> " << s->pop() << std::endl;
    }

    s->display();
    s->peek();

    return 0;
}


texts:
I need this kind of ORDER BY to list my curriculum vitae data: when ep.data_termino is null it means that the job is your current job (you can have multiple current jobs), then I must list them first. Then, I need to list all the others ordered by the ep.data_termino ASC.

The IF was my only choice. I know that it is never a good option to use IFs in queries (at least that's how I learned it), so I am asking here if there is any better solution.

    SELECT ep.nome_empresa, ep.data_inicio, ep.descricao, ct.nome as contratacao_tipo_nome, p.nome as profissao_nome,

IF(ep.data_termino IS NULL,NOW(),ep.data_termino) as data_term

    FROM experiencia_profissional as ep
    JOIN contratacao_tipo as ct ON ct.codigo = ep.codigo_contratacao_tipo
    JOIN profissao as p ON p.codigo = ep.codigo_profissao
    JOIN experiencia_profissional_membro as epm ON epm.codigo_experiencia_profissional = ep.codigo
    JOIN membro as m ON m.codigo = epm.codigo_membro
    JOIN usuario as u ON u.codigo_membro = m.codigo

    WHERE u.codigo = 124
    ORDER by data_term DESC, ep.data_inicio ASC


texts: Performing efficient batch inserts after batch inserts using Ecto.Multi

texts:
I have a transactional batch inserts where previous batch insert results will be used in another batch insert. My code below already works and just want to ask if there are part of the code to be improved.
      Multi.new()
      |> Multi.insert(:template, ChecklistTemplate.changeset(%ChecklistTemplate{}, attrs))
      |> Multi.merge(fn _ ->
        items = Map.get(attrs, "items")

        items
         |> Enum.with_index()
         |> Enum.reduce(Multi.new, fn {item, idx}, multi ->
          Multi.insert(multi, {:item, idx}, ChecklistItem.changeset(%ChecklistItem{}, item))
         end)

      end)
      |> Multi.merge(fn result ->
        template = Map.get(result, :template)
        max = length(attrs["items"]) - 1

        0..max
        |> Enum.reduce(Multi.new, fn id, multi ->
          item = Map.get(result, {:item, id})
          changeset = %Checklist{template_id: template.id, item_id: item.id}
          Multi.insert(multi, {:joined, id}, changeset)
        end)
      end)
      |> Repo.transaction()

I have sample data below:
%{
  "items" => [%{"name" => "National ID"}, %{"name" => "Postal ID"}],
  "name" => "Default"
}


texts:
A more proper version of this utility can be found at the following link here: Giveth me thy easier user input in C++ - follow up.

I've always been a little bothered by the fact, that in order to get user input in C++, one had to use up to three lines of code in an ugly manner like the below to get user input for a specific type, with a prompt:

int user_input;
std::cout << ">> ";
std::cin << user_input;

So, in order to make this process easier, I've created an easy_input function which allows for the user to specify a type, a prompt, and set user input to a variable, all in one line.

easy_input.h

#ifndef EASY_INPUT_H_
#define EASY_INPUT_H_
#pragma once

#include <iostream>
#include <string>

// We're simply "re-defining" the standard namespace
// here so we can patch our easy_input function into
// it for the user's sake.
namespace std
{
    template <typename TInput>
    TInput easy_input(const std::string& prompt);
}

/**
 * This function serves as a wrapper for obtaining
 * user input. Instead of writing three lines every
 * time the user wants to get input, they can just
 * write one line.
 * @param {any}    TInput - The type of the input.
 * @param {string} prompt - The prompt to use for input.
 * @returns - Whatever the user entered.
 */
template <typename TInput>
TInput std::easy_input(const std::string& prompt)
{
    TInput user_input_value;
    std::cout << prompt;
    std::cin >> user_input_value;
    return user_input_value;
}

#endif

main.cpp (tests)

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

int main()
{
    const std::string user_input1 = std::easy_input<std::string>(">> ");
    std::cout << user_input1 << "\n";

    const int user_input2 = std::easy_input<int>(">> ");
    const int user_input3 = std::easy_input<int>(">> ");
    std::cout << user_input2 + user_input3 << "\n";
}

I'd (preferably) like to know the following things:

Am I using templates appropriately? I feel like I might have done something wrong here in the process.
Is there anything that can be improved performance-wise?
Is there a need for include guards?
Is it okay to patch easy_input into std without problems? Is this a good practice?
Is there anything else that's glaringly wrong?


texts:
I've just found out there is sendfile(). In the man page of sendfile(), it says:

  sendfile() is more efficient than the combination of read(2) and write(2).

So, I wrote a function to copy a file using sendfile().

Is really my code more efficient than the combination of read(2) and write(2)?

/* leftsize is initialized with total size of source file. */
fd_src = open(src_fname, O_RDONLY);
if (fd_src<0){
    printf("open failed(%s)\n", src_fname);
    return -1;
}
fd_dest = creat(dest_fname, 0666);
if (fd_dest<0){
    printf("create failed(%s)\n", dest_fname);
    return -1;
}
while (leftsize > 0) {
    n = sendfile(fd_dest, fd_src, NULL, max_size);
    if (n<0) {
        printf("sendfile failed. ret:%d errno:%d\n", n, errno);
    }
    leftsize -= n;
}