texts: A simple thread safe LRU cache using unordered map and lists in C++

texts:
I am learning concurrent programming and am writing a thread safe LRU cache for practice. Below is my first attempt. Kindly comment and let me know where I can improve.

PS: There have already been a few questions asked on this topic but a more toned down version will help me understand the underlying concept of concurrency.

#include "stdafx.h"
#include <iostream>
#include <unordered_map>
#include "thread"
#include "mutex"

class LRUCache
{

    std::mutex mu;

private:
    int cacheSize;
    std::unordered_map<int, std::pair<int, std::list<int>::iterator>> cache;
    std::list<int> lru;
    void update(std::unordered_map<int, std::pair<int, std::list<int>::iterator>>::iterator &it);

public:
    void setSize(int size);
    int get(int key);
    void set(int key, int value);
};

void LRUCache::setSize(int size)
{
    std::lock_guard <std::mutex> locker(mu);
    cacheSize = size;
}

int LRUCache::get(int key)
{
    std::lock_guard <std::mutex> locker(mu);
    auto item = cache.find(key);

    if (item == cache.end())
    {
        return -1;
    }

    update(item);

    return item->second.first;
}

void LRUCache::set(int key, int value)
{
    std::lock_guard <std::mutex> locker(mu);

    auto item = cache.find(key);

    if (item != cache.end())
    {
        update(item);
        cache[key] = { value, lru.begin() };
        return;
    }

    if (cache.size() == cacheSize)
    {
        cache.erase(lru.back());
        lru.pop_back();
    }

    lru.push_front(key);
    cache.insert({ key,{ value, lru.begin() } });
}

void LRUCache::update(std::unordered_map<int, std::pair<int, std::list<int>::iterator>>::iterator &it)
{
    lru.erase(it->second.second);
    lru.push_front(it->first);
    it->second.second = lru.begin();
}

void function2(LRUCache *lruCache)
{
    lruCache->set(5, 5);
    lruCache->set(6, 6);
    lruCache->set(1, 1);

    std::cout << "F2::Successful Execution: " << lruCache->get(4) << std::endl;

    lruCache->set(8, 8);

    std::cout << "F2::Successful Execution: " << lruCache->get(1) << std::endl;
}

void function1(LRUCache *lruCache)
{
    lruCache->set(1, 1);
    lruCache->set(2, 2);
    lruCache->set(3, 3);

    std::cout << "F1::Successful Execution: " << lruCache->get(3) << std::endl;

    lruCache->set(4, 4);

    std::cout << "F1::Successful Execution: " << lruCache->get(2) << std::endl;
}

int main() {

    LRUCache *lruCache = new LRUCache();
    lruCache->setSize(2);

    std::thread t1(function1, lruCache);
    t1.join();

    std::thread t2(function2, lruCache);
    t2.join();

    return 0;
}


texts:
I wanted to implement a selection sort and wanted to make sure that I'm doing it correctly. I wanted to do it in a way that's efficient and use recursion. Please let me know if I am doing this correctly or if there is a better way for me to do it.

 /**
 * selectionSort
 * @param toSort
 * @param sorted
 * @returns {Array}
 */
function selectionSort(toSort, sorted=[]) {
    if (!toSort.length) {
        return sorted;
    }
    let minIndex = findMinimum(toSort);
    sorted.push(...toSort.splice(minIndex, 1))
    return selectionSort(toSort, sorted);
}

function findMinimum(arr) {
    let minIndex=0;
    arr.forEach(function (item, index) {
        if(item < arr[minIndex]) {
            minIndex = index;
        }
    })
    return minIndex;
}

const testCase = [64, 25, 12, 22, 11]
const answer = selectionSort(testCase);


texts:
https://leetcode.com/problems/spiral-matrix-ii/
Please review for performance, how can this code run faster

  Given a positive integer n, generate a square matrix filled with
  elements from 1 to n^2 in spiral order.

  Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{

    /// <summary>
    /// https://leetcode.com/problems/spiral-matrix-ii/
    /// </summary>
    [TestClass]
    public class SpiralMatrix2Test
    {
        [TestMethod]
        public void Example3x3Test()
        {
            int size = 3;
            int[][] expected =
            {
                new[]{1,2,3},
                new [] {8,9,4},
                new []{7,6,5}
            };
            int[][] res= SpiralMatrix2.GenerateMatrix(size);
            for (int i = 0; i < size; i++)
            {
                CollectionAssert.AreEqual(expected[i],res[i]);
            }
        }
}

    public class SpiralMatrix2
    {
        public static int[][] GenerateMatrix(int n)
        {

            int startCol = 0;
            int endCol = n - 1;
            int startRow = 0;
            int endRow = n - 1;
            int num = 1;
            int[][] res = new int[n][];
            for (int i = 0; i < n; i++)
            {
                res[i] = new int[n];
            }

            if (n == 0)
            {
                return res;
            }

            while (startCol <= endCol && startRow <= endRow)
            {
                for (int i = startCol; i <= endCol; i++)
                {
                    res[startRow][i] = num++;
                }
                startRow++;// already did this row skip to the next one

                for (int i = startRow; i <= endRow; i++)
                {
                    res[i][endCol] = num++;
                }

                endCol--;// already did the last col move back one col

                for (int i = endCol; i >= startCol; i--)
                {
                    //keep in mind this is a spiral we can be in a line we are not suppose to touch the values
                    //only in the upper half of the matrix we need
                    if (startRow <= endRow)
                    {
                        res[endRow][i] = num++;
                    }
                }
                endRow--;

                for (int i = endRow; i >= startRow; i--)
                {
                    //we need to print the numbers only in the left half of the matrix
                    if (startCol <= endCol)
                    {
                        res[i][startCol] = num++;
                    }
                }

                startCol++;
            }
            return res;

        }
    }
}


texts:
I could not find a compile time counter/accumulator to achieve something like the following:

#define DECLARE_VAR(type, varName) \
   type varName;                   \
   ADD_TO_ACCUMULATOR(sizeof(type));

DECLARE_VAR(float, var1);
DECLARE_VAR(bool, var2);
constexpr int total = GET_ACCU_AND_ADD(0);
static_assert(total == 5);

So I came up with the following:

#define GET_ACCU_AND_ADD_IMPL(number, counterIndex)     \
    summer<counterIndex>::get();                          \
        template<>                                        \
    struct summer<counterIndex+1> {                        \
        constexpr static int get() {                        \
            return summer<counterIndex>::get() + (number);  \
        }                                                     \
    };

#define ADD_TO_ACCUMULATOR_IMPL(number, counterIndex)     \
        template<>                                        \
    struct summer<counterIndex+1> {                        \
        constexpr static int get() {                        \
            return summer<counterIndex>::get() + (number);  \
        }                                                     \
    };

#define GET_ACCU_AND_ADD(number) \
    GET_ACCU_AND_ADD_IMPL(number, __COUNTER__)

#define ADD_TO_ACCUMULATOR(number) \
    ADD_TO_ACCUMULATOR_IMPL(number, __COUNTER__)

template<int tIndex>
struct summer {
    constexpr static int get() {
        static_assert(tIndex == 0, "should not be called/instantiated");
        return 0;
    }
};

template<>
struct summer<0> {
    constexpr static int get() {
        return 0;
    }
};

Downsides:

Relies on __ COUNTER __
?

Feedback is appreciated, maybe there are already better solutions out here?


texts:
So this is my full script that I've been working on. My plan is to Create New, Folder, Create AD Group FS-TESTSHARE-R, Create AD Group FS-TESTSHARE-RW, Apply Both groups to the new share folder, Set Full Read permissions to FS-TESTSHARE-R, Set Full Read/Rights permissions to FS-TESTSHARE-RW, and Set full access permissions to Domain Admins and local Administrators.

I'm Pretty sure I have all of the syntax correct now (thanks to some awesome assistance I've received here), but I was hoping for some clarification on setting ACLs.

At the bottom I've redone how I was attempting to get, create, and set the ACLs Thanks to @themadtechnician), but I was curious as to if I've got all syntax correct or if I should create the set for each of the $objUser instead of putting them all in parentheses (is this the cleanest way to do this)...

$Parent = read-host -prompt "Enter full parent path that will contain the new folder (ie. \\eccofs01\Groups\ECCO IT\)"
$Name = read-host -prompt "Enter New Folder Name."
$Path = "$($parent)$($Name)"
$Location = read-host -prompt "Enter the AD Security Group Location (i.e. Global, Americas, Europe, Asia Pacific)"

Import-Module ActiveDirectory

#Create Security Groups
$GroupParams1= @{
    'Name' = "FS-$NAME-RW"
    'SamAccountName' = "FS-$NAME-RW"
    'GroupCategory' = "Security"
    'GroupScope' = "Global"
    'DisplayName' = "$NAME Read-Write Access"
    'Path' = "CN=$LOCATION,CN=SECURITY GROUPS,CN=FILE SHARE GROUPS,DC=ESG,DC=INTL"
    'Description' = "Members of this group have read-write access to $Path."
}

New-ADGroup @GroupParams1

$GroupParams2= @{
    'Name' = "FS-$NAME-R"
    'SamAccountName' = "FS-$NAME-R"
    'GroupCategory' = "Security"
    'GroupScope' = "Global"
    'DisplayName' = "$NAME Read-Write Access"
    'Path' = "CN=$LOCATION,CN=SECURITY GROUPS,CN=FILE SHARE GROUPS,DC=ESG,DC=INTL"
    'Description' = "Members of this group have read access to $Path"
}

New-ADGroup @GroupParams2

# Create New Folder
New-Item -Path $Path -ItemType Directory

#Set Full Control Permissions
$Rights = [System.Security.AccessControl.FileSystemRights]"FullControl"

$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]"ObjectInherit,ContainerInherit"
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None

$objType =[System.Security.AccessControl.AccessControlType]::Allow

$objUser = New-Object System.Security.Principal.NTAccount("Administrators","esg.intl\Domain Admins","esg.intl\FS-$NAME-RW")

$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)

$objACL = Get-ACL $Path

$objACL.AddAccessRule($objACE)

Set-ACL $Path $objACL

#Set Read and Execute Permissions
$Rights = [System.Security.AccessControl.FileSystemRights]"ReadAndExecute"

$InheritanceFlag = [System.Security.AccessControl.InheritanceFlags]"ObjectInherit,ContainerInherit"
$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None

$objType =[System.Security.AccessControl.AccessControlType]::Allow

$objUser = New-Object System.Security.Principal.NTAccount("esg.intl\FS-$NAME-R")

$objACE = New-Object System.Security.AccessControl.FileSystemAccessRule($objUser, $Rights, $InheritanceFlag, $PropagationFlag, $objType)

$objACL = Get-ACL $Path

$objACL.AddAccessRule($objACE)

Set-ACL $Path $objACL


texts: Competent addition of events in JavaScript

texts:
I want to write my own library. The main class in it is Event. It performs a lot of hard work. I want to make it so that the programmer, using this library, could add his small events like userEventFirst, userEventTwo, etc., in a specially designated place. That he did not look for this place, and was not mistaken, I want to give him an "interface".

Here is my class:

addEvent = function () {

    this.userEventFirst = function () {};
    this.userEventTwo = function () {};

    this.attachEvent = function (event, handler) {

        switch ( event ) {
            case 'eventFirst':  this.userEventFirst = handler;  break;
            case 'eventTwo':    this.userEventTwo = handler;    break;
        }

    };

    this.working = function () {

        this.userEventFirst();

        //... hard work
        var div = document.getElementById('text');
        div.innerHTML += 'class working
';

        this.userEventTwo();
    }

};

And here the programmer takes my class, and appends the actions:

// programmer use my class:

addEvent1 = new addEvent();

addEvent1.attachEvent('eventFirst', function() {

        var div = document.getElementById('text');
        div.innerHTML += 'user event First
' ;

});

addEvent1.attachEvent('eventTwo', function() {

        var div = document.getElementById('text');
        div.innerHTML += 'user event Two
' ;

});

addEvent1.working();

Everything is working. Only, how competently is it done? Performance may be lost, etc. Such events can be a dozen, they can be called in a cycle or in a timer. And the programmer can ask not all events, but only what he needs. You see, I've programmed before only in pascal.

jsFiddle


texts:
I'm learning about control structures now, and I want to see if I'm doing this as cleanly and efficiently as possible. Seems like there should be a less... verbose way of writing the switch but I wouldn't know what it is. Any criticism welcome!

FizzBuzz.java

public class FizzBuzz {

    public static final int fizz = 3;
    public static final int buzz = 5;

    public static void main(String[] args) {
        int status = -1;

        for (int fbNumber = 1; fbNumber <= 100; fbNumber++) {

            if ((fbNumber % fizz == 0) && (fbNumber % buzz == 0)) {
                status = 1;
            } else if ((fbNumber % fizz == 0) && (fbNumber % buzz != 0)) {
                status = 2;
            } else if ((fbNumber % fizz != 0) && (fbNumber % buzz == 0)) {
                status = 3;
            } else {
                status = 4;
            }
            switch (status) {
                case 1:
                    System.out.println("FizzBuzz");
                    break;
                case 2:
                    System.out.println("Fizz");
                    break;
                case 3:
                    System.out.println("Buzz");
                    break;
                case 4:
                    System.out.println(fbNumber);
                    break;
                default:
                    System.out.println("Number could not be evaluated");
            }
        }
    }
}


texts:
Add 2 strings representing 2 doubles, return the sum of the 2 doubles in string format. Please review my code. Is there a cleaner way of writing the code where we have to add the 2 doubles digit by digit?

for example, s1 is '9.9' and s2 is '8.8', we need to return '18.7'.
The requirement is that we cannot pad zeros for cases like adding '9.9' and '7.899'. In another word, we cannot change the input into '9.900' (i.e: with padded 0's) and '7.899'.

we have to add the two input digit by digit. For example, if s1 = '9.9' and s2 = '7.899', then we need to do 8+9 (the digit after the decimal point in s1 and s2), 9+7 (the two digits before the decimal points in s1 and s2). In another words, please do not use internal libraries to convert the two numbers into float and add them together.

def addDoubles(s1, s2):
    s1Split = s1.find('.')
    s2Split = s2.find('.')
    s1Post = ''
    s2Post = ''
    if s1Split != -1:
        s1Post = s1[s1Split+1:]
    if s2Split != -1:
        s2Post = s2[s2Split+1:]
    s1PostLen = len(s1Post)
    s2PostLen = len(s2Post)
    s1PostLonger = s2PostLonger = False
    postLenDiff = 0
    if s1PostLen > s2PostLen:
        #s2Post = s2Post + '0'*(s1PostLen-s2PostLen)
        s1PostLonger = True
        postLenDiff = s1PostLen - s2PostLen
    elif s1PostLen < s2PostLen:
        #s1Post = s1Post + '0'*(s2PostLen-s1PostLen)
        s2PostLonger = True
        postLenDiff = s2PostLen - s1PostLen
    if s1Split != -1:
        s1New = s1[:s1Split] + s1Post
    else:
        s1New = s1
    if s2Split != -1:
        s2New = s2[:s2Split] + s2Post
    else:
        s2New = s2
    postSum = helper(s1New, s2New, postLenDiff, s1PostLonger, s2PostLonger)
    print('s2PostLonger =', s2PostLonger)
    if s1PostLonger or (s1PostLonger == s2PostLonger == False and s1Post != ''):
        postSum = postSum[:-s1PostLen] + '.' + postSum[-s1PostLen:]
    elif s2PostLonger:
        postSum = postSum[:-s2PostLen] + '.' + postSum[-s2PostLen:]
    return postSum

def helper(one, two, postLenDiff, s1PostLonger, s2PostLonger):
    oneIdx = len(one)-1
    twoIdx = len(two)-1
    curSum = 0
    res = ''
    if s1PostLonger:
        res = one[-postLenDiff:]
        oneIdx = oneIdx - postLenDiff
    elif s2PostLonger:
        res = two[-postLenDiff:]
        twoIdx = twoIdx - postLenDiff
    while oneIdx >= 0 or twoIdx >= 0 or curSum>0:
        if oneIdx >= 0:
            curSum += int(one[oneIdx])
            oneIdx -= 1
        if twoIdx >= 0:
            curSum += int(two[twoIdx])
            twoIdx -= 1
        res = str(curSum%10) + res
        curSum //= 10
    return res


texts: Converting from Roman numerals to Arabic numbers

texts:
I got an idea to make a Roman/Arabic number converter, and I would like to hear your thoughts, where I could improve it, if there are Python specific things that I missed, so on and so forth.

# Decodes roman numerals
def get_arabic_numbers(t):
    # Hold the numbers in the list
    l = list()

    # The format
    format = 0

    # Convert from roman numeral to arabic number
    for i in range(0, len(t)):
        if t[i] == 'I':
            l.append(int(1))
        elif t[i] == 'V':
            l.append(int(5))
        elif t[i] == 'X':
            l.append(int(10))
        elif t[i] == 'L':
            l.append(int(50))
        elif t[i] == 'C':
            l.append(int(100))
        elif t[i] == 'D':
            l.append(int(500))
        elif t[i] == 'M':
            l.append(int(1000))

    # Calculate the format as follows:
    i = 0
    while i < len(l) - 1:
        # If the next numeral is greater than the current one, add the next one minus the current one = format = format + next_numeral - current_numeral
        if l[i] < l[i+1]:
            format = format + l[i+1] - l[i];
            i = i + 2
        # Else add it normally
        else:
            format = format + l[i]
            i = i + 1

    # Fix in case the last two numerals are equal
    if i == len(l):
        if l[i-2] == l[i-1]:
            format = format + l[i-1]
    else:
        format = format + l[i]

    # Return the format
    return format

# Encode an arabic digit to a roman numeral
def encode(l, c, one, five, nine):
    # The format to be returned
    format = ""

    # Special case 5.1: 5 has its own numeral 'V'
    # Special case 5.2: 50 has its own numeral 'A'
    # Special case 5.3: 500 has its own numeral 'D'
    if l[c] == 5:
        format = format + five
    elif l[c] < 5:
        for i in range(0, l[c]):
            format = format + one
    elif l[c] > 5:
    # Special case 9.1: 9 depends on 10, so it's 'IX'
    # Special case 9.2: 90 depends on 1000, so it's 'XC'
    # Special case 9.3: 900 depends on 1000, so it's 'CM'
        if l[c] == 9:
            format = format + nine
        else:
            format = format + five
            for i in range(6, l[c] + 1):
                format = format + one

    return format

# Encodes arabic numbers
def get_roman_numerals(t):
    # The arabic number to be converted
    t = int(t)
    # The list contains the number's digits
    l = list()

    # int is not iterable, so I wrote this to get the digits
    while t >= 1:
        l.append(int(t % 10))
        t = t / 10

    # They are in the wrong order, so the list has to be reversed
    l.reverse()

    # The format
    format = ""

    # Current position in the number
    c = 0

    # If the number is at least 1000
    if len(l) >= 4:
        num = 0

    # All the digits after 1000
    i = int(len(l) - 1)
    while i > 3:
        num = num + 1
        i = i - 1

    # A list containing these digits
    li = list()

    for i in range(0, num + 1):
        li.append(l[i])

    # Converts the list to an int
    n = map(str, li)
    n = ''.join(n)
    n = int(n)

    # Add an 'M' for every 1000
    for i in range(0, n):
        format = format + 'M'

    c = num + 1

    # If the number is also least 100
    if len(l) >= 3:
        format = format + encode(l, c, 'C', 'D', "CM")
        c = c + 1

    # If the number is at least 10
    if len(l) >= 3:
        format = format + encode(l, c, 'X', 'L', "XC")
        c = c + 1

    # If the number is at least 100 but smaller than 1000
    if len(l) > 2:
        format = format + encode(l, c, 'I', 'V', "IX")

    # If the number is at least 10 but smaller than 100
    if len(l) == 2:
        format = format + encode(l, c, 'X', 'L', "XC")
        c = c + 1
        format = format + encode(l, c, 'I', 'V', "IX")

    # If the number is at least 1 but smaller than 10
    if len(l) == 1:
        format = format + encode(l, c, 'I', 'V', "IX")

    return format


texts:
I'm new with Angular promise and I would like to know how to improve my code.

I have a service which preload media or data by calling an API.
The media API return an array of urls to preload.

'use strict';

angular.module('myApp').service('PreloaderService', ['$http', '$q', 'localStorageService', function PreloaderService($http, $q, localStorageService) {
  this.preload = function(key){
    var current = 0;
    var deferred = $q.defer();
    switch (key) {
      case 'media':
        // Simplified, in fact it call  a config service to get baseUrl
        var url = 'http://myapi/media';

        $http.get(url, {cache: true}).then(function(data) {
          var data = data.data;
          preloadImage(data, localStorageService.get('cachetoken'));
        }, function(data) {
          deferred.reject(data);
        });
        break;
      case 'data':
        var url = 'http://myapi/data';
        $http.get(url, {cache: true}).then(function(data) {
          var data = data.data;
          localStorageService.add('data', data);
          deferred.resolve(data);
        }, function(data) {
          deferred.reject(data);
        });
        break;
    }

    function preloadImage(arrayOfImages, cachetoken) {
      var promises = [];
      var totalImg = arrayOfImages.length;
      for (var i = 0; i < totalImg; i++) {
        (function(url, promise) {
          var img = new Image();
          img.onload = function() {
            var currentStatus = {
              currentImg: ++current,
              totalImg: totalImg
            };
            deferred.notify(currentStatus);
            promise.resolve();
          };
          img.src = url + '&tok=' + cachetoken;
        })(arrayOfImages[i], promises[i] = $.Deferred());
      }

      $.when.apply($, promises).done(function() {
        deferred.resolve('RESOLVED');
      }).fail(function(data) {
        deferred.reject(data);
      });
    }

    return deferred.promise;
  };
}]);

And I call it with

  var promise = Preloader.preload('media');
  promise.then(
    function(){
      $rootScope.preload.imagesLoaded = true;
    },
    function(){},
    function(currentStatus){
      $rootScope.preload.currentImg = currentStatus.currentImg;
      $rootScope.preload.totalImg = currentStatus.totalImg;
    }
  );


texts:
Is that standards-compliant?

#include <string>
#include <algorithm>
#include <iostream>
#include <cctype>

std::string remove_excessive_ws(std::string const &str)
{
    std::string result{ str };
    auto end{ std::remove_if(std::begin(result), std::end(result),
                             [](std::string::value_type const &ch) {
                                  return std::isspace(static_cast<unsigned>(ch)) &&
                                         (std::isspace(static_cast<unsigned>((&ch)[1])) || (&ch)[1] == '\0');
                             }
              )
    };
    result.erase(end, std::end(result));
    return result;
}

int main()
{
    char const *foo{ "Hello              World!       " };
    std::cout << '\"' << remove_excessive_ws(foo) << "\"\n";
}

I'm unsure whether I should be accessing (&ch)[1]. I think it should be legal, but I am not sure. After all, std::remove_if() could copy the character and pass it to the function, so the pointer (&ch) + 1 might not be valid.


texts: PHP code to scale images and generate thumbnails

texts:
I have written a piece of code by taking help from this link. For generating thumbnail, I create a temporary scaled image and then copy from that image. I am assuming that it is resource intensive.

Settings: the maximum values for target dimensions of scale images are predefined. Also, the thumbnail is always square and its side's value is also predefined.

The logic for my code is:
Maximum Target dimensions - 700X524
Thumbnail - 90X90

Get source image dimensions
Check if either of height or width is larger than 524 & 700 respectively
If yes,
Check if height> width.If yes,set height=524 and scaled width;else set width=700 and scale height.
create true color image from imagecreatettruecolor.
Generate scaled image with new dimensions from the original image

For thumbnail:

Check if either of scaled height and width is greater than 90
If yes, scale the shorter side to 90 and longer side accordingly.
Create a true color canvas of the further scaled dimensions.
Create a short image with the shorter side being 90 and larger one scaled accordingly
Create a true color canvas of dimensions 90X90
Copy thumbnail image to this canvas from the recently created shorter scaled image.

The code:

<?php

// default dimensions
//height : 524px
//width: 700px

$source_image = imagecreatefromjpeg("bg.jpg");
$source_imagex = imageSX($source_image);
$source_imagey = imagesy($source_image);

//destination image size calculation, should not exceed the target

//check if height and width are larger than required and then scale
if($source_imagey>524 || $source_imagex > 700) {
if($source_imagey>$source_imagex){
   $new_height = 524;
       $new_width = 524/$source_imagey*$source_imagex;
}else{
   $new_width = 700;
       $new_height = 700/$source_imagex*$source_imagey;
    }
 }

 $dest_image = imagecreatetruecolor($new_width, $new_height);

 //poor quality but fast
 imagecopyresized($dest_image, $source_image, 0, 0, 0, 0, $new_width,
 $new_height, $source_imagex, $source_imagey);
 imagejpeg($dest_image,"final.jpg", 80);

 //better quality but slow
 imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $new_width,
 $new_height, $source_imagex, $source_imagey);
 imagejpeg($dest_image, 'final2.jpg', 80);

 //create square thumbnail
 // resize image to scale shorter side to 90px
 if($new_width>90 || $new_height>90) {
    if($new_height>$new_width)
    {
       $thumb_height = (90/$new_width)*$new_height;
       $thumb_width = 90;
       $top = ($tHeight - 90)/2;
       $left = 0;
    }else{
   $thumb_width = (90/$new_height)*$new_width;
   $thumb_height = 90;
       $left = ($thumb_width-90)/2;
       $top = 0;
    }
 }
 $image_t = imagecreatetruecolor($thumb_width,$thumb_height);
 imagecopyresampled($image_t, $dest_image, 0, 0, 0, 0, $thumb_width,
 $thumb_height, $new_width, $new_height);

 $thumb_image = imagecreatetruecolor(90,90);
 imagecopy($thumb_image, $image_t, 0, 0, $left, $top,
 $thumb_width,$thumb_height);
 imagejpeg($thumb_image, 'thumb.jpg', 80);

 imagedestroy($thumb_image);
 imagedestroy($dest_image);
 imagedestroy($image_t);

Is this approach of creating a temporary image of smaller size and then copying thumbnail from it, correct ? Is there an alternative to this ? How can it be further optimized ?

UPDATE: The class that I have created, with the above code and some help and insight gained from the link at nettuts, can be found on github


texts: Permutation of list in Python so that list[x] != list[x+1]

texts:
Basically I need to order a list, so that an element is not the same as the element that comes after or before it. I searched for a solution but couldn't find one so I wrote this function myself.

For example, [1,2,2,3,1,3,3] should come out as [3,1,2,3,1,2,3], [3,2,3,1,2,3,1] or [2,1,3,1,3,2,3] and so on.

def unorder(alist):
    multi_lvl_list = []
    unord_list = []

    alist.sort()

    # makes a new list that holds lists where same elements
    # are grouped together
    start = 0
    for i in range(len(alist)):
        if i == len(alist)-1:
            if alist[i] != alist[i-1]:
                multi_lvl_list.append([alist[i]])
            else:
                multi_lvl_list.append(alist[start:])
        elif alist[i] != alist[i+1]:
            multi_lvl_list.append(alist[start:i+1])
            start = i+1
        i += 1

    multi_lvl_list.sort(key=len)

    '''
    goes over every list and pops out one element to a third list
    if there are many same elements they will be put
    to the end of the list
    '''
    while len(multi_lvl_list) > 0:
        for idx, val in enumerate(multi_lvl_list):
            unord_list.append(val.pop())
            if len(val) == 0:
                del multi_lvl_list[idx]

    '''
    go over the list in reverse. if x == x-1 try to put x in the
    beginning of the list. becourse there are
    more likely different elements
    '''
    for i in range(len(unord_list)-1, -1, -1):
        if unord_list[i] == unord_list[i-1]:
            for j in range(len(unord_list)):
                if j == 0:
                    if unord_list[i] != unord_list[0]:
                        unord_list.insert(0, unord_list[i])
                        del unord_list[i+1]
                elif unord_list[i] != unord_list[j] and unord_list[i] != unord_list[j+1]:
                    unord_list.insert(j+1, unord_list[i])
                    del unord_list[i+1]
        else:
            break

    return unord_list

It seems to work in cases where it's possible to make such a list, but I'm pretty sure there is a more efficient way and the code can be optimized.


texts: C++ int_cast function for checked casts?

texts:
In order to detect run-time integer casting problems, I've created this function*:

template<typename TTo, typename TFrom>
static inline TTo int_cast(TFrom value)
{
    TTo result = static_cast<TTo>(value);
    if (static_cast<TFrom>(result) != value || (result >= TTo()) != (value >= TFrom()))
    {
        throw std::out_of_range("numeric_cast: value out of range");
    }
    return result;
}

Two questions:

Are there any loopholes in this function I have not accounted for (e.g. undefined behavior)?
What would be the best way to extend this to perform double-to-float and floating-to-integral conversions?

*Note: Yes, I realize Boost has a function like this. But I want my own. :)


texts: Extracting files and directories from a provided list into separate lists

texts:
This code gets a list of all files and directories from a specific location. Thes code below works.

List<string> FullList = new List<string>(LoadFiles("patch.txt"));
List<string> ShortCatalogList = new List<string>();
List<string> ShortFileList = new List<string>();

            for (int i = 0; i < FullList.Count; i++)
                {

                    if (System.IO.Path.HasExtension(FullList[i]))
                    {
                    ShortFileList.Add(FullList[i]);
                    }

                    if (!System.IO.Path.HasExtension(FullList[i]))
                    {
                        ShortCatalogList.Add(FullList[i]);

                    if (Directory.GetFiles(FullList[i]).Length > 0)
                        {
                            string[] subFile = Directory.GetFiles(FullList[i]);
                                for (int io = 0; io < subFile.Length; io++)
                                    {
                                        ShortFileList.Add(subFile[io]);
                                    }
                        }

                    if (Directory.GetDirectories(FullList[i]).Length > 0)
                     {
                            string[] subFolder = Directory.GetDirectories(FullList[i]);

                            for (int io = 0; io < subFolder.Length; io++)
                            {
                                FullList.Add(subFolder[io]);
                            }
                   }
                  }
                 }

I know that I need to protect from permission problem.


texts:
I am using PHP to keep my webpage organized.

The directory looks like this:

root/folder/file1
root/folder/file2
root/folder/file3
root/index.php

Each file is very simple html doc with content containing a title tag, which I use to create a nav bar.

I want index.php to aggregate all the content from file1, file2 and file3, in addition to creating a nav bar up at the top.

The code I have achieves this successfully, but I'm not sure if I'm doing this in a practical way.

$domain = "domain/"
$dir = "folder/";
$files = scandir($dir);

// loop over all the files, saving their contents and ids to arrays
$contents = Array();
$titles = Array();
$ids = Array();
for ($x = 0; $x < sizeof($files); $x++) {
  if ($files[$x] != "." && $files[$x] != "..") {
    $filename = $domain . $dir . $files[$x];
    $file = fopen($filename, "r");
    $data = file_get_contents($filename);
    array_push($contents, $data);

    $regex = '#<title>(.*?)<\/title>#';
    preg_match($regex, $data, $match);
    $title = $match[1];
    array_push($titles, $title);

    $regex2 = '#( |-|,)#';
    $id = preg_split($regex2, $title)[0];
    array_push($ids, $id);
  }
}

// the first loop sets the nav bar
echo "
";
echo "
";
for ($x = 0; $x < sizeof($contents); $x++) {
    echo "
" . $titles[$x] . "
";
}
echo "
";
echo "
";

// this second loop sets the contents
echo "
";
for ($x = 0; $x < sizeof($contents); $x++) {
    echo "
" . $contents[$x] . "
";
}
echo "
";

I like the idea of having all the content on one big page and the nav bar helps a lot when I'm viewing it on my phone.

Questions

Are there any obvious problems with the way I am aggregating my files?
Are there challenges I may encounter that I have not yet experienced?
Is there a generally accepted way of doing this while achieving the same result?


texts: Fetching data from your database in a constructor

texts:
I have this item (an item is an object linked to a xml view), to build it I need 2 things, get labels from codes, and get text from the strings.xml android file.

please ignore the long to int and int to long convertion, for some reason the database value where randomly set to long and int but they could all be int,
I will refactor this later.

refManager is calling a DAOto fetch data from the database.

I have a for loop, building several OperationInstallItem

//constructor

public OperationInstallItem(final Resources resources, final RefManager refManager,
            final ModuleCategoryEnum category, final ModeleOperationEntity modeleOperationEntity,
            boolean isMandatory) {
        //basic init
        this.category = category
        this.isMandatory = isMandatory;
        this.refTypeOperation = modeleOperationEntity.getRefTypeOperation();
        this.refTypeInstallation = Long.valueOf(modeleOperationEntity.getRefTypeInstallation());

        //label init
        this.operationLabel = refManager.getOperationLabel(Ints.checkedCast(refTypeOperation));
        this.installationShortLabel = parametrageManager.getInstallationShortLabelt(refTypeInstallation);
        this.installationLongLabel = parametrageManager.getInstallationLongLabel(refTypeInstallation);
        this.title = resources.getString(R.string.operation_intallation_title)

        //icons specific to this class
        CodeTypeOperation codeTypeOperation =
                CodeTypeOperation.getEnumByCode(Ints.checkedCast(refTypeOperation));
        addModuleAdapterIconId = codeTypeOperation.getIcon();
        moduleAdapterIconId = codeTypeOperation.getIcon();
        moduleAdapterIconselectedId = codeTypeOperation.getIconSelected();
        moduleFragmentClass = TDBAddModuleFragment.class;
    }

Most of my collueages are uneasy with passing a manager as a constructor arguments but noone of
them can explain me why. "it's just not done this way"

same thing with Resources resources that allow you to get String values from the strings.xml file doing this resources.getString(R.string.operation_intallation_title),
according to them, it is bad to pass it in the constructor.

I don't get it, I need those labels/title, if I do this before the instanciation and pass it as parameters it's the exact
same thing. no performance gain, nothing is different.

Or is there something I'm missing?


texts: Where to protect DB data against XSS injections?

texts:
To protect my web site against XSS injection, I am using OWASP Encoding Project.

Is it a good idea to protect all data retrieved in my DB to avoid XSS by going throuh all the data just returned by the query like this :

public function fetchDataBySql($sql,$dataArray = null,$htmlEncode = true)
{
    try
    {
        $db = Zend_Db_Table::getDefaultAdapter();
        $stmt = $db->query($sql,$dataArray);

        $return = $stmt->fetchAll();
        $this->numberRows = count($return);

        if($htmlEncode)
        {
            array_walk_recursive($return, function (&$value) {
                $value = Reform::HtmlEncode($value);
            });
        }

        return $return;
    }
    catch (Exception $e)
    {
        echo $e->getMessage();
        Application_Model_DbTable_Default::logError(300,$e->getMessage());
        return false;
    }
}

and then in my view :

<?php echo $this->myData; ?>

instead of escape strings in the view like this :

<?php echo Reform::HtmlEncode($this->myData); ?>

Is there any case where the first solution is not secure?


texts:
I'm trying to understand conception of creating unit tests for the frontend applications.

I have created higher order reducer:

// @flow

type action = {
    type: string,
    payload?: any
};

/**
 * Async Reducer Factory to reduce duplicated code in async reducers.
 * Higher Order Reducer.
 *
 * @param {String} name - Reducer name.
 * @returns {Function}
 */
export const asyncReducerFactory = (name: String) => {
    return (
        state = { data: null, isLoading: false, error: null },
        action: action
    ) => {
        switch (action.type) {
            case `FETCH_${name}_STARTED`:
                return { data: null, isLoading: true, error: null };
            case `FETCH_${name}_SUCCESS`:
                return { data: action.payload, isLoading: false, error: null };
            case `FETCH_${name}_ERROR`:
                return { data: null, isLoading: false, error: action.payload };
            default:
                return state;
        }
    };
};

Tests:

import { asyncReducerFactory } from "./factories";

describe("Test async reducers factory", () => {
    const factory = asyncReducerFactory("TEST");

    it("should create reducer", () => {
        expect(factory).not.toBe(null);
    });

    it("should start fetching", () => {
        expect(factory({}, { type: "FETCH_TEST_STARTED" })).toEqual({
            data: null,
            isLoading: true,
            error: null
        });
    });

    it("should end fetching with success", () => {
        expect(
            factory({}, { type: "FETCH_TEST_SUCCESS", payload: "success" })
        ).toEqual({
            data: "success",
            isLoading: false,
            error: null
        });
    });

    it("should end fetching with error", () => {
        expect(
            factory({}, { type: "FETCH_TEST_ERROR", payload: "error" })
        ).toEqual({
            data: null,
            isLoading: false,
            error: "error"
        });
    });

    it("should return default state", () => {
        expect(factory({}, { type: "DIFFERENT" })).toEqual({});
    });
});

I would really appreciate, if you could let me know:

if i'm using flow correctly?
if my tests are reliable?
how could i make it more generic?


texts: RegEx sentence-splitting madness. Mad genius?

texts:
I inherited the following regex:
    /[^.!?\s][^.!?\n]*(?:[.!?](?!['"]?\s|$)[^.!?]*)*[.!?]?['"]?(?=\s|$)/g

This regex is used to split sentences, and is dealing with things like quotes after periods at the end of a sentence (He said "I don't care.") correctly. I've been playing with this regex, but I'm not sure yet if everything that's in here is needed. It seems to me that a lot of "groups" could be removed to achieve the same result.
Obviously documentation on this regex (one of the core aspects of the product) is missing.
This regex is madness. Is it just madness or is it mad genius?


texts: Page for editing an item from an expenses list

texts:
I have been working on a beginner project, learning React and Typescript. The project is an expense manager application and I have tried splitting most of my applications into simple short components.
For the EditExpensePage component I have connected it to the Redux store for the app, in order to be able to access the state and to dispatch actions.

I would like to get some feedback on the code I've written, and ways I could improve it.

The Expense interface :

export interface Expense {
    id: string;
    description: string;
    note?: string;
    amount: number;
    createdAt: number;
}

The EditExpensePage :

import * as React from "react";
import { RouteComponentProps } from "react-router";
import * as Redux from 'redux';
import {withRouter} from 'react-router';
import {connect} from 'react-redux';
import { Expense } from "../types/Expense";
import { AppState } from "../Store/configureStore";
import { compose } from "redux";
import ExpenseForm from "./ExpenseForm";
import { AppActions } from "../types/Actions";
import { addExpense, removeExpense } from "../Actions/expenses";

type PathParamsType = {
  id: string;
};
//component own props
type PropsType = RouteComponentProps<PathParamsType> & {
  id: string;
};

interface StateProps {
    expenses: Expense[]
}

interface DispatchProps{
    addExpense : (expense : Expense) => any,
    removeExpense : (expenseId : string) => any
}

type Props = PathParamsType & PropsType & StateProps & DispatchProps;

function GetSelectedExpense(id : string, expenses : Expense[]){
    for (var i=0 ; i<expenses.length; i++){
        if (expenses[i].id === id)
        {
            return expenses[i];
        }
    }
}

const EditExpensePage: React.FunctionComponent<Props> = (props): any => {
    let selectedExpense = GetSelectedExpense(props.match.params.id, props.expenses)
    return (
    <ExpenseForm description={selectedExpense?.description} amount={selectedExpense?.amount} onSubmit={(expense) => {

        for (let i = 0; i< props.expenses.length ; i++){
            if (props.expenses[i] === selectedExpense)
            {
                props.removeExpense(selectedExpense.id);
                props.addExpense(expense);
            }
        }

    }}/>
 )
};

const mapStateToProps = (state : AppState) :StateProps => {
    return({
        expenses : state.expenses
    })
}

const mapDispatchToProps = (dispatch : Redux.Dispatch<AppActions>) : DispatchProps => {
    return {
        addExpense : (expense : Expense) => dispatch(addExpense(expense)),
        removeExpense : (id : string) => dispatch(removeExpense(id))
    }
}

export default compose(
    withRouter,
    connect(mapStateToProps, mapDispatchToProps))(EditExpensePage);
```


texts:
I'm trying to learn streams and hashmaps, in doing so I want to make a very scalable, very clean version of FizzBuzz while adhering to the book Clean Code by Robert Cecil Martin.

public class Main {

    public static void fizzBuzzHundredTimes(Map<String, Integer> fizzDivisor) throws ArithmeticException{
        String output; // Avoid recreating String each iteration
        for (int i = 1; i <= 100; i++) {
            final int finalI = i; // Variables used in lambda functions need to be final.
            output = fizzDivisor.entrySet()
                    .stream()
                    .filter(entry -> finalI % entry.getValue() == 0)
                    .map(entry -> entry.getKey())
                    .collect(Collectors.joining(""));
            if (output.length() > 0) {
                // the value was divisible.
                System.out.println(output);
            } else {
                System.out.println(i);
            }

        }

    }

    public static void main(String[] args) {

        Map<String, Integer> fizzMap = new HashMap<>();
        fizzMap.put("Fizz",3);
        fizzMap.put("Buzz",5);
        fizzMap.put("Fuzz",7);
        fizzMap.put("Bizz",11);
        fizzMap.put("Biff",13);
        try{
            // Avoid negative numbers
            fizzBuzzHundredTimes(fizzMap);
        } catch(Exception e){
            System.err.println(e + "Was thrown");
        }

    }
}


texts: Convert Array CSV to Object using Header

texts:
Takes the first array in the array and uses that to set the properties of an array-object.

var _ = require("underscore");
function csvToObject(data){
  var header = data.shift();
  return _.map(data, function(row){
    var temp = {};
    _.each(row, function(cell, key){
      temp[header[key]] = cell;
    });
    return temp;
  });
}

I created a non-underscore dep version

function csvToObject2(data) {
  var header = data.shift();
  var alpha = [];
  for (var i = 0; i < data.length; i++) {
    var beta = {};
    for (var j = 0; j < data[i].length; j++) {
      beta[header[j]] = data[i][j];
    }
    alpha.push(beta);
  }
  return alpha;
};

They both performed the same in jsPerf. Thoughts?


texts: Speed up query to rank team sales by aggregating data from two databases

texts:
On my machine it runs in about 60 seconds and about 2-3 minutes live.

The criteria needed are:

Current month only (from first of month until current day)
I need the rank of the currently logged in person based on total sales.
I have two tables across two databases where this data is to be gathered:

Database 1: ProPit_User table (this houses the logged in users).
Database 2: This houses the sales in the Orders table.

Both tables will be linked on the SalesRepID column.
There are around around 352 users in the ProPit_User table.
There are a lot of orders in the orders table.

This code does what I need it to do; it is just dreadfully slow.

public static int GetNationalRank(int teamId, int CurrentUserId)
{
    List<ProPit_User> lstProPit_User = new List<ProPit_User>();
    List<TeamSales> lstTeamSales = new List<TeamSales>();
    int currentUserRank = 0;

    using (ProsPitEntities ppdb = new ProsPitEntities())
    using (TraegerEntities db = new TraegerEntities())
    {
        lstProPit_User = ppdb.ProPit_User.Where(x => x.SalesRepID != null).ToList();

        foreach (var user in lstProPit_User)
        {

            var strStartDate = DateTime.Now.AddDays(-(DateTime.Now.Day - 1)).ToString("M/d/yyyy");
            var dtStartDate = Convert.ToDateTime(strStartDate);

            var strEndDate = DateTime.Now.AddDays(1).ToString("M/d/yyyy");
            var dtEndDate = Convert.ToDateTime(strEndDate);

            var orders = db.Orders.Where(o => o.DateCompleted >= dtStartDate
                                        && o.DateCompleted < dtEndDate
                                        && (o.Status == 1 || o.Status == 2)
                                        && o.Kiosk != 0).AsEnumerable();

            var total = (from o in orders
                         where o.SalesRepID == user.SalesRepID
                         select o.OrderTotal).Sum();

            TeamSales TeamSales = new TeamSales();

            TeamSales.userId = user.userID;
            TeamSales.TotalSales = total;

            lstTeamSales.Add(TeamSales);

            }

        }

        int rank = lstTeamSales.OrderByDescending(x => x.TotalSales).FindIndex(x => x.userId == CurrentUserId);

        if (rank == -1)
        {
            currentUserRank = 0;
        }
        else
        {
            // Zero based index need to add one to rank
            currentUserRank = rank + 1;
        }

    }

    return currentUserRank;
}

I have .FindIndex added as an extension method to IEnumerable.

All I really need is to get the rank of the person logged in in comparison to everyone else sales.


texts: Including functions in _ViewStart.cshtml

texts:
I've got the following code in my _ViewStart.cshtml file:

@using System.Text;
@{
    string controllerName = (string)ViewContext.RouteData.Values["controller"];
    ViewContext.Controller.ViewBag.BodyCssClass = ConvertControllerNameToCssClass(controllerName);
}

@functions {
    private static string ConvertControllerNameToCssClass(string text)
    {
        if (text == null)
        {
            throw new ArgumentNullException("text");
        }

        StringBuilder sb = new StringBuilder();
        sb.Append(text[0]);
        for (int i = 1; i < text.Length; i++)
        {
            if (char.IsUpper(text[i]) && text[i - 1] != '-')
            {
                sb.Append('-');
            }
            sb.Append(text[i]);
        }
        return sb.ToString().ToLower();
    }
}

In my layout the ViewBag.BodyCssClass is used like so:

<body class="@ViewBag.BodyCssClass" itemscope itemtype="https://schema.org/WebPage">

Allowing me to target a particular page with CSS specific to that controller where required.

The ConvertControllerNameToCssClass function has limited use, in that it is not likely to be used elsewhere and shouldn't be used elsewhere either.

However, it is my understanding that the _ViewStart.cshtml is supposed to be used for adding code that would otherwise be duplicated across all views. Is it acceptable to add functions to the _ViewStart.cshtml?

Does anyone have any thoughts on this or any alternatives to how they would implement something like this?


texts: Basic sign-up method, testable and with try/catch

texts:
I am learning how to implement testing and try/catch statements into my code. I have a Laravel application with the following method. I am looking for advice on where I should add in try/catch statements and what phpunit unit-test(s) I would create to ensure this is functioning properly. Tips on comment blocks are also appreciated.

// User sign up
public function postSignup()
{
    $validator = Validator::make(Input::all(), User::$rules);

    $confirmation_code = MyHelper::encrypt_decrypt('encrypt',Input::get('email'));

    if($validator->passes()) {
        $user = new User;
        $user->email = Input::get('email');
        $user->password = Hash::make(Input::get('password'));
        $user->emailVerifiedToken = $confirmation_code;
        $user->firstName = null;
        $user->lastName = null;
        $user->shipAddressId = null;
        $user->billAddressId = null;
        $user->phone = null;
        $user->save();

        $userdata = array(
            'token' => $confirmation_code
        );

        //Send the user an email requesting verification
        $toEmail = $user->email;
        $toName = $user->email;
        $subject = "Email Verification - example.com";

        Mail::queue('emails.account.account-creation', $userdata, function($message) use ($toEmail,$toName,$subject)
        {
            $message->to($toEmail,$toName)->subject($subject);
        });

        if(Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')), false))
        {
            return Redirect::to('/home/')
            ->with('login_message', 'Thank you for creating a new account, please sign in');
        }
    }

    return Redirect::to('/account/sign-up')
            ->with('signup_message',  'Something went wrong')
            ->withErrors($validator)
            ->withInput();
}


texts: Split string with adding separator to substring

texts:
I wrote my Split() extension, it's main goal is to save delimiters and add them to splitted strings.

For example:
I have a string "-1-2+3+4-5-6", and separators '+', '-'
and I want to have following: "","-1","-2","+3","+4","-5","-6" or "-","1-","2+","3+","4-","5-","6" depends on input separator option.

My extension method consists of three parts:

Check input values;
Getting all indexes of separators, and separators in source string;
Split source string and adding separators to left or right substring.

Code:

public enum SeparatorOptions
{
    None = 0,
    AddSeparatorToLeftSubstring = 1,
    AddSeparatorToRightSubstring = 2
}
public static class Extensions
{
    public static string[] Split(this string source, char[] separators, SeparatorOptions separatorOptions)
    {
        if (separatorOptions < SeparatorOptions.None || separatorOptions > SeparatorOptions.AddSeparatorToRightSubstring)
        {
            throw new ArgumentException("Arg_SeparatorEnumIllegalVal");
        }
        if (separators == null || separators.Length == 0)
        {
            return source.Split((char[])null);
        }
        if (separatorOptions == SeparatorOptions.None)
        {
            return source.Split(separators);
        }
        // Getting all indexes of separators, and separators in source string
        int foundCount = 0;
        int[] separatorIndexes = new int[source.Length];
        char[] separatorValues = new char[source.Length];
        for (int i = 0; i < source.Length; i++)
            for (int j = 0; j < separators.Length; j++)
            {
                char separator = separators[j];
                if (source[i] == separator)
                {
                    separatorValues[foundCount] = source[i];
                    separatorIndexes[foundCount++] = i;
                    break;
                }
            }

        string[] splitString = source.Split(separators);
        // Adding separators to left or right substring
        if (separatorOptions == SeparatorOptions.AddSeparatorToLeftSubstring)
            return AddSeparatorToLeftSubstring(splitString, separatorValues, foundCount);
        if (separatorOptions == SeparatorOptions.AddSeparatorToRightSubstring)
            return AddSeparatorToRightSubstring(splitString, separatorValues, foundCount);
        return splitString;
    }
    private static string[] AddSeparatorToLeftSubstring(string[] splitString, char[] separatorValues, int foundCount)
    {
        for (int i = 0; i < foundCount; i++)
        {
            splitString[i] += separatorValues[i];
        }
        return splitString;
    }
    private static string[] AddSeparatorToRightSubstring(string[] splitString, char[] separatorValues, int foundCount)
    {
        for (int i = 1, j = 0; i <= foundCount; i++, j++)
        {
            splitString[i] = separatorValues[j] + splitString[i];
        }
        return splitString;
    }
}
class Program
{
    static void Main(string[] args)
    {
        string str = "-1-2+3+4-5-6";
        Console.WriteLine("Original split()");
        var res2 = str.Split(new char[] { '+', '-' }, SeparatorOptions.None);
        foreach (var el in res2) Console.WriteLine(el);
        Console.WriteLine("Add to right substring");
        var res = str.Split(new char[] { '+', '-' }, SeparatorOptions.AddSeparatorToRightSubstring);
        foreach (var elem in res) Console.WriteLine(elem);
        Console.WriteLine("Add to left substring");
        var res3 = str.Split(new char[] { '+', '-' }, SeparatorOptions.AddSeparatorToLeftSubstring);
        foreach (var el in res3) Console.WriteLine(el);
        Console.ReadKey();
    }
}

What I wrote seems to work, although I am not sure if it is the best way, or recommended way to do something like this, so I want to ask what is wrong with my code and how could it be done better.


texts:
From this library I wrote, I have created this function in Swift, but I'm not happy with the implementation. Can anyone suggest a better way to do this? I really don't like changing counters inside for-loops...

extension Array {

    /// Removes all items that conform to the given closure
    mutating func removeAll(closure: (T) -> Bool) {
        for var counter = 0; counter < count; counter += 1 {
            if closure(self[counter]) {
                removeAtIndex(counter)
                counter -= 1
            }
        }
    }
}


texts: First simple program; counting button presses

texts:
This is my first solo Objective-C program... it does the complicated task of displaying a button and counting how many times it's been pressed.  It retains that count (along with the last time it was pressed) between uses of the app.  I have a few specific questions, but eagerly await any and all feedback.

Is the try/catch block the best way to look up count and lastPress for the first time the app is used?  There aren't any values before it's ever used, but afterward there always should be.
I repeat myself in setting up the directories and documents variables.  Should that be eliminated?  If so, what's the best practice there?
I declare the count as an int property in ViewController.h, and I declare lastPress within ViewController.m.  Is one better than the other?

PMNViewController.h

#import <UIKit/UIKit.h>

@interface PMNViewController : UIViewController
@property (strong, nonatomic) IBOutlet UILabel *buttonCount;
@property (strong, nonatomic) IBOutlet UILabel *buttonDate;
@property (assign) int count;
- (IBAction)pushButtonPressed:(id)sender;
- (void)setDateLabel:(NSString*)documents;
@end

PMNViewController.m

#import "PMNViewController.h"

@interface PMNViewController ()

@end

@implementation PMNViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [directories firstObject];
    NSString *filePathCount = [documents stringByAppendingPathComponent:@"count.plist"];
    NSString *datePath = [documents stringByAppendingPathComponent:@"date.plist"];
    NSString *lastPress;

    @try {
        NSString *contents = [NSString stringWithContentsOfFile:filePathCount encoding:NSUTF8StringEncoding error:nil];
        self.count = [contents integerValue];
        lastPress = [NSString stringWithContentsOfFile:datePath encoding:NSUTF8StringEncoding error:nil];

    }
    @catch (NSException *exception) {
        self.count = 0;
        lastPress = @"Never pressed!";
    }
    @finally {
        self.buttonCount.text = [NSString stringWithFormat:@"%i", self.count];
        self.buttonDate.text = lastPress;
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)setDateLabel:(NSString*)documents{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm 'on' MM-dd-YYYY"];
    NSDate *now = [[NSDate alloc] init];

    NSString *lastPressText = [dateFormatter stringFromDate:now];
    self.buttonDate.text = lastPressText;
    NSString *datePath = [documents stringByAppendingPathComponent:@"date.plist"];
    [lastPressText writeToFile:datePath atomically:YES encoding:NSUTF8StringEncoding error:nil];

}

- (IBAction)pushButtonPressed:(id)sender {
    NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [directories firstObject];

    self.count += 1;
    NSString *countText = [NSString stringWithFormat:@"%i", self.count];
    self.buttonCount.text = countText;
    NSString *filePathCount = [documents stringByAppendingPathComponent:@"count.plist"];
    [countText writeToFile:filePathCount atomically:YES encoding:NSUTF8StringEncoding error:nil];
    [self setDateLabel:documents];

}

@end


texts:
The following code handles querying for user data in a multitenant Cassandra database.  Each tenant has their own keyspace and within that keyspace data about each tenants users is stored.

This code will run as part of a webservice.

I'm looking on comments for how I handled managing the session so that connection pooling is used and only one session is made.

(defn- session []
  (cc/connect ["localhost"]
              {:credentials
               {:username ""
                :password ""}}))

(def memo-session (memoize session))

(defn get-recs-by-user-id [client-name client-id user-id]
    (cql/use-keyspace (memo-session) client-name)
    (cql/select (memo-session) "user_recommendations"
                (where [[= :client_id client-id] [= :user_id user-id]])
                (limit 1)))


texts:
I implemented basic pushd and popd functionality for a Python script. What's a more academic/formal way to implement a directory stack?

_directory_stack = {0:getcwd()}

def pushd(target: str):
    """Push a new directory to the top of the stack and changes to it.

    Arguments:
        target {str} -- Where you want to go
    """
    highest_seen = max(_directory_stack.keys())
    _directory_stack[highest_seen+1] = target
    chdir(target)

def popd():
    """Pops the most recent directory off the stop of the stack and returns you to the previous directory
    """
    current_top = max(_directory_stack.keys())
    _directory_stack.pop(current_top, None)
    chdir(_directory_stack[current_top-1])


texts:
Right now, I have the following:

A win_streak column on the User table.
This method in game.rb

I'm interpreting win_streak as follows:

The number if the number games in the streak
The value (positive or negative) specifies whether those games were wins (positive) or losses (negative)

game.rb:

def adjust_streak
  u = self.user
  case self.result
    when 'Win'
      u.win_streak > 0 ? u.win_streak += 1 : u.win_streak = 1
    when 'Loss'
      u.win_streak > 0 ? u.win_streak = -1 : u.win_streak -= 1
    end
  u.save
end

I'm looking for a cleaner, and more succinct way to do this (e.g. keep track of win/loss streaks).


texts: Better way to write nested loop, if condition and breaking it

texts:
This is a Java method that takes as input a 2 dimensional array called grid.

It uses the i1 and j1 values from when the corresponding grid[i1][j1] position is true for the first time, and then i2 and j2 from when the corresponding grid[i2][j2] position is true for the second time.

A call is then made to drawLine(i1, j1, i2, j2) to draw line between those two points in the screen.

I wrote the following code to take all stuff I want to plot, but the code works but looks bad, is there any better way to write this. This code works fine, I just want to improve on it.

    for(int x1 = 0; x1 < rows; x1++) {
        for (int y1 = 0; y1 < columns; y1++) {
            if (grid[x1][y1] == true) {
                int x2 = x1 + 1;
                for(int y2 = 0; y2 < 500; y2++) {
                    if (grid[x2][y2] == true) {
                        drawLine(x1, y1, x2, y2);
                        break;
                    }
                }
            }
        }
    }


texts:
I'm writing a mechanism to retry any failed downloads that respond with certain http error codes, I've noticed the server I'm downloading from will unexpectedly throw these codes to me and when I manually visit the URL it appears to be fine.

It also seems that its fine when trying to download for a second or (rarely) third time. The KeyValuePair represents the key as being the download link, and the value being the location where the file is set to be saved on the device.

I simply check if the file exists in the save location to determine if it actually downloaded.

public static class DownloadUtilities
{
    public static void DownloadLinks(Dictionary<string, string> files)
    {
        Parallel.ForEach(
            files,
            new ParallelOptions { MaxDegreeOfParallelism = 20 },
            DownloadLink);
    }

    private static void DownloadLink(KeyValuePair<string, string> link, bool retrying = false)
    {
        try
        {
            using (var webClient = new WebClient())
            {
                webClient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)");
                webClient.DownloadFile(new Uri(link.Key), link.Value);
            }
        }
        catch (WebException e)
        {
            if (retrying) { return; } // Silently exit, we're retrying.

            if (e.Status != WebExceptionStatus.ProtocolError)
            {
                throw;
            }

            if (e.Message.Contains("(504) Gateway Timeout") || e.Message.Contains("(403) Forbidden"))
            {
                if (!RetryFailedDownload(link))
                {
                    Program.FailedDownloads.Add(link.Key); // Lets settle for the fact it can't download, and add it to the failed list.
                }
            }
            else
            {
                Logger.Error("Failed to download: " + link.Key);
                Logger.Error(e.Message);
            }
        }
    }

    private static bool RetryFailedDownload(KeyValuePair<string, string> link)
    {
        for (var i = 0; i < 4; i++) // Retry mechanism for 4 trys?
        {
            DownloadLink(link, true);

            if (File.Exists(link.Value)) // It finally managed to download?
            {
                return true;
            }
        }

        return false;
    }
}


texts:
I have written a jQuery function which accepts an elementId and an integer. The function then generates a counter which increments at the average speed of searches made (per month) since you initialised the function.

The elementId is where the counter is placed on the page.
The integer is the number of monthly searches manually taken from Google adWords.

There are a number of factors I'd like to improve; firstly, the error handling as I am trying to get a reasonably accurate counter Math.round shouldn't be used. But other functions to handle divide by zero issues etc are fine.

I'd also like to improve how the calculations are performed to establish the interval speed, it is currently written to show relatively clear calculation steps (I'd like to think).

(function ($) {

/* Initialise Counters*/
keywordSearchCounter(9292208, 'footballCounter');
keywordSearchCounter(292410, 'tennisCounter');
keywordSearchCounter(779180, 'chessCounter');

function keywordSearchCounter(searchesPerMonth, elementId) {

    if($.type(searchesPerMonth) !== "number") return;

    if(searchesPerMonth === 0) return;

    console.log("function initialised for '" + elementId.toString() + "'");

    /* Do some math on searches */
    var daysInMonth = 28,
        hoursInDay = 24,
        minutesInHour = 60,
        secondsInMinute = 60;

    var searchesPerDay = searchesPerMonth / daysInMonth;
    var searches = searchesPerDay;
    console.log('per day: ' + searches);

    var searchesPerHour = searchesPerDay / hoursInDay;
    searches = searchesPerHour;
    console.log('per hour: ' + searches);

    var searchesPerMinute = searchesPerHour / minutesInHour;
    searches = searchesPerMinute;
    console.log('per minute: ' + searches);

    var searchesPerSecond = searchesPerMinute / secondsInMinute;
    searches = searchesPerSecond;
    console.log('per second: ' + searches);

    var interval = (1 / searches) * 1000;
    var counter = 0;
    console.log('interval set to: ' + interval);

    /* Set the counter speed */
    setInterval(function () {
        counter += 1;
        document.getElementById(elementId).innerHTML = counter;
    }, interval);
}
}(jQuery));

A have provided a jsFiddle to show a working example: Demo

Any advice, even on the instantiation of my IIFE would be most welcome!


texts: Optimizing a function with nested loops and if condition

texts:
private  void find_tile(float[] x, float[] z, int nRigidBodies)  {
    int serial[]=new int[nRigidBodies];
    int numTiles=4;
    for(int i=0;i<nRigidBodies;i++)
    {
        // Check for the loaction of each tile to find which one should be switched on...
        //currently only supports 4
        for(int j=0;j<numTiles;j++)
        {
            if ((x[i] > tileCoords[j][0]) && (x[i] < tileCoords[j][1]) && (z[i] > tileCoords[j][2]) && (z[i] < tileCoords[j][3]))
            {
                serial[i]=j+1;
                break;
            }
        }
    }

We have a optitrack system that tracks objects in a room and the number of objects is represented by nRigidBodies and their x-y cordinate by the x[] and z[] array passed here.

Also we have a fixed number of Tiles which are fixtures on the ceiling represented by numTiles and the bounds of these tiles are in tileCoords.

If an object is directly under one of these fixtures, we switch the fixture on.So I create an array serial[] which is of the same size as nRigidBodies.For every object we check if is is within the bounds of that fixture and if it we assign the fixture number to the serial array.Later we just take out all the fixture number from the array( coz these should only be lit up ) and send them a message to light up and the ones not in here are switched off.

The condition where the object is not within any of the fixtures is fine since it is checked later in the code and taken care of.

Sample Input
    float[] x= {1.5, -0.5, 3.5}
    float[] z= {2.5, -1.5, 3.2}
    nRigidBodies= 3
    numTiles=4
    tileCoords={{0.5,1.5,1.5,2.5},{-0.5,0.5,0.5,1.5},{0.5,1.5,0.5,1.5},{-0.5,0.5,-0.5,0.5}}

Expected Output
   serial[]={1,2,0}

I have a simple function that checks for if each object is within the bounds of the cordinates or not.If it is, we assign the number to a variable.

Currently the inner loop generally only has only 4 iterations so it doesn't matter much.However in the future it might run for upto 50 iterations with the outer loop running for 5 iterations max.The code is a time sensitive piece which controls lights in real time.Too much time in computing this function would result in lights appearing to be lagged.

It would be of great help if someone can guide me on how to optimize the function above for faster computation.

I was thinking of using threads to run all of the outer loops at once.If there is something better which can be achieved with single threaded model,I would love to stick to it as that might be making it really complicated.


texts:
Posting my code for LeetCode's LRU Cache, if you'd like to review, please do so, thank you for your time!
Problem

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.

put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the
least recently used item before inserting a new item.

The cache is initialized with a positive capacity.

Follow up:

Could you do both operations in O(1) time complexity?

Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );

cache.put(1, 1);
cache.put(2, 2);
cache.get(1);       // returns 1
cache.put(3, 3);    // evicts key 2
cache.get(2);       // returns -1 (not found)
cache.put(4, 4);    // evicts key 1
cache.get(1);       // returns -1 (not found)
cache.get(3);       // returns 3
cache.get(4);       // returns 4

Code
type LRUCache struct {
    head     *Node
    tail     *Node
    cache    map[int]*Node
    capacity int
}

type Node struct {
    prev *Node
    next *Node
    key  int
    val  int
}

func Constructor(capacity int) LRUCache {
    return LRUCache{capacity: capacity, cache: make(map[int]*Node)}
}

func (this *LRUCache) Get(key int) int {
    node, stored := this.cache[key]
    if !stored {
        return -1
    }

    this.Evict(node)
    this.Add(node)

    return node.val
}

func (this *LRUCache) Put(key int, val int) {
    node, stored := this.cache[key]
    if !stored {
        node = &Node{val: val, key: key}
        this.cache[key] = node
    } else {
        node.val = val
        this.Evict(node)
    }

    this.Add(node)
    if len(this.cache) > this.capacity {
        node = this.tail
        if node != nil {
            this.Evict(node)
            delete(this.cache, node.key)
        }
    }
}

func (this *LRUCache) Evict(node *Node) {
    if node == this.head {
        this.head = node.next
    }

    if node == this.tail {
        this.tail = node.prev
    }

    if node.next != nil {
        node.next.prev = node.prev
    }

    if node.prev != nil {
        node.prev.next = node.next
    }
}

func (this *LRUCache) Add(node *Node) {
    node.prev = nil
    node.next = this.head
    if node.next != nil {
        node.next.prev = node
    }

    this.head = node
    if this.tail == nil {
        this.tail = node
    }
}

Reference
Here is LeetCode's template:
type LRUCache struct {

}

func Constructor(capacity int) LRUCache {

}

func (this *LRUCache) Get(key int) int {

}

func (this *LRUCache) Put(key int, value int)  {

}

/**
 * Your LRUCache object will be instantiated and called as such:
 * obj := Constructor(capacity);
 * param_1 := obj.Get(key);
 * obj.Put(key,value);
 */

146. LRU Cache - Problem

146. LRU Cache - Discuss


texts:
I've created a program that translates any word into the form of igpay atinlay or pig Latin!

I got the project idea from here and you can read the rules here.

My program outputs the same translation as in the rules section in the link above, except for the word "always". It isn't really a big deal as the program translates almost any word correctly.

package pigLatin;

import java.util.Scanner;

public class PigLatin
{
 String str;
 Scanner scan = new Scanner(System.in);
 char firstVow;
 char secondVow;
 int i;

 public void init()

 {
  str = scan.next();
  i = 0; //beginning of a string

  if (str.length() <= 3 && (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u'))
  {
   System.out.println(str + "ay");
   scan.close();
  }

  else if (str.length() > 3 && (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')) {
   firstVow = str.charAt(i);
   i = 1;

   while (str.charAt(i) != 'a' || str.charAt(i) != 'e' || str.charAt(i) != 'i' || str.charAt(i) != 'o' || str.charAt(i) != 'u')

   {
    i++;
    if (i == str.length() - 1 && (str.charAt(i) != 'a' || str.charAt(i) != 'e' || str.charAt(i) != 'i' || str.charAt(i) != 'o' || str.charAt(i) != 'u')) {
     System.out.println(str + "ay");
     break;

    } else if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')

    {
     secondVow = str.charAt(i);

     //issues arise if the first vowel is equal to the second one
     if (firstVow != secondVow) {

      System.out.print(str.substring(str.indexOf(secondVow), str.length()));
      System.out.print(str.substring(str.indexOf(firstVow), str.indexOf(secondVow)));
      System.out.println("ay");
      break;

     } else if (firstVow == secondVow) {
      System.out.print(str.substring(2));
      System.out.print(firstVow);
      System.out.print(str.charAt(1));
      System.out.print("ay");
      break;
     }
     scan.close();
    }
   }

   //checks for words that begin with consonants
  } else {

   i = 0;
   while (str.charAt(i) != 'a' || str.charAt(i) != 'e' || str.charAt(i) != 'i' || str.charAt(i) != 'o' || str.charAt(i) != 'u')

   {
    i++;
    if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')

    {
     firstVow = str.charAt(i);
     System.out.print(str.substring(str.indexOf(firstVow), str.length()) + str.substring(0, str.indexOf(firstVow)) + "ay");
     break;
    }
   }
  }
  scan.close();

 }

 public static void main(String[] args) {
  new PigLatin().init();
 }

}


texts: Generalization of any() function with switchable default parameter for empty iterables

texts:
I have some use-cases where I want the behaviour of the build-in any() function to be slightly different, namely to return True if the iterable is empty.
Therefore I came up with the following override:
_any = any  # Alias built-in any.

def any(iterable, *, default=False):
    """Generalization of the built-in any() function."""

    if not default:
        return _any(iterable)

    count = 0

    for count, item in enumerate(iterable, start=1):
        if item:
            return True

    return count == 0

The code I used to test this is:
EMPTY_TUPLE = ()
FALSEY_TUPLE = (False, None, 0, '')
TRUEY_TUPLE = (False, None, 1, '')

def empty_iterables():
    """Yields empty iterables."""

    yield list(EMPTY_TUPLE)
    yield EMPTY_TUPLE
    yield {item: item for item in EMPTY_TUPLE}
    yield set(EMPTY_TUPLE)
    yield (i for i in EMPTY_TUPLE)

def falsey_iterables():
    """Yields iterables that any() should assert as False."""

    yield list(FALSEY_TUPLE)
    yield FALSEY_TUPLE
    yield {item: item for item in FALSEY_TUPLE}
    yield set(FALSEY_TUPLE)
    yield (i for i in FALSEY_TUPLE)

def truey_iterables():
    """Yields iterables that any() should assert as True."""

    yield list(TRUEY_TUPLE)
    yield TRUEY_TUPLE
    yield {item: item for item in TRUEY_TUPLE}
    yield set(TRUEY_TUPLE)
    yield (i for i in TRUEY_TUPLE)

def test():
    """Tests the custom any() function."""

    # Built-in behaviour.
    for iterable in empty_iterables():
        assert any(iterable) is False

    for iterable in falsey_iterables():
        assert any(iterable) is False

    for iterable in truey_iterables():
        assert any(iterable) is True

    # Custom behaviour.
    for iterable in empty_iterables():
        assert any(iterable, default=True) is True

    for iterable in falsey_iterables():
        assert any(iterable, default=True) is False

    for iterable in truey_iterables():
        assert any(iterable, default=True) is True

if __name__ == '__main__':
    test()

I wonder whether there's a more elegant way to implement the custom any() function with the aforementioned behaviour.
Use case
I have a custom monitoring system, that determines the state of a system using check records from a MariaDB database. I use peewee as an ORM:
def check_customer_system(system):
    """Returns the customer online check for the respective system."""

    end = datetime.now()
    start = end - CUSTOMER_INTERVAL
    condition = OnlineCheck.system == system
    condition &= OnlineCheck.timestamp >= start
    condition &= OnlineCheck.timestamp <= end
    query = OnlineCheck.select().where(condition)

    if query:
        return any(online_check.online for online_check in query)

    raise NotChecked(system, OnlineCheck)

In the current implementation, I need to check, whether the amount of records in the query in non-empty by doing if query:.
However, this will execute the query an load all records into RAM, which I want to avoid. Peewee has the optional .iterator() method on queries, which will return an iterator, that will not load all records into RAM at once. However, if I use that, if query: will always be True since it's testing the truth value of a generator object then.
Hence, I came up with the idea to implement a function, that returns True if any value of an iterable is True or the iterable is empty.
And I just realized that this is indeed an XY-Problem, since I'd loose the ability to distinguish between a checked and a non-checked system.
Thanks @Eric Duminil.


texts: User-defined color implementation in windows console

texts:
I have implemented an user defined colors enumerator, and if is possible I appreciate if I will get a code review.
I want to know if my implementation is correctly or must improve it.
If there exist a better alternative (color enumerator) to my code which is?

Usage example:

 HANDLE hConsole;
 setTextColor(hConsole,YELLOW_TEXT|PINK_BACKGROUND);
 std::cout << "YELLOW_TEXT|PINK_BACKGROUND";
 resetTextColor(hConsole);

Colors enumerator:

 enum COLOR
 {
     // Text foreground colors
     // Standard text colors
     GRAY_TEXT=8,      BLUE_TEXT,       GREEN_TEXT,
     TEAL_TEXT,        RED_TEXT,        PINK_TEXT,
     YELLOW_TEXT,      WHITE_TEXT,
     // Faded text colors
     BLACK_TEXT=0,     BLUE_FADE_TEXT,  GREEN_FADE_TEXT,
     TEAL_FADE_TEXT,   RED_FADE_TEXT,   PINK_FADE_TEXT,
     YELLOW_FADE_TEXT, WHITE_FADE_TEXT,
     // Standard text background color
     GRAY_BACKGROUND=GRAY_TEXT<<4,     BLUE_BACKGROUND=BLUE_TEXT<<4,
     GREEN_BACKGROUND=GREEN_TEXT<<4,   TEAL_BACKGROUND=TEAL_TEXT<<4,
     RED_BACKGROUND=RED_TEXT<<4,       PINK_BACKGROUND=PINK_TEXT<<4,
     YELLOW_BACKGROUND=YELLOW_TEXT<<4, WHITE_BACKGROUND=WHITE_TEXT<<4,
     // Faded text background color
     BLACK_BACKGROUND=BLACK_TEXT<<4,           BLUE_FADE_BACKGROUND=BLUE_FADE_TEXT<<4,
     GREEN_FADE_BACKGROUND=GREEN_FADE_TEXT<<4, TEAL_FADE_BACKGROUND=TEAL_FADE_TEXT<<4,
     RED_FADE_BACKGROUND=RED_FADE_TEXT<<4,       PINK_FADE_BACKGROUND=PINK_FADE_TEXT<<4,
     YELLOW_FADE_BACKGROUND=YELLOW_FADE_TEXT<<4, WHITE_FADE_BACKGROUND=WHITE_FADE_TEXT<<4
 };

Set and reset functions:

  BOOL resetTextColor(HANDLE h)
  {
      return SetConsoleTextAttribute(h,WHITE_FADE_TEXT);
  }

  BOOL setTextColor(HANDLE h, WORD c)
  {
      return SetConsoleTextAttribute(h,c);
  }

Capture:


texts:
This sample code works fine, but it looks awful.  How would you improve this?

data.Add(((Adress)(((OwnerIDList)owner.Adresses.Value)[0].Adress.Value)).FirstName.Value.ToString());
data.Add(((Adress)(((OwnerIDList)owner.Adresses.Value)[0].Adress.Value)).LastName.Value.ToString());

Why do we use .Value in FirstName.Value.ToString()?

FirstName is a DTString object (implements a basic interface for all data types to be stored in data base).


texts:
This is a fun piece. I have this block of code here:

if (minutes >= 60 && hours < 24) {
        return hours + " hours ago";
    } else if (hours >= 24 && days <= 30) {
        return days + " days ago";
    } else if (minutes <= -60 && hours > -24) {
        return -hours + " hours from now";
    } else if (hours <= -24 && days >= -30) {
        return -days + " days from now";
    } else if (minutes >= -60 && minutes < 0) {
        return -minutes + " minutes from now";
    } else if (days > 30 && days < 365) {
        if (days/30 == 1) {
            return "Last month";
        }
        return days/30 + " months ago";
    } else if (days < -30 && days > -365) {
        if (-days/30 == 1) {
            return "Next month";
        }
        return -(days/30) + " months from now";
    } else if (days >= 365) {
        if (days/365 == 1) {
            return "Last year";
        }
        return days/365 + " years ago";
    } else if (days <= -365) {
        if (-days/365 == 1) {
            return "Next year";
        }
        return -(days/365) + " years from now";
    } else {
        return minutes + " minutes ago";
    }

I want to reduce the number of if-else statements. The ways I was thinking of tackling this was:

Store these into a hashmap and then call it \$O(1)\$ time
Use enums
Ternary operators
Switch statements

I don't want to use enums since this is on a mobile device, and enums are heavier on memory. I was thinking that maybe ternary operators are best here. Thoughts?

The negative is intentional. It's with an API that I am working with and they use negatives to imply future events.

Input from API:

This is the following example input from the API:

"time": "2015-03-06 20:00:00 EST"

It is passed to the following code block, and it is expected to return something like:

"45 minutes ago"
"56 seconds ago"
"1 hour from now"
"2 days from now"
"2 months from now"
"Next year"
"Two years from now"
"A month ago"
"28 days ago"
"5 mins from now"
//etc.


texts: Trouble returning web scraping output as python dictionary

texts:
So I am attempting to scrape a website of its staff roster (https://www.milb.com/greenville/ballpark/frontoffice) and I want the end product to be a dictionary in the format of {staff: position}. I am currently stuck with it returning every staff name and position as a separate string. It is hard to clearly post the output, but it essentially goes down the list of names, then the position. So for example the first name on the list is to be paired with the first position, and so on. The lowest I could get to the text I need by using the class_ parameter was the individual div that the p is contained in. I am pretty sure that the way to accomplish this would be to use zip to put the elements in a dictionary, but I have tried several ways of getting there and nothing has worked so far. I am still inexperienced with python and new to web scraping, but I am relativity well versed with html and css, so help would be greatly appreciated.

# Simple script attempting to scrape
# the staff roster off of the
# Greenville Drive website

import requests
from bs4 import BeautifulSoup

URL = 'https://www.milb.com/greenville/ballpark/frontoffice'

page = requests.get(URL)

soup = BeautifulSoup(page.content, 'html.parser')

staff = soup.find_all('div', class_='l-grid__col l-grid__col--xs-12 l-grid__col--sm-4 l-grid__col--md-3 l-grid__col--lg-3 l-grid__col--xl-3')

for staff in staff:
    data = staff.find('p')
    if data:
        print(data.text.strip())

position = soup.find_all('div', class_='l-grid__col l-grid__col--xs-12 l-grid__col--sm-4 l-grid__col--md-6 l-grid__col--lg-6 l-grid__col--xl-6')

for position in position:
    data = position.find('p')
    if data:
        print(data.text.strip())

# This code so far provides the needed data, but need it in a dict()
```


texts: Correct 4 bytes out of 65K to match a crc32 checksum

texts:
I have a corrupted png image. I checked and the crc32 checksum of the first chunk (size ~65k) does not match with the one I get. I am sure of this.

Also, I have identified the 4 bytes that have the wrong value. I am sure of this.

My question: Is there an efficient way to calculate the values of these 4 bytes, in order to match the required crc32 checksum?

I made a program in C to brute force the values, using this CRC32 function

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

// The CRC32 function
uint32_t crc32(uint32_t crc, const void *buf, size_t SIZE_CHUNK);

// The size of the corrupted chunk (TYPE+DATA)
uint32_t SIZE_CHUNK = 65449;

// The CRC32 that has to be matched
uint32_t GOOD_CRC32 = 2784191201;

// The offset of the 4 corrupted bytes
uint32_t OFF[4] = {20121, 20467, 20742, 20893};

int main() {
        uint8_t *buf = (uint8_t *)calloc(SIZE_CHUNK, sizeof(uint8_t));
        uint32_t i, j, k, l, crc = 0;
        FILE *fp;

        fp = fopen("corrupted.png", "r+");
        // Offset to the first `IDAT` chunk of the png file
        fseek(fp, 87, SEEK_SET);
        // We fill `but` with the TYPE+DATA fields of the chunk
        fread(buf, sizeof(uint8_t), SIZE_CHUNK, fp);

        // Bruteforce...
        for (i=0; i<256; i++) {
                buf[OFF[0]] = i;
                for (j=0; j<256; j++) {
                        buf[OFF[1]] = j;
                        for (k=0; k<256; k++) {
                                buf[OFF[2]] = k;
                                for (l=0; l<256; l++) {
                                        buf[OFF[3]] = l;
                                        crc = crc32(0, buf, SIZE_CHUNK);
                                        if (crc == GOOD_CRC32)
                                                printf("Values found! i=%d j=%d k=%d l=%d\n", i,j,k,l);
                                }
                        }
                }
        }
        free(buf);
        fclose(fp);
}

However, this is very slow. If it doesn't speed up, it may take several days. It might be due to the size of the chunk (~65Kb).

I thought about pre-compute the CRC (the part from 0 to OFF[0]-1), but it would still be too long.

  Info:

  The exact size of the chunk is 65449. The corrupted bytes positions
  are between 20k-21k.


texts:
I'm in the process of creating a simple SDL2 wrapper for a breakout clone. The real learning objectives for this project are:

Learn how to manage resources properly via wrappers
Learn more about SDL2
I'm building these wrapper as I step through Lazy Foo's tutorial and wanted to get some feedback on how I'm doing, and what other things I could be doing.

Here's my SDL_Surface wrapper so far:

// Surface.h
#pragma once
#include <iostream>
#include <SDL.h>
#include <string>
#include "Window.h"

namespace SDL2 {
    class Surface
    {
    private:
        SDL_Surface* ScreenSurface = nullptr;
        bool IsWindowSurface = false;
        std::string ImagePath = "";

    public:
        // This function creates a Surface object associated with a Window (gets cleaned when Window is destroyed)
        Surface(SDL2::Window& window);
        Surface(std::string path);
        // Move constructor
        Surface(Surface&& source);
        // Disable copy constructor
        Surface(const Surface& source) = delete;
        ~Surface();
        // Disable copy by assignment
        Surface& operator=(const Surface& source) = delete;
        // Move assignment
        Surface& operator=(Surface&& source);
        void FillRect();
        void Update(SDL2::Window& window);
        bool LoadBMP();
        // TODO: Add more parameters at future SDL2 tutorial
        void BlitSurface(SDL2::Surface& destination);
    };
}

// Surface.cpp
#include "Surface.h"

SDL2::Surface::Surface(SDL2::Window& window) :
    ScreenSurface{ SDL_GetWindowSurface(window.GetSDLWindow()) },
    IsWindowSurface{ true }
{
}

SDL2::Surface::Surface(std::string path) :
    ImagePath{ path },
    IsWindowSurface{ false }
{
}

SDL2::Surface::Surface(Surface && source) :
    ScreenSurface{ source.ScreenSurface },
    IsWindowSurface{ source.IsWindowSurface },
    ImagePath{ source.ImagePath }
{
    source.ScreenSurface = nullptr;
    source.IsWindowSurface = false;
    source.ImagePath = "";
}

SDL2::Surface::~Surface()
{
    // If surface is not associated with Window, need free the surface with SDL2 call
    if (!IsWindowSurface) {
        SDL_FreeSurface(ScreenSurface);
    }
}

SDL2::Surface & SDL2::Surface::operator=(Surface && source)
{
    if (&source == this)
        return *this;

    // If surface is not associated with Window, need free the surface with SDL2 call
    if (!IsWindowSurface) {
        SDL_FreeSurface(ScreenSurface);
    }

    ScreenSurface = source.ScreenSurface;
    IsWindowSurface = source.ScreenSurface;
    ImagePath = source.ImagePath;

    // Return source to stable state
    source.ScreenSurface = nullptr;
    source.IsWindowSurface = false;
    source.ImagePath = "";

    return *this;

}

// TODO: Define SDL_Rect parameter and Color parameter (make wrappers for these)
void SDL2::Surface::FillRect()
{
    SDL_FillRect(ScreenSurface, NULL, SDL_MapRGB(ScreenSurface->format, 0x00, 0x00, 0xFF));
}

void SDL2::Surface::Update(SDL2::Window& window)
{
    SDL_UpdateWindowSurface(window.GetSDLWindow());
}

// This function is called after a non-window surface is created.  Check on this return value for success/fail.
bool SDL2::Surface::LoadBMP()
{
    // Load image from path
    ScreenSurface = SDL_LoadBMP(ImagePath.c_str());

    if (!ScreenSurface) {
        std::cout << "Unable to load image " << ImagePath << " SDL Error: " << SDL_GetError() << '\n';
        return false;
    }
    return true;
}

// The source Surface is `this`.  This function applies the image to the destination surface (though not updated on the screen)
void SDL2::Surface::BlitSurface(SDL2::Surface & destination)
{
    // Args: Source, FUTURE, Destination, FUTURE
    SDL_BlitSurface(this->ScreenSurface, NULL, destination.ScreenSurface, NULL);
}

Any pointers would be much appreciated!


texts:
This plugin is initialized like so:

$("#calendar").ksdCalendar({
    feedUrl: "http://www.kent.k12.wa.us/site/RSS.aspx?DomainID=275&ModuleInstanceID=4937&PageID=4334",
    elemHeight: 750
});

I would like a review on the code, structure, or anything else that comes to mind. What this plugin does is take an RSS feed from JGFeed, parse the entries, then pass them into another calendar plugin which in turn builds and displays the calendar.

(function ( $, window, document, undefined ) {
    "use strict";
    var Calendar = {

        init: function(options, elem) {

            this.options = $.extend( {}, this.options, options );
            this.elem = $(elem);

            this.setupAjax();
            this.getFeed();

            return this;
        },

        options: {
            feedUrl: "",
            elemHeight: 750
        },

        entries: [],

        getFeed: function() {
            var self = this;
            $.jGFeed(this.options.feedUrl, function (feeds) {

                if (!feeds) {
                    return false;
                }

                $.extend(self.entries, feeds.entries);

                self.parseEntries();
            }, 100);
        },

        parseEntries: function() {
            //Rename to fit plugin requirements
            for (var i = 0; i < this.entries.length; i++) {
                var entry = this.entries[i];
                    entry["allDay"] = false;

                //Rename
                entry["url"] = entry["link"];
                delete entry["link"];

                var position = entry.title.indexOf(' - ');

                if (position === -1) {
                    //All day event
                    entry.allDay = true;
                    var space = entry.title.indexOf(" "),
                        title = entry.title.substring(space + 1),
                        firstHalf = entry.title.slice(0, space); //Start date, no time because it's all day event
                } else {
                    var firstHalf = entry.title.slice(0, position), //Start date/time
                        secondHalf = entry.title.substring(position + 3);

                    if (secondHalf.indexOf("AM") !== -1) {
                        var title = secondHalf.substring(secondHalf.indexOf("AM") + 3); //Title if has AM
                    } else {
                        var title = secondHalf.substring(secondHalf.indexOf("PM") + 3); //Title if has PM
                    }

                    secondHalf = secondHalf.slice(0, -(title.length + 1)); //End date/time
                }

                entry["start"] = Date.parse(firstHalf);
                entry["end"] = Date.parse(secondHalf);
                entry.title = title;
            };

            this.setUpCalendar();
        },

        setUpCalendar: function() {
            this.elem.fullCalendar({
                editable:   false,
                weekends:   true,
                header: {
                    left:       'month basicDay',
                    center:     'title',
                    right:      'today prev, next'
                },
                height:     this.options.elemHeight,
                events:     this.entries
            });
        }
    };

    if ( typeof Object.create !== 'function' ) {
        Object.create = function (o) {
            function F() {}
            F.prototype = o;
            return new F();
        };
    }

    $.fn.ksdCalendar = function( options ) {
        if (this.length) {
            return this.each(function() {
                var myCalendar = Object.create(Calendar);
                myCalendar.init(options, this);
                $.data(this, 'ksdCalendar', myCalendar);
            });
        }
    };

})( jQuery, window, document );


texts:
Prospero is a URI scheme. There you have fields and values.

Could you check this code and give common suggestions or even test cases for JUnit tests?

(The documentation is in German.)

/**
 * Gibt einen Prospero-Parameter aus der URL zurück. Dabei wird nur der Prospero-Part geprüft.
 *
 * @param url Die URL, darf nicht null sein.
 * @param name Der Name des Parameters, darf kein '=' enthalten, darf nicht null
 *            sein.
 * @return Den Wert des Parameters oder
 *

 *
null

 *
wenn der Parameter ohne = angegeben wurde.

 *
error-Parameter

 *
wenn kein solcher Parameter gefunden wurde

 *

 */
public static String getProsperoParam(URL url, String name, String error) {
    String path = url.getPath();
    String[] split = path.split(";", 2);
    if (split.length == 2) {
        String params = split[1];
        for (String param : params.split("&")) {
            String[] paramParts = param.split("=", -1);
            if (paramParts.length == 1) {
                if (name.equals(paramParts[0])) {
                    return null;
                }
            }
            if (paramParts.length == 2) {
                if (name.equals(paramParts[0]))
                    return paramParts[1];
            }
            if (paramParts.length > 2) {
                if (name.equals(paramParts[0])) {
                    return param.substring(name.length() + 1);
                }
            }
        }
    }
    return error;
}

I successfully tested these cases:

assert URLTools.getProsperoParam(new URL("http://a:a@a.a.a/a.a?a=a#a"), "a", null) == null;
assert URLTools.getProsperoParam(new URL("http://a:a@a.a.a/a.a;a=4?a=a#a"), "a", null).equals("4");
assert URLTools.getProsperoParam(new URL("http://a:a@a.a.a/a.a;a=4=a?a=a#a"), "a", null).equals("4=a");
assert URLTools.getProsperoParam(new URL("http://a:a@a.a.a/a.a;a=4=a&m=3?a=a#a"), "m", null).equals("3");
String missingString = "Missing!";
assert URLTools.getProsperoParam(new URL("http://a:a@a.a.a/a.a;a=4=a&m=3?a=a#a"), "e", missingString) == missingString;
assert URLTools.getProsperoParam(new URL("http://a:a@a.a.a/a.a;e?a=a#a"), "e", "asdf") == null;
assert URLTools.getProsperoParam(new URL("http://a:a@a.a.a/a.a;e=?a=a#a"), "e", null).equals("");