texts: Add multiple instances of a property to a list

texts:
I'm a novice programmer asking first question here although I've gotten tons of help from previous questions.
The following code is abstracted from what I currently have working.

List<decimal> teamAverage1 = new List<decimal>();
List<decimal> teamAverage2 = new List<decimal>();
List<decimal> teamAverage3 = new List<decimal>();

foreach (int id in TeamIds)
{
    foreach (Player player in Players.Where(p => p.teamId == id && p.a == 'x'))
    {
        teamAverage1.Add(player.Average1);
    }
    foreach (Player player in Players.Where(p => p.teamId == id && p.b == 'y'))
    {
        teamAverage2.Add(player.Average2);
    }
    foreach (Player player in Players.Where(p => p.teamId == id && p.c == 'z'))
    {
        teamAverage3.Add(player.Average3);
    }
}

Is there a way to get rid of the nested foreach loop and do something like:

foreach (int id in TeamIds)
{
    List<decimal> teamAverage1 = Players.Where(p => p.teamId == id && p.a == 'x').Average1
    List<decimal> teamAverage2 = Players.Where(p => p.teamId == id && p.b == 'y').Average2
    List<decimal> teamAverage3 = Players.Where(p => p.teamId == id && p.c == 'z').Average3
}

Is there a way to do this and if there is - is it a better solution than the original code?  I have a long list of properties to average and this would be much cleaner than many foreach loops.

More info: TeamIds identify each team.  Each player has teamId to relate it to a team.  Code should iterate every team id, find different subsets of players that belong to that team and add the stats of those players to lists for the team.  Thank you for your help, let me know if still not clear or if I have something wrong.

The linq statements can and will return more than one record.


texts: PowerShell script to Find and Replace in Word Document, including Header, Footer and TextBoxes within

texts:
I have written a PowerShell script to find and replace text within the whole document, including in the Headers and Footers as well as inside TextBoxes within the Headers.
There was lots of trial and error to get this to work and it is a bit cumbersome and probably not very efficient.
Any suggestion as to how make it better and go faster would be very much appreciated.
In particular, I'm sure there should be a better approach to get to the Headers TextBoxes but I couldn't figure it out so far.
In case it wasn't obvious, I'm not a professional coder, so please excuse the style or lacking thereof... :-)
Thanks!

$folderPath = "C:\Users\User\Folder\*" # multi-folders: "C:\fso1*", "C:\fso2*"
$fileType = "*.doc" # *.doc will take all .doc* files

$word = New-Object -ComObject Word.Application
$word.Visible = $false

Function findAndReplace($Text, $Find, $ReplaceWith) {
    $matchCase = $true
    $matchWholeWord = $true
    $matchWildcards = $false
    $matchSoundsLike = $false
    $matchAllWordForms = $false
    $forward = $true
    $findWrap = [Microsoft.Office.Interop.Word.WdReplace]::wdReplaceAll
    $format = $false
    $replace = [Microsoft.Office.Interop.Word.WdFindWrap]::wdFindContinue

    $Text.Execute($Find, $matchCase, $matchWholeWord, $matchWildCards, `
                  $matchSoundsLike, $matchAllWordForms, $forward, $findWrap, `
                  $format, $ReplaceWith, $replace) > $null
}

Function findAndReplaceWholeDoc($Document, $Find, $ReplaceWith) {
    $findReplace = $Document.ActiveWindow.Selection.Find
    findAndReplace -Text $findReplace -Find $Find -ReplaceWith $ReplaceWith
    ForEach ($section in $Document.Sections) {
        ForEach ($header in $section.Headers) {
            $findReplace = $header.Range.Find
            findAndReplace -Text $findReplace -Find $Find -ReplaceWith $ReplaceWith
            $header.Shapes | ForEach-Object {
                if ($_.Type -eq [Microsoft.Office.Core.msoShapeType]::msoTextBox) {
                    $findReplace = $_.TextFrame.TextRange.Find
                    findAndReplace -Text $findReplace -Find $Find -ReplaceWith $ReplaceWith
                }
            }
        }
        ForEach ($footer in $section.Footers) {
            $findReplace = $footer.Range.Find
            findAndReplace -Text $findReplace -Find $Find -ReplaceWith $ReplaceWith
        }
    }
}

Function processDoc {
    $doc = $word.Documents.Open($_.FullName)
    findAndReplaceWholeDoc -Document $doc -Find "THIS" -ReplaceWith "THAT"
    $doc.Close([ref]$true)
}

$sw = [Diagnostics.Stopwatch]::StartNew()
$count = 0
Get-ChildItem -Path $folderPath -Recurse -Filter $fileType | ForEach-Object {
  Write-Host "Processing \`"$($_.Name)\`"..."
  processDoc
  $count++
}
$sw.Stop()
$elapsed = $sw.Elapsed.toString()
Write-Host "`nDone. $count files processed in $elapsed"

$word.Quit()
$word = $null
[gc]::collect()
[gc]::WaitForPendingFinalizers()


texts: Simple counting fair semaphore implementation

texts:
Here is my attempt to implement a simple counting semaphore in Java. Please share your comments.

/*
 * A simple counting semaphore implementation.
 * Acquire calls block until a resource is available.
 * Supports fairness option which serves Acquire calls
 * in FIFO order.
 */

import java.util.Deque;
import java.util.ArrayDeque;

public class MySemaphore {
   private final int capacity;
   private int usedCount;
   private final boolean isFair;
   private Deque<Long> waitList;

   public MySemaphore(int capacity, boolean isFair) {
      this.capacity = capacity;
      this.isFair = isFair;

      if(isFair) {
         waitList = new ArrayDeque<>();
      }
   }

   public synchronized void acquire() {
      if(isFair)
         waitList.addLast(Thread.currentThread().getId());

      while(!(isResourceAvailable() && isEligibleToAcquire())) {
         try {
            wait();
         } catch(InterruptedException e) {
         }
      }

      usedCount++;

      if(isFair)
         waitList.removeFirst();
   }

   public synchronized void release() {
      if (usedCount > 0) {
         usedCount--;
         notifyAll();
      }
   }

   private boolean isResourceAvailable() {
      return usedCount < capacity;
   }

   private boolean isEligibleToAcquire() {
      if(!isFair)
         return true;

      // True only if current thread is at the head of the queue.
      return Thread.currentThread().getId() == waitList.getFirst();
   }
}

What happens to the intrinsic lock when interrupt is caught in the below block? My understanding is, the thread which catches the exception will still hold the lock. Please clarify.

  while(!(isResourceAvailable() && isEligibleToAcquire())) {
     try {
        wait();
     } catch(InterruptedException e) {
     }
  }


texts:
I've been following a Python programming book and reached the Regex chapter where I encountered this challenge:

Write a password strength checker that checks if a password is:

At least 8 character long
Contains at least one uppercase and lowercase letter.
And contains at least one digit.

I managed to do so, but frankly my solution seems both long and ugly. I was hoping someone could shed some light as to how I could maybe condense my program and improve readability if possible.
import re
def is_password_strong():
    password = input('Enter a password to test: ')

    length_regex = re.compile(r'.{8,}')
    length = True if length_regex.search(password) != None else False

    uppercase_regex = re.compile(r'[A-Z]')
    lowercase_regex = re.compile(r'[a-z]')
    uppercase = True if uppercase_regex.search(password) != None else False
    lowercase = True if lowercase_regex.search(password) != None else False
    case = True if uppercase and lowercase == True else False

    digit_regex = re.compile(r'[0-9]')
    digit = True if digit_regex.search(password) != None else False

    return(length and case and digit == True)
print(is_password_strong())

And here is my non-regex solution if you can't read the above and want to see what I am trying to do with regex:
def is_password_strong():
    password = input('Enter a password to test: ')
    length = len(password) >= 8
    case = password != password.upper() and password != password.lower()
    digit = any(c.isdigit() for c in password)

    return(length and case and digit == True)

I know this isn't a good test of password strength, but it was the book's challenge. I'm not implementing it for any real use.


texts: Make touch drag more intuitive/smooth for AR-Application in C#

texts:
I am currently working on an app to augment pictures on a vertical plane. Once the vertical plane is placed, the user is able to put an object on the plane. The placed object can be selected and dragged on touch - so far everything works fine.

void MoveSelected()
    {
        Vector3 curPos = cam.ScreenToViewportPoint(Input.touches[0].position);
        Vector3 lastPos = cam.ScreenToViewportPoint(Input.touches[0].position - Input.touches[0].deltaPosition);
        Vector3 touchDir = curPos - lastPos;

        touchDir.z = 0;

        curSelected.transform.position += verticalPlane.transform.TransformDirection(touchDir);
    }

However, the dragging is not very intuitive and i would like to make it more smooth. For example, if i scale down the object, dragging becomes very slow. Is there any way to improve my method?

Im using latest ARFoundation, Unity and im testing on Pixel 2.

Thanks


texts:
I am writing a program that computes

$$n-n \cdot \left(\prod_{i=1}^n (1-\frac{1}{p_i})\right)$$

which is rewritten in my code as:

$$\left(1-\left(\prod_{i=1}^n(1-\frac{1}{p_i})\right)\right) \cdot n$$

There are lots of primes involved here especially as \$n\$ gets larger and larger. I do not want to use Atkin's method for generating them since my teacher and I will probably lose oversight as to what is going on, but would still like to optimize my algorithm for speed and accuracy (not sure if the latter can be better).

i = 0
j = 3
old = 1.0
primes = [2]
while True:
    if (j>240000): break
    cont = True
    enumerator = 0
    for e in primes:
        if j%e==0: cont = False
        if enumerator>=len(primes)/2 + 1: break
        enumerator += 1
    if cont: primes.append(j)
    j+=2
#print primes

while True:
    if (i>len(primes)-1): break
    old = old * (1 - 1.0/primes[i])
    print old
    i+=1;
primeslessthan = j-1
amta = 1-old

print "The convergence: " + str(primeslessthan)
print "All the way up to the number: " + str(amta)
print "The amount of active inhibitors are: " + str((1-amta)*primeslessthan)

I am open to multithreading, and to translating this to a different language like C++, but do not know what optimizations I could make there either.


texts: Check if object contains only empty nested objects

texts:
lodash.isEmpty([{}]) returns false even though the object contained in the array is empty.

I need something that considers these kind of nested objects empty too and wrote the below recursive function. It looks a bit ugly and doesn't use any JavaScript specific tricks. Any comments welcome.

export function isDeepEmpty(input) {
  // catch null or undefined object
  if (!input) return true
  if (typeof(input) === 'object') {
    for (const entry of Object.values(input)) {
      if (!isDeepEmpty(entry)) {
        return false
      }
    }
    return true
  }
  // if input is not an object return false
  return false
}


texts: Generating strings dynamically in Python

texts:
I'm generating a URL (in string) that depends on 3 optional parameters, file, user and active.

From a base url: /hey I want to generate the endpoint, this means:

If file is specificied, my desired output would is: /hey?file=example
If file and user is specified, my desired output is: /hey?file=example&user=boo
If user and active are specified, my desired output is: /hey?user=boo&active=1
If no optional parameters are specified, my desired output is: /hey
and so on with all the combinations...

My code, which is working correctly, is as follows (change the None's at the top if you want to test it):

file = None
user = None
active = 1

ep = "/hey"
isFirst = True

if file:
  if isFirst:
    ep+= "?file=" + file;
    isFirst = False;
  else: ep += "&file=" + file;

if user:
  if isFirst:
    ep+= "?user=" + user;
    isFirst = False;
  else: ep += "&user=" + user;

if active:
  if isFirst:
    ep+= "?active=" + str(active);
    isFirst = False;
  else: ep += "&active=" + str(active);

print ep

Can someone give me a more python implementation for this? I can't use modules as requests.

Thanks in advance.


texts: Tree Template Class Implementation for C++

texts:
I have not done any parameter checking, however I think the meat of the class is there.  Let me know what you think.

#include <cstddef>
#include <vector>
using namespace std;

template<class T>
class TreeNode {

private:

    T* data;
    TreeNode<T>* parent;
    vector< TreeNode<T>* > children;

public:

    TreeNode(TreeNode<T>* parent, T data);
    ~TreeNode();

    T& getData() const;
    void setData(const T& data);
    void addChild(const T& data);
    void removeChild(const size_t& indx);
    TreeNode<T>* findChild(const T& data) const;
    TreeNode<T>* getChild(const size_t& indx) const;
    TreeNode<T>* getParent() const;
    int getNumChildren() const;

};

template<class T>
TreeNode<T>::TreeNode(TreeNode<T>* parent, T data) : parent(parent) {
    this->data = new T(data);
}

template<class T>
TreeNode<T>::~TreeNode() {
    delete data;
    for(TreeNode<T>* childNode : children)
        delete childNode;
}

template<class T>
T& TreeNode<T>::getData() const {
    return *this->data;
}

template<class T>
void TreeNode<T>::setData(const T& data) {
    *this->data = data;
}

template<class T>
void TreeNode<T>::addChild(const T& data) {
    children.push_back(new TreeNode<T>(this, data));
}

template<class T>
void TreeNode<T>::removeChild(const size_t& indx) {
    children.erase(children.begin()+indx);
}

template<class T>
TreeNode<T>* TreeNode<T>::findChild(const T& data) const {
    for(int i=0; i<children.size(); i++)
        if(children[i]->getData() == data)
            return children[i];
    return NULL;
}

template<class T>
TreeNode<T>* TreeNode<T>::getChild(const size_t& indx) const {
    return children[indx];
}

template<class T>
TreeNode<T>* TreeNode<T>::getParent() const {
    return parent;
}

template<class T>
int TreeNode<T>::getNumChildren() const {
    return children.size();
}


texts:
I am making a simple function to find and match any possibilities what Pokémon the user wants. This is accomplished by taking in the input (what the user thinks the Pokémon is named) and compare its spelling with preset Pokémon names (letter by letter searching). With each successful match, the Pokémon's score (determined by its value in the dictionary) will go up by one. Only the top seven Pokémon are returned.

The function:

import re
import operator

# Dictionary of Pokemon
list_of_chars = {"Bulbasaur": 0, "Ivysaur": 0, "Venusaur": 0, "Squirtle": 0, "Wartotle": 0, "Blastoise": 0,
                 "Charmander": 0, "Charmeleon": 0, "Charizard": 0, "Zapdos": 0, "Articuno": 0, "Moltres": 0, "Mew": 0,
                 "Mewtwo": 0}
list_of_keys = []

# Allow the list to actually contain the keys
for key in list_of_chars:
    list_of_keys.append(str(key))

def indiv_search(entry):
    certain_list = []
    # Loop through the possible Pokemon
    for i in range(0, len(list_of_keys)):
        # Loop through each *letter* of the entry
        for b in range(0, len(entry)):
            try:
                # Match each letter of entry with the letter of the Pokemon
                m = re.search(str(entry[b]), list_of_keys[i][b], re.IGNORECASE)
            except IndexError:
                continue
            if m is not None:
                # Match is successful
                list_of_chars[list_of_keys[i]] += 1
            elif m is None:
                # Match is not successful
                continue
    # "Sort" dictionary by score values
    sorted_x = sorted(list_of_chars.items(), key=operator.itemgetter(1))
    # Take only top seven choices
    while len(sorted_x) > 7:
        del sorted_x[0]
    for i in range(6, -1, -1):
        certain_list.append(sorted_x[i][0])
    # Return results
    return "Possible Choices: " + ", ".join(certain_list)

while True:
    # Take input, keep in string format
    poke_name = str(raw_input("Pokemon's Name: "))
    if poke_name == "QUIT":
        break
    else:
        # Print results
        print indiv_search(poke_name)
        # Reset all values in dictionary
        for i in range(0, len(list_of_chars)):
            list_of_chars[list_of_keys[i]] = 0

Example output:

Pokemon's Name: Char
Possible Choices: Charmander, Charizard, Charmeleon, Blastoise, Articuno, Venusaur, Zapdos

Note that the first line contains the raw_input() prompt and the input (separated by a space due to the prompt purposely having a space at the end to improve readability). The second line has the results of the function.

I have a few questions:

Is the code Pythonic?
What can be improved to uphold PEP rules?
What can be done to improve the efficiency and if possible, accuracy of the code?


texts: Select a specific line after matching a pattern

texts:
I just recently started using AWK and I'm still learning about it. I have solved the problem I'm about to show but I feel it's not the best solution and I'm trying to find a solution to fit within an AWK command rather than keep piping.

I have a bunch of .txt files ending for which I read the header (1st line only).

head -1 *.txt

Outputs:

==> anglia.txt <==
String - Anglian

==> carr.txt <==
String - Carr
etc..

From here I have a case switch where a user inputs 1-9. It's sorted so first line is always Anglian and second is always Carr.. etc
So if a user inputs 1 I know they want to select anglian. But for further process my code I need to extract the String "Anglian".

head -1 *.txt | awk '/[a-z]/&&!/.txt/'

Outputs:

String - Anglian
String - Carr

Here I got rid of the first line that had the filename.

head -1 *.txt | awk '/[a-z]/&&!/.txt/' | awk '{print $3}'

Outputs:

Anglian
Carr

Here I selected column 3 which contains the String that I need!

head -1 *.txt | awk '/[a-z]/&&!/.txt/' | awk 'NR==1{print $3}'

Outputs:

Anglian

Here I selected the first row which is exactly the output that I want! However I had to use an extra pipe. All I want is a awk command that does all of this in a single command somethings around the lines of:

head -1 *.txt | awk '/[a-z]/&&/.txt/{if(NR==1)print $3}'

Outputs:

EMPTY LINE

This is the problem I'm having. Since I'm having the pattern and NR in 1 command it's selecting the 1st line but the first line is a line that is being hidden by my pattern and it's the ==> anglian.txt <== hence

head -1 *.txt | awk '/[a-z]/&&/.txt/{if(NR==2)print $3}'

Outputs:

Anglian

However this is of no use because only matches Anglian where it is NR==2 and due to my case switch that I have I want it to be NR==1 otherwise the code does not work.

Is this possible? I hope I made myself clear here :)


texts: User input for student grades is too verbose

texts:
I need some help with this beginner C++ program (it's an assignment). How can I use a single variable and make the program get the six inputs I need instead of using a variable for each input?

#include <iostream>
using namespace std;

int main()

{

double grade1,grade2,grade3,grade4,grade5,grade6;
double totalGrade;
cout << "program to calculate grade" << endl << endl;
cout << "hi please enter the six grades ";
     << endl << endl;

cin >> grade1;
cin >> grade2;
cin >> grade3;
cin >> grade4;
cin >> grade5;
cin >> grade6;

grade1 = grade1 * 0.125;
grade2 = grade2 * 0.125;
grade3 = grade3 * 0.05;
grade4 = grade4 * 0.05;
grade5 = grade5 * 0.05;
grade6 = grade6 * 0.1;

totalGrade = grade1 + grade2 + grade3 + grade4 + grade5 + grade6;

if((totalGrade >= 9.5) && (totalGrade <= 10)) {
    cout << "grade is: >> " << totalGrade << endl << endl;
    cout << "you have approved + " << endl;
    }
else if ((totalGrade >= 9) && (totalGrade <= 9.5)) {
    cout << "grade is >> " << totalGrade << endl << endl;
    cout << "you have approved -" << endl;
    }
else if (totalGrade < 9) {
    cout << "grade is: >> " << totalGrade << endl << endl;
    cout << "you have reproved  "<< endl;

    }

return 0;
}


texts: Reading a text file, manipulating it and saving it to a mongo database

texts:
We have an upcoming project at work which is going to require working with express.js. I have no prior experience with node.js, so I thought I'd try and do something aside from some courses. Are there any anti-patterns and what can be improved?

Objective

I have a text file that is retrieved from an external source and looks like this (It has a lot more lines than this)

I do not need the first 3 lines, but I do need the data separated by a "|". Wherever there is a "||" it adds an undefined value to the array so I just remove it. I also do not need any text which has a "/" in it.

2019-10-09 11:03:33 : ============================= ATTACK LOG ==============================
2019-10-09 11:03:33 : |                      -------  LOOT ------           ------ BONUS ------
2019-10-09 11:03:33 : |AC|TIME.|TROP.|SRC|DS|   GOLD| ELIXIR|  DE|TR.|S|  %|  GOLD|ELIXIR|  DE|L.
2019-10-09 11:15:44 :   1|11:15| 1761| 17| 4| 450447| 546344|1704|-17|0| 47|     0|     0|   0|--||211/220|
2019-10-09 11:20:49 :   1|11:20| 1744| 14| 4| 307817| 279805| 643| 10|1| 62| 15640| 15640|   0|G1||209/220|

I am using a library called line-reader to read the text file and my Mongoose schema is defined as Results

    router.get('/retrieve-logs', (req,res,next)=>{
      var headers = ['accountNumber','timeOfAttack',
                   'trophies','searches','ds',
                   'gold','elixir','darkElixir',
                   'trophyChange','victory','damagePercentage',
                   'bonusGold','bonusElixir','bonusDarkElixir'];

      const filePath = 'AttackLog-2019-10.log'

      //Read from each line
      lineReader.eachLine(filePath, (line)=> {
        //Do nothing if 'ATTACK LOG' in line
        if (line.includes('ATTACK LOG')) {
        } else {
          //Remove appended date and time
          removedDateTime = line.substring(22);

          if (removedDateTime.includes('GOLD')) {
          } else {
            //Grab lines after headers removed
            attackData = removedDateTime.split("|");
            tempAttackData = [];
            //Remove undefined from array of data and remove last value from array
            for(let i of attackData)
                i && tempAttackData.push(i);
            attackData = tempAttackData;
//Remove last item from array which we don't need
            attackData.pop();
            // Remove excess whitespace
            cleanedAttackData= [];
            attackData.forEach((data, index) => {
              cleaned = data.trim();
              cleanedAttackData.push(cleaned)
            });
            //Create object for DB {headers: attackData}
            var result = {};
            headers.forEach((headers, i) => result[headers] = cleanedAttackData[i]);

            //Save the created object
            finalResults = new Results(result)
            finalResults.save();
          }
        }
    })

      Results.find({},(err, docs) => {
        res.status(200).send({
          message: "Results successfully loaded",
          success: docs
        })
      })

    })


texts:
I am trying to make an efficient prime number calculator. I've seen ones that can go up to close to 1 trillion in right around 4 hours, however I left mine on overnight and didn't get anywhere near that. I am asking this to see if anyone here knows a more efficient way for me to get up to a really high number really quickly. I also want to see if my everything else is up to standard as this is only my "2nd year" (classes where you self teach) coding.

#include <vector>
#include <iostream>

int main()
{
    std::vector<int> primes;  //vector that will have all numbers in it
    primes.push_back(3);      //push back the first 2 primes (not 2 due to never checking % 2 numbers)
    primes.push_back(5);
    for (unsigned long long i = 7;; i += 2)  //loop controlling the number that will be output
    {
        for (int j = 0; i % primes[j] != 0; ++j)  //loop that "scrolls" through my vector
        {
            if (sqrt(i) <= primes[j])  //if the square root of the number you're outputting is lower than the number you're checking against
            {
                std::cout << i << std::endl;  //output
                primes.push_back(i);
                break;
            }
            else
                continue;
        }
    }
    return 0;
}


texts: Initializing and printing an array using pointers and dynamic allocation in C

texts:
I have written a code for basic array creation and printing it's values in C. I would appreciate comments on how it can be improved, and the industry standards.

One issue I'm encountering is having no way to tell printArr() what the size of the array is.

Some questions:

Can I use arr[i] anywhere in the functions instead of **arr? (Gave error when I tried it)
What is the most common way of dealing with arrays when writing professional code? Is my approach correct?

int * initArr (int ** arr, int n)
{
    *arr=(int *) malloc(sizeof(int*)*n);
    printf("size is %d\n", sizeof(*arr));
    int i;
    for (i=0;i<n;i++)
    {
        *(*arr+i)=i+10;
    }
    return *arr;
}

void ** printArr (int ** arr, int n)
{
    int i;
    for (i=0;i<n;i++)
    {
        printf("Arr element %d is %d\n", i, *(*arr+i));
    }
    return *arr;
}

int main(void) {

    int *arr2;
    arr2=initArr(&arr2,10);
    printArr(&arr2,10);

    return 0;
}

Running the above code (with includes for stdio and stdlib) produces:

size is 8
Arr element 0 is 10
Arr element 1 is 11
Arr element 2 is 12
Arr element 3 is 13
Arr element 4 is 14
Arr element 5 is 15
Arr element 6 is 16
Arr element 7 is 17
Arr element 8 is 18
Arr element 9 is 19


texts: Creating Pascal's Triangle when specified number of rows

texts:
Does anyone have any tips on how I could improve my code

function pascal(row){
 for(var k = 0; k<=row; k++){
  var pascalRow = [1];
  for(var i = 1; i<=k; i++){
   pascalRow.push(pascalRow[i-1]*(k+1-i)/i)
  }
  console.log(pascalRow)
 }
}
pascal(/*Insert # of rows here */)


texts:
Challenge

Conceal a binary code within a word.

Specifications

The first argument is a path to a file.
The file contains multiple lines.
Each line is a test case represented by a space separated word and a binary code.
For each test case, print the binary masked word.
The mask alters the word according to the following:

If the bit is 1, change the letter to upper case.
If the bit is 0, leave the letter as is.

Constraints

Words are from 1 to 20 letters long.
The length of each word is equal to the length of the binary code.
Words are always in lower case.
The number of test cases is 40.

Sample Input

  hello 11001
  world 10000
  cba 111

Sample Output

  HEllO
  World
  CBA

Source

My Solution

#include <stdio.h>
#include <ctype.h>

#define LINE_BUFFER 42

int main(int argc, char *args[]) {
    if (argc < 2) {
        puts("File path not provided.");
        return 1;
    }

    if (argc > 2) {
        puts("Excessive arguments, only the first will be considered.");
    }

    FILE *file = fopen(args[1], "r");
    if (file == NULL) {
        puts("Could not access file / file not found.");
        return 1;
    }

    char line[LINE_BUFFER];
    while (fgets(line, LINE_BUFFER, file)) {
        for (int i = 0, word_length = 0; ; i++, word_length++) {
            if (line[i] == ' ') {
                line[i++] = '\0';
                for (int j = 0; j < word_length; j++, i++) {
                    if (line[i] == '1') {
                        line[j] = toupper(line[j]);
                    }
                }
                printf("%s\n", line);
                break;
            }
        }
    }

    fclose(file);
}


texts: slide out navigation bar seems too simple but it works, is it?

texts:
http://crystalcleanhomes.com/slide/

There are countless scripts that perform this simple slide-out navigation menu but they are all so bloated and the styles are so convoluted that I decided to make my own and it seems almost too simple and too basic so I've come here for criticism. From my testing it even works in IE7 and an older Android tablet (and of course flawlessly in Chrome, iOS, FF, etc.). So please critique this!

Here is a fiddle to more easily see the code: http://jsfiddle.net/9nT7B/

Question: does this meet compliance?

$(function(){
    $('#menubutton').click(function(e){
        e.preventDefault();
        e.stopPropagation();
        });
    function handler1(){
        $("#page").animate({left:"200px"},150);
        $("#menu").css("overflow-y","auto");
        $("#menubutton").one("click",handler2);
        }
    function handler2(){
        $("#page").animate({left:"0"},150);
        $("#menu").css("overflow-y","hidden");
        $("#menubutton").one("click",handler1);
        }
    $("#menubutton").one("click",handler1);
    $("#page").click(handler2);
    $("#menu").css("visibility","visible");
    });


texts: Convert an in-ordered and pre-ordered array to a BST

texts:
I am working on a Daily Coding Challenge to print the BST if given an in-ordered and pre-ordered array.

Below is my code in JavaScript ES6.

Please can you review it. This is my first fully-featured JS program so I am very unaware of standard syntax or shortcuts in JS

function Tree(){
    this.value = null
    this.right = null
    this.left = null
    this.reconstruct = (pre_order, in_order)=>{
        if (pre_order){
            if (this.value == null){
                this.value = pre_order[0]
            }
            let node = pre_order[0]
            let split_index = in_order.indexOf(node)
            let left_tree = in_order.slice(0, split_index)
            let right_tree = in_order.slice(split_index+1)

            this.left = new Tree()
            this.right = new Tree()

            if (left_tree.length>1){
                this.left.reconstruct(pre_order.slice(1, split_index), left_tree)
            }else{
                if (left_tree){
                    this.left.value = left_tree[0]
                }
            }
            if (right_tree.length>1){
                this.right.reconstruct(pre_order.slice(split_index+1), right_tree)
            }else{
                if (right_tree){
                    this.right.value = right_tree[0]
                }
            }
        }
    }
    this.print_tree = (level) =>{
        if (this.value){
            console.log(" ".repeat(level), this.value)
            if(this.left){
                this.left.print_tree(level+1)
            }
            if(this.right){
                this.right.print_tree(level+1)
            }
        }
    }
}
in_order = [4, 3, 5, 2, 6, 1, 12, 8, 13, 7, 10, 9, 11]
pre_order = [1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 9, 10, 11]
t = new Tree()
t.reconstruct(pre_order, in_order)
t.print_tree(0)


texts:
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!
Problem

Let's say a positive integer is a superpalindrome if it is a
palindrome, and it is also the square of a palindrome.
Now, given two positive integers L and R (represented as strings),
return the number of superpalindromes in the inclusive range [L, R].
Example 1:

Input: L = "4", R = "1000"
Output: 4
Explanation: 4, 9, 121, and 484 are superpalindromes.
Note that 676 is not a superpalindrome: 26 * 26 = 676, but 26 is not a palindrome.

Note:

\$1 <= len(L) <= 18\$
\$1 <= len(R) <= 18\$
L and R are strings representing integers in the range [1, 10^18).
int(L) <= int(R)

Inputs
"4"
"1000"

"10"
"99999199999"

"1"
"999999999999999999"

Outputs
4
23
70

Code
#include <cstdint>
#include <cmath>
#include <string>
#include <math.h>
#include <queue>
#include <utility>

struct Solution {
    static std::int_fast32_t superpalindromesInRange(const std::string L, const std::string R) {
        const long double lo_bound = sqrtl(stol(L));
        const long double hi_bound = sqrtl(stol(R));
        std::int_fast32_t superpalindromes = lo_bound <= 3 && 3 <= hi_bound;
        std::queue<std::pair<long, std::int_fast32_t>> queue;
        queue.push({1, 1});
        queue.push({2, 1});

        while (true) {
            const auto curr = queue.front();
            const long num = curr.first;
            const std::int_fast32_t length = curr.second;
            queue.pop();

            if (num > hi_bound) {
                break;
            }

            long W = powl(10, -~length / 2);

            if (num >= lo_bound) {
                superpalindromes += is_palindrome(num * num);
            }

            const long right = num % W;
            const long left = num - (length & 1 ? num % (W / 10) : right);

            if (length & 1) {
                queue.push({10 * left + right, -~length});

            } else {
                for (std::int_fast8_t d = 0; d < 3; ++d) {
                    queue.push({10 * left + d * W + right, -~length});
                }
            }
        }

        return superpalindromes;
    }

private:
    static bool is_palindrome(const long num) {
        if (!num) {
            return true;
        }

        if (!num % 10) {
            return false;
        }

        long left = num;
        long right = 0;

        while (left >= right) {
            if (left == right || left / 10 == right) {
                return true;
            }

            right = 10 * right + (left % 10);
            left /= 10;
        }

        return false;
    }

};

References

Problem

Discuss

Solution


texts: Perfect elimination ordering and high memory usage

texts:
The following code calculates a perfect
elimination ordering in a special case in Haskell.

I am less worried about its correctness than
its high use of memory. The following code runs
out of memory on my computer. It seems it should be
possible to execute the algorithm without ever having
more than around 1000 integers in memory.

The function do_elimination is tail-recursive, which is
supposed to be efficient in Haskell.

{-# LANGUAGE FlexibleInstances #-}
import Data.List (partition, (\\))

class Eq a => Concurrent a where
    isConcurrent :: a -> a -> Bool

instance Ord a => Concurrent (a, a) where
    isConcurrent (x,y) (z,w) = ( (x <= z) && ( y > z) )
                || ( (x >= z) && ( x < w) )

-- the actual algorithm
perfect_elimination_order :: Concurrent a => [a] -> [a]
perfect_elimination_order list = reverse . concat $ do_elimination [] [list]

split_for_elimination :: Concurrent a => a -> [a] -> [[a]]
split_for_elimination x = listify . partition  (isConcurrent x)
            where listify (a,b) = [a,b]

do_elimination :: Concurrent a => [a] -> [[a]] -> [[a]]
do_elimination used list | null difflist = list
                         | otherwise = do_elimination (pivot:used)
                            $ list >>= (split_for_elimination pivot)
            where pivot = head difflist
                  difflist = (concat list) \\ used

-- example
list :: [(Integer, Integer)]
list = [(a,b) | a <- [1,2,3,4,5,6], b<-[1,2,3,4,5,6] ]

main = print $ perfect_elimination_order list

Any ideas how to decrease memory usage?


texts: Java generics, convert nested list to array

texts:
I have to interface to some old code using nested arrays, so I have to convert my nested Lists to nested arrays. Any idea, suggestions, improvements are warmly welcomed.

public static <E> int getNestedListMaxSize(List<List<E>> list){
    int result = 0;
    if (list != null && list.size() > 0){
        for (List<E> innerList : list){
            result = Math.max(result, innerList == null ? 0 : innerList.size());
        }
    }
    return result;
}

@SuppressWarnings("rawtypes")
public static <E> Class getNestedListClass(List<List<E>> list){
    Class result = null;
    if (list != null && list.size() > 0){
        for (List<E> innerList : list){
            if (innerList != null && innerList.size() > 0){
                result = innerList.get(0).getClass();
                break;
            }
        }
    }
    return result;
}

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <E> E[][] convertNestedList(List<List<E>> list){
    E[][] result = null;
    Class clazz = getNestedListClass(list);
    if (clazz != null){
        result = (E[][]) Array.newInstance(clazz, list.size(), getNestedListMaxSize(list));

        for(int i=0; i < list.size(); i++) {
            E[] element = null;
            if (list.get(i) != null){
                E[] dummy = (E[]) Array.newInstance(clazz, list.get(i).size());
                element = list.get(i).toArray(dummy);
            }
            result[i] = element;
        }
    }
    return result;
}

public static void main(String[] args) {
    List<List<String>> list = new ArrayList<List<String>>();
    list.add(new ArrayList<String>());
    list.get(list.size()-1).add("0.0");
    list.get(list.size()-1).add("0.1");
    list.get(list.size()-1).add("0.2");
    list.add(new ArrayList<String>());
    list.get(list.size()-1).add("1.0");
    list.get(list.size()-1).add("1.1");
    list.get(list.size()-1).add("1.2");
    list.get(list.size()-1).add("1.3");
    list.add(new ArrayList<String>());
    list.get(list.size()-1).add("2.0");
    list.get(list.size()-1).add("2.1");

    String [][] array = convertNestedList(list);

    System.out.println(Arrays.deepToString(array));
}


texts: Session handling using Python Requests client

texts:
I'm using this code to login to an experiment login system created by me for this purpose.

import requests
import re

def get_page_data(regex, req):
    match = re.compile(regex).search(req.text)
    if match != None:
        return match.group(1)
    return 'no match found on {}'.format(regex)

def print_req_data(req, req_name):
    print('{} status code: {}'.format(req_name, req.status_code))
    print('{} title: {}'.format(req_name, get_page_data('<title>(.*?)</title>', req)))
    print('{} content:\n{}'.format(req_name, req.text))

form_url = 'http://migueldvl.com/heya/login/'
post_url = 'http://migueldvl.com/heya/login/process.php'
headers = {'User-agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1'}

with requests.Session() as s:
    # get form page, so the cookies are set (form token)
    logged_out_req = s.get(form_url, headers=headers)
    print_req_data(logged_out_req, 'Logged out request')
    title_logout = get_page_data('<title>(.*?)</title>', logged_out_req)
    # getting the form token
    token = get_page_data('<input type="hidden" name="token" value="(.*?)">', logged_out_req)
    login_data = {'password' : 'password', 'username' : 'miguel', 'token': token}
    # posting the data to the post url
    post_req = s.post(post_url, data=login_data, headers=headers)
    print_req_data(post_req, 'Post request (redirect page)')
    check_post_title = get_page_data('<title>(.*?)</title>', post_req)
    # comparing the titles (logged out title with redirect page title) so i see if login success
    if(check_post_title != title_logout):
        print('SUCCESS\n[+] Checking if still logged in...')
        # going to see if i'm still loggin, see if our loggedin session is permanent
        logged_req = s.get(form_url, headers=headers)
        print_req_data(logged_req, 'Check if still logged request')
        title_check = get_page_data('<title>(.*?)</title>', logged_req)
        if(title_check == check_post_title):
            print('You are still loogedin')
        else:
            print('Not loggeding anymore')
    else:
        print('FAIL LOGIN')
        print_req_data(post_req, 'Post request (redirect page)')

I was wondering if there is a better way to do this, especially with regard to:

Is there a better way to get the form token? I tried checking the headers,

logged_out_page = s.get(form_url, headers=headers)
print(logged_out_page.headers) # headers the server sent back to us
print(logged_out_page.request.headers) # headers we sent to the server

I know that session values are not stored on our machine (browser) unlike normal cookies, those are stored in the server so the real session value is not on the headers (just some id key to the server, so it can fetch the real data stored on it). But is there anyway besides using regex to extract the session value? PS: (session cookie produced with php, $_SESSION['token] = md5(time())).

Is there a way (besides doing a string comparison of the page title, or some other element on the page) to check if the login was successful?

Any other comments and suggestions are, of course, welcome. If you'd like to test this code (python3, using the links above, form_url and post_url) with the username miguel and the password password.

PS: Bear in mind that this code is based on the loggedin system mechanic that I created (the most usual, i guess). I don't wish any improvements on this code based on another


texts:
I am working on a project for Udacity, where I should use CSV files to display data on fake corporate dashboard. Structure of the data I am working on is like this:

I am using AngularJS for this project, I created service for getting the data, formatting it to JSON and summarizing data into months. It works good, but I can see that it takes up to 1-2 sec to load a page, and data sheet has only around 90 lines. Anybody has suggestion how to speed it up?

I am also using MomentJS for formatting dates.

Service:

var getIssues = function() {
    return $http.get('data/issues.csv').then(
        function(response) {
            return CSV2JSON(response.data);
        }
    );
};

this.summorizeIssues = function() {

    return new Promise(function(resolve) {

        getIssues().then(function(data) {

            var datesarray = [];
            var returnarray = [];

            data.forEach(function(item) {
                if (item['submission timestamp']) {
                    var month = moment(item['submission timestamp'], 'M-D-YY h:m a').format('MMM-YY');
                    if (datesarray.indexOf(month) < 0) {
                        datesarray.push(month);
                    }
                }
            });

            datesarray.sort(function(a, b) {
                return moment(a, 'MMM-YY') - moment(b, 'MMM-YY');
            });

            datesarray.forEach(function(date) {
                var counter = 0;
                data.forEach(function(item) {
                    var month = moment(item['submission timestamp'], 'M-D-YY h:m a').format('MMM-YY');
                    if (month === date) {
                        counter += 1;
                    }
                });
                returnarray.push({
                    label: date,
                    issues: counter
                });

            });

            resolve(returnarray);
        });
    });
};

Controller:

issuesdataProvider.summorizeIssues().then(function(data) {
    _this.issues = data;
    _this.datesIssues = issuesdataProvider.monthstoYears(data);
    _this.currentDateIssues = _this.datesIssues[_this.datesIssues.length - 1];
});

This is the result of   return CSV2JSON(response.data); :

[
  {
    "submission timestamp": "4-7-16 2:28 PM",
    "customer name": "Tincom",
    "customer email address": "tincom@tincom.com",
    "description": "error 64",
    "open/closed status": "open",
    "closed timestamp": 0,
    "employee name": "Mickie Daley"
  },
  {
    "submission timestamp": "7-23-15 1:12 PM",
    "customer name": "Tripplehow",
    "customer email address": "tripplehow@tripplehow.com",
    "description": "error 95",
    "open/closed status": "closed",
    "closed timestamp": 42208.59706,
    "employee name": "Daine Whittington"
  },
  {
    "submission timestamp": "3-8-14 1:33 PM",
    "customer name": "Betadox",
    "customer email address": "betadox@betadox.com",
    "description": "error 94",
    "open/closed status": "closed",
    "closed timestamp": 41706.67644,
    "employee name": "Corliss Zhang"
  }]

And this how data looks after the process is done:

[
   {
      "label":"Jan-14",
      "issues":5
   },
   {
      "label":"Feb-14",
      "issues":1
   },
   {
      "label":"Mar-14",
      "issues":7
   },
   {
      "label":"Apr-14",
      "issues":4
   },
   {
      "label":"May-14",
      "issues":2
   },
   {
      "label":"Jun-14",
      "issues":2
   },
   {
      "label":"Jul-14",
      "issues":2
   },
   {
      "label":"Aug-14",
      "issues":1
   },
   {
      "label":"Sep-14",
      "issues":1
   },
   {
      "label":"Oct-14",
      "issues":1
   },
   {
      "label":"Nov-14",
      "issues":2
   }...
]


texts: Unit of Work and Repository with Entity Framework 6

texts:
Based on the reply of this question I have created the following code. I need to check whether it's good or not.

Here is my entity class:

public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Designation { get; set; }
}

This is my db context implementation:

 public class MyDataContext<T> : DbContext where T:class
{
    private IDbSet<T> _dbSet;

    public MyDataContext() : base("name=DefaultConnectionString")
    {
        _dbSet = this.Set<T>();
    }

    public MyDataContext(IDbSet<T> dbSet )
        : base("name=DefaultConnectionString")
    {
        this._dbSet = dbSet;
    }

    public IDbSet<T> DbSetOjbect
    {
        get { return _dbSet; }
    }
}

Now I have implemented the EmployeeService business logic class and the IEmployee service class:

 public interface IEmployeeService
{
    List<Employee> GetEmployees();
}

Here is the implementation:

public class EmployeeService : IEmployeeService
{
    private IDbSet<Employee> employee;

    public EmployeeService()
    {
        var employeeContext = new MyDataContext<Employee>();
        employee = employeeContext.DbSetOjbect;
    }

    public EmployeeService(IDbSet<Employee> employee)
    {
        this.employee = employee;
    }

    public List<Employee> GetEmployees()
    {
        return employee.ToList();
    }
}

The following is my controller code in ASP.NET MVC controller.

 public class EmployeeController : Controller
{
    private readonly IEmployeeService _employeeService;

    public EmployeeController()
    {
        _employeeService = new EmployeeService();
    }

    public EmployeeController(IEmployeeService employeeService)
    {
        _employeeService = employeeService;
    }

    public ActionResult Index()
    {
        return View(_employeeService.GetEmployees());
    }
}

I want to check whether it is a good approach for TDD Test Driven Development or not.


texts: Functional method for storing a query string as a simple key-value object

texts:
I'm working on an isomorphic javascript module (query-hash) to handle query strings and base64 tokens. It's essentially a simple key-value object with methods for taking in data and giving it back in the format you ask for.

function queryToObject(queryString) {
    return queryString.split('&')
        .map(kv => kv.split('='))
        .reduce((p, kv) => {
            p[kv[0]] = decodeURIComponent(kv[1] || '').replace(/\+/g, ' ');

            return p;
        }, {});
}

For the "functional approach", mapping the array created by split() seems like unnecessary function calls. Should I be splitting the string in the reduce() method? Is there a better approach?


texts: Converting a 32bit number in a proprietary timestamp with PHP

texts:
This is a copy of a posting I made on SO, it was suggested I post it here all I've changed from that post is I'm now doing the bitwise AND using a decimal number rather than using bindec("111") to create the mask. The output is identical.

I have a 32 bit number represented as a HEX string that I need to convert to a timestamp following these rules:

What I want to check is that I'm not doing something glaringly stupid? Does my conversion look sane given the timestamp specification?

I've put together the following code to do this. I know PHP isn't the best for this sort of work but it's part of a larger legacy application all written in PHP.

$t is taken from an XML file of readings, one every 5 mins.

    // convert the hex string to a string representation of the binary number
    // sprintf pads leading zeros, for debugging only
    $binStr = sprintf('%032s', base_convert($t, 16, 2));

    //get a decimal representation so we can use the bitwise operator on it
    $decimal = base_convert($t, 16, 10);

     // get the first 6 bits
    $min = $decimal & 63; // 111111 in binary

    // drop the first 8 bits then apply a mask to the next 5
    $hour = ($decimal >> 8) & 31; // 11111 in binary

    // drop the first 15 bits then apply a mask to the next 1
    $daylightSaving = ($decimal >> 15) & 1;

    // etc
    $day  = ($decimal >> 16) & 31; // 11111
    $yearLsb  = ($decimal >> 21) & 7; //111
    $month = ($decimal >> 24) & 15; //1111
    $yearMsb  = ($decimal >> 28) & 15; //1111

    Logger::debug(
        "Incoming timestamp " . $t . " \n" .
        " (as binary " . $binStr . ") converted to: \n" .
        " Day: " . $day . "\n" .
        " Month: " . $month . "\n" .
        " Year: " . $yearMsb . $yearLsb . "\n" .
        " Hour: " . $hour . "\n" .
        " Min: " . $min . "\n" .
        " Daylight saving: ". $daylightSaving
    );

The output for the last entry in the file is:

Incoming timestamp 2DAC1B0A
 (as binary 00101101101011000001101100001010) converted to
 Day: 12
 Month: 13
 Year: 25
 Hour: 27
 Min: 10
 Daylight saving: 0

I know the file was created at 11:25am on the 12th Nov 2013, the readings are for 11:10 to 11:25 with the last one in the file being the 11:10am one.

The mins match those in the file I get 10 through 25 in 5 min increments. The day is also accurate if I run it against other files.

There's a chance that the equipment manufacturer who wants us to purchase some expensive software to do this parsing has munged the timetamp specification but that being an option I've played with lots of possible combinations in that 32bit integer and I can't see how I can get all the numbers I require from the supplied timestamps.


texts: Codeigniter 3: how can I avoid repeating this chunk of code in my controllers?

texts:
I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.

Several entities are present in all controllers (except Login.php and Register.php): static data, categories and pages.

$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();

Further more, in most controller, the code above appears more then one time.

I am afraid this is mot the only case of repetitive code in the application. (See the entire application, at its current state, on my Github account).

I am looking for specific and/or general advice from experienced PHP developers that would help me reduce code redundancy and make it more efficient.

What is the best way to avoid the repeating of the code above in my controllers?


texts:
To expand from the changes supplied by the answer of my previous question:

#include <condition_variable>
#include <iostream>
#include <random>
#include <mutex>
#include <thread>
#include <vector>

// global variables
std::condition_variable cv;
std::mutex mtx;
std::vector<char> data;

int count = 0, buff_size = 0;

char random_char() {
    thread_local std::random_device seed;
    thread_local std::mt19937 generator(seed());
    thread_local std::uniform_int_distribution<int> dist('A', 'Z');

    return static_cast<char>(dist(generator));
}

/* Consumer

Prints out the contents of the shared buffer.

*/
void consume() {
    std::unique_lock<std::mutex> lck(mtx);

    while (count == 0) {
        cv.wait(lck);
    }

    for (const auto& it : data) {
        std::cout << it << std::endl;
    }

    count--;
}

/* Producer

Randomly generates capital letters in the range of A to Z,
prints out those letters in lowercase, and then
inserts them into the shared buffer.

*/
void produce() {
    std::unique_lock<std::mutex> lck(mtx);

    char c = random_char();
    std::cout << " " << static_cast<char>(tolower(c)) << std::endl;
    data.push_back(c);

    count++;
    cv.notify_one();
}

int main() {
    std::cout << "The Producer-Consumer Problem (in C++11!)" << std::endl << "Enter the buffer size: ";
    std::cin >> buff_size;

    // keep the buffer in-range of the alphabet
    if (buff_size < 0) {
        buff_size = 0;
    }
    else if (buff_size > 26) {
        buff_size = 26;
    }

    std::thread production[26], processed[26];

    // initialize the arrays
    for (int order = 0; order < buff_size; order++) {
        production[order] = std::thread(produce);
        processed[order] = std::thread(consume);
    }

    // join the threads to the main threads
    for (int order = 0; order < buff_size; order++) {
        processed[order].join();
        production[order].join();
    }

    std::cout << "Succeeded with a shared buffer of " << data.size() << " letters!";
}


texts: Optimize program to test for divisibility of numbers 3.0

texts:
This is a follow up on my previous question.

JS1's answer suggested that I should use a precomputed table containing all permutations of the lowest valid number for each number between 1 and MAX. It was well described how to implement the precomputed table but somewhere I seem to have miserably failed since the code runs much slower than my previous versions of the code.

I don't believe there's anything wrong with my lookup table but if that's for any use here is the code I wrote to obtain all permutations for numbers between 1 and MAX.

Something with my code seems off because for larger calculations (the example found in my previous question) the code runs terribly slow.

#include <stdio.h>

int lookup[] = {
#include "table.h"
};

#define LENGTH(x) (sizeof(x) / sizeof((x)[0]))
#define MAX 1000000

int main(void) {
  int n[100];
  int x, i, j, k, l, m, N;

  scanf("%d", &N);
  for(i=0;i<N;i++) scanf("%d", &n[i]);
  for(x=1;x<MAX;x++) {
    j=x-1;
    i=-x;
    while((unsigned int)(j) < LENGTH(lookup) && lookup[j] != i) ++j;
    for(l=0;l<N;l++) {
      m = j;
      while((k = lookup[++m]) > 0) {
        if(k%n[l]==0)break;
      }
      if(k<0) goto outer;
    }
    break;
    outer:
    continue;
  }
  fprintf(stdout, "%d\n", x);
}

Perhaps the access time on the array is affecting the speed?


texts: Batch renames file's extension in a given directory with Python

texts:
Arguments:

The directory in which you would like to change file extensions
Old file extension
And what the new extension should be

Example:
$ touch /tmp/spam.eggs
$ python change-ext.py /tmp .eggs .spam
$ ls /tmp
$ spam.spam

My Concerns.

Is the code easy to read and comprehend?
Is the code Pythonic?
Does the code have any BUGS?
Should i have used argparse instead of sys.argv

'''
Batch renames file's extension in a given directory
'''

import os
import sys
from os.path import join
from os.path import splitext

def main():
    try:
        work_dir, old_ext, new_ext = sys.argv[1:]
    except ValueError:
        sys.exit("Usage: {} directory old-ext new-ext".format(__file__))

    for filename in os.listdir(work_dir):
        if old_ext == splitext(filename)[1]:
            newfile = filename.replace(old_ext, new_ext)
            os.rename(join(work_dir, filename), join(work_dir, newfile))

if __name__ == '__main__':
    main()


texts: config.properties, Static Classes and Reflection

texts:
I wanted an opinion about an idea I had regarding the use of config.properties, static classes and the use of reflection.

I have to load some preferences at application startup, for that I will be using config.properties. Certain properties within config.properties will be changed during various points in the program. So, instead of opening, searching for the property, updating and closing properties.config - I was thinking I could use a static class to read and write values, use reflection to write values back and forth between static class and properties.config file during application startup and close.

Is there a better approach I should be considering? Should I be avoiding static class?

Here is simplified code

//Class with static variables, the values get used and updated at
//various points within the program. For example prop1 gets updated and used
//at a different points in the program. Also, they are active at
//different  points in the program than prop1 and prop2.
//values need to be saved for application startup.

public class StaticProp {
    public static String prop1 = "a";
    public static String prop2 = "b";
    public static String prop3 = "c";
}

During application close, using Reflection - write values to properties.config

    private void writeConfigProp() {
    Properties prop = new Properties();
    OutputStream outputStream = null;
    try {
        outputStream = new FileOutputStream("resources/config.properties");
        Field[] fields = StaticProp.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                prop.setProperty(field.getName(), Utility.tryParseVal(field.get(null)));
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        prop.store(outputStream, "Config for UI");
    } catch (IOException io) {
        io.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

During application startup, using Reflection - read properties.config to static class.

    /**
 * Read Config Properties
 */
private void readConfigProp() {
    Properties prop = new Properties();
    InputStream inputStream = null;

    try {
        inputStream = new FileInputStream("resources/config.properties");
        prop.load(inputStream);

        Field[] fields = PropConfig.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                try {
                    field.set(null, prop.getProperty(field.getName()));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}


texts: How can I make this jQuery code better so variables aren't repeated and the code is more efficient?

texts:
It adds and removes classes from animate.css when mouse events occur. Though I hate how I had to write the same thing twice in both events.

var item = $('.work-item');

item.mouseenter(function(event) {
  var $this = $(this);
  var cover = $(this).find('.item-cover'),
      coverTitle = cover.find('.title');
      coverShortDescription = cover.find('.short-description'),
      coverSep = cover.find('.seperator');
  cover.removeClass('fadeOut').addClass('animated fadeIn');
  coverTitle.removeClass('fadeOutDown').addClass('animated fadeInUp');
  coverShortDescription.removeClass('fadeOutUp').addClass('animated fadeInDown');
  coverSep.removeClass('fadeOut').addClass('animated fadeInUp');
}).mouseleave(function(event) {
  var $this = $(this);
  var cover = $(this).find('.item-cover'),
      coverTitle = cover.find('.title');
      coverShortDescription = cover.find('.short-description'),
      coverSep = cover.find('.seperator');
    cover.removeClass('fadeIn').addClass('fadeOut');
    coverTitle.removeClass('fadeInUp').addClass('animated fadeOutDown');
    coverShortDescription.removeClass('fadeInDown').addClass('animated fadeOutUp');
    coverSep.removeClass('fadeInUp').addClass('fadeOut');
});

Any way to make this more efficient?


texts: Real-time timekeeping logic for ATmega16A

texts:
As part of a clock I'm building based on an ATmega16A, I wrote some assembly code to handle setting up the timer for a 32.768kHz crystal and handle second/minute/hour/day updates. Here are the relevant parts (of the full program):

Timing interrupt handler

        ; One second has passed, do timing things
        ; Increment seconds by 1
TICK:   inc r17

        ; If seconds are 60, do minutes things
        ldi r16,60
        cpse r16,r17
        rjmp TOCK

        ; Clear seconds and increment minutes by 1
        clr r17
        inc r18

        ; If minutes are 60, do hours things
        cpse r16,r18
        rjmp TOCK

        ; Clear minutes and increment hours by 1
        clr r18
        inc r19

        ; If hours are 12, do am/pm things
        ldi r16,12
        cpse r16,r19
        rjmp TOCK

        ; Clear hours
        clr r19

        ; Output the time (testing version)
TOCK:   clr r16
        sbrc r17,0
        sbr r16,(1<<PORTB0)
        sbrc r18,0
        sbr r16,(1<<PORTB1)
        sbrc r19,0
        sbr r16,(1<<PORTB2)
        out PORTB,r16
        reti

Sample loop (not sure about my loops):

        ; Wait for prescaler changes to take effect
TCR2UW: in r16,ASSR
        sbrc r16,TCR2UB
        rjmp TCR2UW

This is my first time writing a non-tiny assembly program, so my main concerns are: does my flow control make sense? Is there a better way to handle my cpse+rjmps? Any advice will be appreciated, however.


texts: Reducing execution time of an HTML parsing script

texts:
The script is intended to return an array with texts containing specific words in English and the equivalent texts in Polish from EUR-Lex - a website with EU documents.

The script downloads the page which address is specified by the passed variable. Then this page is parsed using regular expressions for the document codes. This code are then used to access another page. This page is then parsed for elements contained within <tr> tags, which, if their content contains words from the variable (checked with a regular expression), are saved in an array.

For variables containing 1-2 words the script works fairly well; not so well for more. I got complaints from my free hosting provider (hostinger.in) that the script uses too much resources. I have other scripts run before that script, but not simultaneously, so I don't if they contribute to the problem.

<?php
//test variables
//$var1 = 'board_of_directors';
//$var1 = 'affidavit';
$var1 = 'event_of_default';
$var1 = explode("_", $var1);
$words = implode(" ",$var1);
if (count($var1) >= 2) {
    $var1 = implode("%20",$var1);
} else {
    $var1 = implode("%",$var1);
}
$var1 = "\""."$var1"."\"";
$html = file_get_contents("http://eur-lex.europa.eu/search.html?qid=1&text=$var1&scope=EURLEX&type=quick&lang=en");
preg_match_all('/CELEX:(\w+)&/si', $html, $matches2);
$result = array_unique($matches2[1]);
$result2 = file_get_contents("http://eur-lex.europa.eu/legal-content/EN-PL/TXT/?uri=CELEX:$result[0]&from=EN");
$dom = new domDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($result2);
$items = $dom->getElementsByTagName('tr');
$return_array = array();

for ($i = 0; $i < $items->length - 1; $i++) {
    $text1 = $items->item($i)->childNodes->item(0)->textContent;
    if (preg_match('/' . $words . '/i', $text1)) {
        $text2 = $items->item($i)->childNodes->item(1)->textContent;
        array_push($return_array, $text1);
        array_push($return_array, $text2);
    }
}
echo json_encode($return_array);

?>


texts:
I find that I am often writing files where the names either:

Need to be incremented (rather than overwriting a file that already exists in the directory with the same name)
Need to be timestamped

And, so, I've created the following methods to do so:

public static string CreateDatedFileName(string directory, string filename, string DateTimeFormat = "yyyy-MM-dd", bool AppendNumberIfNameAlreadyExists = true)
{
    if (!CheckIfDirectoryExists(directory))
        throw new ArgumentException(string.Format("The specified directory - {0} - does not exist", directory));

    string formatedTemplate = "{0} - {1}.{2}";

    var fileNameWithoutExtension = filename.Split('.')[0];
    var fileExtension = filename.Split('.')[1];
    var DateValue = DateTime.Now.ToString(DateTimeFormat);

    string newname = String.Format(formatedTemplate, fileNameWithoutExtension, DateValue, fileExtension);
    string path = Path.Combine(directory, newname);

    if (!AppendNumberIfNameAlreadyExists)
        return Path.Combine(directory, newname);
    else
        return CreateFileName(directory, newname, true);
}

public static string CreateFileName(string directory, string filename, bool AppendNumberIfNameAlreadyExists = true)
{
    if (!CheckIfDirectoryExists(directory))
        throw new ArgumentException(string.Format("The specified directory - {0} - does not exist", directory));

    string formatedTemplate = "{0}{1}.{2}";

    var fileNameWithoutExtension = filename.Split('.')[0];
    var fileExtension = filename.Split('.')[1];

    string newname = String.Format(formatedTemplate, fileNameWithoutExtension, string.Empty, fileExtension);
    string path = Path.Combine(directory, newname);
    int AppendDigit = 0;

    while (AppendNumberIfNameAlreadyExists && CheckIfFilePathExists(path))
    {
        ++AppendDigit;
        newname = String.Format(formatedTemplate, fileNameWithoutExtension, "_" + AppendDigit, fileExtension);
        path = Path.Combine(directory, newname);
    }

    return path;
}

public static bool CheckIfDirectoryExists(string directory)
{
    return System.IO.Directory.Exists(directory);
}

public static bool CheckIfFilePathExists(string path)
{
    return System.IO.File.Exists(path);
}

I'm just curious to know if this is an efficient way to accomplish this and, if not, I'd really like to learn why so as to become a better coder overall.


texts:
Problem

  Suppose we abstract our file system by a string in the following
  manners:

  The string dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext represents:

dir
    subdir1
    subdir2
        file.ext

  a directory dir contains an empty sub-directories subdir1 and a sub-directory subdir2 containing a file file.ext.

  The string
  dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext
  represents:

dir
    subdir1
        file1.ext
        subsubdir1
    subdir2
        subsubdir2
            file2.ext

  a directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.extand an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext.

  We are interested in finding the longest (number of characters)
  absolute path to a file within our file system. That is, for example,
  in the second example above, the longest absolute path is
  dir/subdr2/subsubdir2/file.ext, and its length is 30.

  Given a string representing the file system in the above format,
  return the length of the longest absolute path to file in the
  abstracted file system. Simply put, that is the length of a valid path
  that ends with a file, and a file contains . and an extension.

  Time complexity required: O(n) where n is the size of the input
  string.

  Notice that a/aa/aaa/file1.txt is not the path you want, if there is
  aaaaaaaaaaaaaaaaaaaaa/sth.png.

Any advice on code bugs, performance improvements in terms of algorithm time complexity, or code style advice is highly appreciated.

def find_longest_path(source):
    items = source.split('\n')
    prefix = []
    prefix_length = []
    max_length_so_far = -1
    max_path_so_far = ''
    for path in items:
        i = 0
        while path[i] == '\t':
            i += 1
        if len(prefix) > i:
            prefix = prefix[:i]
            prefix_length = prefix_length[:i]
        prefix.append(path[i:])
        prefix_length.append(len(path[i:]))
        if sum(prefix_length) > max_length_so_far:
            max_length_so_far = sum(prefix_length)
            max_path_so_far = '/'.join(prefix)
    return max_path_so_far

if __name__ == "__main__":
    path_name = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext"
    print find_longest_path(path_name)
    path_name = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"
    print find_longest_path(path_name)


texts: Given a sequence of positive integers A and an integer T, return true if a continuous sequence of A sums up to exactly T

texts:
Here is the source of the question, and my solution is below.
Did I determine the worst case correctly?
If you find any input where it doesn't work, please let me know.

public class Main {

    /*
     * http://www.careercup.com/question?id=6305076727513088
     *
     * Worst case: O(2*n)
     * [ 1, 3, 4, 1, 0, 23 ] and k == 23. We have to iterate over the array twice:
     *
     * 1. We sum up all the elements [0, n - 1], n - the array size
     * 2. We subtract all the elements [0, n - 2]
     */
    static boolean findSum(int[] array, int k) {
        int i = 0;
        int start = i;
        int sum = 0;
        for (; i < array.length;) {
            if (array[i] > k) {
                i += 2;
                start = i;
                sum = 0;
                continue;
            }
            if (sum < k) {
                sum += array[i];
                i++;
            }
            while (sum > k) {
                sum -= array[start];
                start++;
            }
            if (sum == k) {
                return true;
            }
        }
        return false;
    }

}

Unit tests.

import static org.junit.Assert.*;

import org.junit.Test;

public class MainTest {

    @Test
    public void testFindSum() {
        // k exists in the input array

        // It's the first element
        assertTrue(Main.findSum(new int[] { 15, 4, 6, 10, 2, 11 }, 15));
        // It's in the middle
        assertTrue(Main.findSum(new int[] { 1, 4, 15, 10, 2, 11 }, 15));
        // It's the last element
        assertTrue(Main.findSum(new int[] { 1, 4, 0, 10, 2, 15 }, 15));

        // k equals to the sum of a few elements

        // The elements are at the beginning
        assertTrue(Main.findSum(new int[] { 10, 4, 4, 10, 2, 16 }, 14));

        // The elements are at the middle
        assertTrue(Main.findSum(new int[] { 1, 4, 4, 10, 2, 16 }, 14));

        // The elements are at the end
        assertTrue(Main.findSum(new int[] { 1, 4, 4, 1, 1, 13 }, 14));

        // k is the sum of all the elements
        assertTrue(Main.findSum(new int[] { 1, 4, 4, 1, 4 }, 14));

        // There is an element which is greater than k
        // It's in the middle
        assertFalse(Main.findSum(new int[] { 1, 42, 4, 1, 4 }, 14));

        // It's the first element
        assertFalse(Main.findSum(new int[] { 42, 1, 4, 1, 4 }, 14));

        // It's the last element
        assertFalse(Main.findSum(new int[] { 1, 0, 4, 1, 42 }, 14));

        // Last but one
        assertFalse(Main.findSum(new int[] { 1, 0, 4, 144, 12 }, 14));

        // Worst case
        assertTrue(Main.findSum(new int[] { 1, 3, 4, 1, 0, 23 }, 23));

    }

}

GitHub


texts: User Access Authorization for Web Resources

texts:
Im refactoring a large internal legacy application and part of the stuff I want to get rid is the  widespread code repetition.

I'm starting with the way the website checks if a User can access a route e.g., '/admin` and which parts should be rendered or not.

I made this little function and works pretty well but wanted to see if you could take a look into it and suggest improvements or point out problems with the way I built it.

Anyway, here's the code:

export default async function isAdmin(alias, policyOverride = null) {
    try {
        var authResult = false;
        const url = 'https://xxx.execute-api.us-west-2.amazonaws.com/local/xxxx/';

        var adminRolePolicy = ['Admin', 'Dev', 'BaseUser']; //Default Admin Policy.

        var rolesBoundToAlias = (await axios.get(url + alias)).data //Fetch roles that the alias holds.

        if(policyOverride){
            adminRolePolicy = policyOverride;
        } //If a new policy is, override the default adminRolePolicy.

        authResult =
            rolesBoundToAlias.some(role => adminRolePolicy.includes(role)); //If alias has any of the roles in the policy grant access.

        return authResult;
    } catch (error) {
        console.error("Error when attempting to authorize user " + alias
            + ". Access for this user has been denied, please try again."
            + "\nError: " + error);
        return false;
    }
}

I added the policyOverride as an optional param so the function can accept an array with different roles... allowing for more flexibility.

One of the most simple applications for this function would be as follows:

import isAdmin from '../utils/authorization.js';
//Other stuff happens here.
//...
isAdmin(alias)
.then((authResult) => {
    if(authResult) {
        //Authorized to view content render this.
    }
    else {
        //Else render a 403 or something...
    }
}


texts: Generic Null/Empty check for each property of a class

texts:
I have created a method to check for null/empty values of class properties and if any null property is found I'm stopping the checking process and returning the result as true. I've used a solution from here and following is the code I have implemented:

/// To check the properties of a class for Null/Empty values
/// </summary>
/// <param name="obj">The instance of the class</param>
/// <returns>Result of the evaluation</returns>
public static bool IsAnyNullOrEmpty(object obj)
{
    //Step 1: Set the result variable to false;
    bool result = false;

    try
    {
        //Step 2: Check if the incoming object has values or not.
        if (obj != null)
        {
            //Step 3: Iterate over the properties and check for null values based on the type.
            foreach (PropertyInfo pi in obj.GetType().GetProperties())
            {
                //Step 4: The null check condition only works if the value of the result is false, whenever the result gets true, the value is returned from the method.
                if (result == false)
                {
                    //Step 5: Different conditions to satisfy different types
                    dynamic value;
                    if (pi.PropertyType == typeof(string))
                    {
                        value = (string)pi.GetValue(obj);
                        result = (string.IsNullOrEmpty(value) ? true : false || string.IsNullOrWhiteSpace(value) ? true : false);
                    }
                    else if (pi.PropertyType == typeof(int))
                    {
                        value = (int)pi.GetValue(obj);
                        result = (value <= 0 ? true : false || value == null ? true : false);
                    }
                    else if (pi.PropertyType == typeof(bool))
                    {
                        value = pi.GetValue(obj);
                        result = (value == null ? true : false);
                    }
                    else if (pi.PropertyType == typeof(Guid))
                    {
                        value = pi.GetValue(obj);
                        result = (value == Guid.Empty ? true : false || value == null ? true : false);
                    }
                }
                //Step 6 - If the result becomes true, the value is returned from the method.
                else
                    return result;
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    //Step 7: If the value doesn't become true at the end of foreach loop, the value is returned.
    return result;
}

I want to extend this code to another end that instead of sending the bool result as true or false, I'll clone the incoming object and based on the values inside the properties can send the object.

For example:

Let's say this is my model: Order.cs

public class Order
{

    [DataMember]
    public Guid OrderId { get; set; }

    [DataMember]
    public string Owner { get; set; }

    [DataMember]
    public string Info { get; set; }

    [DataMember]
    public string Recipient { get; set; }

    [DataMember]
    public int Test { get; set; }

    [DataMember]
    public DateTime CreatedOn { get; set; }
}

Now if there is any null or empty value in any of the properties, I'll be returning a new class which contains only those values which are either null and empty and the status of it as:

//This class is the output class from the IsAnyNullOrEmpty() method and has only those properties which are either null or empty
public class ProcessedModel
{
    public string Property1 { get; set; }   //has null value in type String (set property vaule to "Null value")

    public string Property2 { get; set; } //has empty value in type String (set property vaule to "Empty value")

    public string Property3 { get; set; } //has 0 value in type int (set property vaule to "0 value")
}

Am I following the right approach?


texts:
I am a beginner in Zend Framework 3 and I want to hear your opinions about the code that I wrote. I don't know how exactly I can connect forms, and validators together that the code will be quite nice and readable.

Register method

 public function registerAction()
    {
        $form = $this->form;
        $viewModel = new ViewModel(['form' => $form]);
        $prg = $this->prg('users', false);

        if ($prg instanceof \Zend\Http\PhpEnvironment\Response)
            return $prg;

        elseif ($prg === false)
            return $viewModel;

        $loginExistsValidator = new NoRecordExists(
            [
                'table' => 'users',
                'field' => 'login',
                'adapter' => $this->command->getAdapter()
            ]
        );
        $loginExistsValidator->setMessage('Istnieje już użytkownik o podanym loginie');

        $emailExistsValidator = new NoRecordExists(
            [
                'table' => 'users',
                'field' => 'email',
                'adapter' => $this->command->getAdapter()
            ]
        );
        $emailExistsValidator->setMessage('Ten email jest już zajęty...');

        $form->setInputFilter(new UsersFilter());
        $form->getInputFilter()->get('login')->getValidatorChain()->attach($loginExistsValidator);
        $form->getInputFilter()->get('email')->getValidatorChain()->attach($emailExistsValidator);
        $form->setData($prg);

        if (!$form->isValid())
            return $viewModel;

        $users = $this->command->addUser($form->getData());

        $viewModel->setTemplate('users/register/registerSukcesfull');

        return ['users' => $users];
    }

usersFilter

    <?php
/**
 * Created by PhpStorm.
 * User: Patryk
 * Date: 2016-10-09
 * Time: 12:19
 */namespace Users\Filters;

use Users\Services\RegisterServices;
use Zend\Filter\Callback;
use Zend\Filter\StringTrim;
use Zend\InputFilter\InputFilter;
use Zend\Validator\Db\NoRecordExists;
use Zend\Validator\Db\RecordExists;
use Zend\Validator\EmailAddress;
use Zend\Validator\Regex;
use Zend\Validator\StringLength;

class UsersFilter extends InputFilter
{
    public function __construct()
    {
        $this->add([
                'name' => 'login',
                'required' => true,
                'filters' => [
                    [
                        'name' => StringTrim::class
                    ]
                ],

                'validators' => [

                    [
                        'name' => StringLength::class,
                        'options' => [
                            'min' => 5
                        ]
                    ],

                ],
            ]

        );
        $this->add([
                'name' => 'password',
                'required' => true,
                'validators' => [

                    [
                        'name' => StringLength::class,
                        'options' => [
                            'min' => 12
                        ]
                    ],
                ],
            ]

        );

        $this->add([
                'name' => 'email',
                'required' => true,
                'validators' => [
                    [
                        'name' => EmailAddress::class,
                        'options' =>
                        [
                            'domains' => true
                        ]
                    ]
                ]

        ]);
    }

}


texts: Intel® TinyCrypt: AES-128/CTR to encryption/decryption of 2D arrays

texts:
I need to encrypt/decrypt 2D arrays (double pointers) using AES-128/CTR using Intel TinyCrypt (written in C). The following are two helper methods to simplify the library usage. Any comments would be highly appreciated. Thanks in advance.

#include <tinycrypt/constants.h>
#include <tinycrypt/ctr_mode.h>
#include <tinycrypt/aes.h>

#define AES_128_KEY_LENGTH 16
#define AES_128_CTR_LENGTH 16

typedef struct aes_128_ctr_params_t{
  byte key[AES_128_KEY_LENGTH];
  byte ctr[AES_128_CTR_LENGTH];
} aes_128_ctr_params_t;

//---------------------------------------------------------------------------
inline int32_t encrypt(uint8_t const * const * const plaintext,
                       uint8_t * const * const cihpertext,
                       size_t const height,
                       size_t const width,
                       aes_128_ctr_params_t params) {
  //TODO: Do some validation here!

  struct tc_aes_key_sched_struct sched;
  uint32_t result = TC_CRYPTO_SUCCESS;
  result = tc_aes128_set_encrypt_key(&sched, params.key);
  if (result != TC_CRYPTO_SUCCESS)
    return result;

  size_t const row_size_in_bytes = sizeof(uint8_t) * width;
  for (size_t row_index = 0; row_index < height; ++row_index) {
    result = tc_ctr_mode(cihpertext[row_index], row_size_in_bytes,
      plaintext[row_index], row_size_in_bytes, params.ctr, &sched);

    if (result != TC_CRYPTO_SUCCESS)
      return result;
  }
}

//---------------------------------------------------------------------------
inline int32_t decrypt(uint8_t const * const * const cihpertext,
                       uint8_t * const * const plaintext,
                       size_t const height,
                       size_t const width,
                       aes_128_ctr_params_t params) {
  //TODO: Do some validation here!

  struct tc_aes_key_sched_struct sched;
  uint32_t result = TC_CRYPTO_SUCCESS;
  result = tc_aes128_set_encrypt_key(&sched, params.key);
  if (result != TC_CRYPTO_SUCCESS)
    return result;

  size_t const row_size_in_bytes = sizeof(uint8_t) * width;
  for (size_t row_index = 0; row_index < height; ++row_index) {
    result = tc_ctr_mode(plaintext[row_index], row_size_in_bytes,
      cihpertext[row_index], row_size_in_bytes, params.ctr, &sched);

    if (result != TC_CRYPTO_SUCCESS)
      return result;
  }
}


texts:
I have two helper methods that return li for view with the li for current view having id as selected.

def get_li(a)
  li = "<li"
  li += ' id=selected' if (a[:controller] == params[:controller] && a[:action] == params[:action])
  li += ">" + link_to(a[:text], { :controller => a[:controller], :action => a[:action]}) + "</li>"
end

def get_tab_options
  if (params[:controller] == 'sessions' || params[:controller] == 'users')
    [{:text => "Login", :controller => 'sessions', :action => 'new'},
     {:text => "Sign Up", :controller => 'users', :action => 'new'}]
  elsif (params[:controller] == 'meetings')
    [{:text => "Meetings List", :controller => 'meetings', :action => 'index'},
     {:text => "Create Meeting", :controller => 'meetings', :action => 'new'},
     {:text => "Running Meetings", :controller => 'meetings', :action => 'monitor'}]
  end
end

And the view file has

 %ul
   -get_tab_options.each do |a|
     = get_li(a)

How can I write this better?


texts: Function to find all occurrences of substring

texts:
This function returns a list of all the beginning indices of a substring in a string. After finding the index of a substring, the search for the next one begins just after this index.

def find_substring(substring, string):
    """
    Returns list of indices where substring begins in string

    >>> find_substring('me', "The cat says meow, meow")
    [13, 19]
    """
    indices = []
    index = -1  # Begin at -1 so index + 1 is 0
    while True:
        # Find next index of substring, by starting search from index + 1
        index = string.find(substring, index + 1)
        if index == -1:
            break  # All occurrences have been found
        indices.append(index)
    return indices


texts:
I've written an implementation of a Stack data structure using a linked list.

Stack.java

import java.util.EmptyStackException;

public class Stack<T> {

    private class Node {

        private T data;
        private Node prev, next;

        public Node() {
        }

        public Node(T data) {
            this.data = data;
        }
    }

    private Node top;

    public Stack() {
        top = null;
    }

    public boolean empty() {
        return top == null;
    }

    public T peek() {
        if (top == null) {
            throw new EmptyStackException();
        }
        return top.data;
    }

    public T pop() {
        if (top == null) {
            throw new EmptyStackException();
        }
        T value = top.data;
        top = top.prev;
        return value;
    }

    public T push(T data) {
        Node temp = new Node(data);
        if (top == null) {
            top = temp;
        } else {
            top.next = temp;
            temp.prev = top;
            top = temp;
        }
        return temp.data;
    }
}


texts: Custom maximumBy and minimumBy in Haskell

texts:
Going through the magnificent Haskell Programming from first principles, I'm currently reimplementing functions from standard libraries such as maximumBy and minimumBy.

Here are my current versions of them:

myMaximumBy :: (a -> a -> Ordering) -> [a] -> a
-- maximumBy in Data.List also throws an error on empty lists
myMaximumBy _ [] = error "empty list"
myMaximumBy f (x:xs) =
  foldr (\curMax x -> if f x curMax == GT then x else curMax) x xs

myMinimumBy :: (a -> a -> Ordering) -> [a] -> a
myMinimumBy f = myMaximumBy $ flip f

I know they're not total functions, but I'll get to rewriting them with something like Maybe later on.

I'm happy for any kind of feedback on how to make the code shorter, more readable, or more idiomatic.


texts:
In most of the range query-update questions, we are asked to update some range of the array with some constant_value which can be done using the segment-tree approach. For more optimizations we can use the segment-tree with lazy propagation approach.

But in this question, we are asked to update given range with some given series. In which I faced some difficulties with lazy propagation approach like:

How to keep track of consecutive updates.
If we store some update_value to some parent-node, but when we propagate this update to its children, how to determine which child contributed what part of the update_value.

#include <bits/stdc++.h>

using namespace std;

#define MOD 1000000007

list <int>lazy[3600020];
int tree[3600020],n,q,i,x,y;
short choice;

inline int M(long long x)
{
    if(x%3)
        return (((((x+1)*(x+2)/3)%MOD)*x)%MOD);
    return ((((x*(x+1)/3)%MOD)*(x+2))%MOD);
}

inline void update_node_lazy(int node,int a,int b)
{
    while(!lazy[node].empty())
    {
        tree[node] = (tree[node] + M(b-lazy[node].front()+1) - M(a-lazy[node].front()))%MOD;
        if(a != b)
        {
            lazy[2*node].push_front(lazy[node].front());
            lazy[2*node+1].push_front(lazy[node].front());
        }
        lazy[node].pop_front();
    }
}

inline void update_tree_lazy(int node, int a, int b, int i, int j)
{
    update_node_lazy(node,a,b);
    if(a>b || a>j || b<i)
        return;
    if(a >= i && b <= j)
    {
        tree[node] = (tree[node] + M(b-i+1) - M(a-i))%MOD;
        if(a != b)
        {
            lazy[2*node].push_front(i);
            lazy[2*node+1].push_front(i);
        }
        return;
    }
    update_tree_lazy(node*2, a, (a+b)/2, i, j);
    update_tree_lazy(1+node*2, 1+(a+b)/2, b, i, j);
    tree[node] = (tree[node*2] + tree[node*2+1])%MOD;
}

inline int query_tree_lazy(int node, int a, int b, int i, int j)
{
    if(a > b || a > j || b < i)
        return 0;
    update_node_lazy(node,a,b);
    if(a >= i && b <= j)
        return tree[node];
    return (query_tree_lazy(node*2, a, (a+b)/2, i, j) + query_tree_lazy(1+node*2, 1+(a+b)/2, b, i, j))%MOD;
}

int main()
{
    cin >> n >> q;
    while(q--)
    {
        cin >> choice >> x >> y;
        if(choice == 1)
            update_tree_lazy(1,0,n-1,x-1,y-1);
        else
            printf("%d\n",query_tree_lazy(1,0,n-1,x-1,y-1));
    }
    return 0;
}

But this approach didn't help much, so I need a better approach or some optimization suggestions.


texts: Minimal length of substring that forms cyclic string

texts:
there is a knows problem stated as "Cyclic string":

A string S has been recorded many times, and then from the resulting line took a substring, and give to you.Your task is to determine the minimum possible length of a string S.
Input
In the first and only line of the input file contains a string that contains only letters, line length up to 50000 characters.
Output
The output file you want to display a single number - the answer to the problem.

It can be solved with substring hashes (source).
I composed a solution:
 bool substring_eq(const vector<uint64_t> &p_pow, const vector<uint64_t> &h,
                   size_t i1, size_t i2, size_t len) {
     uint64_t h1 = h[i1 + len - 1];
     if (i1) h1 -= h[i1 - 1];
     uint64_t h2 = h[i2 + len - 1];
     if (i2) h2 -= h[i2 - 1];

     return (i1 < i2 && (h1 * p_pow[i2 - i1]) == h2) ||
            (i1 > i2 && h1 == (h2 * p_pow[i1 - i2]));
 }

 void compute_hashes(const string &s, vector<uint64_t> &p_pow, vector<uint64_t> &h) {
     const int p = 191;
     p_pow[0] = 1;
     for (size_t i = 1; i < p_pow.size(); ++i) {
         p_pow[i] = p_pow[i - 1] * p;
     }

     for (size_t i = 0; i < s.length(); ++i) {
         h[i] = (s[i] - 'A' + 1) * p_pow[i];
         if (i) h[i] += h[i - 1];
     }
 }

 size_t solve(const string &s) {
     vector<uint64_t> p_pow(s.length()), hashes(s.length());

     compute_hashes(s, p_pow, hashes);

     size_t cycle_len = s.length();
     for (size_t k = 1; k < s.length(); ++k) {
         if (substring_eq(p_pow, hashes, 0, k, s.length() - k)) {
             cycle_len = k;
             break;
         }
     }
     return cycle_len;
 }

 int main() {
     //test();

     string input;
     cin >> input;
     cout << solve(input) << std::endl;
     return 0;
 }

I can't passed the last test in e-judging system (I don't know the contents of it).
I even composed a function that generates input strings, but it catches no errors:
 //////////////////////////
 /// Stress testing
 //////////////////////////
 #include <random>

 std::string random_string(std::string::size_type length) {
     static auto &chrs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

     static std::mt19937 rg{std::random_device{}()};
     static std::uniform_int_distribution<std::string::size_type> pick(0, sizeof(chrs) - 2);

     std::string s;

     s.reserve(length);

     while (s.length() < length) {
         char ch = chrs[pick(rg)];
         if (s.find(ch) == string::npos) {
             s += ch;
         }
     }

     return s;
 }

 size_t solve(const string &s);
 void test() {
     srand(100);
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wmissing-noreturn"
     while (true) {
         string::size_type len = (unsigned long) (rand() % 50 + 1);
         string s = random_string(len);
         int count = rand() % 5000 + 2;
         string input;
         for (int i = 0; i < count; ++i) {
             input += s;
         }
         string input1 = input;
         input1 = input1.substr(rand() % (input1.length() - s.length()));
         input1 = input1.substr(0, rand() % (input1.length() - s.length()) + s.length());

         if (input1.empty()) continue;

         size_t k = solve(input1);
         if (k != s.length()) {
             cout << "boom:" << input1;
         }
     }
 #pragma clang diagnostic pop
 }
 //////////////////////////

What else did I miss in the solution?


texts:
Background

This is my first experience with functional programming and totally self-study. I just have 2-3 days' worth experience in Haskell. Now let's continue with actual code.

For Problem 2 of 99 haskell problems I wrote this function

module Functions
(
lastButOne
) where

lastButOne :: [a] -> a
lastButOne [a, b] = a
lastButOne (_:xs) = lastButOne xs
lastButOne a = error "Not Supported"

Is this code ok from functional programming perspective? I am open to criticism from any perspective.

EDIT 1

Code after @Pedro Rodrigues suggestions

lastButOne :: [a] -> a
lastButOne [a, _] = a
lastButOne (_:xs) = lastButOne xs
lastButOne _ = error "lastButOne requires a list with at least 2 members"


texts: Dice roll simulator (updated) created using Python 3.5 and PyQt5

texts:
from random import choice
from sys import (exit, argv)
from time import sleep

from PyQt5.QtCore import Qt
from PyQt5.QtGui import (QIcon, QPixmap, QFont)
from PyQt5.QtWidgets import (QToolTip, QPushButton, QApplication,
                             QWidget, QLabel, QComboBox, QDesktopWidget)

ICON = 'icon.png'
DICE = ('dice_1.png', 'dice_2.png', 'dice_3.png', 'dice_4.png', 'dice_5',
        'dice_6.png')
ROLLING_ANIMATION = 'dice_rolling_animation.png'
SCALED_PARMS = 162, 302, Qt.KeepAspectRatio, Qt.FastTransformation
ONE_DIE_PARMS = 1427, 30, 162, 201
TWO_DICE_PARMS = 1265, 30, 324, 201
SLEEP_TIME = 0.5

class DiceRollSimulator(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.die1 = QLabel(self)
        self.die1.setPixmap(QPixmap(choice(DICE)).scaled(*SCALED_PARMS))
        self.die1.move(0.5, 0.5)

        self.die2 = QLabel(self)
        self.die2.setPixmap(QPixmap(choice(DICE)).scaled(*SCALED_PARMS))
        self.die2.move(162, 0.5)
        self.die2.setVisible(False)

        self.btn = QPushButton('Roll', self)
        self.btn.setFont(QFont('SansSerif', 20))
        self.btn.setToolTip('Click to Roll Die')
        self.btn.clicked.connect(self.rolldie)
        self.btn.resize(166, 43)
        self.btn.move(-2, 161)

        self.dice_amount = QComboBox(self)
        self.dice_amount.addItems(['1', '2'])
        self.dice_amount.activated[str].connect(self.dice_amount_changed)
        self.dice_amount.move(135, -2)

        QToolTip.setFont(QFont('SansSerif', 10))
        QApplication.desktop()
        screen = QDesktopWidget().screenGeometry()
        self.setFixedSize(162, 201)
        x = screen.width() - self.width() - 15
        self.move(x, 1)
        self.setWindowTitle('Dice Roll Simulator')
        self.setWindowIcon(QIcon(ICON))
        self.show()

    def rolldie(self):
        self.die1.setPixmap(QPixmap(ROLLING_ANIMATION).scaled(*SCALED_PARMS))
        self.die2.setPixmap(QPixmap(ROLLING_ANIMATION).scaled(*SCALED_PARMS))
        QApplication.processEvents()
        sleep(SLEEP_TIME)
        self.die1.setPixmap(QPixmap(choice(DICE)).scaled(*SCALED_PARMS))
        self.die2.setPixmap(QPixmap(choice(DICE)).scaled(*SCALED_PARMS))
        QApplication.processEvents()

    def dice_amount_changed(self):
        geo = str(self.geometry())
        geo2 = geo[19:len(geo) - 1]
        loc = [int(x) for x in geo2.split(',')]

        if self.dice_amount.currentText() == '1':
            self.setFixedSize(162, 201)
            x = loc[0] + 154
            y = loc[1] - 30
            self.move(x, y)
            self.die2.setVisible(False)
            self.btn.resize(166, 43)
            self.dice_amount.move(132, -2)

        else:
            self.setFixedSize(324, 201)
            x = loc[0] - 170
            y = loc[1] - 30
            self.move(x, y)
            self.die2.setVisible(True)
            self.btn.resize(328, 43)
            self.dice_amount.move(294, -2)

if __name__ == '__main__':

    app = QApplication(argv)
    ex = DiceRollSimulator()
    ex.show()
    exit(app.exec_())

This is the updated version of the dice roll simulator code I posted some time ago. I've made several changes and additions including ones suggested by users here.


texts:
I just completed Project Euler problem 18 which is a dynamic programming question through a graph of a triangle of numbers. The goal is to find the path from top to bottom of the triangle that has the largest sum.

In the example below the path is 3->7->4->9.

Say the numbers in the triangle are:

   3
  7 4
 2 4 6
8 5 9 3

I built a jagged array that looks like:

int[][] triangleNumbers = new int[4][]
{
    new int[] {3},
    new int[] {7, 4},
    new int[] {2, 4, 6},
    new int[] {8, 5, 9, 3},
};

Then I made a custom object TriangleNode and converted the numbers into TriangleNodes. Then I went through and connected the lower left and lower right nodes to their parent so I could graph traverse them easily.

//build triangle graph
TriangleNode[][] triangleGraph = new TriangleNode[triangleNumbers.Length][];

for(int row = 0; row < triangleNumbers.Length; row++)
{
    triangleGraph[row] = new TriangleNode[triangleNumbers[row].Length];
    for(int col = 0; col < triangleNumbers[row].Length; col++)
    {
            //create the Node and save the value
        triangleGraph[row][col] = new TriangleNode(triangleNumbers[row][col]);
    }
}

//connect triangle graph
for(int row = 0; row < triangleGraph.Length; row++)
{
    for(int col = 0; col < triangleGraph[row].Length; col++)
    {
        if(row + 1 == triangleGraph.Length)
        {
                    //bool for easy graph traversing to check if I'm at the bottom row
            triangleGraph[row][col].IsEnd = true;
        }
        else
        {
                    //hook up the Left/Right pointers
            triangleGraph[row][col].Left = triangleGraph[row + 1][col];
            triangleGraph[row][col].Right = triangleGraph[row + 1][col + 1];
        }
    }
}

Obviously this is a ton of code just to build the graph.

Is there an easier way to build this graph? The requirements are that each TriangleNode holds its value and Left/Right pointers to the Nodes in the row directly below. I was thinking there might be some voodoo magic via LINQ to turn the triangleNumbers[][] into the triangleGraph[][], then some more voodoo to hook up the Left/Right pointers.