texts: Reading a repetitive file with repetitive code

texts:
I made this code for take some data from a .txt file. The text file is a large list of data from temperature with a format that is repetitive and have some lines at the beginning with the station reference. I took the first ten lines but only one time, then I jump to line 12 to take the headers and then I have a mark that tell me if a new year of records is beginning and jump to line 13 and write from the line 13 to 30.

Is there a Pythonic way, without a lot of next(f)?

from itertools import islice
with open(rutaEscribir,'w') as w:
    with open(rutaLeer) as f:
        for line in islice(f,1,10):
            w.write(line)
        f.seek(0)
        for line in islice(f,12,13):
            w.write(line)
        f.seek(0)
        ano = 1977
        for line in f:
            sena = '&'
            if sena in line:
                print('Found')
                print('Año: ',ano)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                next(f)
                for n in  islice(f,0,31):
                    w.write(n)
                ano += 1

Here is an excerpt from the file:

&                      I D E A M  -  INSTITUTO DE HIDROLOGIA, METEOROLOGIA Y ESTUDIOS AMBIENTALES
                                                                                SISTEMA DE INFORMACION
                                   VALORES TOTALES DIARIOS DE RECORRIDO DEL VIENTO (Kms)                       NACIONAL AMBIENTAL

   FECHA DE PROCESO :  2016/09/08                    ANO  1986                              ESTACION : 26185020  MESOPOTAMIA

   LATITUD    0553 N               TIPO EST    CO                   DEPTO      ANTIOQUIA               FECHA-INSTALACION  1970-JUN
   LONGITUD   7519 W               ENTIDAD     01  IDEAM            MUNICIPIO  LA UNION                FECHA-SUSPENSION
   ELEVACION  2314 m.s.n.m         REGIONAL    01  ANTIOQUIA        CORRIENTE  BUEY

***********************************************************************************************************************************
         DIA       ENERO *  FEBRE *  MARZO *  ABRIL *  MAYO  *  JUNIO *  JULIO *  AGOST *  SEPTI *  OCTUB *  NOVIE *  DICIE *
***********************************************************************************************************************************

          01         144      35        10       32       52        6       81      133       44       29        7       17
          …
          05          35     +          31       18       16       15      110      160      125       12       18       56
          …

As you can see on the right, this is a repetitive file. In line 57 I put the & marker for the start of a new year of records.  The next few lines (57 to 65) contain the geographical position from the station, followed by the month header (ENERO,FEB...).  Then, 31 lines contain the data for that year.  I want to use PANDAS to analyze that data.

My code transforms it into something like this:

As you can see, the repetitive headers for geographical position and the months now appear just once.

But I think is possible to do it in a Pythonic way and not with a lot of next(f).


texts: Get owner of ~5 million files and folders using Powershell and Robocopy

texts:
I've written a Powershell script that uses Robocopy to get the full path of all files on a drive and then run it through a foreach loop to get the owner for each file and generate it in a CSV.  The code works, but is very slow when I run it against so many items.  Can someone help me make it as efficient as possible?  I also use "File System Security PowerShell Module 4.2.3" to use Get-NTFSOwner which gets me around the 256 character limit, which is also why I use Robocopy to generate the paths.

Import-Module NTFSSecurity

#Gets initial file and folder list
 $Folderpath = "G:\DEPT"
 $Folders = Get-Childitem $Folderpath

 ForEach ($Folder in $Folders) {Start-Job -ScriptBlock {
          Param($Folder,$Folderpath)
          robocopy "$FolderPath\$Folder" NULL /L /S /NJH /FP /NC /XJ /NS /NJH /NC /NJS /LOG:D:\AutoAssign\Data\RoboLogs\$Folder.txt

           } -ArgumentList $Folder,$Folderpath}

#Wait unitl all jobs are finished
Get-Job | Wait-Job

#Trims out white space and empty lines
  $Folderpath = "D:\AutoAssign\Data\RoboLogs"
  $Files = Get-Childitem $Folderpath

ForEach ($File in $Files) {Start-Job -ScriptBlock {
          Param($File,$Folderpath,$Files)
          $Trim = Get-Content "$Folderpath\$File"
          $Trim.trim() | Where { $_ } | Out-File "$Folderpath\$File"
           } -ArgumentList $File,$Folderpath,$Files }

#Wait unitl all jobs are finished
Get-Job | Wait-Job

#Gets Owner for each file And Create CSV

$Dir = "D:\AutoAssign\Data\RoboLogs"
$Files = Get-ChildItem $Dir
ForEach ($File in $Files){ Start-Job -ScriptBlock {
    Param($Dir,$Files,$File)

$OutputFile = "D:\AutoAssign\Data\Final\$File.csv"
$Results = @()

$Paths = Get-Content $Dir\$File
ForEach ($Path in $Paths){
 $Owner = get-ntfsowner $Path | Select Owner | ft -hidetableheaders | Out-String
 $Owner = $Owner.Trim()

      $Properties = @{

      Path = $Path
      Owner = $Owner

      }

If ($Owner -ne "BUILTIN\Administrators" -and $Owner -ne $null-and $Owner -ne "Domain\Domain Admins" -and $Owner -notlike "S-1*"){
    $Results += New-Object psobject -Property $properties}

    }

$Results | Export-Csv -notypeinformation -Path $OutputFile

} -ArgumentList $Dir,$Files,$File #Ends Initial ForEach

}  #Ends Job Script Block

#Wait unitl all jobs are finished
Get-Job | Wait-Job

#Merge all files into one CSV
Get-ChildItem  D:\AutoAssign\Data\Final | Select-Object -ExpandProperty FullName | Import-Csv | Export-Csv D:\AutoAssign\Data\G.csv -NoTypeInformation -Append

#Delete all original files
Get-ChildItem D:\AutoAssign\Data\RoboLogs | Remove-Item
Get-ChildItem D:\AutoAssign\Data\Final | Remove-Item


texts: Monadic transformation on a list, done in three ways

texts:
I am working my way through the Haskell Book and ran into the exercises at the end of the Monad chapter(18). One in particular asked to define a function with the following signature:

meh :: Monad m => [a] -> (a -> m b) -> m [b]

So I did. I found this routine difficult to implement at first, but once I understood what I was doing and what I needed to do a little better I figured it out.

I have three versions of the routine, my first attempt, a slightly refactored attempt, and a final attempt using do-notation. I was wondering if anyone can give advice on how I could potentially refactor this routine further, or how I can make my implementation better. I feel like I can make the routine far cleaner than I have it, but I am not sure how.

WARNING: If you are reading the Haskell Book and want to work through the exercises yourself, I recommend you do not read any further

Here are all three implementations

-- Attempt #1 with helper routine
meh :: Monad m => [a] -> (a -> m b) -> m [b]
meh list fn = doWork list (return $ []) fn
  where
    doWork (x:xs) base f
      | length xs == 0 = (addToMonad x base f) >>= (\x -> return $ reverse x)
      | otherwise = doWork xs (addToMonad x base f) f

addToMonad x baseMonad fn = do
  someVal <- (fn x)
  base <- baseMonad
  return $ someVal:base

-- Attempt #2 with a fold
meh' :: Monad m => [a] -> (a -> m b) -> m [b]
meh' list fn = (foldl (\acc x -> (fn x) >>= (\y -> acc >>= (\z -> return $ y:z))) (return $ []) list) >>= (\x -> return $ reverse x)

-- Attempt #3 with a fold and do-notation
mehDo :: Monad m => [a] -> (a -> m b) -> m [b]
mehDo list fn = do
  final <- (foldl (\acc x -> do
    val <- (fn x)
    mList <- acc
    return $ val:mList)
    (return $ []) list)
  return $ reverse final

I want to say my last implementation is the easiest to read (it would be easier with better names, IMO) but I don't really know that it is. I am not super experienced in the ways of Haskell, so to be frank I read the routines really slowly regardless.

Anyway, advice or tips on how to make this cleaner would be much appreciated.


texts:
I used the "long" form of all math statements, avoided the use of pointers, and used only while loops for aesthetic purposes (simply put, I think the code is prettier when it is written like that.) I am mainly concerned about the CPU efficiency of the code.

Bubble Sort - The quintessential example of an "inefficient" sorting algorithm. Often the first sorting algorithm introduced to college students.

void BubbleSort(int Array[], int Length)
{
    int CurrentIndex[2];
    int TemporaryValue;
    int WasThereASwap;

    WasThereASwap = 1;
    while (WasThereASwap == 1)
    {
        WasThereASwap = 0;
        CurrentIndex[0] = 0;
        CurrentIndex[1] = 1;
        while (CurrentIndex[1] != Length)
        {
            if (Array[CurrentIndex[0]] > Array[CurrentIndex[1]])
            {
                WasThereASwap = 1;
                TemporaryValue = Array[CurrentIndex[0]];
                Array[CurrentIndex[0]] = Array[CurrentIndex[1]];
                Array[CurrentIndex[1]] = TemporaryValue;
            }

            CurrentIndex[0] = CurrentIndex[0] + 1;
            CurrentIndex[1] = CurrentIndex[1] + 1;
        }
    }
}

Selection Sort - Usually outperforms bubble sort, but it is still not a very good sorting algorithm for large arrays.

void SelectionSort(int Array[], int Length)
{
    int BeginComparisonsIndex;
    int CurrentComparisonIndex;
    int CurrentLowestIndex;
    int TemporaryValue;

    BeginComparisonsIndex = 0;
    while(BeginComparisonsIndex != Length)
    {
        CurrentComparisonIndex = BeginComparisonsIndex;
        CurrentLowestIndex = BeginComparisonsIndex;
        while (CurrentComparisonIndex != Length)
        {
            if (Array[CurrentComparisonIndex] < Array[CurrentLowestIndex])
            {
                CurrentLowestIndex = CurrentComparisonIndex;
            }

            CurrentComparisonIndex = CurrentComparisonIndex + 1;
        }

        TemporaryValue = Array[BeginComparisonsIndex];
        Array[BeginComparisonsIndex] = Array[CurrentLowestIndex];
        Array[CurrentLowestIndex] = TemporaryValue;
        BeginComparisonsIndex = BeginComparisonsIndex + 1;
    }
}


texts:
The following is an implementation of a tree in C++ designed for keys which do not have an order (otherwise a std::map could be used). T is a key type and H is a hash for T.

#include <iostream>
#include <memory>
#include <utility>
#include <unordered_map>

template<typename T, typename H>
class tree;

template<typename T, typename H>
class tree : public std::unordered_map<T, std::shared_ptr<tree<T, H>>, H> { };

template<typename T, typename H>
std::ostream& operator<<(std::ostream& s, const tree<T, H> &t);

template<typename T, typename H>
std::ostream& operator<<(std::ostream& s, const tree<T, H> &t)
{
    for(auto i : t) {
        s << i.first << std::endl;
        s << *i.second << std::endl;
    }
    return s;
}


texts:
I was able to find all kinds of examples that demonstrate how to validate a Luhn Checksum but very few that actually generated the check digit. Here is my attempt in base 10, based on the validation examples found at Wikipedia and Rosetta Code:

/// <summary>
/// Constructs the check digit for a given numeric string using the Luhn algorithm; also known as the "mod 10" algorithm.
/// </summary>
/// <param name="value">The string that a check digit will be calculated from.</param>
public static int Mod10(string value) {
    const int validCodePointCount = 10;
    const int validCodePointOffset = 48;

    var index = value.Length;
    var parity = true;
    var sum = 0;

    while (0 < index--) {
        var digit = (value[index] - validCodePointOffset);

        if (parity) {
            if ((validCodePointCount - 1) < (digit <<= 1)) {
                digit -= (validCodePointCount - 1);
            }
        }

        parity = !parity;
        sum += digit;
    }

    return ((validCodePointCount - (sum %= validCodePointCount)) % validCodePointCount);
}


texts:
I was doing 3sum question on leetcode
Question
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4]
A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

My solution
For this I wrote the following solution but this is giving me Time Limit Exceeded error.

var threeSum = function(nums) {

    // Creating triplet memory so there are any duplicates
    const triplet_memory = {}

    // num occurrence will have all the numbers in the input array and number of time they occured
    const num_occurence = {}

    nums.forEach((element) => {
        if (!num_occurence.hasOwnProperty(element)) {
            num_occurence[element] = 1
        } else {
            num_occurence[element] += 1
        }
    })

    // iterating over input array
    nums.forEach((elParent, indexParent) => {

     // Nested loop so that I try all possible combination
        nums.forEach((elChild, indexChild) => {

            if (indexParent !== indexChild) {

                // decreasing the value of current element from our object
                // created copied_num_mem so that we don't change main object memeory
                const copied_num_mem = {...num_occurence}

                // We are decreasing the elParent and elChild value because for currentSum we are utilizing those value
                // For example if elParent is 1 and elChild = 2, we would be using those value in our currentSum hence we are decreasing their count by 1
                copied_num_mem[elParent] = copied_num_mem[elParent] - 1
                copied_num_mem[elChild] = copied_num_mem[elChild] - 1

                // multiplying by -1 because suppose we have elParent as -1 and elChild as -1, their sum would give us -2 and we would need the reciprocal of -2 i.e 2 to make it positive
                const currentSum = (parseInt(elParent) + parseInt(elChild))*-1

                // Checking if 2 exist in our copied_num_mem and if yes, it's value is greater than 0
                if (copied_num_mem.hasOwnProperty(currentSum.toString()) && copied_num_mem[currentSum.toString()] > 0) {

                  // 2, -1, -1 and -1, 2, -1 all are triplets, we are sorting it so that the order of triplet is always the same and we are going to then store that triplet in our triplet_memory
                  const tripletInt = [currentSum, parseInt(elParent), parseInt(elChild)].sort((a, b) => a -b)
                 const tripletStringified = tripletInt.join('/')
                 triplet_memory[tripletStringified] = true
                }
            }
        })
    })
    const finalErr = []
    Object.keys(triplet_memory).forEach(el => {
        const elements = el.split('/').map((element) => {
            return parseInt(element)
        })
        finalErr.push(elements)
    })
    return finalErr
};

console.dir(threeSum([0,0,0]))
console.dir(threeSum([-1,0,1,2,-1,-4]))

Can someone help me in optimizing the algorithm? I have added comments so it should be easy to understand the code.


texts: Basic Implementation of Hash Table in Python

texts:
Basic impl of hash_table in python.  Supports set, get, and delete.  Uses open addressing with linear probing function.  Any ideas would be greatly appreciated! Thanks!

class Entry:
    """
        holds key, value pairs
    """
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.is_deleted = False

class Map(object):
    """
        a basic, minimal implementation of a hash map
    """
    def __init__(self):
        """
            constructs a new Map
        """
        self.table = [None] * 10
        self.load_factor = .75
        self.current_size = 0

    def __setitem__(self, key, item):
        """
            stores the key value combo in the table
            implements open addressing collision resolution
        """
        entry = Entry(key, item)
        for i in range(len(self.table)):
            index = self.__get_hash_code(key, i)

            if self.table[index] is None or self.table[index].is_deleted:
                self.table[index] = entry
                self.current_size += 1
                if float(self.current_size) / len(self.table) >= self.load_factor:
                    self.__resize_table()
                break

    def __getitem__(self, key):
        """
            gets the value associated with the key
        """
        for i in range(len(self.table)):
            index = self.__get_hash_code(key, i)

            if self.table[index] is not None:
                if self.table[index].key == key:
                    if self.table[index].is_deleted:
                        raise KeyError('Key is not in the map')
                    else:
                        return self.table[index].value

            elif self.table[index] is None:
                raise KeyError('Key is not in the map')

        raise KeyError('Hmm something has gone wrong here')

    def __get_hash_code(self, key, value):
        return (hash(key) + value) % len(self.table)

    def __resize_table(self):
        new_table = [None] * (len(self.table) * 2)
        for i in range(len(self.table)):
            new_table[i] = self.table[i]

        self.table = new_table

    def delete(self, key):
        """
            deletes a value from the hash table
        """
        for i in range(len(self.table)):
            index = self.__get_hash_code(key, i)

            if self.table[index] is not None:
                if self.table[index].key == key:
                    if self.table[index].is_deleted:
                        raise KeyError('Key is not in the map')
                    else:
                        self.table[index].is_deleted = True
                        self.current_size -= 1
                        break


texts: Is it ok to pull out specific arguments from a Java dynamic proxy invocation?

texts:
I have a Java dynamic proxy with an invoke method that looks like this:

 @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object result;
    try {
        //Not sure if this line is ok?
        Token token = (Token) args[0];

        System.out.println("Token with id: "+token.getId()+ " was passed");
        result = method.invoke(realObject, args);
    } catch (InvocationTargetException e) {
        throw e.getTargetException();
    } catch (Exception e) {
        throw new RuntimeException("unexpected invocation exception: " + e.getMessage());
    } finally {
        System.out.println("after method " + method.getName());
    }
    return result;
}

Would it be considered bad practice to pull out and cast that Token object from the args array?

The problem I can see is that it means the proxy isn't generic and in fact will only work for method invocations that pass an instance of a Token object as the first parameter.


texts: JavaScript module to render and handle a form to add users

texts:
I recently switched to modular JavaScript and really like the idea of having the state of your application in JavaScript and not in the DOM. I want to know if what I am doing is considered best practices or not and how I can avoid re-rendering the entire list after each change.

First, the code:

HTML

<form id="add-user-form">
  <input type="text" placeholder="username" name="username">
  <button>add User</button>
</form>

JavaScript

// lets you get templates from HTML ( as you can see in the HTML above ).
// This is to avoid writing out HTML inside JavaScript
const Template = {
  cached: {},
  get(templateId, placeholders) {
   let templateHtml = ''
   if (!this.cached[templateId]) {
      templateHtml = document.getElementById(templateId).innerHTML.trim()
      this.cached[templateId] = templateHtml
   }
   else {
      templateHtml = this.cached[templateId]
   }

   for (key in placeholders) {
     templateHtml = templateHtml.replace(new RegExp("\\${\\s*" + key + "\\s*}", "g"), placeholders[key]);
   }
   return templateHtml
  }
}

const Users = {
  users: [],
  init() {
    this.cacheDom()
    this.bindEvents()
  },
  cacheDom() {
    this.addUserFormEl = document.getElementById('add-user-form')
    this.userListEl = document.getElementById('user-list')
  },
  bindEvents() {
    this.addUserFormEl.addEventListener('submit', this.handleAddUser.bind(this))
  },
  render() {
    // gets the HTML from ALL users of our user list and replaces the current user list
    const userHtml = this.users.map( user => Template.get('user-template', user) ).join('')
    this.userListEl.innerHTML = userHtml
  },
  handleAddUser(e) {
    e.preventDefault()

    const username = e.currentTarget.elements['username'].value
    if (!username) return
    e.currentTarget.elements['username'].value = ''

    const key = this.users.length // I know I know this is bad practice, please ignore :)

    this.users.push({
      key: key,
      name: username
    })

    this.render()
  }
}

Users.init()

The code has a form with an input field where you can type in a name that, once the form gets submitted, will be added to the user list below. It would probably be a good idea to separate the userlist and the userform into seperate concerns, but for the sake of this example I kept it simple.

I want to keep DOM modifications to a minimum so I put them inside the method Users.render. This however has one side-effect. Whenever I add an user, it reloads the entire list. It might work with this amount of data, but let's say I have thousands of records, maybe even with input fields. These would all be emptied again.

I could of course just add the new entry to the DOM inside the Users.handleAddUser method but what if later I also want to delete users? I would have to delete the entry within Users.handleRemoveUser and would then have two methods that handle DOM modifications for the same thing.

I know this all can be easily and beautifully achieved with frameworks such as VueJs that use a vDOM but I am looking for a vanillaJs way of handling this.
(Please note that the code is just an example. Yes Unit testing and typeScript are missing and I am well aware of the fact that the code will not run in browsers that do not support ES-6).


texts:
How do I find the number of unique digits in a given number.

e.g
if 'input1' is 252 it must return 1, since 5 is the non-repeating digit;
if 'input1' is 25000 it must return 2, since digits 2 and 5 are the only non-repeating ones.

Is there a better way to solve this problem?

// COUNT UNIQUE DIGITS

int nonRepeatDigitsCount(int input1){
int i=0,j,k;
int n=input1;
int count=0,check,c2=0;

// FINDING NUMBER OF DIGITS ON THE GIVEN NUMBER
while(n>0){

    n=n/10;
    c2++;
    }
//CREATING ARRAY OF THE 'c2' SIZE
int arr[c2];
n=input1;
//STORING INDIVIDUAL DIGITS IN THE ARRAY
while(n>0)
{
    arr[i]=n%10;
    n=n/10;
    i++;

}
// CONDITION TO FIND NON REPEATING DIGITS
for(j=0;j<c2;j++)
{
    check=0;

    for(k=0;k<c2;k++)
    {
          if(j!=k)
          {
           if(arr[j]==arr[k])
           {
            check++;
           }
          }

    }

    if(check==0)
     {
        count++;
     }
 }

return count;
}


texts: Maximum product of word lengths in Python

texts:
Problems was to calculate maximum product of word lengths:

  Given a string array words, find the maximum value of length(word[i])
  * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If
  no such two words exist, return 0.

Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The two words can be "abcw", "xtfn".

Example 2:
Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return 4
The two words can be "ab", "cd".

Example 3:
Given ["a", "aa", "aaa", "aaaa"]
Return 0

My answer is correct and passed all the test cases. I am looking to get some code review on this.

class Solution(object):
    def maxProduct(self, words):
        """
        maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters
        >> maxProduct(["eae", "ea", "aaf", "bda", "fcf", "dc", "ac", "ce", "cefde", "dabae"])
        >> 15
        """
        max_product = 0
        words = sorted(words, key=len, reverse=True)
        for index, j in enumerate(words):
            for i in words[index + 1:]:
                count = 0
                for k in i:
                    if k in j:
                        count = 1
                        break
                if not count:
                    m = len(j)
                    n = len(i)
                    word_product = m * n
                    if ((m == n) or (m > n and n == m - 1)) and word_product > max_product:
                        return word_product
                    if word_product > max_product:
                        max_product = word_product
        return max_product


texts: Powershell Script to remove printers and drivers

texts:
I am learning Powershell Scripting as I move my work environment to Windows 10. The script below is to be edited by the SysAdmin (for the list of Print Queues and Printer Drivers) to specify what needs to be removed, then outputs what it did. I am looking for whether the Powershell syntax / convention is followed. This script will be distributed to other SysAdmins in my team when completed.

The script currently starts by declaring variables that will be used throughout the script. The variables tell the script which print queues to remove, and what print drivers to remove. It then loops through the arrays, removing the printers requested.

# Remove old printers by name - Written by Luke Barone
#
# VARIABLES TO EDIT
# $PrintersToRemove - (REQUIRED) An array of printers to cycle through and
#     remove. Use the exact name of the printer to have it included in the list
# $PrintDriversToRemove - (optional) An array of printer drivers to cycle
#     through and remove. You can obtain a list by running the "prndrvr.vbs -l"
#     command on a computer with drivers to remove. Alternatively, you can
#     leave the array empty, and the script will remove any unused (determined
#     by the system) print drivers automatically.
$PrintersToRemove = @("Printer1", "Printer2")
$PrintDriversToRemove = @("Manufacturer1", "Manufacturer2")

# The variables below should only be changed from the default if the scripts
# are not in this location!
$PrintingAdminScriptsFolder = "C:\Windows\System32\Printing_Admin_Scripts\en-US"
$PrintScriptFiles = @("prnmngr.vbs", "prndrvr.vbs")

# SANITY CHECKS
If ($PrintersToRemove.Length -eq 0) {
    Write-Host "Required variable not filled! Please edit the script and re-run"
    Exit 1
}
If (($PrintScriptFiles | ForEach {Test-Path ($PrintingAdminScriptsFolder + "\" + $_)}) -contains $false) {
    Write-Host "Required scripts not found in specified folder! I need the two
    VBS scripts ($(PrintScriptFiles)) inside of $($PrintingAdminScriptsFolder)
    in order to function!"
    Exit 2
}

# SCRIPT START
Write-Host "Starting at $(Get-Date -Format g) on client $($env:COMPUTERNAME)"
C:\Windows\System32\cscript.exe //H:CSCRIPT //S | out-null
cd $PrintingAdminScriptsFolder
Write-Host ""
Write-Host "Removing selected printers..."
$PrintersToRemove | foreach {
    & .\prnmngr.vbs -d -p "$_".ToString() | findstr "0x80041002" | out-null
    If ($LASTEXITCODE -eq 0) {
        Write-Host "    $_ does not exist"
    } else {
        Write-Host "    $_ removed"
    }
}
Write-Host ""

If($PrintDriversToRemove.count -gt 0) {
    Write-Host "Removing selected Printer Drivers..."
    $PrintDriversToRemove | foreach {
        & .\prndrvr.vbs -d -m "$_" -v 3 -e "Windows x64".ToString() | findstr "0x80041002" | out-null
        If ($LASTEXITCODE -eq 0) {
            Write-Host "    $_ does not exist"
        } else {
            Write-Host "    $_ driver removed"
        }
    }
} else {
    Write-Host "Removing excess Printer Drivers..."
    .\prndrvr.vbs -x
}


texts: Function to split full name into first & last

texts:
In angular, I have an input field for a user's full name. And a function called splitName which extracts the first / last name from the field. Is there a way to improve this logic?

<input type="text" name="fullName" ng-model="data.full_name" />

On the backend, on form submit I do a POST which requires both a first_name and last_name in the body.

    scope.splitName = function(data, fullName) {
      var formData = angular.copy(data),
          nameArr,
          _lastName;

      if (fullName) {
        nameArr = fullName.split(' ');

        if (nameArr.length > 2) {
          _lastName = nameArr.pop();
          formData.first_name = nameArr.join(' ');
          formData.last_name = _lastName;
        } else {
          formData.first_name = nameArr[0];
          formData.last_name = nameArr[nameArr.length - 1];
        }
      }

      // remove full name as its not needed for backend
      delete formData.full_name;

      // return the copy
      return formData;
    };

Therefore, these are some examples.

scope.data = {
   full_name: 'Joe Middle Name Smith',
   first_name: '',
   last_name: '',
}

var example = scope.splitName(scope.data, scope.data.full_name);

//- which should return
{
  first_name: 'Joe Middle Name',
  last_name: 'Smith'
}


texts: Dice rolling program which also counts and stores the result

texts:
Is there any room for improvement, in terms of simplicity and efficiency?
from random import randint

class Dice():

    def __init__(self):
        """Making a dice instance with 6 sides."""
        self.sides = 6

class Roller(Dice):

    def __init__(self,name,age):
        """Making a Dice Roller Instance"""
        super().__init__()
        #inhert sides attribute of a dice
        self.name = name
        self.age = str(age)

    def describe_roller(self):
        """Describe the information of the roller"""
        print('name: ' + self.name.title())
        print('age: ' + self.age)

    def roll_multiple(self,t):
        """Roll the dice multiple times and keep count in a dict"""
        count = {}
        one = 0
        two = 0
        three = 0
        four = 0
        five = 0
        six = 0
        for i in range(0,t):
            key = randint(1, self.sides)

            if key == 1:
                one += 1
                count["one"] = one
            elif key == 2:
                two += 1
                count["two"] = two
            elif key == 3:
                three += 1
                count["three"] = three
            elif key == 4:
                four += 1
                count["four"] = four
            elif key == 5:
                five += 1
                count["five"] = five
            elif key == 6:
                six += 1
                count["six"] = six
        print(count)

mike = Roller('mike',25)
mike.roll_multiple(6)


texts: Is it correct to extend a bean class and write a class which holds logic to populate the bean we extend?

texts:
I need to extract some metrics from ManagedBeans and store the collected metrics in an object bean.

The object bean is defined with member variables to hold the metrics. In this case, is it right to extend the ObjectBean and write the extractor class?

For example:

class ThreadMetricsBean {
    private long liveCount, daemonCount;

    public void record(long liveCount, long daemonCount) {
        this.liveCount = liveCount;
        this.daemonCount = daemonCount;
    }
}

// Here to avoid code redundancy I feel it's correct to extend the  ThreadMetricsBean class
// Am I wrong ??

class ThreadMetricsExtractor {
    private long liveCount, daemonCount;
    private ThreadMetricsBean bean = new ThreadMetricsBean();

    public void run() throws Exception{
        extractMetrics();
        recordToBean();
    }

    private void extractMetrics() {
        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        this.liveCount = threadMXBean.getThreadCount();
        this.daemonCount = threadMXBean.getDaemonThreadCount();
    }

    private void recordToBean() {
        bean.record(liveCount, daemonCount);
    }
}


texts: Finding recessions in US GDP data using pandas

texts:
For an assignment, I am identifying the first quarter of the 2008 recession in the United States. The Excel data I'm using can be downloaded here: gdplev.xls. How can I improve this pandas code to make it more idiomatic or optimized?

def get_recession_start():
    '''Returns the year and quarter of the recession start time as a
    string value in a format such as 2005q3'''
    GDP_df = pd.read_excel("gdplev.xls",
                           names=["Quarter", "GDP in 2009 dollars"],
                           parse_cols = "E,G",
                           skiprows = 7)
    GDP_df = GDP_df.query("Quarter >= '2000q1'")
    GDP_df["Growth"] = GDP_df["GDP in 2009 dollars"].pct_change()
    GDP_df = GDP_df.reset_index(drop=True)
    # recession defined as two consecutive quarters of negative growth
    GDP_df["Recession"] = (GDP_df.Growth < 0) & (GDP_df.Growth.shift(-1) < 0)
    return GDP_df.iloc[GDP_df["Recession"].idxmax()]["Quarter"]
get_recession_start()


texts:
I wondered how an expandable list could be implemented. My first thought: You could create a class that has an array and you can create a new array each time the user wants to append an element and than you can copy the old array plus the new element into the new array. But this seems very inefficient to me. Then I read something about so called linked lists. The idea is very simple. Such a list has nodes. Nodes contain an object and another node. The nodes can be linked as required. I had my thoughts about that and I tried to write a class that follows this thought.

LinkedList.java

package linkedList;

public class LinkedList<T> {
    private Node<T> startNode;

    public LinkedList() {
        startNode = new Node<T>();
    }

    private Node<T> getEmptyNode() {
        Node<T> currentNode = this.startNode;
        while (currentNode.hasObject()) {
            currentNode = currentNode.getNextNode();
        }
        return currentNode;
    }

    public void insert(T object) {
        Node<T> emptyNode = getEmptyNode();
        emptyNode.setObject(object);
        emptyNode.setNextNode(new Node<T>());
    }

    public int getNumberOfElements() {
        Node<T> currentNode = startNode;
        int numberOfElements = 0;
        while (currentNode.hasObject()) {
            numberOfElements++;
            currentNode = currentNode.getNextNode();
        }
        return numberOfElements;
    }

    private Node<T> getNodeByIndex(int index) {
        Node<T> currentNode = startNode;
        for (int i = 0; i < index; i++) {
            currentNode = currentNode.getNextNode();
        }
        return currentNode;
    }

    public T get(int index) {
        return getNodeByIndex(index).getObject();
    }

    public void delete(int index) {
        if (index == 0) {
            startNode = getNodeByIndex(1);
            return;
        }

        // if index equals last available index
        if (index == (getNumberOfElements() - 1)) {
            Node<T> nodeBefore = getNodeByIndex(index - 1);
            nodeBefore.setNextNode(null);
            return;
        }

        Node<T> nodeBefore = getNodeByIndex(index - 1);
        Node<T> nodeBehind = getNodeByIndex(index + 1);
        nodeBefore.setNextNode(nodeBehind);
    }
}

Node.java

package linkedList;

public class Node<T> {
    private T object;
    private Node<T> nextNode;

    public Node() {
        this.object = null;
        this.nextNode = null;
    }

    public boolean hasObject() {
        return object != null;
    }

    public boolean hasNextNode() {
        return nextNode != null;
    }

    public T getObject() {
        return object;
    }

    public Node<T> getNextNode() {
        return nextNode;
    }

    public void setNextNode(Node<T> nextNode) {
        this.nextNode = nextNode;
    }

    public void setObject(T object) {
        this.object = object;
    }
}

Main.java

package linkedList;

public class Main {
    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList<>();
        linkedList.insert("Hallo");
        linkedList.insert("Test");
        linkedList.insert("Wie gehts?");
        linkedList.insert("Freuen sie sich?");
        System.out.println("Anzahl der Elemente: " + linkedList.getNumberOfElements());
        System.out.println("Drittes Element: " + linkedList.get(2));
        System.out.println("Alle Elemente:");
        for (int i = 0; i < linkedList.getNumberOfElements(); i++) {
            System.out.println(linkedList.get(i));
        }

        linkedList.delete(2);
        System.out.println("Alle Elemente:");
        for (int i = 0; i < linkedList.getNumberOfElements(); i++) {
            System.out.println(linkedList.get(i));
        }
    }
}

Because this is my first attempt to do such stuff I am wondering what things can be improved. Is there a way to make this more efficient? Is the code clean and readable enough?


texts:
I have written a simple C header for converting the endianness of short integers and long integers. It uses the GCC macro __BYTE_ORDER__ to check the system's byte order and define the macros based on that.

The header creates the macros LITTLE_ENDIAN_SHORT(n), LITTLE_ENDIAN_LONG(n), BIG_ENDIAN_SHORT(n), BIG_ENDIAN_LONG(n) which convert the value n from host endianness to the endianness specified.

Here is the source for endian.h:

#ifndef ENDIAN_H
#define ENDIAN_H

#define REVERSE_SHORT(n) ((unsigned short) (((n & 0xFF) << 8) | \
                                            ((n & 0xFF00) >> 8)))
#define REVERSE_LONG(n) ((unsigned long) (((n & 0xFF) << 24) | \
                                          ((n & 0xFF00) << 8) | \
                                          ((n & 0xFF0000) >> 8) | \
                                          ((n & 0xFF000000) >> 24)))

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#    define LITTLE_ENDIAN_SHORT(n) (n)
#    define LITTLE_ENDIAN_LONG(n) (n)
#    define BIG_ENDIAN_SHORT(n) REVERSE_SHORT(n)
#    define BIG_ENDIAN_LONG(n) REVERSE_LONG(n)
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#    define LITTLE_ENDIAN_SHORT(n) REVERSE_SHORT(n)
#    define LITTLE_ENDIAN_LONG(n) REVERSE_LONG(n)
#    define BIG_ENDIAN_SHORT(n) (n)
#    define BIG_ENDIAN_LONG(n) (n)
#else
#    error unsupported endianness
#endif

#endif

Is this a good way to implement the macros or is there a better way?


texts: Buttons labelled with the number of times they have been clicked

texts:
I am new to functional programming and I decided to learn it thru Elm instead of haskell. I wrote a practice code where there are 2 buttons and their names correspond to the number of times they are clicked. The following is my implementation:

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick)

main = Html.beginnerProgram {model=model, view=view, update=update}

-- model
type alias Model =
   { a : Int
   , b : Int
   , total : Int}

model : Model
model = Model 0 0 0

 -- view
type Msg = Add Foo
type Foo = A | B

view : Model -> Html Msg
view model =
   div []
     [ button [onClick (Add A)] [text (toString model.a)]
     , button [onClick (Add B)] [text (toString model.b)]
     , div [] [ text (toString model.total)]
     ]

 -- update
update : Msg -> Model -> Model
update msg model =
   case msg of
     Add foo ->
       case foo of
         A ->
           let
             a = model.a + 1
             total = a + model.b
           in
             {model | a = a, total = total}
         B ->
           let
             b = model.b + 1
             total = b + model.a
           in
             {model | b = b, total = total}

I feel like that the above code is a dumb implementation of what I wanted to accomplish. Can somebody suggest a better implementation?


texts:
Formally, a deterministic finite automaton is a 5-tuple \$M = (Q, \Sigma, \delta, q_0, F)\$, where

\$Q\$ is the set of all possible states
\$\Sigma\$ is the alphabet
\$\delta \colon Q \times \Sigma \to Q\$ is the transition function
\$q_0\$ is the starting state
\$F\$ is the set of accepting states

Basically, each DFA represents a so-called regular language \$L\$, and given input string \$s\$, answers whether \$s \in L\$. This is done in \$\mathcal{O}(|s|)\$ time simply by consuming each character and making the state transitions starting from \$q_0\$; if after reading the entire string we end up in a state in \$F\$, the DFA accepts the string.

Please, tell me anything that comes to mind.

TransitionFunction.java

package net.coderodde.dfa;

import java.util.HashMap;
import java.util.Map;

/**
 * This class implements a transition function.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Apr 2, 2016)
 */
public class TransitionFunction {

    private final Map<Integer, Map<Character, Integer>> function =
          new HashMap<>();

    public void setTransition(Integer startState,
                              Integer goalState,
                              char character) {
        function.putIfAbsent(startState, new HashMap<>());
        function.get(startState).put(character, goalState);
    }

    public Integer process(Integer startState, char character) {
        if (!function.containsKey(startState)) {
            return null;
        }

        return function.get(startState).get(character);
    }
}

DFA.java

package net.coderodde.dfa;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Objects;
import java.util.Scanner;
import java.util.Set;

/**
 * This class implements a
 *
 * deterministic finite automaton.
 *
 * @author Rodion "rodde" Efremov
 * @version 1.6 (Apr 2, 2016)
 */
public class DFA {

    private final TransitionFunction transitionFunction;
    private final int startState;
    private final Set<Integer> acceptingStates;

    public DFA(TransitionFunction transitionFunction,
               int startState,
               Set<Integer> acceptingStates) {
        this.transitionFunction =
                Objects.requireNonNull(transitionFunction,
                                       "Transition function is null.");
        this.startState = startState;
        this.acceptingStates =
                Objects.requireNonNull(acceptingStates,
                                       "Accepting state set is null.");
    }

    public boolean matches(String text) {
        Integer currentState = startState;

        for (char c : text.toCharArray()) {
            currentState = transitionFunction.process(currentState, c);

            if (currentState == null) {
                return false;
            }
        }

        return acceptingStates.contains(currentState);
    }

    public static void main(String[] args) {
        // A regular language over binary strings with even number of 1's.
        TransitionFunction transitionFunction = new TransitionFunction();

        transitionFunction.setTransition(0, 0, '0');
        transitionFunction.setTransition(1, 1, '0');
        transitionFunction.setTransition(0, 1, '1');
        transitionFunction.setTransition(1, 0, '1');

        Set<Integer> acceptingStates = new HashSet<>(Arrays.asList(0));
        DFA dfa = new DFA(transitionFunction, 0, acceptingStates);

        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();

            if (line.trim().equals("end")) {
                break;
            }

            System.out.println(dfa.matches(line));
        }
    }
}


texts:
I intend to populate some fields in a form based on some presets values. The user choose the presets from a list. The following code is working, but as I'm a newbie, I would like to know if I done it the proper way and if it can be improved.

Preset obj:

var obj = {
    "preset_a":{
        "input":{
            "field_a":"value",
            ...
            "field_b":"value",
        },
        "select":{
            ...
        },
        "radio":{
            ...
        }
    },
    "preset_b":{
        "input":{
            "field_a":"value",
            ...
            "field_b":"value",
        },
        "select":{
            ...
        },
        "radio":{
            ...
        }
    }
};

The script:

function applyPresets(preset)
{
    if (typeof obj[preset] != 'undefined')
    {
        if (typeof obj[preset]['input'] != 'undefined')
        {
            jQuery.each(obj[preset]['input'], function( k, v ) {
                jQuery("input#"+ k).val(v);
            });
        }

        if (typeof obj[preset]['select'] != 'undefined')
        {
            jQuery.each(obj[preset]['select'], function( k, v ) {
                jQuery("select#" + k).val(v);
            });
        }

        if (typeof obj[preset]['radio'] != 'undefined')
        {
            jQuery.each(obj[preset]['radio'], function( k, v ) {
                jQuery("fieldset#" + k + " > input[type=radio]").val(v);
            });
        }
    }
    else
    {
        alert('Preset [ ' + preset + ' ] not found!');
        return;
    }

    submitSettings();
}


texts: Read quantization tables from JPEG files

texts:
I'm developing an application that will hide information inside the quantization tables of JPEG files. It's called DQTsteg, if you want to know more about what I'm attempting to do.

Right now I'm developing the most basic component of this system, which is the part that reads quantization tables from files. So it'd be a good thing if this code were as fast as it can possibly be, as it'll be a very frequent operation.

Here's the whole code on GitHub, fewer than 93 lines long.

I have noticed that sometimes urllib.requests sometimes are somewhat slow (above one second).

I've seen some people on Stack Overflow saying that some servers don't support byte by byte requests through urllib.request (you either download the whole file or you don't). I don't know whether these people are right or not, but is there any case where this urllib.request could go wrong (and then I'd either be denied access to the target file or I'd loop endlessly over the first few bytes, or anything of this sort)?

Any suggestions are welcome. Here follows the code:

#!/usr/bin/env python

"""
QT_reader.py

Functions for reading quantization tables from files and URLs.

Below are some global variables defined according to the JPEG Standard.

"""

DEFINE_QUANTIZATION_TABLE = b'\xff\xdb'
SINGLE_TABLE_PAYLOAD_DATA = b'\x00\x43'
DOUBLE_TABLE_PAYLOAD_DATA = b'\x00\x84'

def load_file(jpgpath):
    """
    Loads a file from jpgpath. Direct acess not intended; use QT_get_single() or QT_get_all().
    Args:
        jpgpath (str): file path.
    Returns:
        jpgpath (object): file object.
    """
    if load_file.status == "web":
        import urllib.request
        jpgpath = urllib.request.urlopen(jpgpath)
    if load_file.status == "file":
        jpgpath = open(jpgpath,"rb")
    return jpgpath

def QT_get_single(jpgpath, status="file"):
    """
    Reads a single quantization table from file.
    Args:
        jpgpath (str): file path, local or URL.
        status (str): set to "file" for local files or set to "web" for URLs.
    Returns:
        tuple: A tuple with .tell() position for the DQT on [0] and the QT table itself on [1] as a bytearray.
    """
    if QT_get_single.status != "off":
        if status == "web":
            load_file.status = "web"
        elif status == "file":
            load_file.status = "file"
        load_file.jpgpath = jpgpath
        jpgpath = load_file(load_file.jpgpath)
    while True:
        while True:
            QT_buffer = jpgpath.read(2)
            if QT_buffer == DEFINE_QUANTIZATION_TABLE: break
            if QT_buffer == b'':
                raise EOFError("Reached end of file.")
        DQT_position = jpgpath.tell()
        QT_buffer = jpgpath.read(2)
        if QT_buffer == DOUBLE_TABLE_PAYLOAD_DATA:
            QT_buffer = jpgpath.read(130)
            break
        elif QT_buffer == SINGLE_TABLE_PAYLOAD_DATA:
            QT_buffer = jpgpath.read(65)
            break
        else:
            continue
    return ( DQT_position, bytearray(QT_buffer) )

def QT_get_all(jpgpath, status="file",stop=-1):
    """
    Reads multiple quantization tables from file. Reads all QTs by default.
    Args:
        jpgpath (str): file path, local or URL.
        status (str): set to "file" for local files or set to "web" for URLs.
        stop (int): Stop after retrieving the nth table. One retrieves one; two retrieves two; zero or default retrieves all.
    Returns:
        list: A list of QT_get_single() tuples.
    """
    QT_tables = []
    counter = 0

    load_file.status = status
    load_file.jpgpath = jpgpath
    jpgpath = load_file(load_file.jpgpath)

    QT_get_single.jpgpath = jpgpath
    QT_get_single.status = "off"

    while True:
        try:
            QT_buffer = QT_get_single(QT_get_single.jpgpath,QT_get_single.status)
            QT_tables.append(QT_buffer)
            counter += 1
        except: break
        if counter == stop: break
    return QT_tables


texts: Retrieving result sets from a MySQL table

texts:
This retrieves result sets from a MySQL table. The objective of this function is to correctly retrieve any number of rows (with $sql) from a MySQL table, binding the needed values accordingly ($params[]), having the possibility to choose the column/s you want to retrieve ($cols[]).

$db = new PDO('mysql:host=127.0.0.1;dbname=xxx;charset=utf8','root','');

function query($sql, $params=[], $cols=[], $db){
    if($stmt = $db->prepare($sql)){
        $x = 1;
        $vec = [];
        if(count($params)){
            foreach($params as $p){
                $stmt->bindValue($x, $p);
                $x++;
            }
        }
    }
    if($stmt->execute()){
        while($row = $stmt->fetch(PDO::FETCH_OBJ)){
            $array = '';
            foreach ($cols as $col) {
                $array .= $row->$col.' ';
            }
            $vec[] = $array;
        }
        return $vec;
    } else {
        return $db->errorInfo();
    }
}

Call:

foreach (query('SELECT * FROM angajati WHERE nume=?',['admin'],['id','nume','prenume'],$db) as $q){
    echo $q,'<br/>';
}

My questions are the following:

How can I improve this function?
Is there any query that can not be run correctly by this function? joins, subqueries, etc.
Is there anything else you think that isn't right at this function?


texts: Advent Of Code 2020, day 1, find desired sum and multiply the addends


texts:
I have created an Arduino sketch that I am using to send and receive data via serial. It works pretty well and doesn't seem go wrong as long as the correct formats are received. Is there anything I could do to improve this/shrink it to clear up some code smells?

String dataString;
void setup() {
 Serial.begin(9600);

 //setup digital pins as inputs pin 3 - 13
 for (int i = 2; i <= 7; i++) {
    pinMode(i, INPUT);
  }
  //setup digital pins as OutPuts  pin 22 - 53
  for (int i = 7; i <= 13; i++) {
    pinMode(i, OUTPUT);
  }

}
void loop() {
  serialDataOutput();
  serialDataInput();
  delay(100);

}

void serialDataOutput() {
  dataString = "";
  for (int i = 0; i <= 13; i++) {
    dataString.concat(i);
    dataString.concat("," + String(digitalRead(i)) + "/");
  }

  for (int i = 14; i <= 18; i++) {
   dataString.concat(i);
   dataString.concat("," + String(analogRead(i - 14)) + "/");
  }
   Serial.println(dataString);
  delay(0);
    }
      void serialDataInput() {
  String Input;
   if (Serial.available() > 0) { // If data is available to read,
    Input = Serial.readStringUntil('\n'); // read it and store it in val
  }
  //  Input = "13,1";
  int commaIndex = Input.indexOf(',');
  //  Search for the next comma just after the first
  int secondCommaIndex = Input.indexOf(',', commaIndex + 1);
  String firstValue = Input.substring(0, commaIndex);
  String secondValue = Input.substring(commaIndex + 1, secondCommaIndex);
  digitalWrite(firstValue.toInt(), secondValue.toInt());
}


texts: Lazy-loading iframes as they scroll into view

texts:
I'm working in a Tableau driven system, with large numbers of charts, I needed a way to reduce the strain of the initial load of our app. It's fairly simple, but wanted to ensure I accounted for every scenario, I don't generally utilize lazy loading.

Print isn't a priority.

jsfiddle: Demo (Tableau doesn't work within SO's snippets because of the iframes)

Relevant Javascript

const throttle = (fn, delay) => {
    let canCall = true;
    return (...args) => {
      if (canCall) {
        fn.apply(null, args);
        canCall = false;
        setTimeout(() => {
          canCall = true;
        }, delay);
      }
    };
  };

  const setAttributes = (el, options) =>
    Object.keys(options).forEach(attr => el.setAttribute(attr, options[attr]));

  const w = window;
  const d = document;
  const b = d.body;
  const x = w.innerWidth || e.clientWidth || b.clientWidth;
  const y = w.innerHeight || e.clientHeight || b.clientHeight;

  /* unecessary, but to have same object format, e.g. readability */
  const win = Object.create(null);
  win.y = y;

  const frame = d.querySelectorAll("iframe");

  /** may be over doing it here... test results */
  const preloadPath = () =>
    frame.forEach(item => {
      const source = item.getAttribute("data-src");
      const preloadLink = d.createElement("link");
      const head = d.getElementsByTagName("head")[0];

      setAttributes(preloadLink, {
        rel: "preload",
        as: "document",
        type: "text/html",
        crossorigin: "anonymous",
        href: source
      });

      head.insertBefore(preloadLink, head.firstChild);
    });

  const loadFrame = () =>
    frame.forEach(item => {
      /* only run if not src is present */
      if (!item.src) {
        const source = item.getAttribute("data-src"); // path
        const parent = item.parentElement; // wrapper
        const frameRect = parent.getBoundingClientRect(); // wrapper dimensions

        if (
          w.pageYOffset + win.y >= frameRect.y && // if frame top exceeds page bottom
          frameRect.y + frameRect.height >= w.pageYOffset // if frame bottom exceeds page top
        ) {
          item.src = source; // set path
          item.removeAttribute("data-src"); // remove placeholder attr
        }
      }
    });

  /** load on docReady */
  d.addEventListener("DOMContentLoaded", [preloadPath, loadFrame]);

  /** throttle on scroll */
  const t = throttle(loadFrame, 64);
  w.addEventListener("scroll", t);


texts:
Is this the correct way to block requests in Express?

app.js

app.use("/", indexRouter);

app.use(function(req, res, next) {
  next(createError(404));
});

app.use(function(err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  console.log(err);
  res.status(err.status || 500);
  res.json({ error: err.message });
});

controller

exports.fetch_seat = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ error: true, message: errors.array() });
  }

  Seat.getSeatByNumber(req.params.seatNumber, (err, seat) => {
    if (err) res.json(err);
    else res.json(seat);
  });
};

model

Seat.findSeat = function(key, value) {
  return new Promise((resolve, reject) => {
    const seat = file.find(r => r[key] === value);
    if (!seat) {
      reject({
        error: true,
        message: "Seat not found",
        status: 404
      });
    }
    resolve(seat);
  });
};

Seat.getSeatByNumber = function(seatNumber, result, next) {
  try {
    this.findSeat("seatNumber", seatNumber)
      .then(seat => {
        console.log(seat);
        if (seat !== undefined && Object.keys(seat).length > 0) {
          return result(null, seat);
        } else {
          return result({
            error: true,
            message: "Seat not found",
            status: 404
          });
        }
      })
      .catch(error => {
        console.log(error);
        console.log("1st catch");
        return result(error, null);
      });
  } catch (error) {
    console.log("outer catch");
    console.log(error);
    return result(error);
  }
};

I have changed the functions within my model to promises. do i need it to be promises from the controller?


texts: Refactoring Java class with lots of constants

texts:
class MyObject
{
    public static enum Type {A, B, C, D;}

    public static final int ID_MAIN = 1;
    public static final int ID_MAIN_UK = 2;
    public static final int ID_MAIN_US = 3;
    public static final int ID_SUB = 4;
    // lots more constants here

    public static final String DESCRIPTION_1 = "Desc Full Name";
    public static final String DESCRIPTION_2 = "Desc2 Full Name";
    // lots more constants here

    private int id;

    public MyObject(final int id)
    {
        this.id = id;
    }

    //simple getter
    public int getID() { return this.id;}

    // real responsibility of the class is in the following two methods
    public static String getDescription()
    {
         switch(id)
         {
              case MyObject.ID_MAIN:
              case MyObject.ID_MAIN_UK:
                  return MyObject.DESCRIPTION_1;
              case MyObject.ID_SUB:
                  return MyObject_Description_2;
              default:
                   // throw IllegalArgException
         }
    }

    public static Type getType(int id)
    {
         switch(id)
         {
             case MyObject.ID_MAIN:
             case MyObject.ID_SUB:
                 return Type.A;
             case MyObject.ID_MAIN_UK:
             case MyObject.ID_MAIN_US:
                 return Type.B;
             default:
                 return Type.Undefined;
         }
     }
 }

Basically, there is an ID that maps to both a description and a type. This ID is passed in during construction of the class and it should map to a set of constants already contained in the class. If the id is not part of the list of constants, an error is thrown when trying to get the description that maps to the id and an 'Unknown' type is return if the type is queried. The ID maps a description to a set of constants. The same ID maps to a certain Type (defined as an enum).

This code is pretty ugly because there are tons of constants defined at the top, which makes the switch statements pretty bloated. Is there a simple way to refactor this without changing the public interface? It seems trivially simple, but it seems pretty ugly no matter how you slice it. How can I simplify these mappings to make the code more concise?

I was thinking about representing the mappings in a text file and having a manager class that held simple containers in a hashmap. When the manager class is constructed, it would create the objects by reading the text file and map them to an ID. When the manager is queried with the ID, it would just call the corresponding get method, for instance:

class Manager
{
     private HashMap<int, MyObject> objectMap;

     public Manager() {} //construct the object map
     public String getDescription(int id) { return objectMap.get(id).getDescription();}
     public Type getType(int id) { return objectMap.get(id).getType();}
}

class DataContainer
{
     private String description;
     private Type type;

     public DataContainer(String desc, Type type) {//set mem vars}
     public String getDescription() //simple getter
     public Type getType() //simple getter
 }

But this solution seems too complicated. Is there a better solution, preferably one that would keep everything in one class?


texts: Sklearn custom transformer (label encoder and imputer)

texts:
I have a pandas.Dataframe with a single (new) record and the following function:

self.encoders # is a dict and stores a sklearn LabelEncoder() for each column
self.fillNewLabels # is a pd.Series and has an entry for each column with the most frequent element

def transform(self, data):
    for column, encoder in self.encoders.items():
        fittedLabels = encoder.classes_
        replacementForUnseen = self.fillNewLabels[column]
        data[column] = data[column].astype(str) # deliberately call str as found no better way to handle categoricals directly
        data.loc[~data[column].isin(fittedLabels), column] = str(replacementForUnseen)
        data.loc[:, column] = encoder.transform(data[column])
    return data

For around 100 columns this step takes around 3 seconds for a single row of new data. What can I do to speed it up?

edit

A nice picture from profiling results can be found here: http://imgur.com/a/K08GN


texts:
The find function is designed to start at the given node and return the index of the node with the value valueInput (indices start at 0). Return -1 if valueInput does not exist.
How can this code be improved, optimized and free of potential runtime errors?
Please note I am new to data structures and algorithms.

#include <iostream>

class Node {
    public:
        int value;
        Node* next = NULL;
};

void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node =
            (struct Node*) malloc(sizeof(struct Node));

    /* put in the data */
    new_node->value = new_data;

    /* link the old list off the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = new_node;
}

int find(struct Node *head, int n)
{
    int count = 1;

    //if count equal too n return node->data
    if(count == n)
    return head->value;

    //recursively decrease n and increase
    // head to next pointer
    return find(head->next, n-1);
}

int main()
{
    struct Node* head = NULL;

    push(&head, 1);
    push(&head, 4);
    push(&head, 1);
    push(&head, 12);
    push(&head, 1);

    printf("Element at index 3 is %d", find(head, 3));
    getchar();
    return 0;
}


texts: Arbitrary function redirection at runtime

texts:
This code is for my upcoming challenge on PPCG.  The key part of this challenge is supposed ability to overwrite functions that other people have written.  Overwriting functions will happen at runtime, and a particular function on a bot instance can be overwritten many times

For example, CodeBot A has a function sendMessage() which returns a message to send.  If CodeBot A were to overwrite CodeBot B's sendMessage(), then any time CodeBot B needed to send a message, CodeBot A's sendMessage() function would get called.

The CodeBot class:

package codebots.bot;

import codebots.gameobjects.*;

import java.util.List;

public abstract class CodeBot {

    private Bot underlyingBot;

    public final void setUnderlyingBot(Bot bot){
        this.underlyingBot = bot;
    }

    public abstract List<IPAddress> selectMessageRecipients();
    public abstract Message sendMessage();
    public abstract void processMessage(Message message);
    public abstract IPAddress selectAttackTarget();
    public abstract void readData(ReadonlyBot bot);
    public abstract FunctionType selectFunctionToReplace();
    public abstract FunctionType selectFunctionToBlock();
    public abstract String getFlag();

    protected final AddressBook getAddressBook(){
        return underlyingBot.getAddressBook();
    }

    protected final Log getLog(){
        return underlyingBot.getLog();
    }

    protected final Variables getVariables(){
        return underlyingBot.getVariables();
    }

}

The Bot class:

package codebots.bot;

import codebots.gameobjects.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class Bot {
    private final Map<FunctionType, CodeBot> functionOwners;
    private final AddressBook addressBook;
    private final Log log;
    private final Variables variables;

    public Bot(CodeBot parent){
        functionOwners = new HashMap<>();
        for (FunctionType type: FunctionType.values()){
            functionOwners.put(type, parent);
        }
        addressBook = new AddressBook();
        log = new Log();
        variables = new Variables();
    }

    private CodeBot getOwner(FunctionType type){
        CodeBot owner = functionOwners.get(type);
        owner.setUnderlyingBot(this);
        return owner;
    }

    public List<IPAddress> selectMessageRecipients(){
        return getOwner(FunctionType.SELECT_MESSAGE_RECIPIENTS).selectMessageRecipients();
    }
    public Message sendMessage(){
        return getOwner(FunctionType.SEND_MESSAGE).sendMessage();
    }
    public void processMessage(Message message){
        getOwner(FunctionType.PROCESS_MESSAGE).processMessage(message);
    }
    public IPAddress selectAttackTarget(){
        return getOwner(FunctionType.SELECT_ATTACK_TARGET).selectAttackTarget();
    }
    public void readData(ReadonlyBot bot){
        getOwner(FunctionType.READ_DATA).readData(bot);
    }
    public FunctionType selectFunctionToReplace(){
        return getOwner(FunctionType.SELECT_FUNCTION_TO_REPLACE).selectFunctionToReplace();
    }
    public FunctionType selectFunctionToBlock(){
        return getOwner(FunctionType.SELECT_FUNCTION_TO_BLOCK).selectFunctionToBlock();
    }
    public String getFlag(){
        return getOwner(FunctionType.GET_FLAG).getFlag();
    }

    public AddressBook getAddressBook(){
        return addressBook;
    }

    public Log getLog(){
        return log;
    }

    public Variables getVariables(){
        return variables;
    }

    public void replace(FunctionType type, CodeBot bot){
        functionOwners.put(type, bot);
    }

}

As you can see, there is a lot of duplicated code.  Bot contains a copy of a function in CodeBot, and simply selects the bot call the function on.

I'm looking for a better way to design my code, as well as general improvements.  I'm using Java 8, so any feature from Java 8 is allowed.


texts: Data analysis code (finds coincidences in three sets of data)

texts:
I've written the following data analysis code (using just a couple lines from CERN's ROOT data analysis framework). It's designed to find coincidences in three sets of data (timestamps from an experiment for a given year) by pairing up each timestamp in one dataset with the closest possible timestamp in both the second and third datasets, then sorting those pairings by maxval - minval, and keeping only the closest "unique" coincidences (no two coincidences may share a timestamp, and each coincidence is a triplet, with one timestamp contributed by each dataset). The code works perfectly, however it's a bit messy and could probably use some cleaning up. Perhaps there are some clever tricks for simplifying some of this that I'm unaware of as well. Please do be very critical, I appreciate the feedback.
My code:
int binary_search(const vector<double> &vec, const double key) {

    int high = vec.size();
    int low  = 0;
    unsigned int mid;

    while(low <= high){
        mid = low + (high-low)/2;

        if(vec[mid] == key) return mid;
        else if(vec[mid] < key)  low = mid + 1;
        else high = mid - 1;
    }

    return mid;

}

void binary(){

    ROOT::RDataFrame statn1("D", "./path/to/data");
    ROOT::RDataFrame statn2("D", "./path/to/data");
    ROOT::RDataFrame statn3("D", "./path/to/data");

    vector<double> vec2, vec3;
    statn2.Foreach([&](double tstamp){vec2.push_back(tstamp);},{"UNIX"});
    statn3.Foreach([&](double tstamp){vec3.push_back(tstamp);},{"UNIX"});

    vector<vector<double> > coincidences;
    statn1.Foreach([&](double tstamp){},

        int res_i = binary_search(vec2, tstamp);

        double p = dabs(tstamp-vec2[res_i]);
        double q = dabs(tstamp-vec2[res_i+1]);
        double r = dabs(tstamp-vec2[res_i-1]);

        if(r<q && r<p) --res_i;
        else if(q<r && q<p) ++res_i;

        int res_j = binary_search(vec3, tstamp);

        p = dabs(tstamp-vec3[res_j]);
        q = dabs(tstamp-vec3[res_j+1]);
        r = dabs(tstamp-vec3[res_j-1]);

        if(r<q && r<p) --res_j;
        else if(q<r && q<p) ++res_j;

        double first = tstamp-vec2[res_i];
        double second = tstamp-vec3[res_j];
        double third = vec2[res_i] - vec3[res_j];
        double fourth = std::min(std::min(first, second), third);

        coincidences.push_back({tstamp, vec2[res_i], vec3[res_j], first, second, third, fourth});

    {"UNIX"});

    std::sort(coincidences.begin(), coincidences.end(),
        [](const vector<double>& A, const vector<double>& B){
            return A[6] < B[6];
    });

        std::set<double> cache;

    for(auto pair : coincidences){

        if(cache.find(pair[1]) == cache.end() && cache.find(pair[2]) == cache.end())    {
            std::cout << "Coincidence found!\n";
            cache.insert(pair[1]); cache.insert(pair[2]);
        }
    }
}

EDIT: CERN's ROOT framework can be found at https://root.cern.ch


texts: Adding and removing PHP parameters on click

texts:
I'm trying to optimize this repetitive piece of code. I think I need to set subsection href as a variable and then figure out a way to merge the functions?

$(document).ready(function () {
    $('#alphabetical').click(function () {
        $('.subsection').attr('href', function () {
            return this.href + '&sort=alphabetical';
        });
    });
    $('#chronological').click(function () {
        $('.subsection').attr('href', function () {
            return this.href.replace('&sort=alphabetical', '');
        });
    });
    $('#builtfilter').click(function () {
        $('.subsection').attr('href', function () {
            return this.href + '&status=built';
        });
    });
    $('#allfilter').click(function () {
        $('.subsection').attr('href', function () {
            return this.href.replace('&status=built', '');
        });
    });
});


texts: Haskell Parsec parser of Verilog-style number literals

texts:
I've set myself the task to write a function that parses Verilog-style number literals. In Verilog, numbers are written like this:
8'b10101100, 16'hffff, '789, 32'd0, 12'o7, etc.

The syntax is:

<size>'<radix>value

where <...> denotes an optional field, and

size is the binary representation length of the number (in bits). The default is 32.
radix is 'b' or 'B' for binary, 'o' or 'O' for octal, 'd' or 'D' for decimal, 'h' or 'H' for hexadecimal. The default is 'd'.
value is the appropriate number representation for the given radix.

I'm new to Haskell, so I really would appreciate a critical appraisal of the following implementation. I think it is correct. Is it also 'good' Haskell/Parsec? Can it be done better, i.e. more concisely, more clearly, using more appropriate idioms?

import System.IO
import System.Environment
import Data.Either (either)
import Data.Either.Extra (fromRight)
import Data.Char (digitToInt, toLower)
import Numeric (readInt, readOct, readHex)
import Text.Parsec.Combinator
import Text.ParserCombinators.Parsec
import Text.Parsec.Char (hexDigit, octDigit)

integerLog :: Integer -> Integer
integerLog = floor . logBase 2.0 . fromIntegral

-- |numberSize calculates the length (in bits) of the binary representation of Integer
numberSize :: Integer -> Integer
numberSize = (1+) . integerLog

-- |The type Number has a val (Integer value) and a len (binary representation length).
data Number = Number {val::Integer, len:: Integer} deriving Show

-- |makeNumber is a safe constructor of an Either String Number
makeNumber :: Integer -> Integer -> (Either String Number)
makeNumber v l
  | v < 0     = Left "makeNumber: Negative values not allowed in Number"
  | size > l  = Left $ "makeNumber: Value " ++ show v ++ " is "
    ++ show size ++ " bits long, should be at most " ++ show l ++ " bits"
  | size <= 0 = Left $ "makeNumber: Size can't be negative or zero"
  | otherwise = Right $ Number v l
  where size = numberSize v

-- |readBin is not defined in Numeric (readInt, etc., are)
readBin = readInt 2 (`elem` "01") digitToInt

-- conversions String -> Number
hexToInteger x = fst $ readHex x !! 0 :: Integer
octToInteger x = fst $ readOct x !! 0 :: Integer
binToInteger x = fst $ readBin x !! 0 :: Integer

-- |binDigit is not in Text.Parsec.Char (hexDigit, octDigit are)
binDigit :: CharParser st Char
binDigit = oneOf "01"

-- |parse Verilog-style numbers <size>'<radix>value
parseNumber :: Parser Number
parseNumber = do
  size <- option "32" (many1 digit)
  char '\''
  radix <- option 'd' $ oneOf "hH" <|> oneOf "dD" <|> oneOf "oO" <|> oneOf "bB"
  let (thisDigit, convert_digits) =
        case toLower radix of
          'h' -> (hexDigit, hexToInteger)
          'o' -> (octDigit, octToInteger)
          'd' -> (digit   , read)
          'b' -> (binDigit, binToInteger)
          _  ->  error "parseNumber: Internal error"
  val <- many1 thisDigit
  let size' = read size :: Integer
      val' = convert_digits val :: Integer
      num = makeNumber val' size'
    in
    either fail return num

main :: IO ()
main = do
  args <- getArgs
  let results = map (parse parseNumber "parseNumber") args
  mapM_ print results

Note: In true Verilog numbers have the format <size>'<signed><radix>value but in my application negative numbers are not allowed, hence the omission of <signed>.


texts:
This code checks if the given integer is a palindrome. If it is, prints given integer is a palindrome else, not a palindrome:

from collections import deque
def polindrome(input):
 d = deque()
 d.extendleft(str(input))
 result = int(''.join(d))
 if input == result :
     return input , 'is a polindrome'
 else :
     return (input , 'is not a polindrome')


texts: When values are pasted into a bigger range, the values should be repeated as needed to fill the range

texts:
I am currently working on a project, and I just wrote a piece of it that requires a lot of array manipulation.  Given a text input I want to expand it to fill the number of rows and columns I have.  I worked out a solution, but I am concerned that I am creating too many arrays in my solution.  I am looking for pointers on how I can make this code more efficient.  I always get really lost when trying to refactor things like this.

function fillIn(data,numRows,numCols) {
  // First, split the data by newlines and tabs into an array of arrays.
  var dataArr = data.split('\n').map(function(row) { return row.split('\t'); });

  function fillRows(pRows){
    return [].concat.apply([], new Array(Math.floor(numRows / pRows.length)).fill(pRows));
  }

  function fillCols(pRows) {
    for (var i = 0; i < pRows.length; i++) {
      pRows[i] = [].concat.apply([], new Array(Math.floor(numCols / pRows[i].length)).fill(pRows[i]));
    }
    return pRows;
  }

  function fillSelection(pRows) {
    if (numRows > pRows.length) {
      pRows = fillRows(pRows);
    }
    if (numCols > pRows[0].length) {
      pRows = fillCols(pRows);
    }
    return pRows;
  }

  dataArr = fillSelection(dataArr);

  return dataArr;
}

console.log(fillIn('foo',2,2)); //[['foo','foo'],['foo','foo']]
console.log(fillIn('foo\tbar',4,2)); //[['foo','bar'],['foo', 'bar'],['foo','bar'],['foo','bar']]
console.log(fillIn('foo\nbar',2,4)); // [['foo','foo','foo','foo'],['bar','bar','bar','bar']]


texts: Recursive find function in JavaScript / jQuery

texts:
I wrote the following code as a way of plucking data from a n-depth JavaScript object.
It works a charm and even appends the parents of the the found item.

I was just wondering if you guys had any ideas on making it better.

//#region function recursiveFind
function recursiveFind(data, key, childKey, match, result) {

    ///<summary>Returns JS obj and its parents based on a data set, key and match.</summary>
    ///<param name="data" type="Object" optional="false">the data object you want to find within</param>
    ///<param name="key" type="String" optional="false">the key for the data you want to match against eg. 'id' will look for data.id</param>
    ///<param name="childKey" type="String" optional="false">the data object you want to find within</param>
    ///<param name="match" type="Any" optional="false">the value you wish to search for</param>
    ///<returns type="Object">returns the found result</returns>

    var parents = [];
    var depth = 0;
    var recurse = function (data, key, childKey, match, result) {
        // Build Parents
        depth++;

        // Check this Object
        if (data[key] === match) {
            result = data;
        }
        else if (depth === 1) {
            parents.push(data);

        }

        // If not found check children
        if (result === undefined) {
            if (data[childKey]) {
                $.each(data[childKey], function (k, v) {
                    if (v[key] === match) {
                        result = v;
                        return false;
                    } else {
                        result = recurse(v, key, childKey, match, result);
                        if (result) {
                            parents.push(v);
                            return false;
                        }
                    }
                });
            }
        }

        // Set parents object into the result
        if (result) {
            result.parents = $.extend([], parents);
        }

        // Clean up parents object
        depth--;
        if (depth === 0) {
            parents.length = 0;
        }
        return result;
    };
    return recurse(data, key, childKey, match, result);
}
//#endregion


texts: Check existence of user identification number

texts:
I was tasked with writing a python script to check if a passed ID number exists within a file. The file I was give contains roughly 25,000 unique ID numbers. An ID number is a unique 9 digit number.

I have a couple specific things for you to comment on if you decide to review this:

As it stands, I convert the user_id passed in the id_exists to a str. I do this because I need the ID number to be the same type when I read the ID's from the file. Is there an easier way to accomplish this?
This is my first time using a PEP 484 type hint, Generator. Am I using it correctly?
This is also my first time utilizing a generator in this fashion. I used a generator here because instead of loading the entire file into memory, storing in a list, then iterating over the list, I can read each line and can exit early if an ID is found. Is it good that I'm using it in this way, or is there an easier way to do this?
Using a helper function is a new concept to me. Am I utilizing this helper function in the most pythonic way?

Of course, any constructive criticism beyond these points is welcome. Thanks in advance.

"""
Ensures id number matches any within the ID file.

An ID number is a unique 9 digit number.
"""

import random
import time

from typing import Union, Generator

def id_exists(user_id: Union[int, str]) -> bool:
    """
    Determines if the passed ID exists within the ID file. The
    ID passed must be of length 9 exactly, and only contain numbers.

    :param Union[int, str] user_id: User ID to check for existence

    :return bool: True if ID exists in file, False otherwise
    """

    # Generator[yield_type, send_type, return_type] #
    def get_ids() -> Generator[str, None, None]:
        """
        Helper function for `id_exists`.

        Yields each line in the ID file.

        :return Generator[str, None, None]: Lines in ID file.
        """

        with open("ids.txt", "r") as file:
            for line in file:
                yield line.strip()

    # Convert user_id to <class 'str'> if not already #
    if type(user_id) == int:
        user_id = str(user_id)

    # Ensure user_id matches specifications #
    if len(user_id) != 9 or not user_id.isdigit():
        raise ValueError("ID should be 9 characters long and all digits.")

    # Check ID against file and return result #
    return any(user_id == stored_id for stored_id in get_ids())


texts:
I am trying to write a text adventure as my first Python project. For this segment, I wanted a random enemy (part of a class with its own attributes) to appear and then enter a turn based battle with the player until either the enemies health is 0 or the player's health is 0. The player can use one of three moves to attack the enemy. The difficulty to beat the enemy is based on its strength, defence and health attribute.

Feel free to pull it apart and mention improvements or constructive criticisms that you may come up with.

import random, time

player_health = 100

class Enemy:

    def __init__(self, name, strength, defense, health):
        self.name = name
        self.strength = strength
        self.defense = defense
        self.health = health

    def attack_enemy(self):
        time.sleep(1)
        print ("what move would you like to make? (punch, kick or headbutt?")
        print("")
        answer = input()

        if answer == "punch":
            self.health = self.health -     (random.randint(1,100)/(random.uniform(0,1)*     self.defense))
            self.health = int(self.health)
        elif answer == "kick":
            self.health = self.health - (random.randint(1,100)/(random.uniform(0,1)* self.defense))
            self.health = int(self.health)
        elif answer == "headbutt":
            self.health = self.health -   (random.randint(1,100)/(random.uniform(0,1)* self.defense))
            self.health = int(self.health)
        else:
            print("you stumble...")

        time.sleep(1)

        print (self.name + "'s health is now: " + str(int(self.health)))
        print("")

        return int(self.health)

    def enemy_attack(self):
        global player_health
        time.sleep(1)
        print ("The enemy " + self.name + " " + "attacks...")
        print("")
        player_health = player_health - (self.strength * random.uniform(0.1, 1.4))
        player_health = int(player_health)
        time.sleep(1)
        print ("Your health is now " + str(int(player_health)))
        print ("")
        return int(player_health)

    def battle_script(self):
        global player_health
        print ("An enemy " + self.name + " appears...")
        print ("")
        time.sleep(1)
        while player_health > 0 and self.health > 0:
            self.attack_enemy()
            if self.health <=0:
               break
            self.enemy_attack()
            if player_health <=0:
                break
        if self.health <= 0:
            time.sleep(1)
            print ("You have killed the " + self.name)

        if player_health <= 0:
            time.sleep(1)
            print ("Sorry, you are dead")

enemies = [Enemy("Boar", 10, 5, 100), Enemy("Wolf", 20, 10, 100), Enemy("Lion", 30, 20, 100), Enemy ("Dragon", 40, 30, 130)]

random_enemy = random.choice(enemies)
random_enemy.battle_script()


texts: Bash - Passing arguments with "$@" to either 'sudo su' or 'sh'

texts:
I have a server where shell commands to the supervisor-service must be executed by the specific user lx. I have written a bash function that does exactly that.

function supervisor {
if [ `id -nu` != lx ]; then
    sudo su - lx -c "supervisor \"\$@\"" -- supervisor "$@"
else
    sh -s "$@" <<EOF
supervisor "$@"
EOF
fi
}

It works, but it's doesn't look clean and I'm not really comfortable with half the things I'm using here.

How can that function be written in a less convoluted way?


texts: Inserting a Node in a singly linked list

texts:
I'm currently writing an "insert" function for a linked list. The code works but I would like to know if there is any way I can improve this code and at the same time covering all the "special" cases.`

private class Node{
    Node next;
    int data;

    public Node(int data, Node next){
        this.data = data;
        this.next = next;
    }

    public Node(){
        this.next = null;
        this.data = 0;
    }}`

public void insert(int data) {
    if(first == null || first.item != data){
        first = new Node(data, first);
    }
    else{
        Node x = first;
        while(x.next != null && x.next.item != data){
            x.next = new Node(data, x.next);
        }
        x = x.next;
    }
}


texts:
Question (SAD Queries on CodeChef)

  The Summed Absolute Difference (SAD) of two arrays. Given arrays
  (1-indexed) \$P\$ and \$Q\$ of lengths \$p\$ and \$q\$.

  Given a collection of \$n\$ arrays \$A_1, \ldots, A_n\$, report \$SAD(A_i, A_j)\$ for
  several queries \$(i, j)\$.

  The first line of input contains a single positive integer \$n\$.

  Each of the next \$n\$ lines starts with a positive integer \$s_i\$, the size
  of \$A_i\$,

  followed by \$s_i\$ space-separated integers \$A_{i,1}, \ldots, A_{i,s_i}\$ which denotes
  the array \$A_i\$. The next line of input consists of a single positive
  integer \$M\$.

  Each of the next \$M\$ lines consists of 2 positive integers \$a\$ and \$b\$ which lie
  between \$1\$ and \$n\$ (inclusive), specifying the indices of the arrays for
  which the SAD value must be reported.

Example

  Input:

4
4 0 3 1 -2
2 0 4
2 2 4
4 4 -3 -4 4

3
3 4
4 2
1 4

  Output:

30
30
60

Explanation

  Query 1: The arrays in question are A3 = [2, 4] and A4 = [4, -3, -4,
  4].

  $$SAD(A3, A4)$$
  $$= |2 - 4| + | 2 - (-3) | + |2 - (-4) | + | 2 - 4 |$$
  $$+ | 4 - 4 | + | 4 - (-3) | + | 4 - (-4) | + | 4 - 4 |$$
                         $$= 2 + 5 + 6 + 2 + 0 + 7 + 8 + 0$$
                         $$= 30$$

Constraints

\$1 \leq n, M \leq 10^5\$

\$1 \leq s_1 + ... + s_n \leq 10^5\$

\$-10^9 \leq A_{i,j} \leq 10^9\$

\$1 \leq i, j \leq n\$ in each of the queries

My approach

#include <iostream>
#include<cmath>

using namespace std;

int main()
{

    long long  int n,x,a,b,sum=0,s=1;
    cin>>n;
    long long int *size=new long long int[n];
    long long int **arr=new long long int*[n];
    for(int i=1;i<=n;i++)
    {
        arr[i]=new long long int[n];
    }
    for(int i=1;i<=n;i++)
    {
        cin>>size[s];

        for(int j=0;j<size[s];j++)
        {
            cin>>arr[i][j];
        }
        s++;
    }
    long long int m;
    cin>>m;
    while(m--)
    {
        cin>>a>>b;
        for(int i=1;i<=size[a];i++)
        {
            for(int j=0;j<size[b];j++)
                sum=sum+fabs(arr[a][i]-arr[b][j]);
        }
        cout<<sum;
        cout<<endl;
        sum=0;
    }
    return 0;
}

How can i reduce the time complexity and space complexity of this program.

I have taken a 1D dynamic array to store the size of arrays and a 2D dynamic array to store the index and the array value for that index


texts:
I'm parsing a JSON data send from server to new JSON Object using JavaScript.

JSON data from server will be in this format

SERVER JSON:

{
  'serverFromDate': '15/07/1988',
  'serverToDate': 123,
  'hdnUserName' : 'User',
  'hdnRole' :'Admin',
  'hdncmbRoles':[{'text':'Admin', 'hdnvalue':'admin'},
           {'text':'Client', 'hdnvalue':'client'}]
}

and I'm converting this JSON to below format

CLIENT JSON:

{
      'clientFromDate': '15/07/1988',
      'clientToDate': 123,
      'txtUserName' : 'User',
      'txtRole' :'Admin',
      'cmbRoles':[{'text':'Admin', 'value':'admin'},
               {'text':'Client', 'value':'client'}]
    }

My Conversion Util is like this...I will check for every server key is present in the Server JSON, if it there then i will added it to the client JSON.

var j_Utils = {
  getValueOf: function(json) {
    return function(key) {
      return json[key];
    }
  },

  hasKeyOf: function(json) {
    return function(key) {
      return json.hasOwnProperty(key);
    }
  }
};

function getMappedData(data) {
  var jObj = {},
    getValueOf = j_Utils.getValueOf(data).bind(j_Utils),
    hasKeyOf = j_Utils.hasKeyOf(data).bind(j_Utils);

  if (hasKeyOf('serverFromDate'))
    jObj['clientFromDate'] = getValueOf('serverFromDate');
  if (hasKeyOf('serverToDate'))
    jObj['clientToDate'] = getValueOf('serverToDate');

  //..........................................
  // TOO MANY DATA OR MAY NOT HAVE ALL TIME
  //..........................................

  return jObj;
};

var clientData = getMappedData({
  'serverFromDate': '15/07/1988',
  'serverToDate': 123
});
console.table(clientData);

Some time these data will be huge, so I'm supposed to write a lengthy javascript code which does the same operation from mapping one value to other. So I want to simplify this JavaScript code in a more efficient and simpler way. The keys from server and client are different (yeah there may be some prefix and suffix or some keys are entirely different), is there any possible ways to simplify these steps in ES6/ES5?


texts:
I'm new to JavaScript (and programming) and taking a course. I was tasked with creating a bubble sort on any array using JavaScript. Of course, since this is an algorithm challenge, no sort method allowed. After I wrote this, I looked around at other implementations of bubble sort. I only found one that used a similar algorithm. Most set a variable to true or false to exit the loop.

I'm curious if the way I've written this is valid, efficient, and even a bubble sort at all -- since I don't loop through the entire array at any point (unless edge case is the array is already sorted). I know there are tons of bubble sort questions out there, but I couldn't find one exactly like this.

//Bubble Sort algorithm practice for JavaScript class

arrayX = [1,9,-1,5,10,23,-2,7,4,5,1];

for (i = 0; i <= arrayX.length-1; i++)
  {
    if (arrayX[i] > arrayX[i+1])
      {
        temp = arrayX[i+1];
        arrayX[i+1] = arrayX[i];
        arrayX[i] = temp;
        i = i-2;
      }
  }
console.log(arrayX);


texts:
The code I want to refactor look as following:

public bool CheckPay(Int64 orderID)
{
    vpc_OrderInfo = orderID;
    RequestParams =
        string.Format(
            "vpc_Version={0}&vpc_Command={1}&vpc_AccessCode={2}&vpc_MerchTxnRef={3}&vpc_Merchant={4}&vpc_User={5}&vpc_Password={6}",
            vpc_Version, vpc_Command, vpc_AccessCode, vpc_MerchTxnRef, vpc_Merchant, vpc_User, vpc_Password);

    string[] response = SendRequest(vpc_VirtualPaymentClientURL, RequestParams).Split('&');
    bool ResponseCode = false;
    bool exist = false;
    Total = 0;
    TransactionDate = DateTime.Now;
    TransactionId = CardNo = vpc_Message = string.Empty;

    var query = new StringBuilder();
    try
    {
        foreach (string s in response)
        {
            if (string.IsNullOrWhiteSpace(s))
                throw new Exception(string.Format("Message='{0}' ", s));

            if (s.IndexOf("vpc_SecureHash") == -1)
            {
                string vpcMessage = s.Split('=')[1];
                query.AppendFormat("{0}-{1}|", s.Split('=')[0], vpcMessage);

                if (s.IndexOf("vpc_DRExists") > -1)
                {
                    exist = vpcMessage == "Y";
                }
                if (s.IndexOf("vpc_TxnResponseCode") > -1)
                {
                    ResponseCode = vpcMessage == "0";
                }
                if (s.IndexOf("vpc_Amount") > -1)
                {
                    Total =
                        double.Parse(vpcMessage.Length > 2
                                            ? vpcMessage.Insert(vpcMessage.Length - 2, ",")
                                            : "0," + vpcMessage);
                }
                if (s.IndexOf("vpc_BatchNo") > -1)
                {
                    TransactionDate = DateTime.Parse(vpcMessage.Insert(6, "-").Insert(4, "-"));
                }
                if (s.IndexOf("vpc_TransactionNo") > -1)
                {
                    TransactionId = vpcMessage;
                }
                if (s.IndexOf("vpc_CardNum") > -1)
                {
                    CardNo = vpcMessage;
                }
                if (s.IndexOf("vpc_Message") > -1)
                {
                    vpc_Message = vpcMessage;
                }
            }

            serviceLog.InfoFormat("Message: " + s);
        }
    }
    catch (Exception ex)
    {
        serviceLog.Error("fatal error", ex);
    }
    return exist && ResponseCode;
}

I'm not sure if I can get rid of these multiple if statements.

The "exist" and "ResponseCode" are boolean values and I need them to return bool type from method. Other values are class properties.


texts: Appending a codepoint to an UTF8 std::string using icu4c

texts:
My code is
void utf8_append(UChar32 cp, std::string& str) {
    size_t offset = str.size();
    str.resize(offset + U8_LENGTH(cp));
    auto ptr = reinterpret_cast<uint8_t*>(&str[0]);
    U8_APPEND_UNSAFE(ptr, offset, static_cast<uint32_t>(cp));
}

This works but seems ugly. Maybe I am overlooking a simpler approach?
Relevant documentation: https://unicode-org.github.io/icu/userguide/strings/utf-8.html and https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/utf8_8h.html.


texts: Is This a Sufficient Demonstration of the Effects of Exception Handling

texts:
We have some developers in house that believe it is best practice to use exception handing as flow control, as well as, thinking that catching and re-throwing exceptions is effective error handling.

In an effort to educated, I attempted to come up with a simple sample to demonstrate to them the negative effects of doing so.  The code sample below is what I came up with.  It consistently demonstrates that there is a penalty for gratuitous usage of try/catch blocks; but the effect is much greater than I had anticipated.  I can't help but think I've done something very wrong in this sample.  I would appreciate any suggestions of improvement.

In this sample, I am comparing the cost of catching and re-throwing an exception with just allowing the exception to bubble up.  I needed to execute the methods in parallel to avoid waiting days for the code to execute on high values.

    static void Main(string[] args)
    {
        TimeSpan ts1 = new TimeSpan();
        TimeSpan ts2 = new TimeSpan();
        List<Task> tasks = new List<Task>();

        for (int i = 0; i < 100; ++i)
        {
            Task a = new Task(() =>
            {
                Stopwatch watch1 = new Stopwatch();
                watch1.Start();
                function1(function2);
                watch1.Stop();
                ts1 += watch1.Elapsed;
            });
            a.Start();
            tasks.Add(a);

            Task b = new Task(() =>
            {
                Stopwatch watch2 = new Stopwatch();
                watch2.Start();
                function1(function3);
                watch2.Stop();
                ts2 += watch2.Elapsed;
            });
            b.Start();
            tasks.Add(b);
        }

        while (!tasks.All(t => t.IsCompleted)) ;
        Console.WriteLine("Watch1: " + ts1);
        Console.WriteLine("Watch2: " + ts2);
        Console.ReadLine();
    }

    static void function1(Action action)
    {
        try
        {
            action();
        }
        catch
        {
        }
    }

    static void function2()
    {
        try
        {
            int.Parse(null);
        }
        catch
        {
            throw;
        }
    }

    static void function3()
    {
        int.Parse(null);
    }


texts: Assign value of nested array as array key

texts:
I have a multi dimensional array like this:

[0] =>
    ['batch_id'] => '1'
    ['some_stuff'] => 'values'
    [0] =>
        ['unit_id'] => '12'
        ['some_stuff'] => 'values'
    [1] =>
        ['unit_id'] => '41'
        ['some_stuff'] => 'values'

This comes from an external API, so I have no control over the original formatting of the array.

What would be the preferred (least overhead) way to take all the 'unit_id' and 'batch_id' fields, remove them from the group of values about the item, and assign that value to the item's key?

What I've tried (and works, but I want to find something cleaner):

public function fixArray($batches) {
    $batchfix = array();
    foreach($batches as $batch) {
        $unitfix = $array;
        $batch_temp = $batch;
        array_shift(array_shift($batch_temp)); // Get rid of id details
        foreach($batch_temp as $unit)
            $unittemp = $unit;
            array_shift($unittemp);
            $unitfix[$unit['unit_id']] = $unittemp;
        $batchfix[$batch['batch_id']] = $batch;
    }
    return $batchfix;
}

Any suggestions?