texts: Export running data from Garmin API to CSV

texts:
I'm interested in getting better. Current script does the job but I'm really unsure regarding

Quality of overall structure & comments
Error handling
Possibility the add testing (what and how should I test?)

Here is the script:

# This script runs through your Garmin Connect activities (New->Old) and saves them as CSV
import json
import csv
import requests
from http.cookies import SimpleCookie

# To get started open garmin connect in Google Chrome, log in and grab the id of your latest activity as in https://connect.garmin.com/modern/activity/<START_ID>
START_ID = 2399797019 # Paste it here
END_ID = 0 # Id to stop at if you've run this script before, leave 0 otherwise

# Then, press F12, click on "Network", press F5, scroll to the very first element, it will have your <START_ID> as name. Click on it and copy the whole value of "Cookie" in Headers > Request Headers
RAW_DATA = 'SESSION=63497e03-bcbc-4...'

cookie = SimpleCookie()
cookie.load(RAW_DATA)
cookies = {}
for key, morsel in cookie.items():
    cookies[key] = morsel.value

# Crawl politely, leave a way for them to contact you
headers = {
    'User-Agent': 'Some hobbyist runner and pythonista trying to bulk extract CSVs, get in touch if you have an issue with this',
    'From': 'you@domain.com'
}

def get_previous_activity_id(activity_id):
    url = 'https://connect.garmin.com/modern/proxy/activity-service/activity/{}/relative'.format(activity_id)
    r = requests.get(url, headers=headers, cookies=cookies)
    try:
        previous_activity_id =  r.json()["previousActivityId"]
        return(previous_activity_id)
    except KeyError:
        print('Issue getting the key ["previousActivityId"] for activity with id {}'.format(activity_id))
        return KeyError

def export_activity_laps(activity_id):
    url = 'https://connect.garmin.com/modern/proxy/download-service/export/csv/activity/{}'.format(activity_id)
    r = requests.get(url, headers=headers, cookies=cookies)
    try:
        with open('data/activities/{}.csv'.format(activity_id), 'w') as temp_file:
            temp_file.writelines(r.content.decode('utf-8'))
        return True
    except Exception as e:
        print('Issue writing the csv file for activity {}'.format(activity_id))
        return e

def export(activity_id):
    previous_id = get_previous_activity_id(activity_id)
    export_activity_laps(activity_id)
    if previous_id and previous_id != END_ID :
        export(previous_id)
    else:
        print("Finished exporting")

def main():
    export(START_ID)

if __name__ == '__main__':
    main()


texts: Iterator based version of quicksort, allowing user defined pivot-selection-strategy

texts:
I have implemented a iterator based version of Quicksort, which allows the user to define and pass his own pivot-selection-strategy:

template<typename It>
It Partition(It begin,It end,It pivot)
{
    std::swap(*begin, *pivot);
    pivot = begin;
    It i{ begin }, j = std::next(begin, 1);
    for(;j != end; j++)
    {
        if(*j < *pivot)
            std::swap(*j, *++i);
    }
    std::swap(*pivot, *i);
    return i;
}

template<typename It, typename Pivot>
void Quicksort(It begin, It end, Pivot&& GetPivot)
{
    if (std::distance(begin, end) == 0)
        return;
    It pivot{ GetPivot(begin,end) };
    It elementAtCorrectPosition = Partition(begin, end,pivot);
    Quicksort(begin, elementAtCorrectPosition, GetPivot);
    Quicksort(std::next(elementAtCorrectPosition, 1), end, GetPivot);
}

The algorithm can be used in the following way:

std::vector<int> v{  3, 8, 2, 5, 1, 4, 7, 6 };
auto quickSort = v;
auto stdSort = v;
Quicksort(quickSort.begin(),
          quickSort.end(),
          [](auto a, auto b) { return a; });
std::sort(stdSort.begin(), stdSort.end());
Assert::IsTrue(quickSort == stdSort);

Where the lambda expression

 [](auto a, auto b) { return a; }

is just to demonstrate how a pivot selection strategy can be passed to the algorithm.

Any suggestions that lead to a more robust, concise and readable code are welcome.

Special thanks to @ratchet freak, who discovered an emberassing bug:

The initial implementation only worked for the special case, where the first element is selected as pivot. See above for the corrected version.


texts: Assigning JSON object values to objects in a KnockoutJS setup

texts:
I am using this for in loop to loop through a JSON object and to assign the JSON object's value to my own object in a KnockoutJS setup.

The JSON object looks like this:

[
    {
    categoryId: "013",
    categoryName: "Toys",
    id: 2328,
    name: "Megatron",
    summary: "",
    price: 120,
    extraInfo: {
        minAge: 3,
        maxAge: 7
    }
    },
    {
    categoryId: "014",
    categoryName: "Apparels",
    id: 2327,
    name: "Tank Top",
    summary: "",
    price: 70,
    extraInfo: {
        minAge: 5
        maxAge: null
    }
    }
]

And the for in loop goes inside the JSON object and then assign the JSON object's values to an existing object:

   function Item(data){
       var self = this;
       for(i in data){
       if(typeof data[i]==='object'){
           var dataObj = data[i];
           for(j in dataObj){
           self[j] = dataObj[j];
           }
       }
       else{
           self[i] = data[i];
       }
       }
   }

As you can see, I'm basically copying over the key values of the JSON object to an existing object, and if the value is an object, I copy the values too and assign them to the object.

This is already an improvement from an older version, where I basically copy over the keys manually, like:

self.someKey = data.someKey;

However, I can't help but feel this can be improved, particularly the part where I was checking for an object within the JSON object. I came from a web designer background and often find myself coding code that's not rigorous enough and breaks in cases I don't foresee. I hope doing this regularly will improve my code with time.


texts:
I'd want to see if is possible to optimize performance even further of the following generate color method.

package generacolorrgb;

import java.util.Random;

public class GeneracolorRGB {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Random r = new Random();
        for (int i = 0; i < 100; i++) {
            System.out.println(generateColor(r));
        }

    }

    private static String generateColor(Random r) {
        StringBuilder color = new StringBuilder(Integer.toHexString(r
                .nextInt(16777215)));
        while (color.length() < 6) {
            color.append("0");
        }

        return color.append("#").reverse().toString();

    }

}

Average time it takes on my machine: 1650704.333 ns


texts: Decode Argon2 parameters and handling decode errors

texts:
I am writing a function to decode Argon2 hashed string to extract parameters. I need to handle many decode errors, and handle those errors lead to write many repeating if err == nil check code. Is there a better way to do this kind of check?

The encodedHash string follows the format, separated by $

"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s"

so an example string looks like

$argon2id$v=19$m=65536,t=3,p=4$ruDgwQK24h0wGXI87+lVWAbHmgNidUNPVSTdSloOlfM$py20HR7L4K6LllGsZNDbkrbh89x2tIF8JCIG0DAaoi8

What the decode function do is convert the string into this struct

type Argon2Params struct {
    Memory     uint32
    Time       uint32
    Threads    uint8
    SaltLength uint32
    KeyLength  uint32
}

Here is the decode function, I need to do a serious check during the decoding process. Every filed need to be checked to make sure no error rises.

func decodeHash(encodedHash string) (p *Params, salt, hash []byte, err error) {
    fileds := strings.Split(encodedHash, "$")
    if len(fileds) != 6 {
        return nil, nil, nil, errors.New("The encoded hash is not in the correct format")
    }

    var version int
// error check
    if _, err = fmt.Sscanf(fileds[2], "v=%d", &version); err != nil {
        return
    }
// error check
    if version != argon2.Version {
        return nil, nil, nil, errors.New("Argon2 version not match")
    }

    p = &Params{}
    _, err = fmt.Sscanf(fileds[3], "m=%d,t=%d,p=%d", &p.memory, &p.time, &p.threads)
// error check
    if err != nil {
        return
    }

    salt, p.saltLength, err = decodeBase64WithLength(fileds[4])
// error check
    if err != nil {
        return
    }
// error check
    hash, p.keyLength, err = decodeBase64WithLength(fileds[5])
    return
}
// a helper function
func decodeBase64WithLength(encodeString string) (str []byte, length uint32, err error) {
    str, err = base64.RawStdEncoding.DecodeString(encodeString)
    length = uint32(len(str))
    return
}


texts: How can this Encryption Class be more secure?

texts:
How secure is this encryption?
Secondly, is there something I could do to "turn it up a notch" and make it 'more' secure?

Imports System.Security.Cryptography

Public Class clsCrypt
Private TripleDES As New TripleDESCryptoServiceProvider

'create and return the key and initialization vector hash
Private Function TruncateHash(ByVal key As String, ByVal length As Integer) As Byte()

    Dim sha1 As New SHA1CryptoServiceProvider

    ' Hash the key.
    Dim keyBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(key)
    Dim hash() As Byte = sha1.ComputeHash(keyBytes)

    ' Truncate or pad the hash.
    ReDim Preserve hash(length - 1)
    Return hash

End Function

'initialize the class
Sub New(ByVal key As String)

    ' Initialize the crypto provider.
    TripleDES.Key = TruncateHash(key, TripleDES.KeySize \ 8)
    TripleDES.IV = TruncateHash("", TripleDES.BlockSize \ 8)

End Sub

'encrypt the passed text
Public Function EncryptData(ByVal plaintext As String) As String

    ' Convert the plaintext string to a byte array.
    Dim plaintextBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(plaintext)

    ' Create the stream.
    Dim ms As New System.IO.MemoryStream

    ' Create the encoder to write to the stream.
    Dim encStream As New CryptoStream(ms, TripleDES.CreateEncryptor(),
                                      System.Security.Cryptography.CryptoStreamMode.Write)

    ' Use the crypto stream to write the byte array to the stream.
    encStream.Write(plaintextBytes, 0, plaintextBytes.Length)
    encStream.FlushFinalBlock()

    ' Convert the encrypted stream to a printable string.
    Return Convert.ToBase64String(ms.ToArray)

End Function

'decrypt passed text
Public Function DecryptData(ByVal encryptedtext As String) As String

    ' Convert the encrypted text string to a byte array.
    Dim encryptedBytes() As Byte = Convert.FromBase64String(encryptedtext)

    ' Create the stream.
    Dim ms As New System.IO.MemoryStream

    ' Create the decoder to write to the stream.
    Dim decStream As New CryptoStream(ms, TripleDES.CreateDecryptor(),
                                      System.Security.Cryptography.CryptoStreamMode.Write)

    ' Use the crypto stream to write the byte array to the stream.
    decStream.Write(encryptedBytes, 0, encryptedBytes.Length)
    decStream.FlushFinalBlock()

    ' Convert the plaintext stream to a string.
    Return System.Text.Encoding.Unicode.GetString(ms.ToArray)

End Function
End Class

Lastly, would this encryption class function the same if I passed in a different key in different Subs? Example:

Private Sub EmployeeFrm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

    Dim strKey As String = "Key1" 'encryption Key
    Dim clsEncrypt As clsCrypt         'Assigns a variable to clsCrypt class
    clsEncrypt = New clsCrypt(strKey)   ' creates a new isntance of the clsCrypt class

And also:

Private Sub InsertBtn_Click(sender As System.Object, e As System.EventArgs) Handles InsertBtn.Click

    Dim strKey As String = "Strong3rKeY!" 'encryption Key
    Dim clsEncrypt As clsCrypt         'Assigns a variable to clsCrypt class
    clsEncrypt = New clsCrypt(strKey)   ' creates a new isntance of the clsCrypt class

Both are in the same form, just during different events.

Is this even a good way to utilize encryption? I am using it to encrypt specific strings and insert them into the database.


texts:
This function takes a string from an HTTP POST or GET string, finds the specified variable, and allocates memory for the result and puts it in a string. The destination is given as an address of an empty pointer.

username=johndoe&password=password123

Would produce:

password123

when finding variable password.

void httpString(char **dest, char *input, const char *find) {
char *start;
char *o_input = input;
const char *o_find = find;
size_t length = 0;
size_t i = 0;
while (*input) {
    if (*input == '&' || input == o_input) {
        if (*input == '&') {
            input++;
            if (*input == 0) {
                return;
            }
        }
        while (*input == *find) {
            if (*input == 0 || *find == 0) {
                return;
            }
            input++;
            find++;
            if (*input == '=' && *find == 0) {
                input++;
                if (*input == 0) {
                    return;
                }
                start = input;
                while (*input != '&' && *input) {
                    input++;
                    length++;
                }
                *dest = malloc(length + 1);
                input = start;
                while (*input != '&' && *input) {
                    (*dest)[i] = *input;
                    input++;
                    i++;
                }
                (*dest)[i] = 0;
                return;
            }
        }
    }
    find = o_find;
    input++;
}
}

Any feedback related to how this function can be improved would be greatly appreciated. I am worried about potential edge cases where a memory access violation could occur.


texts: Bash script to capture error message and change exit status

texts:
I'm working with the Perforce command line client.                                                                                I want to check for the case when a user tries to unshelve an unsubmitted changelist that has a valid changelist number, but has no shelved files. In this case the p4 unshelve command will still have an exit status of 0, but it will print an error message to stderr.

I'm fairly inexperienced with bash scripts, but I did run my code through shellcheck.net to find any obvious errors.

In a lot of places I think this script could be more concise or robust, but I don't know exactly what I should be changing.

Any help is greatly appreciated.

#!/bin/bash

p4 unshelve -f -s "$1"  &> tmp_file

# capture the exit status of the call to p4 unshelve
if [ $? -eq 0 ]
then
    flag0=0
else
    flag0=1
fi

std_err_output="$(cat tmp_file)"
error_message="No such file(s)."

# even if the exit status is 0, still check that the error message was not thrown.
if [ "$std_err_output" = "$error_message" ]
then
   flag1=1
else
   flag1=0
fi

rm tmp_file

exit_status="expr $flag0 | $flag1"

exit "$($exit_status)"


texts: How to add forms dynamically in javascript?

texts:
Example speaks for it self:

function writeSpecialTabContentForTtm(){
        document.write('
');
        document.write('<form  id="ttmsetpointrun" action="" style="text-align:right">');
        document.write('<input style="float:bottom;" type="submit" value="Move to Set Point" />');
        document.write('</form>');
        document.write('
');

How this should be done? There is a form that is chosen by user. To be precise, user choses a tab and when creating a tab the above function is called. This is something that is changed frequently, so it would be nice to write it in a separate file.

edit:

so, in my case it would be:

var newdiv = document.createElement('div');
newdiv.style = "float:right;width:250px;min-height:200px;display:block;border-width: 1px 1px 1px";
document.body.appendChild(newdiv);

var newform = document.createElement('form');
newform.id = "ttmsetpointrun";
newform.action="";
newform.style="text-align:right";
newdiv.appendChild(newform);

var newinput = document.createElement('input');
newinput.style = "float:bottom;";
newinput.type = "submit";
newinput.value = "Move to Set Point";
newform.appendChild(newinput);


texts:
I know that this is very very basic, but now I am starting from group up after getting frustrated with my coding practices and knowledge of standard idioms out there and elegant way of coding corner cases. The problem is to insert into tail of a linked list.

void insertattail (struct node *head, int data)
{
  //First construct the node in newp
  struct node *newp;
  struct node *p;
  newp = malloc (sizeof (struct node));
  newp -> data = data;
  newp -> next = NULL;

  // Standard name for node pointers only used for traversal? p? q? tmp?
  // if more than 1 kind of nodes?
  // Then what about temp pointers for swapping etc but not exactly for traversal?

  if (head == NULL)  // is there more elegant way of dealing with this? any idiom?
  {
    head = newp;
    return;
  }

  for (p=head; p->next != NULL; p++)
    ;
  p->next=newp;
}


texts:
This program takes a symbolic link as argument, and swaps the link with its referent.  For example, given a -> b, the result will be b -> a.  It creates a relative link if the original was relative, otherwise an absolute link.
I wanted to ensure that this is an all-or-nothing command, so if it fails, it leaves everything as it was.  This isn't completely achievable in the face of concurrent modification, but it does make a best-effort attempt to undo changes if it was unsuccessful.  I also use rm with --no-clobber and ln without --force to avoid data loss regardless.
#!/bin/bash

set -eu -o pipefail

die()
{
    printf '%q: ' "$1"; shift
    printf '%s\n' "$@"
    exit 1
}

usage()
{
    cat <<END
Usage: $0 FILE
       FILE  a symlink
The symlink will be swapped with its target
END
}

undo=""

add_undo()
{
    # prepend a command to the undo list
    local command
    printf -v command '%q ' "$@"
    undo="$command"$'\n'"$undo"
}

restore()
{
    # execute the undo commands
    eval "$undo" ||
        die "$0" "Failed to restore to initial state!"
}

trap restore ERR;

if [ $# -ne 1 ]
then
    usage >&2
    exit 1
fi
case "$1" in
    -h|--help)
        usage; exit ;;
esac

test -L "$1" || die "$1" 'not a symlink'
test -e "$1" || die "$1" 'dangling symlink'

target=$(readlink -e "$1")
lnopts=(--symbolic)
case "$(readlink "$1")" in
    /*)
        # make $1 absolute, without following the link itself
        set -- "$(realpath --no-symlinks "$1")"
        ;;
    *)
        lnopts+=(--relative)
        ;;
esac

# Create temporary working directory alongside the link
linkdir="$(mktemp --directory --tmpdir="$(dirname "$1")")"
test -d "$linkdir"
add_undo rm -r "$linkdir"

# Move the symlink into tempdir
mv -T "$1" "$linkdir/link"
add_undo mv -T "$linkdir/link" "$1"

# Create a new symlink next to the target
newlink="$(mktemp --dry-run --tmpdir="$(dirname "$target")")"
test -n "$newlink"
ln "${lnopts[@]}" "$1" "$newlink"
add_undo rm "$newlink"

# Move the target to its new location
# This is the riskiest and most expensive thing to restore, so do it last
mv -T --no-clobber "$target" "$1"
add_undo mv "$1" "$target"

# Move the new link into position left by target
mv -T --no-clobber "$newlink" "$target"

# Succeeded, so remove the temporary directory
undo=""
rm -r "$linkdir"


texts:
Please comment on time and space efficiency.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JobInterviewTests
{
    [TestClass]
    public class MergeSortUnitTest
    {
        [TestMethod]
        public void MergeTest()
        {
            int[] array = new int[] { 5, 10, 1, 4, 2, 3, 7 };
            SortHalf(array, 0, array.Length-1);

            int[] expectedOutput = new[] { 1, 2, 3, 4, 5, 7, 10 };
            CollectionAssert.AreEqual(expectedOutput, array);
        }
        private void SortHalf(int[] array, int startIndex, int endIndex)
        {
            int mid;
            if (endIndex > startIndex)
            {
                mid = (endIndex + startIndex) / 2;
                SortHalf(array, startIndex, mid);
                SortHalf(array, mid + 1, endIndex);
                DoMerge(array, startIndex,mid+1, endIndex);
            }
        }

        private void DoMerge(int[] array, int startIndex, int mid, int endIndex)
        {
            int[] temp = new int[array.Length];
            int i, start, numOfElements, position;
            start = mid - 1;
            position = startIndex;
            numOfElements = endIndex - startIndex + 1;
            while((startIndex <= start)&& (mid <= endIndex))
            {
                if(array[startIndex] <= array[mid])
                {
                    temp[position++] = array[startIndex++];
                }
                else
                {
                    temp[position++] = array[mid++];
                }
            }
            while(startIndex <= start)
            {
                temp[position++] = array[startIndex++];
            }

            while(mid <= endIndex)
            {
                temp[position++] = array[mid++];
            }

            for (i = 0; i < numOfElements; i++)
            {
                array[endIndex] = temp[endIndex];
                endIndex--;
            }

        }
    }
}


texts: How to properly add some new arguments in a subclass?

texts:
I am trying to subclass list in order to implement a callback function that would be called whenever a list item is being set.

I have this:

class CustomList(list):
    def __init__(self, *args, **kwargs):
        self.setitem_callback = kwargs['setitem_callback']
        del kwargs['setitem_callback']
        super().__init__(*args, **kwargs)

    def __setitem__(self, *args, **kwargs):
        super().__setitem__(*args, **kwargs)
        self.setitem_callback()

def callback():
    print('callback')

 l = ['a', 'b', 'c']
 custom_list = CustomList(l, setitem_callback=callback)
 custom_list[1] = 'd' # prints 'callback'

It works as expected, but I am concerned about having to do del kwargs['setitem_callback'] in order for the superclass' __init__ to work. Is it a bad practice? Are there any other ways to achieve the same?


texts:
I am having performence issues with image processing task (flash light effect). I used c#, and used couple references (LockBits Method, Extension). The program has bad frame rates.

Edited the code, improvments were made but still doesn't match up to my expectations.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ImagePro
{
    public partial class Form1 : Form
    {
        Bitmap Dog;
        Rectangle rect;

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Dog = new Bitmap(@"D:\Programs\VS 2013\Projectss\ImageProcessing\ImageProcessing\dog.jpg");
            rect = new Rectangle(0, 0, Dog.Width, Dog.Height);
            this.Width = Dog.Width;
            this.Height = Dog.Height;
            timer1.Interval = 100;
            timer1.Start();
            this.DoubleBuffered = true;
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Bitmap tempImg = new Bitmap(Dog);
            BitmapData imgRawData = tempImg.LockBits(rect, ImageLockMode.ReadWrite, tempImg.PixelFormat);
            IntPtr arrStart = imgRawData.Scan0;

            int size = imgRawData.Stride * tempImg.Height;
            byte[] rgbValues = new byte[size];

            System.Runtime.InteropServices.Marshal.Copy(arrStart, rgbValues, 0, size);
            var absPos = PointToClient(Cursor.Position);
            for (int x = 0; x < tempImg.Width; x++)
            {
                for (int y = 0; y < tempImg.Height; y++)
                {
                    double distence = GetDistance(absPos.X, absPos.Y, x, y); //Distence from pixel to cursor
                    int pixelIndex = x * 4 + y * imgRawData.Stride;

                        for (int i = 0; i < 3; i++)
                        {
                            if (distence > rgbValues[pixelIndex + i])
                            {
                                rgbValues[pixelIndex + i] = 0; //Sets pixel to black
                            }
                            else
                            {
                                rgbValues[pixelIndex + i] -= (byte)distence; //Reduce pixel brightness
                            }
                        }
                        //rgbValues[pixelIndex];          //blue
                        //rgbValues[pixelIndex + 1];     //green
                        //rgbValues[pixelIndex + 2];    //red
                        //rgbValues[pixelIndex + 3];   // alpha
                }
            }
            System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, arrStart, size);
            tempImg.UnlockBits(imgRawData);
            e.Graphics.DrawImage(tempImg,0,0);
        }
        private static double GetDistance(double x1, double y1, double x2, double y2)
        {
            return Math.Sqrt(Math.Pow((x2 - x1), 2) + Math.Pow((y2 - y1), 2));
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Invalidate();
        }
    }
}


texts:
I wrote a Hangman game to try out some of the new features in C++11. I'm pretty new to C++, and I would like some good advice on how I can improve this code (in terms of conventions, bad/good practices, ...):

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stdexcept>
#include <random>
#include <algorithm>

const unsigned initial_number_of_lives = 5;

// Returns a random word from the given words file.
std::string pick_word(const std::string& words_filename) {
  std::vector<std::string> words;
  std::ifstream words_file(words_filename.c_str());
  if (!words_file) {
    throw std::runtime_error("Couldn't open file.");
  }
  std::string word;
  do {
    std::getline(words_file, word);
    words.push_back(word);
  } while (!words_file.eof());

  std::uniform_int_distribution<uintmax_t> random_distribution(0, words.size() - 1);
  std::mt19937 random_engine(static_cast<std::mt19937::result_type>(std::time(nullptr)));
  uintmax_t word_index = random_distribution(random_engine);
  return words[word_index];
}

int main(int argc, const char *argv[]) {
  if (argc != 2) {
    std::cerr << "usage: " << argv[0] << " <words-file>\n";
    return 1;
  }

  std::string word;
  try {
    word = pick_word(argv[1]);
  } catch(...) {
    std::cerr << argv[0] << ": couldn't open words file: " << argv[1] << '\n';
    return 1;
  }

#if DEBUG
  std::cout << "(debug) word: " << word << "\n\n";
#endif

  std::cout << "Welcome to hangman!"; // Newline in main loop below.

  unsigned lives = initial_number_of_lives;
  std::vector<char> guessed_letters;
  for (;;) {
    bool won = true;
    for (char &letter : word) {
      if (std::find(guessed_letters.begin(),
                    guessed_letters.end(),
                    letter) == guessed_letters.end()) {
        won = false;
      }
    }
    if (won) {
      std::cout << "You won the game!!1\n";
      return 0;
    }

    std::cout << "\n\nLives left: " << lives;

    std::cout << "\nAlready guessed: ";
    for (char &letter : guessed_letters) {
      std::cout << letter << ' ';
    }

    std::cout << '\n';
    for (char &letter : word) {
      if (std::find(guessed_letters.begin(),
                    guessed_letters.end(),
                    letter) != guessed_letters.end()) {
        std::cout << letter;
      } else {
        std::cout << '_';
      }
    }

    char guess;
    std::cout << "\nEnter a letter: ";
    std::cin >> guess;
    guess = std::tolower(guess);
    // Don't allow player to enter the same letter twice.
    if (std::find(guessed_letters.begin(),
                  guessed_letters.end(),
                  guess) != guessed_letters.end()) {
      std::cout << "You have already guessed that letter!\n";
      continue;
    }

    // Don't allow player to enter anything but letters.
    if (!std::isalpha(guess)) {
      std::cout << "That is not a letter!\n";
      continue;
    }

    guessed_letters.push_back(guess);

    bool word_contains_letter = false;
    for (char &letter : word) {
      if (letter == guess) {
        word_contains_letter = true;
        break;
      }
    }

    if (word_contains_letter) continue;
    --lives;
    if (lives == 0) {
      std::cout << "Game over! The right word was: " << word << '\n';
      break;
    }
  }

  return 0;
}


texts:
I have a sample code and some question.

Simple type property

member val CabinetNetworkState : uint8 = 0uy with get, set
member this.CabinetNetworkStateAsValues : (CabinetNetworkStateHosts * uint8) array =
        let cabinetNetworkStateMap = new ResizeArray<(CabinetNetworkStateHosts * uint8)> ()

        let extNetworkState = (this.CabinetNetworkState >>> 0) &&& uint8 2
        match Enum.IsDefined(typeof<CabinetNetworkState>, extNetworkState) with
        | true ->  cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.EXT, extNetworkState)
        | false -> cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.EXT, 0uy)

        let canNetworkState = (this.CabinetNetworkState >>> 3) &&& uint8 2
        match Enum.IsDefined(typeof<CabinetNetworkState>, canNetworkState) with
        | true ->  cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, canNetworkState)
        | false -> cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, 0uy)

        let net1NetworkState = (this.CabinetNetworkState >>> 5) &&& uint8 2
        match Enum.IsDefined(typeof<CabinetNetworkState>, net1NetworkState) with
        | true ->  cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.NET1, net1NetworkState)
        | false -> cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.NET1, 0uy)

        let net2NetworkState = (this.CabinetNetworkState >>> 7) &&& uint8 2
        match Enum.IsDefined(typeof<CabinetNetworkState>, net2NetworkState) with
        | true ->  cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, net2NetworkState)
        | false -> cabinetNetworkStateMap.Add (CabinetNetworkStateHosts.CAN, 0uy)

        cabinetNetworkStateMap.ToArray()

What it does it converts a value into array of bit value and enum that value represents
My question is should I use Map instead of tuple array, or it does not matter?


texts: Returning consonants of a plane's starting and ending points

texts:
I am just starting to program in C#, so I am a beginner.  I've been practicing some coding and I would like your opinion on something.

I have a flying direction for a plane, e.g. ''London - Berlin'' (direction). I want to create a method that will return the first and the last consonant of the plane's starting point (London), and the first and the last consonant of the plane's destination (Berlin).

I have written this, so I would like to know if it's ok, or if you have some suggestions:

public class Flight
{
    private string direction;

    public Flight(string direction)
    {
        this.direction = direction;
    }

    public string Consonants()
    {
        string starting = direction.Split('-')[0];
        string destination = direction.Split('-')[1];

        string startConsonants = starting.ToUpper().Replace("A", "").Replace("E", "").Replace("I", "").Replace("O", "").Replace("U", "");
        string destConsonants = destination.ToUpper().Replace("A", "").Replace("E", "").Replace("I", "").Replace("O", "").Replace("U", "");

        return string.Format("{0}{1}-{2}{3}", startConsonants[0].ToString(), startConsonants[startConsonants.Length-1].ToString(), destConsonants[0].ToString(), destConsonants[destConsonants.Length-1].ToString());
    }
}


texts:
I made this implementation of a stack in Swift that stores its elements as a linked list. It seems to work perfectly well, but I’m wondering how I can improve it to follow the best practices of the language.

struct StackList<T> : CustomStringConvertible {
    private var first: StackNode? = nil // The topmost node in the stack

    /// Add a new element to the top of the stack
    /// - parameter newElement: the new element to be added
    mutating func push(_ newElement: T) {
        let newElement = StackNode(newElement);
        newElement.next = first;
        first = newElement;
    }

    /// Remove and return the topmost element from the stack
    /// - returns: Optional containing the removed element, or nil if the stack was empty
    mutating func pop() -> T? {
        guard let first = first else { return nil }

        let poppedElement = first.element
        self.first = first.next
        return poppedElement
    }

    /// The number of elements in the stack
    var size: Int {
        var count = 0
        var current = first

        // Traverse the list
        while current != nil {
            count += 1
            current = current!.next
        }
        return count
    }

    /// Textual representation of the stack
    var description: String {
        var output = ""

        // Traverse the list
        var currentNode = first;
        while let thisNode = currentNode {
            if output != "" { output += ", " }  // Add commas between elements
            output += String(describing: thisNode.element)

            currentNode = thisNode.next
        }

        return "[\(output)]"
    }

    private class StackNode {
        var next: StackNode? = nil
        var element: T

        init(_ element: T) {
            self.element = element
        }
    }
}


texts: Validating credit card numbers - Haskell

texts:
I'm learning Haskell and doing the exercises from http://www.seas.upenn.edu/~cis194/spring13/lectures.html.

This is my code to validate credit cards as described on http://www.seas.upenn.edu/~cis194/spring13/hw/01-intro.pdf.

I know very little about it and welcome any advice on how to improve.

Here's my solution:

toDigits :: Integer -> [Integer]
toDigits x
  | x <= 0 = []
  | otherwise = toDigits (div x 10) ++ [mod x 10]

toDigitsRev :: Integer -> [Integer]
toDigitsRev x
  | x <= 0 = []
  | otherwise = (mod x 10) : toDigitsRev (div x 10)

doEveryTwo' :: (t -> t) -> [t] -> [t]
doEveryTwo' _ [] = []
doEveryTwo' f (x:xs) = x : doEveryTwo f xs

doEveryTwo :: (t -> t) -> [t] -> [t]
doEveryTwo _ [] = []
doEveryTwo f (x:xs) = f x : doEveryTwo' f xs

doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther [] = []
doubleEveryOther xs
  | length xs `mod` 2 == 0 = doEveryTwo (*2) xs
  | otherwise = head xs : doEveryTwo (*2) (tail xs)

sumDigits :: [Integer] -> Integer
sumDigits [] = 0
sumDigits (x:xs) = sum (toDigits x) + sumDigits xs

validate :: Integer -> Bool
validate x
  | x < 10 = False
  | otherwise = sumDigits (doubleEveryOther (toDigits x)) `mod` 10 == 0


texts:
My application will accept textarea content that is submitted by a user, and i would like some people to review my code to make sure there is no security vulnerability such as XSS.

My mySQL column that will save this information is a column of type TEXT and is not required and nullable.

When storing the data to database, my script is doing the following:

// to avoid inserting html tags in the database
$input = str_replace(["<", ">"],"", $_POST['userinput'])

// to avoid saving problematic characters such as quotes
$cleanInput = htmlentities(input , ENT_QUOTES)

// store the content
$addPostStmt = $conn -> prepare("
  INSERT INTO posts(description) VALUES ( ?)
");

$addPostStmt -> bind_param("s", $cleanInput);
$addPostStmtExecute = $addPostStmt -> execute();

When presenting the data to the user, the script is doing the following:

<?php echo htmlspecialchars(html_entity_decode($post['description']), ENT_SUBSTITUTE); ?>


texts:
For fun, I implemented a version of Python's range function in JavaScript. I found that underscore.js implements it as well, but with notable differences. I'm hoping others can comment on the differences. I assume that underscore's implementation is, if not more optimal, at least more idiomatic. And I'd like to build my intuition for the best way to do things in JavaScript.

My version:

var range = function () {
    var results = [];

    // Allow comparison to be variable
    var lessThan = function (a, b) {return (a < b); };
    var greaterThan = function (a, b) {return (a > b); };

    if (arguments.length === 1) {
        var start = 0;
        var stop = arguments[0];
        var step = 1;
        var comparisonTest = lessThan;
    } else {
        var start = arguments[0];
        var stop = arguments[1];
        var step = arguments[2] || 1;
        var comparisonTest = ((step > 0)? lessThan : greaterThan);
    };

    for (var i = start; comparisonTest(i, stop) ; i += step) {
        results.push(i);
    };

    return results;
};

And underscore's implementation:

_.range = function(start, stop, step) {
    if (arguments.length <= 1) {
      stop = start || 0;
      start = 0;
    }
    step = arguments[2] || 1;

    var length = Math.max(Math.ceil((stop - start) / step), 0);
    var idx = 0;
    var range = new Array(length);

    while(idx < length) {
      range[idx++] = start;
      start += step;
    }

    return range;
  };

I see that not specifying function parameters - which made it easier to deal with variable lengths of arguments, ended up being more verbose than the way underscore handles it. Is there any other reason to always specify parameters?

And how about the actual building up of the range - underscore declares an Array constructor with length. Is that necessary?

Any insight or comments is appreciated!


texts: Extracting address information from non-formatted text

texts:
I'm pretty new to large projects, and usually my code is neat and manageable. But now that I'm about a month deep, things are starting to seem sloppy (or at least not aesthetically pleasing).

Are there any good methods/things I should keep in mind when designing a function that is compact and neat?

Function is question: 'postal', 'streettypecheck', and 'namecheck' are regex

function addresscheck(serverpackage) {
    var i;
    var streetnumber = [];
    var postalcode = [];
    var potentialname = [];
    var streettype = [];
    var highlightdata = serverpackage.split(' ');
    for (i = 0; i <= highlightdata.length; i++) {
        if(!isNaN(highlightdata[i])) {
            streetnumber.push(highlightdata[i]);
        } else if (postalcheck.test(highlightdata[i])) {
            if (highlightdata[i].indexOf('-') !== -1 || highlightdata[i].indexOf(" ") !== -1 && highlightdata[i].length == 7) {
                postalcode.push(highlightdata[i]);
            } else if (highlightdata[i].indexOf('-') == 1 || highlightdata[i].indexOf(' ') && highlightdata[i].length == 6) {
                postalcode.push(highlightdata[i]);
            }
        } else if (streettypecheck.test(highlightdata[i])) {
            streettype.push(highlightdata[i]);
        } else if (namecheck.test(highlightdata[i])) {
            potentialname.push(highlightdata[i]);
        }
    }
    var addressinfo={
        postalcode: postalcode,
        streetnumber: streetnumber,
        streettype: streettype,
        potentialname: potentialname
    }
    return addressinfo;
}

Consider that all text is non formatted.

Sample data1: Street st jksh7dyasf B7Z-8U0 aaa

Sample data2: 166623gggdgdgdgdf 123 88f8f88d88dydydy B7Z-8U0 Street st 8888 aaaa


texts:
I would love it if someone could give me some suggestions for these 2 graph search functions. I am new to scala and would love to get some insight into making these more idiomatic.

  type Vertex=Int
  type Graph=Map[Vertex,List[Vertex]]
  val g: Graph=Map(1 -> List(2,4), 2-> List(1,3), 3-> List(2,4), 4-> List(1,3))
 //example graph meant to represent
 //  1---2
 //  |   |
 //  4---3

//I want this to return results in the different layers that it finds them (hence the list of list of vertex)
def BFS(start: Vertex, g: Graph): List[List[Vertex]]={
  val visited=List(start)
  val result=List(List(start))

  def BFS0(elems: List[Vertex],result: List[List[Vertex]], visited: List[Vertex]): List[List[Vertex]]={
    val newNeighbors=elems.flatMap(g(_)).filterNot(visited.contains).distinct
    if(newNeighbors.isEmpty) result
    else BFS0(newNeighbors, newNeighbors :: result, visited ++ newNeighbors)
    }

  BFS0(List(start),result,visited).reverse
   }

//I would really appreciate some input on DFS, I have the feeling there is a way to do this sans var.

 def DFS(start: Vertex, g: Graph): List[Vertex]={
    var visited=List(start)
    var result=List(start)

  def DFS0(start: Vertex): Unit={
     for(n<-g(start); if !visited.contains(n)){
       visited=n :: visited
       result=n :: result
       DFS0(n)
  }}
   DFS0(start)
   result.reverse
}

//some examples
scala> BFS(1,g)
res84: List[List[Vertex]] = List(List(1), List(2, 4), List(3))
scala> BFS(2,g)
res85: List[List[Vertex]] = List(List(2), List(1, 3), List(4))
scala> DFS(1,g)
res86: List[Vertex] = List(1, 2, 3, 4)
scala> DFS(3,g)
res87: List[Vertex] = List(3, 2, 1, 4)


texts:
I have following code that is used of one time skipping some functionality(actually do something only one time until SkipSomeStuff is true):

private bool _skipSomeStuff;
public bool SkipSomeStuff
{
  set
  {
    _skipSomeStuff = value;
  }
  get
  {
    if (_skipSomeStuff)
    {
        _skipSomeStuff = false;
        return true;
    }
    return false;
  }
}

Is such construction ok to use, or I should change it with something?


texts: Comparing columns from two CSV files - follow-up

texts:
This is the second part of a question, you can find the first part here:

Comparing columns from two CSV files

I've made some changes to the script and here is what it looks like now:

import csv, sys

def get_column(columns, name):
    count = 0
    for column in columns:
        if column != name:
            count += 1
        else:
            return(count)

def set_up_file(file, variable):
    columns = next(file)
    siren_pos = get_column(columns, 'SIREN')
    nic_pos = get_column(columns, 'NIC')
    variable_pos = get_column(columns, variable)
    return(siren_pos, nic_pos, variable_pos)

def test_variable(variable):
    with open('source.csv', 'r') as source:
        source_r = csv.reader(source, delimiter=';')
        sir_s, nic_s, comp_s = set_up_file(source_r, variable)
        line_s = next(source_r)
        with open('tested.csv', 'r') as tested:
            tested_r = csv.reader(tested, delimiter=';')
            sir_t, nic_t, comp_t = set_up_file(tested_r, variable)
            size = sum(1 for line in tested_r)
            tested.seek(0, 0)
            line_t = next(tested_r)
            line_t = next(tested_r)
            correct = 0
            try:
                while True:
                    if(line_s[sir_s] == line_t[sir_t]
                    and line_s[nic_s] == line_t[nic_t]):
                        if(line_s[comp_s] == line_t[comp_t]):
                            correct += 1
                        line_t = next(tested_r)
                        line_s = next(source_r)
                    elif(int(line_s[sir_s]) > int(line_t[sir_t])):
                        line_t = next(tested_r)
                    elif(int(line_s[sir_s]) < int(line_t[sir_t])):
                        line_s = next(source_r)
                    else:
                        if(int(line_s[nic_s]) > int(line_t[nic_t])):
                            line_t = next(tested_r)
                        else:
                            line_s = next(source_r)
            except StopIteration:
                return(correct / size * 100)

def main():
    with open('tested.csv', 'r') as file:
        file_r = csv.reader(file, delimiter=';')
        columns = next(file_r)
        found = test_variable('SIREN')
        for column in columns:
            print(column, '%.2f' % (test_variable(column) / found * 100))

if(__name__ == "__main__"):
    main()

There are no real performance issue in the new version but I feel like it could still be improved greatly.

Also, would it be possible to reduce the size of the test_variable function? I thought about cutting it right before the try statement but I'll end up passing about 7 parameters which is not really a clean solution in my opinion.


texts: Plot on a 2D grid a spherically symmetric function

texts:
I am trying to compute a spherically symmetric function on a 2D grid. The simple solution that I came up with is the following:

Grid_side = 10
N_pix = 100

function = lambda r : 1.0 / r**2.0

grid_x = np.linspace(-Grid_side, Grid_side, N_pix)
grid_y = np.linspace(-Grid_side, Grid_side, N_pix)

SphericallySymmetric_function_GRID = np.zeros((N_pix, N_pix))

for i in range(N_pix):

        for j in range(N_pix):

            SphericallySymmetric_function_GRID[i,j] = function(np.sqrt(grid_x[i]**2.0 + grid_y[j]**2.0))

I was wondering if there is a better way to do the following, taking advantage of Numpy.


texts:
I am trying to solve Euler project problem 277 using python 3.8. First, I will show my program and than ask specific questions for enhancements.
The problem is a modified version of Collatz sequence. The general rule of the new one is:

\$ a_{n+1} = \, \,\, \frac {a_n} 3 \quad\$  if \$ a_n \$  is
divisible by 3. We shall denote this as a large downward step, "D".

\$ a_{n+1} = \frac {4 a_n+2} 3 \, \, \$ if \$ a_n \$   divided by 3
gives  a remainder of \$ 1 \$ . We shall denote this as an upward
step, "U".

\$ a_{n+1} = \frac {2 a_n -1} 3 \, \, \$ if \$ a_n \$   divided by 3
gives a remainder of \$ 2 \$ . We shall denote this as a small
downward step, "d".

For instance if \$ a_1=231\$ , then the sequence \$ \{a_n\}=\{231,77,51,17,11,7,10,14,9,3,1\} \$ corresponds to the steps "DdDddUUdDD".
The problem asks What is the smallest \$ a_1 > 10^{15}\$ that begins with the sequence "UDDDUdddDDUDDddDdDddDDUDDdUUDd"?
My code:
def modifCollatz(x, seq, num):
   if num == 0:
       return seq

   if x % 3 == 0:
       num -= 1
       x = x / 3
       seq.append("D")
       return modifCollatz(x, seq, num)

   elif x % 3 == 1:
       num -= 1
       x = (4 * x + 2) / 3
       seq.append("U")
       return modifCollatz(x, seq, num)

   else:
       x = (2 * x - 1) / 3
       num -= 1
       seq.append("d")
       return modifCollatz(x, seq, num)

wordList = []
for i in "UDDDUdddDDUDDddDdDddDDUDDdUUDd":
   wordList.append(i)

n = 10 ** 15
while True:
   if modifCollatz(n, [], 30)[0:30] == wordList:
       print(n)
       break
   else:
       n += 3

That works. I have tested using the example given in problem 277.

I am aware that it's using brute force and don't know what can be done to improve efficiency. I was just able to think of adding solely finding the first 30 elements of each number and incrementing by 3 n += 3, which are probably the easiest ones. What can be done additionally?


texts: Finding the longest substring in common with two large strings

texts:
I want to build a function which finds the longest substring that is common between two large strings. I want to do this using the first two functions.
I'm running it on very large strings (containing more than million characters) and it's taking a lot of time. How can I optimize the function findlongest?

def hash_sequence(string, k):

    dictionary={}
    for i in range(len(string)-(k-1)):
        sequence = string[i:i+k]
        dictionary.setdefault(sequence,[]).append(i)
    return dictionary

def intersects(string1, string2, k): #what if k=0?
    dictionary = hash_sequence(string1, k)

    for i in range(len(string2)-1): #O(n) for sybstring in string

        if string2[i:i+k] in dictionary: #O(n
            return string2[i:i+k]
    return None

def findlongest(string1,string2):
    if intersects(string1,string2,1)==None:
        return None
    for i in range(2,min(len(string1),len(string2))):

        if intersects(string1,string2,i)==None:
            return intersects(string1,string2,i-1),len(intersects(string1,string2,i-1))


texts:
A few weeks back I wrote a class to help serialize/deserialize objects file.  The file format requested was json, then compressed.  After some coding/testing I settled on this design:

class StoreObjects<T>
{
    public IEnumerable<T> LoadObjects()
    {
        List<T> loadObjectList = new List<T>();

        using (Stream stream = new FileStream("fullpathtofile", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            var js = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };

            using (GZipStream gs = new GZipStream(stream, CompressionMode.Decompress))
            {
                do
                {
                    try
                    {
                        var bfs = binaryFormatter.Deserialize(gs);
                        T storeObject = js.Deserialize<T>(bfs as string);
                        loadObjectList.Add(storeObject);
                    }
                    catch (SerializationException se)
                    {
                        //see msdn.microsoft.com/b85344hz.aspx
                        if (se.Message.Contains("Decimal"))
                            throw;
                        //else
                        break;
                    }

                } while (gs != null);
            }
        }

        return loadObjectList;
    }

    public bool SaveObjects(List<T> storedObjects)
    {
        try
        {
            using (FileStream compressedFileStream = File.Create("fullpathtofile"))
            {
                using (GZipStream coStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    var serializer = new JavaScriptSerializer() { MaxJsonLength = Int32.MaxValue };

                    for (int i = 0; i < storedObjects.Count; i++)
                    {
                        var dump = serializer.Serialize(storedObjects[i]);
                        binaryFormatter.Serialize(compressedFileStream, dump);
                    }
                }
            }
            return true;
        }
        catch (Exception exception)
        {
            //swallow exception on purpose, log error message

        }
        return false;
    }

}

2 design decisions I'm not proud of:

During research, we found that if we passed a very large List of objects, the serialize/deserialize would leak memory.  So I settled on a generic class, that you have to pass in a List<T> of the generic to SaveObjects and get back an IEnumerable<T> SaveObjects.  As long as your type isn't a very large list, you don't leak memory.  BTW, the leak happened when I used json.net also.
In LoadObjects the deserialization stops via an exception check.  Because of the nature of deserialize (typically done once for the object tree) and the fact I'm loading lists (see point 1), I have no other way of stopping the deserialization.

It seems to work fine, but I'm not the proud of this design.


texts: Best way to avoid users to cancel my routine halfway through while managing other errors

texts:
I'm struggling to find the best way to prevent users from cancelling a routine halfway through (by pressing ESC, break, etc) without making sure the sheet is being locked again. On top of that, I also want to manage potential other errors that this routine could generate. My code is :

Private Sub Worksheet_Activate()

Application.OnKey "{ESC}", ""
Application.EnableCancelKey = xlErrorHandler
Application.ScreenUpdating = False
ActiveWindow.DisplayHeadings = False
On Error GoTo errHandler

On Error Resume Next
ActiveSheet.Unprotect "XXXXX"
ActiveSheet.ShowAllData
ActiveSheet.Range("estimate_table").AutoFilter Field:=59, Criteria1:=">0"
ActiveSheet.Protect "XXXXX"

Application.ScreenUpdating = True
Application.OnKey "{ESC}"
Application.EnableCancelKey = xlInterupt

exitHandler:
    ActiveSheet.Protect "XXXXX"
    Application.OnKey "{ESC}"
    Application.EnableCancelKey = xlInterupt
    Application.ScreenUpdating = True
    Exit Sub
errHandler:
    If Err.Number = 18 Then
    Resume exitHandler
    Else
    MsgBox "An error has occured. The list can't be updated."
    Resume exitHandler
    End If

End Sub

What I'm trying to achieve is run an autofilter on a table in a locked sheet every time the sheet is activated. I want users to be able to stop the routine if necessary (maybe it's taking forever) but I want to be sure that no matter what, the sheet is back to being locked.

Also, I noticed that sometime, if user stops the routine once and goes back and forth between sheets, the routine won't work anymore and will generate an error that is never reset or cleared (i.e. the message "An error has occured..blablabla" is displayed every time the user activates the sheet). So I want to be sure that the routine doesn't get blocked / bugged even if an error has occurred before (hence my On Error Resume Next).

Overall I'm not sure I'm doing it correctly here (not familiar with VBA and error handling in general). With the code above, It doesn't seem like I'm able to stop the routine at all (but least the sheet seems locked all the time, which is nice)


texts: Using Factory pattern for parsing system

texts:
I am currently trying to write a Parser system for my project. There are different type of files to be parsed (file1, file2, file3):

file1 -> AData // stored in AData class using AParser class's parsing logic
file2 -> BData // stored in BData class using BParser class's parsing logic
file3 -> CData // stored in CData class using BParser class's parsing logic

Files could be binary or txt. Different files require different logic for parsing because of the way file are written.

I have used a factory pattern for this purpose. The Base class is Parser which is an abstract class.

#include <fstream>
#include <iostream>
#include <memory>
#include <string>

// Base class
template <class T>
class Parser {
   public:
    virtual void DoParsing(T&, std::ifstream& fs) = 0;
};

// Base class for data
struct Data {};
//////
struct AData : Data {
    int data;
};

class AParser final : public Parser<AData> {
   public:
    void DoParsing(AData& data, std::ifstream& fs) {
    // implementation goes here
    }
};
///
struct BData : Data {
    char* data;
};

class BParser final : public Parser<BData> {
   public:
    void DoParsing(BData& data, std::ifstream& fs) {
    // implementation goes here
    }
};

template <class T>
class IParsing {
   public:
    void action(std::shared_ptr<Parser<T>> p, T d, std::ifstream& fs) {
        p->DoParsing(d, fs);
    }
};

class FParsing {
   public:
    FParsing() {}

    void HandleParsing(std::string type, Data& d, std::ifstream& fs) {
      if (type == "AParsing") {
        std::shared_ptr<IParsing<AData>> iparse =
        std::make_shared<IParsing<AData>>();
        iparse->action(std::make_shared<AParser>(), static_cast<AData&>(d),
               fs);
      } else if (type == "BParsing") {
        // iparse->action(std::make_shared<BParser>(), fs);
        std::shared_ptr<IParsing<BData>> iparse =
        std::make_shared<IParsing<BData>>();
        iparse->action(std::make_shared<BParser>(), static_cast<BData&>(d),
               fs);

      } else {
        std::cout << "Need shape\n";
      }
    }

   private:
};

int main() {
    std::ifstream iFile("data.txt");
    FParsing fparse;
    //AData is passed by ref because
    // it will be populated during parsing process
    AData ad;
    fparse.HandleParsing("AParsing", ad, iFile);

    // BData
    BData ab;
    fparse.HandleParsing("BParsing", ab, iFile);
}

My questions are:

Do you think this is a right approach for creating a parsing system?
Is the factory pattern implementation correct?
I just wanted to make sure I am not making things more complex than it should be.
Are there other design patterns better than factory pattern for this purpose?


texts: Divide two numbers, then apply a custom rounding rule

texts:
If the fractional part of the number is greater than 0.6, round up; if less, round down.
I need feedback about my code.

public static double DivisionMethod(double a, double b)
{
      double div = a / b;
      double temp = Math.Floor(div);
      double fractional = div - temp;

      if (fractional > 0.6)
      {
          return Math.Ceiling(div);
      }
      else
      {
          return Math.Floor(div);
      }
}


texts: Calculating sum of similarities of strings

texts:
Puzzle:

  For two strings A and B, we define the similarity of the strings to be
  the length of the longest prefix common to both strings. For example,
  the similarity of strings "abc" and "abd" is 2, while the similarity
  of strings "aaa" and "aaab" is 3. Calculate the sum of similarities of
  a string S with each of its suffixes.

  Explanation:

  For ababaa the suffixes of the string are "ababaa", "babaa", "abaa",
  "baa", "aa" and "a". The similarities of each of these strings with
  the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6
  + 0 + 3 + 0 + 1 + 1 = 11.

How can I improve execution time of this (when larger testcases are provided)?

import java.util.Scanner;
public class Solution {
    public static void main(String[] args) {
        Scanner scanner;
        Solution sr = new Solution();
        scanner = new Scanner(System.in);
        int no_cases = scanner.nextInt();
        for (int i = no_cases; --i >=0; ) {
            String to_proc = scanner.next();
            sr.solve(to_proc);
        }
    }
    private void solve(String to_proc) {
            String str=to_proc;
            int len=to_proc.length();
            int count=0;
            int total=0;
            for(int i=1;i<len;i++)
            {
                count=0;
                for(int j=i;j<len;j++)
                {
               //     System.out.println(str.charAt(j)+" , "+str.charAt(j-i));
                    if(str.charAt(j-i)==str.charAt(j))
                    {
                        count++;
                    }
                    else
                    {
                        break;
                    }
                }
                total=total+count;
            }
            System.out.println(total+len);
    }
}


texts: Python Pandas Apply with a Lambda Function

texts:
I have a table in pandas that has two columns, QuarterHourDimID and StartDateDimID ; these columns give me an ID for each date / quarter hour pairing. For instance for January 1st, 2015, at 12:15PM the StartDateDimID would equal 1097 and QuarterHourDimID would equal 26. This is how the data I'm reading is organized.

It's a large table that I'm reading using pyodbc and pandas.read_sql(), ~450M rows and ~60 columns, so performance is an issue.

To parse the QuarterHourDimID and StartDateDimID columns into workable datetime indexes I'm running an apply function on every row to create an additional column datetime.

My code reading the table without the additional parsing is around 800ms; however when I run this apply function it adds around 4s to total run time (anywhere between 5.8-6s a query is expected.) The df that is returned is around ~45K rows and 5 columns (~450days*~100quarter-hour-parts)

I am hoping to more efficiently rewrite what I've written and get any input along the way.

Below is the code I've written thus far:

import pandas as pd
from datetime import datetime, timedelta
import pyodbc

def table(network, demo):
    connection_string = "DRIVER={SQL Server};SERVER=OURSERVER;DATABASE=DB"
    sql = """SELECT [ID],[StartDateDimID],[DemographicGroupDimID],[QuarterHourDimID],[Impression] FROM TABLE_NAME
        WHERE (MarketDimID = 1
        AND RecordTypeDimID = 2
        AND EstimateTypeDimID = 1
        AND DailyOrWeeklyDimID = 1
        AND RecordSequenceCodeDimID = 5
        AND ViewingTypeDimID = 4
        AND NetworkDimID = {}
        AND DemographicGroupDimID = {}
        AND QuarterHourDimID IS NOT NULL)""".format(network, demo)

    with pyodbc.connect(connection_string) as cnxn:
        df = pd.read_sql(sql=sql, con=cnxn, index_col=None)

    def time_map(quarter_hour, date):
        if quarter_hour > 72:
            return date + timedelta(minutes=(quarter_hour % 73)*15)
        return date + timedelta(hours=6, minutes=(quarter_hour-1)*15)

    map_date  = {}

    init_date = datetime(year=2012, month=1, day=1)

    for x in df.StartDateDimID.unique():
        map_date[x] = init_date + timedelta(days=int(x)-1)

    #this is the part of my code that is likely bogging things down
    df['datetime'] = df.apply(lambda row: time_map(int(row['QuarterHourDimID']),
                                                   map_date[row['StartDateDimID']]),
                                                   axis=1)
    if network == 1278:
        df = df.loc[df.groupby('datetime')['Impression'].idxmin()]

    df = df.set_index(['datetime'])

    return df


texts: Concatenate two arrays generated randomly

texts:
I have written the code to concatenate two arrays . Please let me know of any loopholes in the written code.

import java.util.Random;
import java.util.Scanner;

public class ConcatArr {
    static Random rand = new Random();
    static Scanner in = new Scanner(System.in);
    public static void main(String[] args){
        System.out.println("Main Method Started");
        System.out.println("Initialize the 1st array");
        int[] arr1 = initArr();
        System.out.println("The element of the 1st array");
        print(arr1);
        System.out.println("Initialize the 1st array");
        int [] arr2 = initArr();
        System.out.println("The element of the 2nd array");
        print(arr2);
        int[] contArr = concatArr(arr1,arr2);
        System.out.println("Concatnated array");
        print(contArr);
        System.out.println("Main Method Ended");
    }
    public static void print(int[] arr){
        System.out.print("{");
        for(int val:arr){
            System.out.print(val + "  ");
        }
        System.out.print("}");
        System.out.println();
    }
    public static int[] initArr(){
        System.out.println("Enter the limit of the array");
        int limit = in.nextInt();
        System.out.println("Enter the maximum value of the array");
        int maxValue = in.nextInt();
        int[] arr = new int[limit];
        for(int i=0;i<limit;i++){
            arr[i] = rand.nextInt(maxValue);
        }
        return arr;
    }
    public static int[] concatArr(int[] arr1,int[] arr2){
        int[] tempArr = new int[arr1.length+arr2.length];
        for(int i=0;i<arr1.length;i++){
            tempArr[i] = arr1[i];
        }
        for(int j=0;j<arr2.length;j++){
            tempArr[j+arr1.length] = arr2[j];
        }
        return tempArr;
    }
}


texts: Code indentation for declaring inputs/outputs in an array

texts:
I'm writing a list of inputs and outputs for to be compared in unit tests.

var equals = [
                //input                         //output
                ["name:(John Smith)",           "name:(John~ Smith~)"   ],
                ["name:Jon~0.1",                "name:Jon~0.1"          ],
                ["Jon",                         "Jon~"                  ],
                ["Jon Smith~0.1",               "Jon~ Smith~0.1"        ],
                ["Jon AND Bob",                 "Jon~ AND Bob~"         ],
                ["Jon AND Bob~0.1",             "Jon~ AND Bob~0.1"      ],
                ["Steve^9 Jon", ]               "Steve^9 Jon~"          ]

            ];

I've formatted it as such, so it's easy to compare and read.  However, it's unconventional.

Is this a bad idea?


texts: Base 256 array addition Recursively - Follow up

texts:
This is a follow up code review request from Base 256 array addition Recursively

I have made the changes that were suggested for the RecursiveAdd method. Please take some time to review and help me to make it better.

public class Base256Calculator : IBase256Calculator
{
    private const int Base = 256;

    /// <summary> Adds 2 byte arrays together. </summary>
    /// <param name="first">First array.</param>
    /// <param name="second">Second array.</param>
    /// <returns>Result array containing the sum of the two.</returns>
    public byte[] Add(byte[] first, byte[] second)
    {
        byte[] result = new byte[first.Length];
        return RecursiveAdd(first, second, first.Length - 1, result);
    }

    private byte[] RecursiveAdd(byte[] first, byte[] second, int index, byte[] result, int carry = 0)
    {
        if (index < 0)
        {
            if (carry != 1)
            {
                return result;
            }

            List<byte> resultList = result.ToList();
            resultList.Insert(0, 1);
            return resultList.ToArray();
        }

        int sum = first[index] + second[index] + carry;
        carry = Math.DivRem(sum, Base, out int remainder);
        result[index] = (byte)remainder;
        return RecursiveAdd(first, second, index - 1, result, carry);
    }
}


texts:
I am trying to implement a simple raw queue in C++. This is what I have come up with

#include <queue>
#include <cstdint>
#include <array>
#include <cstring>

class simple_queue
{
private:
    static constexpr uint32_t max_msg_size = 4096;
    using char_msg = std::array<char, max_msg_size>;
    std::queue<char_msg> char_queue;

public:
    simple_queue() = default;
    ~simple_queue() = default;
    simple_queue(simple_queue&&) = default;
    simple_queue& operator=(simple_queue&&) = default;

    uint32_t write(const char* const buff, const uint32_t size) noexcept
    {
        const uint32_t size_to_copy = std::min(max_msg_size, size);
        char_msg tmp_msg;
        std::memcpy(&tmp_msg, buff, size_to_copy);
        char_queue.push(std::move(tmp_msg));
        return size_to_copy;
    }

    uint32_t read(char* const buff, const uint32_t size) noexcept
    {
        if (char_queue.empty())
        {
            return 0;
        }
        const uint32_t size_to_copy = std::min(max_msg_size, size);
        std::memcpy(buff, &char_queue.front(), size_to_copy);
        char_queue.pop();
        return size_to_copy;
    }
};

Note that I am trying to implement this queue just to store raw char buffers. As far as I understand making it a template does not make sense in this case.

I have played with it a bit and it seems to work as I expect.

What can I change with this implementation?
Does it make sense to use a custom allocator in here? I am allocating memory every time I write to the queue; how can I use a custom allocator to allocate some default chunk of memory when the queue is constructed?


texts: How can I efficiently manipulate digits in a string without using RegEx in Java?

texts:
I am reading a book with different quizzes about coding interviews.
Please implement a function that increments a string based on the rules below:

It should take the string of unknown length and increment the numberic ending of that string by 1.
If numberic ending is overflown it must be reset.
Don't use regular expressions

Examples of correct functionality are the following:
assertEquals("000003", increment("000002"));
assertEquals("000000", increment("999999"));
assertEquals("GL-322", increment("GL-321"));
assertEquals("GL-000", increment("GL-999"));
assertEquals("DRI000EDERS1RE", increment("DRI000EDERS0RE"));
assertEquals("DRI000EDERS0RE00000", increment("DRI000EDERS0RE99999"));

Here is my solution, I am sure it could be vastly more efficient / succinct:
public class Increment {

    static String padLeftZeros(String inputString, int length) {
        if (inputString.length() >= length) {
            return inputString;
        }
        StringBuilder sb = new StringBuilder();
        while (sb.length() < length - inputString.length()) {
            sb.append('0');
        }
        sb.append(inputString);

        return sb.toString();
    }

    static String increment(String referenceNumber) {

        // Finding the last digit index in referenceNumber
        int indexLastDigit = -1;
        for (int i = 0; i < referenceNumber.length(); i++){
            try {
                Integer.parseInt(String.valueOf(referenceNumber.charAt(i)));
                indexLastDigit = i;
            } catch (NumberFormatException nfe) {
            }
        }

        // Finding the first digit index of the last digit group in referenceNumber
        int indexFirstDigit = -1;
        for (int i = indexLastDigit; i >= 0; i--){
            try {
                Integer.parseInt(String.valueOf(referenceNumber.charAt(i)));
                indexFirstDigit = i;
            } catch (NumberFormatException nfe) {
                break;
            }
        }

        // Checking if numberToIncrement needs reset or not
        String numberToIncrement = referenceNumber.substring(indexFirstDigit, indexLastDigit + 1);
        boolean isReset = true;
        for (int i = 0; i < numberToIncrement.length(); i++){
            if (numberToIncrement.charAt(i) != '9') {
                isReset = false;
            }
        }

        // Incrementing or resetting number
        StringBuilder incrementedNumberSB = new StringBuilder();
        int incrementedNumberInt;
        if (isReset) {
            for (int i = 0; i < numberToIncrement.length(); i++){
                incrementedNumberSB.append("0");
            }
        } else {
            incrementedNumberInt = Integer.parseInt(numberToIncrement) + 1;
            incrementedNumberSB.append(incrementedNumberInt);
        }

        // Creating result string according to referenceNumber structure
        String incrementedNumberString = padLeftZeros(incrementedNumberSB.toString(), numberToIncrement.length());
        String prefix = referenceNumber.substring(0, indexFirstDigit);
        String suffix = referenceNumber.substring(indexLastDigit + 1, referenceNumber.length());
        String result = "";

        if (prefix.length() > 0) {
            result += prefix;
        }
        result += incrementedNumberString;
        if (suffix.length() > 0) {
            result += suffix;
        }

        return result;

    }

}


texts:
I have been making my own scoreboard, and needed a custom spectate function for it, so I made this:

  util.AddNetworkString( "spectatePlayer" )
  local playerLocal
  local isSpectating = false

 net.Receive("spectatePlayer", function(length, client)
    if isSpectating then return end
        isSpectating = true
        playerLocal = client
        print(client:Nick() .. "Started spectating: " .. net.ReadEntity():Nick())
        client:Spectate(5)
        client:SpectateEntity(net.ReadEntity())

 end)

 hook.Add("Tick", "keydown", function()
        if not isSpectating then return end
                if (playerLocal:KeyDown(IN_FORWARD)) then
                        isSpectating = false
                        playerLocal:UnSpectate()
                        print(playerLocal:Nick().."Finished Spectating")
                end
        end)

Is there anything I could improve on? Am I over-complicating anything?


texts:
I've created a personal API for creating elements for an HTML page. I would like feedback on efficiency, particularly in creating buttons and labels. Any and all feedback is appreciated and considered

tag.js

/*
* Shortcuts for creatings different tags
*/
function createLabel(text) {
    let label_tag = document.createElement('label');
    let label_tag_text = document.createTextNode(text);
    tabel_tag.appendChild(label_tag_text);
    return label_tag;
}

function createButton(type) {
    /* need to manually add .onclick when creating button */
    let button_tag = document.createElement('button');
    button_tag.type = type;
    return button_tag;
}

function createInput(type, id) {
    let input_tag = document.createElement('input');
    input_tag.type = type;
    input_tag.id = id;
    return input_tag;
}

function createDiv(id) {
    let div_tag = document.createElement('div');
    div_tag.id = id;
    return div_tag;
}

function createTag(tag) {
    /*
    * Used for creating basic tags (
,
,
, etc)
    * Any tag that doesn't often use an ID, TYPE, NAME, CLASS, etc
    */
    return document.createElement(tag);
}


texts: Search a search button on page and toggle open class and focus on the input

texts:
I have a jQuery solution as below. I am confident the solution can be made better in terms of OO way using constructor pattern

  var $search = $('.search');

  if ($search.length > 0) {
    $search.removeClass('dropdown radix-dropdown-processed');
    $('.search__button').on('click', function (e) {
      e.preventDefault();
      $search.toggleClass('open');
      $('#site_search_query').focus();
    });
  }

Can someone help in making the code better as in reviewing the code so that it is better in terms of performance


texts:
Today I found myself reinventing output separators for the zillionth time.

I have converged on an approach like the following that seem pretty clean:

Live On Coliru

#include <iostream>

void foo(int a, int b) {
    auto sep = [first=true]() mutable { return std::exchange(first, false); };

    std::cout << "foo(";
    if (a) std::cout << sep() << "a:" << a;
    if (b) std::cout << sep() << "b:" << b;
    std::cout << ")\n";
}

int main() {
    foo(0,0);
    foo(0,1);
    foo(2,3);
    foo(4,0);
}

Extracting Building Blocks?

This could be made a bit more general by extracting the mutating state:

template <typename T = bool, T initial = true, T fallback = false>
struct once {
    mutable T flag = initial;

    operator T() const { return std::exchange(flag, fallback); }
};

So that we can now write the sep() lambda as:

auto sep = [first=once{}]{ return first? "" : ", "; };

Abstracting The Whole One-Off Value

We can go one better using

    auto sep = one_off("", ", ");

With:

template <typename T = char const*>
struct one_off {
    mutable once<> flag;

    T first, other;
    one_off(T first, T other) : first(std::move(first)), other(std::move(other)) {}

    operator T() const { return flag? first : other; }
};

Used as: Live On Coliru

void foo(int a, int b) {
    auto sep = one_off("", ", ");

    std::cout << "foo(";
    if (a) std::cout << sep << "a:" << a;
    if (b) std::cout << sep << "b:" << b;
    std::cout << ")\n";
}

Reflection And Merit?

As you can see these are all potentially useful building blocks. I'm wondering whether anyone else uses similar building blocks and what they learned from actual usage.

Ideas:

what about a dynamic separator? It's much easier to capture, say, columnar formatting in a stateful lambda eg: Live On Coliru

void foo(std::vector<int> const& v) {
    auto sep = [n=0u]() mutable {
        if (n++)
            return n%5==1?"\n" : ", ";
        return "";
    };

    for (auto& el : v)
        std::cout << sep() << std::setw(5) << el;
    std::cout << "\n";
}

Doesn't this conflict with standard library concepts like std::once_flag from C++11 too much?
Intuitively I feel these don't mix too well. Say, we want a every_nth style value wrapper instead of one_off (to replace every nth, instead of just the first)? Suppose we want to return from an input sequence, transforming every nth? Aren't we at risk of reinventing a Range Library?
Conversely, is there a straight-forward way to express these building blocks using an existing (range) library such as Boost Range or RangeV3?

  Notes:

  I used C++17 for brevity of exposition; it's not about using C++17 (I'm aware of ostream_joiner).
  It's not about string joining per se, which is why I chose a contrived example. In this example, obviously you could just print the delimiter if (a && b) but that's not the point of the exercise.
  Thanks to @LucDanton for suggesting std::exchange


texts:
I've created a class that allows me to load resources, execute a callback after each individual request has been made and finally, a final callback that can assume all said resources are available.

This is something I came up with when developing something in ExtJS, so there were no formal promises (done, success, then, always, etc.) like you have in jQuery.

Here's the class:

function ResourceLoader(finalCallback) {

    this.requests = [];
    this.finalCallback = finalCallback;

    //pops an additional request on the queue...
    this.addRequest = function (request) {
        this.requests.push(request);
    }

    //execute them all...
    this.executeRequests = function () {

        for (var i = 0; i <= this.requests.length - 1; i++) {

            //if 'errorCallback' member was specified, we will execute it, otherwise, create a empty function.
            var ec = (this.requests[i].errorCallback) ? this.requests[i].errorCallback : function () { };

            //if we are executing not the last request...
            if (i < this.requests.length - 1) {
                $.ajax(this.requests[i])
                .done(this.requests[i].callback)
                .error(ec);
            }
            else {
                //when executing the last queued request, execute the final callback.
                $.when($.ajax(this.requests[i])
                .done(this.requests[i].callback)
                .error(ec)).then(this.finalCallback);
            }

        }
    }

}

This works as intended.

var loader = new ResourceLoader(function () {
    //the final callback hides the spinner...
    $body = $("body");
    $body.removeClass("loading");
});

loader.addRequest({
    method: 'get',
    url: '/HtmlParts/ChatRoom/MessageSelf.html',
    callback: function (data) {
        $messageMe = data;
    }
});

loader.addRequest({
    method: 'get',
    url: '/HtmlParts/ChatRoom/MessageOthers.html',
    callback: function (data) {
        $messageOthers = data;
    }
});

loader.executeRequests();

Here I'm using it to load static HTML content from separate physical file that I can use as I wish to dynamically add instances of them on the fly later on.

Is there a better way to do this in jQuery ?

Thanks.


texts:
I have been working on a little project to tidy up my log table which has exceeded the shared host provider limits:) So I have done some script that is working except one thing at the end: optimise DB.

This script will run in cron so I hope security should not be issue.

My questions are:

the code is working, however I would like to learn how to do it better, so If you could point out thing that I shouldn't do and I did I would appreciate
if someone could tell me why my optimise DB doesn't work I would also thanks.
Performance!!! It will run on a table which has 1million rows and I am worried that his script wont perform fast enough. Any idea how to work this out?

I know I should use PDO (next step - as I am not familiar with it yet) but as a first step I am proud that I could put together something that is working.

<?php
include 'opendb.php';

//functions
function test($string){
  echo "<p>".$string."</p>";
}

function db_rows($db,$ord){
  $dbquery="SELECT azon FROM $db ORDER BY azon $ord LIMIT 1";
  $dbresult=mysql_query($dbquery);
  $row = mysql_fetch_array($dbresult);
  $dbrow = $row['azon'];
  return $dbrow;
}
// end of functions

//config information...
$acttable  = 'foo';
$today = date("yW_Hi");
$newdb = 'test_'.$today;

$firstact= db_rows($acttable,"asc");
$lastact= db_rows($acttable,"desc");
$upto=$firstact+25000;

test($lastact);
test($firstact);

if ($lastact-$firstact>50000) {

//create a new table
$newdbsql=" CREATE TABLE  $newdb ( `azon` bigint(20) NOT NULL AUTO_INCREMENT,  `mikor` datetime NOT NULL,  `felhazon` int(11) NOT NULL,  `felhnev` varchar(255) NOT NULL,  `muvelet` varchar(20) NOT NULL,  `sql` varchar(255) NOT NULL,  `tabla` varchar(255) NOT NULL,  `mezok` varchar(255) NOT NULL,  `ertekek` text NOT NULL,  `feltetel` varchar(255) NOT NULL,  `ip` varchar(255) NOT NULL,  `bongeszo` varchar(255) NOT NULL,  PRIMARY KEY (`azon`),  KEY `mikor` (`mikor`),  KEY `felhazon` (`felhazon`),  KEY `felhnev` (`felhnev`),   KEY `muvelet` (`muvelet`),  KEY `tabla` (`tabla`),  KEY `feltetel` (`feltetel`)) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=3524772 ;" ;
test($newresult);
$newresult = mysql_query($newdbsql);

// copy all the data
$query = "INSERT INTO $newdb SELECT * FROM $acttable WHERE $acttable.azon < $upto";
test($query);
$result = mysql_query($query);

// so what has happened...
if ($result) {
   test("ok");
  $delquery = "DELETE FROM $acttable WHERE $acttable.azon < $upto";
  test($delquery);
  $delresult = mysql_query($delquery);
  if ($delresult) {
     test("Deleted rows - OK");
  } else {
     test("failed to delete...");
     // then tidy up everything:)
    $res = mysql_query('SHOW TABLE STATUS WHERE Data_free / Data_length > 0.1 AND Data_free >  102400');
    while($optrow = mysql_fetch_assoc($res)) {
             mysql_query('OPTIMIZE TABLE ' . $optrow['Name']);
         }
      }
   }
   else {
      test("failed to copy...");
   }

}
else {
  test("no work needs to be done.");
}

// close db
mysql_close($conn);
?>


texts: Read files from a directory using Promises V2

texts:
Follow up to Read files from a directory using Promises

Removed exists() and replaced with stat() so I can check if the file is readable before proceeding.

console.log("Hi");
const fs = require('fs');
const { promisify } = require('util');

function mystat(file) {
    return new Promise(function(resolve, reject) {
        console.log(file);
        fs.stat(file, function(err, stat) {
            if (err) {
                reject(err);
            }
            else {
                console.log("Returning Obj");
                resolve({stat: stat, file: file});
            }
        });
    });
}

readdir     = promisify(fs.readdir);
readFile    = promisify(fs.readFile);
writeFile   = promisify(fs.writeFile);

readdir(".")
.then(files => mystat(files[0]))
.then(data  => {if (!(data.stat.mode | fs.S_IRWXO)) { throw "Not Readable";} return readFile(data.file)})
.then(content => writeFile('Test', content))
.then(() => console.log("It worked"))
.catch(err => console.log("Error: " + err));

To pass parameters through, eg the file passed through stat to the read function; I needed to define my own function so that I could pass the object on). Is there a better way of doing this?


texts:
I'm looking for the best way to return a date on a YYYYMMDD format, such as 20180106.

Here is how I do it:

var x = new Date();
var y = x.getFullYear().toString();
var m = (x.getMonth() + 1).toString();
var d = x.getDate().toString();
(d.length == 1) && (d = '0' + d);
(m.length == 1) && (m = '0' + m);
var yyyymmdd = y + m + d;
alert(yyyymmdd);

Is it correct enough or can I achieve the same in a better way?


texts: How can I implement the generic repository pattern and improve the performance for the code below?

texts:
I've used EF-DB first approach and have written a simple app to retrieve the data from the database and show it in the view. The code is simple and ok for a beginner like me, but how can I implement an effective design-pattern like interface-specification pattern or generic repository pattern, and possibly dependency injection to improve the code below ? I'd like to know because when extending the project I might have to get data from different databases, and would like to implement an effective pattern for maintainability.

Please note that I've started looking into topics like interfaces, design patterns, etc only recently, So I'd greatly appreciate it if you could please break down the explanation to a beginner level.

Below are my view-model and the controller. My model contains a stored-procedure and a table in the .edmx file - Thanks

View-Model

    public class OfficeDTO
    {
        public IEnumerable<EmployeeDTO> Employees { get; set; }
        public IEnumerable<DepartmentDTO> Departments { get; set; }
    }

    public class EmployeeDTO
    {
       public int EmpId { get; set; }
       public string EmpName { get; set; }
    }

    public class DepartmentDTO
    {
        public string DeptCode { get; set; }
        public string DeptName { get; set; }
    }

Controller

  public ActionResult Index()
            {
                EF.OfficeEntities ctx = new EF.OfficeEntities();
                Models.OfficeDTO office = new Models.OfficeDTO();

                using (ctx)
                {

                    var empList = ctx.GetEmployeesByYearJoined("2009")
                              .ToList();

                    var empResults = (from q in empList
                                   select new Models.EmployeeDTO
                                   {
                                       EmpId = q.EmpID,
                                       EmpName = q.FirstName + q.LastName
                                   }).ToList();
                    office.Employees = empResults;

                    var depResults = (from q in ctx.Departments
                                      select new Models.DepartmentDTO
                                      {
                                          DeptCode = q.DepartmentCode,
                                          DeptName = q.DepartmentName

                                      }).ToList();
                    office.Departments = depResults;
                }

                return View(office);
            }


texts:
I have this assignment to write the optimized space and time code for finding the sum of all primes under 2 million. I'm using the following function to check if each number is prime:

int IsPrime(unsigned int number) {
    if (number <= 1) return 0;
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

And running a for loop from 1 to 2 million using a long double, and checking each number if it is prime and then adding it. Is there a more optimized method to do this?


texts:
I've written this class as an exercise for a synchronization construct to be used across multiple threads.

The intent is to have worker threads Increment() it, do some work, then finally Decrement()it.

Meanwhile, when a master thread decides to shut down the program, it signals the threads using a CancellationToken and Wait()s on this structure until all threads have ceased (signalled by _number hitting zero).

I am depending mainly on the fact that Interlocked operations imply full memory fences. I am concerned with the read on the Wait() method, see the comment there.

public class CountdownLatch
{
    int _number;
    readonly ManualResetEventSlim _event;

    public CountdownLatch()
    {
        this._event = new ManualResetEventSlim();
    }

    public void Increment()
    {
        Interlocked.Increment(ref this._number);
    }

    public void Decrement()
    {
        int currentNumber;
        bool firstAttempt = true;

        do
        {
            currentNumber = this._number;
            if (!firstAttempt)
            {
                var spinWait = new SpinWait();
                spinWait.SpinOnce();
            }
            else
            {
                firstAttempt = false;
            }

            if (currentNumber == 0)
            {
                throw new InvalidOperationException("Attempt to decrement past zero");
            }
        } while (Interlocked.CompareExchange(ref this._number, currentNumber - 1, currentNumber) != currentNumber);

        if (currentNumber == 1)
        {
            this._event.Set();
        }
    }

    public bool Wait(TimeSpan timeout)
    {
        // Should this be a volatile read: Volatile.Read(ref this._number) ?
        // AFAICT the memory barrier here would prevent instruction reordering
        // when the order of reads/writes matter, but here it doesn't. I just care
        // to have the latest value of this._number across all CPUs/cores.
        // Or does volatile read in C# specifically do both ?
        if (this._number == 0)
        {
            return true;
        }

        return this._event.Wait(timeout);
    }
}


texts:
I am still a beginner in C++ and I am always curious about good/best coding methods.

Let's say I have a program which allows a users to edit the salary of a employee.

The system will prompt the user which to key in a employee's name first.
The system will then check whether or not the username exist.
If the username existed, the system will then allow the user to change the employee's
salary.

The salary and the name of the person is stored in a text file.

employeeInfo.txt (formatted by name and salary)

john 1000
mary 2000
bob 3000

user.h

#ifndef user_user_h
#define user_user_h
#include <iostream>

class  user  {

public:

    user(std::string userName,std::string salary);

    std::string getUserName();
    std::string getSalary();

    void setUserName(std::string userName);
    void setSalary(std::string salary);

private:
    std::string userName,salary;

};
#endif

user.cpp

#include "user.h"
#include <iostream>
#include <string>
using namespace std;

user::user(string userName,string salary)  {

    setUserName(userName);
    setSalary(salary);

};

string user::getUserName()    {
    return userName;
}
string user::getSalary()  {
    return salary;
}

void user::setUserName(std::string userName) {
    this->userName = userName;
}

void user::setSalary(std::string salary) {
    this->salary = salary;
}

main.cpp

#include "user.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <string.h>
using namespace std;

int main(){
    vector<user> userDetails;
    string line;
    string userName;
    string salary;

    ifstream readFile("employeeInfo.txt");

    while(getline(readFile,line))   {
        stringstream iss(line);
        iss >> userName >> salary;

        //consturctor
        user employeeDetails(userName,
                             salary
                             );
        userDetails.push_back(employeeDetails);

    }
    readFile.close();

    string name;
    cout << "Please enter a user name\n";
    cin >> name;

    for (int i =0; i<userDetails.size(); i++) {
        //search if there's a match
        if (userDetails[i].getUserName() == name) {
            string newSalary;

            cout << "Please enter a new salary" << endl;
            cin >> newSalary;
            userDetails[i].setSalary(newSalary);
        }
    }
    //display to see if the salary gets updated
    for (int i=0; i<userDetails.size(); i++) {
        cout << userDetails[i].getSalary << "\n";
    }
}

I am not really sure if my code (shown below) is the worst method to search for a record in a vector and match it against the input of the user.  I would like to know is there any way to improve my code.  I'd also like to gather some tips and ideas from you all to determine if this is the worst method to search for a record in a vector.

//search for existing username
for (int i =0; i<userDetails.size(); i++) {
            if (userDetails[i].getUserName() == name) {
                //do stuff
            }
        }


texts: Hide and un-hide rows then sort on Worksheet_Activate event

texts:
We used this VBA code mainly to hide blank rows and unhide non-blank rows. After that, the second code sorts the rows by a defined column value once the worksheet activates. This process takes too much time with this code.

Could anyone help me optimize this code and make it faster? (The worksheet contain an average of 500 rows).

Private Sub Worksheet_Activate()
HideRows
Sortingrisk

End Sub

Sub HideRows()
Dim rRange As Range, rCell As Range
Dim strVal As String

   Set rRange = Worksheets(12).Range("A10:A500")

    For Each rCell In rRange
      strVal = rCell
      rCell.EntireRow.Hidden = strVal = vbNullString
    Next rCell

End Sub

Sub Sortingrisk()

    ActiveWorkbook.Worksheets("Control Implementation Plan").AutoFilter.Sort. _
      SortFields.Clear
   ActiveWorkbook.Worksheets("Control Implementation Plan").AutoFilter.Sort. _
      SortFields.Add Key:=Range("G10:G1000"), SortOn:=xlSortOnValues, Order:= _
      xlDescending, DataOption:=xlSortNormal
   With ActiveWorkbook.Worksheets("Control Implementation Plan").AutoFilter.Sort
     .Header = xlYes
      .MatchCase = False
       .Orientation = xlTopToBottom
       .SortMethod = xlPinYin
       .Apply
    End With
End Sub


texts:
I created this testimonial on CodePen

I am a bit skeptical about a few things in my HTML structure. For example, I typically see testimonials enclosed in
s with custom classes. In my case I used a
 but had to overwrite a lot of rules.

Also wondering if enclosing the author in  tags was wise.

HTML

    &ldquo;Such cool. Much awesome. WOW&rdquo;

    &ndash;
    Doge,
    The Moon

CSS

/* == resets == */
body { margin: 0; padding: 0; }
/* == project == */
body {
  background: none repeat scroll 0% 0% rgb(240, 240, 240);
  color: rgb(102, 102, 102);
  font-family: "Helvetica Neue", Helvetica, Arial, Sans-serif;
  font-size: 22px;
}
.wrapper {
  width: 600px;
  margin: 24px auto;
}

blockquote {
  background-color: rgb(255, 255, 255);
  border-radius: 6px;
  font-family: Georgia, serif;
  font-size: 22px;
  line-height: 1.4;
  margin: 0;
  padding: 17px;
}
p.author {
  background-color: transparent;
  font-weight: 500;
  font-size: 22px;
  line-height:22px;
  margin: 24px 0 0 18px;
}
strong {
  color: rgb(68, 68, 68);
}

a {
  color: rgb(64, 131, 169);
  text-decoration: none;
}


texts:
I have a problem where I need to replace every base part of URLs in a body of text.  However, I only want to replace it in specific URLs.  Only URLs that go to "resource.aspx" that have the "source" query string parameter need to get the replacement.  Other URLs could have the target base part and we don't want to touch those.  The resource urls are expected to appear inside quotes.

I made a UDF that takes the text body, the base URL you want to replace, and the base URL to replace with and searches through the text and does the base URL replacement on any "resource URLs" it finds.

Does the algorithm look sound?  Anything I missed?  Better ways to do this?

I was sad to learn that REPLACE() does not work with a pattern, even though it's second paramter is named "string_pattern" :(.  I was hoping it would work like .NET's Regex.Replace() (I know we don't have regex in t-sql, but a pattern based replace function would be nice sigh)

-- =============================================
-- Author:      John Doe
-- Create date:  11/29/2016
-- Description:  Replaces base URLs in text body of every URL that points to
--               resource.aspx that has "source" query string parameter.
--               Replaces specified base url with specified replacement
-- =============================================
CREATE FUNCTION dbo.udfReplaceResourceBaseURLs
(
    @TextBody NVARCHAR(MAX),
    @BaseUrlToReplace NVARCHAR(MAX),
    @BaseUrlReplacement NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
        -- Create Copy of the original body.  We will search and modify the copy in the loop
        DECLARE @EmailBodyCopy NVARCHAR(MAX)
        SET @EmailBodyCopy = @TextBody

        DECLARE @ResourceURLPattern NVARCHAR(MAX) = '%' + @BaseUrlToReplace + '/myResource.aspx%source=%'

        -- Do replacements while resource URLs are found in the copy
        DECLARE @resourceURLStart INT = PATINDEX(@ResourceURLPattern, @EmailBodyCopy)
        WHILE @resourceURLStart > 0
        BEGIN
            -- Get the full URL of the found resource URL
            DECLARE @resourceURLEnd INT = CHARINDEX('"', @EmailBodyCopy, @resourceURLStart)
            DECLARE @resourceURL NVARCHAR(MAX) = SUBSTRING(@EmailBodyCopy, @resourceURLStart, (@resourceURLEnd - @resourceURLStart))

            -- Replace base URL to get the new URL with the desired base URL replaced in
            DECLARE @newResourceURL NVARCHAR(MAX) = REPLACE(@resourceURL, @BaseUrlToReplace, @BaseUrlReplacement)

            -- Replace the URL in the original body with our new one
            SET @TextBody = REPLACE(@TextBody, @resourceURL, @newResourceURL)

            -- Chop off the front of the body copy up to the end of the current resource URL
            -- so that we find the next resource url on next pass
            SET @EmailBodyCopy = SUBSTRING(@EmailBodyCopy, @resourceURLEnd, 999999999) -- get to index infinity to make sure grab to end

            SET @resourceURLStart = PATINDEX(@ResourceURLPattern, @EmailBodyCopy)
        END

        RETURN @TextBody
END


texts: Creating automatic resizing of subelements in WPF

texts:
I currently have this code:

<Window x:Class="Listener.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="600" Width="800" Loaded="Window_Loaded" WindowStyle="None" AllowsTransparency="True" Background="Transparent" MouseDown="Window_MouseDown" KeyDown="Window_KeyDown" ResizeMode="CanResizeWithGrip">
    <Grid Margin="30" x:Name="bgBorder">
        <Grid Margin="0" Background="#555555" x:Name="mainWindow" MouseDown="mainWindow_MouseDown">
            <Grid Margin="2,2,2,2" Height="80" Background="#779999" x:Name="topControl" VerticalAlignment="Top">
            </Grid>
            <Grid Margin="2,84,238,2" Background="#557777" x:Name="playListControl">
            </Grid>
            <Grid Margin="2,84,2,2" Width="234" Background="#668888" x:Name="optionsControl" HorizontalAlignment="Right">
            </Grid>
        </Grid>
    </Grid>
</Window>

A borderless window where the 3 sub panels get resized according to their margin and alignment.

Is this the correct way of doing this?

And on a side node, I plan on creating some sort of border resize and not use

ResizeMode="CanResizeWithGrip"

This was just used for testing.