texts: Limiting access to configuration settings

texts:
Initially, I had my configuration data (database credentials, cookie expiry time..) in a GLOBALS variable, which I know is not a good idea. So now it is in a ConfigManager class which handles this information:

<?php
class ConfigManager {
    private $config;

    function __construct() {
        $this->config = array(
        'mysql' => array(
                    'host' => '127.0.0.1',
                    'username' => 'user',
                    'password' => 'pass',
                    'db' => 'mydb',
                ),
        'remember' => array(
                    'cookie_name' => 'hash',
                    'cookie_expiry' => 604800,
                ),
        'session' => array(
                    'session_name' => 'user',
                    'token_name' => 'token',
                )
        );
    }

    public function get()
    {
        return $this->config;
    }
}

In my DB class, I need the mysql array data, so I pass an instance of ConfigManager into the constructor of DB.

In my User class, I need the remember array data so I do the same. However, it does not seem a wise to allow the User class access to my db credentials when it does not need them. How do you advise I avoid allowing access to sensitive data in places that don't need it? Or should I not be worrying about this?

I access the configuration data with the following class:

<?php
class Config
{
    public static function get(ConfigManager $configManager, $path = null)
    {
            $config = $configManager->get();
            if($path) {
                $path = explode('/', $path);
                foreach($path as $bit){
                    if(isset($config[$bit])){
                        $config = $config[$bit];
                    }
                }
                return $config;
            }
    }
}

So my constructor of the User class looks like this:

public function __construct(ConfigManager $config, $user = null){

        $this->_session_name = Config::get($config, 'session/session_name');
        $this->_cookie_name = Config::get($config, 'remember/cookie_name');
        $this->_cookie_expiry = Config::get($config, 'cookie/cookie_expiry');

Any advice would be much appreciated, regarding my question above and any of the other code.


texts: How to refactor common methods that depend on local variables into a base class

texts:
I'm using Node.js and am creating some models for my different objects.  This is a simplified version of what they look like at the moment.

var Foo = module.exports = function () {

    var values = { type: 'foo', prop1: '', prop2: '' };

    function model() {}

    model.init = function(val) {
        _.extend(values, val);
        return model;
    }

    model.store = function(cb) {
        db.insert(values.type, values, cb);
    }

    model.prop1 = function(val) {
        if(!arguments.length) return values.prop1;
        values.prop1 = val;
        return model;
    }

    return model;
}

Then I can do:

var foo = Foo();
foo.init({prop1: 'a', prop2: 'b'}).store(function(err) { ... });

I then create another model:

var Bar = module.exports = function () {

    var values = { type: 'foo', prop3: '', prop4: '' };

    function model() {}

    model.init = function(val) {
        _.extend(values, val);
        return model;
    }

    model.store = function(cb) {
        db.insert(values.type, values, cb);
    }

    model.prop3 = function(val) {
        if(!arguments.length) return values.prop3;
        values.prop3 = val;
        return model;
    }

    return model;
}

At which point I realize that a lot of the functions, like model.init and model.store will be reused in each of the models. But while they are exactly the same code, they depend on the local values contained in the model closure.

What's the best way to pull these functions out into a common base class that I can then use to extend all of my models with?


texts: Most popular element with count in Array with Java

texts:
Here is the input array of int values

Example: { 5, 4, 6, 5, 1, 0, 7, 7, 3, 5 }

Find the most repeated element with its count, example output;  5 - repeated 3 times

Here is my code after some improvisations to improve the complexity from O(n)

class RepeatedEntry implements Comparable<RepeatedEntry> {
    private int number;
    private int count;

    public void setNumber(int number) {
        this.number = number;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getNumber() {
        return number;
    }

    public int getCount() {
        return count;
    }

    @Override
    public int compareTo(RepeatedEntry obj) {
        return obj.count - this.count;
    }
}

public class MaxCountOfDuplicate {

    public static RepeatedEntry findMostPopularItem(List<Integer> inputList) {
        Collections.sort(inputList);
        Set<RepeatedEntry> resultSet = new TreeSet<>();
        for (int i = 0; i < inputList.size(); i++) {
            int thisEle = inputList.get(i);
            int lastIndexOfThisEle = inputList.lastIndexOf(thisEle);
            int repeatedCount = (lastIndexOfThisEle - i) + 1;
            if (repeatedCount != 1) {
                RepeatedEntry repeatedEntry = new RepeatedEntry();
                repeatedEntry.setNumber(thisEle);
                repeatedEntry.setCount(repeatedCount);
                resultSet.add(repeatedEntry);
            }
        }
        return resultSet.iterator().next();
    }

    /* Given an input array find the duplicate element with max count. */
    public static void main(String[] args) {

        Integer[] x = { 5, 4, 6, 5, 1, 0, 7, 7, 3, 5 }; // input array
        RepeatedEntry finalResult = findMostPopularItem(Arrays.asList(x));

        System.out.println("Most repeated element and its count is -> \n");
        System.out.println(finalResult.getNumber() + " - repeated "
                + finalResult.getCount() + " times");

    }
}

Here are my relevant questions to this

I am sure the time complexity is not O(n) and O(n^2)
In this case, how do I calculate time complexity and what is it in this case?
And coming to space complexity, creating RepeatedEntry objects in a loop, is it a performance issue?

I have assumed the input array to be Integer wrapper, if it was strictly int primitive, the conversions and complexity's would increase I guess. I thought of storing the result in HashMap but avoided as it needs further processing to fetch the output, any answer using HashMap improving complexity would help me learn too and best possible solutions as well.


texts: Longest contiguous Increasing Subset in java

texts:
I have tried to come up with a solution to the longest increasing subsequence problem.Can this solution be optimized further?

Example 1:

Input: {5,4,3,7,8,9,11}
Output: 3, 7, 8, 9, 11

Example 2:

Input: {1,2,1,2,1}
Output: 1, 2 (the latest one)

Implementation:

 public class LongestIncreasingSubsequence {

        public static ArrayList<Integer>[] getLongestIncreasingSubsequence(int[] array, ArrayList<Integer>[] list,
                int index) {

            list[index] = new ArrayList<Integer>();

            if (index == 0) {
                list[index].add(array[index]);

            }

            else {

                if (array[index] > array[index - 1]) {
                    list[index].addAll(list[index - 1]);

                }

                    list[index].add(array[index]);

               }

            if (index == array.length - 1)
                return list;

            return getLongestIncreasingSubsequence(array, list, index + 1);

        }

        public static List<Integer> findLIS(int[] array) {

            ArrayList<Integer>[] arrayList = getLongestIncreasingSubsequence(array, new ArrayList[array.length], 0);

            int maxLength = arrayList[array.length - 1].size();
            int maxIndex = array.length - 1;
            for (int i = array.length - 2; i >= 0; i--) {
                if (arrayList[i].size() > maxLength) {
                    maxLength = arrayList[i].size();
                    maxIndex = i;
                }

            }

            return arrayList[maxIndex];

        }

        public static void main(String args[]) {

            int[] array = new int[] { 7, 1, 3, 8, 11 };

            List<Integer> LIS = findLIS(array);

            for (Integer i : LIS)
                System.out.print(i + ",");

        }
    }


texts:
I'm slurping up fields from an API that returns an array of fields. Each field in the array is a String that actually contains two separate fields (a number and a date). The number is enclosed in parentheses and the date is following this and a space. The following is an example of the format.
const data = [
            "(2) 2020-09-15", "(3) 2020-09-16"
        ];

I'm parsing this field and then storing the data separately in my app. I have my own numbers and dates fields that will be a String in which each number and date is separated by a newline.
I'm achieving this by doing the following.
let numbers = '', dates = numbers;

        for (let datum of data) {
            datum = datum.split(/[() ]/);
            numbers += `${datum[1]}\n`;
            dates += `${datum[3]}\n`;
        }

See an example here.
I don't particularly like this and am wondering if there's a more efficient and cleaner way to write this.


texts:
I have created a python program that prints a vertical bar graph made from fields and values inputted by the user. It works by first creating a horizontal bar graph and then going through each layer and determining whether to print a letter, a "|", a "_", or a space. I would appreciate any feedback on the program and things I could do to improve it.

import re

feilds = input("Input| ex: dogs,10 cats,23 birds,67\n").strip()
while not re.match("^(\w+,\d+ ?)+$", feilds):
  feilds = input("invalid input, use this format:\nfeild,value feild,value feild,value...\n").strip()
width = int(input("How wide is your output window in characters? "))
scale = float(input("Scale: "))
vals = dict([feild.split(",") for feild in feilds.split(" ")])
for k, v in vals.items():
  vals[k] = int(v)
spacing = int(width / len(vals.keys()))
horizontal = ["-" * int(v * scale) + "|" + k[::-1] for k, v in vals.items()]
vertical = []
for x in reversed(range(len(max(horizontal, key=len)))):
  layer = []
  for val in horizontal:
    try:
      if val[x] == "-":
        layer.append("|")
      elif val[x] == "|":
        layer.append("_")
      else:
        layer.append(val[x])
    except IndexError:
      layer.append(" ")
  vertical.append(layer)
print("\n")
print("\n".join((" " * (spacing - 1)).join(layer) for layer in vertical))

ex:

input:

dogs,20 cats,18 fish,25 birds,10
80
.5

output:

                                        f
                                        i
d                                       s
o                   c                   h
g                   a                   _
s                   t                   |
_                   s                   |                   b
|                   _                   |                   i
|                   |                   |                   r
|                   |                   |                   d
|                   |                   |                   s
|                   |                   |                   _
|                   |                   |                   |
|                   |                   |                   |
|                   |                   |                   |
|                   |                   |                   |
|                   |                   |                   |

NOTE: output might be messed up if the width is off by a lot. Make sure to input a width close to what it is.


texts:
I wrote some ugly JavaScript that is responsible for sending Ajax requests and update the DOM. I'm using it to show user progress of background jobs.

this.AjaxPoller = {
  poll: function() {
    setTimeout(this.AjaxPoller.request, 5000);
  },

  request: function() {
    $(".ajax_poller[data-url]").each(function(i, elem) {
      url = $(elem).data("url");

      $.getJSON(url, function(data) {
        if (checkProgress(data)) {
          location.reload();
        };

        $.each(data, function( key, val ) {
          $(key+ ' .progress_info').html(val);
          $(key + ' .progress-bar').width(val);
        });
      });
    });
  }
};

var checkProgress = function(obj) {
  correct = true;

  for (key in obj) {
    if (obj[key] != '100%') correct = false;
  }
  return correct;
}

What can I refactor in this code to make it better?


texts: Generate new latitude and longitude in decimal

texts:
I have created simple algorithm to generate the new Location from given latitude and longitude.

// How to use : first call SetupLocation(InputLat,InputLon float64) to set base latitude and longitude.
// To genreate the location you can call RandomLatLong() to generate using seconds degree.
// And RandomLatLongMinute to genereate new location using minute degree.
package location

import "math/rand"

var lat, lon float64

type LocationDegree struct {
    Degree  int
    Minutes int
    Seconds int
}

// setup base location for generating the new randon lat, lon value.
func SetupLocation(InputLat, InputLon float64) {
    lat = InputLat
    lon = InputLon
}

func ToDegree(location float64) LocationDegree {
    // get degree
    degree := int(location)
    location = location - float64(degree)

    // get minute
    multiply := location * 60.0
    minutes := int(multiply)
    location = multiply - float64(minutes)

    // get seconds
    multiply = location * 60
    seconds := int(multiply)

    // check if the decimal is 9 or 8 we are gointo round up
    location = multiply - float64(seconds)
    if location > 0.5 {
        seconds += 1
    }

    return LocationDegree{
        Degree:  degree,
        Minutes: minutes,
        Seconds: seconds,
    }

}

func ToDecimal(locationDegree LocationDegree) float64 {
    var result float64
    result = float64(locationDegree.Seconds) / 60.0

    result += float64(locationDegree.Minutes)

    result = result / 60.0

    result += float64(locationDegree.Degree)

    return result
}

// add seconds to lat or lon so we can get new location.
// we created array location so we can randomly select lat and lon to add new seconds degree.
// getting seconds value using pseu-do random from given seconds.
// returning latitude and longitude in order.
func RandomLatLong(seconds int) (float64, float64) {
    location := []float64{lat, lon}
    randomIndex := rand.Intn(len(location))

    randomSeconds := rand.Intn(seconds)

    // convert the lat or lon depends on random selection to degree
    degreeLocation := ToDegree(location[randomIndex])
    degreeLocation.Seconds += randomSeconds

    // convert the degree to decimal degree and replace it to the current index
    degreeDecimal := ToDecimal(degreeLocation)
    location[randomIndex] = degreeDecimal

    // return lat and lon in orner
    return location[0], location[1]
}

// add minute to lat or lon so we can get new location.
// we created array location so we can randomly select lat and lon to add new seconds degree.
// getting minute value using pseu-do random from given minute.
// returning latitude and longitude in order.
func RandomLatLongMinute(minute int) (float64, float64) {

    location := []float64{lat, lon}
    randomIndex := rand.Intn(len(location))

    randomMinute := rand.Intn(minute)

    // convert the lat or lon depends on random selection to degree
    degreeLocation := ToDegree(location[randomIndex])
    degreeLocation.Minutes += randomMinute

    // convert the degree to decimal degree and replace it to the current index
    degreeDecimal := ToDecimal(degreeLocation)
    location[randomIndex] = degreeDecimal

    // return lat and lon in orner
    return location[0], location[1]
}

I have created this during my spare time, and wanted to give it a try.
I know that this is not the best generated algorithm since it only add new random value to seconds or minutes and convert it to decimal again.

But I want to share this code and wanted to know if there are something that could be improved.

Source Code


texts: String reversal, capitalize vowels, lowercase consonants

texts:
This was a portion of a skills test given to me by a company. The task was to write a method that takes a string, reverses it, and sets the vowels as capitals and consonants to lowercase. I was also told to prove that my implementation works.

using System;
using System.Diagnostics;

namespace StringOperation
{
    using static Console;

    internal class Program
    {
        #region Entry

        private static void Main()
        {
            while (true)
            {
                WriteLine(MessageStrings.REQUEST_NAME);
                var strResult = ReadLine();

                var result = ProcessInput(string.IsNullOrEmpty(strResult) ? MessageStrings.PROOF : strResult );

                if ((ReadKey(true).Key ^ ConsoleKey.Y) == 0)
                    continue;
                break;
            }
        }

        #endregion

        #region Logic

        private static string ProcessInput(string input)
        {
            var output = new char[input.Length];

            var desc = output.Length;
            var asnd = -1;

            while(asnd++ <= desc--)
            {
                // unroll and reverse
                output[asnd] = Shift(input[desc]);
                output[desc] = Shift(input[asnd]);
            }

            return new string(output);
        }

        private static char Shift(char target)
        {
            // switching the 32 bit and returning the new value
            var i = (target | 0x20);

            // Checking if a the new value is a symbol
            if (i < 97 || i > 122)
                return target;

            switch (i)
            {

                case 97:
                case 101:
                case 105:
                case 111:
                case 117:
                    // Returning a capital vowel
                    return (char) (target & ~0x20);
                default:
                    // returning Lower case consonant
                    return (char) (i);
            }
        }

        #endregion
    }
}


texts:
I have several buttons and I want to toggle between them like radio buttons.

The way I have it set up now is that each button have this same code but the buttonValue varies depending on which button they click on.

ToggleButton one;
one = (ToggleButton) view.findViewById(R.id.number_one);
one.setOnClickListener(new View.OnClickListener()  {
    public void onClick(View view) {
        buttonValue = 1;
        ToggleButton tb = (ToggleButton) view;
        if(tb.isChecked()) {
            RadioGroup gridLayout = (RadioGroup) tb.getParent();
            for(int i=0; i<(gridLayout).getChildCount(); ++i) {
                View nextChild = (gridLayout).getChildAt(i);
                if(nextChild instanceof ToggleButton && nextChild.getId()==tb.getId()){

                }else if (nextChild instanceof ToggleButton && nextChild.getId()!=tb.getId() ){
                    ToggleButton tb2=(ToggleButton) nextChild;
                    tb2.setChecked(false);
                }
            }
        } else{
            RadioGroup gridLayout = (RadioGroup) tb.getParent();
            for(int i=0; i<(gridLayout).getChildCount(); ++i) {
                View nextChild = (gridLayout).getChildAt(i);
                if(nextChild instanceof ToggleButton && nextChild.getId()==tb.getId() ){
                    ToggleButton tb2=(ToggleButton) nextChild;
                    tb2.setChecked(false);
                }else if (nextChild instanceof ToggleButton && nextChild.getId()!=tb.getId() ){
                    ToggleButton tb2=(ToggleButton) nextChild;
                    tb2.setChecked(false);
                }
            }
        }
    }
});

I basically have the same code for 10 buttons! While the code works and the buttons toggle between each other, I don't think is the best approach (especially because it's so many lines of code for 10 buttons where the main isChecked() function is exactly the same in every onClick button listener.

I was wondering if there was a way so that I only have one button listener that increments the buttonValue based on what button was clicked and keeps the main isChecked() function the same.


texts:
I wrote the following code for creating a simple image carousel, that shows multiple images at the same time in the same order, but starting at a different position when the "next" or "prev" button is clicked.

This code works, but does it contradict programming principles and algorithms?

Is there a better solution?

var images = [
   "1.jpg",
   "2.jpg",
   "3.jpg"
];
let slider = document.getElementById("slider");
function next(){
  images.forEach((item , index)=>{
    if(slider.getAttribute("src") == item)
      if(index != images.length-1)
        nextIndex = index+1;
      else
       nextIndex = 0;
    });
   slider.setAttribute("src",images[nextIndex]);
}
function prev(){
  images.forEach((item , index)=>{
    if(slider.getAttribute("src") == item)
      if(index != 0)
         prevIndex = index-1;
      else
        prevIndex = images.length-1;
    });
   slider.setAttribute("src",images[prevIndex]);
}

  <button onClick = "prev()"> Prev </button>

  <button onClick = "next()"> Next </button>


texts: Learning PHP MVC: bootstrapping and front-controller

texts:
I am creating an MVC-Framework to learn more about how PHP and software architecture works in general.
My goal is to create a simple website with it.

Right now I have trouble on what exactly is the job of the bootstrap file and the FrontController Class.

Can you have a look if what I did makes sense to you?

My Bootstrap-File looks like this:

<?php

use app\core\FrontController;
use app\core\Router;

// include configuration, database and autoloader
require_once(realpath(__DIR__ .DS.'..') . "/config/config.php");
require_once(realpath(__DIR__ .DS.'..') . "/config/db.php");
require_once(realpath(__DIR__ .DS.'..'.DS.'..') . "/vendor/autoloader.php"); // autoload for the core MVC Framework

// load composer autoloader
require_once(realpath(__DIR__ .DS.'..'.DS.'..') . "/vendor/autoload.php");

// set routes
$route = isset($_GET['route']) ? $_GET['route'] : null;
$action = isset($_GET['action']) ? $_GET['action'] : null;

// get FrontController
$fc = new FrontController(new Router, $route, $action);

echo $fc->output();

And the FrontController Class

<?php

namespace app\core;

class FrontController {
    public $pdo;
    private $route, $routeName, $model, $controller, $view, $twig;

    public function __construct(Router $router, $routeName, $action = null) {
        $this->pdo = new \PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);

        //Fetch a route based on a name, e.g. "search" or "list" or "edit"
        $this->route = $router->getRoute($routeName);
        $this->routeName = $routeName;

        //Fetch the names of each component from the router
        $modelName = "\app\model\\".$this->route->model;
        $controllerName = "\app\controller\\".$this->route->controller;
        $viewName = "\app\\view\\".$this->route->view;

        //Instantiate each component
        $this->model = new $modelName($this->pdo);
        $this->controller = new $controllerName($this->model);
        $this->view = new $viewName($this->model);

        //Run the controller action
        if(!empty($action) && method_exists($this->controller, $action)) $this->controller->{$action}();

                // load TWIG
                $loader = new \Twig_Loader_Filesystem(realpath(__DIR__ .DS.'..'.DS.'..') . "/site/themes/".TPL_DEFAULT."/templates/"); // *!* replace TPL_DEFAULT with $theme
                $this->twig = new \Twig_Environment($loader, array(
                    'cache' => realpath(__DIR__ .DS.'..'.DS.'..') . "/cache/compilation/",
                ));
    }

    public function getRouteName() {
        return $this->routeName;
    }

    public function getModel() {
        return $this->model;
    }
    public function getController() {
        return $this->controller;
    }
    public function getView() {
        return $this->view;
    }

        public function output() {
                var_dump($this->twig);
                /* removed testing code for getting twig template on code Review SO */

        $nav = $this->view->output($this->routeName, "nav");

        var_dump($nav); // *!* test

        $page = $this->view->output($this->routeName);

        $title = $page["title"];
        $content = $page["content"];

        return $header . "<h1>" . $title . "</h1>" . $content . $footer;
    }
}

I thought maybe you could review these two files and tell me if I understood the use of them correctly.

For me it's like bootstrap is there to just import stuff like config, autoloader, FrontController.
And the FrontController does the basic handling of the Framework.

I hope this code makes at least some sense.
You can find the whole project here btw.


texts:
I wrote a python script that converts English to Entean language from an anime called "The Devil is a part timer".

This is the second version of the script which was first posted here Translating from English to Entean. This version is compatible with both Python 2 and 3.This version uses the str.maketrans method which is faster and more Pythonic.

In the anime, the language in Ente Isla is called Entean, which is basically most of the consonants in the English alphabet switched around. Vowels and the consonants 'L', 'N', 'Q' keep their original position. ABCDEFGHIJKLMNOPQRSTUVWXYZ is changed to AZYXEWVTISRLPNOMQKJHUGFDCB. For example, 'human' is 'tupan', and 'world' becomes 'foklx'.

import sys

PY2 = sys.version_info[0] == 2 #Returns True if Python version is 2

if PY2:
    from string import maketrans
else:
    maketrans = str.maketrans

FULL_ENGLISH_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
FULL_ENTEAN_ALPHABET =  "AZYXEWVTISRLPNOMQKJHUGFDCB"

FULL_ENGLISH_ALPHABET += FULL_ENGLISH_ALPHABET.lower()
FULL_ENTEAN_ALPHABET += FULL_ENTEAN_ALPHABET.lower()

tran_tab = maketrans(FULL_ENGLISH_ALPHABET, FULL_ENTEAN_ALPHABET)

def to_entean(text):
    return(text.translate(tran_tab))

def main(text=None, with_output=True):

    if text is None:
        if PY2:
            text = raw_input("Enter English text: ")
        else:
            text = input("Enter English text: ")

    if with_output:
        print(text)

    entean_text = to_entean(text)

    if with_output:
        print(entean_text)

if __name__ == "__main__":
    main()

If you interested the updated code can be found at https://github.com/Logmytech/English-to-Entean


texts:
Here is the question followed by my working program:

  Given a string, return a version without the first 2 chars. Except
  keep the first char if it is 'a' and keep the second char if it is
  'b'. The string may be any length. Harder than it looks.

deFront("Hello") → "llo"
deFront("java") → "va"
deFront("away") → "aay"

Can this code be improved?

public String deFront(String str) {
    if (str.length() >= 2) {
        char firstCharacter = str.charAt(0);
        char secondCharacter = str.charAt(1);
        if (firstCharacter == 'a' && secondCharacter == 'b') {
            // donot skip
            return str;
        } else if (firstCharacter == 'a' && secondCharacter != 'b') {
            // skip first character only
            return str.substring(0, 1) + str.substring(2);
        } else if (firstCharacter != 'a' && secondCharacter == 'b') {
            // skip second character only
            return str.substring(1);
        } else {
            return str.substring(2);
        }
    } else if (str.length() == 1 && str.charAt(0) == 'a') {
        return str;
    } else {
        return str;
    }
}


texts:
My task is that of caching. If the folder exists then load the cache from disk, if it doesnt create new cache. This is trivial, what bothers me is if I want to create third mode of noop (don't do anything relating to cache).

Currently I have this:

class HeavyCalculationClass:
    def __init__(self, cache_dir=None)
        self.use_cache = cache_dir is not None
        if self.use_cache:
            if os.path.exists(cache_dir):
                if len(os.listdir(cache_dir) != 0:
                    self.cache_type = "write"
                else:
                    self.cache_type = "read"
            else:
                os.mkdir(cache_dir)
                self.cache_type = "write"

    def __getitem__(self, idx):
        if self.use_cache and self.cache_type=="read":
            data = numpy.load(os.path.join(cache_dir, str(idx)+".npy"))
        else:
            data = very_heavy_calculation()

        if self.use_cache and self.cache_type == "write":
            numpy.save(os.path.join(cache_dir, str(idx)+".npy"), data)
        return data

Is there any way to write this in a more elegant form?


texts: HTML form enable one list of options or another

texts:
I'm trying to display a form where a user can select a specific item from a list or a specific category of items from another list. I want them to select one or the other, not both.

I followed this question which solves how to handle this in the backend.

I still need to figure out how to properly show this in the view.
I have the following sample which does what I would like to achieve, but I'm wondering if this is the way to go:

$('.formGroup input:checkbox').on('click', function() {
  var id = $(this).prop('id');
  var groups = $(this).parents('.formGroup').siblings('.formGroup');
  var thisGroup = $(this).parents('.formGroup');

  $('select', thisGroup).prop('disabled', false);

  $.each(groups, function(index, item) {
    var checkbox = $('input:checkbox', item);
    var select = $('select', item);

    checkbox.prop('checked', false);
    select.val(-1).prop('disabled', true);
  })
})

    <input type="checkbox" value="" id="Option1">Select an Item
  <select disabled="disabled">
    <option value=""></option>
    <option value="1">Item 1</option>
    <option value="2">Item 2</option>
    <option value="3">Item 3</option>
  </select>

    <input type="checkbox" value="" id="Option2">Or select a Category
  <select disabled="disabled">
    <option value=""></option>
    <option value="1">Category 1</option>
    <option value="2">Category 2</option>
    <option value="3">Category 3</option>
  </select>


texts: Split the array so that the sum of the numbers on one side of the split equals the sum of the numbers on the other side

texts:
I would really appreciate if you can help me to find a better way to do it.

public class SplitArray
{

    public SplitArray() { }

    public bool CanArrayBeSplit(int[] intArray)
    {
        foreach(var pair in GeneratePairs(intArray))
        {
            if (pair.Item1 == pair.Item2)
                return true;
        }

        return false;
    }

    private List<Tuple<int, int>> GeneratePairs(int[] integerArray)
    {
        var output = new List<Tuple<int, int>>();
        for (int i = 0; i < integerArray.Length -1; i++)
        {
            output.Add(Tuple.Create(GetSum(0, i+1, integerArray), GetSum(i + 1, integerArray.Length ,integerArray)));
        }
        return output;
    }

    private int GetSum(int startIndex, int endIndex , int[] array)
    {
        int sum = 0;

        for (int i = startIndex; i < endIndex; i++)
        {
            sum += array[i];
        }

        return sum;
    }
}


texts:
The 'Do' method is for prepared statements and returns (by fetchall()).  I am also using two looping statements.  Is there any better way to fetch two tables in one statement or query?  If not, what can I do to improve this code?

// 'id' is index in 'userinfo' table and 'id' in 'election' table is a child index(foreign key)
// 'ElectionId' is also the index, but it is not connected with othertable (only 'id' is linked)

 <?php
    $call = new world();
    $get = $call->Do("SELECT Votes, Views, id FROM election WHERE ElectionId = ?", array("electionIdUknwn"));
        foreach($get as $show)
            {

"Votes is :".$show[0]

                $add = $call->Do("SELECT username FROM userinfo WHERE id = ?", array($show[2]) );
                foreach($add as $display)
                {

"Username is :".$display[0]

                }

"Views are :".$show[1]

            }
  ?>


texts: Is there an easier way to use Rx's GroupBy operator?

texts:
I'm just playing with the concept of GroupBy inside Rx. So, I wondered how hard it would be to write a console application that continuously reads lines, groups them by similar words and just prints out the word among the current count of how often the word was written before. It really was a breeze to do that but I wonder if my attempt could be rewritten in a more elegant way. Especially if I can get rid of the nested Subscribes.

Here is what I have:

static void Main(string[] args)
{
    var subject = new Subject<string>();

    var my = subject.GroupBy(x => x);

    my.Subscribe(x => x.Scan(new { Chars = string.Empty, Count = 0},
                                 (a, chars) => new { Chars = chars, Count = a.Count + 1})
      .Subscribe(result => Console.WriteLine("You typed {0} {1} times", result.Chars,
                 result.Count)));

    while (true)
    {
        subject.OnNext(Console.ReadLine());
    }
}

Result

test
you typed test 1 times
test
you typed test 2 times
hallo
you typed test 1 times
test
you typed test 3 times
...


texts:
I have written the following code as the level rendering part of a game engine I am writing. I am very happy how it works but as it is the background / level graphics made up of individual blocks it needs to be quick.

What it does it look take the graphics from a resource loaded elsewhere and scales it onto the block if it is in the viewing window.

Blocksize is the size of the blocks and can be increased of decreased and is used to scale the blocks to give the Zoom in and out effect.

How can I improve this code both in terms of speed and shorten it to improve readability?

public void render(Graphics g){

    //Ensure player co-ords updated
    camerax=playerx-(gamewidth/2);
    cameray=playery-(gameheight/2);

    int blockwidth=blocksize-2;
    //Draw coloured blocks
    int screenx=-(int)camerax-blocksize;
    for (int x=0;x<sizex;x++){
          screenx+=blocksize;
          if (screenx>-blocksize && screenx<gamewidth){
              int screeny=-(int)cameray-blocksize;
              for (int y=0;y<sizey;y++){
              screeny+=blocksize;
              if (screeny>-blocksize && screeny<gameheight){
                if (tiles[x][y][0]>0){
                    g.drawImage(levelgraphics, screenx,screeny, screenx+blockwidth,screeny+blockwidth, graphicsize,0,graphicsize*2,graphicsize, null);
                } else {
                    g.setColor(new Color( tiles[x][y][1]));
                    g.fillRect(screenx,screeny,blockwidth,blockwidth);

                    g.setColor(Color.WHITE);
                    g.drawString(String.valueOf(x+y*sizex), screenx+5,screeny+20);
                }
              }
            }
        }
     }

    //world - camera = screen, algebra that world = screen + camera
    //Add camerax to mouse screen co-ords to convert to world co-ords.
    int cursorx_world=(int)camerax+(int)GameInput.mousex;
    int cursorx_grid=(int)cursorx_world/blocksize;  // World Co-ords / gridsize give grid co-ords
    int cursorx_screen=-(int)camerax+(cursorx_grid*blocksize);

    //Add cameray to mouse screen co-ords to convert to world co-ords.
    int cursory_world=(int)cameray+(int)GameInput.mousey;
    int cursory_grid=(int)cursory_world/blocksize;
    int cursory_screen=-(int)cameray+(cursory_grid*blocksize);

    //Draw on screen cursor
   if (cursorx_grid>=0 && cursory_grid>=0 && cursorx_grid<sizex && cursory_grid<sizey){
            //if (detect(cursorx_grid,cursory_grid)){
            //if (tiles[cursorx_grid][cursory_grid][0]>1){
                g.setColor(Color.yellow);
                g.drawRect(cursorx_screen,cursory_screen,blockwidth,blockwidth);
            //}
    }
    //Draw on screen map
    for (int x=0;x<sizex;x++){
        for (int y=0;y<sizey;y++){
            g.setColor(new Color((int) tiles[x][y][1]));
            g.fillRect(mapx+x*mapsize, mapy+y*mapsize, mapsize, mapsize);
        }
    }

   //Outline
            g.drawRect(mapx,mapy,mapsize*sizex ,mapsize*sizey );

   //Map location box
            g.setColor(Color.RED);
            g.drawRect(mapx+mapsize*((int)camerax/blocksize),mapy+mapsize*((int)cameray/blocksize),(gamewidth/blocksize)*mapsize ,(gameheight/blocksize)*mapsize );
}

The last bit of the code adds a map onto the screen and pops a scaled box on it so players can see what part of the map they are looking at.


texts: Translate strings from an XML attribute into corresponding constants in my module

texts:
I have a non-trivial list comprehension in Python.  My goal is to take a whitespace-delimited list of strings from an XML attribute — which may not exist — and look up the corresponding constant in my module — which may not exist — and create a set of the results.

What's the accepted way to format such a beast?  They all make me want to vomit a little.

    self.types = frozenset(
        v for v in (
            getattr(objects_module,enum_name,None)
            for enum_name in element.attrib.get('object-types', '').split())
        if v)

    self.types = frozenset(
        v
        for v in (getattr(objects_module,enum_name,None)
            for enum_name in element.attrib.get('object-types', '').split())
           if v)

    self.types = frozenset(
        v for v in (
          getattr(objects_module,enum_name,None)
          for enum_name in element.attrib.get('object-types', '').split()
        ) if v
    )

    self.types = frozenset(v for v in (getattr(objects_module,enum_name,None) for enum_name in element.attrib.get('object-types', '').split()) if v)


texts:
I wrote a Ruby gem to analyse strings for word length, word density, and a few more hand methods...

The Counter class accepts a filter (String). The class will remove any words from the original string that you include in the filter. Spec:

  it "removes words passed in the filter" do
    counter = Counter.new("That was magnificent, Trevor.", filter: "magnificent")
    expect(counter.words).to eq(%w[That was Trevor])
  end

I added a feature that allows you to send in a Regexp filter instead of a string. It's my first use of Procs, and I'm sure it can be done better. It's not very readable, and probably not efficient.

  it "it accepts a regexp filter" do
    counter = Counter.new("That was magnificent, Trevor.", filter: /magnificent/i)
    expect(counter.words).to eq(%w[That was Trevor])
  end

def initialize(string, options = {})
  @options = options
  @char_count = string.length
  # Here I split the wrongs from the string, then call reject to
  # remove any words that meet the filter criteria
  @words = string.scan(regex).reject { |word| filter.call(word) }
  # ...
end

# The filter method checks to see if the filter is a string or a Regexp
# It returns a proc object that acts according.
def filter
  filters = @options[:filter]
  if filters.is_a?(String)
    f = filters.split.collect { |word| word.downcase }
    Proc.new { |w| f.include?(w.downcase) }
  elsif filters.is_a?(Regexp)
    Proc.new { |w| w =~ filters }
  else
    Proc.new {}
  end
end

As you can see, it looks a bit messy compared to the original methods:

def initialize(string, options = {})
  @options = options
  @char_count = string.length
  @words = string.scan(regex).reject { |word| filter.include? word.downcase }
  # snip...
end

def filter
  if filters = @options[:filter]
    filters.split.collect { |word| word.downcase }
  else
    []
  end
end

For the sake of brevity I have not included the enter class, but you can see it here (65 lines). And here is a gist of my proposed changes. Only the initialise and filter methods change.


texts:
Yes, I made it up.

This program checks if an entered string is a palindrome or not by assigning a char variable the characters in the inserted word in reverse order. The program then takes the variable and appends it to a  StringBuilder to be able to compare the original word and the finalized reversed version.

package Palindrome;

import java.util.Scanner;

public class palindrome {

static String word;
StringBuilder reversedWord = new StringBuilder();

public palindrome() {
    char reversedChar;

    for (int i = 1; i < word.length() + 1; i++) {
        reversedChar = word.charAt(word.length() - i);
        reversedWord.append(reversedChar);
    }
}

public void checkPalindrome() {
    if(word.equalsIgnoreCase(reversedWord.toString())) {
        System.out.println("You got a Palindrome!");
    }else{
        System.out.println("That's not a Palindrome...");
    }
}

public static void main(String[] args) {
    System.out.print("Enter a word to check Palindromness: ");
    Scanner scan = new Scanner(System.in);
    word = scan.next();
    scan.close();
    new palindrome();
    new palindrome().checkPalindrome();
    }
}


texts: Intercept read access to a certain object attribute

texts:
I have a library that accepts a file-like object but assumes that it has a valid .name unless that name is None. This causes it to break when I pass e.g. someproc.stdout as it has a name of <fdopen>. Unfortunately the attribute cannot be deleted or overwritten.

So I've written this simple wrapper to return None in case the name attribute is requested.

class InterceptAttrWrapper(object):
    def __init__(self, obj, attr, value):
        self.obj = obj
        self.attr = attr
        self.value = value

    def __getattribute__(self, name):
        ga = lambda attr: object.__getattribute__(self, attr)
        if name == ga('attr'):
            return ga('value')
        return getattr(ga('obj'), name)

This seems to work fine, I'm using it like this:

proc = subprocess.Popen(..., stdout=subprocess.PIPE)
some_func(InterceptAttrWrapper(proc.stdout, 'name', None))

However, I wonder if:

My InterceptAttrWrapper object is missing something that could cause problems.
There is a better way to access attributes within __getattribute__. That lambda I'm using right now looks pretty ugly.


texts: Angular UI-Router Repetitive templateProvider Using $rootScope

texts:
I am developing an application that has different configurable versions - "a1" and "a2". The version name is initially being set from the database as "a1" in the $rootScope.

I reference the version name in every templateProvider in UI-Router, which ends up being over 30 times:

.state('app.auto.public.inventory.list', {
    url: '/',
    views: {
        'auto-one@app.auto': {
            templateProvider: ['$rootScope', '$templateCache', function($rootScope, $templateCache) {
            return $templateCache.get($rootScope.autoVersion + '/html/inventory/list/index.html');
        }],
        controller: 'InventoryList'
        }
    }
})

There must be a better way to access the value of "a1", instead of referencing $rootScope.autoVersion so many times?


texts: Generating an ordinal number for the day of the month

texts:
I am relatively new to programming and came across an if statement that I believe to be a bit verbose. I have tested my code and it appears to work without any issues, but I am wanting to know if there is a more efficient means or better shorthand of an if statement checking "day".

NSDate *now = [[NSDate alloc] init];
NSLog(@"The date is %@", now);

double seconds = [now timeIntervalSince1970];
NSLog(@"It has been %f seconds since the start of 1970.", seconds);

NSCalendar *cal = [NSCalendar currentCalendar];
NSLog(@"My calendar is %@", [cal calendarIdentifier]);

unsigned long day = [cal ordinalityOfUnit:NSCalendarUnitDay
                         inUnit:NSCalendarUnitMonth
                         forDate:now];

if (day == 1 || day == 21 || day == 31) {
        NSLog(@"Today is the %lust day of the month", day);
    } else if (day == 2 || day == 22) {
        NSLog(@"Today is the %lund day of the month", day);
    } else if (day == 3 || day == 23) {
        NSLog(@"Today is the %lurd day of the month", day);
    } else {
        NSLog(@"Today is the %luth day of the month", day);
    }


texts:
Here is an array based stack. I tried to implement this basic stack from memory. I want to make sure it is correct.

import java.util.*;

public class Stack{
    private int[] stack;
    private int size;

    public Stack(){
        stack = new int[5];
        int size = 0;
    }

    public Stack(int capacity){
        stack = new int[capacity];
        int size = 0;
    }

    public void push(int pushedValue){
        if(size == stack.length){
            throw new fullStackException();
        }
        stack[size] = pushedValue;
        size++;
    }

    public int pop(){
        if(size == 0){
            throw new emptyStackException();
        }
        int poppedValue = stack[size - 1];
        size--;
        return poppedValue;
    }

    public int peek(){
        if(size == 0){
            throw new emptyStackException();
        }
        return stack[size - 1];
    }

    private class emptyStackException extends RuntimeException{
        public emptyStackException(){
            super();
        }
    }

    private class fullStackException extends RuntimeException{
        public fullStackException(){
            super();
        }
    }

}


texts: Returning postal codes between the ones that are given

texts:
I have a function that returns postal codes between the ones given. It works but I feel like I made this over-complicated and there's easy way to make it more simple but I have no idea how.

Inputs are two strings that represents postal codes of my country. They are in the format 'XX-XXX' where X is [0-9]. The task is to return postal codes between them.

Example:

Input: '80-998' '81-003'

Output: '80-998' '80-999' '81-000' '81-001' '81-002' '81-003'

def codes():
    x = '79-900'
    y = '80-155'

    x1 = int(x.split('-')[0])
    x2 = int(x.split('-')[1])
    y1 = int(y.split('-')[0])
    y2 = int(y.split('-')[1])

    while x1 <= y1:
        if x1 == y1:
           while x2 <= y2:
                print ('{}-{:03d}'.format(x1,x2))
                x2 += 1
        else:
            while x2 < 1000:
                print ('{}-{:03d}'.format(x1,x2))
                x2 += 1
        x1 += 1
        x2 = 0


texts: Google Kickstart Round A 2019 - Training

texts:
Problem: Training

  As the football coach at your local school, you have been tasked with
  picking a team of exactly P students to represent your school. There
  are N students for you to pick from. The i-th student has a skill
  rating Si, which is a positive integer indicating how skilled they
  are.

  You have decided that a team is fair if it has exactly P students on
  it and they all have the same skill rating. That way, everyone plays
  as a team. Initially, it might not be possible to pick a fair team, so
  you will give some of the students one-on-one coaching. It takes one
  hour of coaching to increase the skill rating of any student by 1.

  The competition season is starting very soon (in fact, the first match
  has already started!), so you'd like to find the minimum number of
  hours of coaching you need to give before you are able to pick a fair
  team.

  Input

  The first line of the input gives the number of test cases, T. T test
  cases follow. Each test case starts with a line containing the two
  integers N and P, the number of students and the number of students
  you need to pick, respectively. Then, another line follows containing
  N integers Si; the i-th of these is the skill of the i-th student.

  Output

  For each test case, output one line containing Case #x: y, where x is
  the test case number (starting from 1) and y is the minimum number of
  hours of coaching needed, before you can pick a fair team of P
  students.

  Limits

  Time limit: 15 seconds per test set.
  Memory limit: 1 GB.
  1 ≤ T ≤ 100.
  1 ≤ Si ≤ 10000, for all i.
  2 ≤ P ≤ N.
  Test set 1 (Visible)
  2 ≤ N ≤ 1000.
  Test set 2 (Hidden)
  2 ≤ N ≤ 105.

  Sample

  Input

3
4 3
3 1 9 100
6 2
5 5 1 2 3 4
5 5
7 7 1 7 7

  Output

Case #1: 14
Case #2: 0
Case #3: 6

  In Sample Case #1, you can spend a total of 6 hours training the first
  student and 8 hours training the second one. This gives the first,
  second and third students a skill level of 9. This is the minimum time
  you can spend, so the answer is 14.

  In Sample Case #2, you can already pick a fair team (the first and
  second student) without having to do any coaching, so the answer is 0.

  In Sample Case #3, P = N, so every student will be on your team. You
  have to spend 6 hours training the third student, so that they have a
  skill of 7, like everyone else. This is the minimum time you can
  spend, so the answer is 6.

My solution

#include <iostream>
#include <vector>
#include <algorithm>

void getData(int &p, std::vector<int> &skills) {
    int n;
    std::cin >> n >> p;
    skills.reserve(n);
    for (int i = 0; i < n; i++) {
        int skill = 0;
        std::cin >> skill;
        skills.emplace_back(skill);
    }
}

int minTrainingTime(std::vector<int> &skills, int p) {
    std::sort(skills.begin(), skills.end());
    int low = 0, high = p - 1;

    int currentResult = 0;
    for (int i = 0; i < high; i++) {
        currentResult += skills[high] - skills[i];
    }

    int minResult = currentResult;
    int remainingPossibilities = skills.size() - p;
    for (int i = 0; i < remainingPossibilities; i++) {
        currentResult -= skills[++high] - skills[low++];
        currentResult += p * (skills[high] - skills[high - 1]);
        minResult = std::min(minResult, currentResult);
    }

    return minResult;
}

int main() {
    int t = 0;
    std::cin >> t;
    for (int testCase = 0; testCase < t; testCase++) {
        int p;
        std::vector<int> skills;
        getData(p, skills);

        std::cout << "Case #" << testCase + 1 << ": " << minTrainingTime(skills, p) << std::endl;
    }
}

Analysis

Time complexity: \$O(n\log n)\$, dominated by sorting

Space complexity: \$O(1)\$, not counting the original data given by the problem


texts: Python webscraping for lists of company names and details using BeautifulSoup

texts:
I just started learning Python and made a script that scrapes a corporate directory
https://www.sccci.org.sg/en/directory/corporate/members

So far it gets all the company names and their details under one category page (although i do intend on making it automatically get the details of the other pages too in the future) and writes them into a text file.

However the code uses a lot of nested loops and i am looking to see if there is a better way to code it in terms of efficiency and good practice.

Here is the code:

#Author: James
#Date: 9/11/2017
#nlist stores company names
#detlist stores the details
#finlist stores the href links required to scrape the subsites of SCCCI
import requests
from bs4 import BeautifulSoup
check = False
finlist = []
nlist = []
detlist = []
r = requests.get("https://www.sccci.org.sg/en/directory/corporate/members?ind=150")
soup = BeautifulSoup(r.content, "html.parser")
#finds all the links in the html class "listing" and store them in "finlist"
for items in soup.findAll("div", {"class" : "listing"}):
    for a in items.findAll("ol"):
        for b in a.findAll("a"):
            finlist.append("https://www.sccci.org.sg" + b.get("href"))
#enters each site in finlist and gets the company name found in "member-name"
for record in finlist:
    print("Entering " + record + "...")
    lr = requests.get(record)
    lsoup = BeautifulSoup(lr.content, "html.parser")
    for o in lsoup.findAll(["span"], {"class" : "member-name"}):
        nlist.append(o.get_text("\n",strip=True))
    for o in lsoup.findAll("div", {"class" : "member-info hidden"}):
        detlist.append(o.get_text("\n",strip=True))
    #this loops checks for any additional pages in the link and searches though the additional sites for names and details too
    for j in lsoup.findAll("li", {"class" : "pager-item"}):
        for b in j.findAll("a"):
            print(" Entering https://www.sccci.org.sg" + b.get("href") + "...")
            mR = requests.get("https://www.sccci.org.sg" + b.get("href"))
            mSoup = BeautifulSoup(mR.content, "html.parser")
            for soups in mSoup.findAll("span", {"class" : "member-name"}):
                nlist.append(soups.get_text("\n",strip=True))
            for soups in mSoup.findAll("div", {"class" : "member-info hidden"}):
                detlist.append(soups.get_text("\n",strip=True))

# Request process end -- File dump process start --

print("Start file dump...")
text_file = open("debug.txt", "w", encoding="utf-8")
#combines the namelist and detaillist into the finalList
finalList = [j for i in zip(nlist,detlist) for j in i]
for zippy in finalList:
    zippy = zippy.replace("                                    "," ")
    zipstring = str(zippy)
    text_file.write(zipstring + "\n\n")
text_file.close()
text_file_names = open("cnames.txt", "w", encoding="utf-8")
count = 0
for names in nlist:
    count+= 1
    names = str(names)
    text_file_names.write(str(count) + " | " + names + "\n")
text_file_names.close()
text_file_pnames = open("names.txt", "w", encoding="utf-8")
for pnames in nlist:
    pnames = str(pnames)
    text_file_pnames.write(pnames + "\n")
text_file_pnames.close()
finalitem = len(finalList)/2
print("Done | " + str(finalitem) + " items")
print("Files generated: names.txt | debug.txt | cnames.txt")


texts:
I have a shell script to configure Synaptics touchpad settings at login.

Background

You configure the touchpad with the synclient command. Its usage is

  synclient [-lV?] [var1=value1 [var2=value2] ...]

For example:

synclient PalmDetect=1 — to set a single setting
synclient PalmDetect=1 PalmMinZ=10 — to set multiple

I'm trying to use my script itself as a configuration file by playing around with heredocs and grep. The script greps out all comment lines (starting with #) and then passes everything in the heredoc as arguments to synclient. Is this code clean? How could I improve it?

Script

#!/bin/sh
# script to configure Synaptic touchpad settings
# This script treats itself as a configuration file.

<< END_OF_SETTINGS grep -v '^#' | xargs synclient

# Try to disable touchpad while typing
PalmDetect=1
PalmMinZ=100

# Allow three-finger middle button tap, click
TapButton3=2
ClickFinger3=2

END_OF_SETTINGS


texts: JavaScript function that reuses a modal for adding, deleting, and viewing an item

texts:
I have a table that has buttons per row that makes views/edit an item in a modal and they have a layout like so:

    <button class="btn btn-sm btn-default" onclick="setModalMode('view', '8')" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>
    &nbsp;
    <button class="btn btn-sm btn-info" onclick="setModalMode('update', '8')" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>
    &nbsp;
    <button class="btn btn-sm btn-danger" onclick="setModalMode('delete', '8')" data-toggle="modal" data-target="#license-add" data-id="8">

    </button>

It calls the setModalMode functiton and toggles the mode of the modal:
let modal = 'div#license-add';
let $form = $('form#modal-form');
let modalMode = ''; // this is used by my AJAX function to point what URL should my requests go
let rowObjects = []; // this gets filled up by values on a different function everytime my table generates

function setModalMode(mode, id) {
    loadingOverlay(false, modal);
    modalMode = mode;

    let title = 'Modal title';
    let inputsDisabled = false;
    let hasData = true;
    let needsButton = true;
    let isDelete = false;

    if (mode === 'add') {
        title = 'Add new license';

        hasData = false;
    } else if (mode === 'update') {
        title = 'Updating license';
    } else if (mode === 'view') {
        title = 'Viewing license';

        needsButton = false;
        inputsDisabled = true;
    } else if (mode === 'delete') {
        title = 'Delete this license?';

        inputsDisabled = true;
        isDelete = true;
    } else {
        return;
    }

    if (hasData) {
        let data = rowObjects['license', id];

        $form.find('input#email').val(data.email);
        $form.find('input#key').val(data.activation_key);
        $form.find('input#expiration').val(moment(data.expiration).format('MM/DD/YYYY'));
        $form.find('select#type-select').val(data.type);
        $form.find('input#hidden-id').val(data.id);
    } else {
        $form.find(':input').val('');
    }

    if (needsButton) {
        if (isDelete) {
          $('#deleteButton', modal).show();
          $('#submitButton', modal).hide();
        } else {
          $('#deleteButton', modal).hide();
          $('#submitButton', modal).show();
        }
    } else {
        $('#submitButton', modal).hide();
        $('#deleteButton', modal).hide();
    }

    $('h4#modal-title', modal).text(title);
    $form.find(':input').prop('disabled', inputsDisabled);
}

Although the code does its job perfectly well, I feel like my code is a mess of if statements


texts: PayPal Checkout API with PHP - Sending and retrieving additional data safely

texts:
I am learning to use the new API version of Paypal, and I have some doubts.

  Note: I've tried this on https://www.sandbox.paypal.com and it works,
  I have not done the tests on Live.

onApprove:

I need to send additional personalized data to Paypal, and once the user makes the payment, I return to a URL on my server, and then retrieve the data I sent.

Paypal uses fetch() to do to specify the URL and a Json object called headers, there I am adding the additional value called user_ID that I need to recover.

I am using the PHP function getallheaders(), to retrieve user_ID, which I have specified.

My questions are:

Is this a correct way to send personalized data to PayPal and then be recovered?
It is safe to use getallheaders(), I understand that the headers can be modified before being sent, is there any possibility that these can be altered?
Using $_SERVER['HTTP_REFERER'], to detect that the referred website is from Paypal, is this still safe or difficult to break?
Would this be a secure way to integrate Paypal Checkout?
Any recommendation that can give me, please.

I would greatly appreciate your help.

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <input type="text" id="price" value="100.00">
  <input type="hidden" id="user_id" value="15">


texts:
I am trying to get a powerset (all subsets of a set) in Java. So my logic for that is:

A given set is one subset, so add so it as it is to result.
Remove each element of set from given set and we will get all the combinations for 1 element less. Add these results to final result.
Recursively find subsets of all sets from step 2 and add to result.

I tried searching for a similar solution on Stack Overflow but did not get one. Is this a clean way to implement it?

import java.util.*;

public class PowerSet {
    public static <E> Set<Set<E>> findPowerSet(Set<E> set){
        Set<Set<E>> ret = new HashSet<Set<E>>();
        ret.add(set);
        if(set.isEmpty()){
            return ret;
        }
        Iterator<E> it = set.iterator();
        while(it.hasNext()){
            Set<E> tmp = new HashSet<E>(set);   //create a copy of current set
            tmp.remove(it.next());              //remove current element from copy set
            ret.add(tmp);                       //add the remaining set to result
            ret.addAll(findPowerSet(tmp));      //recursively find subsets of copy set
        }
        return ret;
    }

    public static void main(String[] args) {
        Set<Character> set = new HashSet<Character>();
        set.add('a');set.add('b');set.add('c');
        System.out.println("Input set");        printSet(set);
        System.out.println("\nsub sets");
        findPowerSet(set).stream().forEach(PowerSet::printSet);
    }

    public static <E> void printSet(Set<E> set){
        StringBuilder sb = new StringBuilder(set.size()==0 ? "{}\n" :"{");
        Iterator<E> it = set.iterator();
        while(it.hasNext()){
            sb.append(it.next().toString())
            .append(it.hasNext()? ", " : "}\n");
        }
        System.out.print(sb.toString());
    }
}


texts: Correctly count the number of pairs in an irregular list structure

texts:
From SICP:

For background, here is exercise 3.16:

  Exercise 3.16

  Ben Bitdiddle decides
  to write a procedure to count the
  number of pairs in any list structure.
  It's easy,'' he reasons.The
  number of pairs in any structure is
  the number in the car plus the number
  in the cdr plus one more to count the
  current pair.'' So Ben writes the
  following procedure:

(define (count-pairs x)
  (if (not (pair? x))
      0
      (+ (count-pairs (car x))
         (count-pairs (cdr x))
         1)))

  Show that this procedure is not
  correct. In particular, draw
  box-and-pointer diagrams representing
  list structures made up of exactly
  three pairs for which Ben's procedure
  would return 3; return 4; return 7;
  never return at all.

My solution is to the following question:

  Exercise 3.17

  Devise a correct
  version of the count-pairs procedure
  of exercise 3.16 that returns the
  number of distinct pairs in any
  structure. (Hint: Traverse the
  structure, maintaining an auxiliary
  data structure that is used to keep
  track of which pairs have already been
  counted.)

Here it is:

(define (count-pairs x)
  (define (iter x sum already-counted)
    (if (or (not (pair? x))
            (member x already-counted))
        (list sum already-counted)
        (let ((car-result (iter (car x) (+ sum 1) (cons x already-counted))))
          (iter (cdr x) (car car-result)
                (cadr car-result)))))
  (car (iter x 0 '())))

(define (last-pair x)
  (if (null? (cdr x))
      x
      (last-pair (cdr x))))

(define a '(a b c))
(count-pairs a)

(set-cdr! (last-pair a) a)
(count-pairs a)

(define b '(a b c))
(set-car! b (last-pair b))

(count-pairs b)

Can it be improved?


texts: Rails 5.2 callbacks to trigger score recalculation for relationships

texts:
I have a model that is in a HABTM relationship with 2 other models:

Activity.rb

  has_and_belongs_to_many :mandates, -> { distinct }
  has_and_belongs_to_many :contacts, -> { distinct }

I had to add the following callbacks, since the models defined above have a 'score algorithm' that must be recomputed if activities are removed completely, or one is created initially:

  after_commit  :increase_contact_scores, :increase_mandate_scores
  after_destroy :decrease_contact_scores, :decrease_mandate_scores

The callbacks code seems horribly the same. Is there a way to simplify this by somehow passing the HABT relation class from the callback to a more 'generic' method that can replace these?

I also need to figure out how to ONLY trigger the relevant callback based on the type of the HABTM (ie. not call both increases and both decreases, since if a mandate is destroyed, calling the decrease_contacts_score method will fail).

  def increase_contact_scores
    contacts.each do |contact|
      if contact.activities.count == 1
        contact.calculate_score
        contact.save!
      end
    end
  end

  def increase_mandate_scores
    mandates.each do |mandate|
      if mandate.activities.count == 1
        mandate.calculate_score
        mandate.save!
      end
    end
  end

  def decrease_contact_scores
    contacts.each do |contact|
      if mandate.activities.count.zero?
        contact.calculate_score
        contact.save!
      end
    end
  end

  def decrease_mandate_scores
    mandates.each do |mandate|
      if mandate.activities.count.zero?
        mandate.calculate_score
        mandate.save!
      end
    end
  end


texts: Speed up a function that checks for a sequence

texts:
I created a  function yes.seq that takes two arguments, a pattern pat and data dat, the function looks for the presence of a pattern in the data and in the same sequence.
For example:
dat <- letters[1:10]
dat
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
pat <- c('a',"c","g")

 yes.seq(pat = pat,dat = dat)
[1] TRUE

because this sequence is in the pattern and in the same order.
"a" "b" "c" "d" "e" "f" "g" "h" "i" "j"
If, for example, we reverse the pattern, then we get FALSE:
yes.seq(pat = pat,dat =  **rev(dat)**   )
[1] FALSE

Here is my function:
yes.seq <- function(pat , dat){
  lv <- rep(F,length(pat))
  k <- 1
  for(i in 1:length(dat)){
            if(dat[i] == pat[k])
              {
              lv[k] <- TRUE
              k <- k+1
              }
    if(k==length(pat)+1) break
  }
  return(  all(lv)   )
}

I am not satisfied with the speed of this function.  Can you help me with that?


texts:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
void wrapUp() {
    cout << "-------------------------------------------------" << endl;
    system("CLS");

}

int main() {
    srand(time(0));
    string name;
    int player;
    int livesTracker = 5;
    int x = 1 + (rand() % 10);

    cout << "Hello, what is your name?" << endl;
    cin >> name;
    cout << "Welcome to guess the number, " << name << "!" << endl;
    wrapUp;
    cout << '\n' << "Number of Lives: " << livesTracker << endl;

    for (int round = 1; round <= 3; round++) {

        if (livesTracker == 0) {
            system("CLS");
            cout << "Game Over! Actual Answer: " << x << endl;
            system("Color 4");
            break;
        }

        cout << "Guess the number that will come up on the screen from 1 to 10" << endl;
        cin >> player;

        if (player == x) {
            cout << "You won round " << round << "!" << endl;
            x = (rand() & 10);
        }
        else if(player > x){

            cout << "Your guess was too high, round" << round << "!" << endl;
            wrapUp;
            round--;
            livesTracker--;
            cout << '\n' << "Number of Lives: " << livesTracker << endl;
        }
        else {
            cout << "Your guess was too low, round" << round << "!" << endl;
            wrapUp;
            round--;
            livesTracker--;
            cout << '\n' << "Number of Lives: " << livesTracker << endl;
        }

        if (round == 3) {

            cout << "For the hard level, you have to guess a number from 15!" << endl;
            for (int roundh = 1; roundh <= 2; roundh++) {

                int xh = 1 + (rand() % 15);

                    cout << "Guess the number that will come up on the screen from 1 to 15" << endl;
                    cin >> player;

                if (player == xh) {

                    cout << "You won round " << roundh << "!" << endl;
                    cout << "-------------------------------------------------" << endl;
                    xh = 1 + (rand() % 15);
                }
                else if (player > xh) {

                    cout << "Your guess was too high, round " << round << "!" << endl;
                    wrapUp;
                    roundh--;
                    cout << '\n' << "Number of Lives: " << livesTracker << endl;
                }
                else {
                    cout << "Your guess was too low, round " << round << "!" << endl;
                    wrapUp;
                    roundh--;
                    cout << '\n' << "Number of Lives: " << livesTracker << endl;
                }

            }

        }
    }

    system("pause");

}

This program first creates a random number before going into the loop. A livesTracker variable is then created to control the player's lives. The first loop runs until the player finishes the first round/ level. If the player gets the randomly generated number correct, a new random number will be assigned to x for the next round to start, until the player runs out of lives or wins the game, this will happen.

Just wanted to explain the program because its probably too messy to read, appreciate any help!

EDIT: I know its not good to clear the screen using system("CLS"), but couldn't find any other options, any help on that would be helpful as well!


texts: Improve scala functional string transformation

texts:
How could this scala code be made more concise and/or idiomatic? Do I need to define each functions as a val in order to pass them as values, or is there a shorthand for this? Also looking for feedback on the disenvowel function.

// See: http://nurkiewicz.blogspot.com/2012/04/secret-powers-of-foldleft-in-scala.html
def transformString(s: String, fns: List[Function1[String,String]]) :String =
  (s /: fns) { (s: String, f: Function1[String,String]) => f apply s }

val toUpper = (s: String) => s.toUpperCase
val reverse = (s: String) => s.reverse
val disenvowel = (s: String) => s filterNot { Set('a','e','i','o','u') contains _ }

// scala> transformString("blah",List(disenvowel))
// res175: String = blh

// scala> transformString("blah",List(disenvowel, toUpper))
// res176: String = BLH

// scala> transformString("blah",List(disenvowel, toUpper, reverse))
// res177: String = HLB


texts: Python program to convert a 24 hour format to 12 hour format

texts:
Given a string in a 24 hour format the program outputs a 12 hour format. The rules are:

The output format must be 'hh:mm a.m.' if it represents before midday and 'hh:mm p.m.' after midday
When the hour is less than 10:00 you should not write a 0 before the hour, example: '9:05 a.m.'

For example:

12:30 → 12:30 p.m.
09:00 → 9:00 a.m.
23:15 → 11:15 p.m.

The code:

import datetime
def time_converter(time):
    midday_dt = datetime.datetime.strptime('12:00','%H:%M')
    time_dt = datetime.datetime.strptime(time, '%H:%M')

    if time_dt >= midday_dt:
        if time_dt >= datetime.datetime.strptime('13:00','%H:%M'):
            hours, minutes = clamp_to_twelve(time_dt, midday_dt)
            time = f'{hours}:{minutes}'
        time += ' p.m.'
    else:
        if time_dt < datetime.datetime.strptime('10:00','%H:%M'):
            time = time[1:]
        if is_midnight(time_dt):
            hours, minutes = clamp_to_twelve(time_dt, midday_dt)
            time = f'{hours}:{minutes:02d}'
        time += ' a.m.'
    return time

def clamp_to_twelve(time_dt, midday_dt):
    clamp_dt = time_dt - midday_dt
    minutes, seconds = divmod(clamp_dt.seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return [hours, minutes]

def is_midnight(time_dt):
    return (time_dt >= datetime.datetime.strptime('00:00','%H:%M') and
        time_dt <= datetime.datetime.strptime('00:59','%H:%M'))

if __name__ == '__main__':
    assert time_converter('12:30') == '12:30 p.m.'
    assert time_converter('09:00') == '9:00 a.m.'
    assert time_converter('23:15') == '11:15 p.m.'


texts:
I'm using jquery and cookie.jquery to remember the scroll position. Is there anything I can do to improve my code? Thanks!

$(document).ready(function() {

    // convert cokkie variable for easy access
    var prev_scroll_position = $.cookie('prev_scroll_position');

    // scroll to position
    $(window).scrollTop(prev_scroll_position);

    // update cookie when user scrolls
    $(window).scroll(function (event) {
        var scroll_positon = $(window).scrollTop();
        $.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
    });

});


texts: Pairwise programming challenge - Free code camp

texts:
Challenge:

Given an array arr, find element pairs whose sum equal the second argument arg and return the sum of their indices.

If multiple pairs, that have the same numeric elements but different indices are possible, return the smallest sum of indices. Once an element has been used, it cannot be reused to pair with another.

For example pairwise([7, 9, 11, 13, 15], 20) returns 6.

My code (works, passes all validations) is the below:

function pairwise(list, sum) {
  // noprotect
  var innerCounter,
      outerCounter,
      used = {},
      returnValue = 0;
  for( outerCounter = 0 ; outerCounter < list.length-1 ; outerCounter++){
    if( used[outerCounter] )
      continue;
    for( innerCounter = outerCounter+1 ; innerCounter < list.length ; innerCounter++){
      if( used[innerCounter] )
        continue;
      if( list[innerCounter] + list[outerCounter] == sum ){
        used[innerCounter] = true;
        returnValue = returnValue + innerCounter + outerCounter;
        break;
      }
    }
  }

  return returnValue;
}

I had some internal debate on sum as a parameter name, since we also return a sum. But I stuck to returnValue for the return value and sum for the parameter. Any feedback on this is welcome, from style to algorithm.


texts: C Primer Plus - Chapter 4 - Task 6 (string output)

texts:
Task

Write a Program that requests the user's first name and then the user's last name. Have it print the entered names on one line and the number of letters in each name on the following line. Align each letter count with the end of the corresponding name, as in the following:

Klaus Dieter
    5      6

My Try

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

void printWhitespace(int times) {
    for (int i = 0; i < times; i++) {
        printf(" ");
    }
}

int main(void) {
    // get names
    printf("first name: ");
    char firstName[20];
    scanf("%s", &firstName);
    printf("last name: ");
    char lastName[20];
    scanf("%s", &lastName);

    // display names
    printf("%s %s\n", firstName, lastName);

    // display number of characters under last character of names
    int numOfWhitespace = strlen(firstName) - 1;
    printWhitespace(numOfWhitespace);
    printf("%d ", strlen(firstName));

    numOfWhitespace = strlen(lastName) - 1;
    printWhitespace(numOfWhitespace);
    printf("%d\n", strlen(lastName));
}

Does the author expect that from me? Or is there a better way to write that?


texts:
I just began learning how to use signals and slots in PyQt5, and so I made a cute (pun intended) little program to display just one button. When the button is pressed a thread is spawned which will count from 0 to 99 and display the current count onto the button. However, when the button is counting, the program will not allow the user to spawn another thread.

I am about to actually use my knowledge for a much heavier task, and I wanted to know if there was an easier way to do what I did. Or, perhaps my way is not very efficient? Thanks in advance!

import threading
import sys
import time

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Application(QMainWindow):
    counter = pyqtSignal(str)
    counting = False

    def __init__(self):
        super(Application, self).__init__()

        self.button = QPushButton()
        self.button.setText('99')
        self.button.clicked.connect(self.startCounting)
        self.counter.connect(self.button.setText)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.button)
        self.frame = QFrame()
        self.frame.setLayout(self.layout)
        self.setCentralWidget(self.frame)

    def startCounting(self):
        if not self.counting:
            self.counting = True
            thread = threading.Thread(target=self.something)
            thread.start()

    def something(self):
        for x in range(100):
            self.counter.emit(str(x))
            time.sleep(.01)
        self.counting = False

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Application()
    window.show()
    sys.exit(app.exec_())


texts:
Your task is to print all unique ways to climb a staircase of length n where, from each step, you can take steps of size x where x is an integer value from an array
  For example: if you want to climb a staircase of length 3 and you can move [1, 2] steps from each stair, the output should be

 [1, 1, 1]
 [1, 2]
 [2, 1]

  Note the order is important and hence [1, 2] is different
  to [2, 1].

Is this the fastest way to solve this problem (without using built in libraries such as itertools)?

def valid_moves(position, target, legal, path, permutations):
    if position > target:
        return
    if position == target:
        permutations.append(path)
        return
    for move in legal:
        valid_moves(position + move, target, legal, path + [move], permutations)
    return permutations

start = 0
length_staircase = 3
legal_moves = [1, 2]

print(*valid_moves(start, length_staircase, legal_moves, [], []), sep="\n")


texts: A Person class containing a list of Persons

texts:
What do you guys think about this? I myself think it is pretty usefull, But how does it look from an OOP perspective?

Here's an example class

public class Person
{
    private string firstName, lastName;
    private int id;
    private static int statId;
    private static List<Person> persons = new List<Person>();
    public Person(string firstName,string lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;

        //Like this, everytime a new object of Person is created, the ID will be the id of the last created object +1
        id = statId;
        statId++;

        //Everytime you create a new instance of this class, it will be added to the list
        persons.Add(this);

    }
    public static Person GetPersonById(int id)
    {
        foreach(Person per in persons)
        {
            if (per.ID == id)
                return per;
        }
        return null;
    }
    public int ID
    {
        get { return id; }
    }

    public static List<Person> GetPersons()
    {
        return persons;
    }
    public string FirstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
    public string LastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
}

Now, aside from being able to use this class to store persons, you can also use some methods like GetPersonById and GetPersons / the PersonList property without instantiating it, and whenever you do instantiate it to make a new person, it automatically adds it to the list


texts: Solving the 'Vietnamese school maths problem'

texts:
Having read Can you do the maths puzzle for Vietnamese eight-year-olds that has stumped parents and teachers?, which presented the problem of filling in numbers 1 to 9 to satisfy

$$ a + 13 \frac{b}{c} + d + 12 e - f - 11 + \frac{g \cdot h}{i} - 10 = 66 $$

… I thought I'd try a Common Lisp implementation as a learning exercise.

(defun solve-puzzle (permutation)
  (destructuring-bind (a b c d e f g h i) permutation
    (let ((result (infpre:!! a + 13 * b / c + d + 12 * e - f - 11 + g * h / i - 10)))
      (when (= result 66) (print permutation)))))

(alexandria:map-permutations #'solve-puzzle '(1 2 3 4 5 6 7 8 9) :length 9)

This works; when executed, it produces a list of 136 valid combinations in around 300ms on my laptop.  I have a couple of questions regarding the code though:

How's my idiom?  My background is C, C#, Ruby so I'm probably carrying over habits from those languages.
Are there any obvious performance gotchas in the code - obvious to experienced Lispers, that is?


texts: Checking if a set of checkboxes have a certain number of options checked

texts:
I'm coding a jQuery plugin that basically checks if a set of checkboxes groups have at least x options checked. A checkbox group is named as name=group[]. You'd call the plugin like:

$(':checkbox').checkpass({min: 1}) // Make sure at least one checkbox per group is checked

I've been working on this piece of code for a couple days trying to make it as short and fast as possible because I'm going to implement this on a very large form.  Is it possible to make it shorter/faster, or have I reached the limit?

You can check a live example here.

(function($) {
    $.fn.checkpass = function(options) {

        var opt = $.extend({
            min: function() {
                return (min === 'undefined') ? 1 : min;
            },
            errorContainer: '
',
            errorWrap: '
'
        }, options);

        var $ckboxes = this,
            names = [],
            num = 0,
            $errors = $(opt.errorContainer);

        $ckboxes.each(function() {
            var name = this.name;
            if (!~$.inArray(name, names)) {
                names.push(name);
            }
        });

        for (var i = 0, l = names.length; i < l; i++) {
            $checked = $ckboxes.filter('[name="' + names[i] + '"]:checked');
            if ($checked[opt.min - 1]) {
                num++;
            } else {
                if (opt.min > 0) {
                    var $err = $(opt.errorWrap),
                        _remaining = opt.min - $checked.length,
                        _name = names[i].match(/\w+/).toString()
                                .replace(/^\w/, function($0) {
                                    return $0.toUpperCase();
                                });
                    $err.html('' + _name +
                              ': Check ' +
                              _remaining + ' more.').appendTo($errors);
                }
            }
        }

        return {
            isValid: !! (num === names.length),
            errors: $errors
        };
    };
})(jQuery);


texts: metafunction to determinate the biggest of all supplied types

texts:
Can the metafunction below be implemented more elegantly, with less code? What I have now is not very elegant or smartly written.

#include <type_traits>

namespace detail
{

template <typename T, typename A, typename ...B>
struct max_type
{
  typedef typename max_type<
    typename std::conditional<(sizeof(A) > sizeof(T)), A, T>::type,
    B...
  >::type type;
};

template <typename T, typename A>
struct max_type<T, A>
{
  typedef typename std::conditional<(sizeof(A) > sizeof(T)), A, T>::type type;
};

}

template <typename A, typename... B>
struct max_type
{
  typedef typename detail::max_type<A, A, B...>::type type;
};


texts: Method to find posts in children categories

texts:
I use the gem act_as_votable to allow users to select categories they like. To get the categories a user likes:

 current_user.get_voted(Category)

These categories have children categories, and I need to find the posts in those children categories.

I use this line to do it:

@categories_posts = current_user.get_voted(Category).flat_map { |category| category.children.flat_map(&:posts)}.delete_if{ |post| post.status == "draft"}

But I noticed in my logs that this was doing way too much computation for this task.

Is there a way to make it lighter ?


texts:
This is a Python script I made to download a URL from the clipboard.

When a new URL is copied to a clipboard it adds the URL to a download queue, then on a separate thread it downloads the URL to a file.

I am new to multithreading.  Is my script properly using multithreading? It needs to download the data while still listening for changes in the content of the clipboard.

import time
import os
import urllib
import subprocess
import threading

download_number = 0
count=0
save_file = "links_list.txt"
old_url = ""
download_queue = []
download_delay = 5

data_file = open(save_file, "r")
past_links = data_file.read()
data_file.close()

def get_image():
    print download_queue
    url = download_queue.pop(0)

    data = urllib.urlopen(url).read()
    name = url.split("/")[-1:][0]
    extension = name.split(".")[-1:][0]
    basename = name.split(".")[:-1][0]

    # make a new file name
    if os.path.exists(name):
        new_name = basename+"-0."+extension
        try_count = 0
        while os.path.exists(new_name):
            try_count += 1
            new_name = basename+"-"+str(try_count)+"."+extension
        name = new_name

    data_file = open(name, "w")
    data_file.write(data)
    data_file.close()

    # goto the next link
    if len(download_queue) != 0:
        time.sleep(download_delay)
        get_image()

while(1):
    time.sleep(0.25)
    clipboard = subprocess.check_output('pbpaste', shell=True)
    # check if the clipbard contains a new url
    if clipboard[:4] == "http" and clipboard != old_url and clipboard not in past_links:
        past_links += clipboard
        old_url = clipboard

        # add url to queue
        download_queue.append(clipboard)
        print download_number,

        # start the download fuction
        t = threading.Thread(target=get_image)
        t.start()

        # links that have been downloaded
        data_file = open(save_file, "a")
        data_file.write(clipboard+"\n")
        data_file.close()

        download_number += 1


texts:
To support a demonstration I'm going to be doing, I need a short C# program that can be unit tested. I decided to make a FizzBuzz split into a few methods:

using System;
namespace FizzBuzz
{
    class FizzBuzzer
    {
        public static void Main()
        {
            FizzBuzzer fizzBuzzer = new FizzBuzzer();
            int n = Convert.ToInt32(Console.ReadLine());
            fizzBuzzer.StartLoop(n);
        }

        public int StartLoop(int n)
        {
            int fizzBuzzes = 0;
            for(int i = 0; i < n; i++)
            {
                string output = getOutputForI(i);
                if(output == "FizzBuzz") {
                    fizzBuzzes++;
                }
                Console.WriteLine(output);
            }
            return fizzBuzzes;
        }

        public string getOutputForI(int i)
        {
            string s = "";
            if(i % 3 == 0)
            {
                s += "Fizz";
            }
            if(i % 5 == 0)
            {
                s += "Buzz";
            }
            if(s.Length == 0)
            {
                s = "" + i;
            }
            return s;
        }
    }
}

I want people to focus on the point of my demonstration, and not on potential mistakes in my code. As someone new to C#, I can't evaluate my code very well. Are there any beginner mistakes that would distract pedantic C# experts?

I am of course open to any type feedback, I mainly just want people to not laugh at or get annoyed by my code.

Edit:

here are example unit tests

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace FizzBuzz.Tests
{
    [TestClass()]
    public class FizzBuzzerTests
    {
        [TestMethod()]
        public void StartLoopTest()
        {
            Assert.AreEqual(6, FizzBuzzer.StartLoop(100));
        }

        [TestMethod()]
        public void GetOutputFor0()
        {
            Assert.AreEqual("FizzBuzz", FizzBuzzer.getOutputForI(0));
        }

        [TestMethod()]
        public void GetOutputFor4()
        {
            Assert.AreEqual("4", FizzBuzzer.getOutputForI(4));
        }
    }
}

and for context, here is the updated code (based on Ron Beyer's answer) that those tests are run against:

using System;
namespace FizzBuzz
{
    public static class FizzBuzzer
    {
        public static void Main() { }

        public static int CountFizzBuzzes(int max)
        {
            int fizzBuzzes = 0;
            for (int i = 1; i <= max; i++)
            {
                string result = FizzBuzz(i);
                if (result == "FizzBuzz")
                {
                    fizzBuzzes++;
                }

                Console.WriteLine(result);
            }
            return fizzBuzzes;
        }

        public static string FizzBuzz(int input)
        {
            string s = "";
            if (input % 3 == 0)
            {
                s += "Fizz";
            }
            if (input % 5 == 0)
            {
                s += "Buzz";
            }
            if (s.Length == 0)
            {
                s = "" + input;
            }
            return s;
        }
    }
}


texts: Why is my Bubblesort implementation faster than my Quicksort code?

texts:
Here is my Bubblesort code:

public static List<int> BubbleSort(List<int> _digitList)
      {
          List<int> digitList = _digitList;
          bool didSwap = true;

          while (didSwap)
          {
                didSwap = false;
                for (int i = 0; i < digitList.Count - 1; i++)
                {
                    if (digitList[i] > digitList[i + 1])
                    {
                        int temp = digitList[i];
                        digitList[i] = digitList[i + 1];
                        digitList[i + 1] = temp;

                        didSwap = true;
                    }
                }
          }
          return digitList;
      }

And here is my Quicksort Method, which is actually an implementation of the pseudocode on Wikipedia:

public static List<int> Quicksort(List<int> array)
        {
            if (array.Count <= 1)
            {
                return array; //An array of Zero ot one elements is already sorted
            }

            int pivot = 0;
            List<int> less = new List<int>();
            List<int> greater = new List<int>();

            for (int i = 1; i < array.Count;i++ )
            {
                if (array[i] <= array[pivot])
                {
                    less.Add(array[i]);
                }
                else
                {
                    greater.Add(array[i]);
                }
            }

            List<int> combined = Quicksort(less);
            combined.Add(array[pivot]);
            combined.AddRange(Quicksort(greater));

            return combined;

        }

So for the List = {211, 16, 42, 166, 192, 2, 13, 81, 6, 1, 5, 115, 17, 67}; I get following Stopwatch values.

Bubblesort:

  00:00:00.0002873

Quicksort:

  00:00:00.0003831

Does this mean my Quicksort code is poor or did I misunderstand the Stopwatch concept?


texts: Run a command for all files in a directory

texts:
I have a program that needs to run an command on all the files in a folder:

import glob
import os

dirName = "../pack"

if not os.path.exists(dirName):
    os.mkdir(dirName)

os.chdir("xml/")

files = []
for file in glob.glob("*.xml"):
    files.append(file)

os.chdir("..")

filearchiver_cmdline = "archiver.exe"

for myFile in files:
    filearchiver_cmdline += " xml\\" + myFile

os.system( filearchiver_cmdline )

The command should look like this:

Arhiver.exe file1.xml

What should I change / optimize for this code? Would a class be needed? Should there be logical def-s? Are the variables name good?


texts:
Just started learning/relearning data structures for the semester exams. Most of the examples found online are too cluttered or bloated.

For myself, I implemented it from theory I learned.

It works.

I want to know if there are any mistake that I have done, anything that can be improved .. .

Thanks for your time :)

#include "iostream"
using namespace std;

struct Node{

    struct Node* prev;
    int data;
    struct Node* next;

};

Node* top = NULL;

bool isempty(){
    return  top->prev == NULL;
}

void push(int data){

    struct Node* newnode;
    newnode = new Node();

    if(!newnode){
        cout << "Heap Overflow" << endl;
    }

    newnode->prev = top;
    newnode->data = data;
    newnode->next = NULL;

    top = newnode;
}

void pop(){

    if(isempty()){
        cout << "Stack Underflow";
        exit(1);
    }

    struct Node* tmp;
    tmp = new Node();

    tmp->next = NULL;
    tmp->data = top->prev->data;
    tmp->prev = top->prev->prev;

    free(top);
    top = tmp;

}

void display(){

    struct Node* itr;
    itr = top;

    cout << itr->data << " ";
    while(itr->prev != NULL){
        cout << itr->prev->data << " ";
        itr = itr->prev;
    }
    cout << endl;
}

int main(){

    push(10);
    push(20);
    push(30);
    push(40);
    push(50);

    pop();
    display();
    pop();
    display();
    pop();
    display();
    pop();
    display();
    pop();

    return 0;
}


texts:
EDIT: The full source code in question can be found here.

Is this code reasonably safe against dead/livelocks, and if not, how can I fix it?

I know processes are usually recommended over threads for operations like this, but processing's version of queue doesn't do what I need.
The choose function will be called on 100 objects, but in sequence. I think each one should be finished before the next, but I'm not certain.
The appraise function that choose calls only gets values from dicts, and does math on them.

---thread_queue.py---

class ThreadsnQueues(threading.Thread):
    def __init__(self, queue, out_queue=None, func=None, args=None, semaphore=None):
        super(ThreadsnQueues, self).__init__()
        self.queue = queue
        self.out_queue = out_queue
        self.semaphore = semaphore
        if func is None:
            try:
                func = self.queue.get(block=False)
            except Empty:
                self.func = None
                return
        if func is not None:
            if type(func) is list:
                self.func = func[0]
                self.args = func[1:]
            else:
                self.func = func
        if args != [] and args != None: self.args = args

class ThreadScore(ThreadsnQueues):
    def __init__(self, queue, out_queue, func, semaphore):
        super(ThreadScore, self).__init__(queue, out_queue, func, None, semaphore)
    def run(self):
        try:
            s = self.queue.get() #should be a stock object
        except Empty:
            print "Empty queue?!"
            return
        except:
            return
        while True:
            try:
                self.semaphore.acquire()
                ret = self.func(s) #should return a score (int)
                self.out_queue.put((s, ret)) #tuple with Stock, int
                self.queue.task_done()
                self.semaphore.release()
                return
            except KeyboardInterrupt:
                raise
            except ArithmeticError:
                a, b, c = exc_info()
                print a, b
                pdb.post_mortem(c)
            except StandardError:
                pass

---genome.py---

def choose(self, stocks):
    """
    Scores the whole list of stocks, and puts the top twelve on a list to be
    purchased.
    """
    tmp = {}
    queue = Queue.Queue()
    out_queue = Queue.Queue()
    procs = []
    thread_limit = 10
    self.prog = ProgressBar(widgets=[Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA()],
        maxval=len(stocks)).start()
    sym = threading.BoundedSemaphore(thread_limit)
    for stock in stocks:
        queue.put(stock)
    while queue.empty() != True:
        try:
            for j in range(thread_limit):
                t = ThreadScore(queue=queue, out_queue=out_queue, func=self.appraise, semaphore=sym)
                t.daemon = True
                t.start()
                procs.append(t)
        except ArithmeticError:
            raise
        except threrror:
            print "Encounted a thread error, blocking until threads complete..."
            [ p.join(5.0) for p in procs ]
            procs = []
        except KeyboardInterrupt:
            raise
        except StandardError as e:
            print e
            [ p.join(5.0) for p in procs ]
            procs = []
    [ p.join(timeout=5.0) for p in procs ]
    print "Finished scoring stocks, sorting..."
    self.prog.finish()
    while out_queue.qsize() > 0:
        l, r = out_queue.get() #unpack tuples of Stock, int
        tmp[l] = r #tmp[<Stock>] = score
    pmt = sorted(tmp, key=lambda x: tmp.get(x), reverse=True)
    self.prefers = { key: value for (key, value) in zip(pmt, sorted(tmp.values(), reverse=True))}
    self.scores = self.prefers.copy()
    return self.prefers


texts:
Good day, it's my first time doing something like this so I wanted to solve some of the challenges on project Euler, however I reached a block on my code, even before I submitted I was aware that I would be unable to compile within time limits for numbers well beyond the million or close to a million, still went along with it and of course, the test cases on the million(s)? [because they are hidden and I dont exactly know the numbers] expired due to time limits constraints.

I was wondering if I could receive some feedback on how to improve my code, given that at the minimum the value received would be a million of course.

class Solution {

    private static void mathSolver(long _number){
        long _sum = 0;

        for(long x = 0; x<_number; x++){
            if((x % 3 == 0) || (x % 5 == 0)){
                _sum += x;
            }
        }
        Console.WriteLine(_sum);
    }

    static void Main(String[] args) {
        int t = Convert.ToInt32(Console.ReadLine());
        for(int a0 = 0; a0 < t; a0++){
            int n = Convert.ToInt32(Console.ReadLine());
            mathSolver(n);
        }
    }
}

I already tried of tinkering with it with some math sequences, trying to figure out a pattern that would allow me to jump between numbers, so that instead of iterating through every number on a million, I would, lets say, jump between 3's or 5s directly, however no operation that I could think of would give me the result I wanted as it was very prone to mistakes along the way.

A slight background of me if anyone is interested while reviewing, I'm not exactly new to C#, been doing it for slightly under 2 years however my first employer procured tons of bad practices and code disasters, this is why I want to expose myself to these kind of things, to improve efficiency while coding, to get better code readibility and presentation as well as trying to find solutions that aren't as forceful.

Thank you for your answers and may you have a nice day!


texts:
I am trying to experiment with golang.

This code spins off two Go routines: one to download data and another to read from the body. Both go threads are synced by the data channel.

I have two questions:

Should I have to dispose the body inside downloadData method?
Is this type of coding acceptable in Go?

package main

import (
    "fmt"
    "net/http"
    "time"
)

func main() {
    data := make(chan *http.Response)
    go downloadData(data)
    go readData(data)
    var input string
    fmt.Scanln(&input)
}

func downloadData(data chan *http.Response) {
    resp, _ := http.Get("http://www.google.com")
    defer resp.Body.Close()
    time.Sleep(time.Second * 1)
    data <- resp
}

func readData(data chan *http.Response) {
    response := <-data
    fmt.Println(response)
}