texts:
I was given a task where given a string of '0's and '1's, return the longest substring where the count of '0's and '1's are equal. I was told also that the code should be O(n) and space O(1).

Below is what I came up with:

def max_equal_sub(s):
    '''
    I get the substrings by iterating over the starts and the ends for each start. For each
    of these, check if the counts are equal.
    '''
    return max((s[b:e] for b in range(len(s)) for e in range(b, len(s)) if s[b:e].count('1') == s[b:e].count('0')), key=len)

def main():
    TESTS = ('000', '1111', '001010101', '0001010101', '01010101', '000000111010101',
             '0000001110101011', '00000011101010111111111111111')

    for binstr in TESTS:
        print(max_equal_sub(binstr))

if __name__ == '__main__':
    main()

This code is all working fine, but I was told that this runs at O(n2), not O(n).

Following that I have some questions:

What makes it O(n2), and how can I make it so that it is O(n).
I was told that it needed to be 'space O(1)'. Does it run at that? What would make it run at space O(1) and why?
In the function max_equal_sub, would it be more efficient to put len(s) into a variable to avoid calling it again and again?
In the function max_equal_sub, I do s[b:e] three times. Surely there is a more efficient way?

(Optional, but favoured):

Are there any other things I could do to make it faster?
You could make it PEP8-compliant along the way if you wish.
Any other recommendations, perhaps regarding program logic.


texts: Sorting strings by length - functional Python

texts:
I'm trying to port this little F# snippet while staying pythonic:

["something"; "something else"; "blah"; "a string"] |> List.map (fun p -> p, p.Length) |> List.sortBy snd

In case you don't speak F#, it gets the length of each string, then sorts by length.

Output:

[("blah", 4); ("a string", 8); ("something", 9); ("something else", 14)]

In Python, this is the best I could do so far:

sorted([(p, len(p)) for p in ["something", "something else", "blah", "a string"]], key=lambda a:a[1])

While correct, this doesn't look very elegant to me, or maybe it's just my non-pythonic eye.

Is this pythonic code? How would you write it? Maybe an imperative style is more appropriate?


texts:
This is my bare-bones Brainfuck interpreter in C using lots of unixisms. What improvements can I make (with respect to the clarity of code, or obvious features to add)?

#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

void error(char *msg) {
    fprintf(stderr, "Error: %s\n", msg);
}

enum { MEMSIZE = 30000 };

//unsigned char *mem;
unsigned char mem[MEMSIZE];
unsigned char *ptr;
unsigned char *prog;
size_t progsize;

int init(char *progname) {
    int f,r;
    struct stat fs;
    ptr = mem;// = calloc(MEMSIZE, 1);
    f = open(progname, O_RDONLY);
    assert(f != -1);
    r = fstat(f, &fs);
    assert(r == 0);
    prog = mmap(NULL, progsize = fs.st_size, PROT_READ, MAP_PRIVATE, f, 0);
    assert(prog != NULL);
    return 0;
}

/* As requested, a little more commentary on this, admittedly bizarre, function.
findmatch receives the current instruction-pointer and a bracket character
for which the "match" is desired. It returns a new instruction-pointer.
*/
int findmatch(int ip, char src){
    char *q, *p="[]";
    int i, defer, dir[]= { 1, -1 };
    i = strchr(p,src)-p;  // at this point, if(src=='[') i=0; else if(src==']') i=1;
    ip+=dir[i];           // ie. if(src=='[') ++ip else if(src==']') --ip
                          // so dir[i] tells us which direction we're going
    // next, we reuse the same idiom to check each character as we scan.
    // defer counts up or down as we encounter [ and ] and finally reaches 0
    // when the match is found.
    for (defer=dir[i]; defer!=0; ip+=dir[i]) {
        if (ip<0||ip>=progsize) error("mismatch");   // check exceeded bounds
        if (q = strchr(p,prog[ip])) {   // if the char is a bracket
            int j = q-p;                // j is 0 or 1
            defer+=dir[j];              // adjust the 'defer' level
        }
    }
    return ip - dir[i];  // return new ip value (one past the matched bracket)
}

int run() {
    int ip;
    for(ip = 0; ip>=0 && ip<progsize; ip++)
        switch(prog[ip]){
        case '>': ++ptr; break;
        case '<': --ptr; break;
        case '+': ++*ptr; break;
        case '-': --*ptr; break;
        case '.': putchar(*ptr); break;
        case ',': *ptr=getchar(); break;
        case '[': /*while(*ptr){*/
                  if (!*ptr)
                      ip=findmatch(ip,'[')-1; // modified because run does ip++
                  break;
        case ']': /*}*/
                  if (*ptr)
                      ip=findmatch(ip,']')-1;
                  break;
        }

    return 0;
}

int cleanup() {
    //free(mem);
    ptr = NULL;
    return 0;
}

int main(int argc, char *argv[]) {
    init(argc > 1? argv[1]: NULL);
    run();
    cleanup();
    return 0;
}


texts:
You can perform the following operation on some string a:

  Capitalize zero or more of a's lowercase letters at some index i (i.e., make them uppercase).
  Delete all of the remaining lowercase letters in a.

  Given string a, print YES if it can be transformed to string
  b.

  String a has only capital and small letter alphabets.

  String b has only capital letters.

  THIS is the link
  to the problem.

  Example:

  a: daBcd

  b: ABC

  OUTPUT: YES

This passed all the test-cases. But I wanted to know if any further optimizations can be made or not. Maybe I am using redundant conditions or something like this.

 //n is the length of the string a
 //m is the length of the string b
 public static void func(char[] a,int n, char[] b, int m)
    {
        int[][] mat = new int[n + 1][m + 1];
        for(int i = 0 ; i < n + 1 ; i++)
            mat[i][0] = 0;
        for(int i = 0 ; i < m + 1 ; i++)
            mat[0][i] = 0;
        char capStart = 65;
        char capEnd = 90;
        char smallStart = 97;
        char smallEnd = 122;
        char diff = 32;
        for(int i = 1 ; i < n + 1 ; i++)
        {
            for(int j = 1 ; j < m + 1 ; j++)
            {
                if(a[i - 1] >= smallStart)
                {
                    if(a[i - 1] - diff == b[j - 1])
                    {
                        if(mat[i - 1][j] == j)
                            mat[i][j] = mat[i - 1][j];
                        else
                            mat[i][j] = 1 + mat[i - 1][j - 1];
                    }
                    else
                    {
                        if(mat[i - 1][j] == j || mat[i][j - 1] == j)
                            mat[i][j] = j;
                        else
                            mat[i][j] = Math.max(mat[i - 1][j],mat[i][j - 1]);
                    }
                }
                else
                {
                    if(a[i - 1] == b[j - 1])
                    {
                        mat[i][j] = 1 + mat[i - 1][j - 1];
                    }
                    else
                    {
                        mat[i][j] = mat[i][j - 1];
                    }
                }
            }
        }
        if(mat[n][m] == m)
            System.out.println("YES");
        else
            System.out.println("NO");
    }

If you want, you can check your solution for 1 of the sample inputs:

Input format:

First line contains an integer q showing the number of pairs of a and b. Next 2q lines for a and b.

10
Pi
P
AfPZN
APZNC
LDJAN
LJJM
UMKFW
UMKFW
KXzQ
K
LIT
LIT
QYCH
QYCH
DFIQG
DFIQG
sYOCa
YOCN
JHMWY
HUVPW

Output:

YES
NO
NO
YES
NO
YES
YES
YES
NO
NO


texts: JavaScript - Comparing 2 arrays - Would like to check if I'm reinventing the wheel or am I good to go?

texts:
I would like to be able to use it with IE8 or earlier, so I'm staying away from newer array methods. I'm not an expert so my code may not be the most efficient choice, but it works.

var data = [
["John", 2],
["Jenny", 3],
["John", 4],
["Beavis", 5]]

var newarr = [["John",5]];

for (var x=0; x < data.length; x++) {

    for (var y=0; y < newarr.length+1; y++) {
        if (typeof newarr[y] !== 'undefined') {
            if (newarr[y][0] == data[x][0]) {
                newarr[y][1] = (newarr[y][1] + data[x][1]);
                break;
            }
        }
        else {
            newarr.push([data[x][0]]);
            newarr[y][1] = data[x][1];
            break;
        }
    }

}

alert("newarr is: " + newarr);

//if elements are similar, merge them.

Would like to find out if this is a decent way of doing it, or maybe there are other easier/less code ways of doing it. Maybe somebody sees an issue with this code that I do not. Thanks.


texts: Picking the top 5 results for each individual

texts:
For loops are the devil. I can't see a way to speed this up with apply or other more speedy functions though...

pred <- read.csv("predictions_from_external_multinomial_model.csv")

pred$id <- test_users$user_id

pred$first   <- "a"
pred$second  <- "b"
pred$third   <- "c"
pred$fourth  <- "d"
pred$fifth   <- "e"

for(i in 1:nrow(pred)){
  pred$first[i]   <- names(pred[which(pred[i,] == max(pred[i,2:13]))])
  pred[i,names(pred[which(pred[i,] == max(pred[i,2:13]))])] <- 0

  pred$second[i]  <- names(pred[which(pred[i,] == max(pred[i,2:13]))])
  pred[i,names(pred[which(pred[i,] == max(pred[i,2:13]))])] <- 0

  pred$third[i]   <- names(pred[which(pred[i,] == max(pred[i,2:13]))])
  pred[i,names(pred[which(pred[i,] == max(pred[i,2:13]))])] <- 0

  pred$fourth[i]   <- names(pred[which(pred[i,] == max(pred[i,2:13]))])
  pred[i,names(pred[which(pred[i,] == max(pred[i,2:13]))])] <- 0

  pred$fifth[i]   <- names(pred[which(pred[i,] == max(pred[i,2:13]))])
  pred[i,names(pred[which(pred[i,] == max(pred[i,2:13]))])] <- 0
}

data_long <- melt(pred, id.vars=("id"), measure.vars = c("first", "second", "third", "fourth", "fifth"), value.name = "country")
data_long <- data_long[order(data_long$id),]
data_long$variable <- NULL

What it's doing is picking the top 5 results for each individual, based on the column value of 12 columns in the original prediction dataset.

In the imported csv file each row is a unique individual and each possible prediction class in in a column indexed from 2 to 13.

Here's an example dataset in case you wish to reproduce it (you can use line numbers or an arbitrary sequence in place of test_users$user_id in the code above):

http://wikisend.com/download/535006/2023bd19b880.csv


texts:
I've written a simple python web scraper that parses text from an html table and stores the scraped data in List of dictionaries. The code works and doesn't seem to have any glaring issues performance-wise, but I only used the bare bones modules of lxml and requests.

Is there a more efficient/elegant way to condense the script or to improve the runtime?

The code is below:

import requests
from lxml.html import fromstring
import pprint
import re

url = "https://jobs.mo.gov/content/missouri-warn-notices-py-2017"
response = requests.get(url)
root = fromstring(response.content)

table = root.xpath('.//*[@summary="Missouri WARN Notices PY 2016"]')[0]
tableRes = []
columnHeaders = table.xpath(".//tr//th/span/text()")

for row in table.xpath(".//tr")[1:]:
    i = 0
    rowDict = {}
    for col in row.xpath(".//td"):
        if i != 1:
            rowDict[columnHeaders[i]] = re.sub(r"[\n\t]*", "","".join(col.xpath(".//text()")).replace(u'\xa0', u' '))
        else:
            rowDict[columnHeaders[i]] = re.sub(r"[\n\t]*", "","".join(col.xpath(".//a/text()")).replace(u'\xa0', u' '))
        i += 1
    tableRes.append(rowDict)

pp = pprint.PrettyPrinter(indent=4)
pp.pprint(tableRes)


texts:
I've decided to implement a simple case of the Observer pattern. I've gone about this considering you can only register 1 single observer in the Observable, instead of allowing multiple ones.

I would really like feedback about what'd be the proper way to return the listener in the run method while still yielding values, if possible i'd like to allow some sort of method chaining

Overall I would like some criticism about this whole design and of course, anything else is on the table will be appreciated.

Code:

import time

class Observer:

    def __init__(self):
        self.lines = []
        self.execution_time = None

    def on_process(self, value):
        line = f"<< processed: {value} >>"
        self.lines.append(line)
        return line

    def on_done(self, value):
        self.execution_time = value

class Observable:

    def __init__(self):
        self.listener = None

    def register_listener(self, listener):
        self.listener = listener
        return self

    def run(self, iterable):
        s = time.time()
        for v in iterable:
            yield self.listener.on_process(v)

        self.listener.on_done(time.time() - s)

if __name__ == '__main__':
    obj = Observable().register_listener(Observer())

    for x in obj.run(range(10)):
        print(x)

    listener = obj.listener
    print("Number of lines:", len(listener.lines))
    print("Execution time:", listener.execution_time)


texts: Show one sheet for each field in pivot filter field

texts:
Into my workbook I've the db of inventory, in another sheet I've one pvt and in the filter field I put the filed "Card". Now I want create one sheet for each "Card" usually I use this code for this operation:

Sub cmdg2b2(control As IRibbonControl)  'genera una sheets per ogni card
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
    Sheets("pivot").Select
    ActiveSheet.Unprotect
    ActiveSheet.PivotTables("Pvt_Pck").ShowPages PageField:="Card"
    Sheets("pivot").Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
    Sheets("pivot").EnableSelection = xlNoSelection
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub

This function always runs right, but this year the sheets are much (175) and my code stopped for exceeded memory. I think to hide half off the total sheets, if I hide the sheets manually with pvt filer the operation run in a couple of minutes, if I use this code I need 9 minutes.

Can somebody help me to improve the performance my code?

Function ShowSheets(ByVal conta As String)  'card serves to define whether to show the first half of the sheets or the second
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim tsheet As Integer
Dim tstart As Date, tend As Date, tteempo As Date
tstart = Now()
    ActiveSheet.PivotTables("Pvt_Pck").PivotFields("Card").CurrentPage = "(All)"
    With ActiveSheet.PivotTables("Pvt_Pck").PivotFields("Card")
    tsheet = Int(.PivotItems.Count / 2)
    Select Case conta
    Case "A"
        For i = 1 To tsheet
            .PivotItems(i).Visible = False
        Next i
    Case "B"
        For i = tsheet + 1 To .PivotItems.Count - 1
            .PivotItems(i).Visible = False
        Next i
    End Select
    End With
    Range("A4").Select
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
tend = Now()
ttempo = tend - tstart
Debug.Print ttempo
End Function


texts:
I have seen programs to solve sudoku puzzles but to be honest.. They were badly written.
First of all, readability of the program itself was horrible and the code was really long and confusing.

So I decided to start from scratch, using my own style to write really good solver.
What I have this far is reading a board input from the user and outputting the board representation:

#include <stdio.h>
#include <ctype.h>
#include <iso646.h>
#include <conio.h>
#include <windows.h>

#define FOREGROUND_LBLUE 9
#define COLORSET_MAIN 3

char sudoku [9][9];

int chrton (unsigned char chr)
{
    if(chr >= '0' && chr <= '9')    { return chr - '0'; }
    else                            { return 0;         }
}

int main()
{
    char num = 0;
    char x = 0, y = 0;

    SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_LBLUE | BACKGROUND_BLUE);
    printf("Validate numbers:\t\t\t\t\n\n");
    SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE), COLORSET_MAIN);

    // Part 1 : validating hint numbers
    while(y != 9)
    {
        if(kbhit() && isdigit(num = _getch()))
        {
            printf("%c"" ", num);

            sudoku[x][y] = chrton(num);

            if( ++x == 9 )                  { putchar('\n'); x = 0; y++; }
            if( not((x * x) % 3) and x)     { putchar('\t');             }
            if( not((y * y) % 3) and !x)    { putchar('\n');             }
        }
    }
    system("PAUSE");

    return 1;
}

Obviously it is written for Windows compatibility but I use it as for advantage to exploit some rules of commonly-accepted IO.


texts:
I have started to learn Java for the past 20 days with no prior coding/comp science experience.

My brother gave me an idea to make a subnet calc/ping tool to enhance my knowledge and mentored through this.

Just wanted to know how can I upgrade this code and if I have used proper language idioms in this code. Any ideas to simplify/features for more learning would be appreciated.

import java.util.*;
import java.util.regex.Pattern;
import java.math.*;
import java.text.NumberFormat;
import java.text.ParseException;
import java.net.*;

public class example {

    public static void main(String[] args) {
        Scanner Scan = new Scanner(System.in);
        System.out.print("Enter IP: ");
        String IP;
        IP = Scan.nextLine();
        String Z = IP.split("\\/")[1];
        String Y = IP.split("\\/")[0];
        String[] parts = Y.split("\\.");
        String F1 = parts[0];
        String F2 = parts[1];
        String F3 = parts[2];
        String F4 = parts[3];
        int A = Integer.parseInt(F1);
        int B = Integer.parseInt(F2);
        int C = Integer.parseInt(F3);
        int E = Integer.parseInt(F4);

        {
            System.out.println(F1 + "." + F2 + "." + F3 + "." + F4);
        }
        String X = (IP.substring(IP.lastIndexOf("/") + 1)); {
            System.out.println(X);
        }
        int S = Integer.parseInt(X);
        double Bits = 32;
        double TotalBites = Bits - S;
        double I = Math.pow(2, TotalBites);
        int D = (int)(I - 2); {
            System.out.println(D);
        }

        List < String > Hosts = new ArrayList < String > ();

        if (S >= 24) {
            int val = (int) TotalBites - 0;
            String bitsda = stringMultiply("0", val);
            String bitstoconvert = "1" + bitsda;
            int decimal = Integer.parseInt(bitstoconvert, 2) - 1;
            //String bits = Strings.repeat("0", val);

            for (int IPF4 = E; IPF4 <= decimal; IPF4++) {

                Hosts.add(F1 + "." + F2 + "." + F3 + "." + IPF4);
            }

        } else

        if (S >= 16) {

            int val = (int) TotalBites - 8;
            String bitsda = stringMultiply("0", val);
            String bitstoconvert = "1" + bitsda;
            int decimal = Integer.parseInt(bitstoconvert, 2) - 1;
            //String bits = Strings.repeat("0", val);
            for (int IPF3 = C; IPF3 <= decimal; IPF3++) {
                for (int IPF4 = E; IPF4 <= 255; IPF4++)
                    Hosts.add(F1 + "." + F2 + "." + IPF3 + "." + IPF4);

            }

        } else

        if (S >= 8) {

            int val = (int) TotalBites - 16;
            String bitsda = stringMultiply("0", val);
            String bitstoconvert = "1" + bitsda;
            int decimal = Integer.parseInt(bitstoconvert, 2) - 1;
            //String bits = Strings.repeat("0", val);

            for (int IPF2 = B; IPF2 <= decimal; IPF2++) {
                for (int IPF3 = C; IPF3 <= 255; IPF3++)
                    for (int IPF4 = E; IPF4 <= 255; IPF4++)
                        Hosts.add(F1 + "." + IPF2 + "." + IPF3 + "." + IPF4);

            }
        }

        Hosts.forEach(host -> pingIt(host));

    }

    public static void pingIt(String host) {
        try {
            String ipAddress = host;
            InetAddress inet = InetAddress.getByName(ipAddress);
            System.out.println("Sending Ping Request to " + ipAddress);
            if (inet.isReachable(5000)) {
                System.out.println(ipAddress + " is reachable.");
            } else {
                System.out.println(ipAddress + " NOT reachable.");
            }
        } catch (Exception e) {
            System.out.println("Exception:" + e.getMessage());
        }
    }

    public static String stringMultiply(String s, int n) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
            sb.append(s);
        }
        return sb.toString();
    }
}


texts: Padding with leading zeros or removing leading zeroes to make sure that array is at least given length

texts:
Please refrain from negative comments about the code being poor and inefficient and not idiomatic. I know that much, and that's why I'm here.

I need a function, that takes a byte array and length and returns a byte array.
The function need to do the following:

Drop any leading zeroes in the byte array
If the array length is shorter than passed length parameter, pad the array with leading zeroes up to the passed length

I'm not worried to much about efficiency (e.g. removing a zero only for adding it back later), although I don't mind improvements here, but what I'm really after is to make the code more javascript idiomatic. Can I use Array.map or Array.filter here, for example?

function normalize(byteArray, length) {
  var padding = 0;
  while(padding < byteArray.length && byteArray[padding] == 0) {
    padding++;
  }
  byteArray = byteArray.slice(padding);
  while(byteArray.length < length) {
    byteArray = [0].concat(byteArray);
  }
  return byteArray;
}

Context: the byte array passed to this function comes for a BigInteger value. BigInteger has toByteArray method that produces the array, that needs to be fixed up by the function in question. toByteArray method usually does not produce arrays longer than needed for underlying integer, but sometimes it adds an extra zero byte in front. From the integer perspecive it's all the same, but where the resulting array is going to be consumed (in the printing/formatting function) a certain length is expected, so that the data can be laid out properly. Thus, this function.


texts: Getting list of colours from image in lab format

texts:
I need to write a bit of code that will get a list of the RGB colours in an image and then translate them into a NumPy array of lab colours. I have managed to do this, but I would like to learn how I can do it more efficiently.

from skimage.color import rgb2lab
from skimage.io import imread
import numpy as np
from PIL import Image  # @UnresolvedImport

def get_histogram (img):

    #histogram = plt.hist(img.flatten(), bins=100, facecolor='green', alpha=0.75)
    w, h = img.size
    colours = img.getcolors(w*h)  #Returns a list [(pixel_count, (R, G, B))]
    num, colours_rgb = zip(*colours)
    r,g,b = zip(*colours_rgb)

    num_of_colours = len(r)
    w2,h2 = 1,num_of_colours
    data = np.zeros( (w2,h2,3), dtype=np.uint8)
    print(data.shape)
    data[0,:,0] = r
    data[0,:,1] = g
    data[0,:,2] = b
    print(data)
    colours_lab = rgb2lab(data)


texts:
import tornado.web
from selenium import webdriver
import sys
import psycopg2
from selenium.common.exceptions import NoSuchElementException

class LevelHandler(tornado.web.RequestHandler):
    def __init__(self, application, request, **kwargs):
        super().__init__(application, request, **kwargs)
        self.conn_string = "credentials_here"
        self.conn = psycopg2.connect(self.conn_string)
        self.cursor = self.conn.cursor()

    def get(self, word):
        driver = webdriver.PhantomJS(executable_path=r'bin/phantomjs')
        driver.get(url="http://dictionary.cambridge.org/dictionary/english/%s" % word)
        is_word_cached = self.check_cache(word)
        if is_word_cached:
            response = {'level': is_word_cached[0][0]}
        elif self.check_word_404(driver):
            response = {'level': "This word wasn't found"}
        else:
            try:
                level = driver.find_element_by_xpath(xpath="//span[@class='def-info']/span[contains(@title,'A1-C2')]")
                level = level.text
            except NoSuchElementException:
                level = "The word level isn't known"
            self.write_cache(word, level)
            response = {'level': level}

        self.write(response)

    def check_cache(self, word):
        self.cursor.execute("SELECT level FROM eng_level WHERE word = '{0}'".format(word))
        records = self.cursor.fetchall()
        return records

    def write_cache(self, word, level):
        self.cursor.execute("INSERT INTO eng_level (word, level) values (%s, %s)", (word, level,))
        self.cursor.execute("COMMIT")

    def check_word_404(self, driver):
        try:
            return driver.find_element_by_xpath(xpath="//h1[contains(text(),'404. Page not found.')]")
        except NoSuchElementException:
            return False

application = tornado.web.Application([
    (r"/([A-Za-z]+)", LevelHandler)
])

if __name__ == "__main__":
    application.listen(str(sys.argv[1]))
    tornado.ioloop.IOLoop.instance().start()

The idea is to fetch the word complexity from a dictionary. I use Selenium and XPath to do this, but once a word is fetched from the external HTML I store it in the database as a cache.

Questions:

Is everything asynchronous here?
I'm only 1.5 times faster: the average response from the external website is 4s and from Postgres cache 2.5s. Can I do better?


texts: Python 3.6+ function to ask for a multiple-choice answer

texts:
# Standard multi choice question template
def multiChoiceQuestion(options: list):
    while True:
        print("\nEnter the number of your choice - ")
        for x in range(len(options)):
            print(str((x + 1)) + ". " + options[x])
        print("\n")
        try:
            answer = int(input())
        except ValueError:
            print("Doesn't seem like a number! Try again!")
            continue
        if answer < 1 or answer > len(options):
            print("That option does not exist! Try again!")
            continue
        return answer

I created a template to ask a multi choice question in python. The loop will never reach it's end, since there is always a continue or a return statement. Is the while True condition appropriate for it?


texts:
I'm working on a compiler. During the final stage I will get a collection of Lines.

This is the method that takes the Lines and gives name to Labels that don't have it yet.

Lines can have Labels. When a Line doesn't have a Label, its Label property is set to null. Apart from this, Labels can be unnamed (Label.Name is null)

This is the method. It looks ugly and I'm using a nested method. Please, review it and try to improve it to be elegant. Performance isn't a requirment (at least, for now):

private static void GiveNameToUnnamedLabels(IEnumerable<Line> finalCode)
{
    int count = 0;

    void GiveName(Model.Label label)
    {
        label.Name = $"dyn_label{++count}";
    }

    var unnamed = finalCode.Where(x => x.Label != null && x.Label.Name == null).ToList();
    unnamed.ForEach(x => GiveName(x.Label));
}


texts: Multi-function memoizator and multi-type container

texts:
I'm trying to write a multiple functions memoizator, which I've talked about here. The main problem is creating a container containing different and heterogenous functions.

I found a working solution, but I don't know if it's safe, if there are limitations, if it's somehow inefficient or if there is a more elegant solution.

This is my solution:

template <typename ReturnType, typename... Args>
function<ReturnType(Args...)> memoize(function<ReturnType(Args...)> func)
{
    return ([=](Args... args) mutable {
        static map<tuple<Args...>, ReturnType> cache;
        tuple<Args...> t(args...);
        auto result = cache.insert(make_pair(t, ReturnType{}));
        if (result.second) {
            // insertion succeeded so the value wasn't cached already
            result.first->second = func(args...);
        }
        return result.first->second;
    });
}

struct MultiMemoizator
{
    map<string, boost::any> multiCache;
    template <typename ReturnType, typename... Args>
    void addFunction(string name, function < ReturnType(Args...)> func) {
        function < ReturnType(Args...)> cachedFunc = memoize(func);
        boost::any anyCachedFunc = cachedFunc;
        auto result = multiCache.insert(pair<string, boost::any>(name,anyCachedFunc));
        if (!result.second)
            cout << "ERROR: key " + name + " was already inserted" << endl;
    }
    template <typename ReturnType, typename... Args>
    ReturnType callFunction(string name, Args... args) {
        auto it = multiCache.find(name);
        if (it == multiCache.end())
            throw KeyNotFound(name);
        boost::any anyCachedFunc = it->second;
        function < ReturnType(Args...)> cachedFunc = boost::any_cast<function<ReturnType(Args...)>> (anyCachedFunc);
        return cachedFunc(args...);
    }
};

And this is a possible main:

int main()
{
    function<int(int)> intFun = [](int i) {return ++i; };
    function<string(string)> stringFun = [](string s) {
        return "Hello "+s;
    };
    MultiMemoizator mem;
    mem.addFunction("intFun",intFun);
    mem.addFunction("stringFun", stringFun);
    try
    {
        cout << mem.callFunction<int, int>("intFun", 1)<<endl;//print 2
        cout << mem.callFunction<string, string>("stringFun", " World!") << endl;//print Hello World!
        cout << mem.callFunction<string, string>("TrumpIsADickHead", " World!") << endl;//KeyNotFound thrown
    }
    catch (boost::bad_any_cast e)
    {
        cout << "Bad function calling: "<<e.what()<<endl;
        return 1;
    }
    catch (KeyNotFound e)
    {
        cout << e.what()<<endl;
        return 1;
    }
}


texts: Guessing game where the first player inputs a word and a hint and the second player tries to guess it

texts:
We have been given this project and I was wondering if someone could make my algorithm better using TASM and DOSBox.

This is what I have done so far:

ideal
model small
stack 10244
dataseg
msg1 db 'Enter Word: $'
msg2 db 'Enter Hint: $'
msg3 db 'Enter Guess(Press . to end guess)($'
wrnmsg db 'Wrong!$'
a3msg db 'Number of letters: $'
a4msg db 'First two letters: $'
a5msg db 'Last letter: $'
a6msg db 'Second to the last letter: $'
fail db ' Enter guess again($'
secret db 21 dup('')
hint db 101 dup('')
guess db 21 dup('')
endss db '): $'
win db 'That is correct! You win!$'
lose db 'Im sorry you lose$'
cnt dw 0
codeseg
PROC compare
mov bx, 0
mov di, 0

loop1:
    mov al, [secret+di]
    mov ah, [guess+di]

    cmp ah, al
    jne no
    cmp al, '$'
    je endi
no:
    mov bx, 1
endi:
    ret
ENDP

PROC main
mov ax, @data
mov ds, ax
mov es, ax

lea dx, [msg1]
mov ah, 9
int 21h

mov bx, 0
scan:
    mov ah, 1
    int 21h
    cmp al, '.'
    je com
    inc [cnt]
    mov [secret+bx], al
    inc bx
    jmp scan
com:
    mov [secret+bx], '$'

mov dx, 10
mov ah, 2
int 21h

lea dx, [msg2]
mov ah, 9
int 21h

lea dx, [hint]
mov ah, 10
int 21h

mov dx, 10
mov ah, 2
int 21h

lea dx, [msg3]
mov ah, 9
int 21h

lea dx, [hint]
mov ah, 9
int 21h

lea dx, [endss]
mov ah, 9
int 21h

mov cx, 0
loop2:
    inc cx
    mov bx, 0
    scan2:
        mov ah, 1
        int 21h
        cmp al, '.'
        je com2
        mov [guess+bx], al
        inc bx
        jmp scan2
    com2:
        mov [guess+bx], '$'

        mov dx, 10
        mov ah, 2
        int 21h

    call compare
    cmp bx, 0
    je right

    lea dx, [wrnmsg]
    mov ah, 9
    int 21h

    cmp cx, 3
    je three
    cmp cx, 4
    je four
    cmp cx, 5
    je five
    cmp cx, 6
    je six
    cmp cx, 7
    je fail

    man:

    mov dx, 10
    mov ah, 2
    int 21h

    lea dx, [fail]
    mov ah, 9
    int 21h

    lea dx, [hint]
    mov ah, 9
    int 21h

    lea dx, [endss]
    mov ah, 9
    int 21h

    jmp loop2

right:
    lea dx [win]
    mov ah, 9
    int 21h

    jmp end1

fail:
    lea dx, [lose]
    mov ah, 9
    int 21h

    jmp end1

three:
    lea dx, [a3msg]
    mov ah, 9
    int 21h

    lea dx, [cnt]
    mov ah, 2
    int 21h
    jmp man
four:
    lea dx, [a4msg]
    mov ah, 9
    int 21h

    mov di, 0
    mov si, 1
    mov dh, [secret+di]
    mov ah, 2
    int 21h
    mov dh, [secret+si]
    int 21h

    jmp man
five:
    lea dx, [a5msg]
    mov ah, 9
    int 21h

    mov di, [cnt]
    mov dl, [secret+di]
    mov ah, 2
    int 21h

    jmp man
six:
    lea dx, [a6msg]
    mov ah, 9
    int 21h

    mov di, [cnt]
    dec di
    mov ah, 2
    int 21h

    jmp man
end1:
    mov ah, 4ch
    int 21h
ENDP
END main

What was required of us was a program that will simulate a guessing game where the first player will input the word to be guessed by the second player including a hint such as what category and other description. (Description can have a maximum of 100 characters).

The second player will be given 6 chances to guess. If in the third try, the 2nd player still cannot guess the word, hints will be given for the succeeding unsuccessful guesses as cited below:

Third unsuccessful try – Number of letters will be displayed on screen
Fourth unsuccessful try – First two letters will be revealed
Fifth unsuccessful try – Last letter will be revealed
Sixth unsuccessful try- Second to the last letter will be revealed


texts: Find the number surrounded by square braces using regex

texts:
I need to remove all the numbers appearing inside square braces such as [9] , [2] , ....

This is my regex:

"(?:\[\d*\])"

Which is working fine.
But I am totally new to regex so let me know if is there a better regex that can be used.

Try Online


texts:
Sometimes I need to write a simple Java console applications and menu look:

do {
    System.out.println("please select menu item");
    System.out.println("1-create, 2-remove, 3 - rename");
    int select;
    Scanner scanner = new Scanner(System.in);
    select = scanner.nextInt();

    switch (select) {
        case 1:
            System.out.println("please select menu item");
            System.out.println("1-image, 2-txt");
            select = scanner.nextInt();
            if (select == 1) fileHolder.create("image");
            else if (select == 2) fileHolder.create("image");
            else System.out.println("invalid menu item");
            break;
        case 2:
            System.out.println("please select menu item");
            System.out.println("1-file from pc1, 2-file from pc2, 3-file from pc3");
            select = scanner.nextInt();
            if (select == 1) fileHolder.removeFile("pc1");
            else if (select == 2) fileHolder.removeFile("pc2");
            else if (select == 3) fileHolder.removeFile("pc3");
            else System.out.println("invalid menu item");
            break;
        case 3:
            System.out.println("please type new name");
            String newName = scanner.next();
            fileHolder.rename(newName);
            break;
    }

} while (select != 4);

But I believe that it is not the best choice. I believe that I should use any pattern to improve my code. By description - the state pattern is applicable for my situation but I have no idea how I can use this in this situation. The menu should show the respective menu according to the internal state.


texts:
I have the following function defined in a program that implements the 2048 game. I tried condensing the repeating part of the code into one loop containing +1 offset variables for the indices, which are either set to 0 or 1 depending on the direction passed into the function, but the outer and inner loop variables swap depending on the direction. Could anyone give me some pointers as to how to condense this code and make it more clean, pythonic and terse?

def merge(direction):
    #if adjacent cells are equal, they are merged into one with twice the value and then moved.
    if direction == "up":
        for col in range(nColumns):
            for row in range(nRows-1):
                if grid[row][col] == grid[row+1][col]:
                    grid[row][col] = grid[row+1][col]*2
                    grid[row+1][col] = 0
                    move(direction)

    if direction == "down":
        for col in range(nColumns):
            for row in range(nRows-1):
                if grid[row][col] == grid[row+1][col]:
                    grid[row+1][col] = grid[row][col]*2
                    grid[row][col] = 0
                    move(direction)

    if direction == "left":
        for row in range(nRows):
            for col in range(nColumns-1):
                if grid[row][col] == grid[row][col+1]:
                    grid[row][col] = grid[row][col]*2
                    grid[row][col+1] = 0
                    move(direction)

    if direction == "right":
        for row in range(nRows):
            for col in range(nColumns-1):
                if grid[row][col] == grid[row][col+1]:
                    grid[row][col+1] = grid[row][col]*2
                    grid[row][col] = 0
                    move(direction)


texts: Deep nesting when looping over an object model coming from a 3rd part

texts:
I am stuck with this horrible object model coming back from a 3rd party product.  It's six levels of objects deep, and I have to loop through the collection in each level, to get the values I need, in order to produce a small object model that I actually require.

The code ends up looking like this (with variable and type names changed). How can I clean up this mess when I can't modify the structure of the rootObject?

(This is .NET 3.5.)

var levelOneEnumerator = rootObject.GetEnumerator();
while (levelOneEnumerator.MoveNext())
{
    var levelOneItem = levelOneEnumerator.Current as Foo_LevelOneItem;
    if (levelOneItem == null) continue;

    var levelTwoItemsEnumerator = levelOneItem.LevelTwoItems.GetEnumerator();
    while (levelTwoItemsEnumerator.MoveNext())
    {
        var LevelTwoItemsItem = levelTwoItemsEnumerator.Current as Foo_LevelTwoItem;
        if (LevelTwoItemsItem == null) continue;

        var foobars = new List<FooBar>();

        var levelThreeItemsEnumerator = LevelTwoItemsItem.LevelThreeItems.GetEnumerator();
        while (levelThreeItemsEnumerator.MoveNext())
        {
            var levelThreeItem = levelThreeItemsEnumerator.Current as Foo_LevelThreeItem;
            if (levelThreeItem == null) continue;

            var levelFourItemsEnumerator = levelThreeItem.LevelFourItems.GetEnumerator();
            while (levelFourItemsEnumerator.MoveNext())
            {
                var levelFourItem = levelFourItemsEnumerator.Current as Foo_LevelFourItem;
                if (levelFourItem == null) continue;

                var levelFiveItemsEnumerator = levelFourItem.LevelFiveItems.GetEnumerator();
                while (levelFiveItemsEnumerator.MoveNext())
                {
                    var levelFiveItem = levelFiveItemsEnumerator.Current as Foo_LevelFiveItem;
                    if (levelFiveItem == null) continue;

                    var levelSixItemsEnumerator = levelFiveItem.LevelSixItems.GetEnumerator();
                    while (levelSixItemsEnumerator.MoveNext())
                    {
                        var levelSixItem = levelSixItemsEnumerator.Current as Foo_LevelSixItem;
                        if (levelSixItem == null) continue;

                        var levelSixKey = levelSixItem.Key;
                        var foobar = foobars.Where(x => x.Key == levelSixKey).FirstOrDefault();
                        if (foobar == null)
                        {
                            foobar = new FooBar
                                          {
                                              LevelSixKey = levelSixKey,
                                              TransDate = levelFiveItem.TransDate,
                                              PaidAmount = 0
                                          };
                            foobars.Add(foobar);
                        }

                        // * -1 because value should be positive, while product reports a negative (and vice versa)
                        foobar.PaidAmount += (levelFiveItem.PaidAmount ?? 0) * -1;
                    }
                }
            }
        }

        yield return new FooBarsCollection
                         {
                             Prop1 = levelTwoItemsItem.Prop1,
                             Prop2 = levelTwoItemsItem.Prop2,
                             Prop3 = levelTwoItemsItem.Prop3,
                             FooBars = foobars
                         };
    }
}


texts: Merge two DataFrames with key over-write

texts:
I have implemented a custom merge of 2 pandas DataFrames, but only mutates the first.

The new columns will be the union of the original columns and the new keys will be union of original keys. Additionally, the second DataFrame values will overwrite the first DataFrame if the keys match.

def merge_dataframes(df1, df2):
    for header in set(df2) - (set(df1) & set(df2)):
        df1[header] = None

    old_keys = df2.index.isin(df1.index)
    new_keys = ~old_keys

    df1.update(df2[old_keys])
    df1 = df1.append(df2[new_keys], sort=True)

    return df1

This is tested as follows:

    df1 = pandas.DataFrame(data=["Test1", "Test2"])
    df2 = pandas.DataFrame(data=["Test3", "Test4"])

    # this should simply overwrite df1 with df2
    new_df = merge_dataframes(df1, df2)
    assert (new_df == df2).all()[0]

    df1 = pandas.DataFrame(data=["Test1", "Test2"])
    df2 = pandas.DataFrame(data=["Test3", "Test4"], index=["a", "b"])

    # this should simply overwrite df1 with df2
    new_df = merge_dataframes(df1, df2)
    expected_df = pandas.DataFrame(data=["Test1", "Test2", "Test3", "Test4"], index=[0, 1, "a", "b"])
    assert (new_df == expected_df).all()[0]

Is there a way to accomplish this with less code?


texts: C String - new function to detect user's anger

texts:
This was the most humerus coding I've ever done. It's for my string library in C. It detects if the user is angry to various degrees, namely str_isHeated().

Why?

Ever play a text-based game and you're swearing at the computer by typing, typing multiple !!!, and the computer responds very dumb? I think it may be useful for AI where NPC's (non-playable characters) can judge your mood and respond appropriately. Maybe even used for customer service online.

It works, but I'm interested to see if anyone has any thoughts on how to improve it. I've been having some fun with it.

/*
Function: str_getHeat()
Software usually gets user information, but it hardly
detects the user's emotion when entering in the information.
This may be useful for checking a customer's or player's
typing behavior, which may generate better responses with AI.
Calculated as follows:
    All Caps
    One or more words in caps
    Exclamation Point Count
    If 'please' or 'sorry' is found, take off heat points.
    Swearing words
Returns: EHeat_Cold, EHeat_Warm, EHeat_Heated, EHeat_VeryHeated
*/
EHeat str_isHeated(STRING *objString)
{
int i;
int intHeatScore = 0;       /* 0% cold; 100% very heated */
STRINGCOLLECTION tokens;
STRING temp_a;

/* Count how many exclamations there are */
for (i = 0; i < objString->length; i++)
{
    if (objString->str[i] == '!')
        intHeatScore += 10;
}

/* tokenize user's input */
sc_init(&tokens);
str_tokenize(objString, &tokens);

    /* Check if all caps. That can be taken as impatient. */
if (str_isUpper(objString))
{
    intHeatScore += 10;
}
else
{
    /* check if one or more words are all in caps. That is
       demanding behavior, and that is not nice. */
    for (i = 0; i < tokens.count; i++)
    {
        if (str_isUpperCString(tokens.items[i]))
        {
            intHeatScore += 10;

            /* 'I' is excused. */
            if (!strcmp(tokens.items[i], "I"))
                intHeatScore -= 10;
        }
    }
}

/* Check if the user said please. That's always nice.
   Take off a few heat points. */
if (str_findStringIgnoreCaps(objString, "please"))
    intHeatScore -= 6;

/* Check if the user said he's sorry. That's also nice. */
if (str_findStringIgnoreCaps(objString, "sorry"))
    intHeatScore -= 6;

/* Almost forgot... swearing. That is never nice. */
for (i = 0; i < tokens.count; i++)
{
    str_setText(&temp_a, tokens.items[i]);
    str_toLower(&temp_a);

    /* don't say these words out loud (censored for your innocence*/
    if (str_findString(&temp_a, "$#@#") ||
        str_findString(&temp_a, "@#$@") ||
        str_findString(&temp_a, "@$$") ||
   str_findString(&temp_a, "@$$#@") ||
        str_findString(&temp_a, "%#@") ||
        str_findString(&temp_a, "@#$")
        )
    {
        /* big no-no */
        intHeatScore += 20;
    }
}

/* Check the final heat score */
if (intHeatScore >= 50)
    return EHeat_VeryHeated;

else if (intHeatScore >= 30)
    return EHeat_Heated;

else if (intHeatScore > 10)
    return EHeat_Warm;

else if (intHeatScore >= 0)
    return EHeat_Cold;

return EHeat_Cold;
}


texts: Is this a proper quicksort algorithm in Python?

texts:
import random

def qsort(qslist):

    small = []
    big = []

    if (len(qslist) < 2):
        return qslist

    elif (len(qslist) > 1):

        pivot = qslist[int(random.randrange(len(qslist)))]

        for x in range(len(qslist)):
            if qslist[x] <= pivot:
                small.append(qslist[x])
            else:
                big.append(qslist[x])
        if(len(big) == 0):
            big.append(pivot)
            small.remove(pivot)

return qsort(small) + qsort(big)

qslist = [9,1,8,2,7,3,6,4,5]
print(qsort(qslist))

Please give me advice while picking up Python.  I'm trying to do so while at the same time doing some basic algorithms.

Have I understood how the quicksort algorithm work?
Please give me some general feedback on the Python code.


texts:
I sped through the 5hr F# pluralsight course this week-end and thought I'd sement my learning by going through as many Advent of Code puzzles I could with this new learning. However, already on day 2 I'm starting to question whether I'm too biased from C syntax and imperative coding to do it "right".

I really really miss being able to break from for loops for the second solution here. Sure I could make a while loop and have a mutable i and j, but it seems wrong either way. Also, I'd like function pointers for the "ops", but that's just a matter of doing some more work I guess.

In any case, some pointers on things to improve and make more declarative in the code would be super appreciated. Would really like to get going on the right foot before running off to day 3.

open System
open System.IO

let parse = fun (x:String) -> x.Split ',' |> Array.map int

let run (ops:int[]) =
    let mutable i = 0
    while i < ops.Length do
        match ops.[i] with
            | 1 ->
                let a = ops.[ops.[i+1]]
                let b = ops.[ops.[i+2]]
                ops.[ops.[i+3]] <- a + b
                i <- i + 4
            | 2 ->
                let a = ops.[ops.[i+1]]
                let b = ops.[ops.[i+2]]
                ops.[ops.[i+3]] <- a * b
                i <- i + 4
            | 99 ->
                i <- ops.Length
            | _ ->
                printfn "doh %A" i
    ops

let test = parse >> run

let test1 = test "1,0,0,0,99"
let test2 = test "2,3,0,3,99"
let test3 = test "2,4,4,5,99,0"
let test4 = test "1,1,1,4,99,5,6,0,99"

let input = parse <| File.ReadAllText (Path.Combine [|__SOURCE_DIRECTORY__;@"input.txt"|])
let prog1 = Array.copy input
prog1.[1..2] <- [|12;2|]
run prog1 |> ignore

let exp = 19690720
let mutable solNounVerb = (0, 0)
for i = 0 to 100 do
    for j = 0 to 100 do
        let prg = Array.copy input
        prg.[1..2] <- [|i;j|]
        run prg |> ignore
        if prg.[0] = exp then
            solNounVerb <- (i, j)

let sol2 = (fun (i, j) -> i * 100 + j) solNounVerb


texts: Reduce columns to produce product keycodes

texts:
I have written the following code that achieves my desired goal of converting a "raw" CSV file into a keycoded list. The idea is that a person will get the first product they ask for, and English products are coded as blank because they are the default.

This gist contains a sample of the input and output data. As it stands, rubocop thinks my code is too complex, and I am inclined to agree with it here, as it feels like I am doing far more than I need to in order to get such a simple result.

Not sure if this is helpful but the rubocop stats I'm getting are as follows:

ABC size too high (19.44/15)
Cyclomatic complexity too high (9/6)
Method has too many lines (17/10) (is this one really even a problem?)
Perceived complexity too high (10/7)

Are any of these "true" problems? They seem to reflect my opinion that the code just turned out "ugly"

On paper it I narrowed it down to about 2 cases with some sub cases. (1. Normal header -> write 2.Header has "#" in it -> subcases) and in the second case it's either blank, "1", or a product name. If the line contains "English Map" I write nothing, otherwise I am to write the first product requested sequentially on the line.

require 'CSV'
in_file = 'test.csv'

def code_line_by_product(line)
  new_line = []
  tmp = nil
  e_line = false
  line.each do |item|
    if item[0].include?('#')
      if item[1] != ' ' && item[1] && item[1] != '1' && item[1] != ''
        e_line = true if item[1].include?('English')
        unless tmp || e_line
          tmp = item[1][0]
          new_line << tmp
        end
      end
    else
      new_line << item[1]
    end
  end
  new_line
end

CSV.open("#{File.basename(in_file, '.csv')}_coded.csv", 'a+') do |out|
    out << %w(First Last Company Address address2 City State Zip Country phone_number email_address keycode)
  CSV.foreach(in_file, headers: true) do |line|
    out << code_line_by_product(line)
  end
end

Also, I've been noticing that I use that construction of writing from one file to another a lot and was wondering if there was a more convenient way of doing it (such as writing a function that takes the in file, out file, and the desired transformation). While it's only 4 lines of code, I essentially use those nested block all the time and it would be nice to only have to write the transformation function and then just call a single function to execute it.


texts: Aligning '=' on protocol buffers .proto files

texts:
Should the equals sign be alined on protocol buffers? I am having a huge discussion with a colleague and we can't get to decide on what's the best practice.

message foobar {
    optional bool var_one_short             = 1;
    optional bool var_two_looooooooong_name = 2;
    optional bool another_var               = 3;
}

vs

message foobar {
    optional bool var_one_short = 1;
    optional bool var_two_looooooooong_name = 2;
    optional bool another_var = 3;
}


texts: Improving and optimizing squeeze() function

texts:
I am currently reading The C Programming Language by Dennis Richie and Brian Kernighan, and I came to implement the function squeeze (s1, s2) as an exercise. squeeze() deletes each character in s1 that matches any character in the string s2. While coding squeeze(), I thought that I can extend its capability to act like trim() method in Java, and then the my code was already done, and tested.

However, even though it is implemented in C, I believe that the code below can be improved and optimized. Please help me do so.

char *squeeze (char *str1, char *str2) {

     int i, j;
     int str1Len = strlen (str1);
     int toBeSubtractLen = 0;

     char chr1 = '\0';
     char chr2 = '\0';

     for (i = 0; i < str1Len; i++) {
          chr1 = str1 [i];
          for (j = 0; j < strlen (str2); j++) {
               chr2 = str2 [j];
               if (chr1 == chr2) {
                    toBeSubtractLen++;
               }
          }
     }

     char *finalStr;
     finalStr = malloc ((str1Len - toBeSubtractLen) + 1);
     if (finalStr == NULL) {
          printf ("Unable to allocate memory.\n");
          exit (EXIT_FAILURE);
     }

     int indx = 0;
     for (i = 0; i < str1Len; i++) {
          chr1 = str1 [i];
          for (j = 0; j < strlen (str2); j++) {
               chr2 = str2 [j];
               if (chr1 == chr2) {
                    break;
               }
          }
          if (chr1 != chr2) {
               finalStr[indx] = chr1;
               indx++;
          }
     }
     return finalStr;

} /* end of squeeze() */

Samples:

str1 = ",AaBbCcDdEeFfGgHhIiJjKkLlMmAaAaAaNnOoPpQqRrSsTtUuVvWwXxYyZz"
str2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
str3 = "abcdefghijklmnopqrstuvwxyz"
name = "ChristopherM.Sawi"
birthday = "August14,1988"

Outputs:

1. squeeze-ing str1 by str2 yields: "<space>,<tab>abcdefghijklmaaanopqrstuvwxyz"
2. squeeze-ing str1 by str3 yields: "<space>m<tab>ABCDEFGHIJKLMAAANOPQRSTUVWXYZ"
3. squeeze-ing str2 by str3 yields: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
4. squeeze-ing name by str3 yields: "C<space>M.<space>S"
5. squeeze-ing birthday by str1 yields: "141988"


texts:
This question is really to help me decide on something.  I have started development of my own programming language that I am calling DeliciousWaffle (or maybe samscript).

So far it looks pretty cool.  I built a compiler in Python, and associated .dw files with it.  These files are like .py or .vbs or .java.  They provide the code for the compiler to interpret. I also programmed an IDE for it using wxPython.

Here are a few examples of what it looks like:

The fully functional IDE:

A calculator program that I wrote in DeliciousWaffle:

And here is the code for the compiler.  You can download this if you'd like and try out the syntax.

#deliciouswaffle
import sys
import linecache
varss={}
def Say(vartype,text):
    if vartype=='normal':
        print text
    if vartype=='var':
        print varss.get(str(text))
def Set(var,val):
    global varss
    varss.update({str(var):val})
def Get(var,prmpt):
    val=raw_input(prmpt)
    try:
        val=int(val)
        x=val+1
    except:
        val=str(val)
    Set(var,val)
def Loop():
    global line
    line=0
def IfStr(var1,functlines):
    global line
    var=varss.get(var1)
    try:
        x=var+1
        line+=functlines
    except TypeError:
        pass
def IfInt(var1,functlines):
    global line
    var=varss.get(var1)
    try:
        x=var+1
        pass
    except TypeError:
        line+=functlines
def Convert(var):
    val=varss.get(var)
    if type(val) == type('str'):
        val=int(val)
    if type(val) == type(1):
        val=str(val)
    varss.update({var:val})
def If(var1,compare,var2,functlines):
    global varss
    global line
    var1=varss.get(str(var1))
    var2=varss.get(str(var2))
    if compare=='equ':
        if var1==var2:
            pass
        else:
            line+=functlines
    if compare=='lss':
        if var1<var2:
            pass
        else:
            line+=functlines
    if compare=='gtr':
        if var1>var2:
            pass
        else:
            line+=functlines
def ChangeVar(var,operation,do):
    global varss
    val=varss.get(var)
    if operation=='+':
        val+=do
    if operation=='-':
        val-=do
    if operation=='/':
        val/=do
    if operation=='*':
        val*=do
    varss.update({var:val})
def CombineVars(newvar,var1,var2,operation):
    global varss
    var1=int(varss.get(var1))
    var2=int(varss.get(var2))
    if operation=='+':
        val=var1+var2
    if operation=='-':
        val=var1-var2
    if operation=='/':
        val=var1/var2
    if operation=='*':
        val=var1*var2
    varss.update({newvar:val})
def End():
   global eof
   eof=1
line=0
eof=0

try:
    program = (sys.argv[1])
except:
    program = 'main.dw'

if program == 'main.dw':
    try:
        f=open('main.dw','r')
        f.close()
    except:
        print 'No Delicious Waffle script loaded.'
        print 'Create a script called main.dw, or load one into Delicious Waffle.'
        raw_input()
        sys.exit()

while eof==0:
    try:
        line+=1
        try:
            eval(linecache.getline(program, line))
        except:
            pass
    except:
        eof=1
        f=open('tempvars.file','w')
        f.close()
        sys.exit()

What do you think?  Is this worth completing?  Or should I leave it be?  This question is probably inappropriate for code review, sorry.


texts:
I am using the below code to execute a MySQL query in PHP.

$cus_id = '1';
$query = new QUERY();
$clause = "SELECT * FROM customers WHERE cus_id=:cus_id AND status='ACTIVE'";
$params = array('cus_id'=>$cus_id);
$result = $query->run($clause, $params)->fetchAll();

Is it secure enough, or do I need to bind the static variable as well as seen below?

$clause = "SELECT * FROM customers WHERE cus_id=:cus_id AND status=:status";
$params = array('cus_id'=>$cus_id, 'status'=>'ACTIVE');


texts: Project Euler #2 (classic) - Sum of even fibonacci numbers below 4 million

texts:
I'm looking to use LISP as best I can, not just get the right answer. This is very early on in my LISP career so feedback is welcome and exciting! Recently asked about Project Euler #1, got some feedback and incorporated into this answer for #2, but I know there's a LOT left to be learned!

Description of Problem #2

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

(defun sum (L)
  "sum a list"
  (reduce #'+ L))

(defun filter (L predicate)
  "filters a list"
  (remove-if (complement predicate) L))

(defun fiboNums (maxNum)
  "list of fibonacci numbers that are below maxNum"
  (setq A 1)
  (setq B 2)
  (setq next (+ A B))
  (loop while (< B maxNum) do
    (setq next (+ A B))
    (setq A B)
    (setq B next)
    collecting A))

(defvar answer (sum (filter (fiboNums (* 4 1000 1000)) #'evenp)))
(print answer)


texts:
I'm new to Python and I'm trying to convert between Microsoft GUIDs and plain hex strings:

def hex_to_guid(hex):
    h = binascii.unhexlify(hex)
    return '-'.join(map(bytes.decode, map(
        binascii.hexlify, (h[0:4][::-1], h[4:6][::-1], h[6:8][::-1], h[8:10], h[10:]))))

def guid_to_hex(guid):
    g = binascii.unhexlify(guid.translate(str.maketrans('', '', '-')))
    return ''.join(map(bytes.decode, map(
        binascii.hexlify, (g[3::-1], g[5:3:-1], g[7:5:-1], g[8:]))))

I suspect this may not be very readable. Am I being too clever?


texts:
The point of this is to concatenate a vector of std::strings into one string starting at an index of the vector.

std::string vectorSubstr(std::vector<std::string> vec, int startPos, char seperator)
{
    std::stringstream ss;

    for (int i = startPos; i < vec.size(); i++)
    {
        if (i == startPos)
        {
            ss << vec[i];
        }
        else
        {
            ss << seperator << vec[i];
        }
    }

    return ss.str();
}

Is there anything wrong with this approach? Should  I be using a stringstream or just concatenating strings?


texts: Calculate the nth Fibonacci number, mod m

texts:
I was trying to output F(n) mod m to find the remainder of Fibonacci number, where F(n) could be a very big number:

# Uses python3
n, m =  [int(x) for x in input().split()]

def fib(n):
    a = [0, 1]
    if (n <=1):
        return n
    else:
        for i in range(1, n):
            a.append((a[-1] + a[-2])%m)
        return a[i+1]
print (fib(n))

As I typed in 239 1000, it returns 161 as the remainder, which is correct. But with bigger inputs eg. 2816213588 239, it seems to exceed time limits, what can I do to improve the code?


texts: Counting the total number of characters in an std::set

texts:
I have a std::set<std::string> and I need to know the total number of characters (sum of all strings length):

static size_t SumLength(size_t value, const std::string &str)
{
    return str.length() + value;
}

size_t TotalLength(std::set<std::string> &stringSet)
{
   return std::accumulate(stringSet.begin(), stringSet.end(), 0, SumLength);
}

What do you think of this approach?


texts: Solution to 99 lisp problems, p09 in ruby

texts:
I am fairly new to ruby, and I am worried that my solution to problem 9 of the 99 lisp problems is extremly convoluted and inefficient.
The problem is:

My Code

ul = "putanytexthere"
h = []

ul.upcase
  .split('')
  .sort
  .join('')
  .each_char
  .slice_when { |a,b| a != b }
  .map(&:join)
  .each do |el|
    if el.length > 1
      h << el
    end
  end

  print h.length


texts: Find a n x m binary matrix with exactly a 1's in all rows and b 1's in all columns

texts:
[Base on https://codeforces.com/contest/1360/problem/G]

So my logic is to process each column at a time and find b rows such that the total 1s in them is less than a and if there are many candidates I take the rows with least 1s.

import           Data.List
import           Data.Array
import           Control.Monad
-- import           Debug.Trace

-- debug = flip trace

main :: IO ()
main = do
    t <- read <$> getLine -- testcases
    replicateM_ t $ do
        n : m : a : b : _ <- (map read . words <$> getLine) :: IO [Int]
        mapM putStrLn $ case solve n m a b of
            Just mat ->
                "YES"
                    : [ concatMap show [ mat ! (i, j) | j <- [1 .. m] ]
                      | i <- [1 .. n]
                      ]
            Nothing -> ["NO"]

-- solve :: Int -> Int -> Int -> Int -> Maybe (Array (Int, Int) Int)
solve n m a b = go
    (array (1, n) . zip [1 .. n] $ repeat 0) -- rowcnts
    (array ((1, 1), (n, m)) [ ((i, j), 0) | i <- [1 .. n], j <- [1 .. m] ]) -- matrix
    1 -- column
  where
    go rowcnts mat c
        | length idxs /= b = Nothing -- not enough rows
        | c == m = if all (== a) (elems rowcnts') then Just mat' else Nothing -- last column to process
        | otherwise = go rowcnts' mat' (c + 1) -- recurse for next column
      where
        idxs = take b . filter (\i -> (rowcnts ! i) < a) $ sortOn
            (rowcnts !)
            [1 .. n] -- candidate rows
        rowcnts' = accum (+) rowcnts . zip idxs $ repeat 1 --`debug` show (elems rowcnts)
        mat'     = mat // [ ((idx, c), 1) | idx <- idxs ]

I wish to ask how can I write better code which might be concise and cleaner.


texts:
I'm writing a program and I have a server that needs to be able to handle multiple client connections at once doing many different things.

I'm using the Qt library, so I handle new connections like this:

In the server constructor:

Server::Server(QObject* parent): QObject(parent)
{
  connect(&server, SIGNAL(newConnection()), //&server is a QTcpServer object
          this, SLOT(acceptConnection()));
  qDebug() << "[" << currentTime() << "] " << "Server started.";
  server.listen(QHostAddress::Any, PORT_NUMBER);
  qDebug() << "[" << currentTime() << "] " << "Server listening.";
}

The acceptConnection slot:

void Server::acceptConnection()
{
  client = server.nextPendingConnection(); //client is a QTcpSocket* object

  connect(client, SIGNAL(readyRead()), //When there is data to be read
    this, SLOT(startRead()));
}

The startRead slot:

void Server::startRead()
{

    char serverReceiveBuf[65536]; //A buffer for the data sent to the server
    client->read(serverReceiveBuf, client->bytesAvailable());
    handleConnection(serverReceiveBuf); //Do something with that data
}

I'm not going to give the handleConnection function because it's a bit long and I don't think it's necessary for the question.

My worry is latency. If I have one or two users, it's fine. But I haven't tested many concurrent users. There's a synchronization signal sent by the client that asks the server to verify the data the client has matches the data on the server. I'm sending this request every 250 ms, so with a few more concurrent users the client may end up waiting too long every 250 ms because of the other clients sending in synchronization requests.

At least, that's what I believe. Qt is pretty powerful, but I'm not entirely sure if when a signal is received that a new thread is automatically created to handle the connection. If I'm not mistaken, the current way I handle connections involves queueing, so that when the server receives a signal it'll process the requests in the order received. It's important to note that I don't call client->close() until the client terminates the connection themselves, so once client = server.nextPendingConnecting(); is called client will always exist until the client terminates it.

Is this a good way of handling multiple connections, given that I'll be regularly having users send synchronization requests often? If not, how should I handle the connections instead?


texts: Simple SingleLinkedList Implementation in C++

texts:
Below I have a very simple LinkedList implementation. I was wondering if there are any memory leak problems with this and if I used the pointers correctly. I just started practicing with C++ and hoping to improve my use of pointers and memory leak management.

#include <iostream>

struct node{
    int data;
    node *next;

    node::node(){}

    node::node(const int & val, node* link)
            : data(val), next(link)
    {}
};

class LinkedList
{

    public:
        LinkedList();
        void addToEnd(int val);
        void printList();
        void deleteList(node *head);
        void deleteNode(node *toBeDeleted);
        node* get(int index);

    private:
        int size;
        node *head, *tail;

};

LinkedList::LinkedList(){
    head = NULL;
    tail = NULL;
}

node* LinkedList::get(int index){

    node* temp = head;
    int pointer = 0;

    while(pointer != index){
        temp = temp->next;
        pointer++;
    }

    return temp;

}

void LinkedList::addToEnd(int val){

    node *temp = new node(val, NULL);
    // temp->data = val;
    // temp->next = NULL;

    if(head==NULL){
        head = temp;
        tail = temp;
        temp = NULL;
    }
    else{
        tail->next = temp;
        tail = temp;
    }
}

void LinkedList::printList(){

    node *temp = head;
    //temp = head;
    while(temp){
        cout<<temp->data<<"\t";
        temp = temp->next;
    }
}

//Supposed to delete the nodes coming after the input node
void LinkedList::deleteList(node *start){
    if(start){
        deleteList(start->next);
        delete start;
    }
}

//deletes a single node
void LinkedList::deleteNode(node* toBeDeleted){

    node* temp = head;

    if(head == toBeDeleted){
        head = head->next;
        delete temp;
    }

    while(temp->next != toBeDeleted){
        temp = temp->next;
    }

    if(temp->next){
        temp->next = toBeDeleted->next;
        delete toBeDeleted;
    }

}

int main(){

    LinkedList list;

    for(int i=0;i<4;i++){
        list.addToEnd(i+1);
    }

    list.deleteList(list.get(2));
    //list.deleteNode(list.get(2));

    list.printList();

    return 0;
}

Currently, the main function doesn't run after deleteList. I am not necessarily asking about how to fix that part, I just wanted to learn tips about better pointer uses and memory leak possibilities.

Edit:

I have commented the use of deleteList and deleteNode and below I have added a destructor showing how I was planning to use deleteList.

LinkedList::~LinkedList(){
    deleteList(head);
}


texts: Init.d script for Rails managing a Rails app via Unicorn

texts:
This script is to enable the remote management of a Rails app via one script.
I pieced it together from various blog posts. I am not to familiar with some of the BASH functionality that is used. It seems to work okay, but I wonder if there is anything that I have done sub-optimally in my naïveté.

#!/bin/bash
# /etc/init.d/unicorn

# ### BEGIN INIT INFO
# Provides:          unicorn
# Required-Start:    $network $remote_fs $local_fs
# Required-Stop:     $network $remote_fs $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Stop/start unicorn
### END INIT INFO

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

PROJ_ENV="staging"
RBENV_VERSION=2.2.2
RBENV_ROOT=/opt/rbenv

PROJ_NAME="myapp"

PID_FILE=/var/www/$PROJ_NAME/current/tmp/pids/unicorn.pid
OLD_PID_FILE=$PID_FILE.oldbin
PROJ_DIR=/var/www/$PROJ_NAME
TAG='[unicorn]'

UNICORN_CONFIG=$PROJ_DIR/current/config/unicorn/$PROJ_ENV.rb
DEPLOY_USER=ec2-user
[ -f $PID_FILE ] && KPID=`cat $PID_FILE`

# Start the service
start() {
     # [ is the 'test' command  -f file? -a and -n variable -d directory
    if [ -f $PID_FILE -a -n "${KPID}" -a -d "/proc/${KPID}" ]; then
          logger -sit $TAG "Process ${KPID} in PID file $PID_FILE exists. Service '${PROJ_NAME}' should be running"
        exit 1
    else
        logger -sit "$TAG" "Process doesn't exist. Trying to start server..."
        #su - $DEPLOY_USER -c "bash -c 'cd $PROJ_DIR/current ; pwd      ; /opt/rbenv/bin/rbenv exec bundle exec unicorn -v'"
        su - $DEPLOY_USER -c "bash -c 'cd $PROJ_DIR/current ; pwd       ; /opt/rbenv/bin/rbenv exec bundle exec unicorn -c $UNICORN_CONFIG -E $PROJ_ENV -D'"
        if [[ $? == 0 ]]; then
            logger -sit "$TAG" "server started"
        else
            logger -sit "$TAG" "FAILED to start server"
            exit 1
        fi
    fi
}

# Stop the service
stop() {
        su $DEPLOY_USER -c "kill -TERM $(cat $PID_FILE)"
        sleep 2
        if [[ ! -f $PID_FILE ]]; then
                logger -sit "$TAG" "Server stoped"
        else
                logger -sit "$TAG" "FAILED to stop server"
                exit 1
        fi
}

# Reload service
reload() {
    logger -sit "$TAG" "Trying to reload server"
    kill -USR2 $(cat $PID_FILE)
    sleep 1
    if [[ -f $OLD_PID_FILE ]]; then
        logger -sit "$TAG" "Server reloaded"
    else
        logger -sit "$TAG" "FAILED to reload server"
        exit 1
    fi
}

restart() {
    if [ -f $PID_FILE -a -n "${KPID}" -a -d "/proc/${KPID}" ]; then
        logger -sit "$TAG" "Restarting server"
        kill -HUP $(cat $PID_FILE)
    else
      logger -sit "$TAG" "Process doesn't exist. Running start"
       #$0 is the path of the script
      $0 start
    fi
}

### main logic ###
case "$1" in
    start)
        start
        ;;

    stop)
        stop
        ;;

    restart)
        restart
        ;;
    reload)
        reload
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart|reload}"
        exit 1
esac
exit 0


texts: Getting messages asynchronously using MailKit

texts:
I'm writing a prototype for an application that uses MailKit and imap to connect to gmail. It's the first time I've used MailKit and I'm a bit stumped around the best way to do this.

Essentially, I want to write an async method hosted in a class library that downloads emails based on a simple header text search and invokes a callback each time so I can update the GUI. My attempt to do this is given in the following method.

public async Task<IList<IEmail>> EmailQueryAsync(string query, Action<IEmail> callBack)
{
    IList<IEmail> result = new List<IEmail>();

    using (ImapClient client = new ImapClient())
    {
        await client.ConnectAsync("imap.gmail.com", 993, true);

        client.AuthenticationMechanisms.Remove("XOAUTH2");

        await client.AuthenticateAsync(this.userName, this.password);

        IMailFolder folder = client.Inbox;

        await folder.OpenAsync(FolderAccess.ReadOnly);

        IList<UniqueId> uniqueIds = await client.Inbox.SearchAsync(SearchQuery.FromContains(query));

        IList<Task<MimeMessage>> messageTasks = uniqueIds.Select(m => client.Inbox.GetMessageAsync(m)).ToList();

        while (messageTasks.Count > 0)
        {
            Task<MimeMessage> messageTask = await Task.WhenAny(messageTasks);

            messageTasks.Remove(messageTask);

            MimeMessage message = await messageTask;

            IEmail email = new Email(date: message.Date, id: message.MessageId, messageBody: message.TextBody, references: message.References);

            callBack(email);

            result.Add(email);
        }

        return result;
    }
}

However, I feel there is a lot of code for what I want to do - do I really need to call so many async methods to get the messages, is it essential to have everything inside the using statement, or are there any obvious objects that I can cache. Is there a way that I can rewrite this method so I do not have to include the callBack action? Also, I'm a bit unsure about the types of exceptions I can sensibly expect to handle, timeouts etc...


texts:
I would like to record client information when they go into a location on the web site so I created this ProcessRequest class that will collect data and insert it into the database. This will collect HttpContext and send that data to a Store Procedure that will then insert into a database table.

namespace DataCollection
{
    public class siteDataCollection
    {
        public void ProcessRequest(HttpContext context)
        {
            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            string filename = Path.GetFileName(context.Request.Url.AbsolutePath);

            string customerGuid = context.Request.Cookies["customerguid"].Value.ToString();
            customerGuid = customerGuid.Replace("%2D", "-");

            if(customerGuid is null) {

                customerGuid = HttpContext.Current.Session.SessionID;
            }

            SQLHelper sqlh = new SQLHelper(conn);
            SqlDataReader dr = null;

            SqlParameter[] parms = new SqlParameter[] {
                            new SqlParameter("@CustomerGUID", SqlDbType.NVarChar, 50),
                            new SqlParameter("@FileName", SqlDbType.NVarChar, 255),
                            new SqlParameter("@REMOTE_ADDR", SqlDbType.NVarChar,15),
                            new SqlParameter("@LOCAL_ADDR", SqlDbType.NVarChar,15),
                            new SqlParameter("@HTTP_USER_AGENT", SqlDbType.NVarChar,255),
                            new SqlParameter("@HTTP_REFERER", SqlDbType.NVarChar,255)
                            };

            parms[0].Value = customerGuid;
            parms[1].Value = filename;
            parms[2].Value = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            parms[3].Value = HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"];
            parms[4].Value = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];
            parms[5].Value = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];

            dr = sqlh.ExecuteReaderStoreProcedure("usp_InsertFileLocation", parms);

            context.Response.Clear();
            context.Response.ClearContent();
            context.Response.ClearHeaders();
            context.Response.AddHeader("Pragma", "no-cache");
            context.Response.AddHeader("Expires", "-1");

            context.Response.ContentType = "application/pdf";
            byte[] bytePDF = File.ReadAllBytes(filename);
            context.Response.BinaryWrite(bytePDF);
            context.Response.End();
        }
    }
}


texts: Prompting the user to input a data value into an element in a linked list

texts:
I'm working through a practice problem that is having me build and modify a linked list over a series of steps. I am particularly interested in knowing if there's a more elegant way of prompting the user to input a data value for a new element in a linked list (see step 5 below).

I'd also like to know if there's a better way of counting and returning the number of elements in a linked list.

Practice Problem:

Step 4: Add a function trav_and_print to your program that will traverse the linked list and print the values of all of the data members.
Step 5: Add code to your program that will add another element to the end of the linked list.  Prompt the user for the data value.  Call your trav_and_print function, and also from main print the value of last -> data to make sure that the element was added correctly.
Step 6: Add another function count_elems that will traverse the linked list, count how many elements there are, and return that count.  Test this function by calling it in various places in main, including before there are any elements in the linked list.

My code thus far:

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

typedef struct linked_list
{
   int data;
   struct linked_list *next;
}   element;

typedef element * elementptr;

void trav_and_print(elementptr);

int count_elems(elementptr);

int main()
{
   elementptr first = NULL;
   elementptr last = NULL;
   int var = 0;
   int NumElems = 0;

   /* Create a linked list with one element            */
   /* NOTE: the first element is always a special case */

   first = (elementptr) malloc(sizeof(element));
   last = first;
   last -> data = 5;
   last -> next = NULL;

   /* Add another element to the end of the list */

   last -> next = (elementptr) malloc(sizeof(element));
   last = last -> next;
   last -> data = 12;
   last -> next = NULL;

   /*Add another element to the end of the list;
   user generated number*/

   last -> next = (elementptr) malloc(sizeof(element));
   last = last -> next;
   printf("Enter the data value to add to the linked list: ");
   scanf("%d",&var);
   last -> data = var;
   last -> next = NULL;

   trav_and_print(first); //prints the linked list

   NumElems = count_elems(first); //traverses and counts the elements in the linked list

   printf("Number of elements in the linked list: %d",NumElems);

   free(first);
   free(last);

   return 0;
}
void trav_and_print(elementptr f)
{
    elementptr current;

    current = f;
    if(current == NULL)
        printf("There is no linked list!\n");
    else
        while (current != NULL)
    {
        printf("The data value is %d\n",current->data);
        current = current -> next;
    }
}
int count_elems(elementptr f)
{
    int count = 0;
    elementptr current;
    current = f;
    while(current != NULL)
    {
        current = current->next;
        count++;
    }
    return count;
}


texts:
I have a search on a very simple spring-powered website and I want to display 10 recent inputs:

import java.util.Collection;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

@Component
public class RecentPhrases implements DisposableBean {
    static final int SIZE = 10;
    private final ExecutorService offeringService = Executors.newFixedThreadPool(1);
    private final ConcurrentMap<String, Long> phrases = new ConcurrentHashMap<>();

    @Override
    public void destroy() {
        offeringService.shutdownNow();
    }

    public void offer(final String phrase) {
        offeringService.execute(() -> {
            phrases.put(phrase, System.currentTimeMillis());
            while (phrases.size() > SIZE) {
                long oldestAge = Long.MAX_VALUE;
                String oldestPhrase = null;
                for (Entry<String, Long> entry : phrases.entrySet()) {
                    if (entry.getValue() < oldestAge) {
                        oldestAge = entry.getValue();
                        oldestPhrase = entry.getKey();
                    }
                }
                phrases.remove(oldestPhrase);
            }
        });
    }

    public Collection<String> getRecent() {
        return phrases.keySet();
    }

}

Is there some simpler solution that will be lightweight enough to not update the underlying collection in a separate thread?


texts:
I have developed this function but I'm not sure if this is the best (secure) way to write in resources without corrupt *.exe in case of fails.

What is the best way to write resources to a *.exe file?

procedure SaveToRes(const aResFileName, aResName: string; aMemoryStream : TMemoryStream);
var
   myRes: THandle;
   aUpdateResource : boolean;
begin
   aUpdateResource := false;

   if not(FileExists(aResFileName)) then
     raise Exception.Create('File not found');

   myRes := BeginUpdateResource(PChar(aResFileName),false);

   if myRes = 0  then
     raise Exception.Create('BeginUpdateResource');

   try
      aMemoryStream.Seek(0,0);

      aUpdateResource := UpdateResource(myRes, RT_RCDATA, PChar(aResName), LANG_NEUTRAL, aMemoryStream.Memory, aMemoryStream.Size);

      if not(aUpdateResource) then
         RaiseLastOSError(GetLastError, '[UpdateResource]');

   finally
      if not(EndUpdateResource(myres, not(aUpdateResource))) then
         RaiseLastOSError(GetLastError, '[EndUpdateResource]');
   end;
end;

Usage:

var
    aVal          : LongInt;
    aMemoryStream : TMemoryStream;
begin
    aVal := 5;

    aMemoryStream := TMemoryStream.create;

    try
        aMemoryStream.Write(aVal, sizeOf(aVal));

        SaveToRes('C:\foo\bar.exe', 'myRes', aMemoryStream);
    finally
        aMemoryStream.free;
    end;
end;


texts: Creating Extension Method to map entity with subentities object to Poco object

texts:
I am trying to create an extension method that builds a POCO object (copies all the fields) for an Entity Object.

When Entity object is simple (no navigation, no sub collections), it works fine.
I want to improve it so it could also deal with sub-entities.

For this example I take Nortwind database and use Customer and Order entities.
My POCOs:

 public class CustomerPOCO : BaseDataItemModel
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }

        List<OrderPOCO> orders;

       [PropertySubCollection]
        public List<OrderPOCO> Orders
        {
            get { return orders; }
            set { orders = value; }
        }

        public CustomerPOCO()
        {
            orders = new List<OrderPOCO>();
        }

    }

public class OrderPOCO : BaseDataItemModel
{

   public int OrderID { get; set; }
   public string ShipName { get; set; }
   public string ShipCity { get; set; }

}

Extension Method:

 public static void CopyPropertiesFrom<TObjectTarget>(
           this ICollection<TObjectTarget> targetitems, System.Collections.IEnumerable sourceitems)
            where TObjectTarget : new()
        {
            foreach (var source in sourceitems)
            {

                TObjectTarget targetObject = new TObjectTarget();

                PropertyInfo[] allProporties = source.GetType().GetProperties();

                PropertyInfo targetProperty;
                foreach (PropertyInfo fromProp in allProporties)
                {
                    targetProperty = targetObject.GetType().GetProperty(fromProp.Name);

                    if (targetProperty == null) continue;
                    if (!targetProperty.CanWrite) continue;

                    //check if property in target class marked with SkipProperty Attribute
                    if (targetProperty.GetCustomAttributes(typeof(SkipPropertyAttribute), true).Length != 0) continue;

                    //Sub Collection -> set it here
                    if (targetProperty.GetCustomAttributes(typeof(PropertySubCollection), true).Length != 0)
                    {

                    }
                    else

                        targetProperty.SetValue(targetObject, fromProp.GetValue(source, null), null);

                }

                targetitems.Add(targetObject);

            }
        }

static void Main(string[] args)
 {
      List<CustomerPOCO> customers;
      using (NorthwindEntities northcontext = new NorthwindEntities())
      {
          var cus = from customer in northcontext.Customers
                  select customer;

          customers = new List<CustomerPOCO>();
          customers.CopyPropertiesFrom(cus);

      }
   }

Note: Extension should know the type of sub-entity and a type of sub-poco...


texts:
I already asked for help in optimizing a simple Caesar Cypher code in java here : Cesar code in Java
I tried to implement all the advice from that subject and now I am asking again.
Do you have any other advice to optimize this code ? What can be improved ?

Here is the code, thank you in advance :

Cypher.java :

package fr.thomascloarecd.cypher;

import java.util.Scanner;

public class Cypher {

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

    private static String cypherMethod = "";

    public static void main (String[] args){
        while(!(cypherMethod.equals("stop") || cypherMethod.equals("2"))) {
            System.out.println("Choose a cypher's method and type it :" +
                    "\n (1) - caesarCypher" +
                    "\n (2) - stop => To stop the program");

            cypherMethod = sc.nextLine().toLowerCase();

            if (cypherMethod.equals("1") || cypherMethod.equals("caesarcypher")) {

                String encryptOrDecrypt = "";
                while(!(encryptOrDecrypt.equals("back") || encryptOrDecrypt.equals("3"))) {
                    System.out.println("\nWhat do you want to do (type it) :" +
                            "\n (1) - encrypt" +
                            "\n (2) - decrypt" +
                            "\n (3) - back => To go back in the cypher's method summary");

                    encryptOrDecrypt = sc.nextLine().toLowerCase();

                    if (encryptOrDecrypt.equals("1") || encryptOrDecrypt.equals("encrypt")) {
                        System.out.println("\nThen, what's the sentence that you want to encrypt ?");

                        CaesarCypher caesarcypher = new CaesarCypher(sc.nextLine(), encryptOrDecrypt);

                        System.out.println("\nEncrypted with caesar cypher : "+caesarcypher.translatedSentence());

                    } else if (encryptOrDecrypt.equals("2") || encryptOrDecrypt.equals("decrypt")) {
                        System.out.println("\nThen, what's the sentence that you want to decrypt ?");

                        CaesarCypher caesarcypher = new CaesarCypher(sc.nextLine(), encryptOrDecrypt);

                        System.out.println("\nDecrypted with caesar cypher : "+caesarcypher.translatedSentence());
                    }
                }
            } else if (cypherMethod.equals("2") || cypherMethod.equals("stop")) {
                System.exit(0);
            }
        }
        sc.close();
    }
}

CaesarCypher.java :

package fr.thomascloarecd.cypher;

import java.text.Normalizer;

class CaesarCypher {
    private String userSentence;
    private String encryptOrDecrypt;

    CaesarCypher(String pUserSentence, String pEncryptOrDecrypt){
        userSentence = Normalizer.normalize(pUserSentence, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "").toLowerCase();
        encryptOrDecrypt = Normalizer.normalize(pEncryptOrDecrypt, Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", "").toLowerCase();
    }

    String translatedSentence(){
        char[] ALPHABET = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

        StringBuilder translatedSentence = new StringBuilder();

        for(int i = 0; i <= userSentence.length()-1; i++){
            for(int j = 0; j < ALPHABET.length; j++) {
                if (userSentence.charAt(i) == ALPHABET[j]) {
                    translatedSentence.append(ALPHABET[(26 + j + integerDependOnAction()) % 26]);
                    break;
                } else if (j == 25) {
                    translatedSentence.append(userSentence.charAt(i));
                    break;
                }
            }
        }
        return translatedSentence.toString();
    }

    private int integerDependOnAction() {
        if (encryptOrDecrypt.equals("encrypt") || encryptOrDecrypt.equals("1")) {
            return 1;
        } else if (encryptOrDecrypt.equals("decrypt") || encryptOrDecrypt.equals("2")) {
            return -1;
        }
        return 0;
    }
}


texts: Calculator that is part of a multipurpose program

texts:
I am currently working on a Python project.  It is some sort of a hub, where you can do some cool but basic stuff, such as: setting timers, launching websites, doing basic math, ping and view source codes of URLs, and more.

I want to make this code just a little more compact. I especially want my math menu more compact because I feel there is a way of doing it.  I just can't seem to figure it out.

…
elif userIn == ("math"):
    op = str(input("    * Enter operation (+, -, *, /, exp, sqrt, log): "))
    blank()
    if op==("+") or op==("-") or op==("*") or op==("/") or op==("exp"):
        input_1 = int(input("       * Enter first number:  "))
        blank()
        input_2 = int(input("       * Enter second number: "))
        blank()
    if op == ("+"):
        print ("       > "+str(input_1 + input_2))
        blank()
    elif op == ("-"):
        print ("       > "+str(input_1-input_2))
        blank()
    elif op == ("*"):
        print ("       > "+str(input_1*input_2))
        blank()
    elif op == ("/"):
        print ("       > "+str(input_1/input_2))
        blank()
    elif op == ("exp"):
        print ("       > "+str(input_1**input_2))
        blank()
    elif op == ("sqrt"):
        oneInput=int(input("        * Enter number: "))
        blank()
        print ("       > "+str(math.sqrt(oneInput)))
        blank()
    elif op == ("log"):
        input_1 = int(input("       * Enter number:  "))
        blank()
        input_2 = int(input("       * Enter base: "))
        blank()
        print ("       > "+str(int((math.log(input_1, input_2)))))
        blank()

Link to the code (pastebin).

Note: I have tried setting a basic for loop run through a list of operation symbols, and it would set the operation if the user op. was matched.  But, as it turns out, I just couldn't use strings as math operators in the code itself.

opl=["+", "-", "*", "/"]
for i in range(len(opl)):
    userInput1 (some way of setting op)     userInput2


texts:
I was using the following code to construct the tree from a list of nodes: [1, 2] means that there is a bi-directional link between 1 and 2

def createTreeFromEdges(edges):
    tree = {}
    for i in edges:
        v1, v2 = i
        if v1 in tree:
            tree[v1].append(v2)
        else:
            tree[v1] = [v2]

        if v2 in tree:
            tree[v2].append(v1)
        else:
            tree[v2] = [v1]

    return tree

and it works in the following fashion:

edges = [[2, 1], [3, 2], [4, 2], [5, 1], [6, 1], [7, 1], [8, 7]]
print createTreeFromEdges(edges)

This is cool, but for a python it looks like too much code. Is there a way to make it shorter?


texts: Run stored procedure from repository using EF

texts:
I need to dynamically call a stored procedures from my repository, and here is a my implementation:

        public void ExecProcedure(string name, Dictionary<string, string> param = null)
        {
            List<object> sqlParametesList = new List<object>();

            try
            {
                if (param != null)
                {
                    name = NormalizeProcedureName(name, param);
                    foreach (var item in param)
                    {
                        sqlParametesList.Add(new SqlParameter(item.Key, item.Value));
                    }
                }

                context.Database.ExecuteSqlCommand(name, sqlParametesList.ToArray());
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Error in ExecProcedure: {0}", e.Message));
            }
        }

There is 3 case of call ExecProcedure():

_repo.ExecProcedure("usp_Test"); // call without parameters
_repo.ExecProcedure("usp_Test2 @id", param); // set parameter name after procedure name and pass value as param
_repo.ExecProcedure("usp_Test2", param); // if passing param then we use method NormalizeProcedureName() to set parameter name after procedure name

private string NormalizeProcedureName(string name, Dictionary<string, string> param)
{
    if (!name.Contains("@"))
    {
        StringBuilder sb = new StringBuilder();
        string delimiter = "";
        sb.Append(name);

        foreach (var item in param)
        {
            sb.Append(delimiter);
            sb.Append(" @");
            sb.Append(item.Key);
            delimiter = ",";
        }

        name = sb.ToString();
    }
    return name;
}

What do you think about this implementations?
Any advice will be appreciated. Thanks


texts: Bash script to automate dev environment setup

texts:
After blowing up my environment again messing around with installing random programs and packages I decided to write a bash script I can clone from github and use to reinstall everything like I had before
The idea is that I'll be able to keep adding to it as I find more programs to use so that it will always be a stable starting point. Right now it's just a list of whatever I used to reinstall things copy-pasted into a single file.
Do people bother organizing bash scripts? If so what sort of structure do you use? I keep my actual code relatively clean but this whole thing felt like an aside to keep things orderly in the future
echo Email for github?

# get email, assume github username is same and split it off from domain
read email
name=$(echo $email | grep -o '^[^@]*')

mkdir $HOME/GoProjects
mkdir $HOME/GoProjects/src
mkdir $HOME/GoProjects/bin
mkdir $HOME/PyProjects
mkdir $HOME/JSProjects
mkdir $HOME/pemKeys

# basic update and upgrade
sudo apt update && sudo apt -y upgrade

# install Chromium
sudo apt install -y chromium

#install Go
wget https://dl.google.com/go/go1.14.3.linux-amd64.tar.gz
sudo tar xvfz go1.14.3.linux-amd64.tar.gz -C /usr/local/
rm -f go1.14.3.linux-amd64.tar.gz

cat >> $HOME/.profile << EOF
export GOROOT=/usr/local/go
export GOPATH=$HOME/GoProjects
export GOBIN=$HOME/GoProjects/bin
export PATH=$PATH:/usr/local/go:/usr/local/go/bin:$HOME/GoProjects:$HOME/GoProjects/bin
EOF

. $HOME/.profile

go get github.com/lib/pq

# install VScode
curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > packages.microsoft.gpg
sudo install -o root -g root -m 644 packages.microsoft.gpg /usr/share/keyrings/
sudo sh -c 'echo "deb [arch=amd64 signed-by=/usr/share/keyrings/packages.microsoft.gpg] https://packages.microsoft.com/repos/vscode stable main" > /etc/apt/sources.list.d/vscode.list'

sudo apt install -y apt-transport-https
sudo apt update -y
sudo apt install -y code

rm -f packages.microsoft.gpg

# install postgres
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
RELEASE=$(lsb_release -cs)
echo "deb http://apt.postgresql.org/pub/repos/apt/ ${RELEASE}"-pgdg main | sudo tee  /etc/apt/sources.list.d/pgdg.list
sudo apt update -y
sudo apt -y install postgresql-11

sudo apt install -y build-essential

#install docker
sudo apt install -y apt-transport-https ca-certificates curl gnupg2 software-properties-common
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"
sudo apt update -y
apt-cache policy docker-ce
sudo apt install -y docker-ce
sudo chmod 666 /var/run/docker.sock

#Add anaconda
sudo apt install -y libgl1-mesa-glx libegl1-mesa libxrandr2 libxrandr2 libxss1 libxcursor1 libxcomposite1 libasound2 libxi6 libxtst6
wget https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh
bash Anaconda3-2020.02-Linux-x86_64.sh -b -p
rm -f Anaconda3-2020.02-Linux-x86_64.sh

sudo apt install -y libpq-dev python3-dev
pip install psycopg2

#Add protobuff compiler and grpc
sudo apt install -y protobuf-compiler
export GO111MODULE=on
go get github.com/golang/protobuf/protoc-gen-go
go get -u google.golang.org/grpc

#Need to add NPM
sudo apt install  -y nodejs
sudo apt install -y npm

#setup github
git config --global user.name $name
git config --global user.email $email
git config --global color.ui true

yes "" | ssh-keygen -t rsa -C $email
cat $HOME/.ssh/id_rsa.pub

rm -rf ./SetupDebianDevEnv


texts: Find items that appear the same number of times in two collections

texts:
Here is a Java collection puzzle I found online. I was wondering if anyone can provide me with suggestions on how Appearance and tests can be improved. Suggestions of any kind and scope are very welcomed. it would be even better if reasons can be provided along with the suggestions.

Problem:

Appearance class:

package assign1;

import java.util.*;

public class Appearances {

    public static <T> int sameCount(Collection<T> a, Collection<T> b) {

        Map<T, Integer> map1 = countItemsInCollection(a);
        Map<T, Integer> map2 = countItemsInCollection(b);

        return compareMapForMatchingKeyAndValue(map1, map2);
    }

    private static <T> Map<T, Integer> countItemsInCollection(Collection<T> collection) {

        Map<T, Integer> mapItemToNumberOfOccurance = new HashMap<>();

        for (T item : collection) {
            if (!mapItemToNumberOfOccurance.containsKey(item)) {
                mapItemToNumberOfOccurance.put(item, 1);
            } else {
                mapItemToNumberOfOccurance.put(item, mapItemToNumberOfOccurance.get(item) + 1);
            }
        }

        return mapItemToNumberOfOccurance;
    }

    private static <T> int compareMapForMatchingKeyAndValue(Map<T, Integer> map1, Map<T, Integer> map2) {
        Set<Map.Entry<T, Integer>> set1 = map1.entrySet();
        Set<Map.Entry<T, Integer>> set2 = map2.entrySet();

        Set<Map.Entry<T, Integer>> matchingSet = new HashSet<>(set1);

        matchingSet.retainAll(set2);

        return matchingSet.size();

    }

}

Test class:

package assign1;

import assign1.Appearances;
import static org.junit.Assert.*;
import org.junit.Test;

import java.util.*;

public class AppearancesTest {
    // utility -- converts a string to a list with one
    // elem for each char.

    private List<String> stringToList(String s) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < s.length(); i++) {
            list.add(String.valueOf(s.charAt(i)));
            // note: String.valueOf() converts lots of things to string form
        }
        return list;
    }

    @Test
    public void testSameCount1() {
        List<String> a = stringToList("abbccc");
        List<String> b = stringToList("cccbba");
        assertEquals(3, Appearances.sameCount(a, b));
    }

    @Test
    public void testSameCount2() {
        // basic List<Integer> cases
        List<Integer> a = Arrays.asList(1, 2, 3, 1, 2, 3, 5);
        assertEquals(1, Appearances.sameCount(a, Arrays.asList(1, 9, 9, 1)));
        assertEquals(2, Appearances.sameCount(a, Arrays.asList(1, 3, 3, 1)));
        assertEquals(1, Appearances.sameCount(a, Arrays.asList(1, 3, 3, 1, 1)));
    }

    @Test
    public void testSameCount3(){
        List<Double> a = Arrays.asList(2.2, 3.3, 4.4, 1.0, 4.4, 2.2, 3.3);
        assertEquals(1, Appearances.sameCount(a, Arrays.asList(2.2, 2.2, 3.3)));
    }
}