texts: Performance/Optimization of Knapsack(ish) algorithm for move generation for a game

texts:
I'm writing an AI for an italian Card game scopa http://en.wikipedia.org/wiki/Scopa And as part of it i need to generate all moves available to the user.

A move consists of finding cards in the centerboard that sum to a card in the players hand.

For example if I have a 5 in my hand and the center contains a [5,4,3,2,1,2] the possible moves would be:

pick up the 5 with my five

pick up the 4 and 1 with my five

pick up one of the twos and the three with my five

pick up the other tow and the three with my five

pick up both 2s and the 1 with my five

After profiling my code it shows that this is by far the most expensive part of the program (about 95 percent of execution time being spent here)

Can you see any way to optimize these methods?

this one actually generates all the possible moves.

private void generateMoves(Card myCard,ArrayList<Card> CurrentMove,
              ArrayList<Card> centerCards,ArrayList<Move> moves, int moveSum) {
    if(moveSum>myCard.value)
    {
        return;
    }
    else if(moveSum == myCard.value)
    {
        Move m = new Move(myCard, new ArrayList<>(CurrentMove));
        rateMove(m);
        moves.add(m);
        return;
    }

    for (Card card :centerCards) {
        if(!card.selected)
        {
            CurrentMove.add(card);
            card.selected = true;
            moveSum += card.value;
            generateMoves(myCard, CurrentMove, centerCards, moves, moveSum);
            moveSum -= card.value;
            CurrentMove.remove(card);
            card.selected = false;
        }
    }
}

this one removes any duplicates (the code above would return 4,1 and 1,4 as different moves from the example) I know its hacky but i couldn't think of anything that would be faster. Ideally they would be combined and duplicates would never be returned but i couldn't get it to work.

 protected void removeDuplicates(ArrayList<Move> moves)
{
    ArrayList<Move> temp = new ArrayList<>(moves);

    for(Move move : temp)
    {
        while(moves.remove(move));
        moves.add(move);
    }
}

Any suggestions would be appreciated.


texts: Setting a request header with or without Context in Golang

texts:
I have two ways (middleware) of setting a specific header (if not set) to request but want to know if one is better/beneficial than the other and the reasons why.

Note: At some point I will need to log X-Request-Id value in every single application log I have. If this plan affects your answer, I don't know. Just saying!

Context version

package middleware

import (
    "context"
    "github.com/google/uuid"
    "net/http"
)

type CtxKey string
const CtxReqIdKey CtxKey = "X-Request-Id"

func RequestId(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        CtxKey := req.Header.Get("X-Request-Id")
        if CtxKey == "" {
            CtxKey = uuid.New().String()
        }

        ctx1 := context.WithValue(req.Context(), CtxReqIdKey, CtxKey)
        ctx2 := req.WithContext(ctx1)

        handler.ServeHTTP(res, ctx2)
    })
}

# Elsewhere: request.Context().Value(middleware.CtxReqIdKey)

Without context version

package middleware

import (
    "github.com/google/uuid"
    "net/http"
)

func RequestId(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
        if req.Header.Get("X-Request-Id") == "" {
            req.Header.Set("X-Request-Id", uuid.New().String())
        }

        handler.ServeHTTP(res, req)
    })
}

Usage

err := http.ListenAndServe(":8080", middleware.RequestId(Router))


texts: (Python) Use IMAP lib to download attachments and email details

texts:
This is my first approach to programming in Python, so I hope you will "destroy" my coding!

Idea is to use SSL connection to my mailbox and use IMAP to download attachments from emails with particular subject (all have same one for time being). Beside downloading files I want to display given subject and corresponding UID. Next step will be to save that data (specially subject and corresponding UIDS) in XML file and retrieve to download needed files without extra searches and fetching.

import imaplib
import email.header
import os
import sys

# Your IMAP Settings
host = 'imap.host.com'
user = 'email@adrs.com'
password = 'passwd'

# Connect to the server
print('Connecting to ' + host)
mailBox = imaplib.IMAP4_SSL(host)

# Login to our account
mailBox.login(user, password)

boxList = mailBox.list()
# print(boxList)

mailBox.select()
searchQuery = '(SUBJECT "Desired Subject")'

result, data = mailBox.uid('search', None, searchQuery)
ids = data[0]
# list of uids
id_list = ids.split()

i = len(id_list)
for x in range(i):
    latest_email_uid = id_list[x]

    # fetch the email body (RFC822) for the given ID
    result, email_data = mailBox.uid('fetch', latest_email_uid, '(RFC822)')
    # I think I am fetching a bit too much here...

    raw_email = email_data[0][1]

    # converts byte literal to string removing b''
    raw_email_string = raw_email.decode('utf-8')
    email_message = email.message_from_string(raw_email_string)

    # downloading attachments
    for part in email_message.walk():
        # this part comes from the snipped I don't understand yet...
        if part.get_content_maintype() == 'multipart':
            continue
        if part.get('Content-Disposition') is None:
            continue
        fileName = part.get_filename()

        if bool(fileName):
            filePath = os.path.join('C:/DownloadPath/', fileName)
            if not os.path.isfile(filePath) :
                fp = open(filePath, 'wb')
                fp.write(part.get_payload(decode=True))
                fp.close()

    subject = str(email_message).split("Subject: ", 1)[1].split("\nTo:", 1)[0]
    print('Downloaded "{file}" from email titled "{subject}" with UID {uid}.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8')))

mailBox.close()
mailBox.logout()

Thanks in advance!


texts:
Problem Statement:

  Write a function to convert from normal numbers to Roman Numerals:
  e.g.

 1  => I
10  => X
 7  => VII

Code:

import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;

public class RomanNumeral {
  private final int number;
  private static final Map<Integer, String> CACHE = new HashMap<>();

  private static final NavigableMap<Integer, String> NUMBER_TO_ROMAN =
      initMap();

  public RomanNumeral(int number) {
    if (number < 0 || number > 3000) {
      throw new IllegalArgumentException("Number out of range.");
    }
    this.number = number;
  }

  public String getRomanNumeral() {
    if (number == 0) {
      return "";
    }
    String result = CACHE.get(number);
    if (result != null) {
      return result;
    }
    result = toRomen(number);
    CACHE.put(number, result);
    return result;
    //return number == 0 ? "" : toRomen(number);
  }

  private static String toRomen(int num) {
    int floorNum = NUMBER_TO_ROMAN.floorKey(num);
    // Base case
    if (floorNum == num) {
      return NUMBER_TO_ROMAN.get(num);
    }
    return NUMBER_TO_ROMAN.get(floorNum) + toRomen(num - floorNum);
  }

  private static NavigableMap<Integer, String> initMap() {
    NavigableMap<Integer, String> map = new TreeMap<>();
    map.put(1, "I");
    map.put(4, "IV");
    map.put(5, "V");
    map.put(9, "IX");
    map.put(10, "X");
    map.put(40, "XL");
    map.put(50, "L");
    map.put(90, "XC");
    map.put(100, "C");
    map.put(400, "CD");
    map.put(500, "D");
    map.put(900, "CM");
    map.put(1000, "M");
    return map;
  }
}

Test Suite:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.assertEquals;

@RunWith(Parameterized.class)
public class RomanNumeralsTest {

    private int input;
    private String expectedOutput;

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {0, ""},
                {1, "I"},
                {2, "II"},
                {3, "III"},
                {4, "IV"},
                {5, "V"},
                {6, "VI"},
                {9, "IX"},
                {27, "XXVII"},
                {48, "XLVIII"},
                {59, "LIX"},
                {93, "XCIII"},
                {141, "CXLI"},
                {163, "CLXIII"},
                {402, "CDII"},
                {575, "DLXXV"},
                {911, "CMXI"},
                {1024, "MXXIV"},
                {3000, "MMM"}
        });
    }

    public RomanNumeralsTest(int input, String expectedOutput) {
        this.input = input;
        this.expectedOutput = expectedOutput;
    }

    @Test
    public void convertArabicNumberalToRomanNumeral() {
        RomanNumeral romanNumeral = new RomanNumeral(input);

        assertEquals(expectedOutput, romanNumeral.getRomanNumeral());
    }
}

Design Discussion:

I have used TreeMap as the keys are ordered.
I played a bit with CACHING here since I didn't want to do the same computation again and again.

Reference:

http://exercism.io/exercises/java/roman-numerals/readme


texts:
Self explanatory, and all the functions contain descriptions of their specific problem statements.

Since this is project Euler, I would be particularly interested in any analysis of the functions' computational efficiency.

Option Explicit

Public Function ProjectEuler1() As Long

    '/ Problem statement: sum all multiples of 3 and 5 from 1 to 999

    Dim total As Long
    Dim i As Long

        For i = 1 To 999

            If i Mod 3 = 0 Or i Mod 5 = 0 Then

                total = total + i

            End If

        Next i

    ProjectEuler1 = total

End Function

Public Function ProjectEuler2() As Long

    '/ Problem statement: sum all even Fibonacci numbers below 4 Million

    Dim fiboA As Long, fiboB As Long, currentFibo As Long '/ alternating fibonacci numbers
    Dim bIsHigher As Boolean

        fiboA = 1
        fiboB = 1
        currentFibo = 2

    Dim total As Long

        Do While currentFibo < 4000000

            If currentFibo Mod 2 = 0 Then total = total + currentFibo

            If bIsHigher Then
                    fiboA = currentFibo
                Else
                    fiboB = currentFibo
            End If

            bIsHigher = Not bIsHigher

            currentFibo = fiboA + fiboB

        Loop

    ProjectEuler2 = total

End Function

Public Function ProjectEuler3(ByVal numToFactorise As Long) As Long

    '/ Problem statement: find the largest prime factor of <big number>
    '/ I decided to generalise it

    Dim i As Long
    Dim sqrtLimit As Long
    Dim partiallyFactorisedNum As Long
    Dim largestPrimeDivisor As Long

        sqrtLimit = Application.Floor(numToFactorise ^ 0.5, 1)
        partiallyFactorisedNum = numToFactorise

        i = 2
        If partiallyFactorisedNum Mod i = 0 Then
            largestPrimeDivisor = i
            partiallyFactorisedNum = KeepDividingWhileInt(partiallyFactorisedNum, i)
        End If

        i = 3
        Do While i <= sqrtLimit

            If isPrime(i) Then

                If partiallyFactorisedNum Mod i = 0 Then
                    largestPrimeDivisor = i
                    partiallyFactorisedNum = KeepDividingWhileInt(partiallyFactorisedNum, i)
                End If

            End If

            i = i + 2
            sqrtLimit = Application.Floor(partiallyFactorisedNum ^ 0.5, 1)
        Loop

    If partiallyFactorisedNum > largestPrimeDivisor Then largestPrimeDivisor = partiallyFactorisedNum
    ProjectEuler3 = largestPrimeDivisor

End Function

Public Function isPrime(ByVal numTocheck As Long)

    Dim i As Long
    Dim sqrtLimit As Long
        sqrtLimit = Application.Floor(numTocheck ^ 0.5, 1)

        isPrime = True

        If numTocheck Mod 2 = 0 And numTocheck <> 2 Then isPrime = False

        i = 3
        Do While i <= sqrtLimit And isPrime
            If numTocheck Mod i = 0 Then isPrime = False
            i = i + 2
        Loop

End Function

Public Function KeepDividingWhileInt(ByVal numToDivide As Long, ByVal divisor As Long) As Long

    Dim isDivisible As Boolean

        isDivisible = True
        Do While isDivisible
            If numToDivide Mod divisor = 0 Then
                    numToDivide = numToDivide / divisor
                Else
                    isDivisible = False
            End If
        Loop

    KeepDividingWhileInt = numToDivide

End Function


texts:
I have code which gives permutations for 10 lists. The code works fine for small number of lists with small number of values.

Result : It should return all possible permutations. I have to store the permutations instead of directly working on it and discarding.

As soon as I try for 10 lists, it errors out with OOM : heap space.

Can one of you suggest optimizations for this piece of code?

public static <T> Collection<List<T>> permutations(List<Collection<T>> collections) {
    if (collections == null || collections.isEmpty()) {
        return Collections.emptyList();
    } else {
        Collection<List<T>> result = Lists.newLinkedList();
        findPermutations(collections, result, 0, new LinkedList<T>());
        return result;
    }
}

private static <T> void findPermutations(List<Collection<T>> inputList, Collection<List<T>> outputList, int d, List<T> tempList) {
    if (d == inputList.size()) {
        outputList.add(tempList);
        return;
    }

    Collection<T> currentCollection = inputList.get(d);
    for (T currElement : currentCollection) {
        List<T> copy = Lists.newLinkedList(tempList);
        copy.add(currElement);
        findPermutations(inputList, outputList, d + 1, copy);
    }
}

@SuppressWarnings("unchecked")
public static <T> void main(String[] args) {

    List<Integer> list1 = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
    List<String> list2 = Lists.newArrayList("a", "s", "d", "f", "g", "h", "j", "k", "l", "m", "n", "b");
    List<Boolean> list3 = Lists.newArrayList(true, false, true, true, true);
    List<Integer> list4 = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
    List<String> list5 = Lists.newArrayList("a", "s", "d", "f", "g", "h", "j", "k", "l", "m", "n", "b");
    List<Boolean> list6 = Lists.newArrayList(true, false, true, true, true);
    List<Integer> list7 = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
    List<String> list8 = Lists.newArrayList("a", "s", "d", "f", "g", "h", "j", "k", "l", "m", "n", "b");
    List<Boolean> list9 = Lists.newArrayList(true, false, true, true, true);
    List<Boolean> list10 = Lists.newArrayList(true, false, true, true, true);

    long currentTime1 = System.currentTimeMillis();

    List<Collection<T>> finalList = Lists.newArrayList();
    finalList.add((Collection<T>) list2);
    finalList.add((Collection<T>) list1);
    finalList.add((Collection<T>) list3);
    finalList.add((Collection<T>) list4);
    finalList.add((Collection<T>) list5);
    finalList.add((Collection<T>) list6);
    finalList.add((Collection<T>) list7);
    finalList.add((Collection<T>) list8);
    finalList.add((Collection<T>) list9);
    finalList.add((Collection<T>) list10);

    Collection<List<T>> resultList = permutations(finalList);

    long currentTime2 = System.currentTimeMillis();

    long timeTaken = (currentTime2 - currentTime1);

    System.out.println("result is : " + resultList + "\n" + "size is : " + resultList.size() + "\n" + "time taken is : " + timeTaken);

}


texts:
This task is taken from www.interviewbit.com

  Given an array of integers, return the highest product possible by
  multiplying 3 numbers from the array

  Input:

array of integers e.g {1, 2, 3}

  Example:

[0, -1, 3, 100, 70, 50]

=> 70*50*100 = 350000

  NOTE: Solution will fit in a 32-bit signed integer

My approach: First sort the array, then return the maximum the following numbers: The product of the first two smallest numbers (because they could be negative) and the last number (largest) or the product of the three largest numbers.

My solution has a runtime of \$O(n \log n)\$ due to the sort and a space complexity of \$O(1)\$. I wonder whether there is a faster solution than \$O(n\log n)\$.

function highesProd(a) {
  a.sort((a,b) => a - b);
  return Math.max(a[0] * a[1] * a[a.length - 1], a[a.length - 3] * a[a.length - 2] * a[a.length - 1]);
}


texts: Convert string to double and check for errors

texts:
The following program converts a string to a double, and checks for errors.  It uses the strtod() function to do the conversion, and follows the example given for the strtol() function from the man page to do the error checking.

As an example, the program is executed as follows:

$ ./a.out 123.45

I would really appreciate any comments regarding the code, specifically whether there are any issues to be address or whether the code can be made more efficient or improved in any way.

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

int main(int argc, char *argv[])
{
    char *endptr, *str;
    double val;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s str\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    str = argv[1];

    errno = 0;    /* To distinguish success/failure after call */
    val = strtod(str, &endptr);

    /* Check for various possible errors */

    if ((errno == ERANGE && (val == DBL_MAX || val == -DBL_MAX))
            || (errno != 0 && val == 0.0)) {
        perror("strtod");
        exit(EXIT_FAILURE);
    }

    if (endptr == str) {
        fprintf(stderr, "No digits were found\n");
        exit(EXIT_FAILURE);
    }

    /* If we got here, strtod() successfully parsed a number */

    printf("strtod() returned %f\n", val);

    if (*endptr != '\0')        /* Not necessarily an error... */
        printf("Further characters after number: %s\n", endptr);

    exit(EXIT_SUCCESS);
}


texts:
I don't like this function. Looks too imperative.

It takes two sorted lists and returns a sorted intersection of the two lists. There is an implicit assumption that there are no duplicate elements in either list.

Please don't suggest converting (even one of) the arguments to set, or using some sort of library function. This is a single-pass O(n+m) time, O(1) auxiliary space algorithm, and I want to keep it that way.

def sorted_lists_intersection(lst1, lst2):

  i1 = 0
  i2 = 0
  len1 = len(lst1)
  len2 = len(lst2)

  intersection = []

  while i1 < len1 and i2 < len2:

    while lst1[i1] < lst2[i2]:
      i1 += 1
      if i1 == len1:
        return intersection

    while lst2[i2] < lst1[i1]:
      i2 += 1
      if i2 == len2:
        return intersection

    if lst1[i1] == lst2[i2]:
      intersection.append(lst1[i1])
      i1 += 1
      i2 += 1

  return intersection


texts: Logger module in child processes from os.fork()

texts:
I have had a hard time understanding all the documentation on the logger module and forking processes.

My goal is to have each child process that's worked to write to their own separate log file.

This seems to work but I just want to try and verify that this is the correct way.

import os
import logging

def generate_primes(number):
    logger = logging.getLogger(str(os.getpid()) + ':logger')

    for num in range(number + 1):
       # prime numbers are greater than 1
       if num > 1:
           for i in range(2,num):
               if (num % i) == 0:
                   break
           else:
               logger.info('child:' + str(os.getpid()) + ':' + str(num))

def start_workers():
    logger = logging.getLogger('parent:prime')
    logger.info('parent forking')

    for child in range(10):
        pid = os.fork()

        if not pid:

            logger = logging.getLogger('child:' + str(os.getpid()))
            fh = logging.FileHandler('logs/child_primes_' + str(os.getpid()) + '.log')
            logger.addHandler(fh)

            generate_primes(10000)

            os._exit(0)
        else:
            os.waitpid(pid, 0)

if __name__ == "__main__":

    logging.basicConfig(filename='logs/parent_primes.log', level=logging.INFO)
    logger = logging.getLogger('parent:prime')

    logger.info('Fork parent/child logging example.')
    logger.info('Starting children')

    start_workers()


texts:
I wrote this Pin class as a part of a project to learn SOLID. What do you think about it and what can be made better?

Interface

   public interface IAuthorization
    {
        bool Verify(object obj);
        void Change(object obj);
    }

Class

public class Pin : IAuthorization
    {
        private int _pin;

        public Pin(object pin)
        {
            _pin = ValidPin(pin);
        }

        public void Change (object pin)
        {
            _pin = ValidPin(pin);
        }

        public bool Verify (object pin)
        {
            return (_pin == ValidPin(pin));
        }

        private int ValidPin(object pin)
        {
            if (pin == null)
            {
                throw new ArgumentNullException("pin", "Pin must be exactly 4 digits long integer");
            }

            if (pin.ToString().Length != 4)
            {
                throw new ArgumentException("Pin must be exactly 4 digits long integer", "pin");
            }

            return Convert.ToInt32(pin);
        }
    }


texts: Array initialization inside function to be called repeatedly

texts:
I have written a Fortran95 function that will be called many times in a loop.  A much reduced version of it, called myFunction, is below.  Examples of its use is the fitting of data points to this function, or numerical integration of this function.  This function is part of a small module myFunctionCollection, which can be called from the user's main program.
My worry is that I am reinitializing the local variables arrayIn1, arrayIn2, ... arrayOut3 each time it is called during runtime, and will be unnecessarily slow down the whole calculation.  Is my worry unfounded?  Or, how can I rewrite this function inside the module so that it can more efficiently be called repeatedly, without reinitializing everything over and over again?
MODULE myFunctionCollection

USE bigFatPackage   ! contains bigFatSubroutine
IMPLICIT NONE

CONTAINS

DOUBLE COMPLEX FUNCTION myFunction(a,b,c,d)

  DOUBLE COMPLEX, INTENT(IN) :: a,b,c,d
  DOUBLE COMPLEX :: arrayIn1(7), arrayIn2(7), arrayIn3(7)
  DOUBLE COMPLEX :: arrayOut1(7), arrayOut2(7), arrayOut3(7)

  arrayIn1(1:7) = (/a, a+b, c, c+d, a+d, c+d, d**2/)
  arrayIn2(1:7) = (/a**2, a-b, c, c-d, a-d, dcmplx(0d0,0d0), d**2/)
  arrayIn3(1:7) = (/a**2, (a+b)**2, c, c, c, dcmplx(0d0,0d0),dcmplx(0d0,0d0)/)

  CALL bigFatSubroutine(arrayOut1, arrayIn1, 7, 7)
  CALL bigFatSubroutine(arrayOut2, arrayIn2, 7, 7)
  CALL bigFatSubroutine(arrayOut3, arrayIn3, 7, 7)

  myFunction = arrayOut1(6) + 2d0*arrayOut2(7) + (1/2d0)*arrayOut3(2) + !... more

END FUNCTION

END MODULE

Any further suggestions on coding style is welcome!


texts:
This is something that I initially came up with to protect a bunch of scripts on my personal webserver, but am now planning on using with a few public projects too.

login.php:

<?php
session_start();

//log out if ?logout=true
if($_GET["logout"]){
    $_SESSION["loggedIn"]=false;
    session_destroy();
    header('Location: '. $_SERVER['SCRIPT_NAME']);
    exit();
}

$password = '8f434346648f6b96df89dda901c5176b10a6d83961dd3c1ac88b59b2dc327aa4';

if(empty($_SESSION["loggedIn"])){
    if(isset($_POST["password"])){
        if(hash('sha256', $_POST['password'])===$password){
                session_regenerate_id(true);
                $_SESSION["loggedIn"]=true;
        } else{
            echo "Incorrect password!
";
        }
    }
}

if($_SESSION["loggedIn"] == true){
print '
    You are logged in!

    Logout

';
} else{
print '
Login

      <form action="#" method="post">
        Password: <input type="password" name="password">

      <input type="submit" value="Login!" />
    </form>
';
}
?>

For other files which should only be accessible if the user is logged in:

OtherFiles.php:

<?php
session_start();
if($_SESSION["loggedIn"]==false){
    session_destroy();
    header('Location: login.php');
    exit();
} else {
    //stuff goes here
}

Yes, I know, sha-256 hashes aren't recommended for password storage, but that's only for testing, when deployed it'll be using proper salting for password storage. What I need feedback on is the login script itself.


texts:
I'm looking for some code review of my usage of async. Mainly why this does not work without the done = this.async() method and why I don't have to invoke 'done()' on every request to download a file. This is working now but it is a bit of magic to me. Hoping to understand why it's working and if I'm abusing something.

   /*
   * grunt-esri-slurp
   * https://github.com/steveoh/grunt-esri-slurp
   *
   * Copyright (c) 2014 steveoh
   * Licensed under the MIT license.
   */

    'use strict';
    var fs = require('fs'),
    path = require('path'),

    async = require('async'),
    mkdirp = require('mkdirp'),
    request = require("request"),
    S = require('string'),

    unwind = require('./unwinder'),
    esriModules = require('./esriModules');

  module.exports = function(grunt) {
    grunt.registerTask('esri_slurp', 'download esri js api amd modules and create a package', function() {
      var options = this.options({
          packageLocation: 'src/esri/',
          version: '3.9'
        }),
        done = this.async();

      options.packageLocation = S(options.packageLocation).ensureRight('/').s;

      grunt.log.subhead('downloading esri version ' + options.version + ' modules');

      mkdirp.sync(options.packageLocation);

      var esriVersionBaseUrl = 'http://js.arcgis.com/' + options.version + 'amd/js/esri/';
      grunt.verbose.writeln('esri base url: ' + esriVersionBaseUrl);

      async.eachLimit(esriModules, 10, function(file, callback) {
        var subPath = file.substr(0, file.lastIndexOf('/') + 1),
          fileFolder = options.packageLocation + subPath,
          fileName = path.basename(file),
          httpUrl = esriVersionBaseUrl + subPath + fileName;

        if (!fs.existsSync(fileFolder)) {
          grunt.verbose.writeln(['creating folder ' + fileFolder]);

          mkdirp.sync(fileFolder);
        }

        grunt.verbose.writeln(['requesting ' + httpUrl]);

        request({
            uri: httpUrl,
            encoding: 'binary'
          },
          function(error, response, body) {
            if (body && body.length > 0) {
              grunt.verbose.or.write('.');
              grunt.verbose.writeln(['writing: ' + options.packageLocation + file]);

              var f = S(file);
              if (f.endsWith('.js') || f.endsWith('.css')) {
                body = unwind(body);
              }

              fs.writeFile(options.packageLocation + file, body, 'binary');
            }

            callback(error, body);
          });
      });
    });
  };


texts: Find if the string contains ALL the vowels

texts:
Problem:

  You are given a randoms string containing only lowercase letters
   and you need to find if the string contains ALL the vowels.

Input:

  First line contains N , the size of the string.
   Second line contains the letters (only lowercase).

Output:

  Print "YES" (without the quotes) if all vowels are found in the string, "NO" (without the quotes) otherwise.

Constraints:

  The size of the string will not be greater than 10,000
   1 ≤ N ≤ 10000

The above problem is from hackerearth.com and below is my attempt to solve this problem and I need your review on my codestyle, and efficiency and need your help to make it better.

public class TestClass {

public static void main(String[] args) throws IOException {

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    System.out.println("Enter the Length of the String");
    final int inputLength = Integer.parseInt(input.readLine());//the size of the string

    if (inputLength >= 10000) {
        System.err.println("The size of the string can not be greater than 10,000");
        System.exit(1);
    }

    System.out.println("Enter letters");
    String word = input.readLine().toLowerCase().trim();

    //remove all white space
    word = word.replaceAll(" ", "");

    final char[] vowels = {'a', 'e', 'i', 'o', 'u'};
    short found = 0;

    for (final char c : vowels) if (searchForVowel(c, word)) found++;

    String result = (found == vowels.length) ? "yes" : "no";

    System.out.println(result);
}

private static boolean searchForVowel(char vowel, String word) {
    final char[] chars = word.toCharArray();
    boolean isContains = false;

    for (char c : chars) {
        if (c == vowel) {
            isContains = true;
            break;
        }
    }

    return isContains;
  }

}


texts: Method for returning valid URLs from a sitemap URL

texts:
I need a method which fetches all of the text from a URL (generally a sitemap URL), and returns an IEnumerable of all valid URLs contained in the text returned from the initial address. What I have so far is:

public IEnumerable<Uri> GetSitemapUrls(Uri sitemapUrl)
{
    var sitemapText = GetSitemapText(sitemapUrl);

    if (string.IsNullOrWhiteSpace(sitemapText))
        yield break;

    var urls = new List<string>();

    var urlRegex = new Regex(@"\b(?:https?://|www\.)[^ \f\n\r\t\v\]]+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);

    foreach (Match m in urlRegex.Matches(sitemapText))
        urls.Add(CleanUriString(m.Value));

    foreach (var url in urls)
    {
        var cleanedUriString = CleanUriString(url);

        if (Uri.IsWellFormedUriString(cleanedUriString, UriKind.RelativeOrAbsolute))
            yield return new Uri(cleanedUriString);
    }
}

string GetSitemapText(Uri sitemapUri)
{
    var wc = new WebClient
    {
        Encoding = System.Text.Encoding.UTF8
    };

    return wc.DownloadString(sitemapUri);
}

string CleanUriString(string dirtyUriString)
{
    var legalCharacters = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=".ToCharArray();

    var cleanedString = dirtyUriString;

    foreach (var character in dirtyUriString)
    {
        var matchIndex = dirtyUriString.IndexOf(character);

        if (!legalCharacters.Any(x => x.Equals(character)) && matchIndex > 0)
            cleanedString = dirtyUriString.Substring(0, matchIndex);
    }

    return cleanedString;
}

It seems to work as intended for actual sitemaps, null/empty responses from the URL it receives, and URLs with URL-illegal characters in them. I have a feeling I'm missing out on potential issues or letting bad URLs through anyway, not to mention I haven't thought about spidering through URLs that the initial sitemap (if it is a sitemap) returns.

Is there anything I can do to improve it?


texts:
I've put together the code below, which creates a new sheet in my workbook and applies dynamically-named ranges and page-formatting.

Sub UniqueOverheads()

Set rOverheadsList = Range([B4], [B4].End(xlDown))
Set rOverheadsActuals = Range([C4], [C4].End(xlDown))
Set rOApr = Range([D4], [D4].End(xlDown))
Set rOMay = Range([E4], [E4].End(xlDown))
Set rOJun = Range([F4], [F4].End(xlDown))
Set rOJul = Range([G4], [G4].End(xlDown))
Set rOAug = Range([H4], [H4].End(xlDown))
Set rOSep = Range([I4], [I4].End(xlDown))
Set rOOct = Range([J4], [J4].End(xlDown))
Set rONov = Range([K4], [K4].End(xlDown))
Set rODec = Range([L4], [L4].End(xlDown))
Set rOJan = Range([M4], [M4].End(xlDown))
Set rOFeb = Range([N4], [N4].End(xlDown))
Set rOMar = Range([O4], [O4].End(xlDown))

    Worksheets.Add(after:=Worksheets(4)).Name = "Overheads"

    Range("B3").Select
    ActiveCell.FormulaR1C1 = "Overheads Code"
    With Selection.Interior
        .ColorIndex = 37
        .Pattern = xlSolid
    End With
    Selection.Font.Bold = True
    Cells.Select
    With Selection.Font
        .Name = "Lucida Sans"
        .Size = 10
        .Strikethrough = False
        .Superscript = False
        .Subscript = False
        .OutlineFont = False
        .Shadow = False
        .Underline = xlUnderlineStyleNone
        .ColorIndex = xlAutomatic
    End With

    ActiveWorkbook.Names.Add Name:="OverheadsList", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOverheadsList.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OverheadsActuals", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOverheadsActuals.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OApr", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOApr.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OMay", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOMay.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OJun", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOJun.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OJul", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOJul.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OAug", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOAug.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OSep", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOSep.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OOct", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOOct.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="ONov", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rONov.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="ODec", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rODec.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OJan", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOJan.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OFeb", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOFeb.Address(ReferenceStyle:=xlR1C1)

    ActiveWorkbook.Names.Add Name:="OMar", RefersToR1C1:="=" & _
    ActiveSheet.Name & "!" & rOMar.Address(ReferenceStyle:=xlR1C1)

End Sub

The code does work, but I'm a little concerned that it may be a little clunky and could be written smarter. I'm relatively new to VBA but I'm willing to learn.  I'm wondering if someone, who is perhaps a more seasoned programmer than myself, could look at this.  Please offer some guidance on how I may be able to write this a little better.


texts:
I just wrote this but I'm not sure if this is good practice.  Can someone give me advice as to whether it's good or how I can do better or even it's bad code?

The point is that I need a sub List-array-set of the enum.  The SubType.ELSE shall have another name in reality (I know that was a bad choice, but it's for pointing it out).

public enum ContentType {
    TITLE("$$title$$",SubType.MAIL),
    BODY("$$body$$",SubType.MAIL),
    MESSAGE("$$message$$",SubType.MAIL),
    EVENTS("$$events$$",SubType.ELSE);

    private final String replaceWord;
    private final SubType subType;

    private ContentType(String replaceWord, SubType subType ) {
        this.replaceWord = replaceWord;
        this.subType = subType;
    }

    public String getReplaceWord() {
        return replaceWord;
    }

    private SubType getSubType() {
        return subType;
    }

    public static List<ContentType> values(SubType subType) {
        List<ContentType> subList = new ArrayList<ContentType>();
        for (ContentType type : ContentType.values()) {
            if (type.getSubType() == subType) {
                subList.add(type);
            }
        }
        return subList;
    }
}

enum SubType {
    MAIL,
    ELSE;
}


texts: Copy a directory structure to another, but only copying specific files

texts:
script.py:

#!/usr/bin/python

import os

srcDir = os.getcwd()

dirName = 'target_directory'

dstDir = os.path.abspath(dirName)

def ignore_list(path, files):

    filesToIgnore = []

    for fileName in files:

        fullFileName = os.path.join(os.path.normpath(path), fileName)

        if (not os.path.isdir(fullFileName)
            and not fileName.endswith('pyc')
            and not fileName.endswith('ui')
            and not fileName.endswith('txt')
            and not fileName == '__main__.py'
            and not fileName == 'dcpp.bat'):

            filesToIgnore.append(fileName)

    return filesToIgnore

# start of script

shutil.copytree(srcDir, dstDir, ignore=ignore_list)

As shutil.copytree() has no option where I can give names for required files to copy like "ignore," I have modified the argument of ignore to give "required files to copy."

Review my code.


texts: JavaScript coding style for initializing variables

texts:
I've stripped most of the code and comments from what follows.

My question is about the style that it is written in, not about the correctness of the code itself.

In particular, I've never seen anyone use this way of defining and initializing variables.

The idea is to keep all the definitions together, but to attach and isolate the initialization code for each variable.
Ideally each section does nothing but initialize the named variable, with no side effects on anything else.

It works well for me, but want to know whether other people would find it too confusing.

"use strict"
if (typeof RB === 'undefined') var RB = {}
RB.tab = (function() {
   let tab_start = function(id, color1="#EFE", color2="#CDC", foldername="...") {
      let tabs = document.createElement("div"); {
         tabs.setAttribute("id", "tab_" + id)
      }
      let folder = document.getElementById(id); {
         folder.parentNode.insertBefore(tabs, folder)
         folder.appendChild(document.createElement("div"))
         folder.lastElementChild.innerHTML = "" + foldername
      }
      let c1, c2; {
         let get_rgb = function(color) {
            let value; {
               let temp = document.createElement("div")
               document.body.appendChild(temp)
               temp.style.color = color
               value = window.getComputedStyle(temp).getPropertyValue("color")
               document.body.removeChild(temp)
            }
            return value.substring(4, value.length-1).replace(/ /g, '').split(',')
         }
         c1 = get_rgb(color1)
         c2 = get_rgb(color2)
      }
      ...
   }
   ...
   return function(arg) {// RB.tab([ [id, color, color],...,[id, color, color] ])
      let url = new URL(location.href)
      ...
      window.onresize()
   }
}())


texts:
I had this interview question like a year ago and was asked to code, on a piece of paper, how to reverse each word of a string.  Since I am used to Java, I proposed the obvious answer of using split + reverse, which are native commands in Java.  I was then told I couldn't use those, so I floundered and ended up with a really terrible solution (even though it technically would've worked).

Anyway, it was bugging me lately, so I gave it a shot in straight C, which I am not very good at, so it took me a good while to actually get it working.

I was wondering:

Is this a good solution?
Have I forgotten anything obvious?
Have I done anything non-kosher in the C world?

Again, I'm not very good at C, so even small points will probably help me out.

#include <stdio.h>

void reverseString(char* start, char* end){
   while (start < end){
      char temp = *start;
      *start = *end;
      *end = temp;
      ++start;
      --end;
   }
}

char* word_start_index(char* p)
{
    while((*p != '\0') && (*p == ' ')){
        ++p;
    }

    if(*p == '\0')
        return NULL;
    else
        return p;
}

char* word_end_index(char* p)
{
    while((*p != '\0') && (*p != ' ')){
        ++p;
    }

    return p-1;
}

void main(){
    char arr[] = "kevin is a good programmer";
    char* test = arr;

    while (test != '\0'){
        char* curWordStart = word_start_index(test);
        if (curWordStart == NULL)
            break;
        char* curWordEnd = word_end_index(curWordStart);
        reverseString(curWordStart, curWordEnd);
        test = curWordEnd + 1;
    }
    printf("%s \n", arr);
}

Also, would taking a different approach, like in higher level languages of breaking the string into an array of strings (so I guess a 2D array of chars), then stepping through and reversing each one, be a good approach as well? I thought about this first and was unable to hash it out.


texts: POST variable analysis contains JSON format string PHP

texts:
I am verifying certain codes that work well and I don't know what else to optimize in them or what other tests to do: in this case it is a php script that takes the data of the $_POST variable analyzes them and converts them into an array, this is since in some cases the post field may contain a JSon string.

I leave a functional example where I have manually set the $_POST variable to do the Demonstration:

https://wtools.io/php-sandbox/bqsT

Original Code example:

<?php

#Example Array

$_POST = array(
    "valor1" => 1200,
    "valor2" => "texto",
    "valor3" => true,
    "valor4" => '{"seclvl_text":"datp","seclvl_boolean":"false"}',
);
#Validate Function for Json
function ValidateJson($Var) {
    if (!is_array($Var)) {
        return ((json_decode($Var) != null) AND (is_object(json_decode($Var)) OR is_array(json_decode($Var)))) ? true : false;
    } else {
        return false;
    }
}
#Parse Function
function buildVirtualData($data) {
    if (is_array($data)) {
        $result = [];
        foreach ($data as $key1 => $val1) {
            $valJson = ValidateJson($val1);
            if ($valJson) {
                $jsonObj       = json_decode($val1, true);
                $result[$key1] = buildVirtualData($jsonObj);
            } elseif ($valJson == false && is_array($val1)) {
                foreach ($val1 as $key2 => $val2) {
                    $result[$key1][$key2] = buildVirtualData($val2);
                }
            } else {
                if ($val1 === 'true') {
                    $val1 = true;
                } else if ($val1 === 'false') {
                    $val1 = false;
                }
                $result[$key1] = $val1;
            }
        }
        return $result;
    } else {
        if (ValidateJson($data)) {
            $jsonObj = json_decode($data, true);
            return buildVirtualData($jsonObj);
        } else {
            return $data;
        }
    }
}
# call to Function:
$data = buildVirtualData($_POST);
echo '<pre>';
echo var_dump($data);
echo '</pre>';

this parse have the feature that convert any text true or false to Boolean.


texts:
After creating a similar program in C++, I've decided to try to write it in x86 assembly language (the type of assembly I was taught in college).

I'd like to receive feedback regarding syntax and clarity.  The macros used here were provided by my college, so I don't think that's a concern.

%include "macros.s"

.DATA

num_lbl:   DB   "> Numbers (2): ", 0
gcd_lbl:   DB   "*** GCD: ", 0
lcm_lbl:   DB   "*** LCM: ", 0

num1:   DD   0
num2:   DD   0

num1_cpy:   DD   0
num2_cpy:   DD   0

gcd:   DD   0
lcm:   DD   0

.CODE
.STARTUP

xor       EAX, EAX
xor       EBX, EBX
xor       ECX, ECX
xor       EDX, EDX
xor       EDI, EDI
xor       ESI, ESI

main:
     nwln
     nwln
     PutStr   num_lbl
     nwln
     nwln
     GetLInt   [num1]
     GetLInt   [num2]

     mov   EAX, [num1]
     mov   [num1_cpy], EAX
     mov   EBX, [num2]
     mov   [num2_cpy], EBX

     call   calc_euclidean
     call   calc_lcm

     nwln
     PutStr   gcd_lbl
     PutLInt   [gcd]
     nwln
     PutStr   lcm_lbl
     PutLInt   [lcm]
     nwln

     .EXIT

calc_euclidean:
               mov   EAX, [num2]
               cmp   EAX, 0
               jne   chk_swap

               mov   EAX, [num1]
               mov   [gcd], EAX

               ret

calc_lcm:
         mov   EAX, [num1_cpy]
         mov   EDX, [num2_cpy]
         mul   EDX

         mov   EDI, EAX

         xor   EBX, EBX

         mov   EDX, EDI
         shr   EDX, 16
         mov   EAX, EDI
         mov   BX, [gcd]
         div   BX

         mov   SI, AX
         mov   [lcm], SI

         ret

chk_swap:
         mov   EAX, [num1]
         mov   EBX, [num2]
         cmp   EAX, EBX
         jl    swap

after_check:
            jmp   loop

swap:
     mov   EAX, [num1]
     mov   EBX, [num2]

     ; temp
     mov   ECX, [num2]

     ; num2 = num1
     ; num1 = temp
     mov   EBX, EAX
     mov   EAX, ECX

     mov   [num1], EAX
     mov   [num2], EBX

     jmp   after_check

loop:
     mov   EDX, [num1]
     shr   EDX, 16
     mov   EAX, [num1]
     mov   BX, [num2]
     div   BX

     mov   EDI, [num1]
     mov   ESI, [num2]
     mov   EDI, ESI
     mov   [num1], EDI
     mov   [num2], EDX

     jmp   calc_euclidean


texts: Outputting a standalone shell script from arguments

texts:
I am solving an exercise. Essentially, it's a shell script that takes in file and/or directory arguments and outputs another (standalone) shell script that outputs these files, including any directory structure associated with them.

Example usage:

bundle.sh dir1 dir2 file1 file2 file3 >unpack.sh

This expects that bundle.sh can be found in the PATH environment variable. If not, just run it like this:

`pwd`/bundle.sh dir file1 file2 >unpack.sh

Running unpack.sh should recreate everything.

Accepted limitations:

Only works for textual files
Files may not contain the line End of filename

Solution:

echo "# Run to unpack"
for i; do
    (cd $i 2>/dev/null &&
     echo "mkdir $i && cd $i" &&
     $0 * &&
     echo cd ..)
    cd $i 2>/dev/null || (
        echo echo `ls -l $i`
        echo "cat >$i <<'End of $i'"
        cat $i
        echo End of $i)
done

This is my solution for exercises 3-17 and 3-18 in the Unix Programming Environment by Brian W. Kernighan and Rob Pike. It works but I would appreciate any feedback. I will mention that the book has not yet covered conditional statements, globbing, etc. So I am trying to stick to what I've learned so far for now and might come back to it later.

One thing that I realize is that this doesn't deal with names that contain spaces. I have tried putting \"s around most $is (except for the ones in the echos, where it shouldn't matter) but that seems to make things worse. The other two is that I find my usage of cd to test for directories kind of a hack and the fact that I am not sure I am handling $0 correctly, which is why I made explicit requirements on how to run bundle.sh (maybe there is some way to make it better?). However, I am not interested in just these issues, I want feedback in general given my requirements and constraints. Even advice regarding to style may be valuable to me.


texts: Attaching an interrupt to a member function

texts:
I am making my own optical encoders. Each of them follows the exact same structure, so I figured I'd lump all the encoder processing in a class, StepCounter. However, when I directly attach an interrupt to a member function, I get

cannot convert 'StepCounter::step' from type 'void (StepCounter::)()' to type 'void (*)()'

Fair enough, a member method is different than a global method (however, maybe I can somehow cast it to a void(*)() by providing this?). So, I made the following solution (note: 18, 19 and 22, 23 are pin numbers, so assume that the naming convention makes any sense there):

class StepCounter {
  public:
    StepCounter(int pinInterrupt, int pinSecond, void (*wrapperFcn)(void)) :
      pinInterrupt(pinInterrupt),
      pinSecond(pinSecond) {
      pinMode(pinInterrupt, INPUT);
      pinMode(pinSecond, INPUT);
      stateSecond = digitalRead(pinSecond);
      attachInterrupt(digitalPinToInterrupt(pinInterrupt), wrapperFcn, CHANGE);
    };

    volatile int distance = 0;

    void step() {
      int newSecond = digitalRead(pinSecond);
      int stateXOR = digitalRead(pinInterrupt);
      // Direction is stateXOR * (stateSecond==newSecond)
      // if we take (-1,1) rather than (0,1) for (true,false)
      int  multiplier = (stateXOR == HIGH) ? -1 : 1;
      if (stateSecond == newSecond) {
        distance -= multiplier;
      } else {
        distance += multiplier;
      }
      stateSecond = newSecond;
    }

  private:
    const int pinInterrupt;
    const int pinSecond;
    volatile int stateSecond;

};

void interrupt1822(); // Forward declaration
void interrupt1923();

StepCounter stepCounter1822(18,22,interrupt1822),
            stepCounter1923(19,23,interrupt1923);

void interrupt1822() {
  stepCounter1822.step();
};
void interrupt1923() {
  stepCounter1923.step();
};

But, in all honesty, this looks rather clumsy with a bunch of forward declarations. And, although there is only so many interrupt pins on an Arduino, I still feel that copy-pasting so many things is something that should usually be avoided in programming.

Furthermore, I'm wondering whether there is any faster way of doing my step() function; since it's an interrupt service routine that I expect to be called a lot, I'd like it to be as fast as possible.


texts:
I need to convert my model to fit data in tableview cell finding better approach
My Model

class MyResponseModel {
    var question: String = ""
    var id: String = ""
    var answer: String = ""
    //Other variables also but not required to display
     init(fromDictionary dictionary: [String:Any]) {
        self.question = (dictionary["question"] as? String) ?? ""
        self.id = (dictionary["id"] as? String) ?? ""
        self.answer = (dictionary["answer"] as? String) ?? ""
    }
    //MARK: Converting model to cell data
    func toModel() -> MyTblCellDetail {
        return MyTblCellDetail(title:self.question,detail:self.answer)
    }
}
//MARK: Initialize cell data with custom model
struct MyTblCellDetail {
    var title: String = ""
    var detail: String = ""
    var isSelected:Bool = false

    init(title:String,detail:String) {
        self.title = title
        self.detail = detail
    }
    init(data:MyResponseModel) {
        self.title = data.question
        self.detail = data.answer
    }
}

Note: I am reusing same cell to display most of the data so i will use
the same method to converting all class model to MyTblCellDetail
struct

So my question is which is better way to do the same or any other approach i can use for the same. Thank you!


texts:
Python lacks dynamic unpacking. Example: You want to unpack a list, let's say coordinates, but don't know whether it contains 3 items or just 2.

x, y, z = [1,2,3] works only if len([x,y,z]) == len([1,2,3]).

x, y, z = [1,2] results in an error. You could add try and except blocks but that could be complicated.

The best option is z being None, as you can simply check using if n is None without any excessive try/except.

So expected result:

>>> x, y, z = unpack([1,2])
>>> print(x)
1
>>> print(y)
2
>>> print(z)
None

My code

def unpack(num, list):
    return_arr = [None] * num
    for i,elem in enumerate(list):
        return_arr[i] = elem
        if i+1 == num:
            return return_arr
    return return_arr

And usage examples:

a,b,c,d = unpack(4, [1,2,3])
print(a),
print(b),
print(c),
print(d),
print("\n")

e,f,g = unpack(3, [1,2,3])
print(e),
print(f),
print(g)

resulting in

1 2 3 None

1 2 3

You basically have to specify the amount of variables you're unpacking the list to, since the function can't know that.


texts: Dijkstra finding shortest path satisfying given constraints

texts:
The question is originated from Hackerrank.

  Suppose there are 1 to N stores in a city which are connected by
  bidirectional roads associated with traveling times. Each store sells
  some types of fishes (0 <= type_of_fish_store_i < K), in total K
  types of fishes are selling in the city. A cat starts at store 1 and
  traveling along some path puchases fishes at each store on the path.

  Calculate minimum time that satisfies the constraints

  the cat has to end at a specified store X
  the cat has to end with specified types of fishes in the basket

  Note: a store including the final destination can be visited more than once

  Shop and fish types selling at that shop ({shop:fish_type}):

{1: {1}, 2: {2}, 3: {3}, 4: {4}, 5: {5}}

  Adjacency matrix with cells filled with time cost (referring to
  cost_matrix):

[[0, 10, 10, 0, 0],
 [10, 0, 0, 10, 0],
 [10, 0, 0, 0, 10],
 [0, 10, 0, 0, 10],
 [0, 0, 10, 10, 0]]

Approach I've implemented:

def dijkstra(cost_matrix, start, wanted, end):
    """

    :param cost_matrix: adjacency matrix filled with time costs
    :param start: the store where the cat starts at
    :param wanted: types of fishes the cat wants at the end of journey
    :param end: the store where the cat ends at
    :return:
    """
    fish_basket = shop_and_fish[start]
    accum = 0
    h =[]
    visited = [start]

    while not (wanted.issubset(fish_basket) and start == end):
        for i, dist in enumerate(cost_matrix[start - 1]):
            if dist > 0:
                    heapq.heappush(h, [ accum + dist, i + 1, fish_basket | shop_and_fish[i + 1], visited + [i + 1]])
        # print("heap: ", h)
        accum, start, fish_basket, visited = heapq.heappop(h)
    print("Total time: ", accum, ", End store:", start, ", Fish types collected: ", fish_basket, ", Path: ", visited)
    return accum

Execute:

dijkstra(cost_matrix, 1, {1,2,3,4,5}, 5)
# this is saying the final accepted state is the cat
# at 5th store with {1,2,3,4,5} types of fishes in hand

Returns

50
# Total time:  50 , End store: 5 , Fish types collected:  {1, 2, 3, 4, 5} , Path:  [1, 2, 4, 5, 3, 5]

Problem

Efficiency. Expanding unnecessary nodes such as [1,2,1,2,1,2], in some other cases [1,2,3,4,3,2,1,2,3,4..], maybe some other unforeseen patterns. Any thoughts on how to eliminate them? I've tried palindrome, but it seems to add a lot of complexity as it examines every path and every subpath of that path. Moreover, if you've identified any other improvements, feel free to add to answer.


texts: Calculate EMI based on principal, rate, duration (month or years)

texts:
I am trying to create an EMI calculator for a loan. The problem description is:

Given a principal amount, rate of interest, monthly or quarterly installment terms and duration of loan in months/years and print EMI amount.
Input format:Principal, Rate of Interest per year, M/Q for Monthly or quarterly installment, duration of year in Year (Y) or Month (M)
Example Inputs:
10000, 12, M, 2Y: Principal = 10000, Rate of Interest = 12%, Monthly installment, Duration = 2 years
50000, 10.5, Q, 36M: Principal = 50000, Rate of Interest = 10.5%, Quarterly installment, Duration = 36 months

What are the flaws in this code? How can I perfect it?
def EMI_calculator(P,R , M,d):
#set rate of interest monthly
    print type(R)
    r= (R/(12.0 *100))
    print r
#chechk if monthly or quaterly installment
    if M== 'Q':
        x=4
    else:
        x=1

    if d[-1] =='Y':
        print "duration in years"
        n = d[0:(len(d)-1)]
        print n
        m = 12 *int(n)
        print m
    elif d[-1] =='M':
        print "duration is in months"
        n = d[0:(len(d)-1)]
        print n
        m = 1 *int(n)
        print m

    EMI = x*(P*r*(1+r)**m)//((1+r)**m - 1)
    return EMI

print EMI_calculator(10000,12,'Q','3Y')


texts:
I wrote a program that replaces tabs with spaces. First, I defined a maximum length of an input string in the constant MAX_LIMIT. Next, I declared the procedure detab that takes two arguments: an input string and a maximum length. In the procedure I read characters until encountering EOF. I'm replacing tabs with four spaces and I'm checking if index is equal to limit, and if yes, then I break the loop. Finally, I created a str character array. I called on it the detab procedure and I printed out the value of str in main.

main.c

#include <stdio.h>
#define MAX_LIMIT 1000

void detab(char str[], int limit);

int main(void) {
    char str[MAX_LIMIT];
    detab(str, MAX_LIMIT);
    printf("%s", str);
    return 0;
}

void detab(char str[], int limit) {
    char current;
    int index = 0;
    int stop = 0;
    while ((current = getchar()) != EOF) {
        if (stop) {
            break;
        }
        if (current == '\t') {
            for (int i = 0; i < 4 && !stop; i++) {
                if (index == limit) {
                    stop = 1;
                } else {
                    str[index++] = ' ';
                }
            }
        } else {
            str[index++] = current;
        }
    }
}

How can I improve this program? Is it an optimal solution of this problem?


texts: Create variable and use in one stored procedure

texts:
This finds a value via a stored procedure then runs a second process in the same stored procedure rather than calling a second stored procedure.

When a call is 'simple' i.e. not Where x y then... I keep the stored procedure, even when I need to get a variable, in the same procedure.

I'd like to see if the concept that works is the best concept, has any bad habits or can be improved.

USE [Database]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[GetImage]
(
-- Add the parameters for the function here
@SiteID varchar(100)
)
-- Is the below required?
RETURNS varchar(100)
AS
BEGIN
 -- Declare the return variable here
--We limit the length of the image name on import of images
DECLARE @SiteImage varchar(100)
--Client changes visible ID so we thus need to find 'Database ID' (SiteID)
DECLARE @SiteIDOriginal varchar(100)
-- Add the T-SQL statements to compute the return value here
--Get 'Database' ID
SELECT [@SiteIDOriginal] = SiteID FROM TblPropertyDetails WHERE ClientsSiteID=[@SiteID]
--Find the ImageName based on the Original ID (Database ID)
SELECT @SiteImage = ImageName FROM TblImages WHERE SITEID = @SiteIDOriginal
-- Return the result of the function
RETURN @SiteImage

END


texts: Generic function, which populates a collection based on collection interface implementation

texts:
As the above title states I have a function that I use to populate a collection's status names, currency names and other information that I do not store in the database.

This is my function:

    public static List<T> PopulateStatusNames<T>(List<T> items) where T : class
    {

        if (typeof(IStatusResult).IsAssignableFrom(typeof(T)))
        {
            Dictionary<int, string> statuses = new Dictionary<int, string>();

            if (typeof(IActivityStatusResult).IsAssignableFrom(typeof(T))) statuses = GlobalConstants.GetActivityStatuses();
            if (typeof(IPurchaseStatusResult).IsAssignableFrom(typeof(T))) statuses = GlobalConstants.GetPurchaseStatuses();
            if (typeof(IQuotationStatusResult).IsAssignableFrom(typeof(T))) statuses = GlobalConstants.GetQuotationStatuses();
            if (typeof(IInvoiceStatusResult).IsAssignableFrom(typeof(T))) statuses = GlobalConstants.GetInvoiceStatuses();

            foreach (var item in items.OfType<IStatusResult>())
            {
                item.StatusName = statuses[item.Status];
            }
        }

        if (typeof(ICurrencyResult).IsAssignableFrom(typeof(T)))
        {
            Dictionary<int, string> currencies = GlobalConstants.GetCurrencies();

            foreach (var item in items.OfType<ICurrencyResult>())
            {
                item.CurrencyName = currencies[item.Currency];
            }
        }

        return items;
    }

So if a collection implements an interface of type IStatusResult I look up the approapriate status names and loop through the collection to set the status name.

As you also notice in the above that I loop through my collection twice because if  my collection implements another type of interface I need to get a different set key value pairs so that I can look up the name

Is there a way to re-write the below function to populate status names, currency names in a single for loop

Sample POCO that implement these interfaces

Invoice:

public class InvoiceSearchResult : IInvoiceStatusResult, ICurrencyResult
{
    public int Id { get; set; }
    public string InvoiceNo { get; set; }
    public DateTime InvoiceDate { get; set; }
    public string Project { get; set; }
    public string Location { get; set; }
    public string Customer { get; set; }
    public int Currency { get; set; }
    public string CurrencyName { get; set; }
    public int Status { get; set; }
    public string StatusName { get; set; }
    public decimal Subtotal { get; set; }
    public decimal TotalTax { get; set; }
    public decimal Total { get; set; }
}

Location:

public class LocationSearchResult : IActivityStatusResult
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Status { get; set; }
    public string StatusName { get; set; }
}

So as you can see I have a different combination of collections that implement these interfaces, based on the interfaces I am trying to figure out what needs to be populated


texts: Keeping groups based on the row count of a second column

texts:
I have the following code that aims to filter those pid (1 and 4) that have at least before_threshold (2) rows with a value of before in the day_type column and at least after_threshold (2) rows with a value of after in the same day_type column.

Is there a more succinct way of doing this using the tidyverse packages?

library(tidyr)

before_threshold = 2
after_threshold = 2
data <- data.frame(pid = c(rep("1", 5), rep("2",5), rep("3", 1), rep("4", 4)),
                   day_type = c(rep("before", 3), rep("after", 2), rep("before", 5), rep("after", 1), rep("before", 2), rep("after", 2)),
                   stringsAsFactors = F)

data <- data %>%
  group_by(pid) %>%
  add_count(pid, day_type) %>%
  mutate(count_before = ifelse(day_type == "before", n, NA),
         count_after = ifelse(day_type == "after", n, NA)) %>%
  fill(count_before, .direction = "downup") %>%
  fill(count_after, .direction = "downup") %>%
  filter(count_before >= before_threshold & count_after >= after_threshold)

print(data)


texts: Optimizing Laravel Eloquent multiple joins

texts:
The following is working and readable SQL for Eloquent that I have created. The downside is that it looks more like a 1:1 with SQL and I don't think I'm using the full potential of Eloquent. I thought of using scope queries to shorten it, but for some reasons the selectRaw prevents it (due to multiple join variable scopes).

Data is scattered across three tables and modifying the tables is not an option.

Notes:

$genreIdList is an array of IDs,
$limit is the max number of results requested,
$offset is the starting point of the pull,
selectRaw is necessary as the selected columns are needed.

Here is the original SQL:

SELECT
b.title,
GROUP_CONCAT(DISTINCT(g.name) ORDER BY relevancy, g.name ASC SEPARATOR ' ') as genre_list,
GROUP_CONCAT(DISTINCT CAST(relevancy as char) ORDER BY relevancy ASC SEPARATOR ',') as genre_relevancy,
bg.book_id
FROM book_genres bg
INNER JOIN genre_book g ON bg.genre_id = g.id AND g.id IN (". (($genreIdList) ? $genreIdList : 0) . ")
INNER JOIN book b ON bg.book_id = b.id
INNER JOIN licensors l ON b.licensor_id = l.id
WHERE b.status = 'active' AND b.premium = 'yes' AND l.status = 'active'
GROUP BY bg.book_id

This is the PHP/Eloquent version:

    $relatedBooks = Book::selectRaw("book.title,
        GROUP_CONCAT(DISTINCT(gb.name) ORDER BY bg.relevancy, gb.name ASC SEPARATOR ' ') as genre_list,
         GROUP_CONCAT(DISTINCT CAST(bg.relevancy as char) ORDER BY bg.relevancy ASC SEPARATOR ',') as genre_relevancy,
         bg.book_id ")
        ->join('book_genres AS bg', 'bg.book_id', '=', 'book.id')
        ->join('genre_book AS gb', 'gb.id', '=', 'bg.genre_id')
        ->join('licensors AS l', 'l.id', '=', 'book.licensor_id')
        ->whereIn('gb.id', $genreIdList)
        ->where('book.premium', '=', 'yes')
        ->where('book.status', '=', 'active')
        ->where('l.status', '=', 'active')
        ->take($limit)
        ->offset($offset)
        ->get();


texts: Send Opencv::Mat image from Qt application to HTML client, using websocket

texts:
I wrote an application in C++ using Qt 5.7, basically is a websocket server, using qwebsocket for this, capable to send an image elaborated with OpenCV to an HTML client.

In order to do this I encode the image in base64, transmit it and on the client put the encoded string in the src of an image tag.

SERVER

imgIn = cv::imread("/home/me/color.png", CV_LOAD_IMAGE_UNCHANGED);
std::vector<uchar> buffer;
cv::imencode(".png",imgIn,buffer);
std::string s = base64_encode(buffer.data(),buffer.size());
pClient->sendTextMessage(QString::fromStdString(s));

CLIENT

<img id="ItemPreview" src="" style="border:5px solid black" />

websocket.onmessage = function (evt) {
console.log( "Message received :", evt.data );
document.getElementById("ItemPreview").src = "data:image/png;base64," + evt.data;
};

The images comes from a video elaboration, I extract frames, do some image processing and send them to view in the HTML client the video. When computation arises, or the client is remote (but same wifi network) I experience some lag, the video is not smooth.

Is there a better way to transmit images over websocket? Maybe using some other technique than base64 encoding to reduce the data transmitted and the computation speed.

I know TCP protocol used by websocket is not ideal to stream videos as UDP would be preferred to avoid lags, but since the images are small (320*240 ~ 100kb) I would try this way.


texts: Calculator for the price of a team of ninjas and samurai

texts:
var addToTeam = document.getElementsByClassName('addToTeam'),
    parentElement = document.getElementsByClassName('playerTypeBlock'),
    playerName = document.getElementsByClassName('heading'),
    totalVal = document.getElementById('totalvalue'),
    tableBody = document.querySelector('.totalPlayers');

var updatePlayers = function (evt) {

    evt.preventDefault();

    var amount = totalVal.innerHTML,
        productId = this.parentElement.getAttribute('data-player-type-id'),
        productPrice = this.parentElement.getAttribute('data-player-value'),
        playerName = this.parentNode.querySelector('.heading').innerHTML,
        playerId = $(this).parent().data('playerTypeId'),
        updateTotal = parseFloat(amount) + parseFloat(productPrice);

    var quantity = parseInt($(this).data('click'), 10) || 0;
    quantity++;
    $(this).data('click', quantity);

    totalVal.innerHTML = Math.round(updateTotal * 100) / 100;

    if (quantity > 1) {
            $('table .totalPlayers').find('#player-' + playerId + ' .quantity').text(quantity);

    }
    else {
        $('table .totalPlayers').append('
' + playerName + '	' + quantity + '
');
    }

};

for (var i = 0; i < addToTeam.length; i++) {
    addToTeam[i].addEventListener('click', updatePlayers);
}

Ninja

$10
 Add player

Samurai

$20.25
 Add player

            Players
            Quantity

 Total: $
 0.00

It looks like any additional functionality I want to add would have to go through updatePlayers function like for instance if I wanted to remove a player that removePlayer function would need to be inside the updatePlayers function too and If I had a hundred players on the page I would be attaching event listeners to each of them.

Although this works fine, I want to know if there are any OOP techniques I can use to make my code more scalable and extensible?

SEE DEMO


texts:
Is this a proper C# implementation of the Fisher–Yates shuffle?

//Fisher–Yates shuffle en.wikipedia.org/wiki/Fisher–Yates_shuffle
//for i from 0 to n−2 do
//j ← random integer such that i ≤ j < n
//exchange a[i] and a[j]
int count = 52;
int[] deck = new int[count];
for (byte i = 0; i < count; i++)
    deck[i] = i;
Random rand = new Random();
// next(max) Returns a non-negative random integer that is less than the specified maximum.
for (byte i = 0; i <= count - 2; i++)
{
    int j = rand.Next(count - i);
    if (j > 0)
    {
        int curVal = deck[i];
        deck[i] = deck[i+j];
        deck[i+j] = curVal;
    }
}
//suffle the other directinon to be sure
//for i from n−1 downto 1 do
//j ← random integer such that 0 ≤ j ≤ i
//exchange a[j] and a[i]
for (int i = count - 1; i >= 1;  i--)
{
    int j = rand.Next(i + 1);
    if (j != i)
    {
        int curVal = deck[i];
        deck[i] = deck[j];
        deck[i] = curVal;
    }
}


texts: Move files to specific directory, according to file extension

texts:
I've written the following script

import shutil,os,glob

# setting up destination folders

PYDEST = "/home/ubuntu/python-scripts/python-test"

TEXTDEST = "/home/ubuntu/python-scripts/texte-test"

def move8files(pwd):
    PWD = pwd + "*"
    for files in glob.glob(PWD):
        if files.endswith(".txt"):
            print(files)
            shutil.move(files,TEXTDEST)
        elif files.endswith(".py"):
            shutil.move(files,PYDEST)

move8files("/home/ubuntu/python-scripts/")

Questions/Issues are the following:

How can I make it simpler, especially by using the os.listdir but with having the pathname (listdir does not give pathname)?
Would it be possible to include a part in my script, where instead of saying which folders are for python or text files, it will look syntaxically at specific folders containing words like python or texte in it?
What can I improve in my script, for better performance?


texts:
I need to batch messages when pushing them, where multiple threads do the publishing. What could be a better way of doing this?

private String[] eventArr = new String[100];

private int idx = 0;

private final Semaphore publish = new Semaphore(100, true);
private final Semaphore turnstile = new Semaphore(1, true);

public void publish(String data){
    try {
        boolean acquired = publish.tryAcquire();
        if(acquired) {
            storeData(data);
        }else{
            publishToTarget();
            publish.acquire();
            storeData(data);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

private void storeData(String data) throws InterruptedException {
    turnstile.acquire();
    eventArr[idx] = data;
    idx++;
    turnstile.release();
}

private void publishToTarget() throws InterruptedException {
    if(turnstile.tryAcquire()) {
        //TODO publish everything here
        publish.release(idx);
        idx=0;
        turnstile.release();
    }
}


texts:
After poking around in some areas of python, I've decided to try Pygame. After about two hours of coding, this is what I came up with:

import pygame
import time
import random
pygame.init()
pygame.font.init()

WINDOW = pygame.display.set_mode((500, 500))

pygame.display.set_caption('snake')

FOOD_COORS = []

TICK = 15

RUN = True
SNAKE_COMP = [[50, 50, 2], [40, 50, 2], [30, 50, 2], [20, 50, 2], [10, 50, 2]]
f = [random.randint(0, 50)*10, random.randint(0, 50)*10]
d = 2
CLOCK = pygame.time.Clock()

def hit():
    time.sleep(3)
    pygame.quit()

class snake():
    def __init__(self, SNAKE_COMP):
        self.x, self.y = SNAKE_COMP[0][0:2]
    def draw(self, SNAKE_COMP):
        self.SNAKE_COMP = SNAKE_COMP
        for i in range(0, len(SNAKE_COMP)):
            pygame.draw.rect(WINDOW, (255, 255, 255), (SNAKE_COMP[i][0], SNAKE_COMP[i][1], 10, 10))

    def hit_check(self, SNAKE_COMP):
        self.SNAKE_COMP = SNAKE_COMP
        if SNAKE_COMP[0][0] >= 500 or SNAKE_COMP[0][0] < 0:
            hit()
        if SNAKE_COMP[0][1] >= 500 or SNAKE_COMP[0][1] < 0:
            hit()
        test_l = [[]]
        for i in range(0, len(SNAKE_COMP)):
            test_l.append(tuple(SNAKE_COMP[i][0:2]))
        for i in range(0, len(test_l)):
            if test_l.count(test_l[i]) > 1:
                hit()

class food():
    global FOOD_COORS
    def draw(self):
        x, y = self.x, self.y
        pygame.draw.rect(WINDOW, (255, 255, 255), (x, y, 10, 10))
    def spawn(self, SNAKE_COMP):
        global FOOD_COORS
        self.SNAKE_COMP = SNAKE_COMP
        test_l = [[]]
        for i in range(0, len(SNAKE_COMP)):
            test_l.append(SNAKE_COMP[i][0:2])
        g = True
        while g:
            x = random.randint(0, 49)*10
            y = random.randint(0, 49)*10
            if [x, y] not in test_l:
                g = False
        FOOD_COORS = [x, y]
        self.x, self.y = x, y
snek = snake(SNAKE_COMP)
apple = food()
apple.spawn(SNAKE_COMP)
s = False
g = False
while RUN:
    CLOCK.tick(TICK)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            RUN = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP] and d != 3:
        d = 1
    elif keys[pygame.K_RIGHT] and d != 4:
        d = 2
    elif keys[pygame.K_DOWN] and d != 1:
        d = 3
    elif keys[pygame.K_LEFT] and d != 2:
        d = 4
    if g != True and SNAKE_COMP[0][0:2] != FOOD_COORS:
        last = len(SNAKE_COMP) - 1
        for i in range(1, len(SNAKE_COMP)):
            SNAKE_COMP[len(SNAKE_COMP)-i][2] = SNAKE_COMP[len(SNAKE_COMP)-i-1][2]
        SNAKE_COMP[0][2] = d
        for i in range(0, len(SNAKE_COMP)):
            if SNAKE_COMP[i][2] == 1:
                SNAKE_COMP[i][1] -= 10
            elif SNAKE_COMP[i][2] == 2:
                SNAKE_COMP[i][0] += 10
            elif SNAKE_COMP[i][2] == 3:
                SNAKE_COMP[i][1] += 10
            elif SNAKE_COMP[i][2] == 4:
                SNAKE_COMP[i][0] -= 10
    else:
        k = SNAKE_COMP[0][2]
        FOOD_COORS.append(k)
        if k == 1:
            FOOD_COORS[1] -= 10
        elif k == 2:
            FOOD_COORS[0] += 10
        elif k == 3:
            FOOD_COORS[1] += 10
        elif k == 4:
            FOOD_COORS[0] -= 10
        SNAKE_COMP.insert(0, FOOD_COORS)
        apple.spawn(SNAKE_COMP)
    snek.hit_check(SNAKE_COMP)
    apple.draw()
    snek.draw(SNAKE_COMP)
    pygame.display.update()
    WINDOW.fill((0, 0, 0))

pygame.quit()

I definitely thinks this can be improved, just not sure how.


texts:
It's my university task. Can I get some opinions on it?

#include <iostream>
#include <vector>

using namespace std;

string toBinary(short n) {
   string r;
   while(n != 0) {
      r = ( n % 2 == 0 ? "0" : "1" ) + r;
      n /= 2;
   }
   return r;
}

int has_even_parity(int c) {
   int k = 0;
   if (c != 0)
      k++;
if ((c & 0x2) >> 1 == 1)
    k++;
if ((c & 0x4) >> 2 == 1)
    k++;
if ((c & 0x8) >> 3 == 1)
    k++;
if ((c & 0x10) >> 4 == 1)
    k++;
if ((c & 0x20) >> 5 == 1)
    k++;
if ((c & 0x40) >> 6 == 1)
    k++;
if ((c & 0x80) >> 7 == 1)
    k++;
 return k % 2;
}

char decode(short int a) {
  char result;
  unsigned short int mask = 0b0111111110000000;
  return (char)((a & mask) >> 7);
}

int main() {
short int result[64];
string str;
vector<string> text_list;

for (int i = 0; i < 8; i++) {
    getline(cin, str);
    text_list.push_back(str);
}
cout << endl;
int k = 0;

for (int i = 0; i < text_list.size(); i++) {
    string l = "";
    for (int j = 0; j < text_list[i].size(); j++) {
        short int c_ = text_list[i][j];
        short int l_ = 0b0000000;
        c_ = l_ | c_;
        result[k] = (short) has_even_parity(c_);
        result[k] = result[k] << 8;
        result[k] = result[k] | c_;
        result[k] = result[k] << 1;
        c_ = (short) (has_even_parity(i) ^ has_even_parity(j));

        result[k] = result[k] | c_;
        result[k] = result[k] << 3;
        result[k] = (short) (result[k] | i);

        result[k] = result[k] << 3;
        result[k] = (short) (result[k] | j);

        l += decode(result[k]);
        k++;
    }
    cout << l << endl;
}

return 0;
}

I have input as text 8 letters x 8 lines, 2 bytes for one letter.

In bit 0-2 number of line
In bit 3-5 number of position in line
In bit 6 parity bit of 1) and 2)
In bit 7-14 ASCII code of letter
In bit 15 parity bit of 4)

And after, decode letter.


texts:
I'm making a GUI system in Python for game development with PyGame. Right now I have a button that changes colors when you hover and click on it. My question is, is this code well designed or can it be improved?

game.py

import sys, pygame
from pygame.locals import *
from gui import *

def input(events):
    for e in events:
        if e.type == QUIT:
            pygame.quit()
            sys.exit()

pygame.init()
pygame.display.set_caption("GUI Demo")

window = pygame.display.set_mode((640, 480))
screen = pygame.display.get_surface()
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
button = Button("btn_1", "Hello World", 50, 50, 200, 120)

button.decorate((255, 0, 0), (0, 255, 0), (0, 0, 255))

while True:
    screen.fill((120, 40, 200))
    input(pygame.event.get())
    button.update(pygame.mouse.get_pos(), pygame.mouse.get_pressed())
    button.draw(screen)
    pygame.display.flip()

gui.py

# Mini-GUI demo

import pygame

BUTTON_NORMAL = 0
BUTTON_HOVER = 1
BUTTON_ACTIVE = 2

class Surface:
    def __init__(self, x, y, w, h, color):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.color = color

    def collides(self, surface):
        return self.y < surface.top + surface.height and self.y + self.h > surface.top and self.x < surface.left + surface.width and self.x + self.w > surface.left

    def getCoords(self):
        return (self.x, self.y)

    def draw(self, surface):
        pass

class GUIElement(Surface):
    def __init__(self, id, x, y, w, h, color):
        super(GUIElement, self).__init__(x, y, w, h, color)
        self.id = id

class Textbox(GUIElement):
    def __init__(self, id, x, y, w, h, color):
        super(Textbox, self).__init__(id, x, y, w, h, color)
        self.data = ""

    # TODO: update and draw

class Button(GUIElement):
    def __init__(self, id, text, x, y, w, h):
        super(Button, self).__init__(id, x, y, w, h, None)
        self.text = text
        self.font = pygame.font.Font(None, 32)
        self.state = BUTTON_NORMAL
        self.normalColor = None
        self.hoverColor = None
        self.activeColor = None

    def decorate(self, normalColor, hoverColor, activeColor):
        self.normalColor = normalColor
        self.hoverColor = hoverColor
        self.activeColor = activeColor
        self.color = self.normalColor

    def update(self, mouseCoords, mousePressed):
        (up, down, middle) = mousePressed
        if len(mouseCoords) < 4: mouseCoords = pygame.Rect(mouseCoords[0], mouseCoords[1], 1, 1)

        if not self.collides(mouseCoords):
            self.state = BUTTON_NORMAL
            self.color = self.normalColor
            return

        if up:
            self.state = BUTTON_ACTIVE
            self.color = self.activeColor
        else:
            self.state = BUTTON_HOVER
            self.color = self.hoverColor

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, pygame.Rect(self.x, self.y, self.w, self.h))
        surface.blit(self.font.render(self.text, 1, (255, 255, 255)), self.getCoords())


texts: Keeping a search history in localStorage, with a length limit

texts:
I'm having a problem figuring out how I can make this particular part of my code DRY. Currently, the code is repeating itself but with minor changes in each case of a switch.

SearchParam is a string that the user has searched for in the application that this code is from. The function creates a new li element with searchParam as the text. This value is then added to localStorage as 'search1'. Dependent on how many li elements there are already, the function uses a switch to add the new li element to the beginning of the list. If there are already 3 items, then the last item in the list will be deleted and removed.

function searchHistory(searchParam) {
  var liElements = $('#history').children();
  var recentSearch = liElements.first();

  var newItem = `

${searchParam}

  `;

  switch($('#history').children().length) {
     case 0:
        $('#history').append(newItem);
        localStorage.setItem('search1', searchParam);
        break;

     case 1:
        var secondSearch = liElements.children()[1].innerHTML;

        recentSearch.before(newItem);
        localStorage.setItem('search1', searchParam);
        localStorage.setItem('search2', secondSearch);
        break;

     case 2:
        var secondSearch = liElements.children()[1].innerHTML;
        var thirdSearch = liElements.children()[3].innerHTML;

        recentSearch.before(newItem);
        localStorage.setItem('search1', searchParam);
        localStorage.setItem('search2', secondSearch);
        localStorage.setItem('search3', thirdSearch);
        break;

     default:
        var oldSearch = liElements.last();
        var secondSearch = liElements.children()[1].innerHTML;
        var thirdSearch = liElements.children()[3].innerHTML;

        localStorage.setItem('search1', searchParam);
        localStorage.setItem('search2', secondSearch);
        localStorage.setItem('search3', thirdSearch);

        recentSearch.before(newItem);
        oldSearch.remove();
  }
};


texts: Printing twin primes less than a given natural number n

texts:
I have two programs doing this task correctly, but at first I'm not sure if the code is correct (I mean absence of not efficient and superfluous pieces of the code). Then, I can't choose which one is better and smarter. Couldn't you do it for me?

First:

int n, p, q;

scanf_s("%d", &n);

p = 1;
q = 2;

char flag = 1;

while (q < n)
{
    flag = 1;
    for (int i = 2; i <= sqrt(q); i++)
    {
        if (q%i == 0)
        {
            flag = 0;
            break;
        }
    }
    if (flag)
    {
        if (q - p == 2)
        printf("%d %d\n", p, q);
        p = q;
    }
    q++;
}

Second:

int n=0, p=3, q=5, f = 0;
    scanf("%d", &n);
    while (q < n)
    {
        f = 1;
        for (int i = 2; i <= p / 2; i++)
            if (p%i==0) { f = 0; break; }

        for (int i = 2; i <= q / 2; i++)
            if (q%i == 0) { f = 0; break; }

        if (f) printf("p = %d, q = %d\n", p, q);
        p++;
        q++;
    }


texts: Python - Split nth occurence of a character in string

texts:
I needed this function for a project I'm currently working on. I think there is definitely a way to make this prettier and have tickle more performance out of it, but how?

def nthofchar(string: str, char: str, n: int = 2) -> list:
    l = []  # New list
    temp = ""  # temp value
    count = 0  # Counter, that get will be reset, each time the temp get`s appended to the list

    for value in string.split(char):
        temp += value + char  # Add char to have it still in the string

        # Incrementing
        count += 1
        if count >= n:
            l.append(temp[:len(char) * -1])  # Remove last char
            # Reset
            count = 0
            temp = ""

    return l

print(nthofchar("25:hellwdasd:64:da:12:yeah:1:y", ":", 2))
# Output: ['25:hellwdasd', '64:da', '12:yeah', '1:y']

print(nthofchar("1;a;2;b;3;c;4;d;5;e;6;f", ";", 2))
# Output: ['1;a', '2;b', '3;c', '4;d', '5;e', '6;f']


texts: Function to erase a character in a string

texts:
void chrrem (char arr[], size_t len, size_t pos)
{
    memmove(arr + pos, arr + (pos + 1), (len - pos) + 1);
}

It is supposed to be just fast.
Erases the character pointed by pos (starting from 0)

Note that this function works with a statically allocated array like so:

char arr [256] = "Mystring";

// >>
chrrem (arr, strlen(arr), 0);
chrrem (arr, strlen(arr), 0);

printf(arr);

  Output:

sring


texts:
I think I finally finished a small coin flip project I found online. However, I'm pretty confident this is far from the optimal solution and would really appreciate any feedback on how this could be improved. Since I'm studying by myself using Head First and Code Academy any feedback would be very very helpful!

The goals of the challenge are:

As a user I want to be able to guess the outcome of a random coin flip (heads/tails).
As a user I want to clearly see the result of the coin flip.
As a user I want to clearly see whether or not I guessed correctly.
As a user I want to clearly see the updated guess history (correct count/total count).
As a user I want to be able to quit the game or go again after each cycle.

This is my first time really using GitHub, but I included the .py file which hopefully you can access here.

import random

def random_flip(): #function to generate random Heads or Tails output

    random_choice = random.choice(["Heads","Tails"])
    return random_choice

def user_choice(): #function to ensure a valid input from the user, and returns that input.

    user_input = ""
    valid_guesses = ["Heads", "Tails"]

    while user_input not in valid_guesses:
        user_input = input("Heads or Tails?")

    return user_input

def coin_flip_game(): #function that plays the coin flip game.

    guess_count = 1  #guesses set to 1 so that program considers 1st guess.
    guesses = []     #list of guesses made by user
    winner = False
    first_try = True      #Variable to determine whether first try of user or not
    cancel_game = False   #Variable to determine whether game was cancelled

    print("Lets start! Begin by choosing:")

    while winner == False:
        if first_try == True:
            user_input = user_choice()

            if user_input != random_flip():
                guess_count += 1
                guesses.append(user_input)
                first_try = False
            else:
                winner = True
        else:
            decision = input("You guessed wrong, do you want to continue? Yes or No ")

            if decision == "Yes":
                user_input = user_choice()

                if user_input != random_flip():
                    guess_count += 1
                    guesses.append(user_input)
                    first_try = False
                else:
                    winner = True
            else:
                winner = True
                cancel_game = True
                break

    if cancel_game == True:
        print("Game over")
    elif guess_count == 1:
        print("Congratulations, you guessed correctly on your first try!")
    else:
        print("Congratulations! After ", guess_count, "you guessed correctly!")
        print("Your previous guesses were: ", guesses)

coin_flip_game()


texts:
For a simple project, I represent a two-dimensional grid as a one-dimensional array, with both row and column indices between 1 and gridHeight. When retrieving a cell from the grid, I first need to check if both row and column IDs are within allowed bounds.

public void checkIfAllowed(int row_or_column) {
    if ((row_or_column < 1) || (row_or_column > gridHeight)) {
        throw new IndexOutOfBoundsException("Row or column ID is not acceptable.");
    }
}

public boolean getCellById(int row, int column) {
    checkIfAllowed(row);
    checkIfAllowed(column);
    return grid[row * gridHeight + column];
}

Can it possibly be improved?

There are two things about this code that I don't particularly like:

Somewhat repetitive code in getCellById.
It asks for permission instead of forgiveness: first checks everything, and then does the action. I would prefer a try .. catch construction (something like "try to return a value and then catch IndexOutOfBoundsException), but would it really work for Java? The array dimension is defined during run time, and initial declaration for my grid is just private boolean[] grid;.


texts:
This is how I made a cross context join.

What do you think?

How would you do this better?

using (var context = ContextFactory.Create())
{
    var users =  await context
                         .Users.AsNoTracking()
                         .OrderBy(user => user.DisplayName)
                         .Where(user => user.AccountName.Contains(query))
                         .Select(user => new UserProfileDTO
                         {
                             Id = user.Id,
                             DisplayName = user.DisplayName,
                         })
                         .ToListAsync().ConfigureAwait(false);

    foreach (var user in users)
    {
        var entity = await context.UserInfos.FindAsync(user.Id).ConfigureAwait(false);
        if (entity != null)
            user.HasPicture = entity.HasPicture == true ? true : false;
    }

    return users;
}


texts:
I'm writing the C++ program that involves a twist on Rock, Paper, Scissors. How the added Lizard and Spock affect the game is very simple and you could look it up if you want, but its not needed as I'm 99% sure my issue lies with the formatting of my if-else statements.
In every iteration, no matter what configuration the computer or the user chooses, the outcome is always the same - i.e. "You win! :)". Even in the cases where the user should have tied, or the user should have lost. If you are experienced, you will probably very easily see where I am messing up, please take a look. I apologize for the confusing curly braces but inputting my code was being very finnicky so I had to add random indents to make it format.
#include <iostream>
int main(){

srand(time(NULL));
int computer = rand() % 5 + 1;

int user = 0;

std::cout << "=============================================\n";
std::cout << "Rock    Paper    Scissors    Spock    Lizard!\n";
std::cout << "=============================================\n";
std::cout << "1) Rock\n";
std::cout << "2) Paper\n";
std::cout << "3) Scissors\n";
std::cout << "4) Lizard\n";
std::cout << "5) Spock\n";
std::cout << "\n";
std::cout << "Shoot!\n";

std::cin >> user;
std::cout << "Computer chose: " << computer << "\n";

if(user == 1){
if(computer == 3 || 4){
  std::cout << "You win! :)\n";
}
else if(computer == 1){
  std::cout << "You tied! :/\n";
}
else{
  std::cout << "Computer wins! :(\n";
}
    }
else if(user == 2){
if(computer == 1 || 5){
  std::cout << "You win! :)\n";
}
else if(computer == 2){
  std::cout << "You tied! :/\n";
}
else{
  std::cout << "Computer wins! :(\n";
}
 }
else if(user == 3){
if(computer == 2 || 4){
  std::cout << "You win! :)\n";
}
else if(computer == 3){
  std::cout << "You tied! :/\n";
}
else{
  std::cout << "Computer wins! :(\n";
}
}
else if(user == 4){
if(computer == 2 || 5){
  std::cout << "You win! :)\n";
}
else if(computer == 4){
  std::cout << "You tied! :/\n";
}
else{
  std::cout << "Computer wins! :(\n";
}
  }
else{
if(computer == 1 || 3){
  std::cout << "You win! :)\n";
}
else if(computer == 5){
  std::cout << "You tied! :/\n";
}
else{
  std::cout << "Computer wins! :(\n";
}
 }
  }


texts:
I am a nurse and I'm learning to code. I have coded this simple tool that helps me doing some common nursing formulas for medication. It works, however I think it is too bulky/redundant. Can you help me with some ideas for refactoring it?

class NursingFormulas
  def initialize
    puts "What do you want to do?"
    puts "1) How many tablets should I administer?"
    puts "2) How many ml should I administer?"
    puts "3) What's the ml per hour rate of my IV?"
    puts "4) What's the drop rate of my IV?"
    puts "5) Exit"
    choice = gets.chomp.to_i
    case choice
    when 1 then mass_for_mass
    when 2 then mass_for_liquid
    when 3 then iv_ml_rate
    when 4 then iv_drop_rate
    when 5 then exit(0)
    else
      exit(0)
    end
  end

  def mass_for_mass
    puts "What's the prescribed mass in mg?"
    prescribed = gets.chomp.to_f
    puts "What's the mass you've got in mg?"
    mass = gets.chomp.to_f
    result = prescribed / mass
    puts "Administer #{result} tablets"
  end

  def mass_for_liquid
    puts "What's the prescribed mass in mg?"
    prescribed = gets.chomp.to_f
    puts "What's the mass you've got in mg?"
    mass = gets.chomp.to_f
    puts "How many mL do you have?"
    ml = gets.chomp.to_f
    result = (prescribed / mass) * ml
    puts "Administer #{result} ml"
  end

  def iv_ml_rate
    puts "What's the volume in mL?"
    volume = gets.chomp.to_f
    puts "What's the time in hours?"
    time = gets.chomp.to_f
    result = (volume / time).round
    puts "The rate is #{result} ml per hour"
  end

  def iv_drop_rate
    puts "What's the volume in mL?"
    volume = gets.chomp.to_f
    puts "What's the time in hours?"
    time = gets.chomp.to_f
    time = time * 60
    puts "What's the drop factor?"
    factor = gets.chomp.to_f
    result = ((volume / time) * factor).round
    puts "The drop rate is #{result} drops per minute"
  end
end


texts: Reading numbers from console until input isn't a number

texts:
I want to read N numbers (Nmax = 100) from console into a list. N is not known, but the first input that is not a number may break the reading process... However the solution should be as simple as possible, so I just read 100 lines:

let numbers = [1..100]
        |> List.map (fun x -> Int32.TryParse(Console.ReadLine()))
        |> List.filter (fun (isNum, num) -> isNum)
        |> List.map (fun (isNum, num) -> num)

Is there a simpler (less code) solution?


texts:
I have made a little Quiz Game in Python. This was my first experience in programming Gui's in Python with Tkinter. In general, I do not have much knowledge about graphic programming and have acquired the necessary knowledge through skimming internet articles and try and error. Accordingly, the code looks like sciolism and semi-professional structuring. That should be improved. I will not be able to avoid a good basic tutorial on graphic programming, I think. However, if you have tips for me how to improve the style I would be grateful to hear them.

from tkinter import Tk, Frame, Label, Button
from time import sleep

class Question:
    def __init__(self, question, answers, correctLetter):
        self.question = question
        self.answers = answers
        self.correctLetter = correctLetter

    def check(self, letter, view):
        global right
        if(letter == self.correctLetter):
            label = Label(view, text="Right!")
            right += 1
        else:
            label = Label(view, text="Wrong!")
        label.pack()
        view.after(1000, lambda *args: self.unpackView(view))

    def getView(self, window):
        view = Frame(window)
        Label(view, text=self.question).pack()
        Button(view, text=self.answers[0], command=lambda *args: self.check("A", view)).pack()
        Button(view, text=self.answers[1], command=lambda *args: self.check("B", view)).pack()
        Button(view, text=self.answers[2], command=lambda *args: self.check("C", view)).pack()
        Button(view, text=self.answers[3], command=lambda *args: self.check("D", view)).pack()
        return view

    def unpackView(self, view):
        view.pack_forget()
        askQuestion()

def askQuestion():
    global questions, window, index, button, right, number_of_questions
    if(len(questions) == index + 1):
        Label(window, text="Thank you for answering the questions. " + str(right) + " of " + str(number_of_questions) + " questions answered right").pack()
        return
    button.pack_forget()
    index += 1
    questions[index].getView(window).pack()

questions = []
file = open("questions.txt", "r")
line = file.readline()
while(line != ""):
    questionString = line
    answers = []
    for i in range (4):
        answers.append(file.readline())

    correctLetter = file.readline()
    correctLetter = correctLetter[:-1]
    questions.append(Question(questionString, answers, correctLetter))
    line = file.readline()
file.close()
index = -1
right = 0
number_of_questions = len(questions)

window = Tk()
button = Button(window, text="Start", command=askQuestion)
button.pack()
window.mainloop()

questions.txt (this file has to be in the same folder)

Where is Germany?
In Europe
In Great Britain
In Asia
In the USA
A
Where is England?
In Asia
On an island
In the USA
In China
B
What is the etymological meaning of antibiotics?
For Life
For Health
Against Live
Against Diseases
C
"Portability is for people who can not write new programs." From whom does the quote come from?
Bill Gates
Hillary Clinton
Richard Stallman
Linus Torvalds
D
Who is the richest man in the world?
Jeff Bezos
Bill Gates
Donald Trump
Me
AX


texts: rand number generator with limits in ruby

texts:
I have an array of 1000 numbers, randomly generated. 10 of those numbers must be between 0-9 (including 0 and 9), and 10 of those numbers must be between 991 and 1000 (including 991 and 1000). This is what I came up with:

arr = []
980.times do
  arr << (11..989).to_a.sample
end

arr2 = []
10.times do
  arr2 << rand(10)
end

arr3 = []
10.times do
  arr3 << (990..1000).to_a.sample
end

arr4 = []
arr4 = arr + arr2 + arr3

arr4.shuffle

Is there a more elegant way to do this in ruby?