Three functions for computing simple arithmetic Here is my code where I have 3 functions that do simple arithmetic:

#include <stdio.h>

/* The following Code Contains 3 functions
 * that compute simple arithmetic such as
 * computing the sum of 3 integers and divison
 * of three floating integers.
 */
 void getSum(int x, int y, int z);
 double doDiv(float one, float two, float three);
 void getDiv(float a, float b, float c);

 int main()
 {
    getSum(100,242,62);
    getDiv(100.0,25.0,2.0);
    return 0;
 }

/*The function getSum accepts three int
 *values and computes the sum of all three and prints
 *the result via standard output.
 */

 void getSum(int x, int y, int z)
 {
    int sum = x + y + z;
    printf("%i\n",sum);

 }

/*The function doDiv accepts three floating
 *values and computes the divison of first two.
 *Finally it divides the result by the third
 * floating value and returns the final answer.
 */

 double doDiv(float one,float two, float three)
 {
    float answer;
    answer = one/two;
    answer = answer/three;
    return answer;
 }

/* The function getDiv accepts three floating values
 * and then calls the doDiv function. The three accepted
 * values are passed as parameters in the function call.
 */

 void getDiv(float a, float b, float c)
 {
    float finalAnswer;
    finalAnswer = doDiv(a,b,c);
    printf("%f\n", finalAnswer);
 }

I have tried my best to comment each function but I am not sure if I am doing it correctly. Can someone please advise me on making my comments better, naming variables better and anything else that can help me utilize coding standards correctly?

I would like to pick up the habit now while I am still writing small lines of code so I can take it forward with me when I write bigger codes.

Any suggestions on how I can comment better, name variables better, write code more elegant are welcome. Also, do I comment the method declarations on top?

There's a bit to say about this code, so I'll try to take it from the top and work my way down:

Declare main() after your functions so you don't have to declare those function prototypes at the beginning of your source code.
You shouldn't be printing anything from the functions other than main() here.  You should be returning the values to main() and handle them there.
You are restricting yourself by only accepting int parameters into your getsum() function.  I would use intmax_t from <stdint.h> instead.
You don't protect yourself from integer overflow within any of your functions. Take a look at this question and answer for an idea of how to implement that protection using the latest standards.
Why does your doDiv() function accept float values, and then return a double value?  Inconsistent and not what a programmer would expect.  Either return a float, or accept doubles as parameters.
Always declare what parameters your function takes in, even if nothing.

int main(void)

You might wonder why we have to do this.  Imagine we have the function foo() declared as such:

int foo()

In C, this is known as an identifier list and means that it "can take any number of parameters of unknown types".  We can actually pass values to the function even though we don't mean to or intend to.  If the caller calls the function giving it some argument, the behavior is undefined. The stack could become corrupted for example, because the called function expects a different layout when it gains control.

Using identifier lists in function parameters is depreciated.  It is much better to do something like:

int foo(void)

In C, this is known as a parameter type list and defines that the function takes zero arguments (and also communicates that when reading it) - like with all cases where the function is declared using a parameter type list, which is called a prototype.   If the caller calls the function and gives it some argument, that is an error and the compiler spits out an appropriate error.

The second way of declaring a function has plenty of benefits. One of course is that amount and types of parameters are checked. Another difference is that because the compiler knows the parameter types, it can apply implicit conversions of the arguments to the type of the parameters. If no parameter type list is present, that can't be done, and arguments are converted to promoted types (that is called the default argument promotion). char will become int, for example, while float will become double.
Use %g when printing float values.  It also allows you to print double if you decide to "upgrade" the type later.
You don't have to return 0 at the end of main(), just like you wouldn't bother putting return; at the end of a void-returning function. The C standard  knows how frequently this is used, and lets you not bother.

  C99 & C11 §5.1.2.2(3)

  ...reaching the } that terminates the main() function returns a
  value of 0.

You asked me to comment on your formatting and documentation.  I find leading by example is a good way to learn something, so look at how I do it in this question of mine. Also, I use doxygen for my documentation generation.  I think it is a good habit that you should get into as well.


Helper function to solve Project Euler question 26 Project Euler problem 26 asks us to:

  Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.

I wrote this function in Python to find the decimal representation of a rational number p/q. How can I improve it? Also suggest good coding styles.

#! /usr/bin/env python
# -*- coding - utf-8 -*-

"""This program converts a rational number
into its decimal representation.

A rational number is a number of the form p/q
where p and q are integers and q is not zero.
The decimal representation of a rational number
is either terminating or non-terminating but
repeating.

"""

def gcd(a, b):
    """Computes gcd of a, b
    using Euclid algorithm.

    """

    if not isinstance(a, int) or not isinstance(b, int):
        return None

    a = abs(a)
    b = abs(b)

    while b != 0:
        a, b = b, a % b

    return a

def decimal(p, q):
    """Computes the decimal representation
    of the rational number p/q. If the
    representation is non-terminating, then
    the recurring part is enclosed in parentheses.
    The result is returned as a string.

    """

    if not isinstance(p, int) or not isinstance(q, int):
        return ''

    if q == 0:
        return ''

    abs_p = abs(p)
    abs_q = abs(q)

    s = (p / abs_p) * (q / abs_q)
    g = gcd(abs_p, abs_q)

    p = abs_p / g
    q = abs_q / g

    rlist = []
    qlist = []

    quotient, remainder = divmod(p, q)
    qlist.append(quotient)
    rlist.append(remainder)

    if remainder == 0:
        return str(quotient)

    while remainder != 0:
        remainder *= 10
        quotient, remainder = divmod(remainder, q)
        qlist.append(quotient)

        if remainder in rlist:
            break
        else:
            rlist.append(remainder)

    qlist = map(str, qlist)

    if remainder:
        recur_index = rlist.index(remainder) + 1
        dstring = qlist[0] + '.' + ''.join(qlist[1:recur_index]) + \
            '(' + ''.join(qlist[recur_index:]) + ')'

        if s < 0:
            dstring = '-' + dstring
    else:
        dstring = qlist[0] + '.' + ''.join(qlist[1:])

        if s < 0:
            dstring = '-' + dstring

    return dstring

if __name__ == '__main__':
    p = raw_input('p: ')
    q = raw_input('q: ')

    try:
        p = int(p)
        q = int(q)

        if q == 0:
            raise ValueError

        print '%d/%d =' % (p, q), decimal(p, q)
    except ValueError:
        print 'invalid input'

I'm just going to comment on your gcd function.

The docstring mixes up the function's interface ("computes gcd of a, b") with its implementation ("using Euclidean algorithm"). It's best to restrict the docstring to the interface (which is what the user needs to know); if you also need to document the implementation, put it in comments.
Your gcd implementation returns None if its arguments are not integers. This behaviour should be mentioned in the docstring.
But returning exceptional values is generally a bad idea: it pushes the complexity of error handling onto the caller, where it would be easy to forget to do the checking. And in fact you have failed to check that the result is not None:

g = gcd(abs_p, abs_q)
p = abs_p / g   # What if g is None here?

It is better for a function to raise an exception if it is given the wrong arguments: that way the caller doesn't need to take any special precautions, but the error is reliably detected and reported.
The test isinstance(a, int) is too restrictive. Euclid's GCD algorithm will work on other kinds of numbers too, and it would be nice to be able to support:

>>> from fractions import Fraction
>>> gcd(Fraction(1, 3), Fraction(1,4))
Fraction(1, 12)

or:

>>> from decimal import Decimal
>>> gcd(Decimal('11.1'), Decimal('2.1'))
Decimal('0.3')

instead of having to write separate gcd implementations for these other types.

So in fact the best thing to do is not to have any type-checking at all in your gcd function. If someone calls it with the wrong type of object, they will get a TypeError:

>>> gcd('hello', 'world')
Traceback (most recent call last):
    ...
TypeError: not all arguments converted during string formatting

You call abs on the arguments a and b. But in fact you only ever call gcd with arguments that have non-negative values already. So the extra calls to abs are wasted.
So in summary, I would write the gcd function like this:

def gcd(a, b):
    """Return the greatest common divisor of a and b."""
    while b != 0:
        a, b = b, a % b
    return a

But in fact Python already has a built-in gcd function (in the fractions module), so all you actually have to do is write:

from fractions import gcd


Composing URLs for fetching passenger fares from multiple providers Can someone give me advice, how to make this code look nice?

def getFare(self, orig, dest, odate, idate, vid, pax, lang, epi, country_from, country_to):

    def create_link(link_str, API_url, dep_date, ret_date, magic_code, lang):
        '''
        :param link_str: str on which you will use format method
        :param API_url: on which url you should send request
        :param dep_date: departure date as strftime('%d.%m.%Y')
        :param ret_date: arrival date as strftime('%d.%m.%Y')
        :param magic_code: some numbers that identifies the request
        :param lang:
        :return: completed url for request
        '''
        kid_age = ''
        if len(pax['ages']) > 0:
            for age in pax['ages']:
                kid_age += str(age) + ','
            kid_age = kid_age[:-1]
        ages = 0 if kid_age == '' else kid_age
        trip_type = 'false' if idate else 'true'

        created_link = link_str.format(
            url=API_url,
            orig=orig,
            dest=dest,
            dep_date=dep_date,
            ret_date=ret_date,
            adults=pax['a'],
            children=pax['c'] + pax['i'],
            age=ages,
            trip_type=trip_type,
            magic_code=magic_code,
            epi=epi,
            curr=vendor_info[2],
            lang=lang
        )
        return created_link

    if vid == 1:
        user_id = 'some_id'
        new_url = 'http://www.www.www/search/results'
        idate = odate.strftime('%d.%m.%Y') if not idate else idate.strftime('%d.%m.%Y')
        format_url = '{url}/dc/{orig}/rc/{dest}/dd/{dep_date}/rd/{ret_date}/noa/{adults}/noc/{children}/ca/{age}/' \
                         'ow/{trip_type}/mid/{magic_code}/curr/{curr}/lang/{lang}'
        url = create_link(format_url, new_url, odate.strftime('%d.%m.%Y'), idate, user_id, lang)
    else:
        two_way = '/rd/%s' % idate.strftime('%d.%m.%Y') if idate else ''
        format_url = 'http://{url}/iws/search/dc/{orig}/rc/{dest}/dd/{dep_date}{ret_date}/' \
                         'noa/{adults}/noc/{children}/ca/{age}/ow/{trip_type}/mr/50/mid/{magic_code}/msparams/{epi}/' \
                         'curr/{curr}/lang/{lang}'
        url = create_link(format_url, vendor_info[0], odate.strftime('%d.%m.%Y'), two_way, vendor_info[1], lang)

    res = requests.get(url, timeout=(3.1, 30))

Is this a good idea to put a string and parameters for format method in different function and format the string in it?

You can definitely simplify some things. For example, determining the ages variable:

kid_age = ''
if len(pax['ages']) > 0:
    for age in pax['ages']:
        kid_age += str(age) + ','
    kid_age = kid_age[:-1]
ages = 0 if kid_age == '' else kid_age

can be done in a single line and str.join():

ages = ','.join(pax['ages']) if pax['ages'] else 0

Some other notes:

docstrings should be enclosed in triple double quotes, not single quotes
I would move create_link from out of the function to "helpers" or "libs"
define your format_url format strings as constants and move to the module level
follow lower_case_with_underscores variable and method naming convention
define your date format as a constant as well - this way, if it changes, you would make a change in a single place only


Selection sort review. Does it look good? I always wanted to ask this but couldn't for some reason.

I had written this chunk of code about 3 months ago when one of my teacher explained what selection sort was using flow chart. I had a basic understanding of what arrays were. So I sat down and wrote this:

#include <stdio.h>

#define MAX_NUMBER 10

void selection_sort(int [], int []);

void selection_sort(int num[], int sorted[])
{
    int i, high = 0, k, j = 9, store;

    for(k = 0; k < MAX_NUMBER; k++)
    {
      for(i = 0; i < MAX_NUMBER; i++)
      {
         if(num[i] > high)
         {
             high = num[i];
             store = i;
         }
      }

      sorted[j] = high; // Place the highest number in the end of array and decrement array
      j--;
      num[store] = 0; // Place 0 in the place of maximum number that was in the array
      high = 0; // again make high as zero, so as to compare zerpo again with all the numbers that are in the array
    }
}

int main()
{
    int num[MAX_NUMBER], sorted[MAX_NUMBER];
    int i;

    printf("Enter %d numbers: ", MAX_NUMBER);

    for(i = 0; i < MAX_NUMBER; i++)
    {
        scanf("%d", &num[i]);
    }

    selection_sort(num, sorted);

    for(i = 0; i < MAX_NUMBER; i++)
      printf("%d ", sorted[i]);

    return 0;
}

and I took almost 30 minutes to write this. But as you know the program in text books are a lot faster and smaller.

Can you please tell me what kind of programmer I can become? I have been programming for a good 6 months now.

This code review monster got into my head after reading Steve McConnell: Code Complete. Still I have a lot of pages to go through.

You don't need two arrays, it works with one too, simply swap the
values. This needs less memory.
According to this:

int i, high = 0, k, j = 9, store;

j is always one less than the size of the array. Don't use magic numbers, use the constant.
If you want to reuse this selection_sort it would be adviseable to
add a parameter for the size, so you don't need the global constant.
In the inner loop you also iterate through the array parts which also have been sorted. (This may also be the reason you choose to use two arrays)
The result may be wrong if you'd only have negative values in the array (due high = 0)

Here my improved implementation:

void selection_sort(int *num, size_t size)
{
    size_t k, i, j, store; // for indexes
    int high, swap; // for values

    // no need to sort if the array is short enough
    if(size <= 1) return;

    high = INT_MIN; // set the highest number to the minium
    j = size - 1;

    for(k = 0; k < size; k++, j--)
    {
      for(i = 0; i <= j; i++)
      {
         if(num[i] >= high)
         {
             high = num[i];
             store = i;
         }
      }

      // swap the highest number with the number at the last position
      // in the array
      swap = num[j];
      num[j] = num[store];
      num[store] = swap;
      high = INT_MIN; // reset the highest number
    }
}

There is also a similar implementation on Wikipedia


Rate my first python prime checker I'm new to programming; I started about a week ago and started learning python.
Currently, I only know some basic arithmetic operations in addition to some basic knowledge about lists, dictionaries, strings, etc.

I tried testing what I learnt so far. I made this prime number checker, which works except when the numbers are really big.  Please rate it and suggest improvements that I can understand at my current level.

Here is the code:

'''
pr means the number we'll be working on
dl is a dictionary that contains our the dividend and the reaminder
x is the dividend
e is a list that contains all remainders
and what the program does as you might have guessed already
it makes a list of all remainders of the division of our number by every integer before it
and checks for the number 0
if it finds it then the number is not prime
and if it doesn't then it's prime
'''

pr = int(input("Enter your number "))

print("\n")

dl = {}

x = pr - 1
while x < pr and x > 1 :
    r = pr % x
    dl[x]= r
    x -= 1

e = list(dl.values())

if any( z == 0 for z in e ) :
    print(pr," is not a prime number")
else :
    print(pr," is a prime number")

print("\n")

input("Press Enter to close the program")

I'd have to rate your program a "D-Minus".

incorrectly labels 1, 0, and all negative numbers as prime!
runs in \$O(n)\$ time, instead of \$O(\sqrt n)\$ time
runs in \$O(n)\$ space, instead of \$O(1)\$ space

Other deficiencies:

'''docstrings''' should be used for describing "how" to use the module/class/method; comments should be used to explain how the code works
variable names are cryptic; too short to be descriptive
PEP8 guidelines are not consistently followed.  Operators like = should have 1 space on each side.  No space should be used after (, or before ), as well as not before :
a dictionary is being used to store a list of values; a simple list would suffice
dl.values() is an iterable; there is no need to convert it into a list in order to use in the for z in ...

As suggested by aaaaa says reinstate Monica,
please work on your solution and then submit it as a new question.


Making a dynamic query based on a cookie change I have a PHP function which sets/unsets something (category and tags) in the cookie and then makes a dynamic query based on it:

public function tagged(){

    $this->specific_tag  =  true;

    function unset_cookie($cookie_name) {
        setcookie($cookie_name, "", time() - 3600, '/');
        unset($_COOKIE[$cookie_name]);
    }

    function set_cookie($cookie_name, $cookie_value) {
        setcookie($cookie_name, $cookie_value, 2147483647, '/');
        $_COOKIE[$cookie_name] = $cookie_value;
    }

    if ( isset($_GET['c']) ) {
        if ( empty($_GET['c']) ) {
            unset_cookie('qanda_questions_category');
        } else {
            set_cookie('qanda_questions_category', $_GET['c']);
        }
    }

    if ( isset($_GET['t']) ) {
        if ( empty($_GET['t']) ) {
            unset_cookie('qanda_questions_tag');
        } else {
            set_cookie('qanda_questions_tag', $_GET['t']);
        }
    }

    $this->consider_category_tag_cookies();

    if ( $this->category_cookie || $this->tag_cookie ) {

        $query_where = $query_join = '';

        if ( $this->category_cookie ) {
            $query_where .= "AND qa.category = :c";
            $this->parameters[":c"] = $_COOKIE['qanda_questions_category'];
        }

        if ( $this->tag_cookie ) {
            $query_join  .= " INNER JOIN qanda_tags qt ON qt.qanda_id = qa.id
                              INNER JOIN tags ON tags.id = qt.tag_id";
            $query_where .= " AND tags.name = :t";
            $this->parameters[":t"] = $_COOKIE['qanda_questions_tag'];
        }

        return $this->index($query_where, $query_join, __FUNCTION__);
    } else {
        return header("Location: /myweb/questions".make_url_query($_GET, [],['c','t']));
    }
}

I've tried so much to write it clean and functional, but it contains lots of if statements. It bothers me and I think it should be possible to reduce some of them. Do you have any idea?

Do I need to add more function to the code? Or should I chop the code into multiple separated functions? Anyway, how can I write it more cleanly?

First suggestion is that you shouldn't write the same code twice.

Your $_GET-if-conditions can be put into a separate function.

$this->handleCookieByGetParameter('c', 'qanda_questions_category');
$this->handleCookieByGetParameter('t', 'qanda_questions_tag');

public function handleCookieByGetParameter($parameter, $name)
{
    if ( isset($_GET[$parameter]) ) {
        if ( empty($_GET[$parameter]) ) {
            unset_cookie($name);
        } else {
            set_cookie($name, $_GET[$parameter]);
        }
    }
}

and then I recommend that you check your error before you handle your other stuff:

if ( !$this->category_cookie && !$this->tag_cookie ) {
    return header("Location: /myweb/questions".make_url_query($_GET, [],['c','t']));
    // better an RedirectException
}

$query_where = $query_join = '';

if ( $this->category_cookie ) {
    $query_where .= "AND qa.category = :c";
    $this->parameters[":c"] = $_COOKIE['qanda_questions_category'];
}

if ( $this->tag_cookie ) {
    $query_join  .= " INNER JOIN qanda_tags qt ON qt.qanda_id = qa.id
                  INNER JOIN tags ON tags.id = qt.tag_id";
    $query_where .= " AND tags.name = :t";
    $this->parameters[":t"] = $_COOKIE['qanda_questions_tag'];
}

return $this->index($query_where, $query_join, __FUNCTION__);

my next step would be to look to extract the query code into a separate function, so I could use it for other methods too.


Basic calculator program in Python I was writing a basic calculator program to practice my skills at python.
I'm a beginner at Python and was wondering if there is a way to simplify this code of mine? It seems a little bit too long and messy in some sort of way.
Again, I'm still a beginner so I don't know all the tricks in the book!

import math
import time

def add(x,y):
  return x + y

def subtract(x,y):
  return x - y

def divide(x,y):
  return x / y

def multiply(x,y):
  return x * y

def sqrt(x):
  if math.sqrt(x) * math.sqrt(x):
     return False
  else:
     return math.sqrt(x)

def power(x,y):
  return math.pow(x,y)

def repeat():
  print('Would you like to perform another calculation? y/n')
  rep = input('')
  if rep.lower() == 'y':
     time.sleep(0.5)
     main()
  elif rep.lower() == 'n':
     print('Goodbye!')
     time.sleep(1)
     exit()
  else:
     print('Please enter y/n.')
     time.sleep(1)
     repeat()

def numCheck(x):
  try:
     int(x)
  except ValueError:
     print("Please enter a valid number.")
     print('')
     time.sleep(1)
     main()

def choiceCheck(y, z):
   for x in y:
       if x == z:
           return True
           break
       else:
           pass

def main():
  choices = ['1', '2', '3', '4']
  print('Choose your operation: ')
  print('1. Add')
  print('2. Subtract')
  print('3. Divide')
  print('4. Multiply')
  print('5. Square Root')
  print('6. Exponent')
  print('1/2/3/4/5/6')
  choice = input('')
  if choice == '5':
     print('Please choose the number you would like to square root.')
     rt = input('')
     numCheck(rt)
     rt = int(rt)
     rts = sqrt(rt)
     if rts == False:
        print('%d is an irrational number.' % (rt))
     else:
        print('The square root of %d is %d' % (rt, rts))
        repeat()
  elif choice == '6':
     print('Choose the number you would like to raise to a power: ')
     base = input('')
     numCheck(base)
     base = int(base)
     print('')
     print('Now please choose the indice: ')
     ind = input('')
     numCheck(ind)
     ind = int(ind)
     time.sleep(1)
     print('%d to the power of %d is %d' % (base, ind, power(base,ind)))
     repeat()
  elif choiceCheck(choices, choice) != True:
     print('Please choose a valid number.')
     print('')
     time.sleep(1)
     main()
  a = input('Please choose your first number: ')
  numCheck(a)
  a = int(a)
  print('')
  b = input('Please choose your second number: ')
  numCheck(b)
  b = int(b)
  if choice == '1':
     print('%d + %d = %d' % (a, b, add(a,b)))
  elif choice == '2':
     print('%d - %d = %d' % (a, b, subtract(a,b)))
  elif choice == '3':
     print('%r / %r = %r' % (a, b, divide(a,b)))
  elif choice == '4':
     print('%d * %d = %d' % (a, b, multiply(a,b)))
  else:
     print('Please choose a valid number')
     print('')
     time.sleep(1)
     main()
  repeat()

main()

All help is appreciated!

This being Python, where indentation is significant, it is important to consistently follow the convention of four spaces per level.

You shouldn't format the square root as %d, since the result is rarely an integer.

There are several recommendations that I could make about organizing this code, but the single most important point is that functions should not be treated as goto labels.  If you need a loop, then write a loop using while or for.  Don't have main call main().  Don't have repeat call main().  Don't have repeat call repeat().  Otherwise, you end up with spaghetti code.


Web scraping the titles and descriptions of trending YouTube videos This scrapes the titles and descriptions of trending YouTube videos and writes them to a CSV file. What improvements can I make?

from bs4 import BeautifulSoup
import requests
import csv

source = requests.get("https://www.youtube.com/feed/trending").text
soup = BeautifulSoup(source, 'lxml')

csv_file = open('YouTube Trending Titles on 12-30-18.csv','w')
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['Title', 'Description'])

for content in soup.find_all('div', class_= "yt-lockup-content"):
    try:
        title = content.h3.a.text
        print(title)

        description = content.find('div', class_="yt-lockup-description yt-ui-ellipsis yt-ui-ellipsis-2").text
        print(description)

    except Exception as e:
        description = None

    print('\n')
    csv_writer.writerow([title, description])

csv_file.close()

Why web-scrape, when you can get the data properly through the YouTube Data API, requesting the mostpopular list of videos?  If you make a GET request to https://www.googleapis.com/youtube/v3/videos?key=…&part=snippet&chart=mostpopular, you will get the same information in a documented JSON format.

Using the Python client, the code looks like:

import csv
import googleapiclient.discovery

def most_popular(yt, **kwargs):
    popular = yt.videos().list(chart='mostPopular', part='snippet', **kwargs).execute()
    for video in popular['items']:
        yield video['snippet']

yt = googleapiclient.discovery.build('youtube', 'v3', developerKey=…)
with open('YouTube Trending Titles on 12-30-18.csv', 'w') as f:
    csv_writer = csv.writer(f)
    csv_writer.writerow(['Title', 'Description'])
    csv_writer.writerows(
        [snip['title'], snip['description']]
        for snip in most_popular(yt, maxResults=20, regionCode=…)
    )

I've also restructured the code so that all of the CSV-writing code appears together, an inside a with open(…) as f: … block.


Playing Card in Swift I'm trying to properly write a card class in swift. I've been taking classes in software engineering and I need help in understanding how to take a more object-oriented approach to my class. I have seen a Class for suit and rank and I'm wondering would that approach would be better? I have also seen the suit as enums and wonder if that approach would be better.

Any help will be appreciated.

Thank you

class Card

private var rank: Int
private var suit: Int

init(n: Int) {
    self.rank = -1;
    self.suit = -1;
    if(n >= 0 && n <= 51) {
        self.rank = n % 13;
        self.suit = n / 13;
    }
}

func getRank() -> Int {
    return self.rank;
}

func getSuit() -> Int {
    return self.suit;
}

func compareRank(otherCard: Card) -> Bool {
    return self.rank == otherCard.getRank();
}

func compareSuit(otherCard: Card) -> Bool {
    return self.suit == otherCard.getSuit();
}

In addition to what @Carpsen90 said:

No get... accessor methods

Unlike some other programming languages, you don't define accessor methods for the properties, these are implicitly created by the compiler. If suit and rank are constant properties (initialized once and never mutated) then it is simply

struct Card {
    let rank: Int
    let suit: Int

    // ...
}

For properties which are publicly read-only, but internally read-write, it is

 struct Card {
    private(set) var rank: Int
    private(set) var suit: Int

    // ...
}

That makes the compareRank/Suit methods obsolete, because you can directly  test

if card1.rank == card2.rank { ... }

etc.


Updating values in a database I'm using standard jQuery Ajax to update values in the database and reflect the result in an output. This repetition seems like bad practice and I don't know enough about jQuery to consolidate this correctly.

jQuery

        $("#vendorticket").change(function() { //Input/Select tag
            var output = ("#vendorticket-result");
            $.ajax({
                url: 'includes/view.func.php', // Updating database based on specified row id, column, and value
                type: 'post',
                data: {
                    vendorticket: $(this).val(),
                    column: 'vendorticket',
                    id: 15
                },
                success: function(result) {
                    $(output).html(result); //Output span either "Saved" or "Save Failed"
                }
            });
        });

//Rinse & Repeat...

        $("#priority").change(function() {
            var output = ("#priority-result");
            $.ajax({
                url: 'includes/view.func.php',
                type: 'post',
                data: {
                    priority: $(this).val(),
                    column: 'priority',
                    id: 15
                },
                success: function(result) {
                    $(output).html(result);
                }
            });
        });

        $("#assignedto").change(function() {
            var output = ("#assignedto-result");
            $.ajax({
                url: 'includes/view.func.php',
                type: 'post',
                data: {
                    assignedto: $(this).val(),
                    column: 'assignedto',
                    id: 15 //
                },
                success: function(result) {
                    $(output).html(result);
                }
            });
        });

    });

HTML

<input type="text" id="assignedto" />

<input type="text" id="priority" />

<input type="text" id="vendorticket" />

Simplifying redundancy
You could do something like iterating over the id attribute of each input element, calling a function to add the handler.
['priority', 'assignedTo', 'vendorticket'].forEach(addChangeHandler);

function addChangeHandler(inputId) {
    $("#" + inputId).change(function() { //Input/Select tag
        var output = ("#" + inputId + "-result");
        var data = {
            column: inputId,
            id: 15
        };
        data[inputId] = $(this).val()
        $.post({
            url: 'includes/view.func.php', // Updating database based on specified row id, column, and value
            data: data,
            success: function(result) {
                $(output).html(result); //Output span either "Saved" or "Save Failed"
            }
        });
    });
}

Note the code uses the shortcut method $.post() to allow skipping the request type.
But a simpler technique would be to add a generic change handler that would be called after any change event on any of those inputs. This can be done by combining the selectors passed to the jQuery function:
$('#priority, #assignedTo, #vendorticket')

This can then be used to add a generic function handler that can get the id of the input using .attr('id'):
$('#priority, #assignedTo, #vendorticket').change(changeHandler);
function changeHandler() {
    var inputId = $(this).attr('id');
    var output = ("#" + inputId + "-result");
    var data = {
        column: inputId,
        id: 15
    };
    data[inputId] = $(this).val()
    $.post({
        url: 'includes/view.func.php', // Updating database based on specified row id, column, and value
        data: data,
        success: function(result) {
            $(output).html(result); //Output span either "Saved" or "Save Failed"
        }
    });
}

If you had a lot more input elements to add to that list, a class could be applied and they could be selected by class name (e.g. $('.inputToWatch')) or else if they were all child elements of a container then a child selector might simplify things (e.g. $('#containerElement input').
Simplifying the success function
The success function could be replaced with a bound function - i.e. a function bound to $(output).html:
success: $().html.bind($(output))

These changes are visible in this phpfiddle.
You could also use the other syntax of $.ajax() i.e. Query.post( url [, data ] [, success ] [, dataType ] )
$.post('includes/view.func.php', data, $().html.bind($(output)));


Minecraft city class This is a class representing a city in a mod I am creating for Minecraft. All the constructor parameters are mandatory and they are used to help the class that calculates and builds the Paths, Buildings etc.

The City class has all the fields that are listed in the constructor including a 2D array that is a representation of the city in X and Z axes. There are also 2 methods to serialize and deserialize the data in order to save them using the Minecraft Forge API.

public City(int id, BlockPos startingPos, int citySize, int edgeLenght, int pathExtends, Block groundBlock, Block pathBlock, boolean hasMainStreets, boolean hasPaths) {
    this.id = id;

    this.startingPos = startingPos;

    this.chunkLength = citySize;

    this.cityLength = citySize * 16;
    this.edgeLength = edgeLenght;
    this.mapLength = cityLength + edgeLenght + blockStart;

    this.pathExtends = pathExtends;

    this.hasMainStreets = hasMainStreets;
    this.hasPaths = hasPaths;

    this.groundBlock = groundBlock;
    this.pathBlock = pathBlock;

    this.blockStart = edgeLenght;

}

Initializing a city object looks like:

BlockPos startingPos = new BlockPos(1000,63,1000);
int citySize = 5; // Will be pseudorandom
int edgeLength = 4;// Will be pseudorandom
int pathExtends = 2;// Will be pseudorandom
City newCity = new City(++id, startingPos, citySize, edgeLength, pathExtends, Blocks.OBSIDIAN, Blocks.DIAMOND_BLOCK, true, true);

From an organizational point of view I can see the benefits of this approach but is this a good practice? Does it involve any pitfalls I have not thought about or is there a better way to do this?

This is not easy to read and understand and I was wondering if there was any better way to do it. My idea was to create CitySettings object hence making more readable the City object by moving all these fields to another class.

I am thinking of creating a class CitySettings to hold all of City's fields and an instance of CitySettings that will be stored as a field in the City class.

If it's readability you're mostly worried about, then you could change the style of your code:

public City(int id,          BlockPos startingPos,
            int citySize,    int edgeLenght,
            int pathExtends, Block groundBlock,
            Block pathBlock, boolean hasMainStreets,
            boolean hasPaths) {
    this.id             = id;
    this.startingPos    = startingPos;
    this.chunkLength    = citySize;
    this.cityLength     = citySize * 16;
    this.edgeLength     = edgeLenght;
    this.mapLength      = cityLength + edgeLenght + blockStart;
    this.pathExtends    = pathExtends;
    this.hasMainStreets = hasMainStreets;
    this.hasPaths       = hasPaths;
    this.groundBlock    = groundBlock;
    this.pathBlock      = pathBlock;
    this.blockStart     = edgeLenght;

}

Columnising is a useful trick which can make things more readable.

Yes, there is still visibly a lot of parameters clogging up the screen, but it's not so much that you can't put it all in one constructor. It also helps to remember KISS (Keep It Simple, Stupid), don't overcomplicate unless you need to.


linked list in c code I have implemented linked list data structure in c.

linkedlist.h

#ifndef LINKED_LIST
#define LINKED_LIST

#include <stdbool.h>

struct linkedlist {
    int key;
    struct linkedlist* next;
    struct linkedlist* prev;
};

bool list_insert(struct linkedlist** p,int k);
struct linkedlist* list_search(struct linkedlist* p,int k);
bool list_delete(struct linkedlist** p,int k);
void list_show(struct linkedlist* p);
void memory_map(struct linkedlist* p);

#endif

list.c

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

bool list_insert(struct linkedlist** p,int k) {
    struct linkedlist* x = malloc(sizeof (struct linkedlist));
    if(!x)
    {
        return false;
    }
    x->key = k;
    x->prev = NULL;
    x->next = *p;

    if(*p)
    {
        (*p)->prev = x;
    }
    *p = x;
    return true;
}

struct linkedlist* list_search(struct linkedlist* p,int k) {
    if(!p)
    {
        return NULL;
    }

    while(p != NULL)
    {
        if(p->key == k)
        {
            return p;
        }
        p = p->next;
    }
    return NULL;
}

bool list_delete(struct linkedlist** p,int k) {
    struct linkedlist* x = list_search(*p,k);
    if(!x)
    {
        return false;
    }
    if(x->prev)
    {
        x->prev->next = x->next;
    }
    if(x->next)
    {
        x->next->prev = x->prev;
    }

    free(x);
    return true;
}

void list_show(struct linkedlist* p) {
    printf("\n[linkedlist][");
    while(p)
    {
        printf("%d ",p->key);
        p = p->next;
    }
    printf("]");
}
void memory_map(struct linkedlist* p) {
        printf("\n[memory map for linkedlist]");
        while(p)
        {
                printf("\n%d : [%p]", p->key,p);
                p = p->next;
        }
}

main.c

#include <stdio.h>
#include "linkedlist.h"

int main()
{
    struct  linkedlist* head = NULL;
    int i;
    for(i = 0; i < 5; i++)
    {
        if(!list_insert(&head,i+1))
            printf("list_insert operation fails");
    }
    list_show(head);
    memory_map(head);
    list_delete(&head,2);
    list_delete(&head,1);
    list_delete(&head,3);
    list_insert(&head,18);
    list_show(head);
    memory_map(head);
    return 0;
}

Naming

You should consider renaming or removing Your memory_map() function, all functions from Your linkedlist library does have a prefix list_, and this one does not. Also, it's kind a misleading. For user of Your library it might look like something related to mmap().

What does p, k, x mean? Please, consider using proper names for Your variables.

Verbosity

Just returning false in case of error usually is not verbose enough. I'd suggest considering proper error codes and/or proper error logger, for example something like this:

#ifndef LLIST_LOG
#define LLIST_LOG(format, ...) \
    fprintf(stderr, "LLIST_LOG: %s(): " format "\n", \
          __FUNCTION__, ##__VA_ARGS__)
#endif /* LLIST_LOG */

Consistency

Spacing and indentation is inconsistent. You should decide, how many spaces do You put between functions, how and when You separate if() {}, while() {}, arithmetical operations, etc blocks from each other or other logical parts of Your code. Or even better, use already defined C coding style, for example Linux kernel one.

Input verification

Rule of thumb, user of Your library is going to be dumb. And/or it will get messy debugging bigger project with Your library included. So, really, verify ALL the inputs. For example, Your list_delete(NULL, 1) segfaults.

Generic practices

Back to memory_map(), in general it's quite common to provide iterator function which calls some callback with every single element of the structure as a parameter instead. It's way more versatile.

It's common to suffix include guards by some randomly generated gibberish or hash, especially for such a common names as LINKED_LIST. Also, for compatibility with some compilers it usually defines it to some specific value. For example:

#ifndef LINKED_LIST_H_093e74eeda79fcc4c29e9d2986f5b701
#define LINKED_LIST_H_093e74eeda79fcc4c29e9d2986f5b701 1

Also, You should consider adding function list_create() and list_destroy() for Your library user not to mess with malloc() and free() directly and handle errors properly there.

Generic rant

There is a memory leak in Your example ;)


Speech Recognition Part 2: Classifying Data Now that I have generated training data, I need to classify each example with a label to train a TensorFlow neural net (first building a suitable dataset).  To streamline the process, I wrote this little Python script to help me.  Any suggestions for improvement?

classify.py:

# Builtin modules
import glob
import sys
import os
import shutil
import wave
import time
import re
from threading import Thread

# 3rd party modules
import scipy.io.wavfile
import pyaudio

DATA_DIR = 'raw_data'
LABELED_DIR = 'labeled_data'
answer = None

def classify_files():
    global answer
    # instantiate PyAudio
    p = pyaudio.PyAudio()

    for filename in glob.glob('{}/*.wav'.format(DATA_DIR)):
        # define stream chunk
        chunk = 1024

        #open a wav format music
        wf = wave.open(filename, 'rb')
        #open stream
        stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                        channels=wf.getnchannels(),
                        rate=wf.getframerate(),
                        output=True)
        #read data
        data = wf.readframes(chunk)

        #play stream
        while answer is None:
            stream.write(data)
            data = wf.readframes(chunk)
            if data == b'': # if file is over then rewind
                wf.rewind()
                time.sleep(1)
                data = wf.readframes(chunk)

        # don't know how to classify, skip sample
        if answer == '.':
            answer = None
            continue

        # sort spectogram based on input
        spec_filename = 'spec{}.jpeg'.format(str(re.findall(r'\d+', filename)[0]))
        os.makedirs('{}/{}'.format(LABELED_DIR, answer), exist_ok=True)
        shutil.copyfile('{}/{}'.format(DATA_DIR, spec_filename), '{}/{}/{}'.format(LABELED_DIR, answer, spec_filename))

        # reset answer field
        answer = None

        #stop stream
        stream.stop_stream()
        stream.close()

    #close PyAudio
    p.terminate()

if __name__ == '__main__':
    try:
        # exclude file from glob
        os.remove('{}/ALL.wav'.format(DATA_DIR))

        num_files = len(glob.glob('{}/*.wav'.format(DATA_DIR)))
        Thread(target = classify_files).start()
        for i in range(0, num_files):
            answer = input("Enter letter of sound heard: ")
    except KeyboardInterrupt:
        sys.exit()

Most of your comments aren't that great. Commenting about PEP8 compliance shouldn't be needed, and saying you're instantiating an object before doing it duplicates the amount we have to read for no actual gain.
os.path.join is much better at joining file locations by the OSes separator than '{}/{}'.format. Please use it instead.

An alternate to this in Python 3.4+ could be pathlib, as it allows you to extend the path by using the / operator. I have however not tested that this works with the functions you're using.

Here's an example of using it: (untested)

DATA_DIR = pathlib.PurePath('raw_data')

...

os.remove(DATA_DIR / 'All.wav')

You should move chunk out of the for loop, making it a function argument may be a good idea too.
Making a function to infinitely read your wf may ease reading slightly, and giving it a good name such as cycle_wave would allow people to know what it's doing. As it'd work roughly the same way as itertools.cycle. This could be implemented as:

def cycle_wave(wf):
    while True:
        data = wf.readframes(chunk)
        if data == b'':
            wf.rewind()
            time.sleep(1)
            data = wf.readframes(chunk)
        yield data

For your spec_filename you can use re.match to get a single match, rather than all numbers in the file name. You also don't need to use str on the object as format will do that by default.
Rather than removing a file from your directory, to then search the directory, you can instead remove the file from the resulting list from glob.glob. Since it returns a normal list, you can go about this the same way you would otherwise.

One way you can do this, is as followed:

files = glob.glob('D:/*')
try:
    files.remove('D:/$RECYCLE.BIN')
except ValueError:
    pass

If you have multiple files you want to remove you could instead use sets, and instead use:

files = set(glob.glob('D:/*')) - {'D:/$RECYCLE.BIN'}

All of this together can get you:

import glob
import sys
import os
import shutil
import wave
import time
import re
from threading import Thread

import scipy.io.wavfile
import pyaudio

DATA_DIR = 'raw_data'
LABELED_DIR = 'labeled_data'
answer = None

def cycle_wave(wf):
    while True:
        data = wf.readframes(chunk)
        if data == b'':
            wf.rewind()
            time.sleep(1)
            data = wf.readframes(chunk)
        yield data

def classify_files(chunk=1024):
    global answer
    join = os.path.join

    p = pyaudio.PyAudio()
    files = set(glob.glob(join(DATA_DIR, '*.wav'))) - {join(DATA_DIR, 'ALL.wav')}
    for filename in files:
        wf = wave.open(filename, 'rb')
        stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                        channels=wf.getnchannels(),
                        rate=wf.getframerate(),
                        output=True)

        for data in cycle_wave(wf):
            if answer is not None:
                break
            stream.write(data)

        # don't know how to classify, skip sample
        if answer == '.':
            answer = None
            continue

        # sort spectogram based on input
        spec_filename = 'spec{}.jpeg'.format(re.match(r'\d+', filename)[0])
        os.makedirs(join(LABELED_DIR, answer), exist_ok=True)
        shutil.copyfile(
            join(DATA_DIR, spec_filename),
            join(LABELED_DIR, answer, spec_filename)
        )

        # reset answer field
        answer = None

        #stop stream
        stream.stop_stream()
        stream.close()

    #close PyAudio
    p.terminate()

if __name__ == '__main__':
    join = os.path.join
    try:
        # exclude file from glob
        files = set(glob.glob(join(DATA_DIR, '*.wav'))) - {join(DATA_DIR, 'ALL.wav')}
        num_files = len(files)
        Thread(target = classify_files).start()
        for _ in range(0, num_files):
            answer = input("Enter letter of sound heard: ")
    except KeyboardInterrupt:
        sys.exit()

But I've left out proper handling of streams, in most languages, that I've used streams in, it's recommended to always close the steam. In Python it's the same. You can do this normally in two ways:

Use with, this hides a lot of the code, so it makes using streams seamless. It also makes people know the lifetime of the stream, and so people won't try to use it after it's been closed.

Here's an example of using it:

with wave.open('<file location>') as wf:
    print(wf.readframes(1024))

Use a try-finally. You don't need to add an except clause to this, as if it errors you may not want to handle it here, but the finally is to ensure that the stream is closed.

Here's an example of using it:

p = pyaudio.PyAudio()
try:
    stream = p.open(...)
    try:
        # do some stuff
    finally:
        stream.stop_stream()
        stream.close()
finally:
    p.terminate()

I'd personally recommend using one of the above in your code. I'd really recommend using with over a try-finally, but pyaudio doesn't support that interface. And so you'd have to add that interface to their code, if you wanted to go that way.


Extracting lines from a file, the smelly way I have a section of code I use to extract an event log out of a large text file. It works well, it's just my use of list(itertools.takewhile(...)) that feels a little sketchy to me.

Is there a nicer way of doing this?

import itertools

testdata = '''
Lots of other lines...
Really quite a few.

*************
* Event Log *
*************
Col1  Col2  Col3
----- ----- -----
1     A     B
2     A     C
3     B     D

Other non-relevant stuff...
'''

def extractEventLog(fh):
    fhlines = (x.strip() for x in fh)
    list(itertools.takewhile(lambda x: 'Event Log' not in x, fhlines))
    list(itertools.takewhile(lambda x: '-----' not in x, fhlines))
    lines = itertools.takewhile(len, fhlines) # Event log terminated by blank line
    for line in lines:
        yield line # In the real code, it's parseEventLogLine(line)

Expected output:

>>> list(extractEventLog(testdata.splitlines()))
['1     A     B', '2     A     C', '3     B     D']

Yes, it is indeed a bit sketchy/confusing to use takewhile when you really don't want to take the lines, but discard them. I think it's better to use dropwhile and then use its return value instead of discarding it. I believe that that captures the intent much more clearly:

def extractEventLog(fh):
    fhlines = (x.strip() for x in fh)
    lines = itertools.dropwhile(lambda x: 'Event Log' not in x, fhlines)
    lines = itertools.dropwhile(lambda x: '-----' not in x, lines)
    lines.next() # Drop the line with the dashes
    lines = itertools.takewhile(len, lines) # Event log terminated by blank line
    for line in lines:
        yield line # In the real code, it's parseEventLogLine(line)


Processing an API's JSON response I am using the JSON output of the MediaWiki API documented here and here, and I have found that for Boolean values, it often returns an empty string if true and omits it if false. Thus, I want to "rationalize" the response.

(Historical context: This was before a new output format was added that uses native JSON true and false.)

My current code to do so (written some months ago) is located in a giant anonymous function:

user = query.users[0];
invalid = typeof user.invalid != "undefined";
missing = typeof user.missing != "undefined";
groups = (typeof user.groups == "object") ? user.groups : [];
editcount = (typeof user.editcount == "number") ? user.editcount : null;
registration = (typeof user.registration == "string") ?
    UserinfoJsParseDate(user.registration) : null;
blocked = typeof user.blockedby != "undefined";
gender = (typeof user.gender == "string") ? user.gender : null;
lastEdited = (typeof query.usercontribs[0] == "object") &&
    (typeof query.usercontribs[0].timestamp == "string") ?
    UserinfoJsParseDate(query.usercontribs[0].timestamp) : null;

I am trying to clean this up, breaking the script's main components into separate functions:

/**
 * Extract relevant information from the server's response.
 * @param data The server's response to the AJAX request
 * @return An object containing the user's information
 */
function processResponse( data ) {
    var query = data.query, info = {};

    if ( query && query.users && query.users[0] ) {
        var user = query.users[0];

        info.invalid = 'invalid' in user;
        info.missing = 'missing' in user;
        info.groups = user.groups || [];
        info.editcount = ( 'editcount' in user ) ? user.editcount : null;
        info.registration = ( 'registration' in user ) ? parseDate( user.registration ) : null;
        info.blocked = 'blockexpiry' in user;
        info.gender = ( 'gender' in user && user.gender != 'unknown' ) ? user.gender : null;

        info.lastEdited = null;
        if ( query.usercontribs && query.usercontribs[0] ) {
            var contribs = query.usercontribs[0];
            if ( contribs.timestamp ) {
                user.lastEdited = parseDate( contribs.timestamp );
            }
        }

    }

    return info;
}

Is this better, or have I just written more messy code?

It is certainly better. You can improve it further:

Use early exits to reduce arrow code.
Use a JSON initializer for the result.
Prefix boolean names with 'is'.
Fix the 'user.lastEdited' bug.

.

function processResponse(data) {
    if (!data.query || !data.query.users || !data.query.users[0]) return {};

    var user = data.query.users[0];

    return {
        isInvalid: 'invalid' in user,
        isMissing: 'missing' in user,
        groups: user.groups || [],
        editCount: ('editcount' in user) ? user.editcount : null,
        registration: ('registration' in user) ? parseDate(user.registration) : null,
        isBlocked: 'blockexpiry' in user,
        gender: ('gender' in user && user.gender != 'unknown') ? user.gender : null,
        lastEdited: (data.query.usercontrib
                             && data.query.usercontribs[0]
                             && data.query.usercontribs[0].timestamp)
                        ? parseDate(data.query.usercontribs[0].timestamp) : null
    };
}


SelectionSort Algorithm using Python I am a rookie and I need help optimizing this SelectionSort() algorithm which I have tried using Python.
def selectionSort(arr,an):
    for lastUnsortedInteger in range(an-1,0,-1):
        largest = arr.index(max(arr[0:lastUnsortedInteger+1]))
        swap(arr,largest,lastUnsortedInteger)
    return arr

def swap(arr,ai,aj):
    arr[ai],arr[aj] = arr[aj],arr[ai]

if __name__ == '__main__':
    an = int(input())
    arr = list(map(int,input().strip().split()))
    selectionSort(arr,an)
    print("Sorted using SelectionSort():\n")
    for ai in arr:
        print(arr)

Seems like you already incorporated a few of the suggestions from back when this was on StackOverflow, e.g. changing the inner loop to max. However, you do so in a very inefficient way:

you create a slice of the list, O(n) time and space
you get the max of that slice, O(n) time
you get the index of that element, O(n) time

Instead, you can get the max of the range of indices, using a key function for comparing the actual values at those indices:
largest = max(range(0, lastUnsortedInteger+1), key=arr.__getitem__)

This way, this step has only O(n) time (for Python 3).
Some other points:

the an parameter (the length of the array/list) is not necessary, you can use len
in my opinion, it is a bit simpler looping from first to last index, and using min instead of max accordingly
since the swap is a single line now and only used once, we could inline this directly into the sorting function
the function modifies the list in-place, so no return is needed and might lead users to expect that the function does not modify the list but create a sorted copy instead
technically, arr is not an array but a list, and you might prefer snake_case to camelCase (it's "Python" after all)

My version:
def selection_sort(lst):
    for i in range(len(lst) - 1):
        k = min(range(i, len(lst)), key=lst.__getitem__)
        lst[i], lst[k] = lst[k], lst[i]

Needless to say, for all practical purposes you should just use sorted or sort.


Putting all desktop items into a new folder I'm quite a newbie with Python, but I wanted to try my own little project, so I made a small script that puts all the desktop icons/folders into a newly created folder (called "Desktop1") if there are more than 25 items on the desktop.

import os
import shutil

#My user on windows is Shadow so you're not like 'huh??'

os.chdir("C:\Users\Shadow\Desktop")
desktop = os.listdir("C:\Users\Shadow\Desktop")
desktopFiles = []

#Folder that the desktop files/icons will move to once created
newFolder = "C:\Users\Shadow\Desktop\Desktop1"

#Function that does the moving
def moveFilesToFolder(files, directory, folder):
    for files in directory:
        shutil.move(files, folder)

#Place the files into a list so I can determine how many there are
for x in desktop:
    desktopFiles.append(x)

if len(desktopFiles) > 25:    #If there's more than 25 files/icons on the desktop

   #If you already have an EMPTY folder named Desktop1 on your Desktop
    if os.path.exists(newFolder) and os.listdir(newFolder) == []:
        moveFilesToFolder(file, desktop, newFolder)
        print "Desktop1 already exists and is empty, so the files have been placed there"

    else:                 #Otherwise, make Desktop1 and move the icons/files into it
        os.mkdir(newFolder)
        moveFilesToFolder(file, desktop, newFolder)

What can I do to make it better? It works well and gets the job done, but is there any improvement I can make to it now (performance, syntax, etc.) that I can use for any later programs I may want to create? I feel like I'm not using object oriented programming at all.

You hard-coded "C:\Users\Shadow\Desktop" three times.  Once would have been too many, as it turns a general-purpose script into a throwaway script.  Your script could take a command-line parameter or infer the desktop directory for the current user.

If you must hard-code a path as a string literal, use raw strings to prevent Python from interpreting special backslash escape sequences such as \n for Newline.

Let's focus on this function:

#Function that does the moving
def moveFilesToFolder(files, directory, folder):
    for files in directory:
        shutil.move(files, folder)

What is files?  It's a parameter that you accept but never use.  Rather, you reuse the same variable name as a dummy variable for iteration.
Using an iteration variable with a plural name is awkward.
What do the parameters directory and folder mean?  How about renaming directory → files and folder → dest_dir for clarity?

I was curious how you actually call that function, given the weird parameter design.

moveFilesToFolder(file, desktop, newFolder)

At first glance, it appears that the script should fail, since file is never defined as a variable in your script.  However, it turns out that file is the name of a built-in constructor function.  So, you're passing some arbitrary function as a parameter to a function that ends up doing nothing with it.  I find that rather funny.


finding definite integrals in Python using Trapezium rule I wrote this program which finds the definite integral of a function. Where in the program could I optimize this code:

def trapezium(f,n,a,b):
    h=(b-a)/float(n)

    area = (0.5)*h
    sum_y = (f(0)+f(b))

    i=a
    while i<b:
        print i
        sum_y += 2*f(i)
        i += h

    area *= sum_y

    return area

def f(x):
    return x ** 2

print trapezium(f, 10000, 0, 5)

First, there is an error where you have:

sum_y = (f(0)+f(b))

f(0) should be f(a). It doesn't matter on your example, because you start with 0, but would otherwise.

Another error is that you add f(a) 3x instead of just once. i=a+h should be the line before while.

Your while loop makes O(n) multiplications and twice as many additions. Instead you should have something like:

i = a+h
part_sum = 0
while i<b:
    part_sum += f(i)
    i += h
sum_y += 2*part_sum

Still same number of additions, but only one multiplication.

Using list comprehensions might be a bit faster, but you'd spend too much memory at scale where it matters.

print significantly slows your function. If you actually need to print this, then store intermediate results in array and then print them before final result with print "\n".join(intermediates).


N queens problem in python I just tried to create a program for the N queens problem.

def print_board() -> None:
    """ Prints the board """

    length = 3 * (SIZE - 1) + SIZE + 4

    print()

    print('-' * length)

    for row in board:
        print('| ' + ' | '.join(row) + ' |')
        print('-' * length)

    print()

def isValid(row: int, col: int) -> bool:
    """ Returns if a cell index is valid """

    return 0 <= row < SIZE and 0 <= col < SIZE

def isSafe(row: int, col: int) -> bool:
    """ Checks if the given index position is safe """

    # Checks if the column is safe
    for i in range(SIZE):
        if i != row and board[i][col] != ' ':
            return False

    # Checks if the row is safe
    for j in range(SIZE):
        if j != col and board[row][j] != ' ':
            return False

    # Checks if the diagonals are safe
    for k in range(SIZE):
        if isValid(row + k, col + k) and board[row + k][col + k] != ' ' or \
           isValid(row - k, col + k) and board[row - k][col + k] != ' ' or \
           isValid(row + k, col - k) and board[row + k][col - k] != ' ' or \
           isValid(row - k, col - k) and board[row - k][col - k] != ' ':

            return False

    return True

def backtrack(row=0, total=0) -> bool:
    """ Backtracks and fills chacks for every possible combination """

    # If all rows are safely filled with queens
    if row == SIZE:
        # print_board()  # Uncomment the code to print the current solution
        # input('Enter to continue... ')

        return 1

    for col in range(SIZE):
        # If the current index is safe, check for the next row
        if isSafe(row, col):
            board[row][col] = 'Q'

            total += backtrack(row + 1)

            board[row][col] = ' '

    return total

def solve() -> None:
    """ Calls backtrack and prints number of solutions """

    total = backtrack()

    print()

    if not total:
        print('No possible solution was found')
    elif total == 1:
        print('There is a total of 1 solution')
    else:
        print(f'There are a total of {total} solutions')

if __name__ == '__main__':
    SIZE = int(input('Enter the size of the board: '))

    board = [[' '] * SIZE for row in range(SIZE)]

    solve()

Though it does work, I'm not satisfied yet.

I want to make this code as short as possible while also following Pep8 rules.

I believe there isn't a faster approach, but if there are any, please enlighten me!

Thank you!

This isn't bad looking code. It's formatted nicely, and I think this is a good use of type hints.

My two main concerns are your naming, and your use of print.

Names should be snake_case according to PEP8. You started adhering to it, then reverted back to camelCase later. It can be a hard change to make if you're used to other languages, but it's proper for Python, and studies have shown that it's easier to read anyways.

I think you're "abusing" print here.

print_board is printing the board instead of returning a representation that can be used elsewhere. I'd change it to format_board (or stringify_board or something similar), and have it return a string instead of forcibly printing the board. It would be a fairly trivial change too. Just concatenate the different printed strings together, replace the print() calls with a "\n", and change your imperative for loop to a list comprehension that you give to join after. It would honestly probably be shorter and cleaner after those changes anyways.

Then elsewhere, like in solve, you're printing the results. I would instead return some kind of indicator value, like an Enum instead of printing there.

Why bother with limiting print? Testing and portability. Say you wanted to programmatically test print_board. You would need to intercept sys.stdin to get the printed text to compare it against a known string. This is both slower and more complicated than just having a function that returns a string in the first place. The same goes for solve. To test that's its operating correctly, you need to verify what it's printing instead of just checking the return value.

Forcing use of print also prevents you from using these function in any other context, like a Tkinter UI.

Return the data and let the caller decide how they want to use it.

If you really want a print_board function for convenience, just make a wrapper:

def print_board() -> None:
    print(format_board())

Lastly, instead of using strings to indicate piece types, I'd use an Enum. Right now, you have a strong "Q" to indicate a queen on the board. Strings can be easily typo'd though; enums can't. If the only two valid board piece options are an empty space and a queen, you should use an enum to not only make that explicitly stated, but to enforce it. Entering an invalid enum invalid enum value will lead to an error instead of code-dependant effects that may end lead to silent failures.

I also realized just as I was about to submit this that your print_board and backtrack functions are relying on the global board defined in the "main". Don't do this! If those functions require data like board, that data should be explicitly passed in as arguments. If you wanted to test those functions, you wouldn't be able to just generate a dummy board in the console and pass it in. You would need to modify the global, run the function, then remember to modify to global again before further testing. The less relience you have on global variables, the easier your code will be to test and comprehend. Ideally, functions should accept as arguments all the data that they require, and return all data that they produce. This isn't always feasible, but it's a good design choice to pick unless you have a good reason to rely on globals (like board) and side-effects (like print).

Now that I'm on my full computer, I'm able to take a better look at the code and play with it a little more.

First, here's the enum usage that I was referring to. Ignore my previous suggestion for solve. I realized that an enum wasn't really appropriate there (I'll show my alternate suggestion after). Basically, BoardSquare represents the total possible states of each square on the board, along with the string representations that they have:

from enum import Enum

class BoardSquare(Enum):  # A square on the board can either be a queen, or an empty space
    QUEEN = "Q"
    EMPTY = " "

With that, I decided to use some slightly more advanced type hinting and created an alias for the board:

from typing import List

Board = List[List[BoardSquare]]  # A Board is a list of lists of board squares

This, combined with the enum ensures that nothing except a QUEEN or EMPTY is ever put into a board. Attempting to do so will cause a warning. This helps prevent typos:

board: Board = [[BoardSquare.EMPTY] * side_length for _ in range(side_length)]
board[1][2] = "SOME INVALID DATA"  # Causes an "Unexpected types" warning

And here's my format_board that I came up with:

# A helper to neaten up format_board
def _format_row(row: List[BoardSquare]) -> str:
    return '| ' + ' | '.join(square.value for square in row) + ' |'  # .value is the string defined in the enum

def format_board(board: Board) -> str:
    """ Formats the board as a string """
    board_length = len(board)  # Instead of relying on the global SIZE, I'd just compute it
    print_side_length = 3 * (board_length - 1) + board_length + 4

    top_bottom_str = '-' * print_side_length  # Might as well save this instead of writing the same thing twice.

    # I'll admit, this got a little more convoluted than I thought it would. It's just nested called to `join `though.
    return top_bottom_str + "\n" \
           + '\n'.join(_format_row(row) + '\n' + top_bottom_str for row in board)

Yes, as the comments note, this got a little longer than I though it would. The need to translate the enum into a string using the generator expression necessitated breaking off the formatting of each row into its own function for readability.

After going around and touching up some other stuff (see the comments), here's the full code that I ended up with:

from typing import List
from enum import Enum

class BoardSquare(Enum):  # A square on the board can either be a queen, or an empty space
    QUEEN = "Q"
    EMPTY = " "

Board = List[List[BoardSquare]]  # A Board is a list of lists of board squares

# Make it easier to create a new board for testing purposes
def new_board(side_length: int) -> Board:
    return [[BoardSquare.EMPTY] * side_length for _ in range(side_length)]

# A helper to neaten up format_board
def _format_row(row: List[BoardSquare]) -> str:
    return '| ' + ' | '.join(square.value for square in row) + ' |'  # .value is the string defined in the enum

def format_board(board: Board) -> str:
    """ Formats the board as a string """
    board_length = len(board)  # Instead of relying on the global SIZE, I'd just compute it
    print_side_length = 3 * (board_length - 1) + board_length + 4

    top_bottom_str = '-' * print_side_length  # Might as well save this instead of writing the same thing twice.

    # I'll admit, this got a little more convoluted than I thought it would. It's just nested called to `join `though.
    return top_bottom_str + "\n" \
           + '\n'.join(_format_row(row) + '\n' + top_bottom_str for row in board)

def print_board(board: Board) -> None:
    """ Prints the board """
    print(format_board(board))

def is_valid(row: int, col: int) -> bool:
    """ Returns if a cell index is valid """
    return 0 <= row < GLOBAL_SIZE and 0 <= col < GLOBAL_SIZE

def is_safe(row: int, col: int) -> bool:
    """ Checks if the given index position is safe """
    # Checks if the column is safe
    for i in range(GLOBAL_SIZE):
        if i != row and global_board[i][col] != BoardSquare.EMPTY:
            return False

    # Checks if the row is safe
    for j in range(GLOBAL_SIZE):
        if j != col and global_board[row][j] != BoardSquare.EMPTY:
            return False

    # Checks if the diagonals are safe
    for k in range(GLOBAL_SIZE):
        if is_valid(row + k, col + k) and global_board[row + k][col + k] != BoardSquare.EMPTY or \
           is_valid(row - k, col + k) and global_board[row - k][col + k] != BoardSquare.EMPTY or \
           is_valid(row + k, col - k) and global_board[row + k][col - k] != BoardSquare.EMPTY or \
           is_valid(row - k, col - k) and global_board[row - k][col - k] != BoardSquare.EMPTY:

            return False

    return True

def backtrack(row=0, total=0) -> int:  # I changed this to int. It was bool before, but that was wrong
    """ Backtracks and fills checks for every possible combination """
    # If all rows are safely filled with queens
    if row == GLOBAL_SIZE:
        # print_board(global_board)  # Uncomment the code to print the current solution
        # input('Enter to continue... ')
        return 1

    for col in range(GLOBAL_SIZE):
        # If the current index is safe, check for the next row
        if is_safe(row, col):
            global_board[row][col] = BoardSquare.QUEEN  # Use the enums values here instead
            total += backtrack(row + 1)
            global_board[row][col] = BoardSquare.EMPTY

    return total

def report_solution() -> None:
    """ Calls backtrack and prints number of solutions """
    total = backtrack()

    print()

    if not total:
        print('No possible solution was found')

    elif total == 1:
        print('There is a total of 1 solution')

    else:
        print(f'There are a total of {total} solutions')

if __name__ == '__main__':
    GLOBAL_SIZE = int(input('Enter the size of the board: '))

    global_board = new_board(GLOBAL_SIZE)

    report_solution()


Method to determine redirect after login I have a method that returns a URL to send a user should they pass a login.  My problem is two of these links are hard coded one of which is attempting to pass a variable to the model of that controller.  My question is two fold:

A. Is this safe
B. Is there a better way to do this without hard-coding things like this?

public class LoginViewModel
{
  public string UserId {get; set;}
  public string GetAppAccess()
  {
    using (var db = new WebContext())
    {
      var query = (from a in db.Permissions
                   join b in db.UserPermissions on a.PermissionId equals b.PermissionId
                   join c in db.Applications on a.Name equals c.AppName
                   where a.PermissionType == PermissionType.AppAccess & b.UserId == UserId
                   select c).ToList();
      switch (query.Count)
      {
        case 0:
          return "http://SERVERNAME/Tickets/Create?subject=Request%20For%20Application%20Access";
          // TODO: code ticket logic to except this argument
        case 1:
          return query[0].AppUrl;
        default:
          return "http://SERVERNAME/Dashboard/" + UserId;
      }
    }
  }
}

You are correct in feeling uneasy about the hardcoded URLs: I would put them in a config file.

By hardcoding them you will be forced to rebuild the project should you change to a different server while using a configuration file you can change it whenever you want and it will get picked up automatically.


Form involving several models related to each other I have a form that I feel I am overcomplicating because of the relationship between models that are involved.  Can you let me know if there's a more elegant solution to what I have?

(for reference) The form ultimately looks like this:

The relationship between the involved models:

user_relation has_many :user_relation_skills
user_relation_skills has_many :progresses
progress has_many :ratings, :as => :ratable

The form looks like this (I removed most of the classes/extraneous information but left the divs in to give a better idea of whats going on):

<%= simple_form_for(@user_relation) do |f| %>
    <%= f.fields_for :user_relation_skills do |ff| %>
        <%= ff.fields_for :progresses do |fff| %>
            <%= fff.fields_for :ratings do |ffff| %>

                        <%= link_to(user_relation_skill_path(ffff.object.scope)) do %>
                          <%= ffff.object.scope.skill.category.name %>&nbsp&nbsp<%= ffff.object.scope.skill.name %>
                        <% end %>

                <% if @current_type_for_views == 'coach' %>

                            <%= ffff.select("value", 1..8, {}, {class: "ratings-skill"}) %>

                                <%= button_tag(type: 'submit', class: "small button") do %>
                                    Update
                                <% end %>

                <% else %>

                            <%= ffff.select("value", 1..8, {}, {class: "static-rating"}) %>

                <% end %>

            <% end %>
        <% end %>
    <% end %>
<% end %>

Are this many 'nests' in a form typical or should I be doing something else?

I'm including part of a simple UML diagram with a focus on the "Rating" model that is attached to many things (there are lots of things in the app that can be rated):

Most of the lines going up out of the screen connect either to unimportant models or Active Record directly.  The only pertinent thing that is not pictured is the fact that Rating rates Users (a user model that someone would typically expect).

This view knows far too much about your data model structure.

One level of nesting is reasonably acceptable, but this many is dangerous : in fact, this view needs knowledge about no less than 4 different business objects, not to mention it has to know the relations between them.

Solution 1 : the facade pattern

Abstract away all those details in another object, which would be the sole source of truth for your view : call it a form object, or a presenter, or a context in DCI idiom, whatever.

The idea is that this object has a simple interface that maps to the complex underlying system. We'd need more details on your business logic to be able to help you on this one.

Solution 2 : cook your own "accepts_nested_attributes" method

on your UserRelation model, create a ratings method that provides direct access to your ratings. Then create another method that allows assignment, like ratings_attributes=. In this method, process the passed parameters to create / update associated ratings ; you can find inspiration for this in the source for the accept_nested_attributes method.


Divide number by factors I'm learning F#.
The code below gets a number e.g. 100 and list of factors and should divide that number by the factors without any rest. (There is an actual code I've got in C#, but this is F# port).

I especially didn't liked equalsDifference function.. any better solution?

namespace RozbijaczApp
module Rozbijacz =
    let precision = 2

    let minUnit = 1m / (pown 10m precision)

    let round x = System.Math.Round(decimal x, precision, System.MidpointRounding.AwayFromZero)

    let mainMapper factor factorSum x =
        round (x * factor / factorSum)

    let equalsDifference minUnit (difference: decimal) (l: decimal list) =
        let listSize = List.length l
        let mutable acc = difference

        [for i in [0..listSize-1] do
            let element = l |> List.item i
            if acc <> 0m then
                if difference < 0m then
                    if element >= minUnit then
                        acc <- acc + minUnit
                        yield element - minUnit
                    else
                        yield element
                else
                    acc <- acc - minUnit
                    yield element + minUnit
            else
                yield element
        ]

    let divider (number:decimal) factors =
        let factorsSum = factors |> List.sum
        let result = factors |> List.map (fun x -> mainMapper number factorsSum x)
        let controlSum = result |> List.sum
        let difference = number - controlSum
        printfn "Difference %O" difference
        // add or substract diffenernce by minUnit for results
        let fixResult = equalsDifference minUnit difference result
        let finalControlSum = fixResult |> List.sum
        let finalDifference = number - finalControlSum
        printfn "Final difference %O should by zero"finalDifference

        fixResult

and usage:

        let factors = [0.2m;0.3m;0.4m]
        let results = Rozbijacz.divider 100m factors
        printfn "Result: %A" results

ok, as you suggested map is better:

let equalsDifference minUnit (difference: decimal) (l: decimal list) =
    let listSize = List.length l
    let mutable acc = difference

    let resp = l |> List.map (fun element -> (
        if acc <> 0m then
            if difference < 0m then
                if element >= minUnit then
                    acc <- acc + minUnit
                    element - minUnit
                else
                    element
            else
                acc <- acc - minUnit
                element + minUnit
        else
            element
        ) )
    resp

But is this enough? Any F# magic?

Instead of using mutable variables, it is possible to apply the fold:

let equalsDifference minUnit difference l =
    l
    |> List.fold
        (fun (acc,xs) element ->
               if acc <> 0m then
                  if difference < 0m then
                     if element >= minUnit then
                         acc + minUnit, (element - minUnit)::xs
                     else
                         acc, element::xs
                  else
                     acc - minUnit, (element + minUnit)::xs
               else
                  acc, element::xs)
        (difference, [])
    |> snd
    |> List.rev


Number of unique substrings of particular length of a binary string Question: A binary string is given with only 0's and 1's. A number n is also given as the length of a sub string to be considered. It is to find the number of unique substrings. Here, n=3.

My algorithm: The ways I followed:
(i) First, I extracted out the sub string of length 3 and converted it into a number.
(ii) Then, I stored the number in a new integer type array. In this way, I had an integer array full of numbers representing the substrings.
(iii) Lastly, I traversed down the array, keeping track of the occurrence of the unique numbers only. The amount of unique numbers therefore correspond to the number of unique substring.

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

int main(void)
{
    char arr[50];
    int o[50],check[10000];
    int i,j,count=1,l,k=0,sum,p;

    l=strlen(arr);

    for(i=0;i<l-2;i++){
        p=4;sum=0;
        for(j=0;j<3;j++){
            sum+=(arr[i+j]-'0')*p;
            p/=2;
        }
        o[k++]=sum;
    }

    memset(check,0,sizeof(check));

    for(i=0;i<k-1;i++){
        for(j=i+1;j<k;j++){
            if(o[i]!=o[j] && check[o[i]]!=1 && check[o[j]]!=1){
                count++;
                check[o[j]]=1;
            }
        }
        check[o[i]]=1;
    }

    printf("\n%d",count);

    return 0;
}

I think that my code is quite long and it could be shortened with a good optimization. But I can't think of a way.

Your code can be more efficient.  For example, both nested for-loops can be replaced with single for-loops.  In the first loop, the next sum can be calculated by left-shifting the previous sum, adding the new bit, and masking off n-bits.  count[sum] is how many times an n-bit pattern == sum has been seen.  So the second loop merely counts how many '1's are in count.  Something like the code below (not tested).

int count_unique(char *arr, int n) {
    int mask = (1 << n) - 1;

    /* the size needs to be 2**n.  This works for n <= 10 */
    int count[1024];
    memset(count, 0, sizeof(count));

    int sum = 0;

    for (int i = 0; arr[i]; i++) {
        sum = ((sum << 1) | (arr[i] - '0')) & mask;

        if (i >= n - 1) {
            count[sum]++;
        }
    }

    int unique = 0;

    for (int i = 0; i < sizeof(count)/sizeof(int); i++) {
        if (count[i] == 1) {
           unique++;
        }
    }

    return unique;
}


Simple hashing algorithm TL;DR: The algorithm receives a string as input, allocate another string to be the final digest, and start working on them. For each char on the digest (a null character on a first moment), it XORs it with every character from the original string, also XORing it with a set of "random bytes" that are specified in the beginning of the code.

Here are some results:

  "000" = qpktluvsqpktluvs; "001" = bcygoiwnccxfohxn;

  "abc" = ayedeufryzdfftds; "cba" = cqgleoxlarrnfnvm;

  "aaaaa" = hingixcphingixcp; "aabaa" = aprndovlapgneovk;

Am I mathematically getting the full potential of the performance I'm using? How good would you say it is compared to other hashing algorithms? Thanks a lot for reading!
This is my first hashing algorithm. My goal is to be simple and performatic. How can I improve it?

#define HASH_LENGTH 16
char *hash(char *input){
    // Alphabet and length
    const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    const int alphabetLen = sizeof(alphabet)/sizeof(char) - 1;

    // Randomization variables and length
    const char vars[] = {
        0xA6,
        0xC1,
        0x5E,
        0x31,
        0xF5,
        0x88,
        0xA1,
        0xE2
    };
    const int varsLen = sizeof(vars)/sizeof(char);

    // Digest (where the hash is made)
    char *digest = (char*)malloc(sizeof(char) * (HASH_LENGTH + 1));

    // Input length calculation
    int inputLen = 0;
    while(input[inputLen] != '\0') inputLen++;

    // Digest cleaning
    int i;
    for(i = 0; i < HASH_LENGTH; i++){
        digest[i] = 0;
    }

    // Hashing process
    int j;
    for(i = 0; i < HASH_LENGTH; i++){
        // XORs digest[i] with vars[input[j]]
        for(j = 0; j < HASH_LENGTH; j++){
            digest[i] ^= vars[input[j % inputLen] % varsLen];
        }
        // XORs digest[i] with input[i] + vars[i]
        digest[i] ^= input[i % inputLen] + vars[i % varsLen];
    }

    // Translates digest to desired alphabet
    for(i = 0; i < HASH_LENGTH; i++){
        j = digest[i] > 0 ? 1 : -1;
        digest[i] = alphabet[digest[i] * j % alphabetLen];
    }
    // Finalizes digest string
    *(digest + HASH_LENGTH) = '\0';

    return digest;
}

This is how the function is called:

printf("%s", hash("foo"));

I'm not particularly familiar with C, but I have a few observations that may be helpful.

I like the attention to zeroing out your digest before you start. Using uninitialised memory is the sort of bug that can go unnoticed for a while, and it's good that you've caught it.

At the same time, I'm slightly alarmed that you're doing everything with raw loops, instead of using standard library functionality that does the same job. For example your loop to find inputLen could be replaced by a call to something like strlen and your loop to zero the array with a call to memset. As well as generally being more confident that you're using a tested and optimised routine, using library functions makes it easier to read and reason about your code.

I also quite like your use of comments. They're well placed, complementing the code and explaining some of the whys where the code explains the hows.

As for the hashing itself, I'm sure that the output looks fairly random, but it's actually doing a lot of work for the level of hashing that it supplies.

My top concerns:

If the input is longer than HASH_LENGTH, the latter part of the input is completely ignored.
XOR is a standard building block for this sort of low level stuff, but one of the key properties of XOR is that it undoes its own work. That is to say, because your for loop with j is only doing XOR it will confuse rather less than you'd expect for the work that goes into a nested loop.
The space allocated to digest at the end is underused. For example, because it's restricted to that alphabet, the first three bits of every byte will be "011". That has implications for use with, say, hash maps because the hash map will allocate 87.5% of its slots to values this hash function can never fill for any possible input.


Memory allocation for linked list in C I am new to C and am writing a basic program to calculate the arithmetic sum of two numbers stored in a linked list.

My main question is idiomatic memory management in C. The program below allocates a new linked list node, but does not deallocate it. What is a good way to do so?

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

typedef struct SinglyLinkedListInt {
  int value;
  struct SinglyLinkedListInt *next;
} SinglyLinkedListInt;

SinglyLinkedListInt *add_two_numbers(SinglyLinkedListInt *l1, SinglyLinkedListInt *l2) {
  SinglyLinkedListInt root = { .value = 0, .next = NULL };
  SinglyLinkedListInt *current = &root;

  int carry = 0;
  while (l1 || l2 || carry) {
    int a = l1 ? l1->value : 0;
    int b = l2 ? l2->value : 0;
    int value = carry + a + b;

    SinglyLinkedListInt *next = malloc(sizeof(SinglyLinkedListInt));
    next->value = value % 10;
    next->next = NULL;
    current->next = next;

    carry = value / 10;
    l1 = l1 ? l1->next : NULL;
    l2 = l2 ? l2->next : NULL;
    current = current->next;
  }

  return root.next;
}

int main() {
  SinglyLinkedListInt l13 = { .value = 3, .next = NULL };
  SinglyLinkedListInt l12 = { .value = 4, .next = &l13 };
  SinglyLinkedListInt l11 = { .value = 2, .next = &l12 };

  SinglyLinkedListInt l23 = { .value = 4, .next = NULL };
  SinglyLinkedListInt l22 = { .value = 6, .next = &l23 };
  SinglyLinkedListInt l21 = { .value = 5, .next = &l22 };

  SinglyLinkedListInt *result = add_two_numbers(&l11, &l21);

  while (result) {
    printf("%d ", result->value);
    result = result->next;
  }
  printf("\n");

  return 0;
}

I think you're on the right track with this, but that there are some improvements you could make.
A Better Abstraction
The way you have it now, a user of this linked list type has to do a bunch of work to create and maintain the list. You could make it a lot easier on a user to define a list type separate from the node type. Something like this:
typedef struct IntNode {
    int value;
    struct IntNode *next;
} IntNode;

and
typedef struct IntList {
    IntNode *head;
    IntNode *tail;
} IntList;

What this allows you to do is quickly insert at the head and tail, which are 2 common operations. It also means that a user of this type doesn't have to make all the links between the nodes manually.
You could add a function to create a new empty list, a function to insert an int into the list at the tail, and another to remove an int from the list. Once you have the creation and insertion functions, you don't need to put memory allocation code into the add() function. You would simply create the list at the start of the add() function, then as you go through the 2 input lists, generate the new int containing the sum, and insert it into the list. It might look something like this:
SinglyLinkedListInt *add_two_numbers(SinglyLinkedListInt *l1, SinglyLinkedListInt *l2) {
  SinglyLinkedListInt *result = create_new_list();
  if (result == NULL)
  {
    return NULL;
  }

  int carry = 0;
  while (l1 || l2 || carry) {
    int a = l1 ? l1->value : 0;
    int b = l2 ? l2->value : 0;
    int value = carry + a + b;

    append(result, value % 10);

    carry = value / 10;
    l1 = l1 ? l1->next : NULL;
    l2 = l2 ? l2->next : NULL;
  }

  return result;
}

Here you'd write the create_new_list() function and the append() function that would add the new value to the end of the list. Now you don't have allocation code in a math function, and you don't need to keep track of the current node and keep incrementing it. (As pointed out by @chux, you will need some way to tell whether append() successfully allocated memory or not. I would probably have it return a boolean indicating success or failure and make sure to check it after calling.)
Memory Management
You are correct that not calling free() on something that you've created with malloc() is a problem. In the code you currently have, you should be freeing result and every node in the list after you're done using them. Note that that's one more thing a user of this code has to keep track of: some lists are created on the stack and some are created on the heap, and it's even possible that some nodes in the same list could be created in different places and need to be handled differently for freeing them.
If they were always created on the heap, it would simplify using the type by having a free_list() function that did it for you. If you used my above suggestion about creating a separate IntList type, it might look something like this:
void free_list(IntList *list)
{
    if (list == NULL)
    {
        return;
    }

    IntNode* current_node = list->head;
    IntNode* next_node = NULL;
    while (current_node != NULL)
    {
        next_node = current_node->next;
        free(current_node);
        current_node = next_node;
    }
    list->head = NULL;
    list->tail = NULL;
    free(list);
}

Then your call sequence becomes:
IntList* list = create_new_list();
// ... Add some nodes
list->append(...);
list->append(...);
//... do whatever else with the list
free_list(list);


Does this tkinter-based web browser widget use a well implemented class? I have fully functional code in class format, and as far as I am aware from my previous question, it conforms to PEP 8 and the code logic and implementation is suitably pythonic. My main concerns here is whether or not I have put self. in front of the correct variables, and some ambiguity surrounding my @staticmethod.

Should I leave it as it is?
Should I change the logic so it is not static?
Should it be in the class at all?

# This imports some necessary libraries.
import webbrowser
import tempfile
import urllib.request
from tkinter import *

class Browser:
    """This creates a relay that allows a user to directly view data sent from a web server."""
    def __init__(self, master):
        """Sets up a browsing session."""
        # Explicit global declarations are used to allow certain variable to be used in all methods.
        global e1

        # Here we create some temporary settings that allow us to create a client that ignores proxy settings.
        self.proxy_handler = urllib.request.ProxyHandler(proxies=None)
        self.opener = urllib.request.build_opener(self.proxy_handler)

        # This sets up components for the GUI.
        Label(master, text='Full Path').grid(row=0)
        e1 = Entry(master)
        e1.grid(row=0, column=1)
        Button(master, text='Go', command=self.browse).grid(row=0, column=2)

        # This binds the return key to self.browse as an alternative to clicking the button.
        root.bind('<Return>', self.browse)

    @staticmethod
    def parsed(data):
        """Cleans up the data so the file can be easily processed by the browser."""
        # This removes removes all python-added special characters such as b'' and '\\n' to create understandable HTML.
        initial = str(data)[2:-1]
        lines = initial.split('\\n')
        return lines

    def navigate(self, query):
        """Gets raw data from the queried server, ready to be processed."""
        # This gets the opener to query our request, and submit the response to be parsed.
        response = self.opener.open(query)
        html = response.read()
        return html

    def browse(self):
        """Wraps all functionality together for data reading and writing."""
        # This inputs and outputs the necessary website data from user-specified parameters.
        raw_data = self.navigate(e1.get())
        clean_data = self.parsed(raw_data)

        # This creates a temporary file in which we store our HTML data, and open it in the default browser.
        with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as cache:
            cache.writelines(line.encode('UTF-8') for line in clean_data)
            webbrowser.open_new_tab(cache.name)

# Creates a Tk() window that is always in front of all other windows.
root = Tk()
root.wm_attributes('-topmost', 1)

# Starts the program by initializing the Browser object and main-looping the Tk() window.
anon = Browser(root)
root.mainloop()

Class Scoping

So your comment afore your global declaration of e1 mentions how you wish for e1 to be accessible in all methods. If you want a variable to be accessible in all methods of a class, the conventional way is to assign it as a property of self:

class Foo():
     def __init__(self, bar):
         self.boz = bar * 3

     def baz(self):
         # boz is now accessible here
         print(self.boz)

Note that boz is not a global; if I create two Foo() objects, I'll end up with 2 different boz variables:

>>> f1 = Foo(3)
>>> f1.boz
9
>>> f2 = Foo(2)
>>> f2.boz
6
>>> f1.boz
9 # Still

Static Methods

To answer your (most conceptual) questions about the static method:

Potentially
The function takes some data, and then performs an operation on it. It does not rely on any other state to decide what operation to perform, so it is a perfect candidate for being static.
No, it does not need to be static; a static method is (conceptually) a function in all but name, so you could write it as a function. The main reasons to have something be a static variable is usually organizational or conceptual, so if you think that applies here, keep it as a staticmethod. Otherwise, consider making it a bog standard function.

There is no definite rule for when to write a function and when to write a static method; it's something you learn over time. The two questions I ask myself when deciding to write a static method are "Could I write this as a function?" and "Is this code very tightly linked (conceptually) to the class?". If the answer to both of those questions is yes, then I might write it as a static method.

In this case, I think a function might be more useful.

General bugs

Just some little things I noticed:

Your parsed static method says that it removes cruft from a string, but it never checks to see if the characters it expects to be there actually exist. Personally, I would use a regexp to implement this function, but regardless, it might be wise to check that the characters you are deleting are the ones you expect to be there.
In __init__ you do root.bind(...), where you could do master.bind(...), which might be better, as it would avoid using a global variable.
I'd recommend using a new style class by replacing class Browser: with class Browser(object):. The benefits of the syntax difference are subtle, but noticeable (and it helps with forward compatibility iirc).
It might be a better idea to define a main function, and then call that instead of just doing loads of stuff in the global scope. You could also add a guard case of the form if __name__ == "__main__": main() to allow you to import the script into a REPL without running the code.
Some of your variable names kinda suck. Try and find more descriptive names than e1!


Is there anything wrong with this double ternary? Is there anything wrong with using double ternary operator like so:

var stateName:String = state is String ? state as String : "name" in state ? state.name : null;

Here is two lines because someone requested it:

var stateName:String = state is String ? state as String :
                        "name" in state ? state.name :
                            null;

Here is the alternative:

if (state is String) {
    stateName = state as String;
}
else if ("name" in state) {
    stateName = state.name;
}
else {
    stateName = null;
}

The function:

/**
 * Sets the style in the state specified. Creates state if it doesn't exist.
 * */
public static function setStyleInState(styleName:String, value:*, state:*, target:UIComponent = null):void {
    var stateName:String = state is String ? state as String : "name" in state ? state.name : null;

    if (!StateUtils.hasState(target, state)) {
        state = createState(stateName, null, target);
    }
    else if (!(state is State)) {
        state = getState(target, stateName);
    }

    // more code to write
}

It makes sense to me but I'm the one writing it.

This is ActionScript3 or ECMAScript 4 (basically JavaScript with strong typing).

Given your example I think that your double ternary operation should actually be a separate function. When you start getting complex one-liners like this, it is a sign that you need another function. Here's how I approached it:

function getStateName(state) {
  if(state is String) {
    return state as String;
  }

  // This will always return "null" if state.name does not exist.
  // I don't know about AS, but in JavaScript if something doesn't
  // exist it returns as undefined (not null), but you want the null
  // return. As far as I am aware, AS supports the || short-circuit and
  // truthy/falsey equivalence, like JavaScript.
  return state.name || null;
}

This could be used in your function like so;

public static function setStyleInState(styleName:String, value:*, state:*, target:UIComponent = null):void {
    var stateName:String = getStateName(state);

    if (!StateUtils.hasState(target, state)) {
        state = createState(stateName, null, target);
    }
    else if (!(state is State)) {
        state = getState(target, stateName);
    }
}

There's more to be said here; I think that exposing mutability like this on a static method (instead of on the instance of a state) is going to lead you into trouble later on down the road and you should probably re-evaluate your design.

Specifically, state in static methods is always a recipe for disaster when it comes to testability and debugging, especially when you branch into multiple threads.