texts: Rename files by editing their names in an editor

texts:
Inspired by the a recent question to rename files by editing the list of names in an editor, I put together a similar script.

Why: if you need to perform some complex renames that are not easy to formulate with patterns (as with the rename.pl utility), it might be handy to be able to edit the list of names in a text editor, where you will see the exact names you will get.

Features:

Edit names in a text editor
Use the names specified as command line arguments, or else the files and directories in the current directory (resolve *)
Use a sensible default text editor

According to man bash, READLINE commands try $VISUAL or else $EDITOR -> looks like a good example to follow.
Abort if cannot determine a suitable editor.

Abort (do not rename anything) if the editor exits with error
Paths containing newlines are explicitly unsupported
Perform basic sanity checks: the edited text should have the same number of lines as the paths to rename

Here's the script:

#!/usr/bin/env bash
#
# SCRIPT: mv-many.sh
# AUTHOR: Janos Gyerik <info@janosgyerik.com>
# DATE:   2019-07-27
#
# PLATFORM: Not platform dependent
#
# PURPOSE: Rename files and directories by editing their names in $VISUAL or $EDITOR
#

set -euo pipefail

usage() {
    local exitcode=0
    if [[ $# != 0 ]]; then
        echo "$*" >&2
        exitcode=1
    fi

    cat << EOF
Usage: $0 [OPTION]... [FILES]

Rename files and directories by editing their names in $editor

Specify the paths to rename, or else * will be used by default.
Limitations: the paths must not contain newline characters.
EOF

    if [[ $editor == *vim ]]; then
        echo "Tip: to abort editing in $editor, exit with :cq command."
    fi

    cat << "EOF"

Options:
  -h, --help         Print this help

EOF
    exit "$exitcode"
}

fatal() {
    echo "Error: $*" >&2
    exit 1
}

find_editor() {
    # Following READLINE conventions, try VISUAL first and then EDITOR

    if [[ ${VISUAL+x} ]]; then
        echo "$VISUAL"
        return
    fi

    # shellcheck disable=SC2153
    if [[ ${EDITOR+x} ]]; then
        echo "$EDITOR"
        return
    fi

    fatal 'could not determine editor to use, please set VISUAL or EDITOR; aborting.'
}

editor=$(find_editor)

oldnames=()
while [[ $# != 0 ]]; do
    case $1 in
    -h|--help) usage ;;
    -|-?*) usage "Unknown option: $1" ;;
    *) oldnames+=("$1") ;;
    esac
    shift
done

work=$(mktemp)
trap 'rm -f "$work"' EXIT

if [[ ${#oldnames[@]} == 0 ]]; then
    oldnames=(*)
fi

printf '%s\n' "${oldnames[@]}" > "$work"
"$editor" "$work" || fatal "vim exited with error; aborting without renaming."
mapfile -t newnames < "$work"

[[ "${#oldnames[@]}" == "${#newnames[@]}" ]] ||
    fatal "expected ${#oldnames[@]} lines in the file, got ${#newnames[@]}; aborting without renaming."

for ((i = 0; i < ${#oldnames[@]}; i++)); do
    old=${oldnames[i]}
    new=${newnames[i]}
    if [[ "$old" != "$new" ]]; then
        mv -vi "$old" "$new"
    fi
done

What do you think? I'm looking for any and all kinds of comments, suggestions, critique.


texts:
I have this linq query that queries a table that retains any change history done to any of the tables is constructed like this:

History (Primary Key) | Table_Name | Primary_Key | Field_Name | Old_Value | New_Value | Action_Type | Action_Date | Action_User

The Linq query I have that queries this table is this:

 var complaintHistory = from histories in DbContext.Histories
                                       where ((from c in taskIds
                                               select "<Task_ID=" + c + ">").Contains(histories.Primary_Key) ||
                                              (from c in notificationListIds
                                               select "<Notification_List_ID=" + c + ">").Contains(histories.Primary_Key) ||
                                              (from c in emailSentIds
                                               select "<Email_Sent_ID=" + c + ">").Contains(histories.Primary_Key) ||
                                                  histories.Primary_Key == "<Complaint_ID=" + Complaint.Complaint_ID + ">") &&
                                                  histories.Field_Name != "rowversion"
                                       select histories;

I'm having serious latency whenever I call this query. Can this Linq query be re-written to increase performance dramatically?


texts: Product of all but one number in a sequence

texts:
I was given the following prompt in a coding interview:

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]

I solved this in two ways:

fun multiplies all elements together in the first iteration, and then loops again and divides by the number at that position
fun2 does not use division, and instead iteratively builds up the sum in each index

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

int fun(int* nums, int arr_size)
{
    int sum;
    int i;

    for(i=0, sum=1; i<arr_size; i++)
        sum*=nums[i];
    for(i=0; i<arr_size; i++)
        nums[i]=sum/nums[i];
    return 0;
}

int fun2(int* nums, int arr_size)
{
    int i,j;
    int sum=1;
    int new_arr[arr_size];

    for(i=0; i<arr_size; i++) {
        for(j=0; j<arr_size; j++) {
            if(i!=j)
                sum*=nums[j]; //skip member same index in the loop
        }
        new_arr[i]=sum;
        sum=1;
    }
    memcpy(nums, new_arr, arr_size*sizeof(int));
    return 0;
}

int main(void)
{
    /*Given an array of integers, return a new array such that each element at index i of the
    new array is the product of all the numbers in the original array except the one at i.
    For example, if our input was [1, 2, 3, 4, 5], the expected output would be
    [120, 60, 40, 30, 24] */
    int nums[] = {1, 2, 2, 4, 6};
    int size = sizeof(nums)/sizeof(nums[0]);
    int i;
    fun(nums, size);
    for (i = 0; i < size; i++)
        printf("%d ", nums[i]);

    //what if you can't use division?
    printf("\n");
    int nums2[] = {1, 2, 2, 4, 6};
    fun2(nums2, size);
    for (i = 0; i < size; i++)
        printf("%d ", nums2[i]);

    return 0;
}
```


texts: Find Triangle Triplets from a list of given numbers

texts:
If a triplet of segments A, B and C are triangle triplets if and only
if

A + B > C
A + C > B
B + C > A

Is there a better implementation for this problem?
#include<vector>
#include<iostream>

void findTriangleTriplets( std::vector<int>& vec_input, std::vector<std::vector<int>>& triplets)
{
    int size =  vec_input.size();
    for(int i = 0; i < size; ++i)
    {
        for(int j = i+1; j < size; ++j)
        {
            for(int k = 0; k < size; ++k)
            {
                if( ( ( vec_input.at( i ) + vec_input.at( j ) ) > vec_input.at( k ) ) &&
                    ( ( vec_input.at( i ) + vec_input.at( k ) ) > vec_input.at( j ) ) &&
                    ( ( vec_input.at( j ) + vec_input.at( k ) ) > vec_input.at( i ) ) )
                {
                    std::vector<int> temp;
                    temp.emplace_back( vec_input.at( i ) );
                    temp.emplace_back( vec_input.at( j ) );
                    temp.emplace_back( vec_input.at( k ) );
                    triplets.emplace_back( temp );
                }
            }
        }
    }
}

int main()
{
    std::vector<std::vector<int>>  triplets;
    std::vector<int> vec_input { 1, 2, 3, 4, 5, 6 };

    findTriangleTriplets( vec_input,  triplets);
    for ( auto &x : triplets)
    {
        std::cout<<x.at(0)<<" "<<x.at(1)<<" "<<x.at(2)<<"\n";
    }

    return 0;
}


texts: A function that checks for duplicate elements in an array

texts:
Is there a simpler way to implement this function?

function has_duplicates(arr) {
  var myObject = {};

  for (var key in arr) {
    if (myObject[arr[key]])
      return true;
    else
      myObject[arr[key]] = true;
  }
  return false;
}

console.log(has_duplicates(["foo", "bar", "baz", "quux", "foo"]));


texts: Getting current weather data using OpenWeatherMap API

texts:
I would really appreciate if someone could take a look at this code. I am not very advanced, so ANY kind of feedback and critique would be precious to me.

What this program is supposed to do is to go to a given URL, download the list of cities, for which it will download the data, based on a https://openweathermap.org/api . It should be run on a regular basis and write all of the results to the CSV file.

It is divided into two parts. The first one consists only of the scheduler, final function which is being run by it and the list of columns I want to get as the final result.

Code is written for Python 3.6.

from API.helpers import get_weather_data, json_to_df, create_dict
import schedule, time

URL = 'https://pm1aapplicantsdata.blob.core.windows.net/databases/CitiesWeather/CitiesWeather.csv'
columns = ["name","sys.country","main.temp",
           "main.humidity","main.pressure",
           "visibility", "wind.speed"]
#Writing results to CSV
def weather_api(URL):
    dict = create_dict(URL)
    for city, code in dict.items():
        data = get_weather_data(city, code)
        json_to_df(data, columns)
schedule.every().day.at("10:30").do(weather_api, URL)
while True:
    schedule.run_pending()
    time.sleep(1)

Here is the second part, which is my "helper" file.

import json
import requests
from pandas.io.json import json_normalize
import pandas as pd
import os
import requests
import csv
api_key = "xxxxxxxxxxxxxxxxxxxxxxx"

#function to build api requests
def build_request(city, code):
    base_url = "http://api.openweathermap.org/data/2.5/weather?"
    complete_url = base_url + "appid=" + api_key + "&q=" + city +"," + code
    return complete_url

#function to get weather data
def get_weather_data(city, code):
    url = build_request(city, code)
    try:
        response = requests.get(url)
        response.status_code
    except requests.exceptions.HTTPError:
        print('Error occured while downloading data')
    except requests.exceptions.URLError:
        print('Error occured while downloading data')
    citydataJSON = response.text
    citydata = json.loads(citydataJSON)
    return citydata

def json_to_df(data, columns):
    df = pd.DataFrame.from_dict(json_normalize(data), orient='columns')
    new_df = df[columns]
    new_df.insert(0, 'TimeStamp', pd.datetime.now().replace(microsecond=0))
    if not os.path.isfile('weather.csv'):
        return new_df.to_csv('weather.csv', header='column_names', index=False)
    else:
        return new_df.to_csv('weather.csv', mode='a', header=False, index=False)
#creating a dictionary of cities and city codes(based on the CSV file downloaded from a given URL
def create_dict(URL):
    with requests.Session() as s:
        dict = {}
        download = s.get(URL)
        decoded_content = download.content.decode('utf-8')
        cs = csv.reader(decoded_content.splitlines(), delimiter=',')
        next(cs, None)
        my_list = list(cs)
        for row in my_list:
            dict[row[0]] = row[1]
        return dict


texts: Search for directories with a certain prefix that contain no files of a given type

texts:
These two functions search for directories with a certain prefix that contain no files of a given type.

Does the code adhere to Ruby standards and conventions?
Am I doing something the hard way or the "non-Ruby" way?
Should I use more/fewer/different comments?

def find_empties(directory, dirprefix, fsuffix)
  empty_dirs = Array.new
  Dir.chdir directory do
    Dir["#{dirprefix}**/"].each do |subdir|
      Dir.chdir subdir do
        empty_dirs.push subdir if Dir["**.#{fsuffix}"].empty?
      end
    end
  end
  return empty_dirs
end

def find_empties_sorted(directory, dirprefix, fsuffix)
  empties = find_empties(directory, dirprefix, fsuffix)
  nums = Hash.new
  non_numeric = Array.new
  empties.each do |x|
    # if starts with digits, trim leading zeroes and extract; else, nothing
    num = x.sub(/^#{Regexp.escape dirprefix}0*(\d+).*/, '\1')
    is_num = num !~ /\D/
    if is_num
      n = Integer num
      nums[n] = Array.new unless nums[n]
      nums[n].push x
    else
      non_numeric.push x
    end
  end
  result = Array.new
  nums.sort.each do |k, v|
    v.each do |x|
      result.push x
    end
  end
  result.concat non_numeric.sort
  result
end

The code works as intended, but here's a test case:

$ ls
emptyfinder.rb
emptyrunner.rb
$ cat emptyrunner.rb
require_relative 'emptyfinder.rb'

puts find_empties_sorted(Dir.pwd, 'e', 'txt')
$ mkdir testcase
$ cd testcase
$ mkdir e1 e2 e003 e004 e4 e5 e9 e10 e11 empty emptier emptynot
$ touch emptynot/file.txt
$ touch empty/not_a_txt.csv
$ ruby ../emptyrunner.rb
e1/
e2/
e003/
e004/
e4/
e5/
e9/
e10/
e11/
emptier/
empty/
$


texts: Supporting different orientation in viewcontrollers

texts:
will you please give your thoughts (code review) on these two way of solving orientation.

About the app:

We have a universal App. The main purpose of the app is to watch the videos. The app has four screens.

Shows the list of shows
show the list of episodes in the show
details of an episode
Player screen

The way we implemented is

a navigationalViewController that shows the viewController 1 (list of show)
then drill into viewController 2 (episodes of a show)
then drill into viewController 3 (episode details)
then viewController 4 ( with av media player view) presented modally from viewController 3

Requirement of orientation:

+--------+------------------+---------------------+-----------------------+-----------------------------+
| Device | Shows list (vc1) | Episodes list (vc2) | Episode details (vc3) | Player ViewController (vc4) |
+--------+------------------+---------------------+-----------------------+-----------------------------+
| iPad   | Landscape        | Landscape           | Landscape             | Landscape                   |
+--------+------------------+---------------------+-----------------------+-----------------------------+
| iPhone | Portrait         | Portrait            | Portrait              | Portrait & Landscape        |
+--------+------------------+---------------------+-----------------------+-----------------------------+

Method 1:

Implement this following code at app delegate level

func application(_ application: UIApplication,
                 supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {

    guard let viewController = self.window?.rootViewController?.presentedViewController else {
        if UIDevice.current.userInterfaceIdiom == .pad {
            return .landscape
        }
        return [.portrait, .portraitUpsideDown]
    }

    if viewController is PlayerViewController && viewController.isBeingDismissed == false {
        return .all
    } else {
        if UIDevice.current.userInterfaceIdiom == .pad {
            return .landscape
        }
        return [.portrait, .portraitUpsideDown]
    }
}

Method 2:

Implement this following code at navigationViewController level

class MyNavigaitonViewController: UINavigationController {

override var shouldAutorotate: Bool {
    if self.traitCollection.userInterfaceIdiom == .pad {
        return true // we are supporting both landscapeLeft and landscapeRight on iPad.
    }
    return false }

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    if self.traitCollection.userInterfaceIdiom == .pad {
        return .landscape // we are supporting both landscapeLeft and landscapeRight on iPad.
    }
    return .portrait }

}

Player view controller has this following code in both Method 1 and Method 2

extension PlayerViewController {
override var shouldAutorotate: Bool {
    if self.traitCollection.userInterfaceIdiom == .pad {
        return true // we are supporting both landscapeLeft and landscapeRight on iPad.
    }
    // TODO: workout a way to support landscapeleft & right in phone
    return true
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.all
}
}


texts: Concurrency mechanism for ensuring repeated threads are executed in a given order

texts:
Inspired by the following leet-code

Suppose you are given the following code:
class FooBar {
  public void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
    }
  }

  public void bar() {
    for (int i = 0; i < n; i++) {
      print("bar");
    }
  }
}

The same instance of FooBar will be passed to two different threads.
Thread A will call foo() while thread B will call bar(). Modify the
given program to output "foobar" n times.
Example 1:
Input: n = 1 Output: "foobar" Explanation: There are two threads being
fired asynchronously. One of them calls foo(), while the other calls
bar(). "foobar" is being output 1 time.
Example 2:
Input: n = 2 Output: "foobarfoobar" Explanation: "foobar" is being
output 2 times.

My solution, which is was accepted:
class FooBar {
    private static class Syncer {
        int status;
    }

    private int n;
    private Syncer syncer = new Syncer();

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        synchronized(syncer) {
            for (int i = 0; i < n; i++) {
                while (syncer.status != 0){
                    syncer.wait();
                }
                printFoo.run();
                syncer.status = 1;
                syncer.notifyAll();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        synchronized(syncer) {
            for (int i = 0; i < n; i++) {
                while (syncer.status != 1){
                    syncer.wait();
                }
                printBar.run();
                syncer.status = 0;
                syncer.notifyAll();
            }
         }
    }
}

Questions:

Do you see any cases, where this solution would not work? (Assuming the input is correct, i.e. n>=1.)

I'm thinking of cases where one thread would not necessarily see the changes to syncer due to it not being volatile and synchronized. (I know this exact issue does not affect my solution, because syncer is, in fact synchronized, so what I mean if there are other similar "pitfalls" which affect the code above.)

Do you see any issues with performance? (I know the code waits in a while-loop, but it calls wait, which is supposed to be optimal.)

In general, is there a way this solution could be improved?

Does this pattern (threads running multiple times in a given order and waiting for each other) have a name, or a high-level Java concurrency object which implements them? (Slightly related: what better name would you give to syncer?)


texts:
I'm relatively new to Python. Here is a Tic Tac Toe game I've created in Python:

def is_valid_move(x,y,board):
    return ((0 <= x <= 2) and (0 <= y <= 2)) and (board[x][y] == '_')

def check_win(board):
    if board[0][0] == board[0][1] == board[0][2] != '_':
        return True
    if board[1][0] == board[1][1] == board[1][2] != '_':
        return True
    if board[2][0] == board[2][1] == board[2][2] != '_':
        return True
    if board[0][0] == board[0][1] == board[0][2] != '_':
        return True
    if board[0][1] == board[1][1] == board[2][1] != '_':
        return True
    if board[0][2] == board[1][2] == board[2][2] != '_':
        return True
    if board[0][0] == board[1][1] == board[2][2] != '_':
        return True
    if board[2][0] == board[1][1] == board[0][2] != '_':
        return True
    return False

def get_input_from_user(message:str):
    coord = input(message)
    str_x, str_y = coord.split()
    return int(str_x), int(str_y)

def make_move(idx,board):
    if idx % 2 == 0:
        x, y = get_input_from_user("Player X, please enter a move:")
        while not is_valid_move(x, y,board):
            x,y = get_input_from_user("Invalid move, please try again:")
        board[x][y] = 'X'
    else:
        x, y = get_input_from_user("Player O, please enter a move:")
        while not is_valid_move(x, y,board):
            x, y = get_input_from_user("Invalid move, please try again:")
        board[x][y] = 'O'

def print_board(board):
    for i in range(3):
        print(board[i])

if __name__ == '__main__':
    idx = 0
    board = [['_','_','_'] for i in range(3)]
    condition = False
    while condition is not True or idx <= 8:
        make_move(idx,board)
        print_board(board)
        condition = check_win(board)
        if condition is True and idx % 2 == 0:
            print("Player X is the Winner!")
        elif condition is True:
            print("Player O is the Winner!")
        idx += 1
    if idx > 8 and condition is not True:
        print("Its a Draw!")

Here is a simple test run of this code:

Player X, please enter a move:0 2
['_', '_', 'X']
['_', '_', '_']
['_', '_', '_']
Player O, please enter a move:0 1
['_', 'O', 'X']
['_', '_', '_']
['_', '_', '_']
Player X, please enter a move:1 1
['_', 'O', 'X']
['_', 'X', '_']
['_', '_', '_']
Player O, please enter a move:0 0
['O', 'O', 'X']
['_', 'X', '_']
['_', '_', '_']
Player X, please enter a move:2 0
['O', 'O', 'X']
['_', 'X', '_']
['X', '_', '_']
Player X is the Winner!

Let me know your thoughts about my code.


texts: Simple administrator authentication page in PHP

texts:
I made a simple administrator page lock in PHP and I was wondering how secure it was. I want to use this script to secure administrator pages for my portfolio site but I want it to be fairly secure.

<?php

/*
 * Array of authenticated users
 */

$users = [
  // Username => Password
  'admin' => 'password'
];

/*
 * Expiration time in seconds
 */

$expire = 30 * 60;

/*
 * We take care of the rest
 */

// Start the session
session_start();

// Last session activity time is greater than the set expiration time
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $expire)) {
  // Free all session variables
  session_unset();
  // Destroy all session variables
  session_destroy();
}

// Set last session activity time
$_SESSION['LAST_ACTIVITY'] = time();

// On form submission
if (isset($_POST['username'], $_POST['password'])) {
  // Reference username and password
  $username = $_POST['username'];
  $password = $_POST['password'];
  // Provided username exists
  if (array_key_exists($username, $users)) {
    // Provided password is verified
    if ($password == $users[$username]) {
      // Set the session user identifier
      $_SESSION['USER_ID'] = $username;
    }
  }
}

// User identifier is not present or is valid
if (!isset($_SESSION['USER_ID']) || !array_key_exists($_SESSION['USER_ID'], $users)) {
  // Render the form for authentication attempts
  echo '<form method="post">
<input type="text" name="username" placeholder="Username">

<input type="password" name="password" placeholder="Password">

<input type="submit">
</form>';
  // Don't allow any action until authentication is finished
  exit();
}

?>

I plan on adding things like halting the script for a few seconds depending on how many attempts were made from the current session.

Any suggestions or insights on if this is secure or how to make it more secure would be very helpful.


texts: HTML5 Parallax Scrolling utility using canvas

texts:
I have created a utility to create scrolling parallax backgrounds.

// Backgrounds as array of objects. canvas id, speed, image url
var bgs = [{
  id: 'sky',
  speed: 1,
  src: 'https://upload.wikimedia.org/wikipedia/commons/9/9f/Sky_back_layer.png'
}, {
  id: 'middle',
  speed: 3,
  src: 'https://upload.wikimedia.org/wikipedia/commons/8/8b/Vegetation_%28middle_layer%29.png'
}, {
  id: 'front',
  speed: 5,
  src: 'https://upload.wikimedia.org/wikipedia/commons/b/be/Ground_%28front_layer%29.png'
}];

// Create render background through Scenery
var Scenery = {
  bgs: [],
  // Initialize individual canvases and set images
  init: function(bgs) {
    var i = bgs.length - 1,j = 0;
    for (; i >= 0; i--,j++) {
      this.bgs[j] = {};
      this.bgs[j].cvs = document.getElementById(bgs[i].id);
      this.bgs[j].ctx = this.bgs[j].cvs.getContext('2d');
      this.bgs[j].img = document.createElement('img');
      this.bgs[j].img.src = bgs[i].src;
      this.bgs[j].left = 0;
      this.bgs[j].speed=bgs[i].speed;
    }
  },
  // According to scroll speed, render images in corresponding canvas
  // To have a seamless effect, render image twice
  scene: function() {
    var i = this.bgs.length - 1,
      left, w, h, bgNow, bgCtx;
    for (; i >= 0; i--) {
      bgNow = this.bgs[i];
      left = bgNow.left;
      w = bgNow.cvs.width;
      h = bgNow.cvs.height;
      bgCtx = bgNow.ctx;

      bgCtx.clearRect(0, 0, w, h);
      bgCtx.drawImage(this.bgs[i].img, -left, 0, w, h);
      bgCtx.drawImage(this.bgs[i].img, w - left, 0, w, h);
      this.bgs[i].left = (left + this.bgs[i].speed) % w;
    }

  }
};

// This handles looping . A wrapper around window.requestAnimationFrame
// Considers frame rate.
var Loop = {
  run: function(scene, fps) {
    this.scene = scene;
    this.frameInterval = 1000 / fps;
    this.lastTime = new Date().getTime();

    this.loop();
  },
  loop: function() {
    var now = new Date().getTime();
    var elapsed = now - this.lastTime;
    if (elapsed >= this.frameInterval) {

      this.scene();
      this.lastTime = now;
    }
    window.requestAnimationFrame(this.loop.bind(this));
  }
};

// Initialize scenery
Scenery.init(bgs);
// Run it
Loop.run(Scenery.scene.bind(Scenery), 60);

HTML

<div>
  <canvas id='sky'></canvas>
  <canvas id='middle'></canvas>
  <canvas id='front'></canvas>
</div>

Styles

div {
  position: relative;
}

canvas {
  position: absolute;
  left: 0;
  top: 0;
}

My question is, is there a better approach to pass Scenery.scene function into Loop.run()?


texts: Karger's min-cut algorithm implemented in python

texts:
I implemented Karger's algorithm with the function find_min_cut and it works, but I don't feel satisfied with the code I wrote.

from numpy import inf
from random import choice
from copy import deepcopy

# We use the karger method for finding the minimum cut in a graph.
# Each row of "original_Graph" needs to match a vertice and each element of
# the row corrispond to the vertices to which it's connected.
# In addition in the first row there needs to be the first vertice, the second
# row the second vertice and so on.
# You also need to input the number of times you want the random "find_cut" to
# be performed.

def find_min_cut(original_Graph, num_repeats):
    min_cut = inf
    for ith_repeat in range(1, num_repeats + 1):
        print ith_repeat, "th repeat"
        Graph = deepcopy(original_Graph)
        cut = find_cut(Graph)
        if cut < min_cut:
            min_cut = cut
    return min_cut

def find_cut(Graph):
    # list_vertices keeps the the list of vertices and can be used for
    # selecting a vertice in the graph by using list_vertices.index(vertice).
    # It basically helps to keep track of the vertices in the graph.

    list_vertices = range(1, len(Graph) + 1)

    # I contract the edges until there are only two vertices
    for num_contraction in range(len(Graph) - 2):
        contract_edge(Graph, list_vertices)
    return count_cut(Graph)

def contract_edge(Graph, list_vertices):

    # I choose randomly two vertices connected to select and edge.
    rand_vertice = choice(list_vertices)
    edge = [rand_vertice, choose_edge(Graph, rand_vertice, list_vertices)]

    unite_edge(Graph, edge, list_vertices)
    clean_graph(Graph, edge, list_vertices)

def count_cut(Graph):
    # When you finished contracting the number of connection between the two
    # vertices is the length of the row containing the connection of the
    # vertices
    return len(Graph[0])

def choose_edge(Graph, vertice, list_vertices):
    # I choose a random connected vertice
    return choice(Graph[list_vertices.index(vertice)])

def unite_edge(Graph, edge, list_vertices):
    new_vertice = list_vertices.index(edge[0])
    old_vertice = list_vertices.index(edge[1])

    # Extend the first vertice with the connection of the second
    Graph[new_vertice].extend(Graph[old_vertice])

    # delete the copied vertice both from the graph and the list of vertices
    del Graph[old_vertice]
    del list_vertices[old_vertice]

def clean_graph(Graph, edge, list_vertices):
    # I iterate over the vertices and save the index of the row matching
    # of each vertice.
    for vertice in list_vertices:
        index_vertice = list_vertices.index(vertice)
        # I substitute the vertice deleted in unite_edge with the remaining
        # one
        if edge[1] in Graph[index_vertice]:
            subtitute_all_elements(Graph, index_vertice, edge[1], edge[0])
        if vertice == edge[0]:
            # I remove the self-connection
            Graph[index_vertice] = filter(
                lambda a: a != edge[0], Graph[index_vertice])

def subtitute_all_elements(Graph, index_vertice, old, new):
    for i in range(len(Graph[index_vertice])):
        if Graph[index_vertice][i] == old:
            Graph[index_vertice][i] = new

So I'm asking for a review. I have some main point that I would like to have commented:

The quality of my comments. Are they clear enough? too many? or to little?
The variables names are good enough?
using deepcopy in find_min_cut is a bad choice? would you have done differently?
Are there ways that can make it faster?
Would you have approached the problem differently? If yes why?

If you have other suggestions or thoughts please tell.

edit.
An example of a graph is:

[[2, 3, 4, 7], [1, 3, 4], [1, 2, 4], [2, 3, 5], [4, 6, 7, 8], [5, 7, 8], [1, 5, 6, 8], [8, 5, 6, 7]]

the first list in the list corrispond to the vertice connected with the first vertice, the second list in the list corrispond to the vertice connected with the second vertice and so on. It is an undirected graph.


texts:
I'm trying to create a scraping API in Express. The API scrapes the different articles featured on the home page.

Here are the issues I'm trying to resolve:

My code's turning into a ton of jquery select statements. How can I resolve this / How can I simplify my code or extract functions from this giant mass?
Are my variable names clear enough?
Are there any Node conventions I'm not following? I've seen a lot of let and I'm using var. If I'm doing anything wrong let me know.

Here is the block of code I'm running:

var express = require('express');
var fs      = require('fs');
var request = require('request');
var cheerio = require('cheerio');
var app     = express();

app.get('/scrape', function(req, res){
  url = 'http://anawesomewebsite.com';

  request(url, function(error, response, html){
    if(!error){
      var $ = cheerio.load(html);

      var title, url, image;
      var articles = [];
      var article = { title : "", url : "", image_src : ""};

      //Get articles featured at top of page
      var i = 0;
      $(".articles li .img img").each(function(){
          var image_src = $(this).attr('src');
          article.image_src = image_src;
          articles[i] = article;
          i = i + 1;
      });

      i = 0;
      $(".articles li a[class='title']").each(function(){
         var title = $(this).text();
         var url = $(this).attr('href');
         article.title = title;
         article.url = "http://vegnews.com" + url;
         articles[i] = article;
         i = i + 1;
      });

      //Get articles featured at bottom of page
      var number_of_articles_beforehand = articles.length;
      i = number_of_articles_beforehand;

      $(".article .image img").each(function(){
        var image_src = $(this).attr('src');
        article.image_src = image_src;
        articles[i] = article;
        i = i + 1;
      });

      i = number_of_articles_beforehand;
      $(".article .image a").each(function(){
         var url = $(this).attr('href');
         article.url = url
         articles[i] = article;
         i = i + 1;
      })

      i = number_of_articles_beforehand;
      $(".article .title").each(function(){
        var title = $(this).text();
        article.title = title;
        articles[i] = article;
        i = i + 1;
      })

    }
    res.send(articles);
  })
})

app.listen('8081')
console.log('Magic happens on port 8081');
exports = module.exports = app;


texts:
I have just finished learning basic-intermediate Python subjects and wanted to test myself. This Battleship game is the third game i have written.

import random

def create_random_ship():
    return random.randint(0, 5), random.randint(0, 5)

def play_again():
    try_again = input("Wanna play again? <Y>es or <N>o? >: ").lower()
    if try_again == "y":
        play_game()
    else:
        print("Goodbye!")
        return

print("Welcome to the Battleship game!"
      "\nYour main objective is to find and destroy all the hidden ships on map!\n")

print("""\nIntroductions:
\nYou have 10 ammo and there are 3 hidden ships on map.
In order to hit them, you have to enter specific numbers for that location. For example:
For the first row and first column, you have to write 1 and 1.
I wish you good fortune in wars to come!\n""")

def play_game():
    game_board = [["O", "O", "O", "O", "O"],
                  ["O", "O", "O", "O", "O"],
                  ["O", "O", "O", "O", "O"],
                  ["O", "O", "O", "O", "O"],
                  ["O", "O", "O", "O", "O"]]

    for i in game_board:
        print(*i)

    ship1 = create_random_ship()
    ship2 = create_random_ship()
    ship3 = create_random_ship()
    ships_left = 3
    ammo = 10

    while ammo:
        try:
            row = int(input("Enter a row number between 1-5 >: "))
            column = int(input("Enter a column number between 1-5 >: "))
        except ValueError:
            print("Only enter number!")
            continue

        if row not in range(1,6) or column not in range(1, 6):
            print("\nThe numbers must be between 1-5!")
            continue

        row = row - 1 # Reducing number to desired index.
        column = column - 1 # Reducing number to desired index.

        if game_board[row][column] == "-" or game_board[row][column] == "X":
            print("\nYou have already shoot that place!\n")
            continue
        elif (row, column) == ship1 or (row, column) == ship2 or (row, column) == ship3:
            print("\nBoom! You hit! A ship has exploded! You were granted a new ammo!\n")
            game_board[row][column] = "X"
            ships_left -= 1
            if ships_left == 0:
                print("My my, i didn't know you were a sharpshooter! Congratz, you won!")
                play_again()
        else:
            print("\nYou missed!\n")
            game_board[row][column] = "-"
            ammo -= 1

        for i in game_board:
            print(*i)

        print(f"Ammo left: {ammo} | Ships left: {ships_left}")

    play_again()

if __name__ == "__main__":
    play_game()

What do you think? How can I make it better? What are my mistakes?


texts: Alternative session token implementation in flask

texts:
Here is my implementation of an alternative session token. The idea is to reset session_token every time get_id is called, so (I think) the session would be made less vulnerable to hijacks or similar attacks.

import os
from flask_login import UserMixin
from app import db, login_manager

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key = True)
    session_token = db.Column(db.Unicode)

    def get_id(self):
        self.session_token = os.urandom(64).decode('utf-8', 'ignore')
        return self.session_token

@login_manager.user_loader
def load_user(session_token):
    return User.query.filter_by(session_token=session_token).first()

I hope you can tell me...

if this really makes the session safer.
how can I handle unicode decoding more elegantly.
if it have any issues on stability.
if it have any issues on performance.


texts: App that Builds a list of "targets" for a Text-Based RPG using the games' API

texts:
all!

I am developing a web "app" with JavaScript and jQuery with the help of a couple of other libraries for ease of use.

Its purpose is to collect user ID's and to build a list of "attackable" targets for the game at https://torn.com

Details for the API can be found at https://api.torn.com, although I'm pretty sure it requires an account to do anything with it (needs an API Key, and I don't want to provide mine for security purposes)

The entirety of the site is on my gitlab instance

My biggest concern is whether or not I have created effective and efficient code to accomplish the purpose of the app. Specifically, the API call and data handling is what I am most concerned with here.

    $.get( url, function( data ) {
        var username = data.name;
        var userlevel = data.level;
        var userstatus = data.status.description;
        var liuser = $('<li/>')
        .addClass('userLevel')
        .text(userlevel)
        .appendTo(`ul.userListItem${value}`)
        var liname = $('<li/>')
        .addClass('userName')
        .text(username)
        .appendTo(`ul.userListItem${value}`);
        var listatus = $('<li/>')
        .addClass('userStatus')
        .text(userstatus)
        .appendTo(`ul.userListItem${value}`);
        var liattack = $('<li/>')
        .addClass('userAttack')
        .html(`<a href="https://www.torn.com/loader.php?sid=attack&user2ID=${value}" class="button" target="_blank">Attack!</a>`)
        .appendTo(`ul.userListItem${value}`);
        var liremove = $('<li/>')
        .addClass('userRemove')
        .html(`<a href="javascript:removeUser(${value})" type="button" class="button" id='removeuser${id}'>x</a>`)
        .appendTo(`ul.userListItem${value}`);
    });

This feels like a lot of work to do within a single API call. It works, and can be demo'd on the site it currently lives on: https://murdr.us

I'm also looking for a better input validation that can check for empty state or non-numbers entered and return an on-screen alert (rather than a browser alert as it currently shows).

here's the current validation method used:

function empty() {
    var x = $('input#useridValue').val();
    if (x == "") {
        alert("Enter a Valid User ID");
        return false;
    };
}

and the button that calls it:

$("button#submitUser").click(function() {
    if (empty() !== false ) {
    var tempid = parseInt($('input#useridValue').val());
    console.log(tempid)
    addID(tempid);
    $('input#useridValue').val("");
    }
});

I greatly appreciate your time, folks. Hopefully, some insight and optimization techniques may be devised from this.

Thanks, all.


texts: Prime power mathematical problem in Python

texts:
I have a mathematical problem about prime power. A number \$x\$ can be considered a prime power if \$x = p^k\$ where \$p\$ is a prime and \$k\$ is a non-negative integer. For example, \$81\$ is a prime power because \$81 = 3^4\$. Now, form a sequence of numbers in the following way. Start by taking a random number.

If the number is a prime power, end the sequence.
If the number is not a prime power, minus that number with the biggest prime power that's not more than the number itself. Do it over and over again until a prime power is met, then stop.

For example, 34 is not a prime power. Hence we minus it with the highest prime power that's not more than it which is \$32\$, hence \$34-32=2\$. \$2\$ is a prime power, so we stop. In this case, the length of the operation is 2 (because 34 -> 2).

Another example is \$95\$. \$95\$ isn't a prime power, so \$95-89=6\$. \$6\$ is also not a prime power, so we minus it again with the highest prime power, \$6-5=1\$. \$1\$ is a prime power (because \$2^0 = 1\$), so we stop. In this case, the length of the operation is 3 (because 95 -> 6 -> 1).

Known that:

1 is the smallest initial number that can be formed with a length of
1 operation.
6 is the smallest initial number that can be formed with
a length of 2 operations.
95 is the smallest initial number that can
be formed with a length of 3 operations.
360748 is the smallest
initial number that can be formed with a length of 4 operations.

I made an application using Python to find the smallest initial number that can be formed with a length of 5, 6 and 7 operations. It is using looping to solve the problem. However, to find the smallest initial number that can be formed with a length of 4 or more operations, the program takes a very very long time to run.

Is there any way I could improve my code to make the program to run much faster? I just want to focus on getting the number with 5, 6 and 7 operations.

from sympy.ntheory import factorint
def pp(q): #to check whether it is a prime power
    fact=factorint(q)
    p=int(list(fact.keys())[0])
    n=int(list(fact.values())[0])
    if q!=p**n:
        return False
    else:
        return True

a=[1,6][-1]

b=a*2
d=1
while d!=0:
    c=b-a
    if pp(b)==False and pp(c)==True:
        for i in range(b-1,c-1,-1):
            if i==c:
                d=0
            elif pp(i)==True:
                b=i+a
                break
    elif pp(b)==False:
        for i in range(b-1,c-1,-1):
            if i==c:
                b=b+a+1
            elif pp(i)==True:
                b=i+a
                break
    elif pp(b)==True:
        b=b+a
b


texts: Imitate Qt Quick's QQuickFramebufferObject, but do the syncing more tidily (with covariance)

texts:
I'm making a system similar to Qt Quick with its scenegraph. Since it's embedded within Qt Quick with its threading system, the items' Renderers should sync some data from their "parent" items at opportune moments, so this data can be used in the rendering thread, while the GUI thread mutates the "parent" item's data.

The relevant Qt Quick things that I'm (partially) imitating are:

base class QQuickFramebufferObject
base class QQuickFramebufferObject::Renderer
the function QQuickFramebufferObject::Renderer::synchronize() (not included in the sample code here, for brevity)

Now, in Qt's relevant examples, a class subclassing Renderer will have (roughly) the same member variables as its "parent" item, so it can sync data between the two places. But this means that the "synced" data in the Renderer (e.g. source - an image's source url) are going to live next to non-synced data, such as some an OpenGL texture id needed for the rendering. To keep things tidy, I have created a SyncedData class hierarchy instead. My design attempt looks like this (simplified):

// ###### BASE CLASSES

struct MyItem : public QObject {
    int x, y, w, h;
};

struct MyItemSyncedData {
    int x, y, w, h;
};

struct MyItemRenderer {
    virtual void render() { }

    virtual MyItemSyncedData* syncedData() {
        return lazyInstantiateSyncedData<MyItemSyncedData>();
    }
protected:
    // implementation helper for this class and subclasses
    template<class SyncedDataSubType>
    SyncedDataSubType* lazyInstantiateSyncedData() {
        if(m_syncedData == nullptr) {
            m_syncedData = new SyncedDataSubType();
        }
        return m_syncedData;
    }

private:
    MyItemSyncedData* m_syncedData = nullptr;
};

// ###### DERIVED CLASSES

struct MyImage : public MyItem {
    string source;
};

struct MyImageSyncedData : public MyItemSyncedData {
    string source;
};

struct MyImageRenderer : public MyItemRenderer {
    GLuint textureId; // non-synced stuff
    virtual void render() {
        // use this->syncedData()->source here
    }
    // covariant override
    virtual MyImageSyncedData* syncedData() {
        return lazyInstantiateSyncedData<MyImageSyncedData>();
    }
};

I see three disadvantages in this design:

seems maybe too complex for what it does
every subclass of MyItemRenderer has to include a trivial reimplementation of syncedData()
of course, the duplication of any values I want to sync, but I don't think that's gonna be avoidable.

If you're wondering about my motivation for reinventing the wheel by making a system similar to Qt Quick: see here.

Things I don't want critique on, because they're just to make the code shorter:

my use of struct instead of class
my use of public member variables (imagine they're Qt properties instead)
my use of plain pointers and skipping any deallocation
my skipping of the std:: prefix


texts: Provably fair coin flip system in Laravel

texts:
I made a provably fair 1v1 coin flip game in Laravel and I want to be sure it's safe (cannot be hacked) and that the outcome is random (50/50).

At first Player 1 starts the bet and the hash will be created. The hash is a SHA256 of the $secret, which will be revealed to the players after the game. This hash ensures that the game outcome depends on the client and not on the server (provably fair). Does it matter which hash type I use? Are they all equally safe?

$secret = str_random(40);
$bet = new Bet;
$bet->user_id = Auth::id();
$bet->amount = $amount;
$bet->secret_key = $secret;
$bet->secret_hash = hash('sha256', $secret);
$bet->save();

So after that, player 2 will be able to join player 1's bet. When player 2 accepts the bet, this is what happens:

$(document).delegate('.flipcoin-btn', 'click', function() {
    // When player 2 clicks the button
    SubmitFlipCoin($(this).attr('id'), CreateClientKey());
});

function CreateClientKey()
{
    var outStr = "", newStr;
    while(outStr.length < 20)
    {
        newStr = Math.random().toString(36).slice(2);
        outStr += newStr.slice(0, Math.min(newStr.length, (20 - outStr.length)));
    }
    console.log("Client string created: "+outStr.toUpperCase());
    return outStr.toUpperCase();
};

function SubmitFlipCoin(id, client)
{
    StopMoneyUpdate = 1;

    $.ajax({
        method: 'POST',
        url: flipcoin_link,
        data: {id: id, clientstr: client, _token: token},
        dataType: 'JSON',
    })
    .done(function(result) {
        if(result.hasOwnProperty("error")) {
            ShowBetError(''+result.error+'');
        }
    })
    .fail(function(error) {
        ShowBetError('An error occurred while flipping the coin, please try again.');
    });
}

As you can see, the client (player 2) generates a random string, which will be send to the server. The server will then make an HMAC hash of bet_id+clientstring with the $secret as key. The outcome of the game is determined by this HMAC hash. It takes the second number of the HMAC hash. If the result is 0 to 4 then player 1 wins, and if result is 5 to 9 player 2 will win.

$resulthash = hash_hmac('sha512', $request->clientstr."-".$bet->id, $bet->secret_key);
$resultnumber = filter_var($resulthash, FILTER_SANITIZE_NUMBER_INT);
if($resultnumber[1] < 5) {
    $result = 0;
}
else {
    $result = 1;
}

EDIT: I did some testing to see if the outcome is really 50/50 and it seems pretty accurate.

$dealer = 0;
$player = 0;
$times = 1000000;

for($i = 0; $i < $times; $i++) {
    $result = filter_var(hash('sha512', rand()), FILTER_SANITIZE_NUMBER_INT)[1];
    if($result < 5) {
        $dealer++;
    }
    else {
        $player++;
    }
}

echo "Dealer: ".$dealer/$times * 100;
echo "
Player: ".$player/$times * 100;

This was the outcome that I got:

Dealer: 49.9891
Player: 50.0109


texts: Sequence-based enumeration of permutations in lexicographic order

texts:
This is follow-up on
On Knuth's "Algorithm L" to generate permutations in lexicographic order,
where I presented the following method to enumerate all permutations of array elements
in lexicographic order:

extension Array where Element: Comparable {

    /// Replaces the array by the next permutation of its elements in lexicographic
    /// order.
    ///
    /// It uses the "Algorithm L (Lexicographic permutation generation)" from
    ///    Donald E. Knuth, "GENERATING ALL PERMUTATIONS"
    ///    http://www-cs-faculty.stanford.edu/~uno/fasc2b.ps.gz
    ///
    /// - Returns: `true` if there was a next permutation, and `false` otherwise
    ///   (i.e. if the array elements were in descending order).

    mutating func permute() -> Bool {

        // Nothing to do for empty or single-element arrays:
        if count <= 1 {
            return false
        }

        // L2: Find last j such that self[j] < self[j+1]. Terminate if no such j
        // exists.
        var j = count - 2
        while j >= 0 && self[j] >= self[j+1] {
            j -= 1
        }
        if j == -1 {
            return false
        }

        // L3: Find last l such that self[j] < self[l], then exchange elements j and l:
        var l = count - 1
        while self[j] >= self[l] {
            l -= 1
        }
        swap(&self[j], &self[l])

        // L4: Reverse elements j+1 ... count-1:
        var lo = j + 1
        var hi = count - 1
        while lo < hi {
            swap(&self[lo], &self[hi])
            lo += 1
            hi -= 1
        }
        return true
    }
}

This question is about using that method to create a Swift Sequence with all permutations, so that one can
simply enumerate these with for .. in loops and related techniques. My first approach is to use
the "type erasers" AnySequence and AnyIterator, which leads to this simple
implementation:

func permutations<T: Comparable>(of a: [T]) -> AnySequence<[T]> {
    var current = a.sorted()
    var done = false
    return AnySequence {
        return AnyIterator {
            if done { return nil }
            defer { done = !current.permute() }
            return current
        }
    }
}

Example usage:

for p in permutations(of: [3, 2, 1]) {
    print(p)
}

let allPerms = Array(permutations(of: ["B", "A", "C"]))
print(allPerms)

So this is easy to use, but what about performance? Here my benchmark code
(on a 1.2 GHz Intel Core m5 MacBook, compiled in Release mode):

let N = 10
var count = 0
let start = Date()
for _ in permutations(of: Array(1...N)) { count += 1 }
let end = Date()
print(count, end.timeIntervalSince(start))

This takes about 1.3 seconds, i.e. it is much slower than calling permute() on a mutable
array in a loop, which takes only 0.03 seconds (see On Knuth's "Algorithm L" to generate permutations in lexicographic order).

It gets a bit better if we implement our own sequence type instead of using the
type erasers:

struct PermutationSequence<T: Comparable>: Sequence, IteratorProtocol {
    private var current: [T]
    private var done: Bool

    init(elements: [T]) {
        self.current = elements.sorted()
        self.done = false
    }

    func makeIterator() -> PermutationSequence {
        return self
    }

    mutating func next() -> [T]? {
        if done { return nil }
        let retval = current
        done = !current.permute()
        return retval
    }
}

Benchmark:

let N = 10
var count = 0
let start = Date()
for _ in PermutationSequence(elements: Array(1...N)) { count += 1 }
let end = Date()
print(count, end.timeIntervalSince(start))

which takes about 0.8 seconds.

All feedback is welcome. In particular I am interested in making Sequence-based
enumeration of all permutations as fast as possible.


texts: LINQ SQL query to display the status of tracked computers

texts:
This is my existing LINQ SQL.  At the moment it works, however the using the coalescing operator for null results on the "let" clauses make me feel like I'm violating some sort of unwritten rule.  Is there a better way?

Also, as this is on a web server, I don't know if this should be set static or not. Methinks not. But how do I get around that? It winds up being bound to a GridView.

public static List<TrackingComputer> TrackingBoardPCsgroup(string groupName)
    {

        using (dbiemrDashboardDataContext db = new dbiemrDashboardDataContext())
        {

            var query =
     (from t in TrackingBoardPCs()
      where t.TrackingGroup == groupName
      join p in db.GetTable<tblTBHealthPing>() on t.ComputerAsset equals p.ComputerAsset
      into pingInfo
      join h in db.GetTable<tblTBHealthHeartbeat>() on t.ComputerAsset equals h.ComputerAsset
      into heartbeatInfo
      let p = pingInfo.OrderByDescending(p => p.HealthPingTime).DefaultIfEmpty().First() ?? new tblTBHealthPing() { ComputerAsset = "Not Found", HealthPingResult = false, HealthPingTime = DateTime.Now}
      let h = heartbeatInfo.OrderByDescending(p => p.HealthHeartbeatTime).DefaultIfEmpty().First() ?? new tblTBHealthHeartbeat(){ ComputerAsset = "Not Found", HealthCurrentUser = "Not Found", HealthCurrentWindow = "Not Found", HealthHeartbeatTime = DateTime.Now, HealthUptime = string.Empty}
      let tc = new TrackingComputer
      {
          ComputerName = t.ComputerAsset,
          IPAddress = t.ComputerIP,
          Location = t.Location,
          Pingable = p.HealthPingResult ?? false,
          PingTime = p.HealthPingTime ?? DateTime.Now.AddDays(-100),
          Username = h.HealthCurrentUser ?? "Not Found",
          CurrentWindow = h.HealthCurrentWindow ?? "Not Found",
          Uptime = h.HealthUptime ?? "Not Found",
          HeartbeatTime = h.HealthHeartbeatTime ?? DateTime.Now.AddDays(-100)
      }
      orderby tc.Pingable
      select tc).ToList<TrackingComputer>();

            return query;

        }

    }


texts: Extracting data from a Word document is too slow

texts:
I have a 100page long .docx format document. I'm using a macro written in VBS to extract some information and then just generate a table from them.  I iterate through the paragraphs and store the found strings in 3 separate arrays.

However, the loop is unreasonably slow. It takes 3 min to complete on a relatively fast computer. Can you take a look at it and tell me what causes this slowness?

'TODO : Add checks, exception handling, dynamic user options, probes, style checks, and fix slowness.

Sub genTable()

Dim objDoc

'''''''''''''''''''''Modify these''''''''''''''''
Dim ColumnName1, ColumnName2, ColumnName3, magicString
ColumnName1 = "foo1"
ColumnName2 = "foo2"
ColumnName3 = "foo3"
magicString = "ASD321: " ' we search for this string

Set objDoc = ActiveDocument ' Because we run inside of word as macro
''''''''''''''''''''''''''''''''''''''''''''''''''

Const MAX = 200 ' using fixed sized arrays, mod this if you'll have more than 200 entries.
Dim vulnerabilityArr(MAX) ' initializing the arrays
Dim severityArr(MAX)
Dim paragraphArr(MAX)

Dim counter ' will count the processed entries in this
counter = 0

Dim currParagraph ' will be set in loop
Dim tmpArray() As String ' for splitting
    For pIndex = 1 To objDoc.Paragraphs.Count ' THIS LOOP IS SLOW
        currParagraph = objDoc.Paragraphs(pIndex)
        currParagraph = Left(currParagraph, Len(currParagraph) - 1) 'remove junk character
        If InStr(1, currParagraph, magicString) > 0 Then ' assuming this string is always present and the other two target data is near it
            tmpArray = Split(currParagraph) ' extract level
            currParagraph = objDoc.Paragraphs(pIndex - 1) 'assuming the previous paragraph is the vuln. name

            'Storing the 3 extracted data
            vulnerabilityArr(counter) = currParagraph
            severityArr(counter) = tmpArray(1)
            paragraphArr(counter) = objDoc.Paragraphs(pIndex - 1).Range.ListFormat.ListString ' for some weird reason I cant use currParagraph here

            counter = counter + 1 ' adjusting index
        End If
    Next pIndex

objDoc.Tables.Add objDoc.Paragraphs(objDoc.Paragraphs.Count).Range, counter, 3, True, True
Set objTable = objDoc.Tables(objDoc.Tables.Count) 'select last table

objTable.Cell(1, 1).Range.Text = ColumnName1
objTable.Cell(1, 2).Range.Text = ColumnName2
objTable.Cell(1, 3).Range.Text = ColumnName3

For RowIndex = 0 To counter
    objTable.Cell(RowIndex, 1).Range.Text = paragraphArr(RowIndex)
    objTable.Cell(RowIndex, 2).Range.Text = vulnerabilityArr(RowIndex)
    objTable.Cell(RowIndex, 3).Range.Text = severityArr(RowIndex)
    Next
    RowIndexy = RowIndex + 1

objTable.AutoFormat (25)

End Sub


texts: Execute script on remote host and obtain variables on localhost

texts:
This executes a predefined script on a remote host, and somehow retrieve variable values without affecting STDOUT and STDERR.

My idea was to encode the data in JSON, write it to a file, then read the data in a separate request.

The cons of this method are that:

I would need to add the following code (file_put_contents) to the bottom of every script.
It requires a separate request (albeit, a pretty light request)

This is a dumbed down example, but inside the script to be run remotely:

<?php
$data = array(...);
$json = json_encode($data);
file_put_contents('tmp.json', $json);

On the local side:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('php script.php');
$json = $ssh->exec('cat tmp.json');

I'm just looking for some input or alternative ways of doing this.


texts: Check string(line) in a file and send email

texts:
I want to check some lines from a log file [check msyql replication slave status log] named "status.txt" (size is always about 3-4 KB):

  Slave_IO_Running: Yes
  Slave_SQL_Running: Yes

If any of these two line's value is 'No' then email is sent to alert@example.com.  These two lines are unique and both occur only once.

#!/usr/bin/python
import smtplib
import os
import email.Utils
from email.mime.text import MIMEText
import sys
i=0
for line in open("status.txt"):
    if "Slave_IO_Running: Yes" in line:
        print "match1",line
        i=i+1
    else:
        pass

for line2 in open("status.txt"):
    if "Slave_SQL_Running: Yes" in line2:
        i=i+1
    else:
        pass
print i

if i<2:
    msg=MIMEText("Mysql not running")
    fromaddr="root@DBausit.com"
    toaddr="alert@example.com"
    server = smtplib.SMTP('localhost')
    server.set_debuglevel(1)
    server.sendmail(fromaddr, [toaddr], msg.as_string())
    server.quit()
else:
    print "mysql running OK"

Please review my code.

Contents of "status.txt" file:

    Relay_Log_Pos: 195294327
        Relay_Master_Log_File: web01-bin.000001
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
mysql,information_schema,cphulkd,eximstats,horde,leechprotect,logaholicDB_web01,performance_schema,roundcube,whmxfer
           Replicate_Do_Table:
       Replicate_Ignore_Table:


texts: Shortcut script for elusive grep command

texts:
This is an example of my filesystem:

/code/

internal/

dev/
main/

public/

dev/
main/
release/

tools/

/code/internal/dev/, /code/public/dev/ and /code/tools/ contain subdirectories for multiple projects. I work almost exclusively in the dev branches of /code/internal/ and /code/public/, and often I want to search for a text string in those directories along with /code/tools/ (which has no branches). In these instances I run a command like this:

grep -I -r FooBar /code/internal/dev/ /code/public/dev/ /code/tools/

Additionally, sometimes I am only interested in certain file types. Then the command becomes:

grep -I -r FooBar /code/internal/dev/ /code/public/dev/ /code/tools/ | grep .c:\|.h:

I usually forget this command between usages and end up having to relearn it. To alleviate that problem, I created a script - which I would appreciate feedback on :)

search() {
    local t
    local OPTIND
    local pattern
    local files
    local types

    if [ $1 = --help ]; then
        echo "Usage: search [OPTION] ... PATTERN [FILE] ..."
        echo "Search for PATTERN in each FILE."
        echo "Example: search -t c -t h 'hello world' /code/internal/dev/ /code/public/dev/"
        echo
        echo "Output control:"
        echo "  -t    limit results to files of type"
        return
    fi

    while getopts ":t:" opt; do
        case $opt in
            t) t=(${t[@]} $OPTARG);; # create an array
        esac
    done
    shift $((OPTIND-1))

    pattern=$1
    files=${@:2}

    if [ -n "$t" ]; then
        # cast the array to a string
        types=${t[@]}

        # convert the string to a pattern usable by grep
        # example: "c h" becomes ".c:\|.h:"
        types=.${types// /':\|.'}:

        grep -I -r $pattern $files | grep $types
    else
        grep -I -r $pattern $files
    fi
}

With this and a couple more shortcut scripts, I can (relatively) quickly find anything I'm looking for:

search-all-code() {
    search $@ /code/internal/dev/ /code/public/dev/ /code/tools/
}

Aside: I realize some versions of grep support --include and --exlude options, but the version of grep I'm stuck with doesn't.


texts: Buy once and sell once for maximum profit

texts:
Suppose we have stock price history, and we are allowed to buy only once and sell only once. The problem is to find the maximum profit we can make. Here is my code that I tested for basic test cases. I'm wondering if there are possible improvements for logic correctness.

My major idea is to keep record of in history minimal price, and determine if sell today (with the purchase of historical minimal price), whether we can make a larger profit.

prices = [100, 113, 110, 85, 105, 102, 86, 63, 81, 101, 94, 106, 101, 79, 94, 90, 97]
result = 0
minSofar = prices[0]
for i in range(1, len(prices)):
    minSofar = min(minSofar, prices[i])
    result = max (result, prices[i] - minSofar)

print result


texts: Guess the number game using jupyter notebook

texts:
I made a number guessing game in Python 3 using jupyter notebook. I would appreciate it a lot if I could get some feedback on my code.

from random import randint
randnumb = randint(1,100)
guesses = 0
maxGuesses = 5

while guesses < maxGuesses:
    personInput = int(input('What is your guess? '))
    guesses = guesses + 1

    if personInput == randnumb:
        print()
        print('You won! It took you', guesses, 'guess(es)!')
        break

    if personInput > randnumb and guesses != maxGuesses:
        print('Guess lower', '(', maxGuesses - guesses,'guess(es) left)')
        print()

    if personInput < randnumb and guesses != maxGuesses:
        print('Guess higher', '(', maxGuesses - guesses,'guess(es) left)')
        print()

    if guesses == maxGuesses and personInput != randnumb:
        print()
        print('You lost! You ran out of your guesses!')
        print('The answer was', randnumb, '!')


texts:
EDIT:

Function is returnted to JClass Text.  Prototypes hold non instance members (statics).  No privacy.  Privacy requires self executing methods.

var Text = function( form_name )
{
    this.text_array = document.forms[form_name].elements;
};

Text.prototype.patterns =
{
    prefix_url: /^http:\/\//,
    url:        /^.{1,2048}$/,
    tweet:      /^.{1,40}$/,
    title:      /^.{1,32}$/,
    name:       /^.{1,64}$/,
    email:      /^.{1,64}@.{1,255}$/,
    pass:       /^.{6,20}$/
};

Text.prototype.pattern = function( type )
{
    return this.patterns[type].exec( this.text_array[type].value );
};

Text.prototype.patternAdd = function( type )
{
    return this.patterns[type].exec( this.text_array.url.value );
};

Text.prototype.same = function()
{
    return ( (this.text_array.email.value) === (this.text_array.email1.value) );
};

Text.prototype.emptyUser = function()
{
    var element;
    for ( element in this.text_array )
    {
        if( this.text_array[element].value === '' )
        {
            return 0;
        }
    }
    return 1;
};

/**
 *      Text End
 */


texts:
I need to lock on my AesManaged instance _Aes to call CreateDecryptor() however the CreateDecryptor() method is not thread safe and this function could be called by multiple threads. Is this the correct way to create a disposable object while needing to use a lock on the parent creating the object?

byte[] encryptedTextBlob = GetEncryptedTextBlob();

ICryptoTransform decryptor = null;
lock(_Aes)
{
    decryptor = _Aes.CreateDecryptor();
}

using (decryptor)
using (var encryptedStream = new MemoryStream(encryptedTextBlob))
using (var decrypedStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read))
using (var textReader = new StreamReader(decrypedStream))
{
    return textReader.ReadToEnd();
}


texts: Accessing files in a child directory in Python 2.7.x

texts:
I have written the below script for use in Python 2.7.x. In essence, I want the script to access a folder contained within the directory the script is and then add all files contained within to a list. I'm then looking to open these files using the csv module and process each line for now.

My script works fine as below but it just seems to be a long-winded way to access the content of files stored in a child directory.

Any suggestions to improve it?

import os
import csv

child_files = []
mypath = "./child_directory/"
onlyfiles = [f for f in os.listdir(mypath) if os.path.isfile(os.path.join(mypath, f))]
for f in onlyfiles:
    file_path = os.path.relpath(f)
    x = os.path.join(mypath, file_path)
    child_files.append(x)
    print x

for f in child_files:
    with open(f, 'rb') as x:
        reader = csv.reader(x)
        for row in reader:
            print row

I'd also be keen to only add '.csv' files contained within the child directory. I can work on this upon a review of my script unless someone can suggest a pythonistic method of incorporating this.


texts: Double event listener for single function

texts:
With your help in this question,
I've got this code to show the pop-up, and than hide it when close button is clicked:

<script>
    var applycouponPopupId = "popup-wrapper";
    window.addEventListener("load", function() {
        document.getElementById(applycouponPopupId).classList.add("modal-overlay_visible");
    });
    document.addEventListener('click', function(e) {
        if (!e.target.classList.contains("modal-overlay__close")) return;
        document.getElementById(applycouponPopupId).classList.remove("modal-overlay_visible");
    });
</script>

Now i need to change the code to close the pop-up on any click or scroll.
According to this answer, i converted code to the following:

<script>
    var applycouponPopupId = "popup-wrapper";
    window.addEventListener("load", function() {
        document.getElementById(applycouponPopupId).classList.add("modal-overlay_visible");
    });

    function mouseMoveHandler() {
        document.getElementById(applycouponPopupId).classList.remove("modal-overlay_visible");
    }

    ("click scroll".split(" ")).forEach(function(e) {
        document.addEventListener(e, mouseMoveHandler, false);
    });
</script>

Please tell if i did everything right.


texts: Passing a DTO into a static domain 'Create' method

texts:
I'm wondering if it's bad practice to couple my DTO to my domain object like this and pass the object itself into Create(). Is it better to just give the parameters needed to perform the creation?

public static Playlist Create(PlaylistDto playlistDto, IUserManager userManager, IPlaylistManager playlistManager)
{
    Playlist playlist = new Playlist
        {
            Id = playlistDto.Id,
            Items = PlaylistItem.Create(playlistDto.Items, playlistManager),
            Sequence = playlistDto.Sequence,
            Title = playlistDto.Title,
            User = userManager.Get(playlistDto.UserId)
        };

    return playlist;
}


texts:
I want to import some data to a 2-D vector. The data type is double like 5.8774718e-39, and the size is 128*3300. Now I make a method for it, but I think it's a bit slow. Could this efficiency be improved?

int main()
{
    ifstream ifs("..//pre.txt");
    vector<vector<double>> data_all(128);
    stringstream buffer;
    buffer << ifs.rdbuf();
    string contents = buffer.str();
    string::size_type pos1 = 0, n = 0;
    int i = 0;
    while ((pos1 = contents.find_first_of("+-.0123456789e", pos1)) != string::npos)
    {
        auto pos2 = contents.find_first_not_of("+-.0123456789e", pos1);
        n = pos2 - pos1;
        double d = stod(contents.substr(pos1, n));
        data_all[i].push_back(d);
        pos1 += n;
        if ((i != 127) && (contents[pos1] == '\n'))
            ++i;
    }
}


texts: Power menu (Shutdown, Reboot, Sleep) in ELISP

texts:
I've written an interactive function which lets me shudown, reboot my machine as well as put it to sleep.

I'm using emacs and I'm just starting out getting into ELISP programming. As I'm a total beginner, I'd like to know what you would do differently in the following code to make it better, lighter and so on. Many thanks in advance.

(defun db/power-menu ()
  "Interactive menu for shutdown, reboot or sleep."
  (interactive)
  (let ((actions '("Shutdown" "Reboot" "Sleep")))
    (setq action (ivy-completing-read "What do you want to do?" actions ))
    (if (y-or-n-p (concat "Execute " action "? Unsaved progress will be lost. "))
        (let ((default-directory "/sudo::"))
          (cond ((equal action "Shutdown")
                 (shell-command "systemctl poweroff"))
                ((equal action "Reboot")
                 (shell-command "systemctl reboot"))
                ((equal action "Sleep")
                 (shell-command "systemctl suspend")))))))


texts: Calculate number of words and characters (/statistics) from an HTML Textarea

texts:
var textarea = document.getElementById("textarea"),
  statusBar = document.getElementById("status-bar");
    function updateStatusBar() {
      var text = textarea.value,
        chars = text.length,
        words = text.split(/\b\S+\b/g).length - 1,
        lines = text.split("\n").length;
      statusBar.value = lines + " lines, " + words + " words, " + chars + " characters";
    }


texts: Optimising multiple streams to single loop

texts:
I am trying to find the best way to optimise the converters below to first follow the flow I call convertAndGroupForUpdate, which triggers the conversions and relevant mappings.

Any help to optimise this code would be massively appreciated.

public List<GroupedOrderActionUpdateEntity> convertAndGroupForUpdate(List<SimpleRatifiableAction> actions) {
    List<GroupedOrderActionUpdateEntity> groupedActions = new ArrayList<>();

    Map<String, List<SimpleRatifiableAction>> groupSimple = actions.stream()
        .collect(Collectors.groupingBy(x -> x.getOrderNumber() + x.getActionType()));

    groupSimple.entrySet().stream()
        .map(x -> convertToUpdateGroup(x.getValue()))
        .forEachOrdered(groupedActions::add);

    return groupedActions;
}

public GroupedOrderActionUpdateEntity convertToUpdateGroup(List<SimpleRatifiableAction> actions) {
    List<OrderActionUpdateEntity> actionList = actions.stream().map(x -> convertToUpdateEntity(x)).collect(Collectors.toList());

    return new GroupedOrderActionUpdateEntity(
        actions.get(0).getOrderNumber(),
        OrderActionType.valueOf(actions.get(0).getActionType()),
        actions.get(0).getSource(),
        12345,
        actions.stream().map(SimpleRatifiableAction::getNote)
            .collect(Collectors.joining(", ", "Group Order Note: ", ".")),
        actionList);
}

public OrderActionUpdateEntity convertToUpdateEntity(SimpleRatifiableAction action) {
    return new OrderActionUpdateEntity(action.getId(), OrderActionState.valueOf(action.getState()));
}


texts: Printing contents of list with indices from other list

texts:
I have two lists: L stores some values and P holds values that are indices in the first list that should be printed. Lists are sorted in ascending order. Error-checking can be ignored, and both lists are valid and values are valid.

Do I understand correctly, that since I always continue from the place I ended at, and since the values in both lists only increase, the cost of this operation is \$O(n)\$, since I only iterate over the list once?

I'd like to clean up the code. For example, is there a way to get the current index from the iterator, that would remove two additional int variables?

#include <stdio.h>
#include <iostream>
#include <list>

using std::list;

void printLots(const list<int> &l, const list<int> &p);

int main(int argc, const char * argv[]) {

    list<int> listL;
    listL.push_back(2);
    listL.push_back(4);
    listL.push_back(6);
    listL.push_back(8);
    listL.push_back(10);
    listL.push_back(12);
    listL.push_back(14);
    listL.push_back(16);
    listL.push_back(18);
    listL.push_back(20);

    list<int> listP;
    listP.push_back(0);
    listP.push_back(9);

    printLots(listL, listP);
}

void printLots(const list<int> &l, const list<int> &p) {

    auto lIterator = l.begin();
    auto pIterator = p.begin();

    int lIndex = 0;
    int pIndex = 0;

    bool finished = false;

    while (!finished) {
        int indexToPrint = *pIterator;

        while (lIndex != indexToPrint) {
            lIndex++;
            lIterator++;
        }

        std::cout << *lIterator << std::endl;
        pIndex++;
        pIterator++;

        if (pIterator == p.end()) {
            finished = true;
        }
    }
}


texts:
Instead of using multiple setter functions within a class like

public function setAction()
public function setMethod()

etc

I've been using a method from a base class that all other classes have access to.

public function set_properties($properties) {

    foreach ($properties as $key => $value) {
    $this->$key = $value;
    }
}

So I can just use it like so

$Class->set_properties(array('action' => 'page.php', 'method' => 'get'));

Is this a bad practice that I'm getting into or is this an okay way of setting properties?


texts: NSAssert or NSLog in defaults switch case

texts:
I am wondering if I should use NSLog(@"Switch out of range") or NSAssert(FALSE,@"Switch out of range"); in the following example:

typedef enum {
    kSectionFavoriteCarpark,
    kSectionPromotions,
    SectionsEnumCount
} SectionsEnum;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case kSectionFavoriteCarpark:
            return self.locationFavoritesKeyArr.count;
        case kSectionPromotions:
            return self.promotionCarparks.count;
        default:
            DLog(@"index out of switch range");
            return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.promotionCarparks.count > 0) {
        return SectionsEnumCount;//one for user defined positions one for favorite parkings
    }
    else {
        return SectionsEnumCount-1;
    }
}


texts:
This module allows to parse indented text file into Map from node to child nodes identified by Coordinate. This module seems way too complex - mainly because of managing stack that allows to "jump back" with decreasing indentation. How can I redesign it?

sample input:

a
 b
 c
  d
   e
 f

produces:

*Parse> parse tree
fromList [("a",["f","c","b"]),("c",["d"]),("d",["e"])]

implementation:

module Parse where
import System.Environment (getArgs)
import Data.List (find, isInfixOf, intercalate)
import Data.Char (isAlpha)
import Control.Lens ((&))
import Data.List.Split (splitWhen)
import Control.Arrow
import qualified Data.Map.Strict as Map
import Data.Maybe
import Debug.Trace
import Control.Applicative

type Coordinate = String

parse :: String -> Map.Map Coordinate [Coordinate]
parse = snd . go
  where
    go = foldl addDependency ([], Map.empty) . filter ((>0) . length) . lines

addDependency (stack, acc) line = if null stack then
                                   (,) [(0, line)] $ Map.singleton line []
                                   else let children = fromMaybe [] . flip Map.lookup acc
                                            lineDepth = countIndent line
                                            indent = signum $ lineDepth - (fst . head $ stack)
                                            coord = toCoordinate line
                                            addChild c = Map.insert c (coord : children c) acc
                                            parent = tail stack
                                        in
                                         case indent of
                                           0 -> (,) ((lineDepth,coord):parent) $ addChild (snd . head $ parent)
                                           1 -> (,) ((lineDepth,coord):stack) (addChild $ snd . head $ stack)
                                           _ -> let newStack = back stack lineDepth
                                                    newHead = snd . head $ newStack
                                                     in (,) ((lineDepth,coord):newStack) (addChild newHead)

back stack@((i,c):ss) indent = if indent > i then stack else back ss indent
toCoordinate = dropWhile (not . special)
special = (||) <$> isAlpha <*> (=='(')
countIndent = length . takeWhile (not . special)


texts:
I wanted to write a program that takes from standard input an expression without left parentheses and prints the equivalent infix expression with the parentheses inserted. For example, given the input
1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )

the program should print
( ( 1 + 2 ) * ( ( 3 - 4 ) * ( 5 - 6 ) ) )

My solution is not best optimized. So, I am looking for suggestions on how to improve/optimize it.
import java.util.Scanner;
import java.util.Stack;

public class ParenthesesCompleter {

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        String line = sc.nextLine();

        Stack<Character> operators = new Stack<Character>();
        Stack<String> operands = new Stack<String>();

        for (int i = 0; i < line.length(); i++)
        {
            switch (line.charAt(i))
            {
                case '+':
                case '-':
                case '*':
                case '/':
                    // Operator case
                    operators.push(line.charAt(i));
                    break;
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    // "operand" case
                    String s = "";
                    s += line.charAt(i);
                    operands.push(s);
                    break;
                case ')':
                    // closing paren case
                    String a = operands.pop();
                    String b = operands.pop();
                    char c = operators.pop();

                    StringBuilder buf = new StringBuilder();
                    buf.append("(");
                    buf.append(b);
                    buf.append(c);
                    buf.append(a);
                    buf.append(")");

                    operands.push(buf.toString());
                    break;
                case ' ':
                    break;
            }
        }
        // case for no outer parentheses
        while (!operators.isEmpty()) {
            String a = operands.pop();
            String b = operands.pop();
            char c = operators.pop();

            StringBuilder buf = new StringBuilder();
            buf.append(b);
            buf.append(c);
            buf.append(a);

            operands.push(buf.toString());
        }
        System.out.println(operands.pop());
        sc.close();
    }
}


texts:
After doing a simple coding challenge regarding strings, I realized that I have forgotten a few things about them. As such, I decided to do a few basic string manipulation practices for myself.

One of them, which I found in my old Java assignments, was a word guessing game. Very small, nothing special. As such, I decided to re-implement it. The game works as follows: You enter the "secret" word, and then you have 10 tries to guess it.

import java.util.Scanner;

public class guess {

    public static void main(String[] args) {
        int tries = 0;

        boolean iterated = false;
        String temp = "";
        String holder = "";

        Scanner keyboard = new Scanner(System.in);
        System.out.println("Enter your secret word:");
        String word = keyboard.nextLine();

        do {
            System.out.println("Enter your letter guess");
            String guess = keyboard.nextLine();

            for(int i = 0; i < word.length(); i ++) {
                if (guess.equals(Character.toString(word.charAt(i)))) {
                    if(!iterated)
                        temp += Character.toString(word.charAt(i));
                    else {
                        holder = Character.toString(temp.charAt(i)).replace("-", guess);
                        temp = temp.substring(0, i) + holder + temp.substring( i + 1, temp.length());
                    }
                } else {
                    if(!iterated) {
                        temp += "-";
                    }
                }
            }
            tries++;
            iterated = true;
            System.out.println(temp);
            if(temp.equals(word)) {
                System.out.println("You guessed correctly!");
                break;
            }
        }while (tries < 10);

    }
}


texts: Learning nested for loops in Python with Pig Latin translator

texts:
I've been trying to learn Python for a bit now. I've taken a few courses, but I've found that I've been going about them wrong and had allowed them to "hold my hand" too much. I'm trying to build projects on my own and thought I would start off small. My third or so project was this Pig Latin translator and I wanted to get my head wrapped around nested for loops.

I know this code is super sloppy and I would love to have some feedback on how to make it more efficient or if there are any glaring mistakes I missed.

vowels = 'AaEeIiOoUuYy'
sentence = raw_input("Enter word to be translated: ")
pig_word = ""
# breaks up the words in the string and puts them into a list
sentence_list = sentence.split()
pig_list = []

def pig_latin_trans():
    global pig_word, pig_list
    for item in sentence_list:
        count = 0
        for letter in vowels:
            if letter == item[0]:
                pig_word = str(item) + "way"
                pig_list.append(pig_word)
                break
            if letter != item[0] and count < len(vowels):
                count += 1
            if letter != item[0] and count == len(vowels):
                pig_word = str(item[1:]) + str(item[0]) + "ay"
                pig_list.append(pig_word)
    print " ".join(pig_list)

pig_latin_trans()


texts:
I have implemented a Merge sort in Python 3, and it works well. If anything needs to be improved, I would appreciate the criticism.

def merge_sort(nums):

    if len(nums) == 1:
        return

    middle_index = len(nums) // 2

    left_half = nums[:middle_index]
    right_half = nums[middle_index:]

    merge_sort(left_half)
    merge_sort(right_half)

    i = 0
    j = 0
    k = 0

    while i<len(left_half) and j<len(right_half):
        if left_half[i] < right_half[j]:
            nums[k] = left_half[i]
            i = i + 1
        else:
            nums[k] = right_half[j]
            j = j + 1

        k = k + 1

    while i<len(left_half):
        nums[k] = left_half[i]
        k = k + 1
        i = i + 1

if __name__ == "__main__":

   nums = [-3,-2,-1,1,2,1,0,-1,-2,-3]
   merge_sort(nums)
   print(nums)


texts: Implementing Multi Producer Multi Consumer Simple Thread Safe Class

texts:
I am learning C# and in the process I am trying to implement a multi producer consumer thread safe class. Can you please code review and point me to any mistakes I have made and improvements I can make? I understand there would be libraries and other thread safe queue objects which would provide me the functionality which I am trying to implement, but the very reason I am doing this myself is to learn how threads and thread safe queues are coded and managed. My idea is to achieve maybe an under-optimized but correctly working code.
//simple thread safe many producer many consumer class
class ProducerConsumer<Task>
{
    public delegate void ConsumerCallback(Task t);

    protected bool keepRunning = false;
    protected Queue<Task> taskQueue = null;
    protected Thread[] consumerThreads = null;
    protected ConsumerCallback clientConsumerMethodCB = null;

    public ProducerConsumer(ConsumerCallback clientConsumerMethod, int consumerThreadsCount)
    {
        keepRunning = true;
        consumerThreads = new Thread[consumerThreadsCount];
        for (int i = 0; i < consumerThreadsCount; i++)
        {
            consumerThreads[i] = new Thread(ConsumerThreadFunction);
        }

        for (int i = 0; i < consumerThreadsCount; i++)
        {
            consumerThreads[i].Start();
        }

        taskQueue = new Queue<Task>();
        clientConsumerMethodCB = clientConsumerMethod;
    }

    public void Produce(Task t)
    {
        lock (taskQueue)
        {
            taskQueue.Enqueue(t);
        }

        Monitor.PulseAll(taskQueue);
    }

    protected void ConsumerThreadFunction()
    {
        Queue<Task> holdTaskQueueItem = new Queue<Task>();
        while (keepRunning)
        {
            while (taskQueue.Count <= 0)
            {
                Monitor.Wait(taskQueue);
            }

            lock (taskQueue)
            {
                if(taskQueue.Count > 0)
                {
                    holdTaskQueueItem.Enqueue(taskQueue.Dequeue());
                }
            }

            if(holdTaskQueueItem.Count > 0)
            {
                clientConsumerMethodCB?.Invoke(holdTaskQueueItem.Dequeue());
            }
        }
    }
}


texts: Is there more elegant way than using if - else to append or update the data array in a React app?

texts:
Below is a React useEffect hook I used in my application, basically what it does is:

data is an array for objects such as {round:number, date:dateString}.

When the application starts running, data will be an empty array, whenever round gets updated, the useEffect() will be called:

if the data array is empty, we update it with its very first object.
else the data array is not empty and if the last object of data array has its date property equal to props.localeDate, I make a new array with the its last object updated
else the data array is not empty and else the last object's date property is not equal to props.localeDate, I append a new object to data array.

const Chart = ({ round, dateAndTime }) => {
  const [data, setData] = useState([]);
  const localeDate = dateAndTime.toLocaleDateString();

  useEffect(() => {
    if (data.length === 0) {
      setData([
        ...data,
        {
          round: round,
          date: localeDate,
        },
      ]);
    } else {
      //update item if date matches
      if (data[data.length - 1].date === localeDate) {
        let newData = data.map((item) => {
          let newItem =
            item.date === localeDate ? { ...item, round: round } : item;
          return newItem;
        });
        setData(newData);
      } else {
        setData([...data, { round: round, date: localeDate }]);
      }
    }
  }, [round]);
 return (jsx element);
}

My code works as expected, but I am wondering if there is any way to improve on it? Using if-else looks really ugly.


texts: Using Elixir pipeline to transform a string into a map

texts:
Consider the list of string values,

lines = ["foo: 1", "bar: 2", "baz: 3"]

That one might transform into the Elixir map,

%{ "foo": "1", "bar": "2", "baz": "3"}

using a simple Enum.reduce,

Enum.reduce(lines, %{}, fn(line, result) ->
  [key, value] = String.split(line, ": ")
  Map.put(result, key, value)
end)

How might one refactor this into something more succinct, specifically with the third argument passed to reduce? For example, my instinct wants to do something like,

Enum.reduce(lines, %{}, fn(line, result) ->
  String.split(line, ": ") |> Map.put(result)
end)

but the Elixir pipe operator doesn't allow piping multiple values nor piping them to anything other than the first argument.


texts:
I am working on this website currently.

If you resize the window to less than 650px then the main menu is replaced by a button which when pressed triggers a left fly-out menu similar to the Facebook uses on the mobile website.

When viewed on a computer the menu works very well, but on mobile devices the performance is not so good and the slide-in effect is not smooth.  I need help with the performance.

      content Goes Here

jQuery:

jQuery(document).ready(function($) {
     var mobNav    = $("#mobNav"),
         mainNav   = $("#mainnav"),
         top       = $("#top"),
         shift     = $("#shift");
     // add navigation items to mobile nav
     mobNav.html(mainNav.html());

     $(window).on("scroll", function() {
        if($(window).scrollTop() > 300){
          top.fadeIn();
        } else{
          top.fadeOut();
        }
        if(parseInt(mobNav.css("left"), 10) == 0){
          // if is visible then hide
          mobNav.css("left", -mobNav.outerWidth());
          shift.css("margin-left", "0");
        }
      });

      $(window).on("resize", function() {
        if(parseInt(mobNav.css("left"), 10) == 0){
          // if is visible then hide
          mobNav.css("left", -mobNav.outerWidth());
          shift.css("margin-left", "0");
        }
      });
      // button that triggers mobile nav visibility
      $("#mob_nav_trigger").click(function(e) {
        e.preventDefault();
        var winWidth = $(window).width(),
            docHeight = $(document).height();
        mobNav.css("minHeight", docHeight).addClass("visible_now").animate({
            left: parseInt(mobNav.css('left'),10) == 0 ? -mobNav.outerWidth() : 0
        });
        shift.animate({
          marginLeft: parseInt(shift.css('margin-left'),10) == 200 ? 0 : 200
        }).css("minWidth", winWidth);
      });
});

Of course I'll be refactoring the code and take some code which is repeating and convert it into a function like:

    if(parseInt(mobNav.css("left"), 10) == 0){
      // if is visible then hide
      mobNav.css("left", -mobNav.outerWidth());
      shift.css("margin-left", "0");
    }


texts: LinkedList implementation with Iterators in Java

texts:
I am a newbie to Java. I will be glad to hear your opinion with regards to this LinkedList implementation. The Iterators are self implemented by my decision:

public interface Iterator {

    public boolean hasNext();
    public Object Next();

}

public class LinkedList {

    private Node mBase;

    private class ListIterator implements Iterator {

        private Node iterator;

        ListIterator(){
            iterator = mBase;
        }
        @Override
        public boolean hasNext(){
            return (iterator.getNext() != null);
        }
        @Override
        public Object Next() {
            Object userData = iterator.getData();
            iterator = iterator.getNext();
            return userData;
        }
    }

    static private class Node {

        private Node next;
        private Object data;

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

        Object getData(){
            return data;
        }

        Node getNext(){
            return next;
        }

        boolean isNext(){
            if (next == null) return (false);

            return (true);
        }
    }

    public void push(Object data){
        Node newNode = new Node(data, mBase);
        mBase = newNode;
    }

    public Object pop(){

        Node baseNode = mBase;
        Object userdata = null;

        if (isEmpty())
        {
            return (null);
        }

        mBase = mBase.getNext();
        baseNode.next = null;
        userdata = baseNode.getData();
        baseNode = null;

        return (userdata);
    }

    public long getSize(){

        Node current = mBase;
        int counter = 0;

        if (isEmpty()){
            return (0);
        }

        while (current.isNext()){
            current = current.getNext();
            ++counter;
        }

        ++counter;

        return (counter);

    };

    public ListIterator getItr(){
        return new ListIterator();
    };

    public boolean isEmpty(){
        return (mBase == null);
    }

}

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        LinkedList list = new LinkedList();

        System.out.print("isEmpty. Print true:");
        System.out.println(list.isEmpty());

        list.push(1);
        list.push(2);
        list.push(3);
        list.push("Hello");
        list.push("World");

        System.out.print("isEmpty. Print false:");
        System.out.println(list.isEmpty());

        System.out.print("getSize(). Should be 5: ");
        System.out.println(list.getSize());

        Iterator itr = list.getItr();

        System.out.print("itr.hasNext() (should be true)");
        System.out.println(itr.hasNext());

        while (itr.hasNext()) {
            System.out.print("itr.getNext()");
            System.out.println(itr.Next());
        }

        System.out.print("itr.getNext()");
        System.out.println(itr.Next());

        while(!list.isEmpty()){

            System.out.print("itr.list.pop()");
            System.out.println(list.pop());
        }

        System.out.print("getSize(). Should be 0: ");
        System.out.println(list.getSize());

    }

}


texts:
I forked this StackExchange Data Explorer (SEDE) query from another one, and made it a bit more complex. I'm looking for feedback on my style, as well as answers to other questions (see below).

-- top users: NYC
-- forked from Avinash Raj's query for Chennai
select
    row_number() over(order by u.Reputation desc) as [#],
    u.Id as [User Link],
    u.Reputation,
    u.Location
from -- denormalize the Users with their Badges, i.e., flatten into a single table.
    Users u
  join
    Badges b
  on
    u.Id = b.UserId
where
    b.name = N'python'
  and
    b.class = 3 -- 1 is gold, 2: silver, 3: bronze
  and
    u.Reputation >= 1000
  and
    (
      lower(u.Location) like '%nyc%'
      or upper(Location) like '%NY, NY%'
      or lower(Location) like '%staten%'
      or lower(Location) like '%bronx%'
      or lower(Location) like '%queens%'
      or lower(Location) like '%new york, ny%'
      or lower(Location) like '%manhattan%'
      or lower(Location) like '%brooklyn%'
    )
order by
    u.Reputation desc;

Questions:

Would this sql work with all relational DB's that accept SQL?
If not, what is non-standard? How would I standardize it?
I don't like all-uppercase queries - I find them more difficult to read, so I used the lowercase, is that problematic?
Is it possible, in a standard way, to factor pieces out of this query? Or nonstandard way specific to SEDE (or other system)? For example, could I avoid doing lower(Location) repeatedly? What about aliasing my joined table outside the code block for usage inside of it? I have order by u.Reputation desc twice, for example, can I factor that out?

I have just got some feedback on using table identifiers so that people don't have to guess, so I'll try to do that from now on. Am I doing it anywhere that's silly?

I was asked about allowing user input for the badge name - Yes, I intended to do that too - as well as specify type of badge (gold, silver, bronze) but I ran out of time, and don't have a clear idea how to implement mapping gold/silver/bronze to 1/2/3. I also have false positives and was hoping someone could point me at a more concise and/or accurate way to filter.


texts:
I have this Python program for calculating Leibniz of 'pi'. I am not able to shorten it more. Can anyone here optimise/shorten it?

s,a,b=0,[],[]
for i in range(int(input())):a.append(input())
for x in a:
    for j in range(int(x)):s+=pow(-1,int(j))/((2*int(j))+1)
    b.append(s)
    s=0
for i in b:print("{0:.15f}".format(i))


texts:
I'm new to Clojure but I already know about functions and lists, so I decided to implement Prime Factors Kata solution. For any natural number the function should return a list of all its prime factors, e.g. for 15 it should return (3 5).

It turned out that to implement a stack safe function I needed to use loop and recur, which I was not familiar with.

So, does my solution look like idiomatic Clojure? What could be improved? Thanks!

(defn primeFactorsOf
 "Return all prime factors of a number"
 [n]
 (loop [number n candidate 2 factors ()]
   (if (= number 1)
     (reverse factors)
     (if (= (mod number candidate) 0)
       (recur (/ number candidate) candidate (conj factors candidate))
       (recur number (inc candidate) factors)))))


texts: Streamlined for-loop for comparing two lists

texts:
I'm new to Python and I'm wondering is there a way to streamline this clunky code I've written. Maybe a built-in function I've never come across before?

I run through two lists of binary numbers and if the same number appears at the same index in list one and two, do x.

So in the example below the number 1 appears at index 2 in both lists.

list1 = [0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
list2 = [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0]

for position, binary in enumerate(list1):
    for placement, number in enumerate(list2):
            if position == placement and binary == 1 and binary == number:
                do x


texts:
I'm new to Java and have been through some tutorials and I'm in the next step of checking how I'm doing now. Is there a better way of doing this?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.Vector;

import org.apache.log4j.helpers.FileWatchdog;

/**
*
* Simple class that reads in a file - sorts its lines in natural order,
* writes it back out to the given filename and adds a timestamp of when it was sorted
*
* Program will be called with:
*
* java TestClass <input_filename> <output_filename>
*
*/

public class TestClass {

public static void main(String [] args) throws RuntimeException{
    boolean OVERWRITE_FILE = true;
    //get filename from args
    String inputFilename = args[0];
    String outputFilename = args[1];

    //check usage
    if(args.length != 2){
        System.out.println("Incorrect number of args");
        System.out.println("Correct usage is:");
        System.out.println(" java TestClass <input_filename> <output_filename> ");
        System.exit(-1);
    }

    //read in file into collection
    try {
        BufferedReader in = new BufferedReader(new FileReader(inputFilename));
        Vector fileContents = new Vector<Object>();
        while(in.ready()){
            fileContents.add(in.readLine());
        }

        //sort the collection in natural order
        Collections.sort(fileContents);

        //add timestamp
        fileContents.add("File Sorted on: ");
        fileContents.add(new Date());

        //write outputFile
        BufferedWriter out = new BufferedWriter(new FileWriter(outputFilename, OVERWRITE_FILE));
        for(int i = 0; i < fileContents.size(); i++){
            out.write((String)fileContents.get(i) + "\n");
        }
        //close output file
        out.close();

    } catch (IOException e) {
        System.out.println("Error while performing IO");
    }
}
}