texts:
I've implemented the K-Means clustering algorithm in Python2, and I wanted to know what remarks you guys could make regarding my code. I've included a small test set with 2D-vectors and 2 classes, but it works with higher dimensions and more classes. Here, it should sort all the elements starting with the same letters in the same classes (except ak, with is quite in between).

What I'm interested in:

Did I do something unpythonic?
Are there unclear or unnecessary parts?
What changes could drastically improve the code's performance?

from __future__ import print_function
from operator import add, sub
from _collections import defaultdict
import random as rd
import math

class Element:
    def __init__(self, idf, data, cls='ukn'):
        self.idf = idf
        self.data = data
        self.cls = cls

    def __str__(self):
        return '%s: %s -> %s' % (str(self.idf), str(self.data), str(self.cls))

    def eucl_dist_to(self, other):
        diff = map(sub, self.data, other.data)
        norm2 = math.sqrt(sum([math.pow(coord, 2) for coord in diff]))
        return norm2

def main():
    test_data_tuple = [('aa', 1, 7), ('ab', 1, 8), ('ac', 1, 9), ('ba', 2, 1), ('bb', 2, 3), ('ad', 2, 8), ('ae', 2, 9),
                   ('bc', 3, 2), ('bd', 3, 4), ('af', 3, 7), ('be', 4, 2), ('bf', 4, 3), ('ag', 4, 8),
                   ('bg', 5, 1), ('bh', 5, 3), ('ah', 5, 6), ('bi', 6, 2), ('bj', 6, 4), ('ai', 6, 6), ('aj', 6, 7),
                   ('bk', 7, 0), ('bl', 7, 2), ('bm', 7, 3), ('ak', 7, 5)]
    test_data_elt = list()
    for t in test_data_tuple:
        test_data_elt.append(Element(t[0], tuple(t[1:])))
    # test_data_elt.sort(key=lambda e: e.idf)
    results = k_means(test_data_elt, 2, 5)

def k_means(elts, nb_classes, nb_steps):
    k = nb_classes
    #init
    centroids = list()
    cls_content = defaultdict(list)
    for cls_nb in range(k):
        cls_name = 'class_'+str(cls_nb)
        centroids.append(Element(cls_name, rd.choice(elts).data, cls='centroid'))
        cls_content[cls_name] = list()

    for itr in range(nb_steps):
        # assign
        cls_content.clear()
        for elt in elts:
            min_dist = float('inf')
            for c in centroids:
                dist = c.eucl_dist_to(elt)
                if dist < min_dist:
                    min_dist = dist
                    best_class = c.idf
            cls_content[best_class].append(elt)
            elt.cls = best_class
        # adjust
        for c in centroids:
            elts_in = list(cls_content[c.idf])
            if len(elts_in) == 0:
                sum_elts_data = 0
            else:
                sum_elts_data = list(elts_in[0].data)
                for elt in elts_in[1:]:
                    sum_elts_data = map(add, sum_elts_data, elt.data)
                sum_elts_data[:] = [e / float(len(elts_in)) for e in sum_elts_data]
                c.data = tuple(sum_elts_data)
        print('\nIteration %d' % itr)
        for c in centroids:
            cls_name = c.idf
            print('\n'+str(c))
            for e in cls_content[cls_name]:
                print(e)
    return cls_content

if __name__ == '__main__':
    main()


texts:
KITTEH HAS IMPROOVD CODE SKILLS, AN NAO HAS BETTR CODE 4 U

This is an improvement of my original Haskell Lolcats Translator, and now features a function to do the translation (recursively?) using a map. I still have two let statements, which I know are frowned upon, but I couldn't get both the strToUpper and inline fmap working, so I opted for strToUpper.

Sample IO:

Enter your text to translate:
Let me have some cake on a plate please
LEMME HAS SUM CAEK ON PLAET PLZ

Teh Codez

import Data.Map
import Data.Strings

type Dictionary = [(String, String)]
lolcatDictionary =
    [
        (" A ", " "),
        ("CAN I", "I CAN"),
        ("MORE", "MOAR"),
        ("CHEESEBURGER", "CHEEZBURGER"),
        ("HAVE", "HAS"),
        ("HI", "HAI"),
        ("GHOST", "GOAST"),
        ("FEET", "FEAT"),
        ("MOAN", "MOWN"),
        ("CROWD", "CROUD"),
        ("NOTHING", "NUTHING"),
        ("MY", "MAI"),
        ("THEM", "DEM"),
        ("THESE", "THEES"),
        ("YOU", "YU"),
        ("LET ME", "LEMME"),
        ("KITE", "KIET"),
        ("CAT", "KAT"),
        ("CATS", "KATS"),
        ("KITTEN", "KITTEH"),
        ("KITTY", "KITTEH"),
        ("KITTENS", "KITTEHS"),
        ("LIKE", "LIEK"),
        ("COME", "COEM"),
        ("CAME", "CAEM"),
        ("BAKE", "BAEK"),
        ("PLATE", "PLAET"),
        ("SOME", "SUM"),
        ("CAKE", "CAEK"),
        ("PLEASE", "PLZ")
    ]

main :: IO ()
main = do
    putStrLn "Enter your text to translate:"
    input <- getLine
    let intermediate = strToUpper input
    let output = stringMapReplace lolcatDictionary intermediate
    putStrLn output

stringMapReplace :: Dictionary -> String -> String
stringMapReplace [] string = string
stringMapReplace (m:ms) s = stringMapReplace ms (strReplace (fst m) (snd m) s)


texts: Returning an array of integers with 1000 elements

texts:
Write a function that returns an array of integers with 1000 elements
  containing the values 1 to 1000 in random order. No number can be
  repeated or omitted.Your answer should show good programming style,
  technique and attention to accuracy and performance.

  Hint: use Random rnd=new Random() to create a new instance of the
  random number generator and rnd.Next(1,1000) to get a random integer
  value between 1 and 1000. No other .Net framework classes should be
  needed outside of the intrinsic data types (i.e. DO NOT use
  collections).

For that I have developed the following code:

import java.util.Random;

public class Domain {

public int[] randomIntArray(int size) {

    Random random = new Random();
    int intArrayHolder[] = new int[size];

    for (int i = 0; i < intArrayHolder.length; i++) {

        boolean isDuplicate = false;

        /*
         * because random.nextInt(int var) return between 0 and given-no and
         * we do not want 0. So size +1 and later in program, we do not
         * assign 0 to the intArrayHolder.
         */

        int randomNextInt = random.nextInt(size + 1);

        for (int j = 0; j < i; j++) {
            if (intArrayHolder[j] == randomNextInt) {

                isDuplicate = true;
                break;
            }
        }

        if ((!isDuplicate) && (randomNextInt != 0)) {
            intArrayHolder[i] = randomNextInt;
        } else {

            i--;

        }

    }

    return intArrayHolder;
}

}

JUnit test class:

import java.util.HashSet;
import java.util.Set;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class DomainJunitTest {

Domain domain = null;
int arraySize = 0;

@Before
public void initialize() throws Exception {
    domain = new Domain();
    arraySize = 1000;
}

@Test
public void randomIntArray_size_check() {

    int intArrayHolder[] = domain.randomIntArray(arraySize);

    Assert.assertEquals(arraySize, intArrayHolder.length);
}

@Test
public void randomIntArray_duplicate_value_check() throws Exception{

    int intArrayHolder[] = domain.randomIntArray(arraySize);

    Set<Integer> intSet = new HashSet<>();

    boolean isDublicate = false;

    for (int i = 0; i < intArrayHolder.length; i++) {

        if (intSet.contains(intArrayHolder[i])) {
            isDublicate=true;
        }else{
            intSet.add(intArrayHolder[i]);
        }
    }

    Assert.assertEquals(false, isDublicate);

}

@Test
public void randomIntArray_size_check_after_removing_dublicate() {

    int intArrayHolder[] = domain.randomIntArray(arraySize);

    Set<Integer> intSet = new HashSet<>();

    for (int i = 0; i < intArrayHolder.length; i++) {
        intSet.add(intArrayHolder[i]);
    }

    Assert.assertEquals(arraySize, intSet.size());

}

}

And I am being advised it is not good enough. Can someone point out where I went wrong?


texts: Project Euler problem #14 (longest Collatz chain) in Swift

texts:
This is my Swift code for finding the starting number, under one million, which produces the longest collatz chain.

var x = 1
var max = 0
var originalNum = 0

func collatzFunc(number: Int, originalNumber: Int){
    let oNum = originalNumber
    var num = number
    if num % 2 == 0{
        num = num/2
    } else {
        num = (3 * num) + 1
    }

    if num == 1{
        x += 1
    if max < x{
        max = x
        originalNum = oNum
    }
    return
    } else {
        x += 1
        collatzFunc(number: num, originalNumber: oNum)
    }
    }

for numbers in 1...1000000{
    x = 1
    collatzFunc(number: numbers, originalNumber: numbers)
}

print(originalNum)

This code is giving correct result but it's taking almost 5 seconds on my system to execute. I believe it can be done well under 1 sec. Where could I be wasting all that time?


texts:
This code takes a website and downloads all .jpg images in the webpage. It supports only websites that have the img element and src contains a .jpg link. The previous version can be found here

import random

import urllib.request

import requests

from bs4 import BeautifulSoup

def Download_Image_from_Web(url):
    # variables
    k = 0
    links_list = []
    # source code to BeatifulSoup
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text, "html.parser")
    # filtering
    for link in soup.findAll('img'):

        image_links = link.get('src')
        if '.jpg' in image_links:
            for i in image_links.split("\\n"):

                links_list.append(i.split())
    # send image links and download them
    while k <= (len(links_list) - 1):
        # create a random name
        name = random.randrange(1, 1000)
        fullName = str(name) + ".jpg"
        # download each link sperated
        lines = links_list[k][0]
        urllib.request.urlretrieve(lines, fullName)

        print(lines)
        print(fullName + '\n')

        k += 1
# choose a site that has the <img> element in its html source code with src tag
Download_Image_from_Web("https://pixabay.com")


texts: Callee specifying more spectific behaviour of the caller

texts:
I am working on a game in Unity/C#. I have a section of code that both feels like the best solution and code smell.
There are two objects. A player, and something interactable. The interactable object defines a method from an interface IInteractable with the signature void Interact(GameObject interactor). The player can call this method on any IInteractable object.
The player object implements an IHolder interface, and the object in question that implements IInteractable is of type Holdable.
When the player calls Interact() on the Holdable, the Holdable checks if the caller implements IHolder by using a generic method call. If it succeeds then it makes the holder call a more specific method on it's own instance.
public void Interact(GameObject interactor)
{
    if (interactor.TryGetComponent<IHolder>(out this.holder))
    {
        this.holder.Hold(this);
    }
}

It doesn't feel right to me that the object to be held is commanding the holder to hold it.
Would a more appropriate solution be to have Interact() return an Action<GameObject> that the player can decide to .Invoke()? Not sure if having the caller call the callee's suggestion to call the caller's method with the callee as an argument is actually better and not just hiding the issue with complexity.
Edit:
Using this refactor as the solution:
public Action GetInteraction(GameObject interactor)
{
    IHolder potentialHolder;
    if (interactor.TryGetComponent<IHolder>(out potentialHolder))
    {
        return () => potentialHolder.Hold(this);
    }

    return null;
}


texts:
This is for a class assignment. The objective is to write a program that will take in user input for employee information and print the wage based on hours worked.

Please review my code.

#include <ctime>
#include <iostream>

using namespace std;

int GetSalary(int,int,int,int);
int GetYearsOfService(int);

int main()
{
    int employeeId, hoursWorked, yearJoined, fullTime;

    cout << "Employee ID: ";
    cin >> employeeId;

    cout << "Hours Worked: ";
    cin >> hoursWorked;

    cout << "Year Joined: ";
    cin >> yearJoined;

    cout << "FullTime Status (0 for no, 1 for yes): ";
    cin >> fullTime;

    double salary = GetSalary(employeeId, hoursWorked, yearJoined, fullTime);
    double taxes = salary * 0.15;

    cout << endl << "Empolyee ID: " << employeeId << endl << "\tFull time?: ";

    if (fullTime == 0)
        cout << "No";
    else
        cout << "Yes";

    cout << endl << "\tHours worked: " << hoursWorked << endl << "\tWages (after tax) for the month: $"
         << salary - taxes << endl << "\tAmount withheld for tax: $" << taxes;

    return 0;
}

int GetSalary(int employeeId, int hoursWorked, int yearJoined, int fullTime) {
    double hourlyWage = 14;

    //Get the hourly wage
    int wage = 14;

    if( wage>=50 && wage < 100){
        wage += 1.25;
    }else if( wage < 160){
        wage += 2.0;
    }else{
        wage += 3.0;
    }

    double baseSalary = hourlyWage * hoursWorked;
    int yearsOfService = GetYearsOfService(yearJoined);

    //Check if any additional benefits/bonusses are to be paid
    if (fullTime == 1)
    {
        baseSalary += (35 *yearsOfService);
        baseSalary += 300;
    }
    else {
        if (yearsOfService > 5)
            baseSalary += (35 * yearsOfService);
    }
    return baseSalary;
}

int GetYearsOfService(int yearJoined) {
    time_t curTime = time(NULL);

    int elapsed = curTime / (365 * 24 * 60 * 60);

    return 1970 + elapsed - yearJoined;
}


texts:
This snippet allows to up and down TCP server via Flask endpoints. I'm seriously concerned about global variables here. And asking for review this code.

The main idea is to be able to up/down TCP server by request to the Flask web service, we need it for testing purposes.

import socket

from flask import Flask
import threading

# tcp server
TCP_IP = '0.0.0.0'
TCP_PORT = 5001
BUFFER_SIZE = 20

# flask app
app = Flask(__name__)

light_on = False
thread_on = False
thread = False

def launchServer():
    def run():
        global light_on
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.bind((TCP_IP, TCP_PORT))
        s.listen(1)
        print("run", flush=True)

        print('waiting for connection', flush=True)
        CONN, addr = s.accept()
        while light_on:
            print('Connection address:', addr, flush=True)
            # Logic Here

        CONN.shutdown(socket.SHUT_RDWR)
        CONN.close()

    global thread
    if thread_on:
        thread = threading.Thread(target=run)
        thread.start()

@app.route('/start')
def start():
    print('starting', flush=True)
    global light_on
    global thread_on
    light_on = True
    thread_on = True
    launchServer()
    return "Started"

@app.route('/stop')
def stop():
    global light_on
    global thread
    global thread_on
    light_on = False
    thread_on = False
    thread.do_run = False
    thread.join()
    return "Stopped"

if __name__ == "__main__":
    app.run(host='0.0.0.0', debug=True, port=5000, use_reloader=False, threaded=True)

Is there a best way for it, or can I avoid global variables, and be sure that the code thread safe?


texts: Handling game states for an online RPG game

texts:
I'm writing an ORPG. The code below is client-side.

I have a main thread looping in Game::Run:

Game::~Game()
{
    PopAllStates();
}

void Game::Run()
{
    sf::Event Event;

    while(Window->isOpen())
    {
        if(LoadQueueMutex.try_lock())
        {
            while(!LoadQueue.empty())
            {
                LoadQueue.front().first->Load(LoadQueue.front().second);
                LoadQueue.pop();
            }
            LoadQueueMutex.unlock();
        }
        while(Window->pollEvent(Event))
        {
            StateStack.top()->HandleEvent(Event);
        }
        Window->clear();
        StateStack.top()->Draw();
        Window->display();
        StateStack.top()->Update();
    }
}

void Game::AddToLoadQueue(Loadable* pLoadable, WorldPacket Argv)
{
    boost::mutex::scoped_lock lock(LoadQueueMutex);
    LoadQueue.push(std::make_pair(pLoadable, Argv));
}

void Game::PushState(GameState* pState)
{
    StateStack.push(pState);
}

void Game::PopState()
{
    if(!StateStack.empty())
    {
        delete StateStack.top();
        StateStack.pop();
    }
}

void Game::PopAllStates()
{
    while(!StateStack.empty())
    {
        PopState();
    }
}

And another thread waiting for a packet:

void WorldSession::Start()
{
    Packet = WorldPacket((uint16)MSG_NULL);

    boost::asio::async_read(Socket,
        boost::asio::buffer(Packet.GetDataWithHeader(), WorldPacket::HEADER_SIZE),
        boost::bind(&WorldSession::HandleHeader, this, boost::asio::placeholders::error));
}

When the packet "arrives", this is usually done because OpenGL breaks if loaded from another thread:

void WorldSession::HandleSomeCoolOpcode()
{
    //...
    sGame->AddToLoadQueue(pSomethingCool, Packet);
}

When the main thread loads the Loadable*, it will usually mess with the state stack:

void World::Load(WorldPacket Argv)
{
    //...
    sGame->PopState();
    sGame->PushState(this);
}

Is there any way to improve this?


texts: Extract Pages from PDF based on search in python

texts:
Everything is working fine except timing.
it takes lot time for my file containing 1000 pages and having 100 pages of interest.

import re
from PyPDF2 import PdfFileReader, PdfFileWriter
import glob, os

# find pages
def  findText(f, slist):
    file = open(f, 'rb')
    pdfDoc = PdfFileReader(file)
    pages = []
    for i in range(pdfDoc.getNumPages()):
        content = pdfDoc.getPage(i).extractText().lower()
        for s in slist:
            if re.search(s.lower(), content) is not None:
                if i not in pages:
                    pages.append(i)
    return pages

#extract pages
def extractPage(f, fOut, pages):
    file = open(f, 'rb')
    output = PdfFileWriter()
    pdfOne = PdfFileReader(file)
    for i in pages:
        output.addPage(pdfOne.getPage(i))
    outputStream = open(fOut, "wb")
    output.write(outputStream)
    outputStream.close()
    return

os.chdir(r"path\to\mydir")
for pdfFile in glob.glob("*.pdf"):
    print(pdfFile)
    outPdfFile = pdfFile.replace(".pdf","_searched_extracted.pdf")
    stringList = ["string1", "string2"]
    extractPage(pdfFile, outPdfFile, findText(pdfFile, stringList))

Updated code after suggestions is at:

https://gist.github.com/pra007/099f10b07be5b7126a36438c67ad7a1f


texts: Optimize a parallelized program to optimize train schedules

texts:
This loops through a vector of vector of A and adds a smaller array to a bigger one at a specified position+random shift.  Then it is checked if it is a better solution, and if yes, it is stored, else it is discarded.  I have already parallelized it.

Can this be improved to run faster?

I am not sure if a vector<vector<struct>> is a good idea, or maybe there is a better memory management to use better cache effects.  The struct is currently global and since it is only readable by the threads all threads use the same instance.

I am using C++11 threads.

Description of what the program does:

We have a big array, rand_val, and we have many small arrays, Leistungskurve. We can add these  array to rand_val at a fixed position + random shift. We want to find a valid position for each array so the max element in rand_val is minimized. In the array, rand is stated which position we have chosen.

#include <iostream>
#include <string>
#include <vector>
#include <time.h>
#include <cmath>
#include <iterator>

#include <algorithm>

#include <fstream>
#include <stdlib.h>
#include <sstream>

#include <stdlib.h>

#include <thread>
#include <random>

using namespace std;

struct Teilstrecke {
  int StreckenNr;
  int Fahrzeit;
  int Haltezeit;
  int FruehesteAbfahrt;
  int SpaetesteAbfahrt;
  int Abfahrtsintervall;
  double *Leistungskurve;
};

struct Zug {
  int ZugNr;
  int AnzahlStrecken;
  vector<Teilstrecke> Teilstrecken;
};

vector<Zug> Zuege;

int Planungsintervall;
int AnzahlZuege;
int AnzahlSchattenzuege;

inline double maxArray(double *arr, int size)
{
  double max = 0;
  int pos = 0;
  for (int i = 0; i < size; i++)
  {
    if (arr[i] > max)
    {
        max = arr[i];
        pos = i;
    }
  }
  return pos;
}

inline void addArray(double *arr1, double *arr2, int size2, int pos)
{
  for (int i = 0; i < size2; i++)
  {
    arr1[pos+i] += arr2[i];
  }
}

inline void addArray(double *arr1, Teilstrecke ts, int shift)
{
    addArray(arr1, ts.Leistungskurve, ts.Fahrzeit*600+1, (ts.FruehesteAbfahrt+shift)*600);
}

inline void randomSolution(int *rand, double *rand_val);

inline int randomNumber(int low, int high) // has to be replaced to c++11 random
{
  return rand() % (high - low + 1) + low;
}

void wrapper()
{
  int size = Planungsintervall*600+1;
  int *rand = new int[AnzahlSchattenzuege];
  fill_n(rand, AnzahlSchattenzuege, 0);
  double *rand_val = new double[size];
  fill_n(rand_val, size, 0);
  int max_iter = 1000000;

  double best_max = 1e20;
  int *rand_best = new int[AnzahlSchattenzuege];
  for (int i = 0; i < max_iter; i++)
  {
    randomSolution(rand, rand_val);
    double max = maxArray(rand_val, size);
    //cout << max << '\n';
    if (max < best_max)
    {
      best_max = max;
      memcpy(rand_best, rand, sizeof(int)*AnzahlSchattenzuege);
    }
    fill_n(rand, AnzahlSchattenzuege, 0);
    fill_n(rand_val, size, 0);
  }
  cout << best_max <<  ' ' << '\n';
}

inline void randomSolution(int *rand, double *rand_val)
{
  int pos2 = 0;
  for (int i = 0; i < AnzahlZuege; i++)
  {
    for (int j = 0; j < Zuege.at(i).AnzahlStrecken; j++)
    {
      Teilstrecke ts = Zuege.at(i).Teilstrecken.at(j);
      int k = randomNumber(0, ts.Abfahrtsintervall);
      rand[pos2+k] = 1;
      addArray(rand_val, ts, k);
      pos2 += ts.Abfahrtsintervall + 1;
    }
  }
}

void read_input(char *read_file);

int main(int argc, char** argv)
{
  read_input((char*)argv[1]);
  vector<thread> threads;
  for (int i = 0; i < 7; i++)
  {
    threads.push_back(thread(wrapper));
  }
  wrapper();
  for (int i = 0; i < 7; i++)
  {
    threads.at(i).join();
  }
}

Profiling

It seems that all work is done in addArray.


texts: Lightweight, modular Discord bot - tips and feedback on the code?

texts:
The full project is up on GitHub. The codebase is super small as it stands.

I'm brand new to reactive programming and Spring, and would mostly like insight on those two things. Asynchronous programming is also one of my weak points, because I'm really used to synchronous program structure - hence the need for help with reactive programming.

Here's a few snippets to start off with, for my specific concerns:

@Repository
public interface GuildMetaRepository extends CrudRepository<GuildMeta, Long> {
    ...
    @Override
    @Cacheable(value = "guilds", key = "#p0")
    Optional<GuildMeta> findById(Long id);
    ...
    @Override
    @CacheEvict(value = "guilds", key = "#p0.id")
    void delete(GuildMeta guild);
}

Spring caching for Repository implementations confuses me a little - is this working as I expect? Should I be using @CachePut in place of @Cacheable?

class CommandRegistry {
    ...
    CommandRegistry() throws ReflectiveOperationException {
        ...
        /* not shown: find all Command implementations with Reflections */
        ...
        // Construct an instance of each module
        for (Class<? extends Command> module : modules) {
            instantiated.add(module.newInstance());
        }
    }
    ...
}

You might need the full context of the command package for this one. Basically, Command is the abstract class that all my command modules extend from, and it has an instance variable for the command name that subclasses call super(name, ...) to identify themselves with. Since it's an instance variable, though, I need to keep an instance of each module available in a List<Command> to check against command names in chat.

That probably didn't make it much clearer, but I did my best. Like I said, there's more context to be had here. The general design pattern I have here is sub-par in my opinion, and I don't really have any ideas on how to fix it. There have definitely been some improvements over the first iteration, though; that was far messier.

I'd love to get some feedback here, whether it's on the snippets or on other code in the project - if you see a problem, hit me with it. Pull requests are always wide open as well if you feel like contributing. Thanks!


texts: How can this VHDL code for a 64-bit timer be improved to use less resources?

texts:
I have code for a 64-bit timer register which can take in a 32-bit slice and depending on the inputs, place the slice in the high side or the low side, or increment the counter.
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.NUMERIC_STD.ALL;

entity CSR_TIMER is
    Port ( clk : in STD_LOGIC;
           reset: in STD_LOGIC := '0';
           DATA_IN : in STD_LOGIC_VECTOR (31 downto 0);
           EN_WRITE_LOW : in STD_LOGIC;
           EN_WRITE_HIGH : in STD_LOGIC;
           DATA_LOW_OUT : out STD_LOGIC_VECTOR (31 downto 0);
           DATA_HIGH_OUT : out STD_LOGIC_VECTOR (31 downto 0));
end CSR_TIMER;

architecture Behavioral of CSR_TIMER is
    signal clock,clock_next : unsigned(63 downto 0) := x"0000000000000000";
begin
    clock_next <=
    x"0000000000000000"                     when (reset = '1') else
    clock(63 downto 32) & unsigned(DATA_IN) when (EN_WRITE_LOW = '1') else
    unsigned(DATA_IN) & clock(31 downto 0)  when (EN_WRITE_HIGH = '1') else
    clock+1;

    DATA_LOW_OUT <=
    std_logic_vector(clock(31 downto 0));

    DATA_HIGH_OUT <=
    std_logic_vector(clock(63 downto 32));

    process(clk)
    begin
        if(rising_edge(clk)) then
            clock<=clock_next;
        end if;
    end process;

end Behavioral;

The trouble that I'm having is that the timer takes up too many physical resources, and I'm looking to shrink it down. This is for a RISC-V Processor where the ISA specifies that a proper processor has 32 of these timers, which is 2kb of on-board memory, and is not friendly to any FPGA. The Data_Low_out and data_high_out are connected to a mux, where they are treated as separate registers at different addresses.
How can I optimize this timer ( or a group of 32 timers ) to reduce the physical resource usage? This is synthesized using Vivado 2020.1.


texts: Delegating to a lazily loaded object in Ruby

texts:
I have an API that takes a class as a configuration parameter, but I don't want to load the class (I'm using Rails) at the time that I'm setting up the API. I figured I could get around this by passing it an object that acts like the class in every way (by delegating to it) but doesn't actually reference the class, and thus load the class. until it us used.

This is what it expects:

MyAPI.configure.model = UserModel

But I'd like to give it something like:

MyAPI.configure.model = ->{ UserModel }

This is what I have. It works as well as expected but I have a feeling I take better advantage of Ruby's features and/or the standard library.

def lazy_delegate(&block)

  delegate = BasicObject.new

  def delegate.method_missing(message, *args)
    @target ||= @target_block.call
    @target.send message, *args
  end

  def delegate.__target__=(block)
    @target_block = block
  end

  delegate.__target__ = block

  delegate
end

I'm using this like:

MyAPI.configure.model = lazy_delegate{ UserModel }

Is there a better way to accomplish this? Does Ruby's standard library have anything that would make this cleaner?


texts:
The application I am developing with has many input fields that interact with one another via the onchange event.
When developing started, the goal was to create a framework that makes it easy to define event actions for the input fields and keep the action functions together.

The back then the following was implemented:

<input type='text' class='process' data-fn='function1;function2'>

And in Javascript using jQuery (leaving out security and validation checks here):

$("body").on("change", ".process", function(e){
     process($(this).attr("data-fn"),$(this),e);
});

function process(functionString, caller, event){
    var functions = functionString.split(";");
    for (var index = 0; index < functions.length; ++index) {
        switch (functions[index]){
            case "function1":
                    //do something
               break;
            case "function2":
                    //do something
               break;
        }
    }
}

The amount of needed functions was highly underestimated. The switch now has 110 cases.
The advantage of the algorithm as it is now is that I can make the break optional, creating functions with multiple "entrances".
The disadvantage is no local variable scope inside each case.

Is there a huge problem that I don't see with this approach (like switch performance etc.)?

I am interested if this is bad coding or just an interesting approach to the problem.

Additionally, does a software design pattern exist, that is defined to do such functionality?

I guess a better approach would have been the following, but now that it is that way..

function process(functionString, caller, event){
    var functions = functionString.split(";");
    for (var index = 0; index < functions.length; ++index) {
        if (functionObj.hasOwnProperty(functions[index]){
            functionObj[functions[index]](caller,event);
        }
    }
}

var functionObj = {
    function1: function (caller, event){
        //do something;
    },
    function2: function (caller, event){
        //do something;
    }
}


texts: Instantiating icons, labels, and text fields for a contact form

texts:
While teaching myself Wx using this GridSizerTutorial page, I suddenly realized that there was a construct in Python that would let me considerably shorten the initialization code below. The three lines at the top replace the twelve commented lines below. (Three statements now split over six lines for greater clarity).

The question, should one do things this way? Is it Pythonic and DRY, or is it obscuring the function? I've encountered similar initializations in the past where the number groups of similar objects being initialized is considerably greater than four. The objects may later diverge, following "customization" calls to their setter methods.

inputOneIco,inputTwoIco,inputThreeIco,inputFourIco = [
    wx.StaticBitmap(self.panel, wx.ID_ANY, bmp) for _ in range(4) ]
labelOne, labelTwo, labelThree, labelFour          = [
    wx.StaticText(  self.panel, wx.ID_ANY, txt ) for txt in ('Name','Address','Email','Phone') ]
inputTxtOne,inputTxtTwo,inputTxtThree,inputTxtFour = [
    wx.TextCtrl(    self.panel, wx.ID_ANY, '') for _ in range(4) ]

#inputOneIco = wx.StaticBitmap(self.panel, wx.ID_ANY, bmp)
#labelOne = wx.StaticText(self.panel, wx.ID_ANY, 'Name')
#inputTxtOne = wx.TextCtrl(self.panel, wx.ID_ANY, '')

#inputTwoIco = wx.StaticBitmap(self.panel, wx.ID_ANY, bmp)
#labelTwo = wx.StaticText(self.panel, wx.ID_ANY, 'Address')
#inputTxtTwo = wx.TextCtrl(self.panel, wx.ID_ANY,'')

#inputThreeIco = wx.StaticBitmap(self.panel, wx.ID_ANY, bmp)
#labelThree = wx.StaticText(self.panel, wx.ID_ANY, 'Email')
#inputTxtThree = wx.TextCtrl(self.panel, wx.ID_ANY, '')

#inputFourIco = wx.StaticBitmap(self.panel, wx.ID_ANY, bmp)
#labelFour = wx.StaticText(self.panel, wx.ID_ANY, 'Phone')
#inputTxtFour = wx.TextCtrl(self.panel, wx.ID_ANY, '')


texts:
This is a small test to try and add a copy of a containing class into a vector. To me, it looks very ugly. I hate the fact I need to write a constructor based off of a pointer in order to add the class to a vector. Is there a better way to organize this?

#include <string>
#include <sstream>
#include <vector>
#include <iostream>

Support function (not the main point of the question):

template <class T>
std::string to_string(const T& number) {
    if (std::is_arithmetic<T>::value) {
        std::stringstream ss;
        ss << number;
        return ss.str();
    } // else
    return "to_string not implemented"; // I could throw here...
}

Main code:

class Return_Self_Test {
private:
    std::string name;

public:
    Return_Self_Test(const std::string& name_in) : name(name_in) { }

    Return_Self_Test(Return_Self_Test* rst) : name(rst->name) {
    }

    Return_Self_Test(const Return_Self_Test &obj) : name(obj.name) {
    }

    void output() const {
        std::cout << "name: " << name;
    }

    std::vector<Return_Self_Test> get_in_vector() const {
        std::vector<Return_Self_Test> rst;
        rst.emplace_back(Return_Self_Test("new one 1"));
        rst.emplace_back(*this);
        rst.emplace_back(Return_Self_Test("new one 2"));
        return rst;
    }
};

void return_self_test() {
    Return_Self_Test rst_a("Original");

    auto a_vect = rst_a.get_in_vector();
    for (size_t i = 0; i < a_vect.size(); i++) {
        std::cout << to_string(i) + ": ";
        a_vect.at(i).output();
    }
}

return_self_test() gets called from main;

Any comments welcome!


texts:
Basically, I'm trying to find all active people with a roleId of 3 (analyst id). But I want to exclude ids that were created as test analysts, i.e. "130", "252", etc. I see that I'm repeating the part to exclude the test ids. Also, I'm repeating the part about the roleId. Isn't there a way to optimize it? My query works fine, but I'm trying to optimize to make it more DRY.

Here's what my code looks like (I've labeled where I think the code can be optimized):

from people in xDoc.Descendants("People")
where (int?) Convert.ToInt16(people.Element("active").Value) == 1 &&
    (int?)Convert.ToInt16(people.Element("id").Value) != 130 &&  // <-- to optimize
    (int?)Convert.ToInt16(people.Element("id").Value) != 252 &&  // <-- to optimize
    (int?)Convert.ToInt16(people.Element("id").Value) != 264 &&  // <-- to optimize
    (int?)Convert.ToInt16(people.Element("id").Value) != 302 &&  // <-- to optimize
    people.Descendants("roleIds").Descendants("int")
        .Select(p => (int?)Convert.ToInt16(p.Value)).FirstOrDefault() == 3  // <-- to optimize
select new PeopleClass
{
    ResAnId = (int) Convert.ToInt16(people.Element("id").Value),
    DpInit = (string)people.Element("clientCode").Value,
    ResAnFName = (string)people.Element("firstName").Value,
    ResAnLName = (string)people.Element("lastName").Value,
    ResAnName = String.Format("{0} {1}", (string)people.Element("firstName").Value,
        (string)people.Element("lastName").Value),
    RoleId = people.Descendants("roleIds").Descendants("int")
        .Select(p => (int?) Convert.ToInt16(p.Value)).FirstOrDefault(),  // <-- to optimize
    DivisionId = (int?) Convert.ToInt16(people.Element("divisionId").Value)
}).ToList();

If you're interested, here's my XML feed:

<People>
  <id>269</id>
  <dummy>false</dummy>
  <firstName>Steve</firstName>
  <lastName>Jobs</lastName>
  <initial></initial>
  <title>CEO</title>
  <active>1</active>
  <analystPosition></analystPosition>
  <clientCode>SJ</clientCode>
  <clientCode2></clientCode2>
  <divisionId>2</divisionId>
  <updatedBy>245</updatedBy>
  <associates>
    <Associate>
      <analystId>269</analystId>
      <associateId>257</associateId>
      <rank>0</rank>
    </Associate>
  </associates>
  <roleIds>
    <int>3</int>
    <int>4</int>
    <int>13</int>
  </roleIds>
</People>


texts: Change random list of numbers into all 5's using simple evolution simulation

texts:
This is supposed to be an evolutionary algorithmic program, and I'm not sure if it does what it's supposed to do.

It is supposed to take a random list of numbers (containing at least one 5), and over many generations, increase the probability of 5's reproducing, thus having the 5's eventually taking over the output.

Is this an accurate representation of an evolutionary algorithm? If so, how can I make it better, and if not, how can I make it one?

import random as r
import os
import sys
import time
from subprocess import call
#call('color a', shell=True)
class Entity(object):
    def __init__(self, number):
        self.number = number
        self.chance = 10
        self.age = 0
class Fitness(object):
    def __init__(self, population):
        self.population = population

    def StartPopulation(self, pop, entities):
        for x in range(pop):
            entity = Entity(r.randint(1, 10))
            entities.append(entity)

    def FitnessMethod(self, entities):

        for x in entities:
            if x.number == 5:
                x.chance += 10
            else:
                x.chance += 0

            if x.chance > 100:
                x.chance = 100

            else:
                x.chance += 0

    def Reproduce(self,entities):
        x = entities[r.randint(0, (len(entities) - 1))]
        if r.randint(0, 100) < x.chance:
            random_children = r.randint(1, 3)
            for a in range(random_children):
                entity = Entity(x.number)
                entity.chance = x.chance
                entities.append(entity)
            x.age += 1

    def Aging(self, entities):
        for x in entities:
            if x.age >= 1:
                entities.remove(x)

pop = r.randint(5, 10)
entities = []
Fitness = Fitness(pop)
Fitness.StartPopulation(pop, entities)
for x in entities:
    print x.number, x.chance
print "~~~~~~~~~~~~~\n"
raw_input()

for x in range(200):
    Fitness.FitnessMethod(entities)
    Fitness.Reproduce(entities)
    Fitness.Aging(entities)
    for x in entities:
        print x.number, x.age, x.chance
    print "Generation_Mutation_Complete"
raw_input()


texts:
I made a small Poker program with C but I believe I could've written it better.

Full source on bitbucket.org

int checkhand (struct Card_s * hand)
{
    assert (hand) ;
    //struct Card_s *suithand = sorthand(hand, true); // Unnecessary
    struct Card_s *sorted = sorthand(hand, false);

    /* check for flushes */
    {
        bool flushsuit = false;
        int suits[4] = { [0 ... 3] = 0 };
        for (int i = 0; i < MAXHAND; ++i)
        {
            switch (hand[i].nSuit)
            {
                case spades:    suits[0]++; break;
                case clubs: suits[1]++; break;
                case hearts:    suits[2]++; break;
                case diamonds:  suits[3]++; break;
            }
        }
        for ( int f = 0 ; f < 4 ; ++f )
        {
            if (suits[f] == 5) { flushsuit = true ; } /* found a flush */
        }

        if ( flushsuit )
        {
            if ( sorted[0].nType == (sorted[1].nType-1) && sorted[1].nType == (sorted[2].nType-1) && sorted[2].nType == (sorted[3].nType-1) && sorted[3].nType == (sorted[4].nType-1) )
            {
                if ( sorted[4].nType == ace ) return 10; /* found royal flush */
                else return 9; /* found straight flush */
            }
            return 6; /* it was a normal flush */
        }
    }

    /* check for 4 of a kind */
    {
        int type [MAXTYPES ] = { [0 ... 12] = 0 }, *types ;
        types = count_types( sorted, type ) ;
        for ( int f = 0 ; f < MAXTYPES ; ++f )
        {
            if ( types[f] == 4 ) { return 8 ; } /* found 4 same types in a row */
        }
    }

    /* check for full house */
    {
        bool threeKind = false, Twopair = false ;
        int type[ MAXTYPES ] = { [0 ... 12] = 0 }, *types ;

        types = count_types( sorted, type ) ;
        for ( int f = 0 ; f < MAXTYPES ; ++f )
        {
            if ( types[f] == 3 ) { threeKind = true ; } /* found three of a kind */
        }

        int pair[MAXTYPES] = { [0 ... 12] = 0 }, *pairs ;
        pairs = count_types( sorted, pair );
        for ( int f = 0 ; f < MAXTYPES ; ++f )
        {
            if ( pairs[f] == 2 ) { Twopair = true ; } /* found normal pair */
        }
        if ( threeKind && Twopair ) return 7; /* found full house */
    }

    if ( sorted[0].nType == (sorted[1].nType-1) && sorted[1].nType == (sorted[2].nType-1) && sorted[2].nType == (sorted[3].nType-1) && sorted[3].nType == (sorted[4].nType-1) )
    {
        return 5; /* found straight */
    }

    /* check for three of a kind */
    {
        int type[ MAXTYPES ] = { [0 ... 12] = 0 }, *types ;
        types = count_types( sorted, type ) ;
        for ( int f = 0 ; f < MAXTYPES ; ++f )
        {
            if ( types[f] == 3 ) { return 4 ; } /* found three of a kind */
        }
    }

    /* check for two pair */
    {
        int type[MAXTYPES] = { [0 ... 12] = 0 }, *types ;
        types = count_types( sorted, type );
        int isTwoPair = 0 ;
        for ( int f = 0 ; f < MAXTYPES ; ++f )
        {
            if (types[f] == 2) isTwoPair++;
            if (isTwoPair == 2) { return 3 ; } /* found two pair */
        }
    }

    /* check for normal pair */
    {
        int type[MAXTYPES] = { [0 ... 12] = 0 }, *types ;
        types = count_types( sorted, type ) ;
        for ( int f = 0 ; f < MAXTYPES ; ++f )
        {
            if ( types[f] == 2 ) { return 2; } /* found normal pair */
        }
    }
    return 1 ; /* player only has a high card value */
}


texts:
I am new to programming and I am trying to make a simple unit converter in python. I want to convert units within the metric system and metric to imperial and vice-versa. I have started with this code and I found this method is slow and in-efficient, How can I code this more efficiently?

import math
import time
"""Unit Converter"""
#Welcome and variable setting
print ("Welcome to Sam's Unit Converter")
cat = raw_input ("Which category would you like to convert? we support length(l) and Weight(w):  ")
if cat == ("l"):
unit1 = raw_input ("Which unit would you like to convert from: ")
unit2 = raw_input ("Which unit would you like to convert to: ")
num1 = raw_input ("Enter your value: " )

    ##Calculations

if unit1 == "cm" and unit2 == "m":
    ans = float(num1)/100
elif unit1 == "mm" and unit2 == "cm":
    ans = float(num1)/10
elif unit1 == "m" and unit2 == "cm":
    ans = float(num1)*100
elif unit1 == "cm" and unit2 == "mm":
    ans = float(num1)*10
elif unit1 == "mm" and unit2 == "m":
    ans = float(num1)/1000
elif unit1 == "m" and unit2 == "mm":
    ans = float(num1)*1000
elif unit1 == "km" and unit2 == "m":
    ans = float(num1)*1000
elif unit1 == "m" and unit2 == "km":
    ans = float(num1)/1000
elif unit1 == "mm" and unit2 == "km":
    ans = float(num1)/1000000


texts:
To put it simply, I'm making a hangman game and it works as it is, it correctly outputs what I want it to, and I have no problem with submitting it now. I only wish to make it more efficient, and I doubt it's at max efficiency as it is. So here it is.
"""
This code runs a hangman game for the user.
"""
# This function gets the user's guess for the letter and determines if its correct
def get_guess():
    global user_guess
    while True:
        user_guess = input("Guess a letter: ")
        if user_guess.isnumeric():
            print("That is not a letter!")
        elif len(user_guess) > 1:
            print("You can only enter one letter!")
            continue
        elif user_guess.islower() == False:
            print("Remember to enter a lowercase letter, but I'll swap it for you this time :)")
            return user_guess.lower()
        else:
            return user_guess

# This function updates the dashes that the code outputs, this function displays the progress
# of the user's guess for the secret word
def update_dashes(secret_word, dashes, user_guess):
    for i in range(len(secret_word)):
        if secret_word[i] == user_guess:
            dashes  = dashes[:i] + user_guess + dashes[i + 1:]
            return dashes

# This imports the random function
import random
# This list defines what words the random.choice method can select from for hangman
words = ["jazz", "hello", "bird", "birds", "peanut", "butter", "cake", "hallway"]
# This secret_word defines a random word from the list for the user to guess
secret_word = random.choice(words)
# This variable defines the progress meter of dashes based on the length of the random word
dashes = "-" * len(secret_word)
# This variable defines the number of tries the user starts with and has left
tries = 10
# This while statement updates the user's progress for guessing the word
while tries > 0 and dashes != secret_word:
    print(dashes)
    guess = get_guess()
    dashes = update_dashes(secret_word, dashes, user_guess)
    if guess in secret_word:
        print("That letter is in the secret word!")
    else:
        print("That letter is not in the secret word.")
        tries = tries - 1
         print("You have " + str(tries) + " tries left.")

# This if statement determines if the user has won or lost based on their tries or if the
# progress meter is full
if tries == 0:
    print("You ran out of guesses, the word was " + secret_word + ".")
    print("--------------------------YOU LOSE----------------------------")
elif dashes == secret_word:
    print(dashes)
    print("You guessed correctly, the word was " + secret_word + "!")
    print("--------------------------YOU WIN!----------------------------")


texts: Collect subsequences of consecutive integers

texts:
I've written a function to split a list into several lists with consecutive integers, e.g.:

extract_subsequences([1,2,3,7,8,9])

  [[1, 2, 3], [7, 8, 9]]

extract_subsequences([1,2,3])

  [[1, 2, 3]]

extract_subsequences([1,2,3, 10])

  [[1, 2, 3], [10]]

extract_subsequences([1,2, 4,5, 8,9])

  [[1, 2], [4, 5], [8, 9]]

This is the code that I came up with:

import numpy as np

def extract_subsequences(seq):
    def split_sequence(seq):
            for i in np.arange(1, len(seq)):
                if seq[i] != seq[i - 1] + 1:
                    break

            if i < len(seq) - 1:
                return seq[:i], seq[i:]
            else:
                if seq[-1] == seq[-2] + 1:
                    return seq, []
                else:
                    return seq[:-1], [seq[-1]]

    res = []
    last = seq
    while len(last) > 1:
        first, last = split_sequence(last)
        res.append(first)

    if len(last) == 1:
        res.append(last)

    return res

Can someone help me improve this code? It's kind of difficult to read with all the indices and special cases, and for the same reasons it was also quite difficult to write. I would very much appreciate a better way of thinking about this problem.


texts: Sorting an array of strings in C using insertion sort

texts:
I am a Java programmer who has C this semester. Needless to say, my writing style is heavily influenced by Java, which is probably not a great thing. I'd be grateful for a few nudges in the right direction. Here's the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 100
#define WID 80

void sort(char s[][WID], int n);
void display(char s[][WID], int n);

int main()
{
    int n, i;
    char s[LEN][WID];
    printf("Enter number of strings : ");
    scanf("%d", &n);
    printf("Enter strings one by one :\n");
    for (i = 0; i < n; i++) {
        printf("%d : ", i + 1);
        scanf(" %s", s[i]);
    }

    printf("The initial elements are:\n");
    display(s, n);
    sort(s, n);
    printf("The elements after sorting are:\n");
    display(s, n);

    return 0;
}

void sort(char s[][WID], int n)
{
    int i, item;
    char elem[WID];

    for (item = 1; item < n; item++) {
        strcpy(elem, s[item]);
        for (i = item; strcmpi(s[i - 1], elem) > 0 && i > 0; i--) {
            //strcpy(s[i], s[i - 1]);
        }
        memcpy(&s[i + 1], &s[i], (item - i) * WID);
        strcpy(s[i], elem);
    }
}

void display(char s[][WID], int n)
{
    int i;
    printf("\n\n");
    for (i = 0; i < n; i++) {
        printf("%s ", s[i]);
    }
    printf("\n\n");
}

If you see something blasphemous, don't hesitate to call it out.


texts: Showing that an integer function's value and the EOF value are not the same

texts:
I was doing Exercise 1.6 and 1.7 in 'The C Programming Language' by K&R.

The questions state: "Verify that the experssion getchar() != EOF is 0 or 1" (Exercise 1.6) and "Write a program to print the value of EOF" (Exercise 1.7)

Here is my attempt at trying to do both in one program:

#include <stdio.h>

int main()
{
    printf("%d \t This is the value of EOF \n", EOF);
    int c = getchar() != EOF;
    printf("%d \t This is the value of getchar(), our variable \n", c);
}

I was wondering if there is a more concise or preferred way to do this?


texts: Ignoring the effect of a space when applying encryption

texts:
I am writing an encryption program that will encrypt the message "STOP POLLUTION" with the encryption function f(p) = (3p + 7) mod 26 where p is given letter.

Here is my code for doing so (tested it works):

    static final int SPACE = -33;
    static int[] convert(String s) {
        char[] array = s.toCharArray();
        int[] distances = new int[s.length()];
        for(int c=0;c<distances.length; c++) {
            distances[c] = array[c] - 'A';
        }
        return distances;
    }
    static String convertBack(int[] distances) {
        String result = "";
        for(int c=0;c<distances.length;c++) {
            char distance = (char) ('A' + distances[c]);
            result += distance;
        }
        return result;
    }
    static void applyShift(int[] distances, int a, int b, int mod) {
        for(int c=0;c<distances.length;c++) {
            if(distances[c]!=SPACE){
                distances[c] = (a*distances[c] + b) % mod;
            }
        }
    }

My question is regarding the space in "STOP POLLUTION". I don't really care about that space in converting the String into an array of distances from zero or converting that array back to a String but I do care about the space when applying the encryption algorithm. I want to leave the space as it is because if I change it, I won't be able to write out the space in the encrypted form.

I do this by checking if the current letter I am processing is a space. To me, this is inefficient because there is only one space. Is there a better way to do this (some way to ignore the checking of the space) but still have the space stay the same?


texts:
I'm creating a MUD and am running into some design issues regarding Items.

Items are stored in an ItemDatabase after being read from a JSON file.

template <typename ItemType>
static void load(std::string const& filename)
{
    PropertyTree propertyTree;
    boost::property_tree::read_json(filename, propertyTree);

    for (auto& jsonItem : propertyTree)
    {
        Item *item = new ItemType();
        item->fromJson(jsonItem);

        database_[item->id()] = item;
    }
}

At first, every Database::find() returned a shallow copy of the item, however, this quickly becomes dangerous and erroneous when items have a finite usage, e.g. a life potion that is consumed after one charge.

Therefore, I want to start returning deep copies as std::unique_ptrs because each Item is unique and is possessed by only one entity. This avoids dangerous dangling pointers, if the Item is not maintained or destroyed by the caller:

template <typename DataType>
std::unique_ptr<DataType> EntityDatabase<DataType>::find(EntityId const& entityId)
{
    auto found = std::find_if(std::begin(database_), std::end(database_),
                              [&entityId](Container::value_type const& candidate)
                              {
                                  return (candidate.second->id() == entityId);
                              });

    if (found != std::end(database_))
        return std::unique_ptr<DataType>(new DataType(*found->second));
    else
        return nullptr;
}

However, the resulting code is worse than hideous. Consider turning an Item into a Weapon:

void Inventory::fromJson(PropertyTree::value_type const& properties)
{
    auto jsonInventory = *properties.second.find("Inventory");

    auto weaponId = getValue<EntityId>(jsonInventory, "Weapon");
    weapon_.reset(static_cast<Weapon*>(ItemDatabase::find(weaponId).release()));

    auto armorId  = getValue<EntityId>(jsonInventory, "Armor");
    armor_.reset(static_cast<Armor*>(ItemDatabase::find(armorId).release()));

    money_ = getValue<Money>(jsonInventory, "Money");

    for (auto& item : jsonInventory.second.get_child("Items"))
    {
        auto itemId = boost::lexical_cast<EntityId, std::string>(item.second.data());
        inventory_.push_back(std::move(ItemDatabase::find(itemId)));
    }
}

How can I improve the code or the design?


texts: Reading from a .txt file to a pandas dataframe

texts:
Having a text file './inputs/dist.txt' as:

     1         1      2.92
     1         2     70.75
     1         3     60.90
     2         1     71.34
     2         2      5.23
     2         3     38.56
     3         1     61.24
     3         2     38.68
     3         3      4.49

I'm reading the text file to store it in a dataframe by doing:

from pandas import DataFrame
import pandas as pd
import os

def get_file_name( path):
    return os.path.basename(path).split(".")[0].strip().lower()

name = get_file_name('./inputs/dist.txt')
with open('./inputs/dist.txt') as f:
    df = DataFrame(0.0, index=[1,2,3], columns=[1,2,3])
    for line in f:
        data = line.strip().split()
        row,column,value = [int(i) if i.isdigit() else float(i) for i in data]
        df.set_value(row,column,value)
m[name] = df

and I end up with a dataframe of the data. I have to read more bigger files that follow this format. Is there a faster way to redo this to improve runtime?


texts:
I would like to solicit advice on everyone's thoughts on how best to combat the Anemic Domain Model anti-pattern when building out a system based on web services.

One of our goals is to build a set of core web services that expose the most basic services we reuse repeatedly in our organization, which is the creating of domain models.  Right now we have a small library that we share and reuse but as we grow our team it would be much nicer to centralize these basic services.  Over time our systems are going to change as some of the data may come from the cloud (Salesforce.com or AWS) so we're not just isolating basic DAO code in a web service but also application integration.

For example, our customer data comes from the accounting, CRM, and order processing systems.  Configuration is a real pain because every app that ships needs to be bundled with the core library and configuration on each system.  I would like to centralize the creation of models, ala, SOA, but retain a rich model higher up in the Service Layer / Facade.

If you think in general that this is a bad I'd be interested in hearing why!

My thought is to define a domain object Employee that has an EmployeeService injected.  At runtime the EmployeeService implementation is an EmployeeWebServiceClientImpl that implements said interface.  EmployeeWebServiceClientImpl uses a web service proxy to the server.

On the server-side of the web service we have EmployeeWebService invoking EmployeeDao to query the database.  Could just as easily be a class calling out to Salesforce.com to get data.  We would share a library that contained the domain model and interface so you would deserialize the web service response directly into a class that contained the needed business logic.

Below is some example code in order from client to server:

//Example of client
public static void main(String[] args) {
    try {
        Employee employee = Employee.getEmployee("james");
        if (employee.isEligibleForRaise()) {
            System.out.println("Give that man a raise!");
        }
    } catch (RuntimeException e) {
        System.out.println("Oh no!");
    }
}

//Employee Domain Object
public class Employee {

  private String name;

  private String username;

  private static EmployeeService service;

  public static Employee getEmployee(String username) {
    return service.getEmployee(username);
  }

  public static List<Employee> getAllEmployees() {
    return service.getAllEmployees();
  }

  public boolean isEmployeeEligibleForRaise() {
    //business logic here
    return true;
  }

//Getters & Setters

 ...
}

//EmployeeWebServiceClientImpl
public class EmployeeWebServiceClientImpl implements EmployeeService {

  //A client web service proxy to our core basic services
  BaseWebServiceProxy proxy;

  @Override
  public Employee getEmployee(String username) {
    return proxy.getEmployee(username);
  }

  @Override
  public List<Employee> getAllEmployees() {
    return proxy.getAllEmployees();
  }
}

//On the server-side we have EmployeeWebService
public class EmployeeWebService implements EmployeeService {

  EmployeeDao employeeDao;

  @Override
  public List<Employee> getAllEmployees() {
    return employeeDao.getAllEmployees();
  }

  @Override
  public Employee getEmployee(String username) {
    return employeeDao.getEmployee(username);
  }
}

Is that making sense?  Basically the plan is to keep core business logic in the Employee domain object but isolate the data access logic in a web service.

Thoughts?


texts: Deriving classes to decorate auto-generated base class code with attributes

texts:
Background:

I am currently in the process of abstracting and refactoring out EF for Dapper with Dapper.Contrib and the entity class definitions from EF are currently being generated by a T4 template. I have not swapped out the entities entirely for generic POCO base classes as yet as the EF implementation is functioning correctly and is serving as a reference implementation at this point in time.

As anyone who has worked with T4 templates will tell you, T4 likes to regenerate the associated code classes quite frequently, so decorating an auto-generated class is out of the question.

Using Dapper.Contrib, I need to decorate my class and key property definitions with attributes to enable the automatic CRUD operation functionality where object definitions don't conform to Dapper.Contrib's property naming convention. At the moment, the business logic layer works exclusively with the EF entity class definitions and refactoring this out at this point in time has been deemed not worth the time effort/cost.

This led to the decision to implement Dapper-specific objects that derive from the EF entity classes as a stop-gap until the Dapper implementation is proved to function correctly at which point, the EF classes can be refactored into plain POCO classes (and perhaps decorated with the Dapper.Contrib attributes as we'll only use Dapper from then onwards).

Code for review:

As mentioned, I am deriving from auto-generated EF entity classes and am wondering whether a more elegant or "better" solution exists for the following:

//Automatically generated class - cannot be changed
public class EFEntity
{
   public int EFEntityID { get; set; }
}

[Table("Schema.EntityTableName")]
public class DapperEntity : EFEntity
{
   public DapperEntity()
   {}

   public DapperEntity(EFEntity efEntity)
   {
       //Copy constructor implementation based on reflection.
   }

   [Key]
   public new int EFEntityID
   {
       get { return base.EFEntityID; }
       set { base.EFEntityID = value; }
   }

}

Is there a better way to handle the derivation/overriding of this class for decorating its properties with attributes?


texts: Encapsulate common parts of Entity Framework queries

texts:
I'm developing a system with some complex logic regarding user permissions to access different data from a SQL Server database using C# and Entity Framework. I have different places across the system where I need to query certain DB entities called 'documents' that are only accessible to current user. I came up with the following class that queries only the necessary documents:

internal class DocumentPermissionsHelper
{
    private readonly MyDbContext dc;
    public DocumentPermissionsHelper(MyDbContext dc) { this.dc = dc; }

    public IQueryable<Document> SelectDocumentsAccessibleToUser(IQueryable<Document> query, Guid userId)
    {
        var permissionsQuery = dc. ... // really big query with multiple JOIN's to determine which user has access to which documents
        IQueriable<Guid> docIdsAccessibleToUserQuery =
            from permissions in permissionsQuery.Where(_ => _.UserId == userId && _.AccessLevel == "Read")
            select permissions.DocumentId;

        return from accessibleDocId in docIdsAccessibleToUserQuery.Distinct()
                from accessibleDoc in query.Where(g => g.Id == accessibleDocId)
                select accessibleDoc;
    }
}

Then I use it in several different queries like this:

public void GetLatestDocsCount(Guid currentUserId)
{
    using (var dc = new MyDbContext(_environment))
    {
        var helper = new DocumentPermissionsHelper(dc);
        var docQuery = dc.Docs.Where(d => d.CreatedDate > DateTime.Now.AddDays(-1));
        docQuery = helper.SelectDocumentsAccessibleToUser(docQuery, currentUserId);
        int latestDocsCount = docQuery.Count();
        return latestDocsCount;
    }
}

As I said, I have many different queries that produce different kinds of data, but all have one common part: the building of subquery that selects only documents accessible to a certain UserID.

Is there a better way to 'inject' this common query part into multiple Entity Framework queries rather than instantiate DocumentPermissionsHelper every time? My own solution seems somewhat clumsy to me.


texts:
This is my solution to Exercise 1.7 from Cracking the Coding Interview.  I would appreciate any feedback on coding style and algorithm efficiency.

I do know that there is an existing function in numpy for rotating a matrix, however I am trying to implement this as an exercise.

The problem statement follows:

  Given an image represented by an NxN matrix where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees.  Can you do this in place?

import unittest

def rotate_square_matrix_right_90(matrix: list) -> list:
    """Rotate an NxN matrix 90 degrees clockwise."""
    n = len(matrix)
    for layer in range((n + 1) // 2):
        for index in range(layer, n - 1 - layer, 1):
            matrix[layer][index], matrix[n - 1 - index][layer], \
                matrix[index][n - 1 - layer], matrix[n - 1 - layer][n - 1 - index] = \
                matrix[n - 1 - index][layer], matrix[n - 1 - layer][n - 1 - index], \
                matrix[layer][index], matrix[index][n - 1 - layer]
    return matrix

class MyTest(unittest.TestCase):
    def test_rotate_matrix_right_90(self):
        input_matrix = [[0, 2, 4, 6], [-1, 1, 3, 5], [-2, 0, 2, 4], [-3, -1, 1, 3]]
        correct_rotated_matrix = [[-3, -2, -1, 0], [-1, 0, 1, 2], [1, 2, 3, 4], [3, 4, 5, 6]]
        self.assertSequenceEqual(rotate_square_matrix_right_90(input_matrix), correct_rotated_matrix)

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


texts: Rethrowing exception just as an information

texts:
I have something like that:

My custom exception class:

public class SolvableException extends RuntimeException {

    protected boolean solved = false;

    public SolvableException(String message) {
        super(message);
    }

    public void setSolved() {
        this.solved = true;
    }

    public boolean isSolved() {
        return this.solved;
    }
}

Class for some very specific calculations which in some unpredictable cases throws my exception:

class VerySpecificCalculator {
    public void makeSomeSpecificCalculations(double someParameter){
        // make some actions...
        // Now I have to make some specific calculations, but sth wrong happend and I do know what to do with it in this place...
        throw new SolvableException("Something wrong happend... Problem with XYZ");
    }
}

My very specific calculator is used in other class and provides some part of its logic:

class Calculator {
    public void makeSomeCalculations(double someParameter){
        // Some variuos calculations...
        VerySpecificCalculator calc = new VerySpecificCalculator();
        try {
            calc.makeSomeSpecificCalculations(4.34);
        } catch (SolvableException e){
            // I know what to do here, so I'm fixing a bug on this level:
            // some fixing code, some rollback whatever...
            e.setSolved();
            // But I want to inform, that the fixing process took place...
            throw e;
        }
    }
}

I use the entire stuff as follows:

class Test {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        try {
            calculator.makeSomeCalculations(344.47);
        }catch (SolvableException e){
            if(e.solved){
                System.out.println("Ok, there was a problem but it has been solved... You can display some JOptionPane to inform a user if you want...");
            } else {
                System.out.println("Buuu, there was a problem an it's still not solved... Action is interrupted ");
                return;
            }
        }
    }
}

Is this approach reasonable? I mean, is it ok to rethrow an exception if the problem has been already solved, and rethrowing plays only some informative role like in my example?

Let's consider such a situation (without rethrowing):

public void f(){
        try {
            methodCausingException();
        } catch (SolvableException e) {
            // fixing code...
        }
        //
        // Code executed when problem is fixed...
        //
    }

But with rethrowing I need to duplicate my code:

public void f(){
        try {
            methodCausingException();
        } catch (SolvableException e) {
            // fixing code...
            e.setSolved();
            //
            // Code executed when problem is fixed...
            //
            throw e;
        }
        //
        // Code executed when problem is fixed...
        //
    }

I can use a finally block, but I don't find this place as good for business logic code.


texts:
I solved this challenge. It passes all the test cases, but I'm not very happy with my solution. I'm convinced this could be done much smoother (i.e less code)

  Swap operation: Given a tree and a integer, K, we have to swap the
  subtrees of all the nodes who are at depth h, where h ∈ [K, 2K,
  3K,...].

  You are given a tree of N nodes where nodes are indexed from [1..N]
  and it is rooted at 1. You have to perform T swap operations on it,
  and after each swap operation print the inorder traversal of the
  current state of the tree.

  Input Format:  First line of input contains N, number of nodes in tree.
  Then N lines follow. Here each of ith line (1 <= i <= N) contains two
  integers, a b, where a is the index of left child, and b is the index
  of right child of ith node. -1 is used to represent null node.  Next
  line contain an integer, T. Then again T lines follows. Each of these
  line contains an integer K.

Here is my code:

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        final int N = s.nextInt();
        int[][] leafs = new int[N][2];

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < 2; j++) {
                leafs[i][j] = s.nextInt();
            }
        }

        int[] depths = new int[s.nextInt()];

        for (int i = 0; i < depths.length; i++) {
            depths[i] = s.nextInt();
        }

        TreeNode leftTree = (leafs[0][0] > -1) ? new TreeNode(leafs[0][0]) : null;
        TreeNode rightTree = (leafs[0][1] > -1) ? new TreeNode(leafs[0][1]) : null;

        if (leafs[0][0] > -1) leftTree.mapChildNodes(leftTree, leafs, (leafs[0][0] > -1) ? 1 : 2, 0, N);
        if (leafs[0][1] > -1) rightTree.mapChildNodes(rightTree, leafs, (leafs[0][0] > -1) ? 2 : 1, 0, N);

        TreeNode mainTree = new TreeNode(1, leftTree, rightTree);

        for(int d : depths) {
            mainTree.swap(mainTree, d, 1);
            mainTree.inorder(mainTree);
            System.out.println();
        }
    }
}

class TreeNode {
    private int data;
    private TreeNode left;
    private TreeNode right;

    TreeNode(int data) {
        this.data = data;
    }

    TreeNode(int data, TreeNode left, TreeNode right) {
        this.data = data;
        this.left = left;
        this.right = right;
    }

    private void insertLeft(int data) {
        if (this.left == null) {
            this.left = new TreeNode(data);
        } else {
            this.left.insertLeft(data);
        }
    }
    private void insertRight(int data) {
        if (this.right == null) {
            this.right = new TreeNode(data);
        } else {
            this.right.insertRight(data);
        }
    }

    public void inorder(TreeNode node) {
        if (node == null) return;

        inorder(node.left);
        System.out.print(node.toString());
        inorder(node.right);
    }

    public void mapChildNodes(TreeNode node, int[][] leafs, int i, int j, int arraySize) {
        if (arraySize == 0) return;

        if (leafs[i][j] > -1){
            node.insertLeft(leafs[i][j]);
            mapChildNodes(node.left, leafs, leafs[i][j]-1, 0, arraySize-1);
        }
        if (leafs[i][j+1] > -1){
            node.insertRight(leafs[i][j+1]);
            mapChildNodes(node.right, leafs, leafs[i][j+1]-1, 0, arraySize-1);
        }
    }

    public void swap(TreeNode node, int targetDepth, int depth) {
        if(node == null) return;

        if(depth % targetDepth == 0) {
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
        }
        swap(node.left, targetDepth, depth+1);
        swap(node.right, targetDepth, depth+1);

    }

    @Override
    public String toString() {
        return this.data + " ";
    }
}


texts:
I'm just wanting some input on to how others would approach this problem. I am learning and wish to gain insight on others techniques. Be as critical as you need. I want to learn. I feel this code is sloppy and the logic is confusing.

/*
    Pig Latin
    Write a program that reads a sentence as input and converts
    each word    to “Pig Latin.” In one version, to convert a word to
    Pig-Latin you remove the first letter and place that letter at the
    end of the word. Then you append the string “ay” to the word. Here
    is an example:
        English: I SLEPT MOST OF THE NIGHT
        Pig Latin: IAY LEPTSAY OSTMAY FOAY HETAY IGHTNAY
*/
#include <iostream>
#include <string>
using namespace std;

// takes a string argument and returns the pigLatin equivalent
string pigLatin(string);

int main()
{
    string mySentence;

    getline(cin, mySentence);
    mySentence = pigLatin(mySentence);
    cout << mySentence << endl;

    return 0;
}

string pigLatin(string word){

    //pigLatWord holds word translated in pig latin.
    //pigLatSentence holds entire translated sentence.
    string pigLatWord, pigLatSentence = "";
    int length = 0, index = 0;

    while (word[index] != '\0'){
        // .find returns -1 if no match is found
        if (word.find(' ', index) != -1){
            length = word.find(' ', index);
            length -= index;//length - index = the number of characters in a word
            pigLatWord = word.substr(index, length);
            pigLatWord.insert(length, "ay");
            pigLatWord.insert(length, 1, word[index]);//first letter is inserted at the end of the string
            pigLatWord.erase(0, 1);// erase first letter in string
            index += length + 1;//adding one moves index from 'space' to first letter in the next word
        }
        else{
            pigLatWord = word.substr(index);
            length = pigLatWord.length();
            pigLatWord.insert(length, "ay");
            pigLatWord.insert(length, 1, word[index]);
            pigLatWord.erase(0, 1);
            index = word.length();
        }

        pigLatSentence += (pigLatWord + " ");
    }
    return pigLatSentence;
}


texts: ReactJS, Material UI component and code organization

texts:
This is my first post here so I hope you will be patient if I'm doing something wrong. I made a small website with create-react-app and I would like to request feedback about. This website was a test and I had a limited amount of time to complete it, hence there are no tests nor license, which for the test purposes weren't necessary.

The main things I would like to have feedback on are:

1) Are my components organized properly?

2) Is the pattern I'm using to develop components appropriate?

Although I'm posting here some code, I would like to ask if you could take a quick look at my github repository and let me know what you think about it: https://github.com/sickdyd/foriio

For the components organization I used the following structure:

To avoid having multiple nested folders, I decided to put all of the sub components that belong to a specific component on the same level. The naming should give away the function, and the folder name has the same name as the main component.

One quick question: the component src/components/body/UserProfile/UserWorks.js is reused in src/components/body/UserWork/UserWork.js; is it ok to leave them with this structure?

The components generally have the following code structure (this is one of the simplest components):

import React from 'react';

import PropTypes from 'prop-types';

import Typography from '@material-ui/core/Typography';
import Skeleton from '@material-ui/lab/Skeleton';

import { makeStyles } from '@material-ui/styles';

const useStyles = makeStyles(theme => ({
  bio: {
    display: "flex",
    justifyContent: "center",
    marginTop: theme.spacing(2),
    color: theme.palette.text.primary,
  },
}));

export default function UserBio(props){

  const classes = useStyles();

  const {
    loading,
    profile,
  } = props;

  return (

    loading ?

        <Skeleton variant="rect" style={{ marginBottom: 12, width: 315 }} />
        <Skeleton variant="rect" style={{ marginBottom: 12, width: 315 }} />
        <Skeleton variant="rect" style={{ marginBottom: 12, width: 315 }} />

    :

        <Typography>
          { profile.bio }
        </Typography>

  )
}

UserBio.propTypes = {
  loading: PropTypes.bool.isRequired,
  profile: PropTypes.object,
}


texts: Determining if the kangaroos will land in the same position

texts:
Problem

  There are two kangaroos on an x-axis ready to jump in the positive
  direction (i.e, toward positive infinity). The first kangaroo starts
  at location x1 and moves at a rate of v1 meters per jump. The second
  kangaroo starts at location x2 and moves at a rate of v2 meters per
  jump. Given the starting locations and movement rates for each
  kangaroo, can you determine if they'll ever land at the same location
  at the same time?

My Solution

#include <iostream>
using namespace std;

int main(){
    int x1, v1, x2, v2;
    cin >> x1 >> v1 >> x2 >> v2;

    // If one kangaroo is behind the other AND moving slower,
    //    he/she will never catch up to the other one
    if ((x1 < x2) && (v1 < v2)) cout << "NO";
    else if ((x2 < x1) && (v2 < v1)) cout << "NO";

    // Otherwise, move each kangaroo one jump at a time until
    //     the one behind is no longer behind.
    else {
        if (x1 < x2) {
            while (x1 < x2) {
                x1 += v1;
                x2 += v2;
            }
        } else {
            while (x2 < x1) {
                x1 += v1;
                x2 += v2;
            }
        }

        // Once he/she is no longer behind the other, check to see
        //    if he/she is in the same position, or if he/she has passed
        if (x1 == x2) cout << "YES";
        else cout << "NO";
    }
    return 0;
}

I am wondering if there is a way to optimize my code for this particular HackerRank problem. I have gotten all of the correct answers, and none of them timeout so for the problem it's 'good enough,' but I am curious if there is a better way of doing it.

Do I use too many conditionals, loops, etc? I have a bad habit of "do everything in for loops, if statements, etc."


texts:
I've implemented the Sieve of Eratosthenes algorithm in Haskell. Please take a look. Any suggestions are greatly appreciated :)

import Data.List

-- a list identical with {seq} but for multiples of {p} which are replaced by {-1}
sieve_once :: [Integer] -> Integer -> [Integer]
sieve_once seq p = map (\x -> if x `mod` p == 0 then -1 else x) seq

-- a list of all prime numbers
sieve :: [Integer]
sieve = unfoldr (\acc -> let p:rest = dropWhile (\x -> x == -1) acc in Just(p, sieve_once rest p)) [2..]

-- a list of all prime numbers not greater than {n}
sieve_until :: Integer -> [Integer]
sieve_until n = takeWhile (\x -> x <= n) sieve


texts: Is there a more succinct way to write this Ruby function?

texts:
Just for fun, I want to try to write this Ruby function more succinctly. I imagine it can be done, I'm just not knowledgeable enough with Ruby yet to know how. Any suggestions?

  def tags
    return ['Cancelled'] if cancelled?
    tags = []
    tags << 'Filled' if filled?
    tags << 'In Progress' if in_progress?
    tags
  end


texts: Generate the Norwegian equivalent to social security numbers

texts:
This is just a little hobby project I've been working on. I've been using it to learn/improve my knowledge of C++.

The program generate Norwegian personal-numbers (11 digits) for males born a given year. It works just fine, but I'd like some input on how to improve the code. For now I have a basic class structure.

Norwegian personal-numbers is built up like this.

#include <iostream>

using namespace std;

const int DATE_LENGTH = 6;
const int BUFFER = 30;

class ID {
    private:
        int date[DATE_LENGTH];
        int i1, i2, i3;
        int k1, k2;
        int year;
    public:
        ID(int i1 = 0, int i2 = 0, int i3 = 0, int k1 = 0, int k2 = 0) {
            for (int i = 0; i < DATE_LENGTH; i++) { date[i] = 0; }
        }

        int *getDate() { return date; }

        void setYear(int year) {
            this->year = year;
        }

        int getYear() {
            return year;
        }

        void individSiffer() {
            static int individ = -1;
            if(year >= 1900 && year <= 1999 ){
                    individ++;
                    i1 = i2 = i3 = 0;
                }
                i3 = individ % 10;
                if(individ < 100){
                    i1 = 0;
                    i2 = individ / 10 % 10;
                }else if(individ < 10){
                    i1 = i2 = 0;
                }else{
                    i1 = individ / 100 % 10;
                    i2 = individ / 10 % 10;
                }
        }

        void generate() {
            k1 = 11 - ((3*date[0] + 7*date[1] + 6*date[2] + 1*date[3] + 8*date[4] + 9*date[5] + 4*i1 + 5*i2 + 2*i3) % 11);
            if(k1 == 11){
                k1 = 0;
            }
            k2 = 11 - ((5*date[0] + 4*date[1] + 3*date[2] + 2*date[3] + 7*date[4] + 6*date[5] + 5*i1 + 4*i2 + 3*i3 + 2*k1) % 11);
            if(k2 == 11){
                k2 = 0;
            }
            if((i3 != 0 && i3 != 2 && i3 !=4 && i3 !=6 && i3 !=8) && (k1 != 10 && k2 !=10)){
                for (int i = 0; i < DATE_LENGTH; i++) {
                    printf("%d", date[i]);
                }
                printf("%d%d%d%d%d\n", i1, i2, i3, k1, k2);
            }
        }
};

int main(int argc, char *argv[]) {
    char dateString[BUFFER];
    int i = 0;
    ID generator;

    printf("%s", "Your date of birth (DDMMYY): ");
    cin.getline(dateString, BUFFER);

    for(int i = 0; i < DATE_LENGTH; i++){
        *(generator.getDate() + i) = int(dateString[i]-'0');
    }
    generator.setYear(1900 + (*(generator.getDate() + 4) * 10) + *(generator.getDate() + 5));
    while(i < 500){
        generator.individSiffer();
        generator.generate();
        i++;
    }
    cout << "\n\n\n";
    return 0;
}


texts: Query Rails 3 Active Record Fetch associated model based on conditions

texts:
Here is what I have. A User model and an Address model. User has_many :addresses and Address belongs_to :user.

Now I want to search for users whose email contains a give term, or one of the user's addresses contains that term. So lets say the term is 'jap', any User whose email like '%jap%' or any user whose any address city or address_line is like '%jap%' should be returned.

I can get the Users with a simple join like this:

users = User.joins('LEFT OUTER JOIN addresses ON users.id=addresses.user_id').where('users.email like '%jap%' OR addresses.city like '%jap%' OR addresses.address_line like '%jap%')

then to get those addresses (if any) that matched the search term I have to query again for each user returned:

users.each do |u|
    u.addresses.where("addresses.city like '%jap%' OR addresses.address_line like '%jap%'")
end

Is there a way to improve this so that I only search the addresses table once? I mean, a single query that returns the Users and the matching addresses for each user.


texts: Reading in a file and performing string manipulation

texts:
In a question I answered I posted the following code:

#include <iostream>
#include <fstream>
#include <algorithm>
#include <sstream>

int main()
{
    fstream iFile("names.txt", ios::in);

    // This does not work so replacing with code that does
    // iFile >> file;

    // This is not the best way.
    // But the closest to the intention of the original post.

    // Get size of file.
    ifile.seekg(0,std::ios::end);
    std::streampos          length = ifile.tellg();
    ifile.seekg(0,std::ios::beg);

    // Copy file into string.
    std::string       file(length, '\0');
    ifile.read(&buffer[0],length);

    // Original code continues.

    std::istringstream ss(file);
    std::string token;

    std::vector<std::string> names;

    while(std::getline(ss, token, ',')) {
        names.push_back(token);
    }

    for (unsigned int i = 0; i < names.size(); i++) {
         auto it = std::remove_if(names[i].begin(), names[i].end(), [&] (char c) { return c == '"'; });
         names[i] = std::string(names[i].begin(), it);
    }

    for (unsigned int i = 0; i < names.size(); i++) {
        std::cout << "names["<<i<<"]: " << names[i] << std::endl;
    }
}

Would this be inefficient for larger files? Would it be better if I read the file into one string, did all the manipulation on that, and then put it into a vector?


texts: Applying OOP to refactor my Windows Forms APP

texts:
Could you please give me some direction about how I could refactor my code? As I add functionalities to my Budget App the class is getting bigger and I'm sure I could start looking at separating concerns and maybe using some sort of abstraction.
I've been studying OOP for a few months now but I'm not sure how to apply this knowledge to the controls on a windows form app. All I could come up with so far is to separate the calculations I  want to make with the budget entries, which I'll do next.
Here's the link to my form code:
https://github.com/pablo-the-souza/Budget1.1/blob/master/Budget1.1/Form1.cs
And here's a snippet:
 private void fillByDateAndCategoryBtn_Click(object sender, EventArgs e)
        {
            this.mainTableAdapter1.FillByDateAndCategory
               (
               this.dataSet2.main,
               categoryCB.SelectedItem.ToString(),
               monthCalendarStart.SelectionRange.Start.ToString(), monthCalendarStart.SelectionRange.End.ToString()
               );
        }

        private void FillByDateAndTypeBtn_Click(object sender, EventArgs e)
        {
            this.mainTableAdapter1.FillByDateAndType
               (
               this.dataSet2.main,
               typeCB.SelectedItem.ToString(),
               monthCalendarStart.SelectionRange.Start.ToString(), monthCalendarStart.SelectionRange.End.ToString()
               );
        }


texts: Program for printing all numbers that user inputs till 42 in Clojure

texts:
As the name suggests it is a very simple program to print numbers to screen till user inputs 42.

(map
  println
  (take-while
    #(not= % "42")
    (repeatedly #(.readLine *in*))))

I have started learning Clojure so please share whether there is some easier way to read lines or anything else that can be improved.


texts:
Purpose:

In an HTML page, a user can filter results, by setting conditions.

At the beginning, there is no condition displayed, but a button to add one.

The code for each condition is always the same, and is know during design.

I am trying to insert the template in the page in the most efficient and standard way.

Code:

I have added the template of the condition, with display:none at the bottom of the page, and when a new condition is requested, the template is cloned and added to the DOM

$("#addConditionButton").click(function() {
  $("#template")
 .clone()
 .attr('id','condition'+$(".condition").length)
 .show()
 .appendTo("#conditions")
})

      Filter conditions

    <button id="addConditionButton">
      Add Condition
    </button>

  <select>
    <option>&lt;</option>
    <option>&gt;</option>
    <option>=</option>
  </select>
  <input type='text'>

My concerns:

I am not sure that the method I used, hidden template then cloning is the best way to do this, in terms of performance, but mostly in terms of best practice, since I'm learning about this.

Thanks,


texts: Object array with identifier: use index to quickly access elements by id?

texts:
I must access the elements of an object array very often by an identifier id, i.e.

[
{id:1, value:“test“, cat:2},
{id:2, value:“test“, cat:2},
{id:3, value:“test“, cat:2}, ...
]

To do so I use find, for example to fetch the value of object with id 3:

  SomeVal = myArray.find(x => x.id === 3).value

However, as I would never change the initial array after creation, and as the id of each item is well defined (I fetch the objects from my sql db), I was thinking to use the array index as identifier. I would use splice to create such array initially and I would start with id 1. I have around 5k objects.

This way I must not use find, but instead could access the array by the index directly:

 SomeVal = myArray[3].value

As my id starts with 1, the array would be of same size in the end.

I would think that’s an enormous performance boost, yet I have never seen anyone going such an approach when accessing elements by an identifier. What do you think?


texts:
I have 2 Truncate string methods.

First:

public static string Truncate(string source, int length)
    {
    if (source.Length > length)
    {
        source = source.Substring(0, length);
    }
    return source;
    }

Second:

public static string Truncate2(string source, int length)
    {
    return source.PadRight(length).Substring(0, length).Trim();
    }

Which of these methods is better, faster?


texts:
I wrote a program to find all the prime numbers up to N on my TI-84, however, it is quite slow for any number above, like, 50. Are there any ways to optimize my code?
(I added comments using //)
Input N
{2}→L₂
For(I,3,N,2) // Loop through every odd number up to N starting at 3
1→J
0→H
√(I)→S
While L₂(J)≤S and H=0 // checks every previously found prime # less than sqrt(I)
If remainder(I,L₂(J))=0
1→H // used to break the loop

J+1→J
End
If H=0 // if no numbers divided evenly, add it to the list
augment(L₂, {I})→L₂

End

Disp L₂

Thanks!


texts: Find largest smaller key in Binary Search Tree

texts:
Given a root of a Binary Search Tree (BST) and a number num, implement
  an efficient function findLargestSmallerKey that finds the largest key
  in the tree that is smaller than num. If such a number doesn’t exist,
  return -1. Assume that all keys in the tree are nonnegative.

The Bst Class is given to me.

public class BstNode
{
    public int key;
    public BstNode left;
    public BstNode right;
    public BstNode parent;

    public BstNode(int keyt)
    {
        key = keyt;
    }
}

you can ignore the unit test code this is a just the demo.

   [TestMethod]
        public void LargestSmallerKeyBstRecrussionTest()
        {
            BstNode root = new BstNode(20);
            var left0 = new BstNode(9);
            var left1 = new BstNode(5);
            var right1 = new BstNode(12);
            right1.left = new BstNode(11);
            right1.right = new BstNode(14);
            left0.right = right1;
            left0.left = left1;

            var right0 = new BstNode(25);
            root.right = right0;
            root.left = left0;
            Assert.AreEqual(14, helper.FindLargestSmallerKeyRecursion(17, root));
        }

this is the code I would like you please to review, comment.

       public static int FindLargestSmallerKey(uint num, BstNode root)
    {
        if (root == null)
        {
            return -1;
        }
        int temp = Math.Max( FindLargestSmallerKey(num, root.left), FindLargestSmallerKey(num, root.right));
        if (root.key < num)
        {
            return Math.Max(root.key, temp);
        }
        return temp;
    }


texts: Project Euler Problem 5: Smallest Multiple of 1 through 20

texts:
In continuing to learn C# I solved Problem #5 with my code below. I tried to follow the suggestion to write [my] program so that it looks like the specification. Where can I improve my code?
The problem is as follows:

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetSmallestEvenlyDivisibleNumber());
            Console.ReadLine();
        }

        static bool isEvenlyDivisible(int value, int lowerBound, int upperBound)
        {
            bool returnValue = true;
            for (int i = lowerBound; i<= upperBound; ++i)
            {
                if (value % i != 0)
                {
                    returnValue = false;
                    break;
                }
            }

            return returnValue;
        }

        static int GetSmallestEvenlyDivisibleNumber(int lowerBound = 1, int upperBound = 20)
        {
            int testNumber = 2521;

            while (!isEvenlyDivisible(testNumber, lowerBound, upperBound))
            {
                testNumber += 1;
            }

            return testNumber;
        }
    }
}


texts: Hide element when clicking anywhere but some elements using jQuery

texts:
I had a jQuery program that displays some hover-over messages when touching an icon, in order to make it disappear the user needs to click again in the icon.

am.homepage.Index.prototype.touchableTitleBinding = function () {
    var that = this;
    $('.' + this.bindingClassForTouchableTitle).on('touchend', function (e) {
        e.stopPropagation();
        $('.' + that.toggleClassForTouchableTitle).not(this).toggleClass(that.toggleClassForTouchableTitle);
        $(this).toggleClass(that.toggleClassForTouchableTitle);
    });
}

The variables are passed to the .js file from an mvc view. and the touchableBinding funciton is called on dom load.

Thing is that now I'd like to make it disappear whenever you click outside any of those icons, so I wrote this:

am.homepage.Index.prototype.hideTouchableTitleBinding = function () {
    var that = this,
        classForTouchabletitle = '.' + this.bindingClassForTouchableTitle;

    am.personExpenditure.Index.prototype.hideTouchableTitleBinding = function () {
        var that = this,
            classForTouchabletitle = '.' + this.bindingClassForTouchableTitle;

        $('*:not(' + classForTouchabletitle + ')').on('touchend', function (e) {
        e.stopPropagation();
        $('.' + that.toggleClassForTouchableTitle).removeClass(that.toggleClassForTouchableTitle);
    });
}

Is it too heavy to select all the elements apart from the ones with toggleClassForTouchableTitle? Is it worth binding like this?

am.homepage.Index.prototype.hideTouchableTitleBinding = function() {
    var that = this,
        classForTouchabletitle = '.' + this.bindingClassForTouchableTitle;

    $(body).on('touchend', '*:not(' + classForTouchabletitle + ')', function(e) {
        e.stopPropagation();
        $('.' + that.toggleClassForTouchableTitle).removeClass(that.toggleClassForTouchableTitle);
    });
};

Is it another way of doing it more elegant/performant?

At the end I've changed to this

am.homepage.Index.prototype.touchableTitleBinding = function() {
    var that = this,
        removeTouchableTitleClass = function (e) {
            e.stopPropagation();
            $('.' + that.toggleClassForTouchableTitle).removeClass(that.toggleClassForTouchableTitle);
        };

    $('.' + this.bindingClassForTouchableTitle).on('touchend', function(e) {
        e.stopPropagation();
        $('.' + that.toggleClassForTouchableTitle).not(this).toggleClass(that.toggleClassForTouchableTitle);

        //If we've displayed the title for one icon we rebind to hide it when clicking outside
        //just once, if we've hide it we stop listening to touch other elements for dealing with this
        $('body').off('touchend', ':not(' + that.toggleClassForTouchableTitle + ')');
        if ($(this).hasClass(that.toggleClassForTouchableTitle)) {
            $(this).removeClass(that.toggleClassForTouchableTitle);
        } else {
            $(this).addClass(that.toggleClassForTouchableTitle);
            $('body').on('touchend', ':not(' + that.toggleClassForTouchableTitle + ')', removeTouchableTitleClass);
        }

    });
};

In which case only once after displaying the tile will listen for the touch in any other part of the screen. I think this is probably slightly less readable but more performant


texts: Making the objectContext.CommandTimeout configurable?

texts:
I am trying to make the CommandTimeout value more configurable.  I'm wondering if this is best practice to do so?

I add the following to my <appsettings> node in my Web.config file:

<add key="commandTimeValue" value ="60"/>

The I added the following to the top of my controllers under the :

using (var db = new myDAL())...

Int32 timeoutVal = Convert.ToInt32

(System.Web.Configuration.WebConfigurationManager.AppSettings["commandTimeValue"]);
((IObjectContextAdapter)db).ObjectContext.CommandTimeout = timeoutVal;

Is this the right way to do this?  What are some other alternatives?


texts:
The .htaccess file redirects all requests to this file and the $_REQUEST['path'] variable contains the url after the base url.

$url = '';
$urlSegments = [];
$resource = '';
$action = '';
$parameters = [];

if(isset($_REQUEST['path'])){
    $url = $_REQUEST['path'];
    $urlSegments = explode('/', $url);

    if(!empty($urlSegments[0])){
        $resource = $urlSegments[0];
        array_shift($urlSegments);

        if(!empty($urlSegments[0])){
            $action = $urlSegments[0];
            array_shift($urlSegments);
            $parameters = $urlSegments;
        }
    }
}

$method = $_SERVER['REQUEST_METHOD'];

I was wondering if there is an better way (with regex maybe?) to parse the url, loop through it and extract the MVC data from the url. array_shift looks ugly and it feels that there must be a better way.


texts: Maximum profit earned on weighted un-directed tree

texts:
I came across this problem while giving a sample test.

  The problem was that we have given a tree which is undirected. We can
  start from any node of our choice. Initially we have power "P" and
  while going from one node to other node we loose some power "X"
  (consider as cost of travelling) and earn some profit "Y". So we need
  to tell that what is the maximum profit that we can earn with a given
  power ? Every node can be visited only once.

Example: First line contains number of nodes and initial power

Next n-1 lines contains node-node-cost-profit

5 4

1 2 1 2

1 3 2 3

1 4 2 4

4 5 2 2

Answer => 7. We can start from 4 and go to 1 and than to 3.

I have applied DFS on this to get maximum profit earned by traversing every single path.

But is there a way to decrease time ??? Can we apply floyd warshall algorithm to calculate distances each edges ??

from collections import defaultdict
class tree:
    def __init__(self,nodes):
        self.nodes = nodes
        self.graph = defaultdict(list)
    def add(self,a,b,charge,profit):
        self.graph[a].append([b,charge,profit])
        self.graph[b].append([a,charge,profit])
    def start(self,power):
        maxi = -1
        visited = [False for i in range(self.nodes)]
        for i in range(1,self.nodes+1):
            powers = power
            visited[i-1] = True
            for j in self.graph[i]:
                temp = self.dfs(j,powers,0,visited)
                if temp > maxi:
                    maxi = temp
            visited[i-1] = False
       return maxi

    def dfs(self,node,powers,profit,visited):
        v,p,pro=node[0],node[1],node[2]
        if powers-p < 0:
            return 0
        if powers-p == 0:
            return profit + pro
        profit += pro
        powers = powers-p
        visited[v-1] = True
        tempo = profit
        for k in self.graph[v]:
            if visited[k[0]-1] == False:
                temp = self.dfs(k,powers,tempo,visited)
                if temp > profit:
                    profit = temp
        visited[v-1] = False
        return profit

t = tree(5)
t.add(1,2,1,2)
t.add(1,3,2,3)
t.add(1,4,2,4)
t.add(4,5,2,2)
print(t.start(4))