texts: Comparing two implementations of smoosh()

texts:
In this question, the suggested solution for smoosh() is as shown below,

public static void smoosh(int[] a) {
    int originalPos = 0;
    int targetPos = 0;
    while (originalPos < a.length) {
        // Copy (and remember) one element to the correct position:
        int currentElement = a[targetPos++] = a[originalPos++];
        // Advance originalPos until a different element is found:
        while (originalPos < a.length && a[originalPos] == currentElement) {
            originalPos++;
        }
    }
    // Fill remaining elements:
    while (targetPos < a.length) {
        a[targetPos++] = -1;
    }
}

but, I felt that this well tested new solution shown below looks more readable than shown above,

  public static void smoosh(int[] a) {
    int saveOriginalPosition = 1;
    int targetPosition = 0, originalPosition = 0;
    while(targetPosition < a.length){
        if(saveOriginalPosition < a.length){
            for(originalPosition = saveOriginalPosition;originalPosition < a.length;originalPosition++)
                if(a[originalPosition] != a[targetPosition])
                {
                    a[++targetPosition] = a[originalPosition];
                    break;
                }
            saveOriginalPosition = originalPosition;
        }else{
            break;
        }
    }
    if(originalPosition == a.length){
        for(int setRemaining = targetPosition+1; setRemaining  < a.length; setRemaining++)
            a[setRemaining] = -1;
    }

 }

because point mentioned by 200_success, i.e., "However, being able to recognize the structure of the loop just by looking at the loop header gives it an advantage in readability." is considered in this new solution, whereas the inner while loop of the suggested solution does not look readable.

Please let me know your inputs on the changes.


texts:
I need to split a list into equal sublists, e. g [1..9] split into groups of 3 will be [[1, 2, 3], [4, 5, 6], [7, 8, 9]]. I have accomplished this task in the following way:

splitInGroupsOf n = takeWhile ((n ==) . length)
                  . map fst
                  . drop 1
                  . iterate (\(res, list) -> splitAt n list)
                  . (,) []

where iterate creates list of tuples with first n elements and rest of list. This way I had to use (,) [] on argument to ensure correct type, and unwrap result afterwards. My questions are

is there a better/more elegant way of performing same task?
is there some standard function I should make use of?

P.S.: I'm not sure where to ask simple Haskell-related questions and will appreciate if someone points me a better place for this than SE.


texts: Prolog predicate for adjacency of integers with all signatures and no spurious choice points

texts:
I want to create a predicate nearby(X,Y) which represents "X and Y are integers 1 apart from each other" and fully satisfies:

%%! nearby(+X:Int, +Y:Int) is semidet.
%%! nearby(+X:Int, -Y:Int) is multi.
%%! nearby(-X,Int, +Y:int) is multi.

In other words it must work for any combination of two bound inputs or one bound and one free input, and must have no spurious choice point when both inputs are bound.

Is this the best way to do so? Note that while I understand that using a built in predicate like plus might make the code more readable, would it inevitably end up substituting down to something like this?

nearby2(X,Y) :- nonvar(X), X = Y.
nearby2(X,Y) :- nonvar(X), Y is X+1.
nearby2(X,Y) :- nonvar(X), Y is X-1.
nearby2(X,Y) :- var(X), nonvar(Y), nearby2(Y,X).

nearby3(X,Y) :- nonvar(X), nonvar(Y), nearby2(X,Y), !.
nearby3(X,Y) :- nearby2(X,Y).


texts: Function fputs always return zero on success

texts:
I am using the fputs() function to write a string to a file. I want to handle the case in which the string has been successfully written to the file. Here is my code:

#include <stdio.h>

main() {

  FILE *fp;
  int rets; //to keep fputs return value

   fp = fopen("test.txt", "w");
   rets = fputs("\nThis is testing for fputs...\n", fp);
   printf("Fputs return value : %d\n",rets); //Return value is always zero
   fclose(fp);

   if(rets >= 0 )
       printf("Successfully written on the file. Proceed..");

   return 0;
}

According to the documentation for fputs():

  On success, a non-negative value is returned.

When I executed this code multiple times, I noticed that the return value is always zero. According to this observation, it is enough to check if return value is zero (rather than non-negative). According to this, the last line of my code could be:

   if(rets == 0 ) //equal to zero for success
       printf("Successfully written on the file. Proceed..");

Should I trust the above observation?

Is the documentation wrong, or ambiguous?


texts:
I would like to make this code more efficient, I have isolated the problem as being these two for loops:

    for i, device in enumerate(list_devices):
        for data_type_attr_name in data_types:
            result_list_element = {
                "device_reference": device.name,
                "device_name": "REF - " + device.name,
                "data_type": data_type_attr_name,
                "type": next(
                    (data_type["type"] for data_type in DATA_TYPES if data_type["name"] == data_type_attr_name)
                ),
                "data_points": getattr(device, data_type_attr_name)(
                    is_last_value=is_last_value,
                    from_timestamp=from_timestamp,
                    to_timestamp=to_timestamp,
                    aggregate_period_name=aggregate_period_name,
                    aggregate_operation_name=aggregate_operation_name,
                    decimal_places=decimal_places,
                ),
            }
            if not isinstance(result_list_element["data_points"], list):
                raise TypeError("`data_points` must be returned as a list, even if it contains only one element.")
            result_list.append(result_list_element)

    return result_list

list_devices is a list of Django model objects, data_types is a list of strings, each one representing a data type.

Is there any way of losing one of the for loops while maintaining the same output?

Thanks


texts: Set of wrapper functions for POSIX signal APIs on Linux

texts:
Please feel free to comment on the accuracy/validity of the following wrapper source for processing signals using the new POSIX sigaction API. If you feel I'm doing anything wrong or potentially dangerous, chime in.

Note: syserr is a custom function not shown to exit gracefully.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <errno.h>

static struct sigaction *
handle_signal(int sig,
              int flags,
              void (*handler)())
{
static struct sigaction action;
static struct sigaction o_action;

/* init the sigaction structs */
memset(&action, 0, sizeof(action));
memset(&o_action, 0, sizeof(o_action));

/* setup our signal handler function to call when it fires */
action.sa_handler = handler;

/* initialize the signal mask */
sigemptyset(&action.sa_mask);

/* use the user passed in flags setting othersize init them */
if (flags != 0)
   action.sa_flags = flags;
else
   action.sa_flags = 0;

if (sigaction(sig, &action, &o_action) != 0)
   syserr();

return(&o_action);

}

static struct sigaction *
ignore_signal(int sig)
{
static struct sigaction action;
static struct sigaction o_action;

/* init the sigaction structs */
memset(&action, 0, sizeof(action));
memset(&o_action, 0, sizeof(o_action));

/* setup to ignore this signal */
action.sa_handler = SIG_IGN;

/* initialize the signal mask */
sigemptyset(&action.sa_mask);

action.sa_flags = 0;

if (sigaction(sig, &action, &o_action) != 0)
   syserr();

return(&o_action);

}

int
block_signal(int sig)
{
static sigset_t mask;
static sigset_t orig_mask;
int ret;

sigemptyset(&mask);
sigemptyset(&orig_mask);

sigaddset(&mask, sig);

ret = sigprocmask(SIG_BLOCK, &mask, &orig_mask);

return(ret);
}

int
unblock_signal(int sig)
{
static sigset_t mask;
static sigset_t orig_mask;
int ret;

sigemptyset(&mask);
sigemptyset(&orig_mask);

sigaddset(&mask, sig);

ret = sigprocmask(SIG_UNBLOCK, &mask, &orig_mask);

return(ret);

}

sigset_t *
get_signal_mask()
{
static sigset_t orig_mask;

sigemptyset(&orig_mask);

/* null in set arg means return current mask */
if (sigprocmask(SIG_SETMASK, NULL, &orig_mask) < 0)
   syserr();

return(&orig_mask);

}


texts: Find hamming distance between two Strings of equal length in Java

texts:
I have a private class that I want to be able to find the shortest Hamming Distance between two Strings of equal length in Java. The private class holds a char[] and contains a method to compare against other char arrays. It returns true if there is only a hamming distance of one.

The average length of the Strings used is 9 characters. They range from 1 to 24 characters.

Is there a way to make the isDistanceOne(char[]) method go any faster?

private class WordArray {

  char[] word;

  /**
   * Creates a new WordArray object.
   *
   * @param word The word to add to the WordArray.
   */
  private WordArray(String word) {
     this.word = word.toCharArray();
  }

  /**
   * Returns whether the argument is within a Hamming Distance of one from
   * the char[] contained in the WordArray.
   *
   * Both char[]s should be of the same length.
   *
   * @param otherWord The word to compare with this.word.
   * @return boolean.
   */
  private boolean isDistanceOne(char[] otherWord) {

     int count = 0;

     for(int i = 0; i < otherWord.length; i++) {
        if (this.word[i] != otherWord[i])
           count++;
     }

     return (count == 1);
  }
}


texts: Registering various kinds of blocks in Minecraft

texts:
After looking at a few tutorials on making minecraft mods i got as far as making my own blocks and the ModBlocks class to me looks awful and unruly especially when more blocks are added:

public class ModBlocks {

public static BlockPlatinum blockPlatinum;
public static BlockNickel blockNickel;

public static void init() {
    registerPlatinum();

    registerNickel();

}

@SideOnly(Side.CLIENT)
public static void initClient(ItemModelMesher mesher) {
    registerClientPlatinum(mesher);
    registerClientNickel(mesher);
}

private static void registerClientNickel(ItemModelMesher mesher) {
    Item item = Item.getItemFromBlock(blockNickel);
    ModelResourceLocation model = new ModelResourceLocation(ModMetaData.RESOURCE_PREFIX + References.NICKEL_BLOCK,
            "inventory");
    ModelLoader.registerItemVariants(item, model);
    mesher.register(item, 0, model);
}

private static void registerClientPlatinum(ItemModelMesher mesher) {
    Item item = Item.getItemFromBlock(blockPlatinum);
    ModelResourceLocation model = new ModelResourceLocation(ModMetaData.RESOURCE_PREFIX + References.PLATINUM_BLOCK,
            "inventory");
    ModelLoader.registerItemVariants(item, model);
    mesher.register(item, 0, model);
}

private static void registerNickel() {
    ResourceLocation location = new ResourceLocation(ModMetaData.MODID, References.NICKEL_BLOCK);
    blockNickel = new BlockNickel();
    blockNickel.setRegistryName(location);
    GameRegistry.register(blockNickel);
    GameRegistry.register(new ItemBlock(blockNickel), location);
}

private static void registerPlatinum() {
    ResourceLocation location = new ResourceLocation(ModMetaData.MODID, References.PLATINUM_BLOCK);
    blockPlatinum = new BlockPlatinum();
    blockPlatinum.setRegistryName(location);
    GameRegistry.register(blockPlatinum);
    GameRegistry.register(new ItemBlock(blockPlatinum), location);
}

}

I have already tried extracting the Block* classes and putting them into a static list and then refactoring the init and client init methods to iterate over the list but that produces invisible blocks.

I am sure this is a problem long since solved by Minecraft mod devs, so if anyone has any guidance that would be awesome.


texts:
Assign equal number chores to each person (assertion made elsewhere to ensure chores % number of people == 0) with the stipulation that each chore must not be one which the person was assigned the previous time.

My simpleton solution (there has to be a cleverer way):

import random

chores = ["hoovering", "dusting", "wash dishes", "tidy garden",
          "clean windows", "empty dishwasher", "dust", "cook"]

people_data = {"David": {"email": "example@gmail.com",
                         "chores" : []},
               "Mark": {"email": "example@gmail.com",
                         "chores": []},
               "Anaya": {"email": "example@gmail.com",
                         "chores": []},
               "Cooper": {"email": "example@gmail.com",
                          "chores": []}
               }

prev_assignment_data = None

def assign_chores(chore_list, prev_assignment_data, people_data):
    """Returns a dict with assign chores to each person

    Arguments:
    chore_list            --  a list of the chores to be assigned
    prev_assignment_data  --  if there has been prev chore assignments this
                              will be a dict containing said assignments.
                              Otherwise, it will have no value ('None')
    people_data           --  a dict of the names and the email address
                              associated with those names. Assigned chores
                              will be appended to this dict and dict
                              returned.
    """

    # if no previous data available, assign each a random chore
    if not prev_assignment_data:
        while chore_list:
            for name in people_data.keys():
                chore = random.choice(chore_list)
                chore_list.remove(chore)
                people_data[name]["chores"].append(chore)

    # if prev data available, assign each chores not the same as previous
    else:
        new_chores = False
        while not new_chores:
            chore_list_copy = chore_list
            for name in people_data.keys():
                # get all chores still available and which are not those
                # the person was assigned the previous time
                avail_chores = [chore for chore in chore_list_copy if chore not
                                in prev_assignment_data[name]["chores"]]

                if avail_chores:
                    chore = random.choice(avail_chores)
                    people_data[name]["chores"].append(chore)
                    chore_list_copy.remove(chore)

                # if only chores remaining are those the person did previously,
                # restart entire assignment process
                else:
                    break
            # all chores assigned and are different to those person did prev
            if not chore_list_copy:
                new_chores = True

    return people_data

assigned_chores = assign_chores(chores, prev_assignment_data,
                                people_data)
print(assigned_chores)


texts:
The crawler is in need of a mechanism that will dispatch threads based on network latency and system load. How does one keep track of network latency
in Python without using system tools like ping?

import sys
import re
import urllib2
import urlparse
import requests
import socket
import threading
import gevent
from gevent import monkey
import time

monkey.patch_all(
  socket=True,
  dns=True,
  time=True,
  select=True,
  thread=True,
  os=True,
  ssl=True,
  httplib=False,
  subprocess=False,
  sys=False,
  aggressive=True,
  Event=False)

# The  stack
tocrawl = set([sys.argv[1]])
crawled = set([])
linkregex = re.compile('<a\s*href=[\'|"](.*?)[\'"].*?>')

def Update(links):
  if links != None:
    for link in (links.pop(0) for _ in xrange(len(links))):
      link = ( "http://%s" %(urlparse.urlparse(link).netloc) )
      if link not in crawled:
        tocrawl.add(link)

def getLinks(crawling):
  crawled.add(crawling)
  try:
    Update(linkregex.findall(requests.get(crawling).content))
  except:
    return None

def crawl():
  try:
    print"%d Threads running" % (threading.activeCount())
    crawling = tocrawl.pop()
    print crawling
    print len(crawled)
    walk = gevent.spawn(getLinks,crawling)
    walk.run()
  except:quit()

def dispatcher():
  while True:
    T = threading.Thread(target=crawl)
    T.start()
    time.sleep(1)

dispatcher()


texts:
How can I speed up this code?

coin=[50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]
def matrix(coins, kerdes): # it create a metrix
    tabla = [[0 for m in range(kerdes + 1)] for m in range(len(coins) + 1)]

    for i in range(kerdes + 1):
        tabla[0][i] = i
    return tabla

def change_making(coin, change):
    table = matrix(coin, change)
    for c in range(1, len(coin) + 1):
        for r in range(1, change + 1):

            if coin[c - 1] == r:
                table[c][r] = 1

            elif coin[c - 1]> r:
                table[c][r] = table[c-1][r]

            else:
                table[c][r] = min(table[c - 1][r], 1 + table[c][r - coin[c - 1]])

    return table[-1][-1] #return the minimum coin what we need to make the change

newcoin=int(input()) # ask the new coin
coin.append(newcoin) #add to the coin list
coin.sort(reverse=True) #sort the list to get the biggest coin to first

changemakings=[int(x) for x in input().split()] # order the 'orders' to list for easier work with it
for changes in changemakings:

    print(change_making(coin, changes))

This is my code it calculate the minimum coin, with possible to give new coin which will result a non canonical change system.


texts:
Code Review has a Zombie Problem and, in comparison to The Walking Dead TV Show, our survival doesn't depend on killing them all day every day.

As a potential solution, I though it would be interesting to setup a friendly zombie killing competition (this wasn't talked about in meta yet), but in order for this to work we need a way to rank our killers.

I've written the following Stack Exchange Data Explorer query, which has the following requirements.

Questions must :

Not be closed/deleted/community owned
Be at least one month older than the competition's start date
Not have answers with a score greater than one preceding the competition's start date

And in order for the zombie to be killed, the questions targeted by the above requirements must have an answer with a score of 1 or more that follows the beginning of the competition's date.

I then group the answers per user, show their "kill count" and order by this value, in descending order.

The query in question

declare @startDate date;
set @startDate = CONVERT(datetime, '2019-07-21');

select top(25) u.DisplayName, count(*)
from   Posts q
       inner join Posts a on q.Id = a.ParentId
       inner join Users u on a.OwnerUserId = u.Id
where  q.PostTypeId = 1
       -- Target old questions with new answers
       and datediff(month, q.CreationDate, @startDate) > 1
       and a.Score > 0
       and a.CreationDate > @startDate
       and not exists (select Id from Posts where ParentId = q.Id and CreationDate < @startDate and Score > 0)
       -- Remove low quality/closed/deleted/community owned questions
       and q.Score >= 0
       and q.ClosedDate is null and q.CommunityOwnedDate is null and q.DeletionDate is null
group by u.Id, u.DisplayName
order by count(*) desc

I don't have a database schema in hand, but there are two table concerned :

Posts : Where we have questions and answers. The answers have a ParentId that is a question. A post has an owner (OwnerUserId) with an associated User. I think the rest of the columns names are pretty self explanatory, but I can add details if necessary.

I've tested the query and, to the best of my knowledge, it works. I'm not very used to SEDE so there might be things I missed, which I'd like to learn.

I'd also like to know if there are performance pitfalls in my query I should be aware of or best practices that I'm missing.

The query itself.


texts:
My target website is Indeed. I tried to implement the scraper such that it is convenient for the end user. I am introducing my code in the readme file on my github repo.

I am somewhat a beginner in programming so I am looking for guidance on things such as if the libraries that I used are approriate, the code itself and on generally making the script better.

Link to the README file.

import requests
from bs4 import BeautifulSoup

jobName = input('Enter your desired position: ').replace(' ', '-')
place = input("Enter the location for your desired work(City, state or zip): ")

URL = 'https://www.indeed.com/q-'+jobName+'-l-'+place.replace(' ', '-')+'-jobs.html'
page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')
pages = soup.find(id='searchCountPages')
noPag = pages.text.split('of')[1].strip(' jobs').replace(',', '')

nmoPag = input(f"There are {noPag} number of pages. If you want to scrape all of them write 'Max' else write number of pages you wish to scrape: ")
if nmoPag == 'Max':
    nmoPag = noPag

for i in range(0, int(nmoPag)*10, 10):
    URL = 'https://www.indeed.com/jobs?q='+jobName+'&l='+place.replace(' ', '+')+'&start='+str(i)
    page = requests.get(URL)
    soup = BeautifulSoup(page.content, 'html.parser')
    results = soup.find(id='resultsCol')
    listings = results.find_all('div', class_='result')

    for job in listings:
        jobT = job.find('a', class_='jobtitle')
        jobL = job.find('span', class_='location').text.strip()
        jobS = job.find('div', class_='summary').text.strip()
        link = jobT['href']
        if any(any(subs in s for s in (jobT.text.strip().lower(), jobS.lower())) for subs in (jobName.split('+')[0], jobName[1])):
            print('Your job in '+jobL+' as a '+ jobT.text.strip()+
                    '.\nHere is a quick summary of your job here: '+
                        jobS+'\nLink for more information and application for the job - https://indeed.com'+link, end='\n\n\n')


texts: Exporting data from PostgreSQL as CSV to S3 bucket

texts:
I have a general question regarding DRY. As you can see there are several parts such as io.StringIO(), csv.writer, io.BytesIO which are repeated. I now wonder if there is a better way, where I don't seem to repeat myself. Or is the way how I use it here a fair approach and not considered as DRY?

What does your code do?

With the code, I create two CSV-files in the buffer and directly upload them to an AWS S3 bucket. The data for these files are from my Postgres database. The framework I use is Django. That's why I am able to access the database with commands such as Event.objects.filter

What does the rest of your program look like?

That's basically all of the program. After the CSV-files are available on my bucket an AWS Lambda function proceeds with the data and a machine learning model.

What Python version did you write this for?

I use Python 3.

class Forecast:
    @classmethod
    def export_data_for_forecast(cls):
        s3 = boto3.client(
            's3',
            aws_access_key_id=settings.ML_AWS_ACCESS_KEY_ID,
            aws_secret_access_key=settings.ML_AWS_SECRET_ACCESS_KEY,
        )

        BUCKET_NAME = 'fbprophet'
        EVENT_DATA_OBJECT = 'event_data_test.csv'
        ORDER_DATA_OBJECT = 'orders_order_test.csv'

        events = Event.objects.filter(status=EventStatus.LIVE).prefetch_related(
            'orders'
        )

        # Prepare buffer for csv files
        event_data_buffer = io.StringIO()
        event_data_writer = csv.writer(event_data_buffer)
        event_data_writer.writerow(["Event PK", "Name", "Start date"])

        order_data_buffer = io.StringIO()
        order_data_writer = csv.writer(order_data_buffer)
        order_data_writer.writerow(["Event PK", "Created", "Total Gross"])

        active_events = filter(lambda event: not event.is_over, events)
        for event in active_events:
            event_data_writer.writerow([event.pk, event.name, event.start_date])

            for order in event.orders.all():
                order_data_writer.writerow(
                    [order.event.pk, order.created, order.total_gross]
                )

        # Prepare buffer and transform to binary
        event_data_buffer_to_binary = io.BytesIO(
            event_data_buffer.getvalue().encode('utf-8')
        )
        order_data_buffer_to_binary = io.BytesIO(
            order_data_buffer.getvalue().encode('utf-8')
        )

        # Upload to S3
        s3.upload_fileobj(event_data_buffer_to_binary, BUCKET_NAME, EVENT_DATA_OBJECT)
        s3.upload_fileobj(order_data_buffer_to_binary, BUCKET_NAME, ORDER_DATA_OBJECT)


texts:
What do you think about this simple calculator?

while True:
    print('Options:')
    print('Enter \'a\' to add two numbers')
    print('Enter \'s\' to subtract two numbers')
    print('Enter \'m\' to multiply two numbers')
    print('Enter \'d\' to divide two numbers')
    print('Enter \'q\' to quit the program')
    response=str(input(':')).lower()
    if response=='q':
        break
    elif response=='a':
        while True:
           try:
               num1=float(input('Enter a number:'))
               break
           except(TypeError,ValueError):
               print('*(Input Error) Enter valid number*')
               continue
        while True:
            try:
                num2=float(input('Enter another number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        result=num1+num2
        print('The answer is '+str(result))
        print()
    elif response=='s':
        while True:
            try:
                num1=float(input('Enter a number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        while True:
            try:
                num2=float(input('Enter another number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        result=num1-num2
        print('The answer is '+str(result))
        print()
    elif response=='m':
        while True:
            try:
                num1=float(input('Enter a number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        while True:
            try:
                num2=float(input('Enter another number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        result=num1*num2
        print('The answer is '+str(result))
        print()
    elif response=='d':
        while True:
            try:
                num1=float(input('Enter a number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        while True:
            try:
                num2=float(input('Enter another number:'))
                break
            except(TypeError,ValueError):
                print('*(Input Error) Enter valid number*')
                continue
        result=num1/num2
        print('The answer is '+str(result))
        print()
    else:
        print('*Unknown input*')
    continue


texts:
I need to complete a sequence of braces and brackets like [ ], ( ), { }, or reject the input. I can add braces/brackets only at the beginning or at the end.

Example:

input: '))[[([{([])}' output: '(())[[([{([])}])]]'
input: '[)[((({}[]'   output: 'rejected'

My implementation is based on using a stack (self-implemented to improve from standard Stack class, based on Vector), but certainly it can be done much better.

public class BraceCompliter {
    private static final char L_PAREN    = '(';
    private static final char R_PAREN    = ')';
    private static final char L_BRACE    = '{';
    private static final char R_BRACE    = '}';
    private static final char L_BRACKET  = '[';
    private static final char R_BRACKET  = ']';
    private static StringBuilder currString;

public static void main(String[] args) {
    String test1 = "))[[([{([])}";
    String test2 = "[)[((({}[]";
    System.out.println(process(test1));
}

public static String process(String s) {
    currString = new StringBuilder(s);
    ArrayStack stack = new ArrayStack(s.length());
    int count = 0;
    for (int i = 0; i < s.length(); i++) {

        if      (s.charAt(i) == L_PAREN){
            stack.push(L_PAREN);
            count++;
        }
        else if (s.charAt(i) == L_BRACE)  {
            stack.push(L_BRACE);
            count++;
        }
        else if (s.charAt(i) == L_BRACKET) {
            stack.push(L_BRACKET);
            count ++;
        }
        else if (s.charAt(i) == R_PAREN) {
            if (stack.isEmpty())
                i = completeStart();
            else if (stack.pop() != L_PAREN)
                    return "rejected";
                else count--;
        }

        else if (s.charAt(i) == R_BRACE) {
            if (stack.isEmpty())
                i = completeStart();
            else if (stack.pop() != L_BRACE)
                return "rejected";
                else count--;
        }

        else if (s.charAt(i) == R_BRACKET) {
            if (stack.isEmpty())
                i = completeStart();
            else if (stack.pop() != L_BRACKET)
                return "rejected";
                else count--;
        }
    }
    if (!stack.isEmpty()) {
        completeEnd(stack, count);
    }
    return currString.toString();
}

private static void completeEnd(ArrayStack stack, int count) {
    for (int i = 0; i < count; i++) {
        Character ch = stack.pop();
        switch (ch) {
            case L_PAREN:
                currString.append(R_PAREN);
                break;
            case L_BRACE:
                currString.append(R_BRACE);
                break;
            case L_BRACKET:
                currString.append(R_BRACKET);
                break;
        }
    }
}

private static int completeStart() {
    int count = -1;
    for (int i = 0; i < currString.length(); i++) {
        char c = currString.charAt(i);
        if (c == L_BRACE || c == L_BRACKET || c == L_PAREN) {
            break;
        }
        switch (c) {
            case R_BRACE:
                currString.insert(0, L_BRACE);
                i++;
                count++;
                break;
            case R_BRACKET:
                currString.insert(0, L_BRACKET);
                i++;
                count++;
                break;
            case R_PAREN:
                currString.insert(0, L_PAREN);
                i++;
                count++;
                break;
        }
    }
    return count;
}

class ArrayStack {

    private int top;
    private char[] storage;

    ArrayStack(int capacity) {
        storage = new char[capacity];
        top = -1;
    }

    void push(char value) {
        top++;
        storage[top] = value;
    }

    char pop() {
        return storage[top--];
    }

    boolean isEmpty() {
        return (top == -1);
    }
}
}

All feedback welcome.


texts: Checking if a number fits in a primitive type

texts:
I made a program that asks for a specified amount of numbers and checks if the input number is in the primitive type range. If it is, it "fits" on the primitive type.

Each input number, it checks if the number is in the range of each primitive type MIN and MAX range. If it is between the range, it prints the type(s) it is ranged on.

import java.math.BigInteger;
import java.util.Scanner;

public class Main {

private Scanner in = new Scanner(System.in);

public Main()
{
    // Get input on how many numbers to ask for
    int t = in.nextInt();
    String input;
    for(int times = 0; times < t; times++) {
        // Ask for the number
        input = in.next();
        try {
            BigInteger number = new BigInteger(input);
            System.out.println(input + " can be fitted in:");
            if(number.longValue() < Byte.MAX_VALUE && number.longValue() > Byte.MIN_VALUE)
            {
                System.out.println("* byte");
            }
            if(number.longValue() < Short.MAX_VALUE && number.longValue() > Short.MIN_VALUE)
            {
                System.out.println("* short");
            }
            if(number.longValue() < Integer.MAX_VALUE && number.longValue() > Integer.MIN_VALUE)
            {
                System.out.println("* int");
            }
            // If the longValueExact() returns a greater number than the long max value, then it throws an ArithmeticException
            if(number.longValueExact() < Long.MAX_VALUE && number.longValue() > Long.MIN_VALUE)
            {
                System.out.println("* long");
            }
        }
        catch(NumberFormatException | ArithmeticException e)
        {
            System.out.println(input + " * nothing");
        }
    }
}

public static void main(String[] args)
{
    new Main();
}
}

I got this "challenge" from this challenge website. It may explain the challenge better.


texts:
Write a method leetSpeak that accepts two parameters: a Scanner
  representing an input file, and a PrintStream representing an output
  file. Your method should convert the input file's text to "leet speak"
  (aka 1337 speak), an internet dialect where various letters are
  replaced by other letters/numbers. Output the leet version of the text
  to the given output file. Preserve the original line breaks from the
  input. Also wrap each word of input in parentheses. Perform the
  following replacements:

  For example, if the input file
  lincoln.txt contains the following text:

  four score and seven years ago our

  fathers brought forth on this continent a new nation And your method
  is called in the following way:

Scanner input = new Scanner(new File("lincoln.txt"));
PrintStream output = new PrintStream(new File("leet.txt"));
leetSpeak(input,output);

  Then after the call, the output file leet.txt should contain
  the following text:

(f0ur) (sc0r3) (4nd) (s3v3n) (y34rZ) (4g0) (0ur)
(f47h3rZ) (br0ugh7) (f0r7h) (0n) (7hiZ) (c0n7in3n7) (4) (n3w) (n47i0n)

  You may assume that each token from the input file is separated by
  exactly one space.

  Hint: You may want to use the String object's replace method, which is
  used as follows:

String str = "mississippi"; str = str.replace("s", "*");    // str = "mi**i**ippi"

I'm looking for general feedback, and other ways to accomplish the task of solving this problem. My hope is that there will be some interesting feedback on this that I can apply to my future coding. If there are any bugs in my code, please let me know.

public static void leetSpeak (Scanner sc, PrintStream ps) {
    while (sc.hasNextLine()) {
        String line = new String(sc.nextLine());
        Scanner tokenScanner = new Scanner(line);
        while (tokenScanner.hasNext()) {
            String token = new String(tokenScanner.next());
            token = token.replace("o", "0");
            token = token.replace("l", "1");
            token = token.replace("e", "3");
            token = token.replace("a", "4");
            token = token.replace("t", "7");
            if (token.substring(token.length() - 1).equals("s")) {
                    token = new String(token.substring(0, token.length() - 1));
                    token += "Z";
            }
            ps.print("(" + token + ")" + " ");
        }
    ps.println();
    }
}


texts:
I wrote a quicksort program in C++.

Is it okay to implement it this way?
Am I using pointers correctly?
Is my style okay?
Any ideas to speed it up or save memory?

void change(int *i, int *j)
{
int temp = *j;
 *j = *i;
*i = temp;
}

int *toplace(int *start, int *end)
{
    int *i = start+1, *j= end;

    while(i<=j)
    {
    for(; *i<=*start && i<=end; i++);
    for(; *j>=*start && start+1<=j; j--);
    if (i<j) change(i++,j--);
    }

    change(start,i-1);
    return i-1;
}

void quicksort(int *start, int *end)
{
    if (start >= end) return;

    for(int *debug = start;debug<=end;debug++) std::cout<<*debug <<" ";
    std::cout<<std::endl;  //this and...

    int *temp = start;
    temp = toplace(start,end);

    for(int *debug = start;debug<=end;debug++) std::cout<<*debug <<" ";
    std::cout<<std::endl; //...this are only to "see under the hood"
    std::cout<<std::endl;

    quicksort(start,temp-1);
    quicksort(temp+1,end);

}

An example usage:

int main(int argc, char* argv[])
{
    int A[] = {5,14,8,12,1,2,11,15,6,9,7,3,13,4,10};
    int n = sizeof (A) / sizeof(A[0]);

    quicksort(A, &A[n-1]);

    for (int i =0; i<n; i++) std::cout<<A[i] <<" ";

    getchar();
    return 0;
}

produces the output:

5 14 8 12 1 2 11 15 6 9 7 3 13 4 10
1 4 3 2 5 12 11 15 6 9 7 8 13 14 10

1 4 3 2
1 4 3 2

4 3 2
2 3 4

2 3
2 3

12 11 15 6 9 7 8 13 14 10
8 11 10 6 9 7 12 13 14 15

8 11 10 6 9 7
6 7 8 10 9 11

6 7
6 7

10 9 11
9 10 11

13 14 15
13 14 15

14 15
14 15

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15


texts: Multiple criterias in a VLOOKUP in Excel VBA

texts:
I have made the following custom defined function in Excel. It works somehow like VLOOKUP(), but it takes two criteria. I think the code is a bit of a mess. Does anyone has any comments, suggestions, or improvements?

Public Function VLOOKUPMC(ByVal return_col_num As Long, ByRef table_array_1 As Range, ByVal lookup_value_1 As Variant, ByRef table_array_2 As Range, ByVal lookup_value_2 As Variant) As Variant
    Dim rCell1 As Range

    For Each rCell1 In table_array_1
        With rCell1
            If .Value = lookup_value_1 Then
                If .Offset(0, table_array_2.Column - .Column) = lookup_value_2 Then
                    VLOOKUPMC = .Offset(0, return_col_num - .Column)
                    Exit Function
                End If
            End If
        End With
    Next rCell1
    VLOOKUPMC = CVErr(xlErrNA)
End Function


texts:
I recently made a linked list for myself, the code of which was posted here, if anyone would be interested. Now, as the next task, I had to make an Iterator for my list, which is working properly.

public Iterator<T> iterator() {
    final MyLinkedList<T> list = this;
    return new Iterator<T>() {
        final Node<T> firstNode = list.firstNode;
        Node<T> currentNode = null;
        @Override
        public boolean hasNext() {
            if (list.isEmpty()) {
                return false;
            } else if (currentNode == null){
                return true;
            } else if (currentNode == list.lastNode){
                return false;
            }
            return true;
        }
        @Override
        public T next() {
            if (list.isEmpty()){
                throw new NoSuchElementException();
            } else if (currentNode == null){
                this.currentNode = firstNode;
                return currentNode.data;
            } else if (currentNode.nextNode == null) {
                throw new NoSuchElementException();
            }
            this.currentNode = currentNode.nextNode;
            return currentNode.data;
        }
    };
}

Here are the variables of the LinkedList class:

private Node<T> lastNode;
private Node<T> firstNode;
private int size;

This is a Node<U>:

private static class Node<U>{
    private Node<U> nextNode = null;
    private Node<U> previousNode = null;
    private int index;
    private U data;

    private Node(U data){
        this.data = data;
    }
}

And this is how I add a new Node:

public boolean add(T data) {
    if (data == null) {
        return false;
    }

    Node<T> currentNode = new Node<T>(data);

    if (this.isEmpty()){
        currentNode.previousNode = null;
        currentNode.index = 0;
        this.firstNode = currentNode;
    } else {
        currentNode.previousNode = lastNode;
        lastNode.nextNode = currentNode;
        currentNode.index = lastNode.index + 1;
    }
    this.lastNode = currentNode;
    this.size++;
    return true;
}

Could this be made significantly faster? Does the code comply with the Java coding conventions?


texts: Sorting a list but the sort order isn't known until runtime

texts:
I need to sort a list of strings that I'm reading in but the sorted order of that list is not predetermined (I can't hard code it); I read in the sort order from a source and build a comparator by assigning a numerical value to each entry in a map and then use that to determine the order.
My implementation is pretty simple and straightforward. I don't know if there is any room to optimize this but given that sorting is generally a slow process in itself, I wanted to submit this for code review in case there are in fact any improvements to be made.
The custom comparator will be cached after creation so I won't be building a new one unless required to do so.
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class RunTest {
   // Runnable test
   public static void main(String[] args) {
      CustomComparator comparator = CustomComparator.fromList(getSortOrder());

      List<String> list1 = getTestList();

      System.out.println("Test list: \n  " + list1);

      Collections.sort(list1, comparator);

      System.out.println("Test list (sorted): \n  " + list1);
   }

   // Comparator
   public static class CustomComparator implements Comparator<String> {
      private Map<String, Integer> _sortOrder;

      public CustomComparator(Map<String, Integer> sortOrder) {
         _sortOrder = sortOrder;
      }

      @Override
      public int compare(String l, String r) {
         Integer lvalue = _sortOrder.get(l);
         Integer rvalue = _sortOrder.get(r);

         if (lvalue == null || rvalue == null)
            return 0;

         if (lvalue < rvalue)
            return -1;

         return 1;
      }

      public static CustomComparator fromList(List<String> sortOrder) {
         // Map each list item to a comparable integer
         Map<String, Integer> customSortOrder = new HashMap<>();

         int i = 0;

         for (String s : sortOrder)
            customSortOrder.put(s, i++);

         return new CustomComparator(customSortOrder);
      }
   }

   // Custom sort order
   public static List<String> getSortOrder() {
      List<String> customSortOrder = new LinkedList<>();

      customSortOrder.add("c");
      customSortOrder.add("b");
      customSortOrder.add("a");

      return customSortOrder;
   }

   // Test list
   public static List<String> getTestList() {
      List<String> randomList = new LinkedList<>();

      randomList.add("b");
      randomList.add("a");
      randomList.add("c");

      return randomList;
   }
}

Output:

Test list:
  [b, a, c]
Test list (sorted):
  [c, b, a]


texts: Check whether given a pair of arrays are permutation of each other

texts:
Does this implementation guarantee execution of \$O(n)\$ time?  What is the additional space utilization for this implementation by excluding the original array size? Is it \$O(1)\$?

#include<iostream>
#include<set>
#include<algorithm>

bool ArraysPermute(int  array1[],int size1, int  array2[], int size2)
{
       if( size1  != size2)
           return false;
       else
       {
           std::set<int> first_set(array1, array1+size1);
           std::set<int> second_set(array2, array2+size2);

           std::pair<std::set<int>::iterator,std::set<int>::iterator> myPair=std::mismatch(first_set.begin(),first_set.end(),second_set.begin());

           if( *myPair.first != *myPair.second)

                return false;
            else
                return true;
       }
}

int main()
{
    int array1[] ={1,2,3,5};
    int array2[]={1,2,4,3};

    if(ArraysPermute(array1,sizeof(array1)/sizeof(int), array2, sizeof(array2)/sizeof(int)))
        std::cout<< " Arrays are permutation of each other\n";
    else
        std::cout<< " Arrays are not permutation of each other\n";

    return 0;
}


texts: Shortest path in a grid between two points

texts:
I have this problem where I have to find the shortest path in an NxM grid from point A (always top left) to point B (always bottom right) by only moving right or down. Sounds easy, eh? Well here's the catch: I can only move the number shown on the tile I'm sitting on at the moment. Let me illustrate:

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

In this 4x4 grid the shortest path would take 3 steps, walking from top left 2 nodes down to 3, and from there 3 nodes right to 1, and then 1 node down to the goal.

[2] 5  1  2
 9  2  5  3
[3] 3  1 [1]
 4  8  2 [7]

If not for the shortest path, I could also be taking this route:

[2] 5 [1][2]
 9  2  5  3
 3  3  1 [1]
 4  8  2 [7]

That would unfortunately take a whopping 4 steps, and thus, is not in my interest.
That should clear things out a bit. Now about the input.

The user inputs the grid as follows:

5 4      // height and width
2 5 2 2  //
2 2 7 3  // the
3 1 2 2  // grid
4 8 2 7  //
1 1 1 1  //

So what have I done? I figured the best way around this (to begin with) would be BFS. Voila, correct answer on every input. Hurray, it's too freakin' slow.

Anyway here's the code at the moment:

#include <iostream>
#include <vector>

struct Point {
    int y, x, depth;
    Point(int yPos = 0, int xPos = 0, int dDepth = 0) : y(yPos), x(xPos), depth(dDepth) { }
};

struct grid_t {
    int height, width;
    std::vector< std::vector<int> > tiles;

    grid_t() // construct the grid
    {
        std::cin >> height >> width; // input grid height & width

        tiles.resize(height, std::vector<int>(width, 0)); // initialize grid tiles

        for(int i = 0; i < height; i++)     //
            for(int j = 0; j < width; j++)  // input each tile one at a time
                std::cin >> tiles[i][j];    // by looping through the grid
    }
};

int go_find_it(grid_t &grid)
{
    std::vector<Point> openList, closedList;
    openList.push_back(Point(0, 0)); // (0, 0) is the first point we want to consult, of course

    do
    {
        closedList.push_back(openList[0]); // the tile we are at is good and checked. mark it so.
        openList.erase(openList.begin()); // we don't need this guy no more

        int y = closedList.back().y; // now we'll actually move to the new point
        int x = closedList.back().x; //
        int depth = closedList.back().depth; // the new depth

        if(y == grid.height-1 && x == grid.width-1) return depth; // the first path is the shortest one. return it

        int jump = grid.tiles[y][x]; // 'jump' is the number shown on the tile we're standing on.
        grid.tiles[y][x] = 0; // mark the tile visited

        if(y + jump < grid.height && grid.tiles[y+jump][x] != 0) // if we're not going out of bounds or on a visited tile
        {
            openList.push_back(Point(y+jump, x, depth+1)); // push in the new promising point along with the new depth
        }
        if(x + jump < grid.width && grid.tiles[y][x+jump] != 0) // if we're not going out of bounds or on a visited tile
        {
            openList.push_back(Point(y, x+jump, depth+1)); // push in the new promising point along with the new depth
        }
    }
    while(openList.size() > 0); // when there are no new tiles to check, break out and return false

    return 0;
}

int main()
{
    grid_t grid; // initialize grid

    int min_path = go_find_it(grid); // BFS

    std::cout << min_path << std::endl; // print the result
    //system("pause");
    return 0;
}

So what I want is some optimization hints, because I suck at it (and am relatively new to C++). Basically jumped into it a month ago with only as much knowledge from PHP and javascript). Should I make it A* instead of BFS? If I did that, how would I calculate the heuristic?


texts: Optimize calculation of distances between pairs of points

texts:
I was trying to solve a challenge. The execution time should not exceed 5s, but for some value my code took longer. I want to know if I can optimize my code for performance.

public class Solution {
    int n;long k;int count=0;
    public static void main(String[] args) {
        new Solution().readInput();

}
public void readInput(){
    try {
        BufferedReader k=new BufferedReader(new InputStreamReader(new FileInputStream("/home/tittanium/NetBeansProjects/HackerRank/src/input.txt")));
        parseNK(k.readLine());
        readAndParse(k.readLine());
        System.out.println(count);
    } catch (IOException ex) {
        Logger.getLogger(Solution.class.getName()).log(Level.SEVERE, null, ex);
    }

}
int cities[];
public void readAndParse(String line){
    int i1=0;
    cities=new int[n];
    StringTokenizer st = new StringTokenizer(line," ");

    while (st.hasMoreElements()) {
         cities[i1]=Integer.parseInt(st.nextToken());
         i1++;
    }
    for(int i=0;i<n;i++){
        final int x=i;
            new Runnable() {
                @Override
                public void run() {
                    for(int j=x;j<n;j++){
                        final int a=cities[x];
                        final int b=cities[j];
                        count = (a>b ? a-b : b-a) == k ? count+1 : count;
                    }
                }
            }.run();
        }
}

public void parseNK(String line){
    n= Integer.parseInt(line.split(" ")[0]);
    k= Integer.parseInt(line.split(" ")[1]);
}

}

This question is trying to solve a problem.  I want to know if any changes can be made to make the program run faster.
This is what I am trying to complete. challenge


texts:
I would like to have a minimal storable class in Python that I can use as ORM. I quite thinking my approach is bad, but I would like to have your opinion.
I do not want to use SQLAlchemy or PeeWee as it is too complex for my application.
I wrote a Model class from which I can derivate storable items:
from tinydb import TinyDB, Query
from typing import NamedTuple

class NotNull:
    pass

class Column(NamedTuple):
    name: str
    type: type = str
    default: any = NotNull

class Model():
    __tablename__: str
    __attrs__: [Column]
    __primary_key__: str
    __hidden__: [str]

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '__tablename__'):
            cls.__tablename__ = cls.__name__.lower()

        if not hasattr(cls, '__hidden__'):
            cls.__hidden__ = []

        return super().__new__(cls)

    def __init__(self, *args, **kwargs):
        # Fill attributes in order
        for attr, arg in zip(self.__attrs__, args):
            if attr.name in self.__hidden__:
                continue

            if not isinstance(arg, attr.type):
                raise ValueError(f"{attr.name} has not type {str(attr.type)}")

            setattr(self, attr.name, arg)

        # Fill conditional attributes
        for attr, value in kwargs.items():
            u = [attrs for attrs in self.__attrs__ if attrs[0] == attr]
            if not u:
                continue
            type = u[0].type

            if not isinstance(value, type):
                raise ValueError(f"{attr} isn't type {str(type)}")

            setattr(self, attr, value)

        # Fill remaining attributes with None
        for attr in self.__attrs__:
            if getattr(self, attr.name, None) is None:
                if len(attr) == 2:
                    raise ValueError(f"{attr.name} has no default value")

        self._post_init()

    def _post_init(self, *args, **kwargs):
        pass

    @classmethod
    def _db(cls):
        table = getattr(cls, '__tablename__', cls.__name__.lower())
        return TinyDB(data_dir(table + '.json'))

    @classmethod
    def all(cls):
        """Get all users from the database."""
        return [cls(**user) for user in cls._db().all()]

    def save(self):
        """Save a new user into the database."""
        pk = self.__primary_key__
        pk_value = getattr(self, pk)
        if self.find(pk_value):
            query = getattr(Query(), pk)
            self._db().update(self.to_dict(), query == pk_value)
            return

        self._db().insert(self.to_dict())

    @classmethod
    def truncate(cls):
        cls._db().truncate()

    @classmethod
    def find(cls, name):
        """Find a user into the database."""
        user = Query()
        results = cls._db().search(user.name == name)
        return cls(**results[0]) if results else []

    def __repr__(self):
        data = ','.join([
            '='.join([attr[0], str(getattr(self, attr[0]))])
            for attr in self.__attrs__ if attr[0] not in self.__hidden__
        ])
        return f'{self.__class__.__name__}({data})'

    def to_dict(self):
        return {attr[0]: getattr(self, attr[0]) for attr in self.__attrs__}

    def to_json(self):
        return to_json(self.to_dict())

For example if I want to store articles:
class Article(Model):
    __attrs__ = [
        ('name', str),
        ('type', str, 'sausage'),
        ('price', float, 0.0)
    ]
    __primary_key__ = 'name'

Then I can use it as follow:
>>> Article('apple'^, 'vegetable', 1.12).save()
>>> Article.all()
[Article(name=apple,type=vegetable,price=1.12)]

Would it be better to use shelve?


texts:
I've quickly made a function to deny or allow access to files that are only used thru Ajax calls.

Key Generator

/**
 * Generate a key for file access permission
 *
 * Function that returns a key to grant access to a PHP file
 * that will be consulted by an ajax call.
 *
 * @param str $salt Any given string to append to the session ID
 *
 * @return str Access Key
 */
public function file_access_key_generator($salt) {

    return sha1(session_id() . $salt);

}

Key Validation

/**
 * Match file access permission key
 *
 * Function to match the given key with the one generated.
 *
 * @param str $salt Any given string to append to the session ID
 * @param str $key  Key to match
 *
 * @return bollean
 */
public function file_access_key_check($salt, $key) {

    return ($this->file_access_key_generator($salt) == $key) ? true : false;

}

The goal, as mentioned, is to prevent direct access to files that should only be accessed thru an Ajax Call within the application.

The methodology implemented is as follows:

// Generate the key to pass with the Ajax Post variables
$check = $this->my_class->file_access_key_generator(basename(__FILE__, '.php'));

// Validating the key
if (isset($_POST['check']) &&
    $my_class->file_access_key_check(basename(__FILE__, '.php'), $_POST['check'])) {
     // do stuff...
} else {
     // friendly user message stating that the access to the file isn't autorized
}

Essentially, what is being done is to generate a key combining the file name and the session ID. Both must match otherwise the access isn't allowed.

Does this secures the access to the file or some considerations are to be made in order to actually secure the file that receives Ajax calls, thus preventing a direct browser access or the file being included within another one?


texts:
How could this code be improved and have fewer repeated lines?

vent.on("createAccountLayout:rendered", function() {
    logger.info('createAccountLayout:rendered => CreateAccountLayoutController');
    showRegion(['phoneNumberRegion', 'keyboardRegion', 'nextRegion', 'quitRegion']);

    vent.trigger('createAccountLayout:setToNumericKeyboard');
});

vent.on('createAccountPhoneNumberView:nextStep', function() {
    closeRegion(['phoneNumberRegion', 'keyboardRegion', 'nextRegion']);
    showRegion(['nameRegion', 'keyboardRegion', 'nextRegion']);

    vent.trigger('createAccountLayout:setToAlphaNumericKeyboard');
    vent.trigger('createAccountLayout:disableNextButton');
});


texts: Using Autofac with static services class

texts:
I am using Autofac to maximise the sharing of code between Android and iOS via a shared PCL assembly in a Xamarin (native) environment. The shared service layer consists of four interfaces to classes containing methods or data that don't change throughout the lifetime of the application.
Instead of resolving the service classes from the Autofac singleton container at every point of use, I've thought of creating a class of static references to the services.
I would like to know whether there is something intrinsically wrong with this approach (e.g. memory leaks), or if there are any better suggestions someone could make.
This is the gist:
Android (& equivalent iOS):
public class BootStrap
{
    private static IContainer container = null;
    public static IContainer Container()
    {
        if (container == null)
        {
            ContainerBuilder builder = new ContainerBuilder();
            builder.RegisterType<CacheFactory>().SingleInstance().As<ICacheFactory>(); ;
            builder.RegisterType<ClientFactory>().SingleInstance().As<IClientFactory>();
            builder.RegisterType<CoreHelpers>().SingleInstance().As<ICoreHelpers>();
            builder.RegisterType<PrefsSerializer>().SingleInstance().As<IPrefsSerializer>();
            builder.RegisterType<Services>().SingleInstance();
            container = builder.Build();
        }
        return container;
    }
}

public class MainApp
{
    private ILifetimeScope RootScope;

    public MainApp
    {
        RootScope = BootStrap.Container().BeginLifetimeScope();         // register types, return container
        RootScope.Resolve<Services>();                                  // set static Services members
    }

    ~MainApp()
    {
        RootScope.Dispose();
    }
}

Shared Assembly:
public class Services
{
    public static ICacheFactory CacheFactory;       // data and methods
    public static IClientFactory ClientFactory;     // data and methods
    public static ICoreHelpers CoreHelpers;         // methods only
    public static IPrefsSerializer PrefsHelper;     // methods only

    public Services(ICacheFactory _cacheFactory, IClientFactory _clientFactory, ICoreHelpers _coreHelpers, IPrefsSerializer _prefsHelper)
    {
        CacheFactory = _cacheFactory;
        ClientFactory = _clientFactory;
        CoreHelpers = _coreHelpers;
        PrefsHelper = _prefsHelper;
    }
}

Usage:
Services.CacheFactory.GetCache().DoSomething();
UserClient user = Services.ClientFactory.GetUserClient();
...


texts: Abstract Interface for managing Init/Shutdown

texts:
In a small game project I'm using 'Init' and 'Shutdown' functions on Systems/Managers/Components to make resetting them easier without having to call the constructor/destructor.

For example when reloading a level you can just call Shutdown and Init to reset to the starting state.

A potential problem however I noticed is that I have to be careful when I call Init and Shutdown, and unless I track the init, or 'active', state of the object and explicitly check for it, undefined behavior could creep in. For example, if I ever accidentally shutdown without init first, etc.

If for no reason other than curiosity, I wanted to see if I could make an abstract interface that would make tracking and maintaining the active state easier. It would be included in any class that uses the 'Init' 'Shutdown' format and with minimal other work from the user would help prevent some of the potential issues. Here is the behavior I wanted to achieve:

Calling Init when not active makes the object active
Calling Shutdown when active makes the object inactive
Calling Shutdown when inactive is ignored
Calling Init when already active calls Shutdown, then Init.

The interface I came up with is as follows:

class InitInterface
{
public:
    InitInterface() : IsActive(IsActive_), IsActive_(false) {}

    // 1. If we are not active, set us to active
    // 2. If we are active, run shutdown (virtually)
    void PreInit()
    {
        if(IsActive) this->Shutdown(); // virtual shutdown call
        IsActive_ = true;
    }

    // return value represents if a shutdown is necessary given our current active state.
    // 1. If we are not active then we can't shut down, so return true (skip shutting down in the derived class)
    // 2. If we are active, set us to not active and return false      (we do need to shut down and not skip it in the derived class)
    bool PreShutdown()
    {
        if(!IsActive) return true;
        IsActive_ = false;
        return false;
    }

    // pure virtual functions we need to implement
    virtual void Init()     = 0;
    virtual void Shutdown() = 0;

    const bool &IsActive; // read-only
private:
    bool IsActive_;
};

And to use it the minimum user implementation I've come up with would be:

class B : public A, public InitInterface
{
public:
    // REQUIRED 1: Shutdown in Destructor
    ~B() { Shutdown(); }

    // REQUIRED 2: Implement Init and call PreInit() as first line
    void Init()
    {
        PreInit(); // calls shutdown virtually
        // INIT CODE HERE
    }

    // REQUIRED 3: Implement Shutdown and check if PreShutdown() indicates a shutdown is necessary
    void Shutdown()
    {
        if(PreShutdown()) return;
        // SHUT DOWN CODE HERE
    }
};

Basically when the user writes a class that should support Init/Shutdown, they include it as a base class and must include the three sections marked as REQUIRED.

Here's an example program to test.

My question is, Is there any way to simplify what the user is required to write even further?

For example I initially wanted to virtually call Shutdown in the destructor of InitInterface to eliminate requirement #1, but realized that this wouldn't work since class B would be destructed before InitInterface.


texts: Advent of code 2017 Day 2 (2) in Functional Programming (FP)

texts:
I wanted to practice functional programming (fp) without using any library but using vanilla JS only. So I took a problem from Advent of Code (the 2nd part of Day 2):

https://adventofcode.com/2017/day/2

I'm doing the 2nd part of Day 2. You can only access the 2nd part once you solved the 1st part.

To access the 2nd part type in this number 50376 or check out the solution here: Advent of Code Day 2 (1) in Functional programming (FP)

  It sounds like the goal is to find the only two numbers in each row
  where one evenly divides the other - that is, where the result of the
  division operation is a whole number. They would like you to find
  those numbers on each line, divide them, and add up each line's
  result.

  For example, given the following spreadsheet:

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

  In the first row, the only two numbers that evenly divide are 8 and 2;
  the result of this division is 4. In the second row, the two numbers
  are 9 and 3; the result is 3. In the third row, the result is 2. In
  this example, the sum of the results would be 4 + 3 + 2 = 9.

My solution in FP:

/*jshint esversion: 6*/
{
  'use strict';

  const INPUT =
    `6046   6349    208 276 4643    1085    1539    4986    7006    5374    252 4751    226 6757    7495    2923
1432    1538    1761    1658    104 826 806 109 939 886 1497    280 1412    127 1651    156
244 1048    133 232 226 1072    883 1045    1130    252 1038    1022    471 70  1222    957
87  172 93  73  67  192 249 239 155 23  189 106 55  174 181 116
5871    204 6466    6437    5716    232 1513    7079    6140    268 350 6264    6420    3904    272 5565
1093    838 90  1447    1224    744 1551    59  328 1575    1544    1360    71  1583    75  370
213 166 7601    6261    247 210 4809    6201    6690    6816    7776    2522    5618    580 2236    3598
92  168 96  132 196 157 116 94  253 128 60  167 192 156 76  148
187 111 141 143 45  132 140 402 134 227 342 276 449 148 170 348
1894    1298    1531    1354    1801    974 85  93  1712    130 1705    110 314 107 449 350
1662    1529    784 1704    1187    83  422 146 147 1869    1941    110 525 1293    158 1752
162 1135    3278    1149    3546    3686    182 149 119 1755    3656    2126    244 3347    157 865
2049    6396    4111    6702    251 669 1491    245 210 4314    6265    694 5131    228 6195    6090
458 448 324 235 69  79  94  78  515 68  380 64  440 508 503 452
198 216 5700    4212    2370    143 5140    190 4934    539 5054    3707    6121    5211    549 2790
3021    3407    218 1043    449 214 1594    3244    3097    286 114 223 1214    3102    257 3345`;

  const sum = (a, b) => a + b;
  const evenlyDiv = (diff, val) => {
    const row = val.split(/\t/);
    return diff.concat(row
      .reduce((d, v, i, line) => {
        return d + line.reduce((reduceRes, runningVar) => {
          return (runningVar % v === 0 && runningVar !== v) ?
            reduceRes + (runningVar / v) :
            reduceRes;
        }, 0);
      }, 0));
  };
  const solution = INPUT.split(/\n/)
    .reduce(evenlyDiv, [])
    .reduce(sum);

  console.log("solution ", solution);
}

Is there a better way to write it in FP with pure JavaScript, i.e. no additional FP library? Any improvement suggestions are welcomed.


texts: When to initialize infrequently used base class objects

texts:
I have a business object base class which is inherited by my business objects:

public class ErrorBase
{
    public bool HasError { get; set; }
    public List<Error> ErrorList { get; set; }

    public ErrorBase()
    {
        HasError = false;
        ErrorList = new List<Error>();
    }
}

Can this be optimized? My concern is that List<Error> is initialized every time a business object is instantiated, regardless of whether an Error object is ever added.

The only alternative I can think of is initializing ErrorList = null, then checking ErrorList != null before calling ErrorList.Add(), but I'm not sure that performing that check every time before adding an Error is actually an optimization. It certainly adds steps to the process of adding an Error object to the List<>.

Is there another way I'm not thinking of? If not, is one of these approaches considered a best practice?


texts:
In an Azure Function, I have a c# program that processes tab delimited data into JSON entries. I'd like to improve it in terms of performance and the connection management.

I want to remove personal data from each line.* As each line gets prepped for turning into JSON I perform this function for two values.** I need to work with the depersonalised data but the operational systems will need to request data from the system. They have access to the PII but the analytical platform (downstream of this function) will not have it. The Key Value pairs are therefore constructed so that the operational system and the log ingestion processes can extract guids. Each key is like AccountID:PIItype:PII and then each value is a guid.***

If I've previously depersonalised a value, I want to retrieve the previously provided value from the Azure Redis Cache. If it doesn't exist, add it to the cache.

using StackExchange.Redis;
using System.Text;
using System.Threading;

private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            ThreadPool.SetMinThreads(50, 50);
            string redisCacheName = System.Environment.GetEnvironmentVariable("rediscache_name", EnvironmentVariableTarget.Process).ToString();
            string redisCachePassword = System.Environment.GetEnvironmentVariable("rediscache_password", EnvironmentVariableTarget.Process).ToString();
            return ConnectionMultiplexer.Connect(redisCacheName + ",abortConnect=false,ssl=true,password=" + redisCachePassword);
        });

public static ConnectionMultiplexer Connection
{
    get
    {
        return lazyConnection.Value;
    }
}

static string depersonalise_value(string input, string field, int account_id)
{
    IDatabase cache = Connection.GetDatabase();
    string depersvalue = $"{account_id}:{field}:{input}";
    string existingguid = (string)cache.StringGet(depersvalue);
    if (String.IsNullOrEmpty(existingguid))
    {
        string value = $"{account_id}{Guid.NewGuid()}";
        cache.StringSet(depersvalue, value);
        return (value);
    }
    else return (existingguid);
}

* Hashing is something considered but discarded

** The two values are independent of each other

*** There is a redis cache per region so can't rely on uniqueness of the guid by host. This is just a simple preventative as an account can only come from a single region.


texts: Quickly applying gravity force between bodies

texts:
I have a function for applying gravity forces between every possible pair of bodies on my game. It is the most used function, and can run more than 100k times per frame so every minor improvement on performance will make a HUGE difference here.

I replaced some divisions by multiplications and the general FPS increased from 5fps to 20fps with ~1000 bodies. This is how performance is affected by this function.

Precision can be decreased if it increases performance considerably. Just make sure you make it clear that a change will decrease precision in your review.

applyGravityBetween(bodyA, bodyB, collisionCallback) {
    var distX = bodyB.x - bodyA.x,
        distY = bodyB.y - bodyA.y,
        distSqr = distX * distX + distY * distY,
        forceA, forceB, dist;

    if (distSqr > (bodyA.radius + bodyB.radius) * (bodyA.radius + bodyB.radius)) {

        // ALERT: Radical actions were taken here to make faster code. Division was avoided at max.

        dist = 1 / Math.sqrt(distSqr); // Dividing one by the distance allows us to multiply instead of dividing later when setting actual velocities, which is more performant.
        forceA = bodyB.mass * dist * dist;
        forceB = bodyA.mass * dist * dist; // Instead of dividing by `distSqr` we can multiply by `dist` twice.

        bodyA.vx += forceA * distX * dist;
        bodyA.vy += forceA * distY * dist;

        bodyB.vx -= forceB * distX * dist;
        bodyB.vy -= forceB * distY * dist;
    } else if (typeof collisionCallback === "function" && bodyA.collidable && bodyB.collidable) collisionCallback(bodyA, bodyB);
}

EDIT:

Here's a benchmark for each separate piece from this function, so you can focus on what you're going to improve:

var declarations took 3.199ms on average to run. Collision check took 3.342ms. Math.sqrt() took 3.122ms.

This question is also related to this one, so if you're interested you can go there too and... Review.


texts: Merging two files' lines of text for output

texts:
My program is supposed to merge two text files' lines together. For instance, if I have two files, one.txt:

a b c d e f g h i j k l m
n o p q r s t u v w x y z

and two.txt:

0 1 2 3 4
5 6 7 8 9

The output is:

a b c d e f g h i j k l m0 1 2 3 4
n o p q r s t u v w x y z5 6 7 8 9

However, I  feel as though some of the conditions are redundant. However, I'm not sure how I can better design this.

// Program to merge lines from two files and output results
#include <stdio.h>

int main(int argc, char *argv[])
{
    char *inName1 = argv[1], *inName2 = argv[2];
    FILE *in1, *in2;
    int c, d;

    // Ensure correct usage
    if (argc != 3)
    {
        fprintf(stderr, "Usage: ./merge <file1> <file2>\n");
        return 1;
    }

    // Open input files and return if unable to open
    if ((in1 = fopen(inName1, "r")) == NULL)
    {
        fprintf(stderr, "Can't open %s.\n", inName1);
        return 2;
    }

    if ((in2 = fopen(inName2, "r")) == NULL)
    {
        fprintf(stderr, "Can't open %s.\n", inName2);
        return 3;
    }

    // Take care of output
    while ((c = getc(in1)) != EOF)
    {
        if (c != '\n')
            putc(c, stdout);
        else
        {
            while ((d = getc(in2)) != EOF)
            {
                if (d != '\n')
                    putc(d, stdout);
                else
                {
                    putc('\n', stdout);
                    break;
                }
            }

            if (d == EOF)
            {
                while (c != EOF)
                {
                    putc(c, stdout);
                    c = getc(in1);
                }
            }
        }
    }

    if (c == EOF)
    {
        while ((d = getc(in2)) != EOF)
        {
            putc(d, stdout);
        }
    }

    fclose(in1);
    fclose(in2);

    printf("\nProcess ended successfully.\n");

    return 0;
}


texts: Securely convert and return a user selected file

texts:
I designed a Python3 webservice which gets a file name, looks for this file in a local folder, converts it using an external software, then sends the converted file to the user.

For this example, the input and output file types are respectively PNG and JPEG, but they're actually proprietary formats.

Here is my code:

#!/usr/bin/python3
# -*- coding: utf-8 -*

from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import os.path as op
import subprocess as sub
from urllib.parse import parse_qs, urlparse

PORT_NUMBER = 8080
PNG_TO_JPG_CALL = '/usr/share/png-to-jpg'
PNG_FOLDER = '/home/foo/png_files'

class RequestHandler(BaseHTTPRequestHandler):
    # Display a text to the user.
    def display_msg(self, text):
        print(text)
        self.send_header('Content-type', 'text/plain; charset=utf-8')
        self.send_header('Content-Disposition', 'inline')
        self.end_headers()
        self.wfile.write(bytes(text, 'UTF-8'))

    # Send a file to the user (open the Download File dialog box).
    def send_file(self, file_path, jpg_name):
        self.send_header('Content-type', 'image/jpeg')
        self.send_header('Content-Disposition', 'attachment; filename="%s"' % jpg_name)
        self.end_headers()
        with open(file_path, 'rb') as f:
            self.wfile.write(f.read())

    # Check for GET requests
    def do_GET(self):
        self.send_response(200)

        # Get URL arguments
        url_args = parse_qs(urlparse(self.path).query, keep_blank_values=True)

        # Check for the `id` attribute
        if 'id' not in url_args:
            self.display_msg('USAGE: [...]/?id=some_file.jpg')
            return

        target = url_args['id'][0]

        # Check if the requested file have the good extension
        if target[-4:] != '.jpg':
            self.display_msg('TARGET SHOULD BE A PNG FILE')
            return

        # build the png file path (change the extension)
        png_path = op.join(PNG_FOLDER, op.splitext(target)[0] + '.png')
        print('Looking for %s' % png_path)

        # Check if the requested is present on the disk
        if not op.isfile(png_path):
            self.display_msg('PNG FILE NOT FOUND')
            return

        # call the converter with the requested file, print the output
        p = sub.Popen([PNG_TO_JPG_CALL, png_path], stdout=sub.PIPE, stderr=sub.PIPE)
        output, errors = p.communicate()
        if output:
            print('output: %s' % output.decode('utf-8'))

        # Check for errors outputs
        if errors:
            self.display_msg('CONVERSION ERROR: png-to-jpg says:\n' + errors.decode('utf-8'))
            return

        # Build the converted file path
        jpg_name = op.splitext(target)[0] + '.jpg'
        jpg_path = op.join(os.getcwd(), jpg_name)

        # Check if the converted file is present on the disk
        if not op.isfile(jpg_path):
            self.display_msg('CONVERSION ERROR: Can not locate the ouput directory.')
            return

        # returns the converted file then remove it
        self.send_file(jpg_path, jpg_name)
        os.remove(jpg_path)

# Launch the web server
try:
    server = HTTPServer(('', PORT_NUMBER), RequestHandler)
    print('Web server started. Please go to 127.0.0.1:%i.' % PORT_NUMBER)
    server.serve_forever()
except KeyboardInterrupt:
    print('Interrupted by the user - shutting down the web server.')
    server.socket.close()

Is this secure?


texts:
As you know there is an algorithm in C++ standard library called std::merge, that merges two sorted ranges into another range. I try to write another merge (called multi_merge) that gets multiple sorted ranges (one or more), and merged them in one.
The code is as follows:

#include <utility>
#include <vector>
#include <algorithm>
#include <iterator>

template<typename I>
using range = std::pair<I, I>;

template<typename I>
struct is_empty_range {
    bool operator()(const range<I>& x) const {
        return x.first == x.second;
    }
};

template<typename I, typename Compare>
struct range_compare {
    range_compare(Compare comp) : comp_{ comp } {}
    bool operator()(const range<I>& x, const range<I>& y) const {
        return comp_(*x.first, *y.first);
    }

    Compare comp_;
};

template<typename I, typename O, typename Compare>
O multi_merge(std::vector<range<I>> inputs, O output, Compare comp) {
    inputs.erase(std::remove_if(std::begin(inputs), std::end(inputs), is_empty_range<I>{}),
        std::end(inputs));

    if (inputs.empty())
        return output;

    while (inputs.size() != 1) {
        auto min = std::min_element(std::begin(inputs), std::end(inputs), range_compare<I, Compare>{comp});
        if (min->first != min->second) {
            *output = *min->first;
            ++min->first;
            ++output;
        }
        else {
            inputs.erase(min);
        }
    }

    return std::copy(inputs[0].first, inputs[0].second, output);
}

template<typename I, typename O>
O multi_merge(std::vector<range<I>> inputs, O output) {
    return multi_merge(inputs, output, std::less<typename std::iterator_traits<I>::value_type>{});
}

I want to know your opinions about this code, especially the way I'm passing list of ranges (a vector of pairs of iterators) to the algorithm. Do you recommend a more general way?

Here is a simple piece of code to test the algorithm:

#include <numeric>
#include <iostream>

int main() {
    constexpr size_t count = 10000;
    std::vector<int> v(count);
    std::iota(v.begin(), v.end(), 0);
    std::random_shuffle(v.begin(), v.end());

    using it_t = std::vector<int>::iterator;
    std::vector<range<it_t>> inputs;
    for (auto part = 0u; part <= count - 1000; part += 1000)
        inputs.emplace_back(v.begin() + part, v.begin() + part + 1000);

    for (auto r : inputs)
        std::sort(r.first, r.second);

    std::vector<int> output;
    output.reserve(count);

    multi_merge(inputs, std::back_inserter(output));

    std::cout << std::boolalpha << "output size is correct: "
        << (output.size() == count) << '\n';
    std::cout << std::boolalpha << "output is sorted: "
        << std::is_sorted(output.begin(), output.end()) << '\n';
}

 Godbolt Link


texts:
I wrote my first Python program today after working through a few books. I decided to build a group initiative tracker for our D&D group and was hoping to get some feedback. Critiques on code efficiency, formatting, suggestions, etc would be appreciated. My plan is to eventually take this from a command-line application to a django or flask web app, or maybe an iOS app.

print('Welcome to Initiative Tracker!')
while True:
    try:
        loop_count=int(input("\nHow many PC's and NPC's total? "))
        loop_start = 0
        initiative_tracking = {}
        while loop_start < loop_count:
            player_name = input('What is the Players name? ')
            player_initiative = int(input('What is ' + player_name + ' initiative? '))
            if player_initiative in initiative_tracking:
                initiative_tracking[player_initiative].append(player_name)
            else:
                initiative_tracking[player_initiative] = [player_name]
            loop_start += 1
            continue
        print('\nYour initiative order is: ')
        for key in sorted (initiative_tracking.keys(), reverse=True):
            print(str(key) + ': ' + ', '.join(initiative_tracking[key]))
        break
    except ValueError:
        print("Sorry I didn't catch that. How many PC and NPC total? ")


texts:
In jQuery, I have been reluctant to create a better form validation, and I feel the time has come for me to do so.

With that said, I have been using this particular type of form validation, and I would like to simplify it.

$('#saveSubmit').on('click', function()
{
  var criteria =
  {
    company: $('#company').val(),
    partnercode: $('#partnercode').val(),
    office: $('#office').val(),
    // few more
  }

  // form validation starts here
  if(criteria.company == "")
  {
    $('#compError').show();
    return false;
  }
  if(criteria.partnercode == "")
  {
    $('#compError').show();
    return false;
  }
  if(criteria.office == "")
  {
    $('#compError').show();
    return false;
  }
  // few more if statements
  else
  {
    // if the form parameters are good, send to processing script
    $.post('process/editUser.php', {criteria:criteria}, function(data)
    {
      if(data.indexOf("Error") >= 0)
      {
        $('#errorModal').modal('show');
        $('#message').text(data);
        return false;
      }
      else
      {
        $('#successModal').modal('show');
        $('#messageSuccess').text(data);
        $('#successModal').on('hidden.bs.modal', function()
        {
          $('#successModal').modal('hide');
          location.reload();
        });
      }
    });
  }
});

All of this works like how it should, but I want to make it less verbose, thus the need for a function.

I want to replace that huge if/else statement within that click event with a function.


texts: Extension for BindableBase that can dispose the old value of a property if that property implements IDisposable and is not null

texts:
I am interested in hearing opinions on this. I need a way to dispose the old value of a property in a way that's compatible with BindableBase. Specifically, I have a few bound properties of type System.Drawing.Bitmap. Am I going about this all wrong?

using Prism.Mvvm;
using System;
using System.Runtime.CompilerServices;

namespace App.Infrastructure
{
    public class DisposableAwareBindableBase : BindableBase
    {
        /// <summary>
        /// Set a property, notifying property change listeners. If the property is of a type that implements IDisposable, Dispose() will be called on the old outgoing value if it is not null.
        /// </summary>
        /// <typeparam name="T">Type of property</typeparam>
        /// <param name="storage">Backing storage for property, passed by reference</param>
        /// <param name="value">New value of the property</param>
        /// <param name="propertyName">Property name</param>
        /// <returns>True if the property was set succesfully, false otherwise</returns>
        protected virtual bool SetAndDisposeProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            T old = storage;
            if (!SetProperty(ref storage, value, propertyName)) return false;
            if (old != null && old is IDisposable)
            {
                (old as IDisposable).Dispose();
            }
            return true;
        }
    }
}

Usage:

using App.Infrastructure;
using System.Drawing;

namespace App.UI
{
    internal class ConfigWindowViewModel : DisposableAwareBindableBase
    {

        // ...

        private Bitmap _PreviewImage;
        public Bitmap PreviewImage
        {
            get
            {
                return _PreviewImage;
            }
            set
            {
                SetAndDisposeProperty(ref _PreviewImage, value);
            }
        }

        // ...

    }
}

This class extends BindableBase from Prism Library.


texts:
Python sets are magical things. Mutable, deduplicating data stores with handy operator overloads for &, ^ and |.

Specifically among the others, sets overload the & operator to do mutual membership tests like so:

>>> set("aasd") & set("aabc")
{'a'}

This is endlessly handy, but the huge downside of sets is they do not allow duplicate entries because they're hash tables, so for instance a fuzzy-finder will be a little too fuzzy.

What to do? Why, spin my own, of course!

def membertester(a, b):
    """a slow (iterative) dupe-preserving sorting subset tester,
    for mutual membership tests (like set overloads &)"""
    c = []
    a, b = sorted(list(a)), sorted(list(b))
    (l, maxl, s, minl) = {
        True:  (a, len(a), b, len(b)),
        False: (b, len(b), a, len(a))
    }[ len(a) >= len(b) ]

    for i in range(maxl):
        try:
            if s.count(l[i]) >= l.count(l[i]):
                c.append(a[i])

        except IndexError:
            pass
    return c

How it works, because it might be a little cryptic:

Retrieve the longer and shorter of the two sorted lists, and their lengths, using a switch statement.
For each item in the longer range, take note of the item if the number of occurences of the same item in the short list is greater than or equal to the number of occurences of the item in the longer list.

Used as above:

>>> membertest("aasd", "aabc")
['a', 'a']

Success!

How can I improve it? Is there a faster or more efficient way, or perhaps a less flimsy algorithm?

Assertions that should pass:

assert membertest("a" * 6, '') == []
assert membertest("abdeg", "rrertabasdddhjkdeg") == ['a', 'b', 'd', 'e', 'g']
assert membertest("abddeg", "rrertabasdddhjkdeg") == ['a', 'b', 'd', 'd', 'e', 'g']

An inconsistency I don't understand, but which is definitely a bug:

>>> is_subset('10', '122')
['0']
>>> is_subset("ab", "acc")
['a']

I don't understand this in the slightest.

I wrote this function specifically for use with A-Za-z, so numbers in strings was an oversight I didn't consider.

The other bugs noted in @alexwchan's great answer are definitely not intentional.


texts: Marking duplicate entries in a numpy array as True

texts:
So the problem is

Find the duplicate entries (2nd occurrence onwards) in the given numpy
array and mark them as True. First time occurrences should be False.

And my solution is:
import numpy as np

def duplicates(a):
    uniques = np.unique(a)
    result = []
    for i in a:
        if i not in uniques:
            result.append(True)
        else:
            result.append(False)
            uniques = np.delete(uniques, np.where(uniques == i))
    return result

np.random.seed(100)
a = np.random.randint(0, 5, 10)
print('Array: ', a)
print(duplicates(a))

What improvments can i make in this program?


texts: Python set variables to shorter list and list length

texts:
I have a simple task that I can't find an elegant solution to. Say I have two arrays and I want to find which one is shorter and create variables for both their lengths (specifying them as long and short). Here's an inelegant way to do it:

l1 = len(arr1)
l2 = len(arr2)

if l1 < l2:
    short_arr = arr1
    long_arr = arr2
    lshort = l1
    llong = l2
else:
    short_arr = arr2
    long_arr = arr1
    lshort = l2
    llong = l1

What's a better way to do it?


texts:
I'm pretty new to C# and was just wondering if there is a better way I can write this calculator that I made:

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;

        namespace AnthonyCalculator
               {
        class Program
          {
        static void Main(string[] args)
        {
            double num01;
            double num02;
            int userChoice = 1;

            Console.WriteLine ("What is your first number?: ");
            num01 = double.Parse (Console.ReadLine());

            Console.WriteLine ("\nPlease select one of the following (1-4)");
            Console.WriteLine ("1 - Add");
            Console.WriteLine ("2 - Subtract");
            Console.WriteLine ("3 - Divide");

            Console.Write("Select number 1-3: ");
            userChoice = int.Parse (Console.ReadLine ());

            switch (userChoice)
            {
                case 1:
                    Console.WriteLine ("\nAddition Selected: ");
                    Console.Write ("\nSecond number: ");
                    num02 = double.Parse (Console.ReadLine());
                    Console.WriteLine ("\nTotal of " + num01 + " + " + num02 + "      = " + (num01 + num02));
                    break;

                case 2:
                    Console.WriteLine ("Subtract Selected: ");
                    Console.Write("\nSecond number: ");
                    num02 = double.Parse(Console.ReadLine());
                    Console.WriteLine("\nTotal of " + num01 + " - " + num02 + " = " + (num01 - num02));
                    break;

                case 3:
                    Console.WriteLine("Division Selected: ");
                    Console.Write("\nSecond number: ");
                    num02 = double.Parse(Console.ReadLine());
                    Console.WriteLine("\n Total of " + num01 + " / " + num02 + " = " + (num01 / num02));
                    break;

                default:
                    Console.WriteLine("Sorry, incorrect input");
                    break;
            }
            Console.ReadLine();

        }
    }
}


texts:
I was inspired from question here, to implement function container that holder any kind of function by using boost::any, I have carried on and extend it further to make the functions holder accept lambda and functor. Also, I have implemented my own any class (AnyFunction) which is seemed work perfectly.

I would like to know how can I improve it further?

#include <functional>
#include <typeindex>
#include <string>
#include <tuple>
#include <map>
#include <cassert>
#include <iostream>
#include <memory>

template <class...>
using void_t = void;

template <class C, class X = void_t<>>
struct has_result_type : std::false_type {};

template <class C>
#define TRAIT_CASE decltype(std::declval<typename C::result_type>())
struct has_result_type<C, void_t<TRAIT_CASE>> : std::true_type {};

class AnyFunction
{
    struct placeholder
    {
        virtual ~placeholder() {}
    };

    template <typename T>
    struct holder : placeholder
    {
        holder(const T& t) : data(t) {}
        T data;
    };

public:
    template <typename T>
    AnyFunction(T&& t) :
    mContent(std::make_shared<holder<std::decay_t<T>>>(std::forward<T>(t)))
    {
    }

    template <typename T>
    const T& cast() const
    {
        assert(dynamic_cast<const holder<T>*>(mContent.get()) != nullptr);
        return static_cast<const holder<T>&>(*mContent).data;
    }

private:
    std::shared_ptr<placeholder> mContent = nullptr;
};

class FunctionHolder
{
public:
    template <typename F>
    void insert(const F& f)
    {
        insertImpl<F>(f, &F::operator());
    }

    template <typename... Ts>
    decltype(auto) call(Ts&&... ts) const
    {
        using type = typename std::tuple_element<0, std::tuple<Ts...>>::type;
        auto it = mFunctionHolder.find(typeid(type));
        assert(it != mFunctionHolder.end());
        return it->second.cast<std::function<type(Ts...)>>()(std::forward<Ts>(ts)...);
    }

private:
    template
    <
        typename F,
        typename R,
        typename... Ts,
        typename = std::enable_if_t<!has_result_type<F>::value>
    >
    void insertImpl(const F& f, R(F::*)(Ts...) const)
    {
        std::function<R(Ts...)> temp = f;
        insertImpl(typeid(R), temp);
    }

    template <typename F, typename = std::enable_if_t<has_result_type<F>::value>>
    void insertImpl(const F& f, bool)
    {
        insertImpl(typeid(typename F::result_type), f);
    }

    template <typename F>
    void insertImpl(const std::type_index& key, const F& f)
    {
        auto result = mFunctionHolder.emplace(key, f);
        if (!result.second)
        {
            std::cerr << "ERROR: key "
                + std::string(key.name())
                + " was already inserted\n";
        }
    }

private:
    std::map<std::type_index, AnyFunction> mFunctionHolder;
};

struct Functor
{
    int operator()(int i, int j) const
    {
        return i + j;
    }
};

int main()
{
    std::function<std::string(std::string, int)> fn = [](const std::string& s, int i)
    {
        return "Hello " + s + " " + std::to_string(i);
    };
    auto lambda = [](double i, int j) { return i * j; };
    Functor functor;

    FunctionHolder holder;

    holder.insert(fn);
    holder.insert(lambda);
    holder.insert(functor);

    std::cout << holder.call(1.5, 2) << std::endl;
    std::cout << holder.call(1, 2) << std::endl;
    std::cout << holder.call(std::string("World!"), 2016) << std::endl;
}


texts: Maximum Subarray Problem - Iterative O(n) algorithm

texts:
I implemented an iterative \$O(n)\$ algorithm for solving the maximum sub-array problem. I would like a general review for it.

Here the max_subarray is the main function and the ones which are static are auxiliary functions for it.

#include<stdio.h>

int max_subarray(int array[], int *low, int *high);

static void initialize(int *sum, int *low, int *high);
static void update_var(int increase, int *sum, int *low, int *high, int i);

int main()
{
    //The maximum subarray-sum is 43 for the following
    int array[16] = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7};
    int low = 0;
    int high = 15;

    printf("%d", max_subarray(array, &low, &high));
    printf("\n%d %d", low, high);

    return 0;
}

int max_subarray(int array[], int *low, int *high)
{
    int max_sum, max_low, max_high;
    int bet_sum, bet_low, bet_high;
    int inc_sum, inc_low, inc_high;

    initialize(&max_sum, &max_low, &max_high);
    initialize(&bet_sum, &bet_low, &bet_high);
    initialize(&inc_sum, &inc_low, &inc_high);

    for (int i = *low; i <= *high; i++)
    {
        if (max_sum + bet_sum + array[i] > max_sum) {
            update_var(bet_sum + array[i], &max_sum, &max_low, &max_high, i);
            initialize(&bet_sum, &bet_low, &bet_high);
            initialize(&inc_sum, &inc_low, &inc_high);

        } else {
            update_var(array[i], &bet_sum, &bet_low, &bet_high, i);
            if (inc_sum + array[i] > inc_sum) {
                update_var(array[i], &inc_sum, &inc_low, &inc_high, i);
                if (inc_sum > max_sum) {
                    max_sum = inc_sum;
                    max_low = inc_low;
                    max_high = inc_high;
                    initialize(&bet_sum, &bet_low, &bet_high);
                    initialize(&inc_sum, &inc_low, &inc_high);
                }
            }
        }
    }
    *low = max_low;
    *high = max_high;
    return max_sum;
}

static void update_var(int increase, int *sum, int *low, int *high, int i)
{
    *sum += increase;
    *high = i;
    if (*low == -1) {
        *low = i;
    }
}

static void initialize(int *sum, int *low, int *high)
{
    *sum = 0;
    *low = -1;
    *high = -1;
}


texts: Fast regex to extract strings before and after a time

texts:
I want to get text1 and text2 by splitting time format

Text1 10:24:02 Text2

Of the two working regexes below, which is faster?

Regex 1

String regex1= "([0-9]{2}):([0-9]{2}):([0-9]{2})";

Regex 2

String regex2= "[0-9][0-9]:[0-9][0-9]:[0-9][0-9]";

This is the code I've used:

String s="Text1 10:24:02 Text2";
String[] split= s.split(regex1);//regex 1 and 2
System.out.println(split[0]);
System.out.println(split[1]);


texts:
I can't get a peer review where I work, I was wondering how my code was and how could it be improved.

https://github.com/lamondea/uploader

Is it a good practice to use functions in classes or should it be replaced by external function that use the object returned by the class:

class _export
{
    public $nbr;
    public $file;

    public function __construct($file,$nbr=0){
        if($nbr != 0 && ($file->ext == 'jpg' || $file->ext == 'png' || $file->ext == 'gif'))
            thumbnailer($file,$nbr);
        else {
            move_uploaded_file($file->tmp_name, ($file->loc).($file->name));
            return $file->name;
        }
    }
}


texts:
I'm trying to learn F# by creating a little web scraper that will do custom scraping based on the url domain. For this, I need to create and select the correct kind of scraper. I figure I would use a Factory that would determine the correct kind of scraper for me.

So here is the interface for my scraper

type IExtractor =

    /// determines if the extractor will work for the url
    /// returns true if the extrator can handle the url
    abstract member Suitable : string -> bool

    /// name of the extractor
    abstract ExtractorName : string with get

Here is the instance of one of the scrapers

type CustomExtractor1() =

    /// <summary>
    /// tests whether the input url is valid
    /// </summary>
    /// <param name="url"></param>
    let (|ValidUrl|_|) url =
        let regexExpression = "^http(s)?://www\.customsite\.com.*\?fd="
        // regex helper that returns string option
        Common.UrlMatch regexExpression url

    interface IExtractor with
        member this.Suitable url =
            match url with
            | ValidUrl url -> true
            | _ -> false

        member this.ExtractorName with get() = "Custom extractor"

Here is the Factory

module Extractor =

    let private _extractors: IExtractor list = [new CustomExtractor1(); new CustomExtractor2()]

    let create url =
        let isSuitable (input: string) (ex:IExtractor)  = ex.Suitable input
        let one (input:string) (ex:IExtractor) = true
        match (_extractors |> List.tryFind (isSuitable url) ) with
        | Some ex -> Some ex
        | _ -> None

Here is the usage

 let input = "https://www.customsite.com?fd=cWz5d"
            let extractor = Extractor.create input

            let extractorOption =
                match Extractor.create input with
                | Some ex -> Some ex
                | _ ->
                     (
                     raise (Error ("no extractor found. Exiting"))
                     )

            let extractor = extractorOption.Value

            // do stuff with extractor
            printfn "%s" extractor.ExtractorName

The flow for this usage somehow feels more like C#, so it seems a little off. Especially in the usage where I'm using extractorOption.Value. I am currently investigating using ROP instead of exception handling for better control flow.

What do you think — is there a way to improve this?


texts: Extracting filenames from a URL by splitting a string

texts:
I am used to accessing items from an array, returned by the Split function, directly. This is lazy, I know. Usually, I know the element I want and I say something like:

Debug.Print Split(href, "/")(0)

Questions:

1) Can I do something similar to access the UBound of the array returned?

2) What is the "best practice" way of doing things and why?

Code:

I wrote the following but it looks messy.

Sub Testing()

    Dim href As String
    Dim fileName As String

    href = "https://www.england.nhs.uk/statistics/wp-content/uploads/sites/2/2018/01/20180111-AmbSYS-post-ARP-month-of-December-2017v2.xlsx"

    fileName = Trim$(Split(href, "/")(UBound(Split(href, "/"))))

End Sub

I saw from here that I can also do:

Debug.Print Split(href, "/")(Len(href) - Len(Replace(href, "/", "")))

Again, messy.

I know that I can assign to an array variable and then access the UBound that way. It looks tidier but is essentially the same thing; i.e.

Dim myArr() As String

myArr() = Split(href, "/")
fileName = myArr(UBound(myArr))