texts:
I have written some ES2015 JavaScript that adds a class to a root element when one of it's immediate children is focused.

Here is the markup for the code to be run on:

    <input type="text">
    <button type="submit>

And the JS itself:

const rootElement = document.getElementById('my-root-element');

[...rootElement.children].forEach((element, _, children) => {
  const update = () => {
    const focused = children.indexOf(document.activeElement) !== -1;

    rootElement.classList[focused ? 'add' : 'remove']('focused');
  };

  [ 'focus', 'blur' ].forEach((eventName) => {
    element.addEventListener(eventName, () => setTimeout(update, 0));
  });
});

Are there any ways to "simplify" this code or generally make it smaller? I know it's short as it is currently but I understand that ES2015 has a lot of features that can help in writing short, concise code.

Here is an actual example of the code being used (focusing either the button or the text field should make the word "Focused!" appear):

const rootElement = document.getElementById('my-root-element');

[...rootElement.children].forEach((element, _, children) => {
  const update = () => {
    const focused = children.indexOf(document.activeElement) !== -1;

    rootElement.classList[focused ? 'add' : 'remove']('focused');
  };

  [ 'focus', 'blur' ].forEach((eventName) => {
    element.addEventListener(eventName, () => setTimeout(update, 0));
  });
});
.focused:after {
  content: 'Focused!';
}

    <input type="text">
    <button type="submit">Submit</button>


texts:
Can anybody help me to minimize my hard coding? Also please give me any suggestions for improving my code for the future?

My Source Code:

  export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
          <View style={styles.border}>
          <Image source={{uri:'https://images.unsplash.com/photo-1579551356536-e2d17fe1c7fa?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=80'}} style={styles.image}/>
          </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    padding: 8,
  },
  border:{
    width: 200,
    height: 300,
    borderTopEndRadius: 50,
    borderBottomStartRadius: 50,
    borderRadius: 15,
    backgroundColor: 'red',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.8,
    shadowRadius: 8,
  },
  image:{
    width:'100%',
    height: '100%',
    borderTopEndRadius: 50,
    borderBottomStartRadius: 50,
    borderRadius: 15,
  }
});


texts:
The code shows here is a demo of my application. The func1 always hang somewhere with reason I haven't figured out by now. Now I just want to write a watchdog for this process. If it didn't generate any data for some time (10 minutes here), watchdog will kill it and start a new one.

All the code is running for few hours with nothing error happened. But I want to know is there any better method for this watchdog. What's the worst case I should to take care of?

from multiprocessing import Value, Queue, Process
import time
import redis

redis_queue = redis.Redis(host="localhost", port=6379, password="password",
    db=0)

THREAD_TIMEOUT = 60 * 10

def func1():
    data2 = do-something1()
    redis_queue.sadd("queue1", data2)

def func2():
    data2 = redis_queue.spop("queue1")
    data3 = do-something2(data2)
    redis_queue.sadd("queue2", data3)

def func3():
    data3 = redis_queue.spop("queue2")
    do-something3()

def watch_dog():
    # watch dog for process p1, timeout is 10 minutes
    time_now = time.time()
    while True:
        queue1_length = len(queue1.smembers('queue1'))
        if queue1_length == 0:
            if time.time() - time_now > THREAD_TIMEOUT:
                print("queue1 has no message for {} minutes".format(
                    THREAD_TIMEOUT / 60))
                watch_dog_q.put("KILL WORKER")
        else:
            time_now = time.time()

if __name__ == "__main__":
    watch_dog_q = Queue()
    p1 = Process(target=func1)
    p2 = Process(target=func2)
    p3 = Process(target=func3)
    wdog = Process(target=watch_dog)
    wdog.daemon = True
    wdog.start()
    p1.start()
    p2.start()
    p3.start()
    p2.join()
    p3.join()
    wdog.join()
    while True:
        msg = watch_dog_q.get()
        if msg == "KILL WORKER":
            print("Terminating timeout process")
            p1.terminate()
            time.sleep(0.1)
            if not p1.is_alive():
                print("p1 process is a goner")
                p1 = join(timeout=1.0)
                p1 = Process(target=p1)
                p1 = start()


texts: Python 3 - simple temperature program version 1.3

texts:
Thank you to everyone for the feedback provided to the initial version of this program posted here.

Please find below the newest version, revised based on the comments provided, for review and comment on how I can further improve my coding.

I have removed the portion of the program that checked if the provided value was a legitimate temperature, as this was useless code only showing that I had recently learned what the opposite of absolute zero was....who cares, and who cares what value the user wants to convert!

I look forward to your feedback.

#!/usr/bin/python
"""

Program: Temperature Conversion (C to F, or F to C)
Date:    05 May 2019
Version: 1.2
Author:  Jason P. Karle

Remark:  This program was inspired by a Python exercise that
asks you to create a program that will convert one Celsius value to Fahrenheit;
so a program that can be executed with three lines of code.

However, I wanted to make something that would allow the user to
convert to and from either C of F, and do so multiple times, until the user
decides to end the program. This was also an exercise for me to
advance not only my code skills, but how I structure a program.

version history:
    1.0 Initial draft
    1.1 Correction of runtime; posted to StackExchange for feedback
    1.2 Re-coded based on feedback; trying to improve flow control
"""

def read_selection():
    selection = input('''Welcome to the temperature conversion program!

Please make a selection:

    c to convert from Celcius to Fahrenheit;
    f to convert from Fahrenheit to Celsius; or
    q to quit the program.

Enter your selection: ''').lower()
    return selection

def value_input(selection):
    value = input('''\nPlease enter the temperature you
want to convert: ''')
    try:
        value = float(value)
    except ValueError:
        print('That is not a number!\n')
    else:
        if selection == 'c':
            convert_c2f(value)
        else:
            convert_f2c(value)
            # return value

def convert_c2f(value):
    print(f'The answer is: {(value * (9/5)) + 32}°F\n')
    return

def convert_f2c(value):
    print(f'The answer is: {(value-32) * (5/9)}°C\n')
    return

def main():
    while True:
        selection = read_selection()
        if selection == 'q':
            return
        elif selection == 'c' or selection == 'f':
            value_input(selection)
            '''convert_c2f()
        elif selection == 'f':
            convert_f2C()'''
        else:
            print('Invalid selction. Try again.\n')

if __name__ == '__main__':
    main()


texts: Parsing an XML File for a single word/phrase

texts:
this is a small part of my code that allows me to request a file through a load balancer, reading this XML file gives me the server's name (only node inside the XML Document) if the machine isn't inside the LAN then it won't be able to query the website.  I give it a longer timeout to make sure that I don't get a ton of errors emailed to me if the network is laggy.

Here is the XML file Structure.

<?xml version="1.0" encoding="utf-8"?>
<Server>
    JSODYAPP01T
</Server>

Here is the Code that retrieves the information

WebRequest request = WebRequest.Create(xmlLocation);
request.Timeout = 90000;

using (WebResponse response = request.GetResponse())
using (XmlReader xmlReader = XmlReader.Create(response.GetResponseStream()))
{
    while (xmlReader.Read())
    {
        if (xmlReader.NodeType == XmlNodeType.Text)
        {
            serverName = xmlReader.Value.ToString();
            serverName = serverName.Replace("\r", "");
            serverName = serverName.Replace("\n", "");
            serverName = serverName.Replace(" ", "");
        }
    }
}

is there a better way of doing this?


texts: Joining multiple functions data in one array

texts:
This bit of code gathers data from two methods and puts it into an array. The code works fine but it doesn't look pretty and I feel like there is a better way of doing what I have done.

public static function RagUpdate()
{
    $MachineOnOffStatus = self::RagOnOffStatus();
    $ActiveMachine = array();
    foreach ($MachineOnOffStatus as $Key => $val) {
        if ($val['DateDifference'] < 360) {
            $ActiveMachine[$val['controllerID']]['controllerID'] = $val['controllerID'];
            $ActiveMachine[$val['controllerID']]["DateDiff"] = $val['DateDifference'];
        }
    }

    foreach (self::ActiveMachineCycleTime($ActiveMachine) as $Key => $val) {
        foreach ($ActiveMachine as $k => $v) {
            if ($val["controllerID"] == $v["controllerID"]) {
                $ActiveMachine[$v['controllerID']]["CycleTime"] = $val['ElaspedTime'];
            }
        }
    }
    return $ActiveMachine;
}

Output of this method:

array (size=5)
2 =>
array (size=3)
  'controllerID' => string '2' (length=1)
  'DateDiff' => string '136' (length=3)
  'CycleTime' => string '-61' (length=3)
28 =>
array (size=3)
  'controllerID' => string '28' (length=2)
  'DateDiff' => string '129' (length=3)
  'CycleTime' => string '-52' (length=3)
30 =>
array (size=3)
  'controllerID' => string '30' (length=2)
  'DateDiff' => string '96' (length=2)
  'CycleTime' => string '-45' (length=3)
37 =>
array (size=3)
  'controllerID' => string '37' (length=2)
  'DateDiff' => string '123' (length=3)
  'CycleTime' => string '-69' (length=3)
40 =>
array (size=3)
  'controllerID' => string '40' (length=2)
  'DateDiff' => string '89' (length=2)
  'CycleTime' => string '-75' (length=3)


texts: Verify user account on button click with an AJAX call

texts:
I have the following code that works perfectly other than the fact that it has to use async false, to wait for a response from ajax. Is there a way of restructuring this by using callbacks, or deferment?

playbtn.on('mousedown', function () { // functions when clicking play button

    function checkUser() {
        $.ajax({
            url: "/submit/checkuser/",
            async: false,
            success: function (userStatus) {
                if (userStatus == 'Disabled') { // check if user if disabled
                    if (Shadowbox.isOpen()) {
                        Shadowbox.close(); setTimeout(function () { accountDisabled(); }, 750);
                    } else {
                        Shadowbox.clearCache(); accountDisabled();
                    };
                    setTimeout(function () { location.replace('/'); }, 10000);
                } else if (userStatus == 'Deleted') { // check if user if deleted
                    if (Shadowbox.isOpen()) {
                        Shadowbox.close(); setTimeout(function () { accountDeleted(); }, 750);
                    } else {
                        Shadowbox.clearCache(); accountDeleted();
                    };
                    setTimeout(function () { location.replace('/'); }, 10000);
                } else {
                    Shadowbox.setup();
                };
            },
            error: function (e) {
                if (e.status != 403) {
                    if (!Shadowbox.isOpen()) {
                        Shadowbox.clearCache(); connectionError();
                    };
                };
            },
            statusCode: {
                403: function () {
                    if (Shadowbox.isOpen()) {
                        Shadowbox.close(); setTimeout(function () { locationNotAuthorized(); }, 750);
                    } else {
                        Shadowbox.clearCache(); locationNotAuthorized();
                    };
                }
            }
        });
    };

    Shadowbox.clearCache(); // disable shadowbox to check user status
    checkUserTimer = setInterval(function () { checkUser(); }, 600000);
    checkUser();
});


texts: Filtering objects according to required and preferred attributes

texts:
This my opportunity object which is a part of my angular app.component.ts file. In my template(HTML of this component) I want to loop out different skills backgrounds nationalitiesetc. array using *ngFor*. So I've filtered out these array of objects based on a property option which can have only 2 values either preferred or required. I've implemented such logic inside my TS file using filterByProperty() function as shown below. Please help make this function more simplified and generalized.

opportunity: any = {
 "id": 526,
  "title": "Testing",
  "nationalities": [
    {
      "option": "preferred",
      "id": 479,
      "name": "India",
    }
  ],
  "skills": [
    {
      "option": "required",
      "id": 1153,
      "name": "Adobe Lightroom",
    },
    {
      "option": "preferred",
      "id": 77,
      "name": "Python",
    },
    {
      "option": "preferred",
      "id": 78,
      "name": "Ajax",
    },
    {
      "option": "required",
      "id": 147,
      "name": "3D Max",
    },
    {
      "option": "preferred",
      "id": 175,
      "name": "Aircraft Engine Technology",
    }
  ],
  "backgrounds": [
    {
      "option": "preferred",
      "id": 232,
      "name": "Biology",
    },
    {
      "option": "required",
      "id": 249,
      "name": "International relations",
    }
  ],
  "languages": [
    {
      "option": "required",
      "id": 18,
      "name": "English",
    },
    {
      "option": "preferred",
      "id": 31,
      "name": "Italian",
    }
  ]
}

My app.component.ts file

    import {Component, OnInit, ViewChild} from '@angular/core';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html'
    })

    export class AppComponent implements OnInit {

  opportunity: any = {}; // Object value is shown above
  backgrounds: any = {
    preferred: [],
    required: []
  };
  skills: any = {
    preferred: [],
    required: []
  };
  languages: any = {
    preferred: [],
    required: []
  };
  nationalities: any = {
    preferred: [],
    required: []
  };

  ngOnInit() {
      this.filterByProperty();
  }

  filterByProperty() {
    this.skills.preferred = this.opportunity.skills.filter((i) => i.option === 'preferred');
    this.skills.required = this.opportunity.skills.filter((i) => i.option === 'required');
    this.backgrounds.preferred = this.opportunity.backgrounds.filter((i) => i.option === 'preferred');
    this.backgrounds.required = this.opportunity.backgrounds.filter((i) => i.option === 'required');
    this.languages.preferred = this.opportunity.languages.filter((i) => i.option === 'preferred');
    this.languages.required = this.opportunity.languages.filter((i) => i.option === 'required');
    this.nationalities.preferred = this.opportunity.nationalities.filter((i) => i.option === 'preferred');
    this.nationalities.required = this.opportunity.nationalities.filter((i) => i.option === 'required');
  }
}


texts:
Any feedback encouraged.  My checkForWinner function feels cumbersome to me.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var buttonOne: UIButton!
    @IBOutlet weak var buttonTwo: UIButton!
    @IBOutlet weak var buttonThree: UIButton!
    @IBOutlet weak var buttonFour: UIButton!
    @IBOutlet weak var buttonFive: UIButton!
    @IBOutlet weak var buttonSix: UIButton!
    @IBOutlet weak var buttonSeven: UIButton!
    @IBOutlet weak var buttonEight: UIButton!
    @IBOutlet weak var buttonNine: UIButton!

    @IBOutlet weak var gameResult: UILabel!

    var gameState = ["","","",
                     "","","",
                     "","",""
                     ]

    let winningCombos = [[0, 1, 2], [3, 4, 5], [6, 7, 8], //horizontal
                         [0, 3, 6], [1, 4, 7], [2, 5, 8], //vertical
                         [0, 4, 8], [2, 4, 6]] //diagonals

    var gameOver = false
    var turnCount = 0
    var currentPlayer: String!

    func pickFirstPlayer() -> String {
        if arc4random_uniform(2) == 0 {
            currentPlayer = "o"
        } else {
            currentPlayer = "x"
        }
        return currentPlayer
    }

    func toggleNextPlayer() {
        if currentPlayer == "o" {
            currentPlayer = "x"
        } else {
            currentPlayer = "o"
        }
    }

    @IBAction func makeMove(sender: AnyObject) {
        let space = sender.tag
        if (gameState[space] == "" && gameOver == false) {
            let turnImage = UIImage(named: "\(self.currentPlayer).png")
            sender.setImage(turnImage!, forState: .Normal)
            gameState[space] = self.currentPlayer
            self.toggleNextPlayer()
            self.turnCount++
            self.checkForWinner()
        }
    }

    func checkForWinner() {
        var winner = ""
        for combo in winningCombos {
            var row: [String] = []
            for space in combo {
                row.append(gameState[space])
            }
            if (row[0] == row[1] && row[1] == row[2] && row[0] != "") {
                gameOver = true
                winner = row[0].uppercaseString
                gameResult.text = "\(winner) is the winner!"

            }
        }
        if (turnCount == 9 && winner == "") {
            gameResult.text = "It's a tie!"
            gameOver = true
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        pickFirstPlayer()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}


texts:
I'm two months in a programming course and our instructor told us we should think about building real-world applications as to gain valuable experience. I got the idea of doing a simple temperature conversion app.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TempratureProject
{
    class Program
    {
        static void Main(string[] args)
        {
            //Ask for the temprature that the user wants to convert
            Console.WriteLine("What is the temprature you wish to convert?");
            var RInput = Console.ReadLine();
            double dInput = Convert.ToDouble(RInput);
            //Ask for what type of conversion
            Console.WriteLine("If you wish to convert Fahrenheit to Celsius, Press 1");
            Console.WriteLine("If you wish to convert Fahrenheit to Kelvin, Press 2");
            Console.WriteLine("If you wish to convert Celsius to Fahrenheit, Press 3");
            Console.WriteLine("If you wish to convert Celsius to Kelvin, Press 4");
            Console.WriteLine("If you wish to convert Kelvin to Fahrenheit, Press 5");
            Console.WriteLine("If you wish to convert Kelvin to Celsius, Press 6");
            //Set YInput equal to the choice made
            var YInput = Console.ReadLine();
              int iInput = Convert.ToInt32(YInput);
            //Use of a a series of If statements to call the methods
              if (iInput == 1)
              {
                  var aAnswer = FtoCelsius(dInput);

                  Console.WriteLine("The value of {0} degrees Fahrenheit is equall to {1} degrees Celsius", dInput, aAnswer);
              }
              else if (iInput == 2)
              {
                  var bAnswer = FtoKelvin(dInput);

                  Console.WriteLine("The value of {0} degrees Fahrenheit is equall to {1} degrees Kelvin", dInput, bAnswer);
              }
              else if (iInput == 3)
              {
                  var cAnswer = CtoFahenreit(dInput);

                  Console.WriteLine("The value of {0} degrees celcius is equall to {1} degrees Fahrenheit", dInput, cAnswer);
              }
              else if (iInput == 4)
              {
                  var dAnswer = CtoKelvin(dInput);

                  Console.WriteLine("The value of {0} degrees celsius is equall to {1} degrees Kelvin", dInput, dAnswer);
              }
              else if (iInput == 5)
              {
                  var eAnswer = KtoFahrenheit(dInput);

                  Console.WriteLine("The value of {0} degrees Kelvin is equall to {1} degrees Fahrenheit", dInput, eAnswer);
              }
            else
              {
                  var fAnswer = KtoCelsius(dInput);

                  Console.WriteLine("The Value of {0} degrees Kelvin is equall to {1} degrees Celsius", dInput, fAnswer);
              }

        }
        //The various methods
        static double FtoKelvin(double CTempIn)
        {
            double fKel = (CTempIn - 32) * (5 / 9) + 273.15;

            return fKel;
        }
        static double FtoCelsius(double CTempIn)
        {
            Double fCels = (CTempIn - 32) * (5 / 9);

            return fCels;
        }
         static double CtoFahenreit(double CtempIn)
        {
            double dFahr = (1.8) * (CtempIn + 32);

            return dFahr;
        }
         static double CtoKelvin(double CTempIn)
        {
            double cKel = CTempIn + 273.15;

            return cKel;
        }
         static double KtoFahrenheit(double CTempIn)
         {
             double kFah = (CTempIn - 273.15) * (9 / 5) + 32;

             return kFah;
         }
         static double KtoCelsius(double CTempIn)
         {
             double KCel = CTempIn - 273.15;

             return KCel;
         }
    }
}

It is working so there is that but I would like to know how well this is written and how I could make it better.


texts:
I have implemented an LRU cache, the question is taken from: leetcode: 146. LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Tests:
[TestClass]
public class LruCacheUnitTest
{
    [TestMethod]
    public void LruCacheTest()
    {
        LRUCache cache = new LRUCache(2 /* capacity */ );

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

Implementation:
public class LRUCache
{
    private int _numOfCells;
    private Dictionary<int, int> _cache;
    private List<KeyValuePair<int, int>> _orderList;

    public LRUCache(int numberOfCacheCells)
    {
        this._numOfCells = numberOfCacheCells;
        _cache = new Dictionary<int, int>(_numOfCells);
        _orderList = new List<KeyValuePair<int, int>>(_numOfCells);
    }

    public void put(int key, int value)
    {
        if (_cache.Count == _numOfCells) // the cache is full we need to remove 1
        {
            var toRemove = _orderList[0];
            _cache.Remove(toRemove.Key);
            _orderList.Remove(toRemove);
        }
        _orderList.Add(new KeyValuePair<int, int>(key, value));
        _cache[key] = value;
    }

    public int get(int key)
    {
        if (!_cache.ContainsKey(key))
        {
            return -1;
        }

        //put the key and value to the back of the ordered list
        var tempCacheCell = _orderList.FirstOrDefault(x=>x.Key == key);
        _orderList.Remove(tempCacheCell);
        _orderList.Add(tempCacheCell);
        return _cache[key];
    }
}


texts:
I've implemented my first data encryption / decryption methods on Node.js.
Although it might look similar to hundreds of sample implementations available online, I'm curious to get a feedback.

I'm particularly interested in:

some flaw points, potential security, and performance issues
In encrypt() I return an ENCRYPTED object with encrypted data after being freezed by Object.freeze(), are there any drawbacks/pitfalls of returning a freezed object besides the read-only status of the object?

const CRYPTO = require("crypto");

const ALG_CIPHER = "aes-256-gcm";

const ENC_IN = "utf8";
const ENC_OUT = "base64";

const BUFFER_SIZE = 16;

const KEY = Buffer.from("…", ENC_IN);

/**
 * Encrypt data using an initialisation vector
 *
 * @param {string} data - data to be encrypted
 * @returns {Promise<{authTag: Buffer, data: string, iv: Buffer}>} encrypted - encrypted data with decryption parameters
 */
const encrypt = async function encrypt(data) {

    const IV = Buffer.from(CRYPTO.randomBytes(BUFFER_SIZE));
    const CIPHER = CRYPTO.createCipheriv(ALG_CIPHER, KEY, IV);

    let enc = CIPHER.update(data, ENC_IN, ENC_OUT);
    enc += CIPHER.final(ENC_OUT);

    const ENCRYPTED = Object.freeze({
        data: enc,
        iv: IV,
        authTag: CIPHER.getAuthTag()
    });

    return ENCRYPTED;

};

/**
 * Decrypt data using an initialisation vector
 *
 * @param {string} data - data to be decrypted
 * @param {string} iv - initialisation vector
 * @param {Buffer} authTag - authentication tag
 * @returns {Promise<string>} decrypted - decrypted data
 */
const decrypt = async function decrypt(data, iv, authTag) {

    const DECIPHER = CRYPTO.createDecipheriv(ALG_CIPHER, KEY, iv);
    DECIPHER.setAuthTag(authTag);

    let decrypted = DECIPHER.update(data, ENC_OUT, ENC_IN);
    decrypted += DECIPHER.final(ENC_IN);

    return decrypted;

};


texts:
I have a hierarchy of types in my program and need to be able to create them dynamically at runtime. The solution I've come up with below is not the most elegant solution. Are there ways of improving it?

Specifically would it be possible to have the method getBuilderFor(...) not need to instantiate the type it's trying to create in order to get a builder for that type?

public class Main {

    public interface E {    }

    public class EImpl implements E { }

    public interface C<V> extends E {

        interface Builder<T> { T build(); }
    }

    public abstract class CImpl<T> extends EImpl implements C<T> {

        public abstract class BuilderImpl<V extends C<?>> implements Builder<V>{  }
    }

    public interface B extends C<String> { }

    public class BImpl extends CImpl<String> implements B {

        public class BuilderImpl extends CImpl<B>.BuilderImpl<B> {
            @Override public B build() { return new BImpl(); }
        }
    }

    public interface D extends C<Double> { }

    public class DImpl extends CImpl<Double> implements D {

        public class BuilderImpl extends CImpl<D>.BuilderImpl<D> {
            @Override public D build() { return new DImpl(); }
        }
    }

    public class Factory {

        public <R extends C<?>, K extends C.Builder<R>> K getBuilderFor(final Class<R> type) {

            if (BImpl.class.equals(type)) {
                // I would ideally like to just have return BImpl.BuilderImpl() here - is it possible?
                return (K) new BImpl().new BuilderImpl();
            } else if (DImpl.class.equals(type)) {
                // I would ideally like to just have return DImpl.BuilderImpl() here - is it possible?
                return (K) new DImpl().new BuilderImpl();
            }
            return null;
        }
    }
}


texts:
I tried solve this easy leetcode challenge in java. Challenge link

Here is my solution

class Solution {
  public int romanToInt(String s) {
    Map<String, Integer> data
        = new HashMap<String, Integer>() {
        {
            put("I", 1);
            put("V", 5);
            put("X", 10);
            put("L", 50);
            put("C", 100);
            put("D", 500);
            put("M", 1000);
            put("IV", 4);
            put("IX", 9);
            put("XL", 40);
            put("XC", 90);
            put("CD", 400);
            put("CM", 900);
        }
    };
    String[] edge = {"IV", "IX", "XL", "XC", "CD", "CM"};
      int sum = 0;
      for (String val : edge) {
          if(s.isBlank()) {
              break;
          } else if(s.contains(val)) {
             sum += data.get(val);
             int index = s.indexOf(val);
             s = s.substring(0, index) + s.substring(index + 2);
          }
      }
      s = s.trim();
      for (char c: s.toCharArray()) {
          sum += data.get("" + c);
      }
      return sum;
      }
}

I am learning to compute the complexity:
Here is my interpretation
Looks like it is O(6) constant ~ O(1) * O(len(string)) ~ O(n) => O(n)
Correct me if it is not O(n)

Any suggestions on my approach to problem and code where I can reduce time and space complexity.


texts: Ruby - class definition for connecting to external API

texts:
I've defined a Client class to connect to an external API.  The Client class will return XML responses for various resources.  Here's what it looks like now:

require 'nokogiri'

class Client
  include Exceptions

  CONFIG = YAML.load_file(File.join(Rails.root, 'config', 'mark.yml'))

  def self.get_leagues_xml(league, start_date, end_date)
    raise ArgumentError, "No args can be nil." if league.nil? || start_date.nil? || end_date.nil?

    start_date = format_date(start_date)
    end_date = format_date(end_date)

    @url = build_url_for(:leagues)
    @url_params = {'League' => league, 'StartDate' => start_date, 'EndDate' => end_date}

    call_http_service
  end

  def self.get_seasons_xml(season)
    raise ArgumentError, "No args can be nil." if season.nil?

    @url = build_url_for(:seasons)
    @url_params = {'Season' => season}

    call_http_service
  end

  protected

  def self.call_http_service
    begin
      conn = create_connection
      resp = get_response(conn)
      resp_xml = Nokogiri::XML(resp.body)
    rescue Faraday::Error::ClientError => ce
      raise MarkClientError.new("Client error occurred trying to access Mark feed at #{@url}: #{ce.message}.")
    rescue => e
      raise e
    end
  end

  def self.get_response(connection)
    connection.get do |req|
      req.params['Username'] = CONFIG['api']['username']
      req.params['Password'] = CONFIG['api']['password']
      @url_params.each_pair { |key, val| req.params[key] = val}
      req.options = {:timeout => 30} # open/read timeout in secs
    end
  end

  def self.create_connection
    Faraday.new(:url => @url) do |builder|
      builder.request  :url_encoded
      builder.response :logger
      builder.adapter  :net_http
    end
  end

  def self.build_url_for(resource)
    CONFIG['api']['url'] + CONFIG['resource']["#{resource.to_s}"]['url']
  end

  def self.format_date(date)
    date = Chronic.parse(date) if date.is_a?(String)
    date.strftime('%m/%d/%Y')
  end

end

My primary question is whether or not my use of the class instance variables (@url and @url_params) is an anti-Rubyism and will get me into trouble when multiple concurrent class method calls are being made?  I've considered making Client a module or a superclass and then having separate classes for each type of API call that needs to made, for ex, LeaguesClient and SeasonsClient.  That way I could make those instantiated classes and initialize with url and url_params.  I'm starting to experiment with the distinct nuances of Ruby but want to check with you guys as to how you would approach.  Any thoughts you have would be welcome.  Thanks!


texts:
I'm working on an XNA project that loads several resources that are packed into a single file. XNA can take a WAV file stream and turn that into a SoundEffect (seen below in "case ".wav"").

Since WAV files are large, I want to enable MP3 audio as one of the resources, so I found MP3Sharp, a cross-platform library that converts mp3 file data into PCM data.(just the wavform data, no headers.) Unfortunately, the method I have to use to integrate this in, "SoundEffect.FromStream(Stream stream)", is expecting both the WAV file headers and the PCM data (waveform) To do this, I am using several MemoryStreams and my instinct tells me that it is horribly inefficient.(noticeably too)  Below you will find the code, the important part being the "case ".mp3":" portion. How can I do this better?

tl;dr: Prepend/combine streams in C#, how? (also note that nChannels and nSamplesPerSec need to be discovered from decoding the mp3 file)

I am worried that I am taking the wrong approach to reading from the stream and

byte[] data = reader.ReadBytes(reader.ReadInt32());
files[path] = data;
string extension = Path.GetExtension(path);
switch (extension)
{
    case ".png":
        string texturePath = Path.ChangeExtension(path, null);
        using (MemoryStream buffer = new MemoryStream(data))
        {
            textures[texturePath] = Texture2D.FromStream(Main.instance.GraphicsDevice, buffer);
        }
        break;
    case ".wav":
        string soundPath = Path.ChangeExtension(path, null);
        using (MemoryStream buffer = new MemoryStream(data))
        {
            sounds[soundPath] = SoundEffect.FromStream(buffer);
        }
        break;
    case ".mp3":
        // TODO, better way to do this?
        string mp3Path = Path.ChangeExtension(path, null);
        MemoryStream wavData = new MemoryStream();
        MemoryStream wavFile = new MemoryStream();
        ushort wFormatTag = 1;
        ushort nChannels;
        uint nSamplesPerSec;
        uint nAvgBytesPerSec;
        ushort nBlockAlign;
        ushort wBitsPerSample = 16;
        using (MemoryStream buffer = new MemoryStream(data))
        {
            using (MP3Sharp.MP3Stream s = new MP3Sharp.MP3Stream(buffer))
            {
                s.CopyTo(wavData);
                nChannels = (ushort)s.ChannelCount;
                nSamplesPerSec = (uint)s.Frequency;
            }
        }
        nBlockAlign = (ushort)(nChannels * (wBitsPerSample / 8));
        nAvgBytesPerSec = (uint)(nSamplesPerSec * nChannels * (wBitsPerSample / 8));
        using (BinaryWriter bw = new BinaryWriter(wavFile))
        {
            bw.Write("RIFF".ToCharArray());
            bw.Write((UInt32)(wavData.Length + 36));
            bw.Write("WAVE".ToCharArray());
            bw.Write("fmt ".ToCharArray());
            bw.Write(16);
            bw.Write(wFormatTag);
            bw.Write(nChannels);
            bw.Write(nSamplesPerSec);
            bw.Write(nAvgBytesPerSec);
            bw.Write(nBlockAlign);
            bw.Write(wBitsPerSample);
            bw.Write("data".ToCharArray());
            bw.Write((UInt32)(wavData.Length));
            bw.Write(wavData.ToArray());
        }
        using (MemoryStream buffer = new MemoryStream(wavFile.ToArray()))
        {
            sounds[mp3Path] = SoundEffect.FromStream(buffer);
        }
        break;
    }

The full method is available on GitHub.


texts: Getting ID of Task List item in Sharepoint 2013

texts:
I want to do some operation by taking an ID of a Task List item in SharePoint on UI front. I've just wrote some jQuery code by traversing the element. I got the ID and performed operations what I wanted to do. But I think this is not best practices to do so.

$(document).on("click", "#idHomePageEditItem", function () {
   $("#Hero-WPQ2").next().next().next().children("tbody").children().each(function () {
      if ($(this).hasClass("s4-itm-selected")) {
         var selectedRecordId = $(this).children().eq(1).children().children().children().children().attr("liid");
         alert(selectedRecordId );
      }
   }
}

If you run this code, then you can get id of the taskList item in the selectedRecordId variable.


texts: Simple, intuitive and (hopefully) safe EventDispatcher

texts:
For my own game engine I need an event system. I tried to avoid the single-huge-enum-approach for minimizing compile times.

The BasicEventListener is the (obviously) base class of the EventListener and is needed for storing EventListeners in a list:

class BaseEventListener {
    friend class EventDispatcher;
    std::map<EventId, EventDispatcher&> dispatchers;
public:
    virtual ~BaseEventListener() {
        for (auto& pair : dispatchers)
             pair.second.listeners[pair.first].erase(this);
    }
};

The Destructor of BaseEventListener ensures, that the dispatchers will not try to dispatch an Event to an deleted EventListener. It will remove this from the corresponding EventDispatcher.

The EventListener itself looks as follow:

template <typename Event>
class EventListener : public virtual BaseEventListener {
public:
    virtual void handleEvent(const Event&) = 0;
};

The user now is able to inherit from EventListener with

class ConcreteEventListener : public EventListener<KeyPressed>,
                              public EventListener<KeyReleased> {...}

Now I'm getting to the Dispatcher:

class EventDispatcher final {
    friend class BaseEventListener;
    std::map<EventId, std::set<BaseEventListener*>> listeners;
    std::queue<std::function<void()>> eventQueue;
public:
    // register an EventListener to the Dispatcher
    template <typename Event>
    bool add(EventListener<Event>& listener) {
        EventId eventId = getEventId<Event>();

        if (!listener.dispatchers.try_emplace(eventId, *this).second) return false;
        bool success = listeners[eventId].insert(&listener);
        assert(success); // shouldn't fail

        return true;
    }

    // remove an EventListener from the Dispatcher
    template <typename Event>
    void remove(EventListener<Event>& listener) {
        EventId eventId = getEventId<Event>();

        if (!listener.dispatchers.erase(eventId)) return;
        bool success = listeners[eventId].erase(&listener);
        assert(success); // shouldn't fail
    }

    // (2) Directly dispatch to EventListeners
    template <typename Event, typename... Args>
    void dispatch(Args&&... args) {
        Event ev(std::forward<Args>(args)...);
        for (auto& listener : listeners[getEventId<Event>()])
            dynamic_cast<EventListener<Event>*>(listener)->handleEvent(ev);
    }

    // (3) Queue Event for later dispatching
    template <typename Event, typename... Args>
    void queue(Args&&... args) {
        eventQueue.emplace([event{std::make_shared<Event>(std::forward<Args>(args)...)}, this] {
            for (auto& listener : listeners[getEventId<Event>()])
                dynamic_cast<EventListener<Event>*>(listener)->handleEvent(*event);
        });
    }

    // dispatch queued Events
    void tick() {
        while (!eventQueue.empty()) {
            eventQueue.front()();
            eventQueue.pop();
        }
    }

    // clean up EventListeners
    ~EventDispatcher() {
        for (auto& eventListenerSet : listeners)
            for (auto& eventListener : eventListenerSet.second)
                eventListener->dispatchers.erase(eventListenerSet.first);
    }
};

Now the questioning :)

(2), (3): Is this well defined behavior/good practice/clean/performant?
For a multithreaded engine, I guess all the sections should be mutex locked?


texts:
I have attempted to implement the Sieve of Eratosthenes in C. It works rather quickly with values tested up to ten million: time ./soe.out 10000000 returns real: 0m0.218s (this is of course, not including the result printing at the end which takes the majority of the time).

Is my code the most efficient it could be, and would implementing a segmented sieve instead be a good idea for improvement?

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <errno.h>
#include <stdlib.h>

#define true (1)
#define false (0)
typedef unsigned char bool;

#define MAX 10000000

/* to_int: converts a character array to an integer, returns -1 on error, -2 on out of limits */
int to_int(char* inp) {
    int len = strlen(inp);
    unsigned int out = 0, prev_out = 0, mult = 1;

    if (len == 0)
        return -1;

    for (int i = len - 1; i >= 0; i--) {
        if (inp[i] < 48 || inp[i] > 57)
            return -1;

        prev_out = out;
        out += (inp[i] - 48) * mult;
        mult *= 10;

        /* detect wrapping */
        if (out < prev_out)
            return -2;
    }

    return out;
}

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Syntax: number to find primes up to (max. %d)\n", MAX);
        return EXIT_FAILURE;
    }

    unsigned int max = to_int(argv[1]);

    if (max == -1) {
        fprintf(stderr, "Syntax: number to find primes up to (you typed %s, which is not a valid number)\n", argv[1]);
        return EXIT_FAILURE;
    }

    if (max > MAX || max == -2) {
        printf("Warning: the number you typed was outside of the limit. It has been set to %d.\nPress the return key to continue...\n", MAX);
        max = MAX;
        getchar();
    }

    max++;

    /* Set up the list */
    bool *list = NULL;
    if ((list = malloc(max)) == NULL) {
        fprintf(stderr, "Error! Could not allocate the requested amount of memory: %s\nExiting...\n", strerror(errno));
        return EXIT_FAILURE;
    }

    memset(list, true, max);

    int iteration = 0;
    int max_sqrt = sqrt(max);

    for (int i = 2; i <= max_sqrt; i++) {
        if (list[i])
            for (int j = i*i; j <= max; j += i)
                list[j] = false;
    }

    for (int i = 1; i < max; i++)
        if (list[i])
            printf("%d: prime\n", i);

    free(list);

    return EXIT_SUCCESS;
}


texts:
I'm writing a program in Scala to perform Hamiltonian Monte Carlo (HMC), coupled with Gibbs sampling of some variables. The algorithm, with the modifications such as perturbing epsilon and l and performing Gibbs updates on some variables may be found in the easily available book chapter "MCMC using Hamiltonian Dynamics" by R Neal. The program works by alternating an HMC update of a set of variables q via the hmcUpdate() method with Gibbs updates of the variables gibbsVar via some unspecified method, then putting the two sets together in a tuple. The hmcRunner() method generates these tuples and prepends them onto a list.

I'm very new to Scala (last Friday) so I would like some feedback on the idiomacity of the code, as well as advice in general on improving readability. I've tried to write this in the form of an abstract class so that myself and my other group members can use this in their own code by supplying the unspecified methods themselves - is this the most appropriate structure to use?

import breeze.linalg._
import breeze.stats.distributions.Uniform
import breeze.stats.distributions.Gaussian
import breeze.stats.distributions.Gamma
import math.log, math.sqrt
import scala.annotation.tailrec

abstract class HMC(ul: Int, ue: Double) {
  val uDev = new Uniform(0.0,1.0)
  val nDev = new Gaussian(0.0,1.0)
  val l = ul
  val ep = ue

  final def metCheck(ho: Double, hn: Double): Boolean = log(uDev.sample()) < ho - hn

  def calcU(q: DenseVector[Double], sigs: List[Double]): Double

  def calcUgrad(q: DenseVector[Double], sigs: List[Double]): DenseVector[Double]

  def gibbsUpdate(q: DenseVector[Double]): List[Double]

  final def hmcUpdate(qo: DenseVector[Double], sigs: List[Double], acc: Int): (DenseVector[Double], Int) = {
    val uep = ep * min(sigs) * min(sigs) * (0.9 + 0.2 * uDev.sample()) // perturb ep, l pm 10% to avoid cyclic orbits
    val ul = (l.toDouble * (0.9 + 0.2 * uDev.sample())).toInt
    val po = DenseVector(nDev.sample(qo.length).toArray)
    val ho = calcU(qo, sigs) + (po dot po) / 2.0
    @tailrec
    def leapFrog(qo: DenseVector[Double], po: DenseVector[Double], ll: Int): (DenseVector[Double], DenseVector[Double]) = {
      if (ll == 1) {
        val qn = qo + (po :* uep)
        val pn = po - (calcUgrad(qn, sigs) :* uep) / 2.0
        (qn, pn)
      }
      else {
        val qn = qo + (po :* uep)
        val pn = po - (calcUgrad(qn, sigs) :* uep)
        leapFrog(qn, pn, ll - 1)
      }
    }

    val (qn, pn) = leapFrog(qo, po - (calcUgrad(qo, sigs) :* uep) / 2.0, ul)
    val hn = calcU(qn, sigs) + (pn dot pn) / 2.0
    if (metCheck(ho,hn)) (qn, acc + 1) else (qo, acc)
  }

  final def stdDevSample(sqmis: Double, n: Int) = sqrt(
    sqmis / (2.0 * Gamma((n.toDouble + 3) / 2.0, 1.0).sample())
    )

  //Pass initial values to rl
  @tailrec
  final def hmcRunner(maxIt: Int, report: Int, iter: Int, acc: Int,
    rl: List[(DenseVector[Double], List[Double])]):
    List[(DenseVector[Double], List[Double])] = {
    if (iter == maxIt) {
      val (qn, accn) = hmcUpdate(rl(0)._1, rl(0)._2, acc)
      val gibbsVar = gibbsUpdate(qn)
      (qn, gibbsVar) :: rl
    }
    else {
      val (qn, accn) = hmcUpdate(rl(0)._1, rl(0)._2, acc)
      val gibbsVar = gibbsUpdate(qn)
      val currU = calcU(qn, gibbsVar)
      if (iter % report == 0) {
        print("\nIteration "); print(iter); print(" of "); println(maxIt)
        print("U: "); println(currU)
        print("Acceptance: "); println(acc.toDouble / iter.toDouble)
      }
      hmcRunner(maxIt, report, iter + 1, accn, (qn, gibbsVar) :: rl)
    }
  }
}


texts: Express middleware to handle errors and send them to Raygun

texts:
I signed up for Raygun on Heroku and wrote a middleware in Express to handle the error, however, I am afraid this might block a request from coming through or executing all the way.  This article is what I am basing this off of.

Do I have the next() in the correct place? I have it in two places just in case.

  app.use(function(req, res, next) {
    let d = domain.create();
      d.on('error', function (err) {
        raygunClient.send(err);
      });
      d.add(req);
      d.add(res);
      d.run(function () {
        next();
      });
    next();
  });


texts:
public HttpResponseMessage Post(LongUrlModel model)
{
    if (ModelState.IsValid)
    {
        var baseAddress = Request.RequestUri.ToString().TrimEnd('/');
        if (model.LongUrl.StartsWith(baseAddress))
        {
            ModelState.AddModelError("", "You cant shorten a URL that belongs to this domain");
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
        }

        *snip*
    }
    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}

I am not at all fond of the conditional logic here, it can be quite hard to follow. How can I refactor the additional model validation logic so that it will co-exist with the standard model validation nicely?

I feel as though there could be a way to refactor this code so that  Request.CreateErrorResponse only occurs in the code once, but I cannot see how at the moment.


texts: HTML5 semantic layout (div, article, section) and explicit identifiers

texts:
I'm writing a markup for:

And I've split it for these sections:

Is it semantically correct(div, section, article) and are my identifiers explicit?


texts: AsyncTask alternative with Runnable and CountdownLatch

texts:
What is wrong with this pattern which emulates AsyncTask functionality?:

// on the UI thread
final CountDownLatch latch = new CountDownLatch(1);
onPreexecuteWrapper();
new Thread(new Runnable() {
        doInBackgroundWrapper();
        latch.countDown();
    }
}).start();

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
                latch.await();
        } catch (InterruptedException e) {
            Logger.error(TAG, "Not good.");
        }

    context.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            onPostExecuteWrapper();
        }
    });
}
}).start();

Here's what I think is wrong:

Two threads -> more resources (I didn't compare actually, just guessing).
No progress update functionality.
Appears to be stinky.


texts: Calculate simple arithmetic string in Scala

texts:
Problem

Given an arithmetic string like 2+2*3 calculate result 8.

Assumptions you can make

string will be always well formed (no error checking needs to be done)
only operators passed in string will be + and *
only single digit numbers allowed

Example

input = 2*2*2+2*1*5
output = 18

input = 2+2*3
output = 8

Hers is scala code for the same

object Expression extends App {
  implicit class Converter(char: Char) {
    def toNum: Int = char - '0'
  }

  def evaluateExpression(s :List[Char]): Int = {
    s match {
      case left::op::List(right) =>  // a+b or a*b
        op match {
          case '+' =>  left.toNum + right.toNum
          case  _ =>   left.toNum * right.toNum
        }
      case left::op::right => // a+b*c or a*b+c
         op match {
           case '+' =>
             left.toNum + evaluateExpression(right)
           case '*' =>
             val nextAdd = right indexOf '+'
             val (multiplication ,pendingExpression) = if (nextAdd == -1) {
                                                         (right,List[Char]())
                                                       } else {
                                                         (right.take(nextAdd), right.drop(nextAdd + 1))
                                                       }
             val product = (multiplication.filter( _ != '*') map (_.toNum)).foldLeft(left.toNum) (_ * _)
             if (pendingExpression.isEmpty) product
             else product + evaluateExpression(pendingExpression)
          }
     }
   }
  List("3*3*3", "2+2*3", "0*0*1", "0+0*1", "0*0*1", "2+2*3*3", "2+2+2*3+2+2") foreach { expr =>
    println(expr + " = " + evaluateExpression(expr.toList))
  }
}

Output for above code

3*3*3 = 27
2+2*3 = 8
0*0*1 = 0
0+0*1 = 0
0*0*1 = 0
2+2*3*3 = 20
2+2+2*3+2+2 = 14


texts: Counting the minimum number of blocks to remove to form a triangular temple

texts:
PROBLEM STATEMENT :

  You want to build a temple for snakes. The temple will be built on a
  mountain range, which can be thought of as n blocks, where height of
  i-th block is given by hi. The temple will be made on a consecutive
  section of the blocks and its height should start from 1 and increase
  by exactly 1 each time till some height and then decrease by exactly 1
  each time to height 1, i.e. a consecutive section of 1, 2, 3, .. x-1,
  x, x-1, x-2, .., 1 can correspond to a temple. Also, heights of all
  the blocks other than of the temple should have zero height, so that
  the temple is visible to people who view it from the left side or
  right side.

  You want to construct a temple. For that, you can reduce the heights
  of some of the blocks. In a single operation, you can reduce the
  height of a block by 1 unit. Find out minimum number of operations
  required to build a temple.

  INPUT

  The first line of the input contains an integer T denoting the number
  of test cases. The description of T test cases follows.

  The first line of each test case contains an integer n.

  The next line contains n integers, where the i-th integer denotes hi

  OUTPUT

  For each test case, output a new line with an integer corresponding to
  the answer of that testcase.

  CONSTRAINTS

  1 ≤ T ≤ 10

  2 ≤ N ≤ 105

  1 ≤ Hi ≤ 10^9

  Example Input

3
3
1 2 1
4
1 1 2 1
5
1 2 6 2 1

  Output

0
1
3

MY SOLUTION

#include <stdio.h>

void quickSort(int arr[], int low, int high);
int partition (int arr[], int low, int high);
void swap(int* a, int* b);

int main(void) {
    // your code goes here
    int t=0, i=0, n=0, move=0, j=0;
    scanf("%d\n", &t);
    for(i=1;i<=t;++i)
    {
        scanf("%d\n", &n);
        int arr[n];
        int i5;
        for(i5=0;i5<n;++i5)
        scanf("%d ", &arr[i5]);

        quickSort(arr, 0, n-1);

        int max= (arr[n-1]!=arr[n-2])?arr[n-2]+1:arr[n-1];
        move = arr[n-1]-max;
        --max;
        int i3=0;
        for(i3=n-2;i3>0;--max)
        {
            move+=((arr[i3]-max)+(arr[i3-1]-max));
            i3-=2;
            if(max==1)
            {
                break;
            }
        }
        for(j=0;j<=i3;++j)
        {
            move+=arr[j];
        }
        printf("%d\n", move);
    }
    return 0;
}

// A utility function to swap two elements
void swap(int* a, int* b)
{
    int t = *a;
    *a = *b;
    *b = t;
}

/* This function takes last element as pivot, places
   the pivot element at its correct position in sorted
    array, and places all smaller (smaller than pivot)
   to left of pivot and all greater elements to right
   of pivot */
int partition (int arr[], int low, int high)
{
    int pivot = arr[high];    // pivot
    int i = (low - 1);  // Index of smaller element
    int j;

    for (j = low; j <= high- 1; j++)
    {
        // If current element is smaller than or
        // equal to pivot
        if (arr[j] <= pivot)
        {
            i++;    // increment index of smaller element
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

/* The main function that implements QuickSort
 arr[] --> Array to be sorted,
  low  --> Starting index,
  high  --> Ending index */
void quickSort(int arr[], int low, int high)
{
    if (low < high)
    {
        /* pi is partitioning index, arr[p] is now
           at right place */
        int pi = partition(arr, low, high);

        // Separately sort elements before
        // partition and after partition
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}


texts: Sieve of Eratosthenes using a Javascript array

texts:
Any feedback on my code would be greatly appreciated.

/*
   The Sieve of Eratosthenes using a javascript array as
   an associative data structure.
*/

function range(start, limit, step) {
    var rangeArray = [];
    for (var i = start; i < limit; i += step)
        rangeArray.push(i);
    return rangeArray;
}

function isNotNull(value) { // predicate for filtering
    if (value !== null)
        return true;
    else
    return false;
}

function nullMultiples(multiple, array) { // mutates array
    var step = multiple;
    while (multiple < array.length) {
        array[multiple] = null;
        multiple = multiple + step;
    }
}

function nextPrime(currentPrime, array) {
    var successor = currentPrime++;
    while (array[successor] === null)
        successor++;
    return successor;
}

function primes(below) {
   var initSet = range(0, below, 1);
   var primeSet = []; // set of numbers used as a multiple
   var currentPrime = initSet[2]; // the first multiple is 2
   while (currentPrime < Math.sqrt(initSet.length)) {
       primeSet.push(currentPrime);
       nullMultiples(currentPrime, initSet); // mutate initSet
       currentPrime = nextPrime(currentPrime, initSet);
   }
   // return the numbers that were used as multiples and all
   // inidicies that still contain a number, except 0 and 1
   return primeSet.concat(initSet.slice(2).filter(isNotNull));
}


texts: Project Euler Problem 12 in Python 3 (Find triangle number with 500 divisors)

texts:
I am doing Project Euler, and 12 is the one that takes significantly longer then everything else.

Here is my code:

# The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be
# 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28.
# The first ten terms would be:
#
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#
# Let us list the factors of the first seven triangle numbers:
#
# Omitted
#
# We can see that 28 is the first triangle number to have over five divisors.
#
# What is the value of the first triangle number to have over five hundred divisors?

import time

start = time.time()

def count_factors(num):
    # One and itself are included now
    count = 2
    for i in range(2, num):
        if num % i == 0:
            count += 1
    return count

def tri_nums(num):
    return int(num * (num + 1) / 2)

x = 500

while True:
    if count_factors(tri_nums(int(x))) > 500:
        break
    x += 1

print('The answer is', tri_nums(x))

print('Answer found in', time.time() - start, 'seconds')

# The answer is 76576500
# Answer found in 36164.39957642555 seconds

The first time that I ran this code it took over 10 hours.
I can't really think of any ways to make this faster, but I am sure that there are.

Also, is count_factors() faster than:

def factors(num):
for i in range(1, num):
    if num % i == 0:
        yield i


texts:
I'm new to both Elixir and tail recursion.

defmodule MyInteger do
  defp sum_upto(x, accumulator) when accumulator <= 1 do
    accumulator
  end

  defp sum_upto(x, accumulator) when accumulator > 1 do
    sum_upto(x, accumulator-1) + accumulator
  end

  def sum_upto(x) when x <= 1 do
    x
  end

  def sum_upto(x) do
    sum_upto(x, x-1) + x
  end
end

Is the above an optimal way to calculate the sum up to x?


texts: Detect if ie10+ and edge is using inPrivate mode

texts:
This is an odd case scenario, but I would like to display a message that tells if indexedDB is not supported or if it is removed due to being in private mode (yes ie10+/edge remove indexedDB in private mode, crazy uh?).

I think found a way without doing crazy UA sniffing or documentMode hacks that I think could work.

if(!window.indexedDB && (window.PointerEvent || window.MSPointerEvent))
  document.body.innerHTML = "Can't use indexedDB because you are in private mode"
else if(!window.indexedDB)
  document.body.innerHTML = "Can't use indexedDB because you don't have it"
else
  document.body.innerHTML = "woho"
  // Other browser in private mode can block indexedb
  // but the message gets handled from db.onerror instead

IE/Edge is the only browser that removes indexedDB when using inPrivate mode..?
so this is a way to detect private mode, but then you have to figure out if it is ie10+ or edge.
so ie10 was the latest browser with support for indexedDB
and ie10+edge is the only browser that support pointerEvent [caniuse]

And I assume there is no other browser with support for pointerEvent and not having indexedDB at the same time that could yield wrong message.

What do you think about this? Good, bad? Any suggestions? It would help if you could test if this works in your browser (I don't have Windows).


texts: Is the code prone to SQL injection or to any other kind of threat

texts:
I am very new to PHP coding, hence just wanted to know if my coding is prone to any SQL injection attack or any other kind of threat. Below is the code for adding client to the database:

<?php
$response = array();
include 'db/db_connect.php';
include 'functions.php';

//Get the input request parameters
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE); //convert JSON into array

//Check for Mandatory parameters
if(isset($input['clientName']) && isset($input['siteName'])){
    $clientName = $input['clientName'];
  $siteName = $input['siteName'];
    //Check if client already exist
    if(!clientExists($clientName, $siteName)){
        //Query to add new material
        $insertQuery  = "INSERT INTO clients(clientName, siteName) VALUES (?,?)";
        if($stmt = $con->prepare($insertQuery)){
            $stmt->bind_param("ss",$clientName,$siteName);
            $stmt->execute();
            $response["status"] = 0;
            $response["message"] = "Client created";
            $stmt->close();
        }
    }
    else{
        $response["status"] = 1;
        $response["message"] = "Client exists";
    }
}
else{
    $response["status"] = 2;
    $response["message"] = "Missing mandatory parameters";
}
echo json_encode($response);
?>

Code for clientExists() function is as follows:

function clientExists($clientName,$siteName){
    $query = "SELECT clientName FROM clients WHERE clientName = ? AND siteName=?";
    global $con;
    if($stmt = $con->prepare($query)){
        $stmt->bind_param("ss",$clientName,$siteName);
        $stmt->execute();
        $stmt->store_result();
        $stmt->fetch();
        if($stmt->num_rows == 1){
            $stmt->close();
            return true;
        }
        $stmt->close();
    }
    return false;
}


texts:
The code below takes a specified number of card decks, and shuffles them according to the Fisher-Yates method. Does this implementation have any bias?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace randomShuffle
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> deck = Cards.startDeck(1);
        }
    }

    class Cards
    {
        public static List<int> startDeck(int numDecks)
        {
            List<int> initial = new List<int>();
            List<int> shuffled = new List<int>();

            //set up list of all cards in order
            while (numDecks > 0)
            {
                for (int i = 2; i <= 14; i++) //2-ace(14)
                {
                    for (int j = 0; j < 4; j++)  //each card in deck 4 times
                    {
                        initial.Add(i);
                    }
                }

                numDecks--;
            }

            //Fisher-Yates method to shuffle
            Random r = new Random(DateTime.Now.Millisecond);
            int count = initial.Count;
            for (int i = 0; i < count; i++) //go through entire unshuffled deck
            {
                //get random number from 0 to new range of unshuffled deck
                int randomDraw = r.Next(0, initial.Count);

                //take whatever is drawn and insert at beginning of shuffled list
                shuffled.Insert(0, initial[randomDraw]);

                //replace the card drawn with the end card
                initial[randomDraw] = initial.Last();

                //remove the end card from initia deck
                initial.RemoveAt(initial.Count - 1);
            }

            return shuffled;
        }
    }
}


texts: Encrypting a binary stream with RSA + AES in counter mode

texts:
I'm writing a little script that encrypts a file using the user's SSH identity.

I read the RSA private key from ~/.ssh/id_rsa (default)
Use the private key to encrypt a random 32 byte symmetric key (PKCS#1 OAEP)
Encrypt a stream of data with AES-256 in counter mode (no extra padding)
Write all of this to the output stream in 65535 byte chunks
Append an HMAC-SHA256 of the ciphertext

The idea is that data is encrypted on a user's computer before being pushed to the cloud. I'm using the SSH identity so that there's no passwords to worry about. If the user's ssh private key is compromised, the data being encrypted is compromised as well.

If the user wants to use a password, they'll just encrypt their private key.

Here's the code:

from Crypto import Random
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto.Hash import HMAC, SHA256

def encrypt_stream_v1(identity, stdin, stdout):
    rng = Random.new()
    iv = rng.read(8)  # counter mode prefix
    key = rng.read(32)  # random AES-256 key
    # AES-256 in counter mode
    aes = AES.new(key, mode=AES.MODE_CTR, counter=Counter.new(64, iv))
    mac = HMAC.new(key, digestmod=SHA256)  # HMAC-SHA256 for ciphertext
    with open(identity) as f:
        # the AES-256 key is encrypte with the users rsa private key
        key = PKCS1_OAEP.new(RSA.importKey(f.read())).encrypt(key)
    # the output stream begins with the 8 byte iv, the length of the
    # encrypted AES-256 key in two bytes and the encrypted key itself
    stdout.write(iv + len(key).to_bytes(2, "big") + key)
    while True:
        # encrypt in chunks of 65535 bytes (a two byte integer)
        chunk = aes.encrypt(stdin.read(0xFFFF))
        if chunk:
            # write the length of the encrypted chunk and the chunk itself
            stdout.write(len(chunk).to_bytes(2, "big") + chunk)
            # update the hmac with the ciphertext
            mac.update(chunk)
        if len(chunk) < 0xFFFF:
            break
    # the two null bytes represent an empty chunk, i.e. the end of the
    # ciphertext, the last 32 bytes of the output stream are the
    # HMAC-SHA256 digest
    stdout.write(b"\x00\x00" + mac.digest())

So the file format is as follows:

7a 70 79 01              # magic bytes and version number (01)
2c 81 6a 25 97 9c 8b 68  # counter iv
01 00                    # length of...
46 3e ........ 47 55 7e  # symmetric key encrypted with public key
00 08                    # length of...
22 12 11 01 2d 66 2e 66  # first encrypted block (repeated)
00 00                    # zero-length block signifies end of stream
18 9a ........ 0f 5a 0e  # hmac of the ciphetext

The reason the IV is 8 bytes is the counter. In order to get a 128 bit counter (the block size of AES), we use an incrementing 64 bit integer (via Crypto.Util.Counter) and prepend the random 64 bit iv.

Relevant links/documentation:

PyCrypto.Util.Counter
PyCrypto.Cipher.PKCS1_OAEP
Counter mode on Wikipedia

Is there anything wrong with how I'm using RSA/OAEP or AES-256-CTR? Is there anything I can optimize with the file format? Any mistakes I'm not seeing?

Changes so far

I'm including the entire file header (magic bytes, encrypted key length, encrypted key) in the HMAC-SHA256 calculation
I'm using a random 128 bit number as the initial value for the counter instead of effectively 64 bits with zeros appended.

Update: The project is now on GitHub


texts: Persistent, dictionary-like object ensurance

texts:
This is a part of a project I'm working on. The codebase is Python 2.7 and I don't have an option to switch to Python 3.

Code:

import shelve
def get_document_info():
    token_shelf = False

    try:
        token_shelf = shelve.open(os.path.join(current_dir, 'document_info.shelve'))
        token_mapping = token_shelf['token_mapping']

        if token_mapping:
            return token_mapping
        else:
            return False

    except Exception, e:
        pass

    finally:
        if token_shelf:
            token_shelf.close()

Shelve is a persistent, dictionary-like object. More info can be found at https://docs.python.org/2/library/shelve.html

I need to ensure that token_shelf is closed at the end. In the beginning of the function, what do I define token_shelf as? If I don't define something there, PyCharm will throw an error saying that the token_shelf in finally block does not exist.

What's the ideal way to write this piece of code? How can it be made more elegant and Pythonic?

PS: This code is working as expected right now.


texts:
What I'm trying to do here is first set the first eight variables to the proper default values. That's the first area I'm thinking there might be a way to optimize. Is there anyway to set both variables at once for example I know in PHP I could do $title=$d_title="value"; Is there any way to consolidate that section? (The variables prefixed with d_ will not change, but the same variable without the d_ may be changed.)

Then the rest of the snippet should do the following:

If the second argument is NOT "config"

Look in the file to see if the a line with the format ${sfile}_variablename="*" exists.

If it does, use sed to replace the contents of the quotes with the new variable
If it does not, append the line in its entirety

If the second argument IS "config"

If a line exists that contains ${sfile}_variablename, read in what's between the quotes and assign it to the variablename
If not, set the variablename to the default value

Below is how I was achieving that. Is there any way to do this in a more simplified or compact manner?

In this case, sdir is a base path I define elsewhere, and sfile is another prefix. Those are hard-coded into the top of the script, so those will always be correct.

d_finddir=${2:-"${sdir}/music/trine_soundtrack/"}
finddir=${d_finddir}

d_title=${3:-"Random Tangent"}
title=${d_title}

d_desc=${4:-"Random Tangent Playlist"}
desc=${d_desc}

d_rand=${5:-"randomize"}
rand=${d_rand}

if [ ! "${finddir}" = "config" ]; then
    if egrep -q "${sfile}_finddir" "${sdir}/config.cfg"; then
        sed -r -i "s,(${sfile}_finddir=).*,\\1\"${finddir}\"," "${sdir}/config.cfg"
    else
        printf "%s_finddir=\"%s\"\n" "${sfile}" "${finddir}" >>"${sdir}/config.cfg"
    fi

    if egrep -q "${sfile}_title" "${sdir}/config.cfg"; then
        sed -r -i "s,(${sfile}_title=).*,\\1\"${title}\"," "${sdir}/config.cfg"
    else
        printf "%s_title=\"%s\"\n" "${sfile}" "${title}" >>"${sdir}/config.cfg"
    fi

    if egrep -q "${sfile}_desc" "${sdir}/config.cfg"; then
        sed -r -i "s,(${sfile}_desc=).*,\\1\"${desc}\"," "${sdir}/config.cfg"
    else
        echo "${sfile}_desc=\"${desc}\"">>"${sdir}/config.cfg"
        printf "%s_desc=\"%s\"\n" "${sfile}" "${desc}" >>"${sdir}/config.cfg"
    fi

    if egrep -q "${sfile}_mode" "${sdir}/config.cfg"; then
        sed -r -i "s,(${sfile}_mode=).*,\\1\"${rand}\"," "${sdir}/config.cfg"
    else
        printf "%s_mode=\"%s\"" "${sfile}" "${rand}" >>"${sdir}/config.cfg"
    fi
else
    if egrep -q "${sfile}_finddir" "${sdir}/config.cfg"; then
        finddir=$(egrep "${sfile}_finddir" "${sdir}/config.cfg" | egrep -o "\".+\"" | sed 's/\"//g')
    else
        finddir=${d_finddir}
    fi

    if egrep -q "${sfile}_title" "${sdir}/config.cfg"; then
        title=$(egrep "${sfile}_title" "${sdir}/config.cfg" | egrep -o "\".+\"" | sed 's/\"//g')
    else
        title=${d_title}
    fi

    if egrep -q "${sfile}_desc" "${sdir}/config.cfg"; then
        desc=$(egrep "${sfile}_desc" "${sdir}/config.cfg" | egrep -o "\".+\"" | sed 's/\"//g')
    else
        desc=${d_desc}
    fi

    if egrep -q "${sfile}_mode" "${sdir}/config.cfg"; then
        rand=$(egrep "${sfile}_mode" "${sdir}/config.cfg" | egrep -o "\".+\"" | sed 's/\"//g')
    else
        rand=${d_rand}
    fi
fi


texts: Boost speed optimizations,C++ operator overloading

texts:
I am writing a part of the program where speed matters the most. In that part I am creating color spaces like RGB and other. In-fact I wrote these 2 structs.
struct RGB {
    unsigned char r;
    unsigned char g;
    unsigned char b;
}

struct ARGB {
    unsigned char a;
    unsigned char r;
    unsigned char g;
    unsigned char b;
}

And I will have like 10 structs like this for different spaces and I have to do operator overloading for all of them, so I did something like this. I created a struct ColorSpace<Type,Child> here is the code
//
// Created by Hrant Nurijanyan on 01.12.20.
//
template<typename T, typename C>
struct ColorSpace {

    const T* cbegin() const { return static_cast<const C*>(this)->arr.cbegin(); }

    const T* cend() const { return static_cast<const C*>(this)->arr.cend(); }

    const T* begin() const { return cbegin(); }

    const T* end() const { return cend(); }

    T* begin() { return static_cast<C*>(this)->arr.begin(); }

    T* end() { return static_cast<C*>(this)->arr.end(); }

    [[nodiscard]] size_t size() const { return std::distance(begin(),end()); }

    const T& operator[](unsigned int i) const {
        return *(begin() + i);
    }

    T& operator[](unsigned int i) {
        return *(begin() + i);
    }

    C& operator=(const C& rhs) {
        std::copy(rhs.begin(), rhs.end(), begin());
        return static_cast<C&>(*this);
    }

    C& operator=(const T& rhs) {
        std::fill(begin(), end(), rhs);
        return static_cast<C&>(*this);
    }

    C operator+(const C& rhs) const{
        C result;
        std::transform(rhs.begin(),rhs.end(),begin(),result.begin(),std::plus<>());
        return result;
    }

    C operator-(const C& rhs) const{
        C result;
        std::transform(begin(),end(),rhs.begin(),result.begin(),std::minus<>());
        return result;
    }

    C operator*(const C& rhs) const{
        C result;
        std::transform(begin(),end(),rhs.begin(),result.begin(),std::multiplies<>());
        return result;
    }

    C operator/(const C& rhs) const{
        C result;
        std::transform(begin(),end(),rhs.begin(),result.begin(),std::divides<>());
        return result;
    }

    C& operator+=(const C& rhs) {
        std::transform(begin(),end(),rhs.begin(),begin(),std::plus<>());
        return static_cast<C&>(*this);
    }

    C& operator-=(const C& rhs) {
        std::transform(begin(),end(),rhs.begin(),begin(),std::minus<>());
        return static_cast<C&>(*this);
    }

    C& operator*=(const C& rhs) {
        std::transform(begin(),end(),rhs.begin(),begin(),std::multiplies<>());
        return static_cast<C&>(*this);
    }

    C& operator/=(const C& rhs) {
        std::transform(begin(),end(),rhs.begin(),begin(),std::divides<>());
        return static_cast<C&>(*this);
    }

    bool operator==(const C& rhs) const {
        return std::equal(begin(),end(),rhs.begin());
    }

    bool operator!=(const C& rhs) const {
        return !std::equal(begin(),end(),rhs.begin());
    }

};

And then I updated my structs like this
struct RGB : ColorSpace<unsigned char, RGB> {
    union {
        std::array<unsigned char,3> arr;
        struct {
            unsigned char r;
            unsigned char g;
            unsigned char b;
        };
    };
};

As you can see I used CRTP to overload operators for each of the color space without much code. I just need to know is my implementation of struct ColorSpace the most performant? I need like super-speed. Please note I use Clang and target platforms are iOS Android Linux.
P.S. I know that I am doing type-punning here in child structs, but that does not really matter...


texts: Getting last and this monday as Unix timestamp in JavaScript

texts:
This is how I achieved it:

<script type="text/javascript">

// Get this monday
var dif, d = new Date();
dif = (d.getDay() + 6) % 7;
d = new Date(d.getTime() - dif * 24*60*60*1000);
d.setHours(0,0,0);
var thisMondayUnixtimestamp = Math.round((d.getTime() / 1000));

console.log('thisMondayUnixtimestamp', thisMondayUnixtimestamp);

// Get last monday
var beforeOneWeek = new Date(new Date().getTime() - 60 * 60 * 24 * 7 * 1000)
  , day = beforeOneWeek.getDay()
  , diffToMonday = beforeOneWeek.getDate() - day + (day === 0 ? -6 : 1)
  , lastMonday = new Date(beforeOneWeek.setDate(diffToMonday));
lastMonday.setHours(0,0,0);
var lastMondayUnixtimestamp = Math.round(lastMonday.getTime() / 1000);

console.log('lastMondayUnixtimestamp = ', lastMondayUnixtimestamp);

</script>

This works. Today is 24th of Jan 2016 and the timestamp values parsed returns the following:

last Monday:
string '11/01/2016 01:00:00' (length=19)

this Monday:
string '18/01/2016 01:00:00' (length=19)

Although this works, I am uncertain if it's correct and reliable as I have put the above together from snippets found via googling.

Is there a more elegant way to do this?


texts:
I started learning C++ and the first exercise was to create a small program to add two numbers. No more requirements. I did this and put a small validate the user input. I am sure that it could be much better written, so I appreciate all the critics and suggestions.

#include <iostream>

int x;
int sum = 0;
int i = 0;

int addTwoNumbers()
{
    while(i<2)
    {
        std::cin >> x;
        if(std::cin.fail())
        {
           std::cout << "Error! Invalid Input" << std::endl;
           std::cin.clear();
           std::cin.ignore(256,'\n');
        }
        else
        {
             sum += x;
             i++;
        }
    }
    return sum;
}
int main()
{
    std::cout << "Enter two integers" << std::endl;
    return sum = addTwoNumbers();
}


texts: Manage a collection of settings in memory with global scope

texts:
I have a WPF app and a bunch of read/write settings that need to be accessible from various view models. a setting can be any type (string, bool, etc) and all are settable, but only from a 'Settings' view. I also need the view models to be notified when any setting has been updated and which one that was.

Here is an enum with all the settings:

public enum Setting
{
    SettingA,
    SettingB,
    //etc
}

here is the settings class, as a singleton:

  internal sealed class Settings
{
    private static volatile Settings _instance;
    private static object _syncRoot = new object();
    private Dictionary<Setting, object> _settings;

    private Settings()
    {
        _settings = new Dictionary<Setting, object>();
        _settings.Add(Setting.SettingA, 1000);
        _settings.Add(Setting.SettingB, 1000);
    }

    public static Settings Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_syncRoot)
                {
                    if (_instance == null)
                    {
                        _instance = new Settings();
                    }
                }
            }
            return _instance;
        }
    }

    public void UpdateSetting(Setting key, object value)
    {
        if (_settings[key] != value)
        {
            _settings[key] = value;
            TriggerNotification(key, value);
        }
    }

    public T GetSetting<T>(Setting key)
    {
        return (T)_settings[key];
    }

    public event EventHandler<SettingsUpdatedEventArgs> OnSettingsUpdated;

    private void TriggerNotification(Setting key, object value)
    {
        var handler = OnSettingsUpdated;
        if (handler != null)
        {
            handler(this, new SettingsUpdatedEventArgs(key, value));
        }
    }
}

here is the overrided event args:

 public class SettingsUpdatedEventArgs : EventArgs
{
    public Setting Type { get; private set; }
    public object Value { get; private set; }

    public SettingsUpdatedEventArgs(Setting type, object value)
    {
        Type = type;
        Value = value;
    }
}

and here is how it is used:

    //update a setting value
    Settings.Instance.UpdateSetting(Setting.SettingA,200);

    //retrieve a setting value
    var value = Settings.Instance.GetSetting<int>(Setting.SettingA);

    //register a listener
    Settings.Instance.OnSettingsUpdated += (sender, args) =>
    {
        if (args.Type == Setting.SettingA)
        {
            var result = args.Value;
        }

    };

and now my questions:

Is there a problem having the settings class as a singleton?
Is this a type-safe way to get the setting values?
Is there a much better/simpler/more elegant way of doing this?


texts:
i wish to improve my Progressbar in Python

from __future__ import division
import sys
import time

class Progress(object):
    def __init__(self, maxval):
        self._seen = 0.0
        self._pct = 0
        self.maxval = maxval

    def update(self, value):
        self._seen = value
        pct = int((self._seen / self.maxval) * 100.0)
        if self._pct != pct:
            sys.stderr.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n')
            sys.stdout.flush()
        self._pct = pct

    def start(self):
        pct = int((0.0 / self.maxval) * 100.0)
        sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n')
        sys.stdout.flush()

    def finish(self):
        pct = int((self.maxval / self.maxval) * 100.0)
        sys.stdout.write("|%-100s| %d%%" % (u"\u2588"*pct, pct) + '\n')
        sys.stdout.flush()

toolbar_width = 300
pbar = Progress(toolbar_width)
pbar.start()
for i in xrange(toolbar_width):
    time.sleep(0.1) # do real work here
    pbar.update(i)
pbar.finish()


texts: Query for finding collection entries matching an arbitrary set of URLs

texts:
Most of my slow queries on my server are due to a single "find" query. I have a collection that represents website pages. I want to be able to look up a page in the collection by URL. The caveat is that a website might have URLs that redirect to it.

I've modeled my schema (with Node.js/Mongoose) like this:

{
        'url':                      { type: String, index: {unique: true, dropDups: true} },
        'redirects':                { type: Array, index: true },
        // ... other stuff
    }

In other words, one entry might have the URL http://codereview.stackexchange.com/ but also have an array of 5 other URLs (such as bit.ly URLs) that redirect to it.

Later, I want to query the collection to see if we have an entry which matches an arbitrary set of URLs. I don't know if the URLs are redirected URLs or what -- I just want to find all matches in my collection that represent these URLs.

So I do this:

// urls is an array of URL strings we want to find...
model.find({$or: [{'url': {$in: urls}}, {'redirects': {$in: urls}}]}).lean().exec( ... );

Unfortunately, I might be looking for around 200 URLs at once, so this query sometimes takes > 1 second.

Is there further optimization I can do, or would it be better to split the query into multiple queries, capping the search-size each time?


texts: Church Numerals - implement one, two, and addition

texts:
Given the following exercise:

  Exercise 2.6

  In case representing
  pairs as procedures wasn't
  mind-boggling enough, consider that,
  in a language that can manipulate
  procedures, we can get by without
  numbers (at least insofar as
  nonnegative integers are concerned) by
  implementing 0 and the operation of
  adding 1 as

(define zero (lambda (f) (lambda (x)
x)))

(define (add-1 n)   (lambda (f)
(lambda (x) (f ((n f) x)))))

  This representation is known as Church
  numerals, after its inventor, Alonzo
  Church, the logician who invented the
  calculus.

  Define one and two directly (not in
  terms of zero and add-1). (Hint: Use
  substitution to evaluate (add-1
  zero)). Give a direct definition of
  the addition procedure + (not in terms
  of repeated application of add-1).

I wrote this solution.  I'm not 100% certain what the correct answer is, and I'm not sure the best way to check my solution so it's possible that I have made a mistake in my answer.  Please let me know what you think.

;given definitions
(define zero (lambda (f) (lambda (x) x)))
(define (add-1 n)
  (lambda (f) (lambda (x) (f ((n f) x)))))
; exercise 2.6: define one and two directly -
; not in terms of zero or add-1
(define one
  (lambda (f) (lambda (x) (f (f x)))))
(define two
  (lambda (f) (lambda (x) (f ((f (f x)) x)))))

(define (church-plus a b)
  (define (church-num n)
    (cond ((= 0 a) (lambda (x) x))
          ((= 1 a) (lambda (f) (lambda (x) (f ((n f) x)))))
          (else (church-num (- n 1)))))
  (church-num (+ a b)))


texts: Forecasts for construction equipment dealers

texts:
I was wondering if it is possible to speed up this script? The source file has 90,000 rows, and it has to create a separate forecast for 1200 unique dealers using fbprophet. I'm new to python so I'm not sure if there is something obvious I'm missing, or if it's just going to have to take a really long time. If any sees a simple solution that would speed it up, I would appreciate any insight. Thank you
Additional details about code:
The code takes a CSV file that has 3 columns(Month, Dealer, and Sales) and creates a filter essentially for each unique dealer name, and then uses Fbprophet to forecast the future results of each dealer. Then it combines all the information in a CSV file. It's 90,000+ rows of data typically, and normally 1200 unique dealers that need to be forecasted. The historical data is 7 years of history.
from pandas import read_csv
from pandas import to_datetime
from pandas import DataFrame

from fbprophet import Prophet
from matplotlib import pyplot
import pandas as pd
# load data
data = read_csv('X.csv', header=0)
# prepare expected column names
data.columns = ['ds','Dealer', 'y']
data['ds']= to_datetime(data['ds'])

results = pd.DataFrame()

for dealer in data['Dealer'].unique():
    df_filtered = data[data['Dealer']==dealer]
    prophet_df = df_filtered[['ds', 'y']]
    # define the model
    model = Prophet()
    # fit the model
    model.fit(prophet_df)
    # define the period for which we want a prediction
    future = list()
    for h in range(11, 13):
        date = '2020-%02d' % h
        future.append([date])
    for i in range(1, 13):
        date = '2021-%02d' % i
        future.append([date])
    for j in range(1, 13):
        date = '2022-%02d' % j
        future.append([date])
    for k in range(1, 13):
        date = '2023-%02d' % k
        future.append([date])
    future = DataFrame(future)
    future.columns = ['ds']
    future['ds']= to_datetime(future['ds'])
    # use the model to make a forecast
    forecast = model.predict(future)
    forecast['Dealer'] = dealer
#     forecast.head(5)
    results = results.append(forecast)

results.to_csv('X1.csv')

Link to Sample Data: https://docs.google.com/spreadsheets/d/1lrkRQ9juDm7WZahsPV8oq2Rh7UFlFxCDpP4AgiTxTzU/edit?usp=sharing


texts: Tiny function to ensure a node of a BST has a valid relationship with its children

texts:
I need to write a method to ensure that all of the nodes of a BST (Binary Search Tree) are valid. For a node to be valid, 2 things must hold:

The left child must be less than the current node's value
The right child must be greater than the current node's value.

I decided to write a helper method that checks an individual node. Conceptually, it's easy enough, but the end result looks clumsy. I started out with:

//Returns true if the left node is less than the current node, and the right
// node is greater than the current node.
private boolean nodeIsValid() {
    if (hasLeft() && left.compareTo(this) > 0) return false;
    if (hasRight() && right.compareTo(this) < 0) return false;

    return true;
}

Then I realized I could combine the 2 guards into a single check:

private boolean nodeIsValid2() {
    if (hasLeft() && left.compareTo(this) > 0 ||
        hasRight() && right.compareTo(this) < 0)
            return false;

    return true;
}

But it seems pretty bulky still. Plus, given I'm just returning true or false based on a condition, I imagine this could be compacted down into a single statement (although I don't know if that would help readability).

Which of my two versions is more pleasant and readable?

Can the check be cleanly reduced to a single statement?


texts: NIO2 and ByteBuffer use for reading variable length messages

texts:
I am reading variable length messages where each message is an int + msg bytes. Messages could be any size.

Right now my strategy is to have a direct buffer that reads from the socket, which then transfers the bytes read into an array-backed nondirect buffer. However my solution has a lot of copying, some loops and just feels a bit "icky".

Is there a better solution?

Here is the read completion handler. I'm hoping it should be pretty obvious what is going on:

class DelimitedReadCompletionHandler implements CompletionHandler<Integer, Object> {

    private final AsynchronousByteChannel channel;
    private final Consumer<byte[]> onMessageCallback;
    private final ByteBuffer channelReadBuffer; // this is a direct buffer.

    private volatile ByteBuffer currentMessageBuffer;

    public DelimitedReadCompletionHandler(AsynchronousByteChannel channel,
                                          Consumer<byte[]> onMessageCallback,
                                          ByteBuffer channelReadBuffer) {

        this.channel = channel;
        this.onMessageCallback = onMessageCallback;
        this.channelReadBuffer = channelReadBuffer;
    }

    @Override
    public void completed(Integer result,
                          Object attachment) {

        channelReadBuffer.flip();

        do {
            if (currentMessageBuffer == null) {
                if (channelReadBuffer.remaining() < Integer.BYTES) {
                    channelReadBuffer.compact();
                    break;
                }

                currentMessageBuffer = ByteBuffer.allocate(channelReadBuffer.getInt());
            }

            int copyLength = Integer.min(currentMessageBuffer.remaining(), channelReadBuffer.remaining());

            for (int i = 0; i < copyLength; i++) {
                currentMessageBuffer.put(channelReadBuffer.get());
            }

            if (!currentMessageBuffer.hasRemaining()) {
                byte[] msg = currentMessageBuffer.array();
                ForkJoinPool.commonPool().execute(() -> onMessageCallback.accept(msg));

                currentMessageBuffer = null;
            }

            if (channelReadBuffer.hasRemaining()) {
                continue;
            }

            channelReadBuffer.clear();
            break;
        } while (true);

        channel.read(channelReadBuffer, null, this);
    }

    @Override
    public void failed(Throwable exc,
                       Object attachment) {

        exc.printStackTrace();
    }
}


texts: Program to automate clicking on the new button on a chat website until the username matches certain conditions

texts:
This is a python program that automates skipping through users on a chat website called
talkwithstrangers using the Selenium Webdriver and BeautifulSoup modules of python.

The first part uses selenium to open the browser

from selenium import webdriver
driver = webdriver.Chrome('C:\SeleniumDrivers\chromedriver.exe')
userName = 'null'
driver.get('https://talkwithstranger.com/talk-to-strangers')

The second part is a while loop that run while the username has not met the required conditions,

while 'female' not in userName or 'Female' not in userName:
    driver.get('https://talkwithstranger.com/talk-to-strangers')
    html = driver.execute_script("return document.documentElement.innerHTML;")

    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html, 'html5lib')
    userVal = soup.find(class_='alert text-center alert-success')
    userNames =  userVal.find_all('b')

    def getName(userNames):
        for name in userNames:
            return name.prettify()

    userName = getName(userNames)

The code is running fine but the problem is the efficiency and runtime.


texts: $.fn.do() method: Execute other code within a jQuery chain

texts:
What I want to do is; without leaving the chain, execute some custom/external code (and continue) within the chain. Otherwise; in a deep chain, I will have to re-query for the DOM element to get back where I've left.

The method below allows to execute custom code inside a jQuery chain synchronously or asynchronously.

//Execute code inside a jQuery chain
$.fn.do = function (callback, async) {
    if (typeof callback === 'function') {
        if (async === true) {
            this.queue(function() {
                callback($(this));
                $(this).dequeue();
            });
        } else {
            callback(this);
        }
    }
    return this;
};

Simplified Usage Example:

var results = {};
$('#some-elem')
    .css({
        //modify some styles here
    })
    .do(function($elem) {
        //do some calculations.. tests here..
        //save them to results object
    }, false) //synchronous
    .css({
        //re-set the styles back to their initial state
    });

This could be a longer chain where you could need to enter the do() method multiple times.

So;

Do you think the approach above is legitimate?
Would you suggest an alternate? Why?


texts: Tabbed user interface with a panel that expands downward

texts:
I have managed to get this to work but I am sure there is a better/more polished way to write this can anyone guide me to some shortcuts?

https://jsfiddle.net/zrpgvoL7/4

/* move the products down in the categories for the opening of filters/sort by aswell as slide down the filters or sort by sections */

var filterHeight = $('.product-filter').outerHeight() + 40;

var sortbyHeight = $('.sortby').outerHeight() + 20;

var speed = 1000

// hide by default instead of display:none in css as we need to find the height first

$('.product-filter').css('display', 'none');
$('.sortby').css('display', 'none');

// slide down filters/sort on click of 'refine' or 'sort' buttons

$('.clickable-header').click(function() {

$(this).toggleClass('active');

if ($(this).hasClass('active')) {

    if ($(this).hasClass('filter-header'))  {

        $('.clickable-header').removeClass('active');
        $(this).addClass('active');
        $('.sortby').slideUp(speed);
        $(this).parent().find('.dropable-section').slideDown(speed);
        $('#category-products').animate({ 'marginTop': filterHeight}, speed);
    }

    if ($(this).hasClass('sort-by-header'))  {

        $('.clickable-header').removeClass('active');
        $(this).addClass('active');
        $('.product-filter').slideUp(speed);
        $(this).parent().find('.dropable-section').slideDown(speed);
        $('#category-products').animate({ 'marginTop': sortbyHeight}, speed);
    }
}

else {

     if ($(this).hasClass('filter-header'))  {

        $(this).parent().find('.dropable-section').slideUp(speed);
        $('#category-products').animate({ 'marginTop': 0}, speed);
    }

    if ($(this).hasClass('sort-by-header'))  {

        $(this).parent().find('.dropable-section').slideUp(speed);
        $('#category-products').animate({ 'marginTop': 0}, speed);
    }

}

});


texts:
I setup simple CRUD in Django

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from intentions.models import User,Prayer,Intention
from intentions.forms import IntentionForm, DeleteIntentionForm

def index(request):
    intentions = Intention.objects.all();
    return render_to_response('intentions/templates/index.html',
                                {'intentions': intentions},
                                  context_instance=RequestContext(request)
                            )

def show(request, id):
    try:
        intention = Intention.objects.get(pk=id)
    except Intention.DoesNotExist:
        return render_to_response('intentions/templates/404_show.html')
    return render_to_response('intentions/templates/show.html',
                                {'intention': intention, 'delete_form': DeleteIntentionForm(instance=intention)},
                                 context_instance=RequestContext(request)
                              )

def new(request):
    if request.method == 'POST': # If the form has been submitted...
        form = IntentionForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            intention = form.save()
            return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST
    else:
        form = IntentionForm() # An unbound form

    return render_to_response('intentions/templates/form.html',
                                {'form': form, 'form_url': reverse_lazy('intention-new')},
                                 context_instance=RequestContext(request)
                              )
def edit(request, id):
    intention = Intention.objects.get(pk=id)
    if request.method == 'POST': # If the form has been submitted...
        form = IntentionForm(request.POST, instance=intention) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...

            intention = form.save()
            return HttpResponseRedirect(reverse_lazy('intention-show', args=[intention.id])) # Redirect after POST
    else:
        intention = Intention.objects.get(pk=id)
        form = IntentionForm(instance=intention) # An unbound form

    return render_to_response('intentions/templates/form.html',
                                {'form': form, 'form_url': reverse_lazy('intention-edit', args=[intention.id])},
                                 context_instance=RequestContext(request)
                             )

def delete(request, id):
    if request.method == 'POST':
        try:
            intention = Intention.objects.get(pk=id)
        except Intention.DoesNotExist:
            return render_to_response('intentions/templates/404_show.html')
        intention.delete()
        return HttpResponseRedirect('/')
    else:
        return render_to_response('intentions/templates/404_show.html')

I see some fragments for refactor, but I am newbie in Python and Django and I would like to get advices from more experienced users about refactoring this code too.