Python computing quiz The following code is a computing quiz:

import random

#the questions/answer dictionary
my_dict =   {
            "Base-2 number system" : "binary",
            "Number system that uses the characters 0-F" : "hexidecimal",
            "7-bit text encoding standard" : "ascii",
            "16-bit text encoding standard" : "unicode",
            "A number that is bigger than the maximum number that can be          stored" : "overflow",
            "8 bits" : "byte",
            "1024 bytes" : "kilobyte",
            "Picture Element. The smallest component of a bitmapped image" : "pixel",
            "A continuously changing wave, such as natural sound" : "analogue",
            "the number of times per second that a wave is measured" : "sample rate",
            "A binary representation of a program" : "machine code"
        }

#welcome message
print("Computing Revision Quiz")
print("=======================")

#the quiz will end when this variable becomes 'False'
playing = True

#While the game is running
while playing == True:

    #set the score to 0
    score = 0

    #gets the number of questions the player wants to answer
    num = int(input("\nHow many questions would you like: "))

    #loop the correct number of times
    for i in range(num):

        #the question is one of the dictionary keys, picked at random
        question = (random.choice( list(my_dict.keys())))
        #the answer is the string mapped to the question key
        answer = my_dict[question]

        #print the question, along with the question number
        print("\nQuestion " + str(i+1) )
        print(question  + "?")

        #get the user's answer attempt
        guess = input("> ")

        #if their guess is the same as the answer
        if guess.lower() == answer.lower():
            #add 1 to the score and print a message
            print("Correct!")
            score += 1
        else:
            print("Nope!")

    #after the quiz, print their final score
    print("\nYour final score was " + str(score))

    #store the user's input...
    again = input("Enter any key to play again, or 'q' to quit.")

    #... and quit if they types 'q'
    if again.lower() == 'q':
        playing = False

Just some general syntax notes I have after a quick scan of your code...

Python isn't C, not all evaluations are about equality!

The line while playing == True:, immediately struck me as odd.  Python evaluates things in if-statements/while-loops/etc.  This is different to a language such as C, which always uses equality (or inequality) for such things.

Specifically, if we take the variable playing to just be (something that is either True or False), and then substitute that into the expression.. We get:

(something that is either True or False) == True

This will *ALWAYS* evaluate to the same value as just using playing - since it's already either True or False.

Input checking, and why (when dealing with users) even sane people validate

The following excerpt:

#gets the number of questions the player wants to answer
num = int(input("\nHow many questions would you like: "))

As you've discovered, input is returning you a string, and the way to cast this to an int is with (the appropriately named) int.  However, if a user enters something like "Tersosaur" instead of a number, you will get a ValueError (raised by int).

The way to deal with this is to use a try/except, like this:

#gets the number of questions the player wants to answer
num = input("\nHow many questions would you like: ")
try:
    num = int(num)
except ValueError:
    print "Error '%s' is not a valid number".format(num)

Just a recommendation,  Make your code more Pythonic

I noticed a lot (all) of your initialization and start-up code (things such as setting score = 0, etc) happens in the program itself, and not in a main block.

You don't technically need this, but it is best practise to use a block like this:

if __name__ == "__main__":
    ...initialization code goes here

Functional Decomposition is your frenemy friend

Functional Decomposition is important, even in small program like this.  It improves the readability, understandability and (perhaps most importantly here) maintainability of your code.

At the moment, all of your logic is wrapped up inside this mainloop style sequence of commands.  The way you get input from the user, the way you keep score, how you check if their answers are correct, etc.  All of these ways and hows are behaviours, which in Python can* become methods.

* Note: Functional Decomposition is not ALWAYS your friend (hence frenemy).  If you go to far you'll end up with just as big a mess of spaghetti code as you started with.  For example, don't extract each and every line from your loop into a separate function and think it's functionally decomposed.  Functional decomposition is about the identification of behaviours.


Parsing URLs in Pandas DataFrame My client needs their Google AdWords destination URL query parsed and the values spell checked to eliminate any typos ("use" instead of "us", etc).

I'm pulling the data using the AdWords API and putting it into a dateframe for manipulation. Everything works, but there are over 100,000 records every pull and sometimes the code takes hours and hours to run. Is there a way to optimize the following code blocks?

def parse_url(df):
    for index, row in df.iterrows():
        parsed = urlparse(str(row['Destination URL'])).query
        parsed = parse_qs(parsed)
        for k, v in parsed.iteritems():
            df.loc[index, k.strip()] = v[0].strip().lower()
    return df

def typo_correct(urlparams, df, dictionary):
    for index, row in df.iterrows():
         for w in urlparams:
            if df.loc[index,w] == None or len(df.loc[index,w])<2 or w == 'account':
                pass
            else:
                high = 0.0
                word = None
                for item in dictionary:
                    prob = lev.ratio(str(df.loc[index,w]), item)
                    if prob == 1.0:
                        high = prob
                        word = str(df.loc[index, w])
                        continue
                    elif prob > high:
                        high = prob
                        word = item+"*"
                    else:
                        pass
                if high != 1.0:
                    df.loc[index,w] = word
                    df.loc[index, 'Fix'] = "X"
    return df

Basically it parses out the query parameters, and puts them into a dictionary. The script takes the keys and creates headers in the dataframe, then the first function above iterates through and puts the values in the correct location.

The second one then goes through each value and checks if it's in a dictionary text file and uses the Levenshtein edit distance to find the right word in the case of a typo.

I'm not sure if this is something that can be done using map or apply as I haven't been working with Pandas long. Does anyone have any suggestions?

I don't know if it's still relevant for you, but I can see some optimization that you could do in your code.
As I see, you are passing all dataframe objects and then parsing specific columns in that dataframe:
def parse_url(df):
    for index, row in df.iterrows():
        parsed = urlparse(str(row['Destination URL'])).query #<==
        parsed = parse_qs(parsed)
        for k, v in parsed.iteritems():
            df.loc[index, k.strip()] = v[0].strip().lower()
    return df

It would be faster if you pass only the column that you need to parse.
E.g.
def parse_url(df):
    for index, row in df.iterrows():
        parsed = urlparse(str(row)).query # <- Notice the change here
        parsed = parse_qs(parsed)
        for k, v in parsed.items(): #use items() in Python3 and iteritems() in Python2
            df.loc[index, k.strip()] = v[0].strip().lower()
    return df

parse_url(df['columnName'])

Then first your function would have less work to do and performance would increase - at least slightly.


Google Maps API with Jackson Parser I am working on the Google Maps API, doing a reverse geocoding with the following code snippet.

What I am using are:

Spring
Jackson Parser
Google Maps API

It is working fine but it gives results a bit slowly. Can I improve my code in terms of performance?

package com.addressparser.api;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class GeocodeAddressParser {
    public String getLocationInfo( String lat, String lng) throws JsonProcessingException, IOException {

        HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=false");

        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
            } catch (IOException e) {
        }

        ObjectMapper mapper = new ObjectMapper();
        JsonNode array =  mapper.readValue(stringBuilder.toString(), JsonNode.class);
        JsonNode object = array.get("results").get(0);
        String reportKey = object.get("formatted_address").textValue();
        System.out.println(reportKey);//just printing it on the console for testing at the moment
        return reportKey;

    }

    public static void main(String[] args) throws JsonProcessingException, IOException{
        GeocodeAddressParser ref = new GeocodeAddressParser();

        ref.getLocationInfo("31.338451","75.554183");
    }
}

Never swallow exceptions silently like this:

} catch (ClientProtocolException e) {
    } catch (IOException e) {
}

You'll have a nasty time debugging hidden problems because of that.  At the very least, print some diagnostic message to System.err.  Furthermore, you couldn't responsibly continue trying to parse an incomplete result, so you should abort the processing instead.

Basically, if you don't know what to do with an exception, you should probably propagate it.  In fact, you already declared that getLocationInfo() can throw an IOException, so why bother catching IOException at all?


Providing advice based on user's favourite YouTuber I have written this code which provides advice based on user's favourite YouTuber. I wonder if there is a better way to do absolutely any of it. Also, if there is any way to optimise it or if there is a problem please also tell me preferably with fixed code as I am still sort of a beginner.
The code is below:

import random

def test():
    youtuber = input('Enter your favourite youtuber:  ')
    youtuber = youtuber.lower()
    favouriteYoutuber = ['Dr. Phil', 'Mr. Beast', 'T-Series', 'PewDiePie', '5 Minute Crafts', 'The Ellen Show']

    if youtuber == 'dr. phil':
        print('You are an awesome lad!')
    elif youtuber == 'james charles':
        print('Errmm. Ok...')
    elif youtuber == 'bloamz':
        print('Ok then.')
    elif youtuber == 'ali a':
        print('I mean. Thats old but ok...')
    elif youtuber == 'jacksepticeye':
        print('Thats kinda cool')
    elif youtuber == 'will smith':
        print('Thats different. I rate that')
    elif youtuber == 'jack black':
        print('you have good taste')
    elif youtuber == 'jack white':
        print('I like him as well')
    elif youtuber == 'dr. mike':
        print('so you like learning then')
    elif youtuber == 'morgz':
        print('I mean just leave now')
    else:
        print('I dont know that one. Ill check them out')

    print('my favourite youtuber is ' + random.choice(favouriteYoutuber))

def try_again():
    again = True
    while again:
        test()
        while True:
            try:
                print("")
                print("Would you like to try again?")
                maybe = input("Y/N ")
                maybe = maybe.lower()
            except ValueError:
                print("That is not a valid option")
                print("")
                continue
            if maybe in ('y','n'):
                if maybe == "n":
                    print("")
                    again = False
                elif maybe == "y":
                    print("")
                break

    else:
        print("Thank you for using this app!")
try_again()

I've heard of dictionary lookups but I don't really understand what they are so if anyone thinks that they maybe relevant and could show me how to implement it that would be great!

Here you go!

Use Dictionaries!

The entire if/elif/else if yelling, if not screaming, to be put into a dictionary. This is a lot faster than your implementation because it's a simple key lookup, instead of multiple logical checks to test the user input.

Here is your test function (now named favorite_youtuber):

def favorite_youtuber():

    youtube_response = {
        'dr. phil': 'You are an awesome lad!',
        'james charles': 'Errmm. Ok...',
        'bloamz': 'Ok then.',
        'ali a': 'I mean. Thats old but ok...',
        'jacksepticeye': 'Thats kinda cool',
        'will smith': 'Thats diferent. I rate that.',
        'jack black': 'You have good taste.',
        'jack white': 'I like him as well.',
        'dr. mike': 'So you like learning then!',
        'morgz': 'I mean just leave now.'
    }
    # Since some youtubers in the list below are not included in the dictionary, I left the list. #
    my_favorite_youtubers = ['Dr. Phil', 'Mr. Beast', 'T-Series', 'PewDiePie', '5 Minute Crafts', 'The Ellen Show']

    youtuber = input('Enter your favourite youtuber:  ').lower()

    if youtuber in youtube_response:
        print(youtube_response[youtuber])
    else:
        print('I dont know that one. Ill check them out.')

    print(f'My favourite youtuber is {random.choice(my_favorite_youtubers)}!')

A dictionary works by utilizing keys and values, like so:

my_dict = {
    "key": "value of any type",
    ...
}

In this case, the key is the name of the youtuber that the user inputs, and the value is the response. This prevents you from having to have multiple print statements depending on what the user inputs. Now, all you have to do is make sure that the youtuber entered by the user is included in the dictionary's keys, utilizing this line:

if youtuber in youtube_response:

Format Your Strings!

The era of my_string = a + " " + b is over. You can now format your strings to include your variables directly in them! Take a look:

print(f'My favourite youtuber is {random.choice(my_favorite_youtubers)}!')

Essentially, the value of the code within {} is placed in that position in the string.

Another option is to use .format(), which is a method called on a string. Take a look:

print('My favourite youtuber is {}'.format(random.choice(my_favorite_youtubers)))

They both do the same thing. It's up to you which one you want to use.

.lower() utilization

Instead of

maybe = input("Y/N ")
maybe = maybe.lower()

do this

maybe = input("Y/N ").lower()

Since input() returns a string, .lower() applies to that string. This prevents you from having to write that extra line, and it makes your code a little nicer.

\n

Instead of

print("That is not a valid option")
print("")

do this

print("That is not a valid option.\n")

It adds a newline character at the end of the string, doing exactly what you're doing but in a nicer way.

Repetitive User Input

Now let's talk about your try_again function.

There's a lot to break down here. I find it easier to show you my improved version of your code, and walking you through what I did. Have a look:

def run_app():
    while True:
        favorite_youtuber()
        again = input("Play again? (Y/N)").lower()
        while again not in "yn":
            print("Please enter Y/N!")
            again = input("Play again? (Y/N)").lower()
        if again == "n":
            break
    print("Thank you for using this app!")

It's fairly self explanatory. The one thing I want to talk about is the nested while loop.

Instead of checking if something is within a tuple ("y", "n"), you can check if something is within a string "yn". It's easier to understand this way. The while loop keeps asking for input until the user enters a "y" or a "n". This is easier than having nested while True: loops, as those can get very messy very fast.

Since you only want to see if they don't want to keep playing, you only need to check for the existence of an "n". Then, it's a simple break statement to print out the final goodbye.

Main Guard

Last thing I'm commenting on.

You should use a main guard when running this program. Why?

Let's say you want to import this module into another program, because you don't want to rewrite all this code in a different file. When you import the module, that spare try_again is going to run. That is not what you want. Containing this extra code in a main guard will prevent this from happening. It's a simple if statement:

if __name__ == "__main__":
    run_app()

I renamed your try_again to run_app(), since that name is more fitting of what the program is doing.


Staircase challenge - Python Your task is to print all unique ways to climb a staircase of length n where, from each step, you can take steps of size x where x is an integer value from an array
  For example: if you want to climb a staircase of length 3 and you can move [1, 2] steps from each stair, the output should be

 [1, 1, 1]
 [1, 2]
 [2, 1]

  Note the order is important and hence [1, 2] is different
  to [2, 1].

Is this the fastest way to solve this problem (without using built in libraries such as itertools)?

def valid_moves(position, target, legal, path, permutations):
    if position > target:
        return
    if position == target:
        permutations.append(path)
        return
    for move in legal:
        valid_moves(position + move, target, legal, path + [move], permutations)
    return permutations

start = 0
length_staircase = 3
legal_moves = [1, 2]

print(*valid_moves(start, length_staircase, legal_moves, [], []), sep="\n")

I have a few suggestions for you:

You should get in the habit on wrapping all code that isn't in a function in a main guard, to ensure that that code only runs if that file is running, and to protect it from import mishaps
Running your code with pylint, a few warnings that popped up were:

Returns: All return statements should return something or none of them should return anything. Since you are returning permutations, the other return's should just return None.
Module Docstring: Your function should contain a docstring describing what the function does, even if it's very obvious. These will help any documentation.
Constant variable names: Since the three variables in the main guard do not change, they should be in all UPPERCASE to make it clear that they are constants.

Refactored code:

def valid_moves(position, target, legal, path, permutations):
    """ Returns unique ways to climb a staircase with passed length `target` """
    if position > target:
        return None
    if position == target:
        permutations.append(path)
        return None
    for move in legal:
        valid_moves(position + move, target, legal, path + [move], permutations)
    return permutations

if __name__ == '__main__':
    START = 0
    STAIRCASE_LENGTH = 3
    LEGAL_MOVES = [1, 2]

    print(*valid_moves(START, STAIRCASE_LENGTH, LEGAL_MOVES, [], []), sep="\n")


Block_breaker clone in pygame with simple edge detection I tried to make this clone of
brick_breaker on my own
in one day. The source code and assets .

However I have some concerns about the code so far:

It uses simple edge detection code (as if ball goes out of screen <600 or <462).
It uses built-in collision detection from pygame.
Simple array for appending blocks.

import pygame,sys,random,time
from pygame.locals import *
pygame.init()
blk=pygame.image.load('block.bmp')    #load blocks image
img=pygame.image.load('back.bmp')     #load background image
thung=pygame.image.load('thung.bmp')  #load player image
gameover=pygame.image.load('go.bmp')
mas=pygame.image.load('masthead.bmp')
soundObj = pygame.mixer.Sound('wall.wav')
back=pygame.mixer.music.load('background.mid')
global windowSurface

windowSurface = pygame.display.set_mode((600, 462), 0, 32)
pygame.display.set_caption('Simple breakout game by piyush')

class pool():
    x=1
    y=1
    dirx=''
    diry=''
    trig=0
    block=[]
    pigger=0

    def trigger(self):
        self.trig=1

    def _init_(self):
        self.x=250
        self.y=250
        dirx='left'
        diry=''
        block=[]
    def movex(self):
        if self.trig==1:
            if self.dirx=='left':
                self.x-=1
            if self.dirx=='right':
                self.x+=1
            if self.x<=0:
                self.dirx='right'
                soundObj.play()
            if self.x==600:
                self.dirx='left'
                soundObj.play()
    def movey(self):
        if self.trig==1:
            if self.diry=='up':
                self.y-=1
            if self.diry=='down':
                self.y+=1
            if self.y==0:
                soundObj.play()
                self.diry='down'
            if self.y>=410:
                self.diry='up'
                self.x=250
                self.y=250

    def drawball(self,surface):
        pygame.draw.circle(surface,(200,100,230),(self.x,self.y),13,0)

    def rev(self):
        if self.diry=='down':
            self.diry='up'
    def drawblock(self,surface):

        for blocks in self.block:
                              surface.blit(blk,blocks)

def play():
    pygame.mixer.music.play(-1, 0.0)

    ball1=pool()
    pygame.init()
    for i in range(10):
            size=i*75
            ball1.block.append(pygame.Rect(size,20,40,40))
    for i in range(10):
            size=i*75
            ball1.block.append(pygame.Rect(size,60,40,40))
    for i in range(10):
            size=i*75
            ball1.block.append(pygame.Rect(size,100,40,40
    ball1.x=400
    ball1.y=200
    ball1.dirx='left'
    ball1.diry='up'
    ball1.pigger=1

    a=300
    b=340
    while True:
        windowSurface.fill((25,25,25))

        pos = pygame.mouse.get_pos()

        a=pos[0]
        for event in pygame.event.get():
             if event.type==QUIT:
                pygame.quit()
                sys.exit()

             if event.type==KEYUP:
                 if event.key==K_LEFT:
                     a-=30
                 if event.key==K_RIGHT:
                     a+=30
                 if event.key==ord('a'):
                     pigger=0

        thunge=pygame.Rect(a, b, 120, 10)
        ball=pygame.Rect(ball1.x, ball1.y, 10, 10)
        windowSurface.blit(img,(0,0))
        windowSurface.blit(thung,thunge)
        ball1.drawball(windowSurface)
        ball1.movex()
        ball1.movey()
        ball1.trig=1
        ball1.drawblock(windowSurface)
        windowSurface.blit(mas,(-20,410))
        if thunge.colliderect(ball):
            print("collision detecte")
            ball1.rev()
            soundObj.play()

        for blok in ball1.block:
            if ball.colliderect(blok):
                ball1.block.remove(blok)

        pygame.display.update()

play()

First off, according to this online tool, you have ~119 PEP8 violations. So, for my first tip, I'm going to reccomend reading Python's official style guide, PEP8. The style guide essentially tells you how to format your code, so I'm not going to give you any tips on that in this answer.
Secondly, your pool class seems weird, partially because it seems like you don't necessarily need it, like it's just a static class with variables, and functions that modify those variables. In that case, I'd recommend abandoning the pool class completely, and just having global variables, with functions that modify those variables.
On your pool class again, you've misspelled __init__ and put _init_ instead.
Sorry if this sounds rude, but some of the names that you've given your variables and functions are awful. I mean, I have no idea what the variable pigger, or thung does just by looking at it. You also shouldn't abbreviate already short variable names. For example, block, does not need to become blk.
Avoid importing multiple files on one line. This helps weed out certain errors if one of the imported files isn't working correctly. You should import modules like this.

import pygame
import sys
import time
import random

Your play function could be separated into multiple functions, like a create_blocks function, or check_for_quit.
You should define SCREEN_WIDTH and SCREEN_HEIGHT variables. This gets rid of "magic numbers", and helps with overall readability.
Finally any variables with values that don't change should be constant. For example, gameover should be GAME_OVER_IMAGE.

Anyways, I hope this helped!


Compare two columns in an Excel spreadsheet I have a VBA code that compares values in two columns (Column A & B), which runs slow. Please advise me the changes to make it run fast

The below code works just fine, but is running slow. Please advise me on how to make it run fast

 Sub compare()
       Dim ListA As Range
       Dim ListB As Range
       Dim c As Range
       Call Unprotect
       Set ListA = Range("A2:A1048576")
       Set ListB = Range("B2:B1048576")

       Application.ScreenUpdating = False

       Range("C1").Value = "Files in A that are NOT in B"
       Range("D1").Value = "Files in B that are Not in A"
       Range("E1").Value = "Matching Files"

       For Each c In ListA
       If Application.CountIf(ListB, c) = 0 Then
       Cells(Cells(Rows.Count, "C").End(xlUp).Row + 1, "C").Value = c
       End If
       Next c

       For Each c In ListA
       If Application.CountIf(ListB, c) >= 1 Then
       Cells(Cells(Rows.Count, "E").End(xlUp).Row + 1, "E").Value = c
       End If
       Next c

       For Each c In ListB
       If Application.CountIf(ListA, c) = 0 Then
       Cells(Cells(Rows.Count, "D").End(xlUp).Row + 1, "D").Value = c
       End If
       Next c

     Application.ScreenUpdating = True

     Call Protect
     End Sub

Any code changes to make the code run fast will be appreciated. Thanks

I'm sure you can further optimize the code, but this will definitely run faster.

It will run faster for a number of reasons, firstly I've combined one of your loops so you only have two For Loops, the second reason is that the code won't be looking at every cell in the worksheet, but it will find the last row with data and loop until then:

Sub compare()
    Dim ListA As Range
    Dim ListB As Range
    Dim c As Range
    Call Unprotect

    ListARange = Cells(Rows.Count, "A").End(xlUp).Row 'find the last row with data on column A
    ListBRange = Cells(Rows.Count, "B").End(xlUp).Row 'find the last row with data on column B

    Set ListA = Range("A2:A" & ListARange) 'set your range only until the last row with data
    Set ListB = Range("B2:B" & ListBRange)
    Application.ScreenUpdating = False

    Range("C1").Value = "Files in A that are NOT in B"
    Range("D1").Value = "Files in B that are Not in A"
    Range("E1").Value = "Matching Files"

    For Each c In ListA
        If Application.CountIf(ListB, c) = 0 Then
            Cells(Cells(Rows.Count, "C").End(xlUp).Row + 1, "C").Value = c
        ElseIf Application.CountIf(ListB, c) >= 1 Then
            Cells(Cells(Rows.Count, "E").End(xlUp).Row + 1, "E").Value = c
        End If
    Next c

    For Each c In ListB
        If Application.CountIf(ListA, c) = 0 Then Cells(Cells(Rows.Count, "D").End(xlUp).Row + 1, "D").Value = c
    Next c

    Application.ScreenUpdating = True

    Call Protect
End Sub


Compare two arrays and show number of matches in a percentage value I wrote this to be able to compare two different arrays to figure out how many words were in common as a percentage value.

The use case is that I have array a which is a list of the most commonly known and used words in a language (normally something like 2000 different words).
In array b I have the text.

The end result is the percentage usage of commonly used words as a means to figure out total readability of the text.

Note:
The intersect_array function is used elsewhere in the full fledged application.

The full functioning CodePen can be viewed here: http://codepen.io/MarkBuskbjerg/pen/rWWRbX?editors=0010

The JS goes like this:

tinymce.init({
  selector: '#myTextArea',
  height: 300,
  setup: function(ed) {
    ed.on('keyup', run);
  },
  init_instance_callback: "run"
});

// helper function that matches two arrays with each other
function intersect_arrays(a, b) {
  var sorted_a = a.concat().sort();
  var sorted_b = b.concat().sort();
  var common = [];
  var a_i = 0;
  var b_i = 0;

  while (a_i < a.length && b_i < b.length) {
    if (sorted_a[a_i] === sorted_b[b_i]) {
      common.push(sorted_a[a_i]);
      a_i++;
      b_i++;
    } else if (sorted_a[a_i] < sorted_b[b_i]) {
      a_i++;
    } else {
      b_i++;
    }
  }
  return common;
}

// simple addition function
function add(a, b) {
  return a + b;
}

function run(inst) {
  var sum;
  var percentageUsage;
  var words = ["store", "javascript", "hammertime"];
  var result = {};
  var text = tinyMCE.get('myTextArea').getContent({
      format: 'text'
  })
    .replace(/<([^>]+)>|[\.\+\?,\(\)"'\-\!\;\:]/ig, "")
    .toLowerCase()
    .split(/[\s]/)
    .filter(Boolean);
  var textLength = text.length;
  var match = intersect_arrays(text, words);

  for (var y = 0; y < match.length; y++) {
    for (var i = 0; i < text.length; ++i) {
       if(text[i] === match[y]) {
         if (!result[text[i]])
            result[text[i]] = 0;
            ++result[text[i]];
       }
    }
  }

 sum = Object
    .values(result)
    .reduce(add, 0);

   percentageUsage = textLength / sum;

   document.getElementById('totalWords').innerHTML = textLength;
   document.getElementById('totalPercentage').innerHTML = percentageUsage;
}

Any ideas as to how I can handle the code more effective, easier or just in a more beautiful way is more than welcome. I'm quite new at JS so still wanna learn a lot about best practice and stuff.

I'm assuming you have already broken your text down into its individual words and stripped the punctuation marks, etc, in your text array?

If so, the percentage of words from the given text array that match your word-list should be pretty easy to find.

Something along the lines of:

function matchPerc(wordList, text){
  var matches = text.filter((word)=>{return wordList.includes(word)}).length
  return (matches / text.length * 100).toFixed(2) + '%'
}


Linked list stack implementation I have used the following code for a stack implementation. The top keeps track of the topmost node of the stack. Now since top is a data member of the node function, each node created will have a top member, which ideally we wouldn't want.

Is this good approach to coding?
Will making top as static make it a better coding practice?
Should I have a global declaration of top?

#include<iostream>
using namespace std;
class node
{
    int data;
    node *top;
    node *link;
    public:
    node()
    {
       top=NULL;
       link=NULL;
    }
    void push(int x)
    {
        node *n=new node;
        n->data=x;
        n->link=top;
        top=n;
        cout<<"Pushed "<<n->data<<endl;
    }
    void pop()
    {
        node *n=new node;
        n=top;
        top=top->link;
        n->link=NULL;
        cout<<"Popped "<<n->data<<endl;
        delete n;
    }
    void print()
    {
        node *n=new node;
        n=top;
        while(n!=NULL)
        {
            cout<<n->data<<endl;
            n=n->link;
        }
        delete n;
    }
};

int main()
{
    node stack;
    stack.push(5);
    stack.push(7);
    stack.push(9);
    stack.pop();
    stack.print();
}

Any other suggestions welcome. I have also seen codes where there are two classes, where the second one has the top member. What about this?

In the pop and the print function, the new node seems unnecessary, since the next line modifies the pointer to point to the top. It could be simply

node *n = top;

The delete n; also looks superfluous in the print since n will always be NULL there.
If I'm right making top as static or global would result that you can't have more than one stack in an application. Linked lists usually have two classes: one is a Node which stores a reference to the next node and the data, and the second is a LinkedList class which stores the head and the implementation of the push, pop, etc. methods. You can see an example in this answer.
Take care of the boundary cases. Calling pop on an empty stack gives a segmentation fault error. I suppose that's not the best error handling method :)


Trim white space from string This function is intended to remove leading and trailing whitespace from a string. How can it be made more efficient?  For example, can the two for loops be combined into one?

string trim(string str)
{
    int i = 0;
    for (char c : str)
    {
        if (!isspace(c))
            break;
        i++;
    }

    string trimmed = str.substr(i, (str.length()-i));

    i = 0;
    for (char c : str)
    {
        if (isspace(c))
            break;
        i++;
    }

    trimmed = trimmed.substr(0, i);
    return trimmed;
}

Your current implementation you will lose all but the first word:

std::string str("this is a sentence");
std::string t  = trim(str);

std::cout << t << "\n"

// Output
this

If that is your intention then there is an easier way of doing that:

std::string trim(std::string const& str)
{
    std::string word;
    std::stringstream stream(str)
    stream >> word;

    return word;
}

If you want to trim space of the ends on the string, then I would use the string search functions [coliru demo]:

std::string trim(std::string const& str)
{
    if(str.empty())
        return str;

    std::size_t firstScan = str.find_first_not_of(' ');
    std::size_t first     = firstScan == std::string::npos ? str.length() : firstScan;
    std::size_t last      = str.find_last_not_of(' ');
    return str.substr(first, last-first+1);
}

Here is the string documentation. Boost also has some extra libraries on the subject.


List Comprehension in Pythonic answer to LPTHW ex48 I'm not really seeing any use for a generator here, unless there's some way to hook a generator into a language dictionary.

But in the following code, the longhand version of the if statement (type_check()) returns a tuple (foo, bar) but to get the tuple from (my first ever) lc (type_identify) it needs to be called from result[0], as opposed to simply result.

Is this normal or am I doing something wrong in the lc?

word_types = {'noun': ['bear', 'princess', 'door'],
            'verb': ['go', 'run', 'hide', 'stop', 'close', 'kill', 'eat'],
            'stop': ['in', 'of', 'at', 'to', 'from', 'the'],
            'direction': ['up', 'down', 'north', 'south',
                        'east', 'west', 'back', 'forward']}

def type_check(word):
    word = word.lower()
    for label, type in word_types.items():
            if word in type:
                return (label, word)

def type_identify(word):
    word = word.lower()
    return [ (label, word) for label, type in word_types.items() if word in type ]

def scan(sentence):
    sentence_list = sentence.split()
    for k, v in enumerate(sentence_list):
        if type_identify(v):
            sentence_list[k] = type_identify(v)[0] #needed to add [0]
        else:
            try:
                sentence_list[k] = ('number', int(v))
            except ValueError:
                sentence_list[k] = ('error', v)
    return sentence_list

That's normal, because with the list comprehension you're generating a whole
list of results instead of returning the first time the check succeeds.

If you want to have the equivalent code to the loop version, that is, just
compute the first value or return None if no check succeeds, you can use a
generator as follows:

return next(((label, word)
             for label, type in word_types.items()
             if word in type),
            None)

where the generator is exactly as the list comprehension, but with parentheses
instead of square brackets and next is a built-in method to get the next value
from an iterator or return the default value if the iterator is exhausted.

Note: if you don't pass a default value you'll get a StopIteration when the iterator is exhausted.


String splitting function in Haskell I need to write a function which selects a run of repeated characters from the start of a string, with the run comprising at most nine characters.

chomp :: String -> String
chomp str =  takeWhile (== head str) str

munch :: String -> String
munch = take 9 . chomp

runs :: String -> [String]
runs string = extract string [] where
    extract str xs
        | length str == 0 = xs
        | otherwise = extract (drop (length (munch str)) str) (xs ++ [(munch str)])

I can't define any new functions (except helper ones), however, I can use all of the haskell built-in ones. Is there a nicer way to write the runs function?

Examples

runs "aaaaabbbbcc"
["aaaaa","bbbb","cc"]

runs "aaaaaaaaaaaaaaabbbbcc"
["aaaaaaaaa","aaaaaa","bbbb","cc"]

runs "dddddddddddd"
["ddddddddd","ddd"]

runs "aaabbbaaa"
["aaa","bbb","aaa"]

Another variant of runs

Let us start with the finished product first, and then I will show you how to get there:

runs :: String -> [String]
runs "" = []
runs xs = munched : runs (drop (length munched) xs)
  where munched = munch xs

Use pattern matching

In your extract function, you've checked str's length. However, that is not necessary and is very expensive. If you want to check whether a list is empty either use null or pattern matching. With pattern matching, we end up with

extract []  xs = xs
extract str xs = extract (drop (length (munch str)) str) (xs ++ [(munch str)])

Use bindings to keep repetition low

However, we repeat ourselves here and use munch str twice. Let's get rid of that:

extract []  xs = xs
extract str xs = extract (drop (length munched) str) (xs ++ [munched])
  where
    munched = munch str

Our line got a little bit shorter. Great. Now let us have a look at your accumulator.

Avoid repeated ++

Your results looks like this:

munch str ++ munch str' ++ munch str'' ++ munch str''' …

However, with parentheses, we actually have

(…(((munch str ++ munch str') ++ munch str'') ++ munch str''') …)

Since ++ is linear in its first argument, that is going to be slow. However, we don't need to use ++ at all, since we're constructing a list element-wise from the first to the last. So instead of an accumulator, let us have extract return the list as soon as possible:

extract [] = []
extract str = munched : extract (drop (length munched) str)
  where munched = munch str

At that point extract has exactly the same type as runs, so we can get rid of it. We end up with

runs :: String -> [String]
runs []  = []
runs str = munched : runs (drop (length munched) str)
  where munched = munch str

Replace str with xs and the first [] with "", and you have my first variant. We're done.

Other functions

You could rewrite chomp in a way that returns already groups of characters, e.g.

chomp "aaaaabbbbbccccc" = ["aaaaa","bbbbb","ccccc"]

Then, you could rewrite munch so that it splits a string after 9 characters:

munch "aaaaaaaaaa" = ["aaaaaaaa","aa"]

If you do that, runs gets a lot simpler:

runs = concatMap munch . chomp

However, the types of chomp and munch would differ in that case. By the way, this variant of chomp is in the standard library, and munch is also easy to implement.


Getting rid of goto without duplication in Go Consider the following function:

func Listen(username string) (net.Listener, error) {
    path := filepath.Join(socketsDir, username)

    oldUmask := syscall.Umask(^0600)
    defer syscall.Umask(oldUmask)

    listener, err := net.Listen("unixpacket", path)
    if err != nil {
        return nil, err
    }

    passwd, err := passwd.Getpwnam(username)
    if err != nil {
        goto chownFailed
    }

    err = os.Chown(path, int(passwd.Uid), os.Getgid())
    if err != nil {
        goto chownFailed
    }

    return listener, err

chownFailed:
    listener.Close()
    return nil, err
}

I think this way of error handling is ugly. Is there a way to get rid of the goto without duplicating the call to listener.Close?

You could use defer along with named return values.

E.g.:

listener, err := net.Listen("unixpacket", path)
if err != nil {
    return nil, err
}
defer func() {
    if err != nil {
        listener.Close()
    }
}()

// rest of function that just does "return nil, err" as needed

A runnable playground version of this:
https://play.golang.org/p/lKnGyzbp_3

Note, normally you'll see things like this in Go:

f, err := os.Open("somefile")
if err != nil {
    return err
}
defer f.Close()

That is easier and works for the common case where the thing (a file here) is being used just inside the function itself and needs to always be closed before returning to the caller. In the question however, the listening socket needs to be closed only if there is a error after it was opened. If there is no error it needs to be left open and returned to the caller. That's why the defer'ed function checks err (which it can do as long as it's a named returned value; you can even change named return values in a defer'ed function).


Checking if a single linked list is a palindrome in C++ The following is my first try at this classical interview question. It is quiet different from the solutions Gayle Laakmann provides in her book, and in another question on stackoverflow, someone initially mentioned there are better ways to do it.

I think my solution should run in O(n) time and use O(n) space. Would better Big O performance be possible? This question claims to do it in O(1) space, but edits the list in place, which in my opinion is not a valid solution (A function checking something should always leave the "something" unchanged).
Are there any other things I should change, especially concerning C++ style? I guess I could be using a stack instead of a vector to save the iterators, would that be of any advantage?

#include <forward_list>
#include <iostream>
#include <cstdlib>
#include <vector>

template<typename T>
bool isPalindrome(const std::forward_list<T>& lf)
{
  auto iter = lf.begin();
  std::vector<decltype(iter)> bv; // <-- Correct usage?

  while(iter!= lf.end())
    { bv.push_back(iter++); }

  int istop = bv.size()/2 + bv.size()%2;
  iter = lf.begin();

  for(int i = bv.size()-1; i>=istop; i--, iter++)
  { if( *iter != *(bv[i])) return false; }
  return true;
}

int main(int argc, char* argv[])
{
  std::forward_list<int> list = {0,1,2,1,0};
  std::cout << "Is palindrome: " << isPalindrome(list) << std::endl;
  return 1;
}

This should compile in any compiler using C++11 / C++14.

I see some things that may help you improve your code.

Omit unused variables

Neither argc nor argv are used in this program and should be eliminated.

Consider the value of simplicity

While your code is correct and likely more efficient, there is often merit in creating a program that is so simple it is obviously defect-free.  Such a routine could be this:

auto bv{lf};
bv.reverse();
return bv == lf;

The advantage to this is that it may be sufficiently fast, depending on your needs.  If it is, then you're done.  If it's not, you can use the code as a benchmark to both verify both the correctness and speed of any alternate versions.

Use the data structure to your advantage

Rather than using a std::vector, it may be better to use std::forward_list for the copy.  Doing so would allow you to do use the push_front() operator which is quite efficient.  That would avoid having to have a std::vector and the possible resizing operations that can occur while adding to it.

Count rather than calculate

Since you're iterating through the list anyway, you could simply count the number of items as you go.  The current code has this somewhat complicated calculation:

int istop = bv.size()/2 + bv.size()%2;

Consider instead that if your code simply increments istop during the copy loop, it could simplify to this:

istop /= 2;

Omit the return in main

Usually, a program that ends main with a non-zero return signifies an error to the operating system.  This program always returns 1 which many operating systems will interpret as an abnormal end to the program.  Simplify your code by simply omitting the return; when main ends without a return, the compiler automatically creates the code equivalent to return 0;.

A worked example

Here's an alternative approach incorporating the ideas above:

template<typename T>
bool isPalindrome(const std::forward_list<T>& lf)
{
    auto iter = lf.begin();
    std::forward_list<decltype(iter)> bv;
    int sz = 0;
    for ( ; iter != lf.end(); ++iter) {
        bv.push_front(iter);
        ++sz;
    }
    sz /= 2;
    iter = lf.begin();
    for (auto it2 = bv.begin(); sz; --sz, ++iter, ++it2) {
        if (**it2 != *iter) return false;
    }
    return true;
}


Exercise to create an insertString function to linked-list Working from 'Programming in C' by Kochan. I'm on an exercise in the chapter 'Pointers'.

This was the exercise:

'Write a function called insertEntry() to inset a new entry into a linked list. Have the procedure take as arguments a pointer to the list entry to be inserted (of type struct entry as defined in chapter), and a pointer to an element after which the new entry is to be inserted.

I've been struggling through this book but this exercise only took me a few minutes, I'm concerned I'm missing the point. Can you please make some suggestions regarding if I've gone wrong?

It compiles and runs fine.

Could I have done this better?

#include <stdio.h>

struct entry
    {
        int value;
        struct entry *next;
    };

void insertEntry(struct entry *addOn, struct entry *element);

int main (void)
{

    struct entry n1, n2, n3, addOn;
    struct entry *list_pointer = &n1;

    n1.value = 100;
    n1.next = &n2;

    n2.value = 200;
    n2.next = &n3;

    n3.value = 300;
    n3.next = (struct entry *) 0;

    while(list_pointer != (struct entry *) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }

    list_pointer = &n1;
    insertEntry(&addOn, &n3);

    while(list_pointer != (struct entry *) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }

    return 0;
}

void insertEntry(struct entry *addOn, struct entry *element)
{
    element->next = addOn;
    addOn->value = 400;
    addOn->next = (struct entry *) 0;
}

I'm not sure if your insertEntry function is correct. It seems to be hardcoded to add an entry at the end of the linked list; you want to be able to add an entry anywhere (except at the start of the list which is the object of the next exercise in the book).

Here's my solution to this exercise.

/* Exercise 10.2

   Write a function called insertEntry() to insert a new entry into a linked
   list. Have the procedure take as arguments a pointer to the list entry to
   be inserted (of type struct entry as defined in this chapter), and a
   pointer to an element in the list *after* which the new entry is to be
   inserted.

   note: inserts n2_5 after n2
*/

#include <stdio.h>

struct entry
{
    int value;
    struct entry *next;
};

void insertEntry (struct entry *new, struct entry *follow)
{
    new->next = follow->next;
    follow->next = new;
}

int main (void)
{
    void insertEntry (struct entry *new, struct entry *follow);

    struct entry n1, n2, n3, n4, n5, n2_5, *listPtr;

    n1.value = 100;
    n1.next = &n2;

    n2.value = 200;
    n2.next = &n3;

    n3.value = 300;
    n3.next = &n4;

    n4.value = 400;
    n4.next = &n5;

    n5.value = 500;
    n5.next = (struct entry *) 0;

    printf ("\nlinked list: ");

    listPtr = &n1;

    while ( listPtr != (struct entry *) 0 ) {
        printf ("%i ", listPtr->value);
        listPtr = listPtr->next;
    }

    printf ("\n");

    // insert new entry

    n2_5.value = 250;

    printf ("inserting new entry %i ...\n", n2_5.value);

    insertEntry (&n2_5, &n2);

    printf ("linked list: ");

    listPtr = &n1;

    while ( listPtr != (struct entry *) 0 ) {
        printf ("%i ", listPtr->value);
        listPtr = listPtr->next;
    }

    printf ("\n");

    return 0;
}


Count character 'a' in first n characters of indefinitely repeating string s Problem statement:

  Lilah has a string, s, of lowercase English letters that she
  repeated infinitely many times. Given an integer, n, find and
  print the number of letter a's in the first n letters of
  Lilah's infinite string.

  For example, if the string s = 'abcac' and n = 10, the
  substring we consider is abcacabcac, the first 10 characters
  of her infinite string. There are 4 occurrences of a in the
  substring.

  Function Description

  Complete the repeatedString function in the editor below. It should
  return an integer representing the number of occurrences of a in
  the prefix of length  n in the infinitely repeating string.

  repeatedString has the following parameter(s):

s: a string to repeat
n: the number of characters to consider

  Input Format The first line contains a single string, s.  The second line contains an integer, n.

  Output Format

  Print a single integer denoting the number of letter a's in the
  first  letters of the infinite string created by repeating infinitely
  many times.

  Sample Input 0

aba
10

  Sample Output 0

7

  Explanation 0  The first  letters of the infinite string are abaabaabaa. Because there are  a's, we print  on a new line.

  Sample Input 1

a
1000000000000

  Sample Output 1

1000000000000

  Explanation 1  Because all of the first  letters of the infinite string are a, we print  on a new line.

My Solution:

def repeatedString(s: String, n: Long): Long = {

  def getCount(str: String): Int = str.groupBy(identity).get('a').map(x => x.length).getOrElse(0)

  val length= s.length
  val duplicate: Long = n / length
  val margin = n % length
  val numberOccurencesInString = getCount(s)
  val countInRepetetiveString = numberOccurencesInString * duplicate

  val numberOfOccurencesInStripedString = getCount(s.take(margin.toInt))

  countInRepetetiveString + numberOfOccurencesInStripedString
}

Your getCount() method is a little difficult to read, on one long line like that, and way too complicated. s.count(_ == 'a') is both concise and efficient.

It's not clear why the number of s repetitions possible in n is called duplicate. It seems an odd choice for that variable name.

Your algorithm is sound, I just find it excessively verbose, especially for a language that prides itself on being both expressive and concise.

val sLen = s.length
s.count(_ == 'a') * (n/sLen) + s.take((n%sLen).toInt).count(_ == 'a')


AudioMetaTagger: recursively read files and gather metadata So the idea is to read metadata recursively in a chosen directory, load their metadata and display it into a table.

Here is the simplified example of what I am doing.

public class AudioMetadataExtractorTest {

    public static void main(String[] args) {
       String audioFiles = "C:\\Music";

       File dir = new File(audioFiles);
       Collection col = checkData(dir);

       for(Object object : col){
        File fil = (File) object;
        System.out.println(fil.getAbsolutePath());
        try {
            printMetaData(fil);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
       System.out.println(col.size());
   }

In this case I am using the apachi.commons library to gather all files.

    public static Collection checkData(File dir){
    Collection files = FileUtils.listFiles(
              dir,
              new RegexFileFilter("^(.*mp3)"),
              DirectoryFileFilter.DIRECTORY
            );
    return files;
}

And with jaudiotagger read and print the metadata.

    public static void printMetaData(File file) throws Exception {
    AudioFile audioFile = null;
    audioFile = AudioFileIO.read(file);
    Tag tag = audioFile.getTag();
    for (FieldKey key : FieldKey.values()) {
        if(key==FieldKey.ALBUM){
        System.out.println(key + " " + tag.getFirst(key));
        }
    }
}

While this code works, it is extremely slow. I am confident there is a more efficient way of doing this.

Is it bad practice to loop over objects and cast them within the loop?
Is the jaudiotagger library an intrinsically slow library?

welcome to code review! Here are some thoughts:

Casting

To get rid of the casting you can use generics (see also: https://docs.oracle.com/javase/tutorial/java/generics/types.html) like so:

public static Collection<File> checkData(File dir){
    Collection<File> files = FileUtils.listFiles(
        dir,
        new RegexFileFilter("^(.*mp3)"),
            DirectoryFileFilter.DIRECTORY
        );
    return files;
}

This way in your main function you can avoid the casting:

 Collection<File> files = checkData(dir);
 for(File file: files) {

This is to be preferred, as casting is to be avoided when possible (Interesting related discussion: https://stackoverflow.com/questions/4167304/why-should-casting-be-avoided).

Code

Why initialize a variable first and then assign the value? You can easily do it in one line, which is nicer to read:

AudioFile audioFile = AudioFileIO.read(file);

Formatting

On the nitpicky side, you should take a look at how code formatting is usually done in java: https://docs.oracle.com/javase/tutorial/essential/io/formatting.html

Using decent indentation and spacing allows for easier reading of the code. The best advice here is probably using the auto-formatter of your IDE (eclipse, intelliJ, etc.), as it is tedious to do it by hand.

Performance

Judging from your code, I don't see any specific place to make it a lot faster using the library. It looks like the library reads the entire file to get the metaData, which is of course very I/O intense, and therefor slow.
More advanced libraries like JAudioTagger (http://www.jthink.net/jaudiotagger/examples_read.jsp) might be able to do this in a more efficient way.

Hope this helps!


Optimizing primes generating program in C++ I am writing a program to generate primes in range 1 upto 10^9 but it seems to be timing out.

It implements the Sieve of Atkin

I have tried optimizing my code using bitsets and pragmas.

Please are there any other ways i can optimize my code. Code below

#include<bitset>
#include<vector>
#include<iostream>
#include<algorithm>
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
using namespace std;
#define int long long
const int LIM = 1e9;
bitset<100000000> sieve;
void compute(int limit)
{
    if (limit > 2)
        cout<<"2 ";
    if (limit > 3)
        cout<<"3 ";

    for (int x = 1; x * x < limit; x++) {
        for (int y = 1; y * y < limit; y++) {
            int n = (4 * x * x) + (y * y);
            if (n <= limit && (n % 12 == 1 || n % 12 == 5))
                sieve.flip(n);

            n = (3 * x * x) + (y * y);
            if (n <= limit && n % 12 == 7)
                sieve.flip(n);

            n = (3 * x * x) - (y * y);
            if (x > y && n <= limit && n % 12 == 11)
                sieve.flip(n);
        }
    }
    for (int r = 5; r * r < limit; r++) {
        if (sieve.test(r)) {
            for (int i = r * r; i < limit; i += r * r)
                sieve.reset(i);
        }
    }
    for(int i=sieve._Find_first();i< sieve.size();i = sieve._Find_next(i))
    {
        if(i==0||i==1)continue;
        cout<<i<<" ";
    }
    cout<<endl;
}
signed main()
{
    compute(LIM);
    return 0;
}

Thanks in advance.

I'm not sure what your optimizations are doing(comments would be nice), but I did notice several inefficiencies:

Never include a calculation in the limit test in a for loop.  It get's re-calculated on every iteration.  In this case set the limit to sqrt(limit).  the calculation is kind of expensive but it's done only once.

The same goes for the iteration step, calculate it once before you enter the loop.

In the tests, in the first set of loops, you use 3*x*x twice and y*y 3 times.  putting these in variables would be a lot cheaper.


A simple shellcode that will kill all your processes GNU/Linux x86_64 So I made a simple shellcode that will kill all your process.
Now I would like to know, can it be done in some better way?
It contains 13 bytes. Thanks for all your feedback

Assembly:

 global _start

 section .text

 _start:

     xor rax, rax
     add al, 0x3e
     dec rdi
     push 0x9
     pop rsi
     syscall

Equivalent in C:

#include<stdio.h>
#include<string.h>

unsigned char code[] =
"\x48\x31\xc0\x04\x3e\x48\xff\xcf\x6a\x09\x5e\x0f\x05";

int main()
{
  printf("Shellcode Length:  %d\n", (int) strlen(code));

  int (*ret)() = (int(*)())code;

  ret(0);
}

Now I would like to know, can it be done in some better way? It contains 13 bytes.

From this I conclude that by better you mean shorter.

You can easily bring this down to 11 bytes if you duplicate the method that was used to fill RSI for the setup of RAX.

push 0x3e
pop  rax
dec  rdi
push 0x9
pop  rsi
syscall

The instruction dec rdi depends on the existing value of RDI.
If you know that its lowest 32 bits are non-zero, then you can write dec edi instead, and lose the REX.W prefix. ( -> 10 bytes)

push 0x3e
pop  rax
dec  edi
push 0x9
pop  rsi
syscall

But the most important improvement you can make is of course writing comments.
For now those numbers 0x3E and 0x09 are just magic numbers. What do they mean?
That's what everyone that reads your code is interested in knowing.


Read output from a subprocess executed by Python I've written these 2 methods and I'm wondering if the 2nd method, which uses yield is more efficient or if I'm using yield wrong. Can someone refactor the 2nd method to make it more efficient for reading system os calls with large output?

def exec_cmd(command):
    proc = subprocess.Popen(command,
                            shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)

    stdout, stderr = proc.communicate()
    return_code = proc.returncode

    if stderr:
        raise Error(stdout, stderr)

    if return_code:
        raise Error(stdout, return_code)

    return stdout, return_code

def exec_cmd_output_line_by_line(command):
    proc = subprocess.Popen(command,
                            shell=True,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.STDOUT)

    return_code = proc.returncode

    if return_code:
        raise Error(proc.stdout, return_code)

    for line in proc.stdout.readlines():
        yield line.strip()

First of all, you have a bug.  You gave stderr=subprocess.STDOUT.  That means exactly what it says: stderr will be redirected to stdout.  Because of that, stderr will always be None and stdout will be assigned to whatever the errors are.  Test it yourself with something like ls --qaz.  What you should have said is stderr=subprocess.PIPE.

It is difficult to do a comparative review because the two functions do not do quite the same thing.  I will, however, do a review of the second function.

I don't see a need to create a temporary return_code variable.  Just check if proc.returncode: instead.

You don't account for the cases when there is an error.  What you used in the first function looks pretty good.  I would use a different exception class so that functions that call this function can handle the different types of exceptions in different ways.

File objects are iterable.  That means that your last loop can be shortened to this:

for line in proc.stdout:
    yield line.strip()

That prevents reading all of the lines into memory.  You could also use map(), though it wouldn't be very efficient in Python 2 (because it creates a complete list instead of a generator):

return map(str.strip, proc.stdout)

Another option is a generator expression:

return (line.strip() for line in proc.stdout)


Programming Contest - Snuke Festival Problem Statement

  The season for Snuke Festival has come again this year. First of all,
  Ringo will perform a ritual to summon Snuke. For the ritual, he needs
  an altar, which consists of three parts, one in each of the three
  categories: upper, middle and lower.

  He has \$N\$ parts for each of the three categories. The size of the
  \$i\$-th upper part is \$A_i\$, the size of the \$i\$-th middle part
  is \$B_i\$, and the size of the \$i\$-th lower part is \$C_i\$.

  To build an altar, the size of the middle part must be strictly
  greater than that of the upper part, and the size of the lower part
  must be strictly greater than that of the middle part. On the other
  hand, any three parts that satisfy these conditions can be combined to
  form an altar.

  How many different altars can Ringo build? Here, two altars are
  considered different when at least one of the three parts used is
  different.

  Constraints

  \$1 ≤ N ≤ 10^5\$
  \$1 ≤ A_i ≤ 10^9 (1 ≤ i ≤ N)\$
  \$1 ≤ B_i ≤ 10^9 (1 ≤ i ≤ N)\$
  \$1 ≤ C_i ≤ 10^9 (1 ≤ i ≤ N)\$

  All input values are integers.

  Time limit: 2 sec / Memory limit: 256 MB

  Input

  Input is given from Standard Input in the following format:

N
A1 … AN
B1 … BN
C1 … CN

  Output

  Print the number of different altars that Ringo can build.

Sample Input1

2
1 5
2 4
3 6

Sample Output1

3

Sample Input2

3
1 1 1
2 2 2
3 3 3

Sample Output2

27

Sample Input3

6
3 14 159 2 6 53
58 9 79 323 84 6
2643 383 2 79 50 288

Sample Output3

87

My solution - classified as Time Limit Exceeded:

import qualified Data.Char as Char
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified Text.Printf as Printf
import qualified Control.Monad as Monad
import qualified Data.Array as Array

bisectLeft :: (Ord a) => a -> (Array.Array Int a) -> Int
bisectLeft n xs = bisectLeft' 0 (length xs) n xs

bisectLeft' :: (Ord a) => Int -> Int -> a -> (Array.Array Int a) -> Int
bisectLeft' lo hi n xs = if lo >= hi then lo else
                    if n <= (xs Array.! mid) then bisectLeft' lo mid n xs
                      else bisectLeft' (mid + 1) hi n xs
                    where mid = (lo + hi) `div` 2

bisectRight :: (Ord a) => a -> (Array.Array Int a) -> Int
bisectRight n xs = bisectRight' 0 (length xs) n xs

bisectRight' :: (Ord a) => Int -> Int -> a -> (Array.Array Int a) -> Int
bisectRight' lo hi n xs = if lo >= hi then hi else
                    if n < (xs Array.! mid) then bisectRight' lo mid n xs
                      else bisectRight' (mid + 1) hi n xs
                    where mid = (lo + hi) `div` 2

main :: IO ()
main = do
  n <- (read :: String -> Int) <$> getLine
  as <- (Array.listArray (0,n-1)) . List.sort . map (read :: String -> Int) . words <$> getLine
  bs <- map (read :: String -> Int) . words <$> getLine
  cs <- (Array.listArray (0,n-1)) . List.sort . map (read :: String -> Int) . words <$> getLine
  print $ foldl (+) 0 $ map (\ b -> (bisectLeft b as) * (n - bisectRight b cs)) bs

I think it takes too much time to make the array, but I cannot think of any way to make it more efficient...
How can I this code more efficiently?

Question Link

It's a good idea to profile your code (which is easy if you use stack – instead of stack build, just type stack build --profile, and run your program with the options +RTS -p) to find out exactly where the bottle-necks are. See the GHC profiling guide for more information.

If you do that, you'll find that a significant amount of your program's time is spent splitting up strings into words, and parsing them into Ints. Remember that a Haskell string is a linked list of characters, and thus not particularly efficient – I found that using the Text type from the text package results in the revised program taking only 40% of the time of your version. (Contrary to the other comment here, the binary search you've implemented seems fairly efficient, that's not where the slow-down is.)

Instead of getLine from the standard Prelude, use the version of getLine from Data.Text; instead of parsing a line of text using read . word, I'd suggest something like the following:

import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import Data.Text (Text)

-- ...

forceEither :: Either a b -> b
forceEither (Right r) = r

parseLine :: Text -> [Int]
parseLine txt =
  map (fst . forceEither . T.decimal) $ T.splitOn (T.pack " ") txt

(Possibly a hand-coded loop might be even faster than T.splitOn, but I didn't check that.)

I'd also suggest splitting out the parsing of input from the actual solving of the problem - no advantage is gained by putting everything into main. I'd further suggest that writing sum makes your intent clearer than foldl (+) 0; and that you use Vectors instead of Arrays, since this will (a) get rid of extra bits of cruft in the code and (b) allow you to use the vector-algorithms package, which already contains a binary search function. It's usually far better to use someone else's de-bugged search routine than write your own. However, if you are submitting for an online competition, that package may not be available. Nevertheless, it provides useful inspiration on how the search may be sped up.

This gives code along the following lines:

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}

import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Read as T
import Data.Text (Text)
import qualified Data.List as L

import qualified Data.Vector.Unboxed as V
import Data.Vector.Unboxed (Vector)
import qualified Data.Vector.Unboxed.Mutable as VMut

import Control.Monad  ( replicateM )

import System.IO.Unsafe
import Data.Bits (shiftR)

-- adapted from "vector-algorithms" package:

{-# INLINE binarySearchPBounds #-}
binarySearchPBounds p vec = loop
 where
 loop !l !u
   | u <= l    = return l
   | otherwise = VMut.unsafeRead vec k >>= \e -> if p e then loop l k else loop (k+1) u
  where k = (u + l) `shiftR` 1

{-# INLINE binarySearchL #-}
binarySearchL vec e = binarySearchPBounds (>= e) vec 0 (VMut.length vec)

{-# INLINE binarySearchR #-}
binarySearchR vec e = binarySearchPBounds (> e) vec 0 (VMut.length vec)

forceEither :: Either a b -> b
forceEither (Right r) = r

parseLine :: Text -> [Int]
parseLine txt =
  map (fst . forceEither . T.decimal) $ T.splitOn (T.pack " ") txt

bisectLeft :: Int -> Vector Int -> Int
bisectLeft n xs = unsafePerformIO $ do
  xs' <- V.unsafeThaw xs
  binarySearchL xs' n

bisectRight :: Int -> Vector Int -> Int
bisectRight n xs = unsafePerformIO $ do
  xs' <- V.unsafeThaw xs
  binarySearchR xs' n

getInput :: IO [Text]
getInput = do
  res@[n, as, bs, cs] <- replicateM 4 T.getLine
  return res

sortedVec :: t -> Text -> Vector Int
sortedVec n txt =
  V.fromList $ L.sort $ parseLine txt

parseProblemInput
  :: [Text] -> (Int, Vector Int, [Int], Vector Int)
parseProblemInput [nStr, asStr, bsStr, csStr] =
  let [n] = parseLine nStr
      as =  sortedVec n asStr
      bs =  parseLine  bsStr
      cs = sortedVec n csStr
  in (n, as, bs, cs)

solve :: (Int, Vector Int, [Int], Vector Int) -> Int
solve (n, as, bs, cs) =
  sum $ map (\ b -> bisectLeft b as * (n - bisectRight b cs)) bs

main = do
  ls <- getInput
  print $ solve $ parseProblemInput ls

This may not be as concise as your code, but should be much easier to follow and to modify - and importantly, for your purposes, it runs in less than half the time.

Other notes - the Unboxed versions of Vectors will normally be faster than the boxed versions, if you can use them; if you're submitting code for review, then I'd think a few more comments in your code wouldn't go astray. I hope that helps.


Get all possible palindromes in C# As the title says, the goal is to get all the possible palindromes of a string in C#:

public static bool IsPalindrome(this string source)
{
    for(int i = 0; i < source.Length / 2; i++)
    {
        if(source[i] != source[source.Length - 1 - i])
        {
            return false;
        }
    }

    return true;
}

public static IEnumerable<string> GetPossiblePalindromes(this string source, int maxPossibleChanges, IEnumerable<char> alphabet)
{
    var executionStack = new Stack<Tuple<string, int>>();
    executionStack.Push(Tuple.Create(source, 0));
    int maxChanges = Math.Min(maxPossibleChanges, source.Length);
    var generated = new HashSet<string>();
    generated.Add(source);

    if(maxPossibleChanges < 0)
    {
        yield break;
    }

    do
    {
        Tuple<string, int> currentRecord = executionStack.Pop();

        string currentString = currentRecord.Item1;
        if (currentString.IsPalindrome())
        {
            yield return currentString;
        }

        int currentNumberOfChanges = currentRecord.Item2;
        if (currentNumberOfChanges == maxChanges)
        {
            continue;
        }

        char[] chars = currentString.ToArray();
        foreach(char character in alphabet)
        {
            for(int i = 0; i < currentString.Length; i++)
            {
                char old = chars[i];
                if(character == old)
                {
                    continue;
                }
                chars[i] = character;
                var newString = new string(chars);
                if (generated.Contains(newString))
                {
                    chars[i] = old;
                    continue;
                }
                generated.Add(newString);
                executionStack.Push(Tuple.Create(newString, currentNumberOfChanges + 1));
                chars[i] = old;
            }
        }
    } while (executionStack.Count > 0);

    yield break;
}

Case sensitivity is taken into account and there is a max number of changes one can make to the original string in order to make it a palindrome. Also, a 1 charactes string is not considered a palindrome.

I wanted to ask for a review. I'm more interested in performance reviews but all the other reviews are more than welcome.

First and foremost your code is solving a different problem from the one stated in the question Get all the possible palindromes of a string or at least that's what it looks like and as pointed in my comments you need to provide more details and context about the code.

I will try to make a few points concerning your existing code aside from it being overly-complicated :

Do you really need an iterator here ? What's the point of saving the state of this code ? You clearly want all the possible palindromes from a specified string which to me sounds like I would receive a List<string> containing all the palindromes in there.
Usually converting string to char array is redundant but if you really need to do that you are better off using string.ToCharArray() instead of string.ToArray() detailed explanation why is given here.
Contains() is O(n) operation so you should avoid it if possible
It might be a good idea to replace that Tuple<string, int> with a class, but I'm not sure what is the point of having it in the first place.

I will provide an alternative solution to the problem :

Get all the possible palindromes of a string with length more than 1.

First let's start by declaring a method that decides if a string is a palindrome.

private static bool IsPalindrome(string input)
{
    for (int i = 0; i < input.Length; i++)
    {
        if (input[i] != input[input.Length - 1 - i])
        {
            return false;
        }
    }
    return true;
}

Here we are making use of the fact that string is already a char[] and we can simply avoid the redundant call ToCharArray(). Also we are using only a single for loop and we are returning as soon as we find 2 different characters to increase performance.

This can also be converted to a one-liner using LINQ

private static bool IsPalindrome(string input)
{
    return !input.Where((t, i) => t != input[input.Length - 1 - i]).Any();
}

or with C# 6

private static bool IsPalindrome(string input) => !input.Where((t, i) => t != input[input.Length - 1 - i]).Any();

Next we need to actually make use of that method and get all of the possible palindromes of a string :

private static List<string> GetPalindromes(string source)
{
    List<string> subsets = new List<string>();
    for (int i = 0; i < source.Length - 1; i++)
    {
        for (int j = i + 1; j <= source.Length; j++)
        {
            if (j - i > 1 && source[j - 1] == source[i])
            {
                string currentSubset = source.Substring(i, j - i);
                if (IsPalindrome(currentSubset))
                {
                    subsets.Add(currentSubset);
                }
            }
        }
    }
    return subsets;
}

This chunk of code is what I would like to have as I explained in my first point but if you really need an iterator :

public static IEnumerable<string> GetPalindromes(this string source)
{
    for (int i = 0; i < source.Length - 1; i++)
    {
        for (int j = i + 1; j <= source.Length; j++)
        {
            if (j - i > 1 && source[j - 1] == source[i])
            {
                string currentSubset = source.Substring(i, j - i);
                if (IsPalindrome(currentSubset))
                {
                    yield return currentSubset;
                }
            }
        }
    }
}


Natural language multiply I am learning Java and this is my solution for a program that will read two numbers in the range of 0 to 99 and multiply them. Input numbers are given in natural language e.g. for input thirty-two ten it should return 320. I have tried to do my best. Could someone please review this and suggest improvements, if any?

package assignments;
import java.util.*;
public class NaturalLanguageMultiply {
    private static final Map<String, Integer> numericValues = new HashMap<String, Integer>();
    private static final String WORD_SEPARATOR = "-";
    static {
        numericValues.put("zero", 0);
        numericValues.put("one", 1);
        numericValues.put("two", 2);
        numericValues.put("three", 3);
        numericValues.put("four", 4);
        numericValues.put("five", 5);
        numericValues.put("six", 6);
        numericValues.put("seven", 7);
        numericValues.put("eight", 8);
        numericValues.put("nine", 9);
        numericValues.put("ten", 10);
        numericValues.put("eleven", 11);
        numericValues.put("tweleve", 12);
        numericValues.put("thirteen", 13);
        numericValues.put("fourteen", 14);
        numericValues.put("fifteen", 15);
        numericValues.put("sixteen", 16);
        numericValues.put("seventeen", 17);
        numericValues.put("eighteen", 18);
        numericValues.put("nineteen", 19);
        numericValues.put("twenty", 20);
        numericValues.put("thirty", 30);
        numericValues.put("forty", 40);
        numericValues.put("fifty", 50);
        numericValues.put("sixty", 60);
        numericValues.put("seventy", 70);
        numericValues.put("eighty", 80);
        numericValues.put("ninety", 90);
    }

    private static int wordToNumber(String word) {
        String[] tokens = word.split(WORD_SEPARATOR);
        int number = 0;
        for(String token : tokens) {
            Integer numericValue = numericValues.get(token);
            if(numericValue == null) {
                throw new IllegalArgumentException("unknown token " + token + " in word " + word);
            }

            number += numericValue;
        }
        return number;
    }

    public static void main(String[] args) {

        if(args.length < 2) {
            System.out.println("argument missing");
            System.exit(1);
        }

        try {
            int firstNumber = wordToNumber(args[0]);
            int secondNumber = wordToNumber(args[1]);
            System.out.format("%d%n", firstNumber * secondNumber);
            System.exit(0);
        } catch(Exception e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }
    }
}

General
I do not know exactly why your question remains unanswered till now. But I guess "exercises" tend to have less attention as this exercise seems to be really basic. Do not get me wrong. Everybody had to go through basic things.
So the point is that you found a solution to a problem. And so far you did very well. But I want encourage you to keep on going as this is only the surface. Here are the things every programmer has to go through.

Learn the theory of sequence, selection and iteration

Train your algorithmic thinking by solving problems with the elements of 1. in a programming language of your choice by increasing difficulty

Get familiar with the language mechanisms

Apply programming paradigms like functional or object-oriented programming

Formalize you code fragments by learning the currently identified 26 design patterns and learn to to apply them in the correct situations

Organize your code by following the correct semantic of each code fragment and learn and apply the SOLID principles as they guide you through the jungle of design decisions

Learn the restrictions of the language you use for a problem. Maybe in another language you are able to express the solution in another way that is more elegant.

The point is that the code provided can only be judged under point 1, 2 and 3. And there your are on a good way. As I do not know how deep you dived into the java programming language maybe it is time to apply the object-oriented or functional programming paradigm.
As your code currently is procedural I suggest to formulate your code in a more object-oriented way.
Suggestions
Reduce static elements
The static modifier is not overall bad (e.g. constants) but for methods it hinders you to benefit from the OO mechanism "polymorphism".
Introduce OO
Try to formulate your code with objects. To start here remove all static modifiers from all methods but the the main-method. Introduce a constructor for your class "NaturalLanguageMultiply". Pass in the arg-Array make the validation and store it in a local variable.
Do not exit with System.exit(0);
This does not make sense at all as every program will leave with the exit code 0 if the program ends. It is a needless statement.
Exception handling
I suggest to have a single concept of exception handling. If you want to promote execution failure of a program by calling System.exit(...) then do this in the final statement in your program. Internally you should rely on exceptions. So your argument validation should not exit the JVM but throwing an IllegalArgumentException.
Currently you catch "Exception". I suggest to catch expected Exceptions explicitly. This helps you to return distinguishable exit codes.
Furthermore avoid System.out.println at arbitrary locations in your code to promote exceptions. This will cause redundant code spread all over the place. Promote the exceptions where you are going to handle them.
Provide a calculation-method
Introduce a method called getResult() to do the multiplication.
Naming
As mentined in the comments naming things properly will help others to read your code. I would change the constant name from "WORD_SEPARATOR" to "TOKEN_SEPARATOR" and renaming "args" into "words". This how it makes sense to me. You have two words that are both spoken numbers. And one word is partitioned into token by a separator of those tokens. Maybe you can also rename "words" into "spokenNumbers" and "word" into "spokenNumber". But I think I made case.
Code
public class NaturalLanguageMultiply {

    private static final Map<String, Integer> numericValues = new HashMap<String, Integer>();

    private static final String TOKEN_SEPARATOR = "-";

    static {
        numericValues.put("zero", 0);
        numericValues.put("one", 1);
        numericValues.put("two", 2);
        ...
        numericValues.put("ninety", 90);
    }

    private String[] words;

    NaturalLanguageMultiply(String[] words) {

        if(words.length < 2) {
            throw new IllegalArgumentException("argument missing");
        }

        this.words = words;

    }

    private int wordToNumber(String word) {

        String[] tokens = word.split(TOKEN_SEPARATOR);

        int number = 0;

        for (String token: tokens) {

            Integer numericValue = numericValues.get(token);

            if(numericValue == null) {
                throw new IllegalArgumentException("unknown token " + token + " in word " + word);
            }

            number += numericValue;
        }

        return number;
    }

    private int getResult() {

        int firstNumber = wordToNumber(words[0]);
        int secondNumber = wordToNumber(words[1]);

        return firstNumber * secondNumber;
    }

    public void main(String[] args) {

        try {

            int result = new NaturalLanguageMultiply(args).getResult();

            System.out.format("%d%n", result);

        } catch (IllegalArgumentException e) {

            System.out.println(e.getMessage());
            System.exit(1);

        } catch (Exception e) {

            System.out.println(e.getMessage());
            System.exit(2);

        }

    }

}

Further steps
Your solution parses and interpretes incoming data and processes calculations. This is best addressed with the state pattern and the interpreter pattern. This is an advanced technique you should have in mind when you feel ready for it.


jQuery parallax site (on scroll) I have this code for a website I'm working on. It uses window.scroll events to parallax some items. It's running a bit slow on average machines. Is there any way I could improve it to make it run faster?

$(function() {

    // Tell the DOM that JS is enabled
    $('html').removeClass('no-js');

    // Navigation Waypoints
    $('.waypoint').waypoint(function(event, d) {
        var a = $(this);
        if (d === "up") a = a.prev();
        if (!a.length) a = a.end();
        $('.active').removeClass('active');
        a.addClass('active');
        $('a[href=#'+a.attr('id')+']').addClass('active');
    }, {offset: '40%'});

    // Parallax Effects
    $(window).scroll(function() {
        var s = $(window).scrollTop(),
            b = ($('body').height()/100)*20;
            $('.container').each(function () {
                $(this).css('top', Math.round((($(this).closest('.waypoint').offset().top-s)+b)/$(this).attr('data-speed')));
            });
            $('#home hgroup').css('bottom', '-'+Math.round(s/6)+'px');
    });

    // FAQs
    $(document).on('click', '.faqs a', function () {
        $('.faqs .open').slideToggle().removeClass('open');
        $(this).siblings().slideToggle('fast').addClass('open');
        return false;
    });

    // Kinetics
    $('.counter').kinetic({
        y: false
    });

    // Smooth Scroll
    $(document).on('click', 'nav a', function() {
        var t = $($(this).attr('href')),
            o = t.offset().top,
            b = ($('body').height()/100)*10;
        if($(this).attr('href') === "#home") {
            $('html, body').animate({scrollTop: o}, 'slow');
        } else {
            $('html, body').animate({scrollTop: o+b}, 'slow');
        }
        return false;
    });

    // Set Margin
    function setMargin () {
        var t = $('#about'),
            o = t.offset().top,
            c = $('.container'),
            b = ($('body').height()/100)*20,
            m = Math.round(parseInt(t.css('margin-top'))),
            a = Math.round((((o/2)+b)+m)/2);
        c.css('top', a);
    }

    // Calculate Padding
    function calcPadding() {
        var p = Math.round(($(window).width()-700)/2);
        $('.pr').css('padding-right', p);
        setWidth();
    }

    // Calculate Width
    function setWidth () {
        $('.draggable').each(function () {
            var w = 0;
            $(this).children().each(function () {
                w = w + $(this).outerWidth() + parseInt($(this).css('margin-left')) + parseInt($(this).css('margin-right'));
            });
            $(this).css('width', w);
        });
    }

    // Window Resize
    $(window).on('resize', calcPadding);

    // Initialize Functions
    calcPadding();
    setMargin();

});

The jQuery documentation offers the best advice:

  Event performance

  In most cases, an event such as click occurs infrequently and performance is not a significant concern. However, high frequency events such as mousemove or scroll can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using setTimeout.

Obviously it would be ideal if you could move the calculations outside the event handler to reach the desired performance, but that may not be possible in this case. So to expand on the rate-limiting approach, there are 2 ways you could go about it:

Call event handler after the user has finished scrolling (hasn't scrolled for some set amount of time):

var timer = null;
$(window).scroll(function () {
  if (timer) {
    clearTimeout(timer);
  }

  timer = setTimeout(function() {
    timer = null;

    // your event handling logic here
  }, 50);
});

Call event handler immediately after scrolling, with a minimum delay between scroll events:

var justExecuted = false;
$(window).scroll(function() {
  if(justExecuted) {
    return;
  }

  // your event handling logic here

  justExecuted = true;
  setTimeout(function() {
    justExecuted = false;
  }, 50);
});


Searching a Join List for an index For the Join List algebraic data type:

data JoinList m a = Empty
                  | Single m a
                  | Append m (JoinList m a) (JoinList m a)
    deriving (Eq, Show)

This homework's problem states to implement indexJ:

  Exercise 2 The first annotation to try out is one for fast indexing
  into a JoinList . The idea is to cache the size (number of data ele-
  ments) of each subtree.

  This can then be used at each step to deter-
  mine if the desired index is in the left or the right branch. We have
  provided the Sized module that defines the Size type, which is simply
  a newtype wrapper around an Int .

  In order to make Size s more
  accessible, we have also defined the Sized type class which provides a
  method for obtaining a Size from a value.

  indexJ finds the JoinList element at the specified index. If the index
  is out of bounds, the function returns Nothing. By an index in a
  JoinList we mean the index in the list that it represents. That is,
  consider a safe list indexing function

I implemented indexJ, which searches for a matching index within a JList.

indexJ :: (Sized b, Monoid b) => Int -> JoinList b a -> Maybe a
indexJ _ Empty = Nothing
indexJ i (Single s x)
  | (getSize . size) s == i = Just x
  | otherwise               = Nothing
indexJ i (Append _ left right)
  | (getSize . size . tag) left >= i = indexJ i left
  | otherwise                        = indexJ i right

with the following background:

tag's definition

newtype Size = Size Int
  deriving (Eq, Ord, Show, Num)

getSize :: Size -> Int
getSize (Size i) = i

class Sized a where
  size :: a -> Size

...

tag :: Monoid m => JoinList m a -> m

Testing

jlIndex1 :: JoinList Size String
jlIndex1 = Append (Size 1) (Single (Size 0) "foo") (Single (Size 1) "bar")

*JoinList> indexJ 1 jlIndex1
Just "bar"
*JoinList> indexJ 33 jlIndex1
Nothing

Please critique my implementation.

The implementation of indexJ seems to be broken. In particular:

indexJ i (Append _ left right)
  | (getSize . size . tag) left >= i = indexJ i left
  | otherwise                        = indexJ i right

indexing with i in the right part is wrong. I'd suggest you to create a function that converts a list into a JoinedList (ideally a blanced one), and then test if indexing into the list produces the same result as indexing into the JoinedList.

Also the implementation of tag is missing, but this is a crucial part of the code, without it it can't be really reviewed.

I'd also suggest to implement other operations on JoinLists, in particular creating a singleton list and concatenation, perhaps also prepending/appending an element to a list.

Finally, you're using a Monoid instance for tagging the tree. This is in general a good idea, but the assignment doesn't say anythong about monoids, sobe sure to understand how the monoid there should be used. You never use the fact that m a monoid in your code. If you're unsure, I'd suggest to forget about monoids at this point and use just the provided Size data type.


Regex for matching expression that consists of single digit numbers and operators I would like to create a regex that will validate that a string is an equation made up of a single digits and either the * or + operator and is no longer than 100 characters.  So these would be valid:

1+2*3*8+0
9
9*9

And these would not be valid:

1++1
12+1
2*25
1+
47
+
+1
11

I came up with the regex below to accomplish this:

^(\d{1}[\+\*]{1}){0,99}\d$

Which appears to work, but I'm curious if there is a cleaner way to accomplish this.  Any suggestions or is this about as clean as it gets?

It is saved here if you would like to play with it.

While your regex appears to work, it will fail for the condition that your expression should not exceed 100 characters mark. With the boundary of {0,99} on a 2 character pattern \d{1}[\*\+]{1}, you are already expecting a possible expression of length 198 characters.
Using {1} quantifier is just redundant.
No need for escaping inside a character set. The only things needing a leading backslash (\) inside a characters list are ] and ^, where the caret is the only character inside, or the first.
Your expressions will not reach a 100 character mark, unless you allow the + to act as an unary operator.

Therefore, the following pattern will be the simplest approach (imo)

^(?:\d[*+]){0,49}\d$

which is the tiniest bit modified from your original expression.

You can check the pattern in action here on the following expressions:

1+2*3*8+0
9
9*9
1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+5*8

1++1
12+1
2*25
1+
47
+
+1
11
1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+1*2+5*8+9


PHP store data from form into MySql DB This is the first time I've tried this. I'd like some feedback on how I did, including any bad practice warnings. For example is it a really bad idea to allow the code to recreate the table if it doesn't "think" it exists? Would it be better to simply create the table once in a different file?

<?php

/*
Database and mail functionality
*/

// get user credentials
$config = parse_ini_file('../config.ini'); // path may vary depending on setup

// Create connection
$conn = new mysqli('localhost', $config['username'], $config['password'],$config['dbname']);

// Check connection
if ($conn->connect_error){
    die('Connection failed. ' . $conn->connect_error);
}

// if table not made yet, create it
if(!$conn->query ("DESCRIBE visitors")) {
    // sql to create table
    $sql = 'CREATE TABLE visitors(
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(30) NOT NULL,
        email VARCHAR(50) NOT NULL,
        message VARCHAR(500),
        reg_date TIMESTAMP
    )';

    if (!$conn->query($sql)){
        die ('Sorry there was an error. Please try again later.');
    }

}

//insert data into table
//clean data for SQL query
$name = mysqli_real_escape_string($conn, $data['name']);
$email = mysqli_real_escape_string($conn, $data['email']);
$message = mysqli_real_escape_string($conn, $data['message']);

$sql = "INSERT INTO visitors (name, email, message)
    VALUES ('$name', '$email', '$message')";

if ($conn->query($sql) === TRUE) {
    $usrMsg = 'Thank you we\'ll be in touch when we have some news';
} else {
    die ("Sorry, there was an Error. Please try again later.");
}

// close connection
$conn->close();

// email
// addresses and default subject
$to = ''; // add details
$from = ''; // add details
$subject = 'New form entry on website';

// prepare message variables - !not sure how to make quotes etc. display properly in email body
$message = wordwrap($data['message']);
$body = <<<_END
Name: {$data['name']}
Email: {$data['email']}
Message: $message
_END;

// send
mail($to, $subject, $body, $from);

?>

Since, as you mentioned, you are pretty new to this, i will start with some novice level advice:

You should refactor your code into seperated functions, both in order to seperate functionality with different purpose, and to be able to reuse.

function connect_db($config)
{
// Create connection
    $conn = new mysqli('localhost', $config['username'], $config['password'],$config['dbname']);

    // Check connection
    if ($conn->connect_error){
        die('Connection failed. ' . $conn->connect_error);
    }
    return $conn;

}

function prepare_visitors_table($conn)
{

    // if table not made yet, create it
    if(!$conn->query ("DESCRIBE visitors")) {
        // sql to create table
        $sql = 'CREATE TABLE visitors(
            id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(30) NOT NULL,
            email VARCHAR(50) NOT NULL,
            message VARCHAR(500),
            reg_date TIMESTAMP
        )';

        if (!$conn->query($sql)){
            die ('Sorry there was an error. Please try again later.');
        }

    }

}

function save_visitor($conn, $name, $email, $message)
{

    //insert data into table
    //clean data for SQL query
    $name = mysqli_real_escape_string($conn, $name);
    $email = mysqli_real_escape_string($conn, $email);
    $message = mysqli_real_escape_string($conn, $message);

    $sql = "INSERT INTO visitors (name, email, message)
        VALUES ('$name', '$email', '$message')";
    return $conn->query($sql) ;
}

function send_visitor_notification($name, $email, $message)
{

    // email
    // addresses and default subject
    $to = ''; // add details
    $from = ''; // add details
    $subject = 'New form entry on website';

    // prepare message variables - !not sure how to make quotes etc. display properly in email body
    $message = wordwrap($message);
    $body = <<<_END
    Name: {$name}
    Email: {$name}
    Message: $message
    _END;

    // send
    mail($to, $subject, $body, $from);

}

$config = parse_ini_file('../config.ini'); // path may vary depending on setup

$conn = connect_db($config);

prepare_visitors_table($conn);
if (save_visitor($conn, $data['name'], $data['email'], $data['message'])) {
        $usrMsg = 'Thank you we\'ll be in touch when we have some news';
    } else {
        die ("Sorry, there was an Error. Please try again later.");
    }
send_visitor_notification($data['name'], $data['email'], $data['message']);

$conn->close();


Iterate over a file multiple times Aim of the code is to print all of the strings from one file that match strings from another file. Names of both of the files are provided by command line arguments.

Code:

int main(int argc, char *argv[]){
    ifstream answers(argv[1]);
    ifstream candidates(argv[2]);

    for (string s; getline(answers,s);){
        for (string h; getline(candidates,h);){
            if (!s.compare(h)){
                cout << h << ":" << s << endl;
            }
        }
        candidates.close();                 //I know theres better than this
        candidates.open(argv[2], ios::in);
    }
}

but I feel like reloading the file into memory every time is redundant. Is there anything that could be improved?

Slightly better way:

    candidates.close();                 //I know theres better than this

If improvement is based on this statement, then something like stringstream would be good fit.

Best way:

std::map<std::string, std::size_t> will fit the job nicely. After you've done with it, just iterate through and see if anything has counter equal to 2 or higher, and print those.

Roughly this:

std::map<std::string, std::size_t> appearance_count;
while (std::getline(answers, s))
{
    ++appearance_count[s];
}
while (std::getline(candidates, s))
{
    ++appearance_count[s];
}

for (const auto& reading: appearance_count)
{
    if (reading.second > 1)
    {
        std::cout << reading.first << '\n';
    }
}

Some edge cases:

There might be duplications in the first file, so it will require first adding into std::set, then adding to the map. Second file is unaffected by that, since any string with appearance count larger than 1 is already wanted. Though if the second file contains duplicates as well, you'll need two sets.


Project Euler #14 solution takes quite a long time Can anybody give me suggestions for making it faster? (Project Euler #14)

import time
start = time.clock()

def collatzChain(n):
    count = 1
    while n != 1:
        if n % 2 != 0:
            count += 1
            n = (n * 3) + 1

        if n % 2 == 0:
            count += 1
            n = n / 2

    return count

chainLengths = []
startNum = 999999
while startNum > 1:
    chainLength = collatzChain(startNum)
    chainLengths.append(chainLength)
    startNum -= 1

print(999999 - chainLengths.index(max(chainLengths)))
elapsed = time.clock() - start
print("This program took " + str(elapsed) + " seconds.")

Consider the chains starting at 13 and 26. When you reach 26, you go over its whole chain. Later, you reach 13, and go over its whole chain too - but 13's chain is the same as 26's, only without the first number (26).

If you implemented collatzChain using recursion, just adding the decorator @functools.lru_cache would create a cache for your function, and thus prevent Python from repeating the same job twice.