texts: WPF: An implementation of INotifyDataErrorInfo

texts:
An abstract base class which derives from the ObservableObject (MvvmLight), implementing the INotifyDataErrorInfo interface.

The model (exposed via the ViewModel) binds directly to the view, to avoid duplication of properties.

A couple of notes:

a) I chose the HashSet<string>> to avoid duplicate errors, e.g. "The number of allowed characters has been exceeded." on every keystroke when UpdateSourceTrigger=PropertyChanged.

b) The RaisePropertyChanged of the MvvmLight's ObservableObject has been overridden to validate individual properties.

c) The method IsValidated() validates the object and provides visual feedback to the user when e.g. the "Save" button has been pressed.

using GalaSoft.MvvmLight;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace WPF.MVVM.UI.Data.Model.Base
{
    public abstract class ValidatedObservableObject : ObservableObject, INotifyDataErrorInfo
    {
        private readonly IDictionary<string, HashSet<string>> _errors = new Dictionary<string, HashSet<string>>();

        public bool HasErrors
        {
            get => _errors.Count > 0;
        }

        public IEnumerable GetErrors(string propertyName)
        {
            if (string.IsNullOrEmpty(propertyName) || !_errors.ContainsKey(propertyName))
                return null;

            return _errors[propertyName];
        }

        public bool IsValidated()
        {
            var results = new List<ValidationResult>();
            var valid = Validator.TryValidateObject(this, new ValidationContext(this), results, true);

            if (valid)
                return true;

            AppendOrUpdateErrors(results);

            return false;
        }

        public override void RaisePropertyChanged(string propertyName = null)
        {
            base.RaisePropertyChanged(propertyName);

            if (!string.IsNullOrEmpty(propertyName))
            {
                ValidateProperty(propertyName);
            }
        }

        private void ValidateProperty(string propertyName)
        {
            var results = new List<ValidationResult>();
            var valid = Validator.TryValidateProperty(GetType().GetProperty(propertyName)?.GetValue(this), new ValidationContext(this) { MemberName = propertyName }, results);

            if (valid)
            {
                RemoveFromErrors(propertyName);
            }
            else
            {
                AppendOrUpdateErrors(results);
            }
        }

        private void RemoveFromErrors(string propertyName)
        {
            if (string.IsNullOrEmpty(propertyName) || !_errors.ContainsKey(propertyName))
                return;

            _errors.Remove(propertyName);

            RaiseErrorsChanged(propertyName);
        }

        private void AppendOrUpdateErrors(IReadOnlyCollection<ValidationResult> results)
        {
            if (results == null)
                return;

            foreach (var memberName in results.SelectMany(r => r.MemberNames).Distinct())
            {
                var memberErrors = new HashSet<string>(results.Where(r => r.MemberNames.Contains(memberName)).Select(r => r.ErrorMessage));

                if (_errors.ContainsKey(memberName))
                {
                    _errors[memberName] = memberErrors;
                }
                else
                {
                    _errors.Add(memberName, memberErrors);
                }

                RaiseErrorsChanged(memberName);
            }
        }

        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

        private void RaiseErrorsChanged(string propertyName)
        {
            ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName));
        }
    }
}


texts:
I have a class that takes a string or an integer, which stand for username or user id in the database.  I am not comfortable with my constructor taking "a string or an integer" and want to modify it to be more type-specific.  But how do I do so?

class User
{

    /**
     *
     * @var string|int
     */
    private $id;

    /**
     *
     * @var array
     */
    private $udata;

    /**
     *
     * @param string|int $var
     */
    function __construct($var)
    {
        $this->id = 0;
        $this->lookup($var);
    }

    /**
     *
     * @param string|int $var
     */
    function lookup($var)
    {
        $sql = "SELECT * FROM user WHERE "
            . (is_numeric($var) ? 'id' : 'username') . " = " . db_input($var);
        $row = query($sql);
        $this->udata = $row;
        $this->id = $row['id'];
        return $this->id;
    }
}

/**
 * Uses
 */
$user = new User(51);
$user = new User("JohnDoe");


texts: Optimizing rendering with a lot of transformations and save/restore

texts:
I have implemented a renderer for shapes described with a L-System grammar. Implementation of that is not important. Basically you feed it an angle and some rules, and it spits out a string of characters that represents instructions. For example, "+" means turn right n radians and vice versa. The instructions will only be computed once.
The job of the method .draw is to read the instructions and draw it on a canvas continuously. The angle is always changing (however the instructions stay the same) and therefore this method will be called repeatedly:
LSystem.prototype.draw = function(ctx, x, y) {
    var self = this;
    var path = this.path;
    var table = {
        "F": function(ctx) {
            // draw forward
            ctx.moveTo(0, 0);
            ctx.lineTo(0, -5);
            ctx.translate(0, -5);
        },
        "+": function(ctx) {
            // turn right
            ctx.rotate(self.angle);
        },
        "-": function(ctx) {
            // turn left
            ctx.rotate(-self.angle);
        },
        "[": function(ctx) {
            // save location and rotation
            ctx.save();
        },
        "]": function(ctx) {
            // restore location and rotation
            ctx.restore();
        }
    };
    ctx.save();
    ctx.beginPath();
    ctx.moveTo(x + 0.5, y + 0.5);
    ctx.translate(x + 0.5, y + 0.5);
    for (var i = 0; i < path.length; i++) {
        // take a character from the path
        // and call the corresponding function (if exists)
        var char = path[i];
        var cmd = table[char];
        cmd && cmd(ctx);
    }
    ctx.stroke();
    ctx.restore();
};

A path (in my case) consists of over 6000 characters. It has no problem in drawing at 60FPS. However the main problem is that it uses a lot of CPU and I can hear the fans in my laptop starts spinning. This is not optimal and I'm looking for a way to solve this.
By looking at the profiling tool in Chrome, we can see that it doesn't like .rotate and .restore being called repeatedly. On a 16ms budget it already takes up half of it:

What is a good way of optimizing the rendering and minimize CPU usage? Would calculating the coordinates for the entire path first then pass it to .lineTo be a better choice? Keep in mind that the angle is different every time .draw is called, so the coordinates cannot be cached and reused.
A demo can be viewed here.


texts: Get object in a Set that is an instance of a generically specified type

texts:
Are there ways to simplify the getLoadComponent(Class<T> type) method? The call LoadComponentFX lcfx = l.getLoadComponent(LoadComponentFX.class); seams a bit clumsy to me.

Here is my code:

public abstract class LoadComponent {}

public class LoadComponentFX extends LoadComponent {}

public class Load {
    Set<LoadComponent> lc;

    public <T extends LoadComponent> T getLoadComponent(Class<T> type) {
        for (final LoadComponent l : lc) {
            if (type.isInstance(l)) {
                return (T) l;
            }
        }
        return null;
    }
}

Test code:

public class LoadTest {
    public static void main(final String[] args) {
        Load l = new PointLoad();

        LoadComponentFX lcfx = l.getLoadComponent(LoadComponentFX.class);
    }
}


texts: Wrapper for Google_Service_Calendar as a Symfony service

texts:
My app interacts with Google Calendar. This Service wraps Google_Service_Calendar:

<?php
declare(strict_types=1);

namespace App\Service;

use Symfony\Component\HttpFoundation\Session\SessionInterface;

class GoogleCalendarService extends \Google_Service_Calendar
{
    public const CALENDAR_ID = '123example@group.calendar.google.com';

    public function __construct(SessionInterface $session) {
        $client = new \Google_Client();
        $client->setAccessToken($session->get('google_access_token'));
        parent::__construct($client);
    }
}

I have the feeling that having the session as a dependency is not good practice. For a user of that service, it is absolutely not clear that the access token needs to be set in the session.

I could probably add some Exceptions for the case that it is not set, but I wonder whether there is a better way?


texts:
I saw this problem on a mock interview I spectated online, and decided to take a stab at it. The problem as stated originally asked to find if a given player had won a standard game of tic-tac-toe. However, the code below goes for a more general case where: the matrix size is variable, and the number of markers in a row to win is also variable.

If \$n\$ = height of the board, the solution below is \$O(k * N^2)\$, where \$k\$ is the number of markers needed in a row to win. The gist of the approach is to loop through every position and check downward or forward if it is the starting point of a solution.

One clear issue here is that the information gained from a failed traversal isn't stored. For example, if on the first row we have xxo, breaking the traversal on the 'o' doesn't prevent us from calling "test_forward" even though it will clearly fail on the next index.

What are potential improvements that could be implemented made here?

tests = {'a': [['x','x','o'],
               ['-','o','x'],
               ['-','-','x']]}

def test_forward(board, i, j, player, num_needed):
    # Check for 3 in a row horizontally (forward)
    for k in range(1, num_needed):
        if board[i][j+k] != player:
            return False

    return True

def test_down(board, i, j, player, num_needed):
    # Check for 3 in a row vertically (downward)
    for k in range(1, num_needed):
        if board[i+k][j] != player:
            return False

    return True

def test_diag_forward(board, i, j, player, num_needed):
    # Check for 3 in a row diagonally down and right
    for k in range(1, num_needed):
        if board[i+k][j+k] != player:
            return False

    return True

def test_diag_backward(board, i, j, player, num_needed):
    # Check for 3 in a row diagonally down and left
    for k in range(1, num_needed):
        if board[i+k][j-k] != player:
            return False

    return True

def check_neighbors(board, dimension, i, j, player, num_needed):
    if board[i][j] != player:
        return False

    # Avoid array out of bounds
    searchable_space = dimension - num_needed

    if j <= searchable_space:
        won_forward = test_forward(board, i, j, player, num_needed)
        if won_forward:
            return True

    if i <= searchable_space:
        won_down = test_down(board, i, j, player, num_needed)
        if won_down:
            return True

    if j <= searchable_space and i <= searchable_space:
        won_diag_forward = test_diag_forward(board, i, j, player, num_needed)
        if won_diag_forward:
            return True

    if j >= num_needed - 1 and i <= searchable_space:
        won_diag_backward = test_diag_backward(board, i, j, player, num_needed)
        if won_diag_backward:
            return True

    return False

# Loop through every square and check if it is the starting point of a solution
def has_winner(board, player, num_needed):
    dimension = len(board[0])
    for i in range(dimension):
        for j in range(dimension):

            result = check_neighbors(board, dimension, i, j, player, num_needed)

            if result == True:
                return result
            else:
                continue

    return result

print has_winner(tests['a'], 'x', 3)


texts:
I wrote a function that finds the difference between two strings. This only works given that the difference is continuous.

Beyond doubt this already exists, I am recreating this for educational purposes. I would like feedback about my performance and efficiency.

Examples of this method:

String difference = Difference("Hello", "Hello world!");
//difference would be " world!"

String difference = Difference("Removing text", "Removi");
//difference would be "ng text"

String difference = Difference("same size", "SAME size");
//difference would be "SAME"

public static String Difference(String string1, String string2)
{
    int size = string2.length() - string1.length();
    if(size < 0)
    {
        size *= -1;
        String swap = string1;
        string1 = string2;
        string2 = swap;
    }
    String difference = "";
    int start = DifferenceStartIndex(string1, string2);
    if(size > 0)
        for(int i = start; i < start + size; i++)
            difference += string2.charAt(i);
    else
    {
        if(start != -1)
        {
            int end = DifferenceEndIndex(string1, string2, start);
            for(int i = start; i < end; i++)
                difference += string2.charAt(i);
        }
        else
            return "";
    }
    return difference;
}

public static int DifferenceStartIndex(String string1, String string2)
{
    int maxSize = (string1.length() > string2.length()) ? string1.length() : string2.length();
    for(int i = 0; i < maxSize; i++)
        if(((i < string1.length()) ? string1.charAt(i) : '\0') != ((i < string2.length()) ? string2.charAt(i) : '\0'))
            return i;
    return -1;
}

public static int DifferenceEndIndex(String string1, String string2, int start)
{
    int maxSize = (string1.length() > string2.length()) ? string1.length() : string2.length();
    int end = maxSize;
    for(int i = start; i < maxSize; ++i)
        if(string1.charAt(i) != string2.charAt(i))
            end = i + 1;
    return end;
}


texts: Airline/Hotel reservation system in Python

texts:
I am trying to teach myself OOP in Python. I am picking up some projects from GitHub and trying it out on my own. I wrote a Airline/Hotel Reservation System, where I want to maintain the customer name, ID and maintain a record for Airline or Hotel or Both. I am not sure if my design is correct. I want some input on how to improve the design for my code.

class Reservation:
   def __init__(self,passenger_id,passenger_fname,passenger_lname):
      self.passenger_id = passenger_id
      self.passenger_fname = passenger_fname
      self.passenger_lname = passenger_lname
      self.cost = 0
      self.reservation_id = []
      self.passenger_record = {'p_name'  : self.passenger_fname + self.passenger_lname,
                             'p_id'    : self.passenger_id,
                             'p_wallet': self.cost,
                             'p_reservation_id': self.reservation_id,
                            }
      self.airline_seats = { 'Business Class' : 50,
                           'First Class'    : 50,
                           'Premium Economy': 100,
                           'Regular Economy': 150 }
      self.airline_price = { 'Business Class' : 2500,
                           'First Class'    : 2000,
                           'Premium Economy': 1800,
                           'Regular Economy': 1500 }
      self.hotel_room = {'Penthouse'             : 10,
                       'King Deluxe Bedroom'    : 20,
                       'Queen Deluxe Bedroom'   : 20,
                       'Kind Standard Bedroom' : 30,
                       'Queen Standard Bedroom': 50 }
      self.hotel_price = {'Penthouse'            : 1000,
                        'King Deluxe Bedroom'    : 700,
                        'Queen Deluxe Bedroom'   : 600,
                        'Kind Standard Bedroom' : 450,
                        'Queen Standard Bedroom': 350 }
   def currentStatus(self,option):
       if option == "Airline":
           for key, value in self.airline_seats.items():
              print key, value
       elif option == "Hotel":
           for key,value in self.hotel_room.items():
              print key, value

   def Total(self):
       print self.passenger_record['p_wallet']

class Airline(Reservation):
   def __init__(self,passenger_id,passenger_fname,passenger_lname,airline_seat_section,
         airline_departure_date):
       Reservation.__init__(self,passenger_id,passenger_fname,passenger_lname)
       self.airline_seat_section = airline_seat_section
       self.airline_departure_date = airline_departure_date

   def CheckAvailability(self):
       if  (self.airline_seats.get(self.airline_seat_section) != 0):
            self.airline_seats[self.airline_seat_section] -= 1
            self.passenger_record['p_wallet'] +=        self.airline_price[self.airline_seat_section]
            print "\n\nReserved Airline Ticket\n\n"

class Hotel(Reservation):
    def __init__(self,passenger_id,passenger_fname,passenger_lname,hotel_room_selection,
             hotel_check_in_date,hotel_check_out_date):
        Reservation.__init__(self,passenger_id,passenger_fname,passenger_lname)
        self.hotel_room_selection = hotel_room_selection
        self.hotel_check_in_date = hotel_check_in_date
        self.hotel_check_out_date = hotel_check_out_date

    def CheckAvailability(self):
        if (self.hotel_room.get(self.hotel_room_selection) != 0):
            self.hotel_room[self.hotel_room_selection] -= 1
            self.passenger_record['p_wallet'] += self.hotel_price[self.hotel_room_selection]
            print "\n\nReserved Hotel Room\n\n"

A1 = Airline("1","Arun","Raman","Business Class","07-07-2014")
A1.CheckAvailability()
A1.currentStatus("Airline")
H1 = Hotel("1","Arun","Raman","Penthouse","07-07-2014","07-10-2014")
H1.CheckAvailability()
H1.currentStatus("Hotel")


texts: Family and vehicles example using the strategy pattern

texts:
I have studied the strategy pattern and understood it w.r.t the example given in the PDF that I referred. I wanted to make sure that my understanding is correct, so I have written a simple program in C++ and designed the strategy pattern using the family and vehicles as the subject. Please provide corrections/suggestions for the program.

#include <iostream>

class Vehicle
{
public:
    virtual void useVehicle() = 0;
};

class FordFigo : public Vehicle
{
public:
    void useVehicle()
    {
        std::cout << "Driving FordFigo" << std::endl;
    }
};

class TataNano : public Vehicle
{
public:
    void useVehicle()
    {
        std::cout << "Driving TataNano" << std::endl;
    }
};

class BlackPulsar : public Vehicle
{
public:
    void useVehicle()
    {
        std::cout << "Riding BlackPulsar" << std::endl;
    }
};

class HondaActiva : public Vehicle
{
public:
    void useVehicle()
    {
        std::cout << "Riding HondaActiva" << std::endl;
    }
};

class Family
{
public:
    Vehicle *myVehicle;
    virtual void display() = 0;
    void setVehicle(Vehicle *v)
    {
        myVehicle = v;
    }
    void driveVehicle()
    {
        myVehicle->useVehicle();
    }
};

class Father : public Family
{
public:
    virtual void display()
    {
        std::cout << "I am Father" << std::endl;
    }
};

class Mother : public Family
{
public:
    virtual void display()
    {
        std::cout << "I am Mother" << std::endl;
    }
};

class Son : public Family
{
public:
    virtual void display()
    {
        std::cout << "I am Son" << std::endl;
    }
};

class Daughter : public Family
{
public:
    virtual void display()
    {
        std::cout << "I am Daughter" << std::endl;
    }
};

int main()
{
    Family *fam = new Father();
    fam->display();
    fam->setVehicle(new FordFigo());
    fam->driveVehicle();

    fam = new Daughter();
    fam->display();
    fam->setVehicle(new HondaActiva());
    fam->driveVehicle();
    return 0;
}


texts:
I'm not sure about this code but it feels ugly to me. It is a solution to this.

package main

import ("golang.org/x/tour/tree"; "fmt"; "reflect"; "sort")

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
    if t != nil {
        ch <- t.Value
        Walk(t.Left, ch)
        Walk(t.Right, ch)
    }
}

func WalkTest(t *tree.Tree, ch chan int) []int {
    go Walk(t, ch)
    var testSlice []int
    for i := 0; i <10; i++ {
        testSlice = append(testSlice, <- ch)
    }
    return testSlice
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
    var t1Slice []int
    var t2Slice []int
    ch1 := make(chan int, 10)
    ch2 := make(chan int, 10)
    go Walk(t1, ch1)
    go Walk(t2, ch2)
    for i := 0; i < 10; i++ {
        t1Slice = append(t1Slice, <- ch1)
        t2Slice = append(t2Slice, <- ch2)
    }
    sort.Ints(t1Slice); sort.Ints(t2Slice)
    return reflect.DeepEqual(t1Slice, t2Slice)
}

func main() {
    // Test the walk function
    walkTestTree := tree.New(1)
    walkTestCh := make(chan int, 10)
    walkTest := WalkTest(walkTestTree, walkTestCh)
    if len(walkTest) != 10 {
        panic("Walk test failed")
    }
    fmt.Println("Walk test ok!")

    // test the Same function
    testTree1 := tree.New(1)
    testTree2 := tree.New(1)
    sameTest := Same(testTree1, testTree2)
    if !sameTest {
        panic("same test failed")
    }
    fmt.Println("Same test passed")

    aTree := tree.New(1)
    bTree := tree.New(1)
    fmt.Println(Same(aTree, bTree))
}


texts:
I'm updating an old ECS I wrote a couple years back, and I've written the following piece of code in order to generate a GUID:

const auto& es::EntityStore::RequestEntity()
{
    if(m_freeEntities.size() != 0)
    {
        return ec::ENTITY_ID_INVALID;
    }
    //Get the lastmost EntityID
    auto eid = m_freeEntities.back(); //an std::vector<uint64_t>
    m_freeEntities.pop_back();
    //Get the index value of the EntityID
    uint32_t idx = 0;
    idx = eid & 0XFFFFFFFF;
    //Get the version value of the EntityID
    uint32_t version = 0;
    version = ((eid >> 32) & 0xFFFFFFFF) + 1;

    //Update the metadata at idx
    m_entityMetadata.at(idx).version = version;

    //Create & return the new EntityID
    eid = version;
    eid = eid << 32 | idx;
    //an unordered_set<uint64_t>
    return *m_livingEntities.insert(eid).first;
}

However, I believe it can be written out nicer, and perhaps with less machine code generated.

HOW THE GUID WORKS

I am using a uint64_t to represent my GUID. Reading left-to-right, the first 32 bits will represent the version of the GUID, while the last 32 bits represent the index of the GUID.

The index will be used to lookup items in other arrays and vectors, so it never changes.

The version, however, is used to differentiate between an object who might have the same index as another.

When a GUID is invalidated, it is stuck onto the end of a vector.
When it is reused, it's version goes up by a counter of 1.

So, if there are any game objects out there referencing ID 0 or belonging to ID 0, even though it occupies the same spot in the array because of it's index, it's GUID will be different because it's version is 1 higher than whatever GUID came before it.


texts:
I am trying to set a OnClickListener to a image in a loop. If the params platform is "android" then use market app, instead of default browswer. Is there a better solution to my exception handling or eliminatingsome of the if-else ?

private void setupListener(ImageView image, final String platform,
        final String urlLink) {
    image.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (platform.equalsIgnoreCase(PLATFORM_ANDROID)) {
                // open with market app
                String packageName = extractPackageName(urlLink);
                if (packageName != null) {
                    try {
                        Intent market = new Intent(Intent.ACTION_VIEW);
                        market.setData(Uri.parse("market://details?id="
                                + packageName));
                        activity.startActivity(market);
                    } catch (Exception e) {
                        e.printStackTrace();
                        startInBroswer(urlLink);
                    }
                } else {
                    startInBroswer(urlLink);
                }

            } else {
                // open with default broswer.
                startInBroswer(urlLink);
            }

        }
    });
}

private void startInBroswer(String urlLink) {
    Intent browser = new Intent(Intent.ACTION_VIEW, Uri.parse(urlLink));
    activity.startActivity(browser);
}


texts: Matching a randomly made colour using sliders

texts:
Below is a code which creates a random colour and shows it to the user in a 64 x 64 square. The user must then use the 3 sliders (R, G, B) to match the colour as closely as possible

from tkinter import *
import random

main = Tk()

photo = PhotoImage(width = 64, height = 64)
photo_2 = PhotoImage(width = 64, height = 64)

r_answer = random.randrange(256)
g_answer = random.randrange(256)
b_answer = random.randrange(256)

def pixel(image, pos, colour):
    r,g,b = colour
    x,y = pos
    for i in range(32):
        for j in range(32):
            image.put("#%02x%02x%02x" % (r,g,b),(y+i,x+j))

def show_values(self):

    r = w1.get()
    g = w2.get()
    b = w3.get()

    pixel(photo, (0,0), (r, g, b))

    label = Label(main, image = photo)
    label.grid(row = 0, column = 1)

w1 = Scale(main, from_=0, to=255, command=show_values)
w1.grid(row = 0, column = 0)
w2 = Scale(main, from_=0, to=255, command=show_values)
w2.grid(row = 1, column = 0)
w3 = Scale(main, from_=0, to=255, command=show_values)
w3.grid(row = 2, column = 0)

pixel(photo_2, (0, 0), (r_answer, g_answer, b_answer))

label_2 = Label(main, image = photo_2)
label_2.grid(row = 1, column = 1)

main.mainloop()


texts: Displaying different tutorials about OneNote

texts:
In my app, I have this code to display different tutorials about OneNote.  This clears and resets certain values, and updates some variables so we know which version we are working with.  The main problem is it has a lot of repetition in the three ifs, although all comments are welcomed.

private void SwitchVersion(string version)
{
    // This programatically selects the top value that is always the same
    // to prevent crashes.  Items is a ListBox.
    Items.SelectedValue = "OneNote";

    // This clears all values except the top value.
    // Data.ItemList is an ObservableCollection<string> bound to Items.
    while (Data.ItemList.Count > 1)
    {
        Data.ItemList.RemoveAt(1);
    }

    // This clears the ObservableCollection<Type> of XAML pages navigated to with
    // the ListBox.  These values are tied to the values in ItemList.
    Data.Pages.Clear();

    if (version == "Phone")
    {
        foreach (string s in GlobalVars.PHome())
        {
            if (s == "OneNote")
            {
                continue;
            }
            Data.ItemList.Add(s);
        }

        foreach (Type t in GlobalVars.PHomeP())
        {
            Data.Pages.Add(t);
        }

        // This is the method called when a value in the ListBox is chosen.
        // We need to call this to update some submenus.
        Data.NewSelectionP("OneNote");
    }

    if(version == "WStore")
    {
        foreach (string s in GlobalVars.Home())
        {
            if (s == "OneNote") continue;
            Data.ItemList.Add(s);
        }

        foreach (Type t in GlobalVars.HomeP()) Data.Pages.Add(t);
        Data.NewSelectionWS("OneNote");
    }

    if (version == "2013")
    {
        foreach (string s in GlobalVars.Home2013())
        {
            if (s == "OneNote") continue;
            Data.ItemList.Add(s);
        }

        foreach (Type t in GlobalVars.HomeP2013()) Data.Pages.Add(t);
        Data.NewSelection2013("OneNote");
    }

    // This is the Frame used to display the data.
    DataFrame.Navigate(Data.Pages[Items.SelectedIndex]);
}


texts: Finding the length of arbitrary ASCII character strings

texts:
I have implemented this MIPS code to determine the length of given ASCII character strings.
Is there a simpler way to implement this code? Is there is a built-in function in MIPS?

  Given String:

  "Hello\n"

  Output:

  6

.data
    message: .asciiz "Hello\n"
.text

main:
    li $t1,0
    la $t0,message

loop:
    lb   $a0,0($t0)
    beqz $a0,done
    addi $t0,$t0,1
    addi $t1,$t1,1
    j     loop
done:

    li   $v0,1
    add  $a0, $0,$t1
    syscall

    li   $v0,10
    syscall


texts:
I needed a quick caching mechanism to save a bitmap (picture). There was no way I could get the bitmap to the class where I need to upload it to the server so for the sake of organization and code cleanliness I created this. I have never seen this before implemented this way but to me this not only fits the purpose but seems to be a good way to do this. I am unsure and definitely want to find the best way to do this.

The image in this cache would be accessed roughly around 30 seconds to 2 minutes after it is stored, so I am not worried about it being garbage collected soon. That is why I used a soft reference but I needed it to stay for awhile just in case the user wanted to delay or lag a while before uploading the image. I understand it could return null if it was garbage-collected, which is an edge case for now.

public class ImageCacheUtils {

    private static SoftReference<Bitmap> imageReference;

    public static void cache(Bitmap bitmap) {
        imageReference = new SoftReference<Bitmap>(bitmap);
    }

    @Nullable
    public static Bitmap getImage() {
        return imageReference.get();
    }
}


texts: Providing factory method to Lazy when factory exists on another lazy instance?

texts:
The Problem

I found myself needing an instance of an IObjectContext interface that should never be null, but wanting to delay instantiation until after some required resources have been loaded.

I decided to approach this with Lazy<T>, but quickly ran into an issue -- I also require an IObjectSet<TEntity> that is never null and lazy instantiated. The problem is this:

// lazyObjectSet needs to be created directly after lazyContext, but I need to
// delay instantiating both. The desired factory method exists on lazyContext,
// but accessing lazyContext.Value instantiates context before it is needed:
//
var lazyObjectSet = new Lazy<IObjectSet<TEntity>>(lazyContext.Value.FactoryMethodName);

My Solution

I would like suggestions for improvements on my approach, or alternative approaches to the problem.

public static class LazyExtensions {
    private class LazyFactory<T, TResult> where TResult : class {
        private readonly Lazy<T> _dependency;
        private readonly MethodInfo _factory;

        public LazyFactory(Lazy<T> lazyDependency, MethodInfo lazyFactory) {
            // Argument null checks omitted for brevity
            Contract.Requires(typeof(TResult).Equals(lazyFactory.ReturnType));
            Contract.Requires(lazyFactory.GetParameters().Count() == 0);

            _factory = lazyFactory;
            _dependency = lazyDependency;
        }

        public TResult Invoke() {
            return (TResult) _factory.Invoke(_dependency.Value, null);
        }
    }

    public static Func<TOut> GetLazyFactory<TIn, TOut>(
        Lazy<TIn> dependency, MethodInfo factoryInfo) where TOut : class {
        return new LazyFactory<TIn, TOut>(dependency, factoryInfo).Invoke;
    }
}

Now I can use GetLazyFactory() to write the following, and the context should not be instantiated until lazyObjectSet.Value is accessed:

var lazyFactory = LazyExtensions.GetLazyFactory<IObjectContext, IObjectSet<TEntity>>(
    new Lazy<IObjectContext>(factory.Create),
    typeof (IObjectContext).GetMethod("ObjectSet"));

var lazyObjectSet = new Lazy<IObjectSet<TEntity>>(lazyFactory);

How can this be improved, and is there a better way of doing this?


texts: How to turn this working A/B optimization program into more pythonic code?

texts:
I have a working solution for the given problem of A/B Optimization, but you as an experienced Python (3) developer will agree with me, that this solution is not very pythonic at all.
My Question here is: How do I make this code more pythonic?
It's a very procedural process that one would expect from a Basic program, but not from a Python program. Please help me to become a better coder and make pythonic code by working through this example with me.
Here's the problem and my solution.
Problem

In this test you will be given a CSV containing the results of a website's A/B homepage test. The site is simultaneously testing 5 design variables (A, B, C, D, and E) and tracking if users clicked on the signup button (Z). Each line of the CSV represents a visitor to the homepage, what they saw, and if they clicked or not. The A-E variables will have values of 1-5, representing which version of that design element was shown to the user. The Z variable will contain either a 1 to represent that the user clicked signup, or a 0 to represent that the user did not.
A B C D E Z
1 3 1 2 4 1
3 2 1 5 5 0
4 3 2 2 5 1
5 5 2 3 4 0
2 4 1 3 4 0
...

Your task will be to determine the single combination of A-E values that will make users most likely to click the signup button. Assume the effects of each A-E value are mutually exclusive. If two values of a variable are equally optimal, choose the lesser value. You will enter the answer in the form of a 5-digit number, the first digit being the optimal A value, the second being the optimal B value, the third being the optimal C value, etc.

Solution
from urllib.request import urlopen

def getBestDesign(url):
    data = urlopen(url).readlines()
    A = {}; B = {}; C = {}; D = {}; E = {};
    A['1'] = 0
    A['2'] = 0
    A['3'] = 0
    A['4'] = 0
    A['5'] = 0
    B['1'] = 0
    B['2'] = 0
    B['3'] = 0
    B['4'] = 0
    B['5'] = 0
    C['1'] = 0
    C['2'] = 0
    C['3'] = 0
    C['4'] = 0
    C['5'] = 0
    D['1'] = 0
    D['2'] = 0
    D['3'] = 0
    D['4'] = 0
    D['5'] = 0
    E['1'] = 0
    E['2'] = 0
    E['3'] = 0
    E['4'] = 0
    E['5'] = 0
    for row in data:
        row = row.decode(encoding='UTF-8').split('\t')
        if row[5].startswith('1'):
            A[str(row[0])] += 1
            B[str(row[1])] += 1
            C[str(row[2])] += 1
            D[str(row[3])] += 1
            E[str(row[4])] += 1
    maxclicks_A = max(A.values())
    maxclicks_B = max(B.values())
    maxclicks_C = max(C.values())
    maxclicks_D = max(D.values())
    maxclicks_E = max(E.values())
    for k, v in A.items():
        if v == maxclicks_A:
            print('A: ', k)
    for k, v in B.items():
        if v == maxclicks_B:
            print('B: ', k)
    for k, v in C.items():
        if v == maxclicks_C:
            print('C: ', k)
    for k, v in D.items():
        if v == maxclicks_D:
            print('D: ', k)
    for k, v in E.items():
        if v == maxclicks_E:
            print('E: ', k)

if __name__ == "__main__":
    url = input('Url: ')
    getBestDesign(url)


texts:
IIUC I should decouple UI logic from the model and controller in my project. I didn't succeed and had to resort to TextView etc in my game logic:

package dev.game.adventure;

import android.graphics.drawable.Drawable;
import android.widget.TextView;

public class Adventure {

    private Player player;

    public Player getPlayer() {
        return player;
    }

    public Adventure(TextView t, AdventureActivity target, PlaceView placeView) {
        World world = new AdventureWorld(this, t, target, placeView);
        Person me = new Person(world, "You", 0, target);
        placeView.mainCharacter = me;
        player = new Player(world, me, t);
    }

    public Drawable loadPicture(int imageName, AdventureActivity target) {
        Drawable im = target.getResources().getDrawable(imageName);
        return im;
    }
}

I have similar to the above in several classes, passing on an android activity and/or a textview into model and controller objects. Will this be a problem and is it possible to solve?


texts:
I've written a variety of libraries that query and work with data from APIs. While the classes and objects being passed around vary from project to project, I'm generating GET requests in the same manner in each project.

I have a basic method to generate a GET request:

private string GenerateWebRequest(string conn)
{
    try
    {
        using (var webClient = new WebClient())
        {
            return webClient.DownloadString(conn);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("There was a problem generating the web request to the API server.");
        Console.WriteLine(e.StackTrace);
        return string.Empty;
    }
}

To make life easier and avoid code repetition, I create a Config object in the primary constructor for each library, which looks something like:

public class Config
{
    public Config()
    {
        localhostNearest = string.Empty;
        localhostRoute = string.Empty;
        localhostTrip = string.Empty;
        processLocation = string.Empty;
        workingDirectory = string.Empty;
        datasource = string.Empty;
    }

    public string localhostNearest { get; set; }

    public string localhostRoute { get; set; }

    public string localhostTrip { get; set; }

    public string processLocation { get; set; }

    public string workingDirectory { get; set; }

    public string datasource { get; set; }
}

And the instantiation of the Config object:

Config cfg = new Config
{
    localhostNearest = "http://localhost:5000/nearest/v1/driving/",
    localhostRoute = "http://localhost:5000/route/v1/driving/",
    localhostTrip = "http://localhost:5000/trip/v1/driving/",
    processLocation = installationFolder + "\\osrm-routed.exe",
    workingDirectory = workingFolder + @"data\"
};

The string conn that gets passed as a parameter to the GenerateWebRequest() method is generated in individual methods, dependent on what should be queried and then deserialized (each response is a JSON string). A sample conn generation would be:

string response = GenerateWebRequest($"{_config.localhostNearest}{lat},{lon}?apiKey={key}");

which would come out as:

http://localhost:5000/route/v1/nearest/-3.3431053161621094,52.50671376947057?apiKey=XXXXX

The connection string is typically made up of three parts:

  Base URL. Such as http://localhost:5000/api/
  User query, which part of the API is being queried.
  API key appended to the end of the URL.

I feel like there is a cleaner way of doing this in each project, and some methods end up being overly verbose due to the creation of the URL.

Are there any recommendations that could be made to improve this?


texts:
Are there any potential issues with the following Javascript code:

var BobsGarage = BobsGarage || {}; // namespace

/**
 * BobsGarage.Car
 * @constructor
 * @returns {BobsGarage.Car}
 */
BobsGarage.Car = function() {

    /**
     * Engine
     * @constructor
     * @returns {Engine}
     */
    var Engine = function() {
        // definition of an engine
    };

    Engine.prototype.constructor = Engine;
    Engine.prototype.start = function() {
        console.log('start engine');
    };

    /**
     * Tank
     * @constructor
     * @returns {Tank}
     */
    var Tank = function() {
        // definition of a tank
    };

    Tank.prototype.constructor = Tank;
    Tank.prototype.fill = function() {
        console.log('fill tank');
    };

    this.engine = new Engine();
    this.tank = new Tank();
};

BobsGarage.Car.prototype.constructor = BobsGarage.Car;

/**
 * BobsGarage.Ferrari
 * Derived from BobsGarage.Car
 * @constructor
 * @returns {BobsGarage.Ferrari}
 */
BobsGarage.Ferrari = function() {
    BobsGarage.Car.call(this);
};
BobsGarage.Ferrari.prototype = Object.create(BobsGarage.Car.prototype);
BobsGarage.Ferrari.prototype.constructor = BobsGarage.Ferrari;
BobsGarage.Ferrari.prototype.speedUp = function() {
    console.log('speed up');
};

// Test it on the road

var car = new BobsGarage.Car();
car.tank.fill();
car.engine.start();

var ferrari = new BobsGarage.Ferrari();
ferrari.tank.fill();
ferrari.engine.start();
ferrari.speedUp();

// var engine = new Engine(); // ReferenceError

console.log(ferrari);

The goal is to have prototype inheritance and nested classes so that classes defined within BobsGarage.Car are not accessible outside the constructor of BobsGarage.Car but instances of them are accessible to derived classes, as shown in the test code.

Note: I am referring to the concept of Class in Javascript as defined on the MDN.


texts:
I keep seeing /subsite/../global/css/file.css when I look at my website's source code, and today I decided that I want to get rid of the unnecessary traversal in the path itself, so it becomes /global/css/file.css. I made myself a function which I now use for all paths. Here is the base of my function that accomplishes this:

function djpth($pth){
    // Split path at slashes (always receives path with forward slash)
    $pth = explode('/',$pth);
    // Iterate through the new array
    foreach ($pth as $i => $part)
        // If we find a traversal mark
        if ($part == '..')
            // We get rid of the folder name before the mark and the mark itself
            array_splice($pth,$i-1,2);
    // We join the array back together
    $pth = implode('/',$pth);
    // Then we return the resolved path
    return $pth;
}

I want to know if there's a better way to go about this, or if this is the best I can get.


texts:
I have this code I use to connect to the database and get a thing from it secure, How can I make more secure??

class db {
    // The database connection
    protected static $connection;

    /**
     * Connect to the database
     *
     * @return bool false on failure / mysqli MySQLi object instance on success
     */
    protected function connect() {
        // Try and connect to the database
        if(!isset(self::$connection)) {

            // Load configuration there are defined in config.php
            require_once('app/config/config.php');
            self::$connection = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DBNAME);
        }

        // If connection was not successful, handle the error
        if(self::$connection === false) {
            // Handle error - notify administrator, log to a file, show an error screen, etc.
            return false;
        }
        return self::$connection;
    }

    /*
        Query the database

        @param $query The query string
        @return mixed The result of the mysqli::query() function
    */
    private function query($query) {
        // Connect to the database
        $connection = $this->connect();

        // Query the database
        $result = $connection->query($query);
        return $result;
    }

    /*
        Fetch rows from the database (SELECT query)

        @param $query The query string
        @return bool False on failure / array Database rows on success
    */
    public function select($query) {
        $result = $this->query($query);

        if($result === false) {
            return false;
        }

        $rows = array();
        while ($row = $result->fetch_assoc()) {
            $rows[] = $row;
        }
        return $rows;
    }
}

When I want infomation from the DB
Example:

$db = new db();
$result = $db->select("SELECT * FROM users WHERE name = John");


texts: Two (or more) LRU caches for a Node.js app

texts:
Here is a caching code of a nodejs / typescript app using lru Cache module from https://www.npmjs.com/package/lru-cache.
For various reason i need to setup separate caches: one for homeCache another one for detailThreadCache... but this is just the beginning I may need to set up more.

This code is working, but how would you refactor it to improve code reuse ? Would you use object oriented paradigm ? If yes how ?

const homeCache = lruCache( 50 )
const detailThreadCache = lruCache( 150 )

export function homeCachedData( key ) {
    return homeCache.get( key )
}

export function homeSetCache( key: string, value, duration: number ) {
    homeCache.set( key, value, duration )
}

export function detailThreadGetCache( key ) {
    return detailThreadCache.get( key )
}

export function detailThreadSetCache( key: string, value, duration: number ) {
    detailThreadCache.set( key, value, duration )
}


texts:
I wrote a function to calculate the gamma coefficient of a clustering. The bottleneck is the comparison of values from dist_withing to dist_between. To speed this up, I tried to adapt and compile it using Cython (I dealt with C only few times). But I don't know, how to rapidly iterate over numpy arrays or if its possible at all to do it faster than

for i in range(len(arr)):
    arr[i]

I thought I could use a pointer to the array data and indeed the code runs in only half of the time, but pointer1[i] and pointer2[j] in cdef unsigned int countlower won't give me the expected values from the arrays. So, how to properly and speedy iterate over an array? And where else can be made improvements, even if in this case it would not make such a difference concerning runtime-speed?

# cython: profile=True
import cython

import numpy as np
cimport numpy as np

from scipy.spatial.distance import squareform

DTYPE = np.float
DTYPEint = np.int

ctypedef np.float_t DTYPE_t
ctypedef np.int_t DTYPEint_t

@cython.profile(False)
cdef unsigned int countlower(np.ndarray[DTYPE_t, ndim=1] vec1,
                             np.ndarray[DTYPE_t, ndim=1] vec2,
                             int n1, int n2):
    # Function output corresponds to np.bincount(v1 < v2)[1]

    assert vec1.dtype == DTYPE and vec2.dtype == DTYPE

    cdef unsigned int i, j
    cdef unsigned int trues = 0
    cdef unsigned int* pointer1 = <unsigned int*> vec1.data
    cdef unsigned int* pointer2 = <unsigned int*> vec2.data

    for i in range(n1):
        for j in range(n2):
            if pointer1[i] < pointer2[j]:
                trues += 1

    return trues

def gamma(np.ndarray[DTYPE_t, ndim=2] Y, np.ndarray[DTYPEint_t, ndim=1] part):
    assert Y.dtype == DTYPE and part.dtype == DTYPEint

    if len(Y) != len(part):
        raise ValueError('Distance matrix and partition must have same shape')

    # defined locals
    cdef unsigned int K, c_label, n_, trues
    cdef unsigned int s_plus = 0
    cdef unsigned int s_minus = 0

    # assigned locals
    cdef np.ndarray n_in_ci = np.bincount(part)
    cdef int num_clust = len(n_in_ci) - 1
    cdef np.ndarray s = np.zeros(len(Y), dtype=DTYPE)

    # Partition should have at least two clusters
    K = len(set(part))
    if K < 2:
        return 0
    # Loop through clusters
    for c_label in range(1, K+1):
        dist_within = squareform(Y[part == c_label][:, part == c_label])
        dist_between = np.ravel(Y[part == c_label][:, part != c_label])
        n1 = len(dist_within)
        n2 = len(dist_between)

        trues = countlower(dist_within, dist_between, n1, n2)
        s_plus += trues
        s_minus += n1 * n2 - trues

    n_ =  s_plus + s_minus

    return (<double>s_plus - <double>s_minus) / <double>n_ if n_ != 0 else 0

Edit1: Passing just the pointers, instead of the arrays to the time-critical function (>99% of time is spent there) made a ~ 10% speed-up. I guess some things just cannot be made faster

@cython.profile(False)
@cython.boundscheck(False)
@cython.nonecheck(False)
cdef unsigned int countlower(double* v1, double* v2, int n1, int n2):
    ''' Function output corresponds to np.bincount(v1 < v2)[1]'''
    ''' The upper is not correct. It rather corresponds to
    sum([np.bincount(v1[i] < v2)[1] for i in range(len(v1))])'''
    cdef unsigned int trues = 0

    cdef Py_ssize_t i, j
    with nogil, parallel():
        for i in prange(n1):
            for j in prange(n2):
                if v1[i] < v2[j]:
                    trues += 1
    return trues


texts: Independent cascade model for networkx graphs

texts:
Similar to this question, I implemented the independent cascade model, but for a given networkx graph (including multigraph with parallel edges). My focus is on readability, pythonic-ness, and performance (although the problem itself is NP-hard).
I cannot wait to hear your feedback!
def independent_cascade_model(G: nx.Graph, seed: list, beta: float=1.0):
    informed_nodes = {n: None for n in seed}
    updated = True

    while updated:
        for u, v, diffusion_time in G.edges(nbunch=informed_nodes, data='diffusion_time'):
            updated = False
            if informed_nodes[u] == None or informed_nodes[u] < diffusion_time:
                if random.random() < beta:
                    if v not in informed_nodes or diffusion_time < informed_nodes[v]:
                        informed_nodes[v] = diffusion_time
                        updated = True
    return informed_nodes


texts: Optimizing lighting algorithm for a voxel engine

texts:
I am creating a Minecraft-like terrain engine in XNA to learn HLSL and more XNA. The problem is my lighting algorithm. Whenever a block which emits light is placed, it takes about half a second to calculate it. I have implemented the lighting in a recursive way.

public void DoLight(int x, int y, int z, float light)
{
    Vector3i xDecreasing = new Vector3i(x - 1, y, z);
    Vector3i xIncreasing = new Vector3i(x + 1, y, z);
    Vector3i yDecreasing = new Vector3i(x, y - 1, z);
    Vector3i yIncreasing = new Vector3i(x, y + 1, z);
    Vector3i zDecreasing = new Vector3i(x, y, z - 1);
    Vector3i zIncreasing = new Vector3i(x, y, z + 1);

    if (light > 0)
    {
        light--;

        world.SetLight(x, y, z, (int)light);
        Blocks.Add(new Vector3(x, y, z));

        if (world.GetLight(yDecreasing.X, yDecreasing.Y, yDecreasing.Z) < light &&
            !world.GetBlock(yDecreasing.X, yDecreasing.Y, yDecreasing.Z).IsSolid &&
            world.InBounds(yDecreasing.X, yDecreasing.Y, yDecreasing.Z))
            DoLight(x, y - 1, z, light);
        if (world.GetLight(yIncreasing.X, yIncreasing.Y, yIncreasing.Z) < light &&
            !world.GetBlock(yIncreasing.X, yIncreasing.Y, yIncreasing.Z).IsSolid &&
            world.InBounds(yIncreasing.X, yIncreasing.Y, yIncreasing.Z))
            DoLight(x, y + 1, z, light);
        if (world.GetLight(xDecreasing.X, xDecreasing.Y, xDecreasing.Z) < light &&
            !world.GetBlock(xDecreasing.X, xDecreasing.Y, xDecreasing.Z).IsSolid &&
            world.InBounds(xDecreasing.X, xDecreasing.Y, xDecreasing.Z))
            DoLight(x - 1, y, z, light);
        if (world.GetLight(xIncreasing.X, xIncreasing.Y, xIncreasing.Z) < light &&
            !world.GetBlock(xIncreasing.X, xIncreasing.Y, xIncreasing.Z).IsSolid &&
            world.InBounds(xIncreasing.X, xIncreasing.Y, xIncreasing.Z))
            DoLight(x + 1, y, z, light);
        if (world.GetLight(zDecreasing.X, zDecreasing.Y, zDecreasing.Z) < light &&
            !world.GetBlock(zDecreasing.X, zDecreasing.Y, zDecreasing.Z).IsSolid &&
            world.InBounds(yDecreasing.X, yDecreasing.Y, zDecreasing.Z))
            DoLight(x, y, z - 1, light);
        if (world.GetLight(zIncreasing.X, zIncreasing.Y, zIncreasing.Z) < light &&
            !world.GetBlock(zIncreasing.X, zIncreasing.Y, zIncreasing.Z).IsSolid &&
            world.InBounds(zIncreasing.X, zIncreasing.Y, zIncreasing.Z))
            DoLight(x, y, z + 1, light);
    }
}

Does anyone see what is costing me so much performance? And if so, could you please suggest any way to fix it?

Especially when I try to update only a single light every frame, I get a depressingly low FPS of 4 (maybe the recursion is the problem).  Does anyone know if a iterative would increase performance ?  If so, how would I implement it?


texts: Decoupling tests from implementation and increase their resilience

texts:
I have read on numerous occasions that tests should not be coupled to implementation details - this makes perfect sense.

Now I am having some trouble decoupling my tests from implementation details and am kindly asking for some help.

The relevant portion of the repository that I am testing looks like this:

public class PostsRepository : IPostsRepository
{
    private readonly DatabaseContext context;

    public PostsRepository(DatabaseContext context)
    {
        this.context = context;
    }

    public Post Find(string slug)
    {
        return context
            .Posts
            .SingleOrDefault(post => post.Slug == slug);
    }

    public bool Delete(string slug)
    {
        var post = Find(slug);

        if (post == null) return false;

        context.Posts.Remove(post);
        return true;
    }
}

The context is mocked using the technique described here and then manually injected into the repository.

The corresponding tests that I am concerned about look like this:

[Test]
public void Delete_ExistentPost_DeletesPost()
{
    databaseSet.SetupSeedData(new List<Post>
    {
        PostsMother.CreatePost(withSlug: "abc")
    });

    repository.Delete("abc");

    databaseSet.Verify(d => d.Remove(It.IsAny<Post>()));
}

[Test]
public void Delete_NonExistentPost_DoesNotThrow()
{
    repository.Delete("abc");
}

[Test]
public void Delete_ExistentPost_ReturnsTrue()
{
    databaseSet.SetupSeedData(new List<Post>
    {
        PostsMother.CreatePost(withSlug: "abc")
    });

    var actual = repository.Delete("abc");
    Assert.True(actual);
}

[Test]
public void Delete_NonExistentPost_ReturnsFalse()
{
    var actual = repository.Delete("abc");
    Assert.False(actual);
}

These tests seem to work well enough but I am concerned about their brittleness. If you look at the implementation of the Delete method you will see that it uses the Remove method but what if that changed? The test would break.

Furthermore (and more importantly), the test is highly dependent on the Delete method using the Find method as the Find method uses the Posts property of the database set which is stubbed according to the seed data configured in the arrange phase of the test (using SetUpSeedData).

It is perfectly conceivable that I will adjust the implementation of the Delete method to catch an exception and return the boolean according to the exception instead of using the Find method.

How can I improve the resilience of my tests in this case?


texts: Python - 'if name in dict:' OR 'try:/except:'

texts:
I'm writing some OO Python and I would like to know which of these methods is more pythonic, or which is generally better, or faster. This is an accessor for an attribute which is a dictionary.

Method 1: if/else

def GetSlot(self, slot_name):
    if slot_name in self.Slots:
        return self.Slots[slot_name]
    else:
        return None

Method 2: try/except

def GetSlot(self, slot_name):
    try:
        return self.Slots[slot_name]
    except KeyError:
        return None

I understand that using try/except is better use of duck typing, but will this make a positive impact on performance?


texts: Find DivTag element in list and click when innerHTML matches account name

texts:
I need to click on a "account" button from a table of buttons. If this "account" button is not present, then I will need to click a different "UseAnotherAccount"
 button.

How I do it at the moment is:

Set a flag account_found to be false by default
use a foreach loop to search through the whole _list of buttons
If the expected account button is found, click it, set account_found flag to be true and break away from this foreach loop
an additional if block is used to to click on UseAnotherAccount button if account_found flag is not set.

My code is shown below:

bool account_found = false;
foreach (DivTag element in _list) {
    String account_name = element.GetInnerHtml();
    if (account_name.Equals(_account_name)) {
        element.Click();
        account_found = true;
        break;
    }
}
if (!account_found) {
    _my_repo.SignInToYourAccount.UseAnotherAccount.Click();
}

I have this feeling my way is not the most elegant way to achieve this. Any suggestions?


texts: Code enhancement for existing npm package

texts:
I am trying to improve the code in the npm package. I have looked through the code but don't have any ideas how to write proper code.

GitHub

//An implementation of SpaceStream that produces a transform stream, which pipes to process.stdout.
//The transform function adds two properties: change in latitude per second (deltaLat), and change in longitude per second (deltaLong).
//These are calculated based on the difference between each current response's coordinates and the coordinates of the response preceeding it.
//Time values are calculated using the timestamp property of each response object.
//The initial response in a new stream will be piped, and will have its deltaLat and deltaLong properties set to null.

var SpaceStream = require('../lib/index');
var util = require('util');
var Transform = require('stream').Transform;

function DeltaLatLong(){
  Transform.call(this);
  this._lastBlip = null;
}
  util.inherits(DeltaLatLong, Transform);

  DeltaLatLong.prototype._transform = function(chunk, encoding, done){
    var currentChunk = JSON.parse(chunk);
    var previousChunk = this.getComparitor();
    var modifiedChunk;
    var calculatedRates;
    var newPacket;

    if (previousChunk === null){
      modifiedChunk = {
        "name": currentChunk.name,
        "id": currentChunk.id,
        "deltaLat": null,
        "deltaLong": null
      };
    } else {

      calculatedRates = this.calculateRates(previousChunk, currentChunk);

      modifiedChunk = {
        "name": currentChunk.name,
        "id": currentChunk.id,
        "deltaLat": calculatedRates.dLat,
        "deltaLong": calculatedRates.dLong
      };
    }
    newPacket = JSON.stringify(modifiedChunk) +'\n';
    this.setComparitor(currentChunk);
    this.push(newPacket);

    done();

  };
  DeltaLatLong.prototype.setComparitor = function(obj){
    if (this._lastBlip === null){
      this._lastBlip = obj;
      return false;
    }
    this._lastBlip = obj;
    return this._lastBlip;
  };

  DeltaLatLong.prototype.getComparitor = function(){
    return this._lastBlip;
  };

  DeltaLatLong.prototype.calculateRates = function(obj1, obj2){
    if (!obj1 || !obj2 || !obj1.latitude || !obj1.longitude || !obj2.latitude || !obj2.longitude){
      throw new Error("The provided Satelite position objects were invalid");
    }
    var changeInLatitude = obj2.latitude - obj1.latitude;
    var changeInLongitude = obj2.longitude - obj1.longitude;
    var changeInTime = obj2.timestamp - obj1.timestamp;

    var dLat = (changeInLatitude / changeInTime);
    var dLong = (changeInLongitude / changeInTime);

    return {
      'dLat': dLat,
      'dLong': dLong
    };
  };

var originalStream = new SpaceStream(25544, 59);
var newStream = new DeltaLatLong();

originalStream.pipe(newStream).pipe(process.stdout);


texts:
I made my first program that I might actually use and I was wondering if anyone had some tips on how I could improve it.

My code is an auto-clicker that uses Python3 ctypes for the clicking and Tkinter for the GUI. I made this in 2 hours so there might be a lot of optimization I could do.

from tkinter import *
from tkinter import ttk
import ctypes
import time

mouse = ctypes.windll.user32
state = False

def StateFalse():
     global state
     global x
     if state == True:
          state = False
          x = 0

def StateTrue():
     global state
     global x
     if state == True:
          state = True
     else:
          x = 0
          state = True

root = Tk()
root.title("AutoClicker")
root.resizable(width=FALSE, height=FALSE)

amount = StringVar()
speed = StringVar()

amount.set(0)
speed.set(100)
mainframe = ttk.Frame(root)
mainframe.grid(padx=5, pady=5)

amountLabel = ttk.Label(mainframe, text="Number of Clicks\n(set to 0 for infinite)").grid(column=1, row=1, sticky=W)
speedLabel = ttk.Label(mainframe, text="Click interval\n(In milliseconds)").grid(column=1, row=2, sticky=W)
amountEntry = ttk.Entry(mainframe, textvariable=amount, width=5).grid(column=2, row=1)
speedEntry = ttk.Entry(mainframe, textvariable=speed, width=5).grid(column=2, row=2)
startButton = ttk.Button(mainframe, text="Start", width=10, command=StateTrue).grid(column=1, row=3,columnspan=2,sticky=W)
stopButton = ttk.Button(mainframe, text="Stop", width=10, command=StateFalse).grid(column=2, row=3, columnspan=2,sticky=E)

mainframe.bind("<F1>",StateTrue())
mainframe.bind("<F3>",StateFalse())

timekeeper = 0
x = 0

while True:
     timekeeper += 1
     if state == True:
          Amount = int(amount.get())
          Speed = int(speed.get())
          print(state)
          if Amount == 0:
               time.sleep(Speed / 1000)
               mouse.mouse_event(2, 0, 0, 0, 0)  # left mouse button down
               mouse.mouse_event(4, 0, 0, 0, 0)  # left mouse button up
               x += 1
               print("Clicked %s Times" % (x))

          elif x < Amount and state == True:
               time.sleep(Speed / 1000)
               mouse.mouse_event(2, 0, 0, 0, 0)  # left mouse button down
               mouse.mouse_event(4, 0, 0, 0, 0)  # left mouse button up
               x += 1
               print("Clicked %s Times" % (x))
               if x == Amount:
                    state = False
     root.update()


texts: A free-standing weak_ptr equivalent to handle lifetime of non-shared callback objects

texts:
I've been finding myself wanting the following pattern recently:

void perform_async_operation(std::function<void(int)>);

class some_class {
  public:
    void foo() {
      perform_async_operation([this](int result) {
        data_ = result;
      });
    }

  private:
    int data_;
};

Now, the issue here is that the lifetime of some_class if fully disconnected from when the callback will be invoked, and I do not want to move to shared ownership to put a shared_ptr in the lambda (like how the boost::ASIO examples handle that situation).

I do, however, have a saving grace: I know for certain that the callback will be invoked in the same thread that manages the lifetime of some_class.

In order to solve this, I've created a bastardized version of weak_ptr (with a matching equivalent of enabled_shared_from_this) that does not require the object to be managed by a shared_ptr in the first place.

#ifndef SLT_WEAK_REF_INCLUDED_H
#define SLT_WEAK_REF_INCLUDED_H

#include <memory>

template <typename T>
class weak_ref {
 public:
  weak_ref(std::shared_ptr<T*> weak_data) : weak_data_(std::move(weak_data)) {}

  operator bool() const { return *weak_data_ != nullptr; }
  T* operator->() const { return *weak_data_; }

 private:
  // Can be safely assumed to always be set.
  std::shared_ptr<T*> weak_data_;
};

template <typename CRTP>
class enable_weak_ref {
 public:
  enable_weak_ref() = default;
  enable_weak_ref(enable_weak_ref&& rhs)
      : weak_data_(std::move(rhs.weak_data_)) {
    if (weak_data_) {
      *weak_data_ = this;
    }
  }

  enable_weak_ref& operator=(enable_weak_ref&& rhs) {
    weak_data_ = std::move(rhs.weak_data_);
    if (weak_data_) {
      *weak_data_ = static_cast<CRTP*>(this);
    }
  }

  // explicitely do nothing
  enable_weak_ref(enable_weak_ref const& rhs) {}
  enable_weak_ref& operator=(enable_weak_ref const&) {}

  ~enable_weak_ref() {
    if (weak_data_) {
      *weak_data_ = nullptr;
    }
  }

  weak_ref<CRTP> get_weak_ref() {
    if (!weak_data_) {
      weak_data_ = std::make_shared<CRTP*>(static_cast<CRTP*>(this));
    }

    return weak_ref<CRTP>(weak_data_);
  }

 private:
  // TODO: perhaps switch to a simple manually ref-counted type here.
  // instead of the overkill shared_ptr<>
  std::shared_ptr<CRTP*> weak_data_;
};

#endif

sample usage:

#include "weak_ref.h"

#include <queue>
#include <iostream>
#include <functional>

std::queue<std::function<void(int)>> queue_;

void queue_delayed(std::function<void(int)> cb) {
  queue_.emplace(std::move(cb));
}

class my_class : public enable_weak_ref<my_class> {
public:
  my_class() {
    queue_delayed([ref = get_weak_ref()](int v){
      if(ref) {
        std::cout << "passed " << v << std::endl;
        ref->value = v;
      }
      else {
        std::cout << "saved " << v << std::endl;
      }
    });
  }

  int value = 0;
};

int main() {
  my_class a;
  queue_.front()(12);
  queue_.pop();
  {
    my_class b;
  }
  queue_.front()(5);
  queue_.pop();

  return 0;
}

Notes:

Moving an object in a lambda is a C++14 feature, without which, a lot of back-and-forth ref-counting happens.
As mentioned, this is intentionally not thread-safe. Thread safety can be added if anyone needs it eventually.

Issues:

Is there a nicer way to tackle this I'm overlooking here?
weak_ref is very weak name, I'd gladly welcome better suggestions.
As always, comments on general code quality are most desired.


texts: Euler 35 - python solution taking too long

texts:
Here is my solution for Project Euler 35. (Find the number of circular primes below 1,000,000. Circular meaning all rotations of the digits are prime, i.e. 197, 719, 971.) The code takes about 30 minutes to run. Can you help me identify which parts of the algorithm are hogging up computation time?

I know there are many solutions out there, I just want to know why this one is soooo slow. I suspect it has something to do with the p.count function call.

p is initialized to a list of all primes below 1 million using the Sieve of Eratosthenes.
total is initialized to 0.

for i in p:
    primer = str(i)
    circ = 1
    for j in range(len(primer)-1):
        primer = primer[1:]+primer[:1]
        if (p.count(int(primer)) == 1):
            circ += 1
    if circ == len(primer):
        total += 1


texts:
I'm working on an application in which it takes quite a bit of time to initialize the data.

Some background: I'm creating a sort of pivot table in which I turn Figure 1 below into Figure 2. I've gone through with Stopwatchs and have been able to isolate a single line of code that takes 2 seconds during program load (it is in a loop called for roughly 2-300 rows of data, 2 seconds is the total time across all iterations). That line is marked in the code example below, Figure 3.

My question is if there is a better way to structure the example method such that I can avoid whatever overhead that line is causing. It is worth noting that when that line executes, mChar contains sometimes 0 elements, but up to around 5 or 1 (see edit below), so I can't imagine what would cause this to take so much time to execute.

Figure 1

SAMPLENUMBER | ANALYSIS_NAME | ANALYSIS_STATUS
----------------------------------------------
   1234      |     NO3       |       I
   1234      |     SO4       |       C
   5678      |     NO3       |       C

Figure 2

SAMPLENUMBER |     NO3       |      SO4
----------------------------------------------
   1234      |      I        |       C
   5678      |      C        |

Figure 3

private List<string> GetPivotData(DataRow sourceRow, DataTable sourceTable)
{
  int pivotStartIndex = sourceTable.Columns.IndexOf(Cols.HotDate) + 1;
  var retList = new List<string>(sourceTable.Columns.Count - pivotStartIndex);
  for (int i = pivotStartIndex; i < sourceTable.Columns.Count; i++)
  {
    string[] elementTest = sourceTable.Columns[i].ColumnName.Split('-');
    var mChars =
        from s in mainData.AsEnumerable()
        where s.Field<string>(Cols.Samplenumber) == sourceRow.Field<string>(Cols.Samplenumber)
          && s.Field<string>(Cols.ElementName) == elementTest[0].Trim()
          && s.Field<string>(Cols.AnalysisNumber) == elementTest[1].Trim()
        select s.Field<string>(Cols.AnalysisStatus);
    retList.Add(mChars.FirstOrDefault()); // <-- this is the line taking so much time.
  }
  return retList;
}

I've tried things like having retList as an array rather than a list, as well as calling .ToList() on my LINQ result and using .Find(x => true) and they really haven't had any effect. The method in Figure 3 is itself inside a for loop, called roughly 200 times, once per sample. The for loop inside the method itself iterates on average 5 times, so that line of code gets called about 1000 times, depending on the data. That means that the average time for the line is around 2ms, which may just be too small in itself to be able to do anything with. Swapping my for loops for Parallel.For halves the time it takes, but I've found that my logic doesn't work well with concurrency. At all.

Edit: I should clarify why I'm using FirstOrDefault() I suppose and I need to clarify an error in my initial post as well. The error is that I said mChars can contain up to 5 elements when FirstOrDefault() is called (it is retList that has up to 5). It will only ever have 0 or 1 element(s). When it's empty, I still need to add a null to the list, so I'm looking into a way to add the mChars result directly to the list without any searches at all.


texts: Online documentation tool with JavaScript

texts:
I'm trying to develop a web application for documentation..

The tool is functional.. Please review the code & help me with performance tuning & simplifying the JavaScript part..

Any suggestions or comment most welcome. Thanks in advance!

Note: Please type something on the <textarea> to see the live preview

$(function() {
  hljs.initHighlightingOnLoad();

  $('#doc_content').on('input', function() {
    var doc = this.value
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/__hj/g, '
')
      .replace(/hj__/g, '

')
      .replace(/__tl\s?/g, '
')
      .replace(/\s?tl__/g, '
')
      .replace(/__st\s?/g, '
')
      .replace(/\s?st__/g, '
')
      .replace(/__(o|u)l[^]*?(o|u)l__/g, m => m.replace(/(?:\r\n|\r|\n)/g, "

"))
      .replace(/__ol\s?/g, '

')
      .replace(/\s?ol__/g, '

')
      .replace(/__ul\s?/g, '

')
      .replace(/\s?ul__/g, '

');

    $('#doc_preview').html(doc);

    hljs.initHighlighting.called = false;
    hljs.initHighlighting();
  })
});
#doc_content {
  white-space: pre-wrap;
  resize: vertical;
  width: 99%;
  min-height: 100px;
  margin: 0px auto;
  font-family: 'Neuton', serif;
}

#doc_preview {
  margin-top: 30px;
  font-family: 'Neuton', serif;
  color: #242729;
  white-space: pre-wrap;
  font-size: 20px;
  line-height: 1.35;
}

#doc_preview .hljs {
  padding-left: 20px;
}

#doc_preview * {
  margin: 0px;
  padding: 0px;
}

#doc_preview h3 {
  margin-top: 8px;
  margin-bottom: -20px;
  font-family: 'Neuton', serif;
}

#doc_preview h4 {
  margin-bottom: -24px;
  font-family: 'Neuton', serif;
}

#doc_preview ul,
#doc_preview ol {
  margin-top: 8px;
}

#doc_preview li {
  margin-left: 30px;
  margin-bottom: 8px;
}

#doc_preview li:last {
  margin-bottom: 0px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.18.1/styles/atom-one-dark.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Neuton:wght@400&display=swap" rel="stylesheet">

  <textarea id="doc_content">
  __tl Some good title ! tl__

You can see a live preview as you type...

__hj
$(function(){
    hljs.initHighlightingOnLoad();

    $('#doc_content').keyup(function(){
        var doc = this.value
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;");

        $('#doc_preview').html(doc);

        hljs.initHighlighting.called = false;
        hljs.initHighlighting();
    })
});
hj__

__tl This is a sub title tl__

It's a great site to get answers for your programming queries !!

Here is a Ordered list:
__ol Login or Signup
Post your query
Check the answers. If you need any clarification, post a comment
Accept answer ol__
Here is an Unordered list:
__ul This is list item 1
This is item 2 ul__

A long passage will loook like below:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
  </textarea>


texts:
I've never formally learned javascript, and I feel very much like I'm unaware of 'good' practice.

I'm working on this open source project, and in particular the code that converts the incoming JSON into a usable data structure in this file

The relevent function looks like this:

   function start() {
       key = "toppage";
       utterances = {};
       links = {};
       colours = {};
       icons = {};
       labels = {};
       slide_number = {};
       var req = new XMLHttpRequest();
       req.open("GET", "pageset.json");
       req.overrideMimeType("application/json");
       req.send(null);
       req.onreadystatechange = function() {
           if (req.readyState == 4 && req.status == 200) {
               var obj = JSON.parse(req.responseText);
               for (grid in obj.Grid) {
           console.log(obj.Grid[grid][0])
                   labels[obj.Grid[grid][0]] = obj.Grid[grid][1];
                   utterances[obj.Grid[grid][0]] = obj.Grid[grid][2];
                   links[obj.Grid[grid][0]] = obj.Grid[grid][3];
                   icons[obj.Grid[grid][0]] = obj.Grid[grid][4];
                   colours[obj.Grid[grid][0]] = obj.Grid[grid][5];
                   slide_number[obj.Grid[grid][0]] = obj.Grid[grid][6];
           if(obj.Grid[grid][6]==0){
            key=obj.Grid[grid][0]
            }
               }
               grid_size_rows = obj.Settings[0];
               grid_size_columns = obj.Settings[0];
               setup_messagewindow();
               setup_table();
               load_page(key);
           }
       };
       //TODO - needs an error message if the JSON doesn't load
   }

I have NO idea if this is a reasonable way to populate structures in javascript.  It works, but I feel like it could be a hell of a lot more elegant.  Any comments people have would be welcome.


texts:
I'm learning C, specifically OOP in C. As practice, I wrote a dynamically-expanding array.

dynarray.h

#ifndef DYNARRAY_H
#define DYNARRAY_H

typedef struct DynArray {
    int length,
        capacity,
        *arr;

    void (*extend)(struct DynArray *dynArr);
    void (*insert)(struct DynArray *dynArr, int val);
    void (*print) (struct DynArray *dynArr);
} DynArray;

void DynArray_extend(DynArray* dynArr);
void DynArray_insert(DynArray* dynArr, int value);
void DynArray_print(DynArray* dynArr);

#endif

dynarray.c

#include <stdlib.h>
#include "dynarray.h"

DynArray* createDynArray() {
    DynArray* newDynArray = malloc(sizeof(DynArray));
    newDynArray->capacity = 10;
    newDynArray->arr = malloc(sizeof(int)*newDynArray->capacity);
    newDynArray->length = 0;

    newDynArray->extend = DynArray_extend;
    newDynArray->insert = DynArray_insert;
    newDynArray->print  = DynArray_print;
}

void DynArray_extend(DynArray* dynArr) {
    int newCapacity = dynArr->capacity * 2,
        *newArr = malloc(sizeof(int)*newCapacity),
        i;

    dynArr->capacity = newCapacity;

    for (i = 0; i < dynArr->length; i++) {
        newArr[i] = dynArr->arr[i];
    }
}

void DynArray_insert(DynArray* dynArr, int val) {
    if (dynArr->length == dynArr->capacity) {
        dynArr->extend(dynArr);
    }

    dynArr->arr[dynArr->length] = val;
    dynArr->length = dynArr->length + 1;
}

void DynArray_print(DynArray* dynArr) {
    int i;
    for (i = 0; i < dynArr->length; i++) {
        printf("%d\n", dynArr->arr[i]);
    }
}

And this is an example application of the dynamic array (program.c):

#include <stdio.h>
#include "dynarray.c"

int main( void ) {
    int i = 0;
    DynArray* someDynArray = createDynArray();

    printf("Length  : %d\n", someDynArray->length);
    printf("Capacity: %d\n", someDynArray->capacity);

    for (i = 0; i < 80; i++) {
        someDynArray->insert(someDynArray, i);
    }

    someDynArray->print(someDynArray);
}

I would like to know if there are any flaws in the style of implementing the abstract data type of the dynamically expanding array.


texts: Is this a good approach to loading JavaScript files asynchronously?

texts:
I want to load JS files asynchronously to speed up page loading, but also need to execute JS code only once the scripts finish loading (so I need a way to implement callbacks).

I based this off of some example code on the Google Pagespeed website:

// Add script elements as a children of the body
function downloadJSAtOnload() {
    var filesToLoad = [
        ["/assets/plugins/typeahead.bundle.min.js", "onTypeaheadLoaded"],
        ["https://apis.google.com/js/client:plusone.js?onload=googlePlusOnloadCallback", ""]
    ];

    filesToLoad.forEach(function(entry) {
        var element = document.createElement("script");
        element.src = entry[0];
        if (entry[1] != "") { // if an onload callback is present (NOTE: DOES NOT SUPPORT NAMESPACES -- http://stackoverflow.com/a/359910/1101095)
            element.onload = function() {
                if (typeof window[entry[1]] != "undefined") {
                    window[entry[1]]();
                }
            };
        }
        document.body.appendChild(element);
    });
}

// Check for browser support of event handling capability
if (window.addEventListener)
    window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
    window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;

I know there are libraries out there for dependency management, callback functions, etc., but I just want something very lightweight and using a library would mean having another HTTP request.

I'm very new to JavaScript and would really appreciate any feedback or advice you might have!


texts: Toggle nav that switches a banner section

texts:
I built this toggle nav that switches a banner section between the slider and a map. All works well but I would like to know how I could improve my JavaScript as I am quite new to it.

$(document).ready(function() {

// Banners Toggle
var bannerSlider = $('#banner_slider');
var bannerMap = $('#banner_map');

$('.thm-banner--toggles').find('a').on('click', function(e){
 e.preventDefault();

if ($(this).hasClass('toggle-map')) {
  bannerMap.css('z-index', '2');
  bannerSlider.css('z-index', '1');
}

if ($(this).hasClass('toggle-slider')) {
  bannerMap.css('z-index', '1');
  bannerSlider.css('z-index', '2');
}

});

});


texts: C++ password generator with WinAPI clipboard function

texts:
I made a simple password generator with a copy-to-clipboard functionality implemented via WinAPI calls. Here is the code:

#include <iostream>
#include <string>
#include <random>
#include <algorithm>
#include <Windows.h>

void copytoclipboard(const std::string& s){
    HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, s.size() + 1);
    memcpy(GlobalLock(hMem), s.c_str(), s.size() + 1);
    GlobalUnlock(hMem);
    OpenClipboard(0);
    EmptyClipboard();
    SetClipboardData(CF_TEXT, hMem);
    CloseClipboard();
}
int main(){
    std::string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%^&$+-_!@#%?";
    std::string pw = "";
    const int pass_length = 12;
    const int from = 0;
    const int to = chars.size();
    std::random_device rd;
    std::mt19937 g(rd());
    std::uniform_int_distribution<int>  distr(from, to);
    auto rng = std::default_random_engine{};
    std::shuffle(chars.begin(), chars.end(), rng);
    for (int i = 0; i < pass_length; ++i){
        pw.push_back(chars[distr(g)]);
    }
    copytoclipboard(pw);
}

What can be improved and are there any pitfalls with the above approach such as the lack of GlobalFree(hMem);?


texts: Check a string for any occurrences of certain character classes

texts:
This is a warm-up programming exercise for learning string methods in Python from HackerRank:

  You are given a string S.
  Your task is to find if string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.

  Input Format

  Single line containing, string S.

  Constraints

0 < len(S) < 1000

  Output Format

  In First line, print True if S has alphanumeric character otherwise print False.
  In Second line, print True if S has alphabetical character otherwise print False.
  In Third line, print True if S has digits otherwise print False.
  In Fourth line, print True if S has lowercase character otherwise print False.
  In Fifth line, print True if S has uppcase character otherwise print False.

My working solution is here:

def parse_input():
    string = raw_input()
    return string

def check_string(string):
    check_funs = [str.isalnum,
                  str.isalpha,
                  str.isdigit,
                  str.islower,
                  str.isupper,
                  ]
    return [any(fun(char) for char in string) for fun in check_funs]

def print_output(results):
    for el in results:
        print el

if __name__ == '__main__':
    string = parse_input()
    print_output(check_string(string))

Apologies for the lack of docstrings; I think aside from that, I'm PEP8 compliant but please let me know if I missed something.  I'm interested in any and all feedback of course, but in particular:

I feel like my check_string() function isn't very pretty.  What's the preferred syntax for folding a list of class methods into a list comprehension?  I found a possibly relevant Stack Overflow question but couldn't quite make heads or tails of it.  It just doesn't seem right to have to do str.method to refer to a function, but then call it with fun(my_string) for fun in func_list instead of my_string.fun() for fun in func_list. (But that latter bit doesn't work of course.)

What are some better ways?


texts:
This is a program I wrote in Python using the BeautifulSoup library. The program scrapes YouTube search results for a given query and extracts data from the channels returned in the search results.

I'm just looking for some tips on how to make my code look (and function) better. I removed most of the redundancies but to me the code still feels ugly.

Suggestions?

#!/usr/bin/python
# http://docs.python-requests.org/en/latest/user/quickstart/
# http://www.crummy.com/software/BeautifulSoup/bs4/doc/

import csv
import re
import requests
import time
from bs4 import BeautifulSoup

# scrapes the title
def getTitle():
    d = soup.find_all("h1", "branded-page-header-title")
    for i in d:
        name = i.text.strip().replace('\n',' ').replace(',','').encode("utf-8")
        f.write(name+',')
        print('\t\t%s') % (name)

# scrapes the subscriber and view count
def getStats():
    b = soup.find_all("li", "about-stat ") # trailing space is required.
    for i in b:
        value = i.b.text.strip().replace(',','')
        name = i.b.next_sibling.strip().replace(',','')
        f.write(value+',')
        print('\t\t%s = %s') % (name, value)

# scrapes the description
def getDescription():
    c = soup.find_all("div", "about-description")
    for i in c:
        description = i.text.strip().replace('\n',' ').replace(',','').encode("utf-8")
        f.write(description+',')
        #print('\t\t%s') % (description)

# scrapes all the external links
def getLinks():
    a = soup.find_all("a", "about-channel-link ") # trailing space is required.
    for i in a:
        url = i.get('href')
        f.write(url+',')
        print('\t\t%s') % (url)

# scrapes the related channels
def getRelated():
    s = soup.find_all("h3", "yt-lockup-title")
    for i in s:
        t = i.find_all(href=re.compile("user"))
        for i in t:
            url = 'https://www.youtube.com'+i.get('href')
            rCSV.write(url+'\n')
            print('\t\t%s,%s') % (i.text, url)

f = open("youtube-scrape-data.csv", "w+")
rCSV = open("related-channels.csv", "w+")
visited = []
base = "https://www.youtube.com/results?search_query="
q = ['search+query+here']
page = "&page="
count = 1
pagesToScrape = 20

for query in q:
    while count <= pagesToScrape:
        scrapeURL = base + str(query) + page + str(count)
        print('Scraping %s\n') %(scrapeURL)
        r = requests.get(scrapeURL)
        soup = BeautifulSoup(r.text)
        users = soup.find_all("div", "yt-lockup-byline")
        for each in users:
            a = each.find_all(href=re.compile("user"))
            for i in a:
                url = 'https://www.youtube.com'+i.get('href')+'/about'
                if url in visited:
                    print('\t%s has already been scraped\n\n') %(url)
                else:
                    r = requests.get(url)
                    soup = BeautifulSoup(r.text)
                    f.write(url+',')
                    print('\t%s') % (url)
                    getTitle()
                    getStats()
                    getDescription()
                    getLinks()
                    getRelated()
                    f.write('\n')
                    print('\n')
                    visited.append(url)
                    time.sleep(3)
        count += 1
        time.sleep(3)
        print('\n')
    count = 1
    print('\n')
f.close()


texts: How do I optimize this Java cube root function for BigInteger?

texts:
I find that this function is one of the biggest causes of slow program execution. I can write a square root version with BigInteger only, but with the cube root, the algorithm sometimes gets caught in an endless loop unless I also use BigDecimal, because the values of r and s never reach equilibrium. I've already used tricks like leftShift to multiply by 2 and s.multiply(s) in place of s.pow(2) to make it faster, but having to use BigDecimal is still slowing it down. Any idea how I could approach this problem?

public static BigDecimal THREE_D=BigDecimal.valueOf(3);

public static int UP=BigDecimal.ROUND_HALF_UP;

// other statements

public static BigInteger cbrt(BigInteger n)
{
 BigDecimal m=new BigDecimal(n);                          // BigDecimal copy
 BigInteger r=BigInteger.ZERO.setBit(n.bitLength()/3);    // initial estimate
 for(BigDecimal s=BigDecimal.ZERO;                        // different from r
     !r.equals(s.toBigInteger());                         // loop test: does r=s?
     s=new BigDecimal(r),r=new BigDecimal(r.shiftLeft(1)) // Convert to BigDecimal,
      .add(m.divide(s.multiply(s),UP))                    // do the tricky division,
      .divide(THREE_D,UP).toBigInteger());                // and convert back.
 return r;                                                // return the value
}

Edit: Followup to this question can be found here.


texts: Parse python code, for specific pep8 issues

texts:
I am aware, that libraries exist for parsing python code, however, for the sake of learning how they parse errors, I'm creating a script that checks a file for only 6 Pep8 errors just for reference.
This is how my current 6 Pep8 functions look (they append an issue to the issues list if the issue was found)
"""
[S001] Line is longer than 79 characters
[S002] Indentation is not a multiple of four
[S003] Unnecessary semicolon after a statement (note, semicolons are admissible in comments)
[S004] At least two spaces before inline comments required
[S005] TODO found (only in comments; the case does not matter)
[S006] More than two blank lines used before this line (must be output for the first non-empty line)
"""
def S001(self, ln_num: int, line: str):
    if len(line) > 79:
        self.issues.append(f"Line {ln_num}: S001 Too Long")

def S002(self, ln_num: int, line: str):
    indentation_length = len(line) - len(line.lstrip())
    if indentation_length % 4 != 0:
        self.issues.append(f"Line {ln_num}: S002 Indentation is not a multiple of four")

def S003(self, ln_num: int, line: str):
    regex1 = re.compile("(.*)((;(\s)*#)|(;$))")
    regex2 = re.compile("#.*;")
    if regex1.search(line) and not regex2.search(line):
        self.issues.append(f"Line {ln_num}: S003 Unnecessary semicolon")

def S004(self, ln_num: int, line: str):
    regex = re.compile("(([^ ]{2})|(\s[^ ])|([^ ]\s))#")
    if regex.search(line):
        self.issues.append(f"Line {ln_num}: S004 At least two spaces before inline comments required")

def S005(self, ln_num: int, line: str):
    regex =  re.compile("#(.*)todo", flags=re.IGNORECASE)
    if regex.search(line):
        self.issues.append(f"Line {ln_num}: S005 TODO found")

def S006(self, ln_num: int, line: str):
    if self.code[ln_num-4:ln_num-1] == ['', '', ''] and line != "":
        self.issues.append(f"Line {ln_num}: S006 More than two blank lines used before this line")

Testcases:
""" Test case 1 """
print('What\'s your name?') # reading an input
name = input();
print(f'Hello, {name}');  # here is an obvious comment: this prints greeting with a name

very_big_number = 11_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000
print(very_big_number)

def some_fun():
    print('NO TODO HERE;;')
    pass; # Todo something
""" END """

""" Test Case 2 """
print('hello')
print('hello');
print('hello');;;
print('hello');  # hello
# hello hello hello;
greeting = 'hello;'
print('hello')  # ;
""" END """

""" Test Case 3 """
    print('hello')
    print('hello')  # TODO
    print('hello')  # TODO # TODO
    # todo
    # TODO just do it
    print('todo')
    print('TODO TODO')
    todo()
    todo = 'todo'
""" END """

""" Test Case 4 """
print("hello")

print("bye")

print("check")
""" END """

""" Test Case 5 """
print('hello!')
# just a comment
print('hello!')  #
print('hello!')  # hello

print('hello!') # hello
print('hello!')# hello
""" END """

Testcase 1 Expected Output:
Line 1: S004 At least two spaces before inline comment required
Line 2: S003 Unnecessary semicolon
Line 3: S001 Too long
Line 3: S003 Unnecessary semicolon
Line 6: S001 Too long
Line 11: S006 More than two blank lines used before this line
Line 13: S003 Unnecessary semicolon
Line 13: S004 At least two spaces before inline comment required
Line 13: S005 TODO found

I am aware my code, is not optimal and doesn't satisfy every edge case, but I want an idea, on how they parse the errors properly. I would like improvements or better ideas on how to parse for errors since I personally don't like my answers.


texts: C like Cpp code to do strncpy and copy a string to a buffer which is not long enough

texts:
The code works, but I guess it could be much better.

/*
DESCRIPTION
The strncpy() function is similar, except that at most n bytes of src
are copied. Warning: If there is no null byte among the first n bytes
of src, the string placed in dest will not be null-terminated.
NOTE
If the length of src is less than n, strncpy() pads the remainder of
dest with null bytes.
*/

char *strncpy(char *dest, const char *src, size_t n)
{
    size_t i = 0;
    char *d = dest;
    while ((i++ < n) && (*d++ = *src++));
    while (i++ < n)
    {
        *d++ = 0;
    }
    return dest;
}

/*
DESCRIPTION
The stlcpy() function copies the string pointed to by src.
to the buffer pointed to by dest.
The strings may not overlap.
NOTE
The destination string dest may *NOT* be
large enough to receive the copy, then the truncation happpens.
size_d is the size of destination buffer.
*/

char *strlcpy(char *dest, const char *src, size_t size_d)
{
    size_t i = 0;
    char * d = dest;
    while ((i < size_d) && (*d++ = *src++)) i++;
    if (i < size_d)//everything copied.
    {
        if (i < size_d -1)
        {
            *d = 0;
        }
        else
        {
            //truncating the last char.
            dest[i-1] = 0;
        }
    }
    else if (i == size_d)
    {
        //truncating the src, size_d - 1 bytes copied.
        dest[i-1] = 0;
    }
    else
    {
        //i > size_d, impossible.
    }
    return dest;
}


texts:
When writing an answer to another question here, I came across the problem of producing lists of integers having a certain total and only consisting of a certain number and an optional rest. So for total 21 and number 5 you would get List(5, 5, 5, 5, 1).

Solving the problem is obviously not hard. However, I have the feeling that it can be written more concisely than this:

def uniformList(sum: Int, num: Int): List[Int] = {
  val rest = sum % num
  List.fill(sum / num)(num) ::: (if (rest == 0) Nil else List(rest))
}

Of course I could inline the rest but I don't think it makes it more readable. I'm not looking for a performant solution but a more concise one. My feeling is that there should be a solution that is as easy to grasp as the concrete example I gave in the first paragraph.


texts: Telling the length of the highest common substring between 2 words

texts:
This takes two strings and returns the length of the largest common substring.

Example:

contando_sstring_igual("abcdef", "cdofhij")
# 2

Because the longest common substring = "cd", so it returns the length of it (2).

Here is the code:

def contando_sstring_igual(string1, string2):
    resposta = ""
    tamanho1 = len(string1)
    tamanho2 = len(string2)
    for i in range(tamanho1):
        for j in range(tamanho2):
            lcs_temp = 0
            igual = ''
            while i + lcs_temp < tamanho1 and j + lcs_temp < tamanho2 and string1[i + lcs_temp] == string2[j + lcs_temp]:
                igual += string2[j+lcs_temp]
                lcs_temp += 1
            if len(igual) > len(resposta):
                resposta = igual
    return len(resposta)

while True:
    a = input()
    b = input()
    if a is None or b is None:
        break
    else:
        print(contando_sstring_igual(a, b))

I need to make my code work significantly faster. It does the job right, but not fast enough. I need to avoid the timeout error I'm getting on the exercise and I'm not even close to figuring out how to do it, without the loop.


texts:
I need to sanitize some chars.  I have a solution that works but I am wondering if there is a better solution that may be faster or better or if I flat out should be approaching this differently?

function escapeStr(_str){
    if (/\"|\'|\%/g.test(_str)) {
        _str = _str.replace(/"/g, "%22");
        _str = _str.replace(/'/g, "%27");
        _str = _str.replace(/%/g, "%25");
    }
    return _str;
}

And vice versa:

function unescapeStr(_str){
    if (/\%22|\%27|\%25/g.test(_str)) {
        _str = _str.replace(/\%22/g, '"');
        _str = _str.replace(/\%27/g, "'");
        _str = _str.replace(/\%25/g, "%");
    }
    return _str;
}


texts:
I'm practicing to write c++11/14 and I implemented a RW lock. Does everything look ok?

class RWLock {
public:
void readLock() {
    std::unique_lock<std::mutex> lock(mutex);
    waitingReaders.wait(lock, [this]{!writer && queuedWriters == 0});
    ++readers;
}

void readUnlock() {
    std::unique_lock<std::mutex> lock(mutex);
    --readers;
    if (readers == 0 && queuedWriters > 0) {
        lock.unlock();
        waitingWriters.notify_one();
    }
}

void writeLock() {
    std::unique_lock<std::mutex> lock(mutex);
    ++queuedWriters;
    waitingWriters.wait(lock, [this]{!writer && readers == 0});
    --queuedWriters;
    writer = true;
}

void writeUnlock() {
    std::unique_lock<std::mutex> lock(mutex);

    if(queuedWriters > 0) {
        lock.unlock();
        waitingWriters.notify_one();
    } else {
        writer = false;
        lock.unlock();
        waitingReaders.notify_all();
    }
}

private:
std::mutex mutex;
std::condition_variable waitingReaders;
std::condition_variable waitingWriters;

int readers = 0;
int queuedWriters = 0;
bool writer = false;
};

In particular:
Do I really need to take a lock in my WriteUnlock() method? It looks like all I'm doing is unlock right away.

And is it recommended to perform a lock.unlock() before I do a notify_one or a notify_all ?

Does performing a condition_variable.wait(lock, lambda) where the lambda is true cause a performance loss? Like potentially in the readLock() method


texts: Wrapping certain elements in an array with an array with PHP

texts:
I have a function that's doing this correctly, but I feel as though this can be done (possibly) with minimal code, with recursion, but I'm just wracking my brain. Basically I have JSON that gets decoded to an array. What I want to do is turn this:

{
  "parentView": {
    "childViews": [
      {
        "type": "container-fluid",
        "childViews": [
          {
            "type": "row",
            "childViews": [
              {
                "type": "slider"
              },
              {
                "type": "slider"
              }
            ]
          }
        ]
      }
    ]
  }
}

Into this:

{
  "parentView": {
    "childViews": [
      {
        "type": "controller",
        "childViews": [
          {
            "type": "container-fluid",
            "childViews": [
              {
                "type": "controller",
                "childViews": [
                  {
                    "type": "row",
                    "childViews": [
                      {
                        "type": "controller",
                        "childViews": [
                          {
                            "type": "slider"
                          }
                        ]
                      },
                      {
                        "type": "controller",
                        "childViews": [
                          {
                            "type": "slider"
                          }
                        ]
                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
}

Here is the code I am using to make it work how I need. I am just looking for a cleaner method:

function createControls($parentView)
{
    $newArr = $parentView;

    foreach ($parentView as $k => $v) {
        $newArr[$k] = [
            'type' => 'control',
            'childViews' => $v
        ];

        if ($v['childViews']) {
            foreach ($v['childViews'] as $kk => $vv) {
                $newArr[$k]['childViews']['childViews'] = [
                    'type' => 'control',
                    'childViews' => $vv
                ];

                if ($vv['childViews']) {
                    foreach ($vv['childViews'] as $_k => $_v) {
                        $newArr[$k]['childViews']['childViews']['childViews']['childViews'][$_k] = [
                            'type' => 'control',
                            'childViews' => $_v
                        ];
                    }
                }
            }
        }
    }

    return $newArr;
}

$newArr = createControls($arr['parentView']['childViews']);
$arr['parentView']['childViews'] = $newArr;