texts: Model profit/loss of a time series of financial position state changes

texts:
I'm newly exploring time series databases, and trying to wrap my head around what data I'll store and how I'll query it.  Also, I'm relatively new to TypeScript.  This prototype exercises my current understanding of how it will work.

What I most want feedback on is:

TypeScript idioms: am I following them? Does anything I'm doing stick out like a sore thumb?
Am I properly representing this in a way analogous to a time-series database? (TimescaleDB is the one I'm eyeing, if it matters.)

namespace Position {
    export enum State {
        BuyingToOpen,
        SellingToOpen,
        Open,
        BuyingToClose,
        SellingToClose,
        Closed,
    };

    export namespace State {
        export type Transition = OrderPlacementTransition | OrderFillTransition;

        export interface OrderPlacementTransition extends TransitionBase {
            newState: Opening | Closing;
            orderId: string;
        }

        export type Opening = State.BuyingToOpen | State.SellingToOpen;
        export type Closing = State.BuyingToClose | State.SellingToClose;

        export interface OrderFillTransition extends TransitionBase {
            newState: State.Open | State.Closed;
        }

        interface TransitionBase {
            timestamp: number;
            positionId: string;
            newState: State;
            affectedAsset: string;
            affectedAssetDelta: number;
        }
    }
}

const positionHistory: Position.State.Transition[] = [
    {
        // placed an order to spend $500 on 2,500 ZRX
        timestamp: 0,
        positionId: '0',
        newState: Position.State.BuyingToOpen,
        orderId: 'A',
        affectedAsset: 'USD',
        affectedAssetDelta: -500,
    },
    {
        // order to spend $500 has been filled, we now hold 2,500 more ZRX
        timestamp: 1,
        positionId: '0',
        newState: Position.State.Open,
        affectedAsset: 'ZRX',
        affectedAssetDelta: +2500,
    },
    {
        // placed an order to sell that 2,500 ZRX
        timestamp: 2,
        positionId: '0',
        newState: Position.State.SellingToClose,
        orderId: 'B',
        affectedAsset: 'ZRX',
        affectedAssetDelta: -2500,
    },
    {
        // order to sell 2,500 ZRX for $505 has been filled
        timestamp: 3,
        positionId: '0',
        newState: Position.State.Closed,
        affectedAsset: 'USD',
        affectedAssetDelta: +505,
    },
];

type ProfitOrLoss = { [asset: string]: number };

console.log(
    positionHistory.reduce<ProfitOrLoss>(
        (profitOrLoss, historyElement) => {
            profitOrLoss[historyElement.affectedAsset] = (
                (profitOrLoss[historyElement.affectedAsset] || 0)
                + historyElement.affectedAssetDelta
            );
            return profitOrLoss;
        },
        {},
    ),
);

Result:

{
    "USD": 5,
    "ZRX": 0
}


texts: Rendering nested array in a  with headings

texts:
I have an array with the following structure

Array
(
    [0] => Array
        (
            [area] => Area ABC
            [activity] => Array
                (
                    [0] => Activity 1
                    [1] => Activity 2
                )
        )
)

I'm trying to render this array in the following way

Area ABC

Activity 1
Activity 2

And am currently using the following code to achieve this

$status = 'closed';
foreach($suggestions as $suggestion)
    {
    if($currentarea != $suggestion['area'])
        {
        echo "
";
        echo $suggestion['area'];
        echo "
";
        if($status == 'closed')
            {
            echo "
";
            $status = 'open';
            }
        }
    foreach($suggestion['activity'] as $activity)
        {
            echo "
";
            echo $activity;
            echo "
";
        }
    if($status == 'open')
        {
            echo "
";
            $status = 'closed';
        }
    $currentarea = $suggestion['area'];
    }

Is this the best way of doing it, or is there a better way, I will have more areas and activities, but the structure stays the same.


texts:
I'm new to Haskell, and I'm wondering why my programs are so slow compared to other languages.

Haskell, 6 seconds (x64, -O2):

nextCollatz :: Int -> Int
nextCollatz x = if even x
    then quot x 2
    else 3 * x + 1

collatzLength :: Int -> Int
collatzLength x = if x == 1
    then 0
    else 1 + collatzLength (nextCollatz x)

main = print . show . sum . map collatzLength $ [1..3000000]

Julia, 0.8 seconds (excluding the compilation time):

function main()
    sum = 0
    for i = [1:3000000]
        while i > 1
            i = isodd(i) ? 3 * i + 1 : i >> 1
            sum += 1
        end
    end
    sum
end

println(main())

Maybe the comparison isn't fair, but I'd like to know how to improve my Haskell code to bring it on par with other high-level languages such as Julia and JavaScript.

While memoization and parallelization would definitely help, currently I'm concerned with efficient iteration and arithmetic.


texts: Sharing data with another thread using lock_guard

texts:
I wrote a updater_thread() and a reader_thread(), and used lock_guard to protect a global instance.
Question

I've never used lock_guard. In this code, is lock_guard used properly?

Is this code thread-safe?

Code
#include <iostream>
#include <thread>
#include <mutex>
#include <iterator>
#include <algorithm>
#include <vector>
#include <initializer_list>
#include <unistd.h>

class C {
  std::vector<int> v;
  std::mutex mutex_;

public:
  C() {}
  void Update(const std::vector<int> &new_v) {
    std::lock_guard<std::mutex> lock(mutex_);
    v = new_v;
  }
  bool Check(const int x){
    std::lock_guard<std::mutex> lock(mutex_);
    return std::find(v.begin(), v.end(), x) != v.end();
  }
  /* dump() is not essential */
  void dump() {
    std::lock_guard<std::mutex> lock(mutex_);
    std::cout << "dump: ";
    std::copy(v.begin(), v.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
  }
};

// create an instance gloablly
C g_c;

void updater_thread() {
  std::cout << "start updater_thread\n";
  while (true) {
    std::vector<int> v;
    for (int i = 0; i < 10; i++) {
        v.push_back(rand() % 10 + 1);
    }
    std::sort(v.begin(), v.end());
    g_c.Update(v);
    std::cout << "updated!!!\n";
    std::copy(v.begin(), v.end(),
              std::ostream_iterator<int>(std::cout, " "));
    std::cout << "\n";
    sleep(5);
  }
}

void reader_thread() {
  std::vector<int> v {1,2,3,5};
  while (true) {
    std::cout << "check: non-exist item: ";
    for (int i = 0; i < v.size(); i++) {
        if (!g_c.Check(v[i])){
            std::cout <<  v[i] << " ";
        }
    }
    std::cout << "\n";
    sleep(1);
  }
}

int main() {
  std::thread t_up(updater_thread);
  std::thread t_r(reader_thread);
  t_up.join();
  t_r.join();
}


texts: implement the merge functionality for 2048 with JavaScript

texts:
I am trying to implement the game 2048 using JavaScript. I am using a two-dimensional array to represent the board. For each row, it is represented using an array of integers.
Here I am focused on implementing the merge left functionality i.e. the merge that happens after the user hits left on their keyboard.
Here are a set of test cases that I came up with
const array1 = [2, 2, 2, 0] //  [4,2,0,0]
const array2 = [2, 2, 2, 2] // [4,4,0,0]
const array3 = [2, 0, 0, 2] // [4,0,0,0]
const array4 = [2, 2, 4, 16] // [4,4,16,0]

Here is one workable solution:
function mergeLeft(array) {
    let startIndex = 0;
    for (let endIndex = 1; endIndex < array.length; endIndex++) {
        if (array[endIndex] === 0) continue;
        let target = array[startIndex];
        if (target === 0 || target === array[endIndex]) { // shift or merge
            array[startIndex] += array[endIndex];
            array[endIndex] = 0;
        } else if (startIndex + 1 < endIndex) {
            endIndex--; // undo the next for-loop increment
        }
        if (target !== 0) startIndex++;
    }
    return array;
}

This works but there are a lot of if-else checking that makes it hard to extend or adapt to merges in other directions e.g. right, up, down.
Is there a better way to design the algorithm or the function so it can be more easily extensible to other directions? Any other feedback is welcomed!
In addition, I would like to ask a few more questions:

If we are going to build this game using a traditional object-oriented way, what are the class we need to design here?
I figured that we can use a 2-dimensional array to represent the board, or as one of the answers presented, we can use a 1-dimensional array to hold x,y coordinates, I wonder what are some of the pros and cons with either approach?
I was looking at it from an OOD approach and I was also aware that we can use functional programming instead. Here is my attempt

const reverse = (array) => [...array].reverse()

const transpose = (grid) => grid[0].map((_, i) => grid.map((r) => r[i]))

const rotateClockwise = (grid) => transpose(reverse(grid))

const rotateCounter = (grid) => reverse(transpose(grid))

// helper functions
const shift = ([n0, n1, ...ns]) =>
  n0 == undefined
    ? []
    : n0 == 0
    ? shift([n1, ...ns])
    : n1 == 0
    ? shift([n0, ...ns])
    : n0 == n1
    ? [n0 + n1, ...shift(ns)]
    : [n0, ...shift([n1, ...ns])]

const fillZeros = row =>
    row.concat ([0, 0, 0, 0]) .slice (0, 4)

const merge = ([firstItem, secondItem, ...rest]) =>
    firstItem == undefined
      ? []
    : firstItem == 0
      ? merge ([secondItem, ...rest])
    : secondItem == 0
      ? merge ([firstItem, ...rest])
    : firstItem == secondItem
      ? [firstItem + secondItem, ... merge (rest)]
    : [firstItem, ...merge ([secondItem, ... rest])]

const mergeRow = (row) =>
    merge(row).concat([0, 0, 0, 0]).slice (0, 4)

const mergeLeft = (grid) => grid.map(mergeRow)
const mergeRight = (grid) => grid.map((row) => reverse(mergeRow(reverse(row))))
const mergeUp = (grid) => rotateClockwise(mergeLeft(rotateCounter(grid)))
const mergeDown = (grid) => rotateClockwise(mergeRight(rotateCounter(grid)))

However I cannot pinpoint exactly which approach i.e. functional programming vs. OOP is better. Can someone give me some concrete benefits for going with either approach?


texts:
We've got a "catch-all" in app.js that renders a .jade file if it exists:

app.get('*', routes.render);

  index.js

render: function(req, res) {
  fs.exists('views' + req.url + '.jade', function(exists) {
    if (exists) {
      //substring: "/admin" -> "admin"
      res.render(req.url.substring(1));
    } else {
      res.status(404);
      res.render('404', {url: req.url});
    }
  });
}

Problem is, we've either got to move everything we don't want rendered this way into another folder, which is a hassle, or create a manual blacklist.  Is there a better way of doing this?


texts:
I don't know why in most of the interviews, interviewers are asking this question commonly.

The question is: There are n number of persons standing in a circle. The first person has a gun and he kills the very next person who is alive and hands over the gun to the next person. Who will remain?

Here is my code for the above scenario.
It works, if anyone needs to ask.

public static void void main(String ar[]) {

    int numberOfGuys = 10000;
    List<Integer> list = new ArrayList<>();
    for ( int i = 1; i <= numberOfGuys; i++ ) {
        list.add( i );
    }
    boolean isNeighbour = false;

    System.out.println( list );
    Iterator<Integer> i = list.iterator();
    list = new ArrayList<>();
    boolean isTrue = true;
    while ( isTrue ) {
        int k = i.next();
        if ( isNeighbour )
            i.remove();
        else {
            list.add( k );
        }
        if ( !i.hasNext() ) {
            System.out.println( list );
            i = list.iterator();
            if ( list.size() == 1 )
                isTrue = false;
            list = new ArrayList<>();
        }
        isNeighbour = !isNeighbour;
    }
}


texts: Is this "smart" way of populating the admin page ok code-wise?

texts:
I am currently hooking a large database up to a django site and want to populate the admin page with a number of models. I am using inspect to get a list of classes from each model file (one file per database in MySQL) and then registering them by name.

from django.contrib import admin
import inspect
from .models import auth

# Auth
for pair in inspect.getmembers(auth):
    # returns a tuple with the class name and ref
    model = tuple[1]
    if tuple[0][0] is not "_" and tuple[0][0].upper() == tuple[0][0]:
        # it doesnt start with _ and does start with an uppercase
        admin.site.register(model)

Is there anything wrong with this code? Is getting class references like this bad practice? It just seems to easy to be true.


texts:
Background

Today at work, I had to bring a component that used to load CSV data into MySQL, and perform calculations as result of SQL queries. I was tasked with replicating that in a programming language.

The general example is like:

There's a 2D array (a table) with columns "Name", "Age", "Grade" and "Total". Produce counts like "Unique Ages", "Unique Ages & Grade", "Unique Ages for which Grade = 3" etc.

My Work

So, I chose Python to do this job. There's a class that takes two parameters: 2D array and columns, and allows for performing some very basic querying capability.

Environment: Python 2.x

class From:
    def __init__(self, array, columns):
        self.columns = columns
        self.array = array

    def where(self, column, data):
        return From(filter(lambda x: x[self.columns.index(column)] == data, self.array), self.columns)

    def whereNot(self, column, data):
        return From(filter(lambda x: x[self.columns.index(column)] != data, self.array), self.columns)

    def select(self, *columns):
        return From([[arrayItem[self.columns.index(col)] for col in columns] for arrayItem in self.array], columns)

    def unique(self, *columns):
        # This function filters those rows which have a unique combination of the columns
        # specified as parameter. If there are 2+ rows with same combination of values
        # under the column, then the last one will be chose. Example use case: Extract a
        # subset of rows that have a unique combination of "first name" & "second name"
        # Invocation: From(<array>,<cols>).unique("first_name","second_name")
        return From({tuple(row[self.columns.index(col)] for col in columns): row for row in self.array}.values(), self.columns)

    def length(self):
        return len(self.array)

    def get(self):
        if len(self.columns) == 1:
            return [x[0] for x in self.array]
        return self.array

Example Usage:

>>> array = [
... ["ben", "son", 23, 10, 93],
... ["gun", "dad", 21, 9,  99],
... ["sam", "mom", 19, 11, 92]
... ]
>>> cols = ["name1","name2", "age", "grade", "marks"]
>>> From(array, cols).where("name1","sam").get()
[['sam', 'mom', 19, 11, 92]]

The querying that is being done in the real code is quite complex beyond the scope of this question. The From class works, for now.

Questions

Can this be improved, maybe made more pythonic from an overall perspective (Please excuse those ugly filter/lambda expressions. I know they are just not pythonic.)?
The From.unique(..) function looks like a dirty hack. Is there any cleaner way to do it? (Please check my comment under the unique function declaration.)
Is there any non-edge case when the above will not work? Anywhere it might just go wrong?
Am I reinventing the wheel?


texts: Different Constructors, Same Implementation

texts:
I have this class containing two constructors with different signatures but they do the same thing:

public Person(Dictionary dictionary, string someString)
    : base(dictionary, someString)
{
    base.GetProperty("FirstName");
    base.GetProperty("LastName");
}

public Person(Dictionary dictionary, string[] someStringArray)
    : base(dictionary, someStringArray)
{
    base.GetProperty("FirstName");
    base.GetProperty("LastName");
}

The type of the second parameter in each of these constructors determines the behavior of the 'GetProperty' method.

I've read about casting and the bad behaviors of it, but would it be appropriate to do something like  this:

public Person(Dictionary dictionary, Object something)
{
}

and then cast something to either a string or string[] depending on whichever is appropriate?


texts:
This is the basic class that I am trying to display:

public class Day
{
    public DateTime Date { get; private set; }

    public SpecialDay SpecialDay { get; set; }

    public DateTime TimeIn { get; private set; }

    public DateTime TimeOut { get; private set; }

    public DayOfWeek DayOfWeek

    public TimeSpan TotalHours
}

It is contained inside a list in in following class:

public class Month
{
    private int _month { get; set; }
    private int _year { get; set; }

    public DateTime Date

    public List<Day> Days { get; private set; }

    public TimeSpan TotalHoursInMonth
}

This is the load function of the main display form

private void MonthDataForm_Load(object sender, EventArgs e)
    {
        int bottomOfPreviousDay = -1;

        foreach (var item in MonthDisplaying.Days)
        {
            DayView dayDisplay = new DayView(item);

            if (bottomOfPreviousDay == -1)
            {
                dayDisplay.Top = this.Top + 10;
            }
            else
            {
                dayDisplay.Top = bottomOfPreviousDay + 2;
            }

            bottomOfPreviousDay = dayDisplay.Bottom;
            this.Controls.Add(dayDisplay);
        }

        this.WindowState = FormWindowState.Maximized;
    }

The form shows a list of days for a given month like so

Each line is a separate instance of the Day class, and in the next stage of development there will be buttons to perform different actions on each instance.

Is there a better way for calculating the position of the user controls that are being added?  I don't like the way the if/else looks but I am not sure how else to do it.


texts: Sidebar menu to hide or expand parts of a form

texts:
I have some of my code that I have tried to improve on to make it cleaner and efficient and I would like some feedback to see if I am going in the right direction with what I am trying to do.

I have a page with a menu, and when you click on menu item it displays the appropriate fieldset.

HTML:

My Account

Order History

Notifications

        <fieldset id="fs_account_details">

        </fieldset>

        <fieldset id="fs_order_history">

        </fieldset>

        <fieldset id="fs_notifications">

        </fieldset>

My original jQuery to display each fieldset was an individual block of code for each button like this:

// Show account details
$('#list_account_details').click( function(){
    $('fieldset').hide( function(){
        $('#fs_account_details').show();
    });
});

// Show order history
$('#list_order_history').click( function(){
    $('fieldset').hide( function(){
        $('#fs_order_history').show();
    });
});

// Show notifications
$('#list_notifications').click( function(){
    $('fieldset').hide( function(){
        $('#fs_notifications').show();
    });
});

And my improvement was to only have one block of code to display each fieldset like this:

// Show appropriate fieldset
$('#side_bar_menu li').click( function(){

    // Get button id
    var button_id = $(this).attr('data-fieldset-id');

    // Hide any opened fieldsets
    $('fieldset').hide( function(){
        // Show appropriate fieldset
        $(button_id).show();
    });
});

Should I be thinking to automatically write all my code like this, or am I possibly reducing individual functionality of each menu list button by incorporating it all into one block of code like that?

Is my new code even considered an improvement at all?


texts:
Here's some code that removes the specified character, ch, from the string passed in. Is there a better way to do this? Specifically, one that's more efficient and/or portable?

//returns string without any 'ch' characters in it, if any.
#include <string>
using namespace std;
string strip(string str, const char ch)
{
        size_t p = 0; //position of any 'ch'

        while ((p = str.find(ch, p)) != string::npos)
                str.erase(p, 1);

        return str;
}


texts:
WE_ALL_LOVE_SHOUTY_SNAKE_CASE_SO_I_WROTE_A_PROGRAM_FOR_IT!!1!

Alright, enough of this. This is a rags-to-riches from this question. The pattern is pretty simple, it takes a String input, verifies if it is numerical, and if so, converts it to SHOUTY_SNAKE_CASE.

  Example : "1231" -> "ONE_TWO_THREE_ONE"

It is fairly simple but it is also the first time I used the Java 8's streams, so I wanted an opinion on my (simple) use of it.

private static final String[] words =
        new String[]{"zero","one","two","three","four","five","six","seven","eight","nine"};

public static String convertNumbersToWords(final String input) {

    if(input == null || !input.matches("^\\d*$")){
        throw new IllegalArgumentException("input cannot be null or non-numerical.");
    }

    return input.chars()
             .mapToObj(c -> getWordFromCharCode(c).toUpperCase())
             .collect(Collectors.joining("_"));
}

private static String getWordFromCharCode(int code){
    return words[code - 48];
}


texts:
This is a very long solution I've been working on to a Number to Words problem. I've identified that there's a lot of repeating logic (e.g. 'if writing > 0', 'writing = integer /',).

How would you refactor this?
When refactoring is there a process you use?
For readability sake would it be better to break this method into various pieces? Why?

def in_words (integer)
  ones_array = ['zero','one','two','three','four','five','six','seven','eight','nine']
  teens_array = ['blank','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
  tens_array = ['blank','ten','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety']

  result = ""

  #FOR MILLIONS
  writing = integer / 1_000_000
  left_over = integer % 1_000_000

  if writing > 0
    result << in_words(writing) << "million "
    integer = left_over
  end

  #FOR THOUSANDS
  writing = integer / 1000
  left_over = integer % 1000

  if writing > 0
    result << in_words(writing) << "thousand "
    integer = left_over
  end

  #FOR HUNDREDS
  writing = integer / 100
  left_over = integer % 100

  if writing > 0
    result << in_words(writing) << "hundred "
    integer = left_over
  end

  #FOR TENS!!!
  writing = integer / 10
  left_over = integer % 10

  if writing > 0
    if writing == 1 && left_over > 0
      result << teens_array[left_over]
      left_over = 0
    else
      result << tens_array[writing]
    end
  end

  writing = left_over

  #FOR ONES!!!!
  if writing > 0
    result << ones_array[writing]
  end

  result

end

p in_words(4) # => "four"
p in_words(15) # => "fifteen"
p in_words(92) # => "ninety two" or "ninety-two"
p in_words(101) # => "one hundred one"
p in_words(9915) # => "nine thousand nine hundred fifteen"
p in_words(1456789) # =>
    #"one million four hundred fifty six thousand seven hundred eighty nine"


texts:
I have a large number of images that were named in a odd way and because of that, when they're displayed in a file browser, they're completely out of order. However, since they weren't named in a completely random manner, I can use regex to properly rename them, once I understand all the subpatterns that went into it. So far I only understood two.

So I'm going to create a program to verify the pattern of each filename, make a set out of it with a sample of each name, and then try to understand the patterns and subpatterns.

def get_pattern(name):
    pattern = []
    for letter in name:
        if letter.isalpha():
            pattern.append('a')
        elif letter.isdigit():
            pattern.append('0')
        else:
            pattern.append(letter)
    return ''.join(pattern)

It's pretty straightforward to loop through the images and then check the pattern for each image.

My questions:

Is there a way to make the code more concise? Maybe using a dictionary?
Is there something in re or other easily available library that does this? Is using isalpha() and isdigit() the way to go here?


texts: Assembly program which detects all numbers with two integral divisors

texts:
For an FASM assembly course I've to do the following exercise:

"Write a program that takes the number n as input. Then it prints all the numbers x below n that have exactly 2 different integral divisors (Besides 1 and x).

For example: 15 is such a number. It is divisible by 1,3,5,15. (Here 3 and 5 are the two different divisiors, besides 1 and 15).

However, 4 is not such a number. It is divisible by 1,2,4."

Full description can be seen here: GitHub xorpd.

Here's the code I've written:

format PE console
entry start

include 'win32a.inc'

; ===========================================
; Write a program that takes the number n as
; input. Then prints all the numbers x below
; n that have exactly 2 different intergral
; divisors (Besides 1 and x).
; Example: 15 : 1, 3, 5, 15 => 3 and 5.
; ===========================================

; ------ Usage example ----------------------
; The first "f" is the number n which was entered by the user.

; C:\Users\michael\Desktop\fasmProgs>divisors
; f
; 6
; 8
; a
; e
; f
; ------------------------------------------

section '.text' code readable executable

start:
    call    read_hex            ; Provided by teacher. Reads in a hexadecimal number from stdin.

    mov     edi,    eax         ; edi becomes the upper limit.
    mov     esi,    5           ; esi becomes the control variable.

outerLoop:
    inc     esi
    mov     ebx,    2           ; ebx becomes the divisor and control variable of the inner loop.
    mov     ecx,    0           ; Counts how many division have been possible.
innerLoop:
    xor     edx,    edx
    mov     eax,    esi
    div     ebx

    cmp     edx,    0
    jne     prepareInnerIteration
    inc     ecx

prepareInnerIteration:
    inc     ebx                  ; Increment the divisor.

    cmp     ebx,    esi          ; Here the control variable acts as the upper limit.
    jl      innerLoop

prepareOuterIteration:
    cmp     ecx,    2
    jne     goToNextIteration

    cmp     esi,    6            ; In case no number was given. Just a blank.
    je      goToNextIteration

    mov     eax,    esi
    call    print_eax            ; Provided by teacher. Prints eax to stdin.

goToNextIteration:
    cmp     esi,    edi
    jl      outerLoop

    push    0
    call    [ExitProcess]

include 'training.inc'

On of the tests I've done:

I enter hexadecimal 1e (decimal 30).

It returns:

6 => Can be divided by 2 and 3. Therefore correct detected.
8 => 2, 4
10 => 2, 5
14 => 2, 7
15 => 3, 5
21 => 3, 7
22 => 2, 11
26 => 2, 13
27 => 3, 9

I would say it works. At least essentially.

Nevertheless:
There might be flaws even bugs in my program. And I guess one could improve it a lot.

So therefore:

Any hints, comments and recommendation by more experienced Assembly programmer very much appreciated.


texts: Fetching data and then writing them to an array

texts:
First I fetch an instance from the database. The three functions getSwitches, getSingle and getLinears need the return value instance.
When all requests are finished I want to fill the array barFrequencyData with the data.

How do I correctly refactor the code? Should I use async/await or promises in this case?

barFrequencyData.datasets[0].data.length = 0;
barFrequencyData.labels.length = 0;
let barFrequencyFill = [{
    label: null,
    value: 0,
}];

let myUser = jwt_decode(localStorage.usertoken);
let myInstance = 0;
getInstance(myUser)
    .then(instance => {
        myInstance = instance.data;
        getSwitches(myInstance)
            .then(res => {
                for (let i = 0; i < res.data.length; i++) {
                    barFrequencyFill.push({
                        label: res.data[i].name,
                        value: res.data[i].counterAmount
                    });
                }
            })
            .catch(err => {
                return err;
            });
        getSingle(myInstance)
            .then(res => {
                for (let i = 0; i < res.data.length; i++) {
                    barFrequencyFill.push({
                        label: res.data[i].label,
                        value: res.data[i].value
                    });
                }
            })
            .catch(err => {
                return err;
            });
        getLinears(myInstance)
            .then(res => {
                for (let i = 0; i < res.data.length; i++) {
                    barFrequencyFill.push({
                        label: res.data[i].name,
                        value: res.data[i].distance,
                    })
                }
            })
            .catch(err => {
                return err;
            });
        return barFrequencyFill;
    })
    .then(barFrequencyFill => {
        for (let i = 0; i < barFrequencyFill.length; i++) {
            barFrequencyData.datasets[0].data.push(barFrequencyFill[i].value);
            barFrequencyData.labels.push(barFrequencyFill[i].label)
        }
    })
    .catch(err => {
        return err;
    });


texts:
Is it OK to mix different lifetime of ISerializer and ICacheProvider in this case? I am using Unity DI. In this case, whenever ICacheProvider is needed, Unity will always give the same instance (singleton) but ISerializer will always be a new instance. I am not sure if it would be OK to have ISerializer as a singleton as well in an ASP.NET Web API environment.

public class MyCacheProvider : ICacheProvider
{
   private readonly ISerializer _serializer;

   public MyCacheProvider(ISerializer serializer)
   {
       _serializer = serializer;
   }
}

Serializer implementation:

public class JilSerializer : ISerializer
    {
        public string Serialize<T>(T instance)
        {
            return JSON.Serialize(instance);
        }

        public T Deserialize<T>(string input)
        {
            return JSON.Deserialize<T>(input);
        }
    }

Configuring DI Container to provide instances:

container.RegisterType<ISerializer, JilSerializer>();
            container.RegisterType<ICacheProvider, MyCacheProvider>(new ContainerControlledLifetimeManager());


texts:
I have an unusual data structure that I need to search - the structure is the result of parsing a JSON file returned from an HTTP request.

The top-level object is an Array, but from top to bottom I have Array->Hash->Array->Hash.

I'm writing code to check the value of a given key in the innermost hash, across the entire data structure.

As it stands, my code is like this:

json = JSON.parse(File.read(file))
json.each do |hash1|
  hash1.keys.each do |key|
    hash1[key].each do |inner_hash|
      # search in the inner hash
    end
  end
end

I know this is ugly. I know there are better ways to iterate over collections and to combine selections together. I'm just not sure what I should do in this instance given the repeated sliding from array to hash.

What I'm Searching

In the above code, I have the search snipped out. My goal with this iteration structure is to skim through entries (the hashes at the entry_id level) for various conditions and either immediately act on or return the Hash object when the conditions are met. For example, if the condition is that field1 contains something, I might want to return

[
  {
    "entry_id": 544,
    "field1": "something",
    "field2": "something else",
    "field3": 456
  },
  {
    "entry_id": 546,
    "field1": "something!",
    "field2": "something else!",
    "field3": 012
  }
]

Example of Data Structure

[
{
  "12345": [
    {
      "entry_id": 543,
      "field1": "value",
      "field2": "other value",
      "field3": 123
    },
    {
      "entry_id": 544,
      "field1": "something",
      "field2": "something else",
      "field3": 456
    }
  ],
  "23456": [
    {
      "entry_id": 545,
      "field1": "new value",
      "field2": "other new value",
      "field3": 789
    },
    {
      "entry_id": 546,
      "field1": "something!",
      "field2": "something else!",
      "field3": 012
    }
  ]
}
]


texts:
I've created a simple application for mobile users, they can login using provided API but must have limitation on the devices, so the requirement is simple :

  User cannot login using more than 2 devices

I'm building the API using laravel for mobile apps, so I've created the function and it works correctly and wrote test and it works fine you can find the full code here.

But I would like to know what are you guys think of this code :

public function isLoginValid2($user_id,$device_id){

        $deviceLimit = 2;

        //retrive device or create new one if doesnt exist
        $params = [
            'user_id' => $user_id,
            'device_id' => $device_id
        ];

        $device = Device::where($params)->first();

        if (!$device) {

            // check if not exceed limit
            if (Device::where(['user_id'=>$user_id, 'is_banned'=>false])->count() <= $deviceLimit) {
                return true;
            }else{
                // the device is above llmit
                return false;
            }

        }else {
            // check if banned
            if ($device->is_banned) {
                // the device is banned user is not pemmitted to login
                return false;
            }else{
                return true;
            }
        }

    }

As for the code above if we take a look there are some code line that we can modify or move to create another function.

The reason why I did it because I can make a unit test case on every function and make sure everything is work. so the code above I've modified it and become like this :

public function isLoginValid2Refactored($user_id,$device_id){
        if($this->isDeviceExistWithUser($user_id,$device_id)){
            //device is exist check if its banned
            if($this->isDeviceBanned($device_id)){
                return false;
            }else{
                return true;
            }
        }else{
            //device is not exits check device limit
            if($this->isUserReachLimitDevice($user_id)){
                //user reach limit device
                return false;
            }else{
                return true;
            }
        }
    }

So from here I created another function called isDeviceExistWithUser and isUserReachLimitDevice any better idea to write testable?  Or any better improvement so I others can read it easily?


texts:
I wrote this algorithm which takes input data from something like a CSV file or a large array that contain a series of String elements in the format of "count, FQDN" and then adds or increments the count of each domain component up to the complete FQDN. For example:

// Sample output (in any order/format):
// getTotalsByDomain(counts)
//   1320    com
//   900    google.com
//   410    yahoo.com
//    60    mail.yahoo.com
//    10    mobile.sports.yahoo.com
//    50    sports.yahoo.com
//    10    stackoverflow.com
//     3  org
//     3  wikipedia.org
//     2  en.wikipedia.org
//     1  es.wikipedia.org
//     1  mobile.sports
//   1  sports

let counts = [ "900,google.com",
    "60,mail.yahoo.com",
    "10,mobile.sports.yahoo.com",
    "40,sports.yahoo.com",
    "300,yahoo.com",
    "10,stackoverflow.com",
    "2,en.wikipedia.org",
    "1,es.wikipedia.org",
    "1,mobile.sports" ];

I was able to do this pretty well with the below algorithm, but I am concerned with the inner for loop which uses var 'j'. I felt like the only way that I could incrementally parse the domain components from the already split array was to create another array which unshifted the domain components to partially create a new array until I completed all of the components of the given FQDN element.

function getDomainHits(arr){

  var splitCount = [];
  var domainCountDict = {};

  for (var i = 0; i < arr.length; i++){

    splitCount = arr[i].split(",");

    var curCnt = 0;
          if (splitCount[0]){

            curCnt = splitCount[0];

          }

    var domain = [];
    var currentDom = [];
          if (splitCount[1] != undefined && splitCount[1]){

            domain = splitCount[1].split(".");

            for (var j = domain.length - 1; j >= 0; j--){

               currentDom.unshift(domain.pop());

               /*console.log("current iter: " + k + "\n"
                           + "currentDom: " + currentDom.join(".") + "\n"
                           + "current count: " + curCnt + "\n");*/

              if (currentDom.join(".") in domainCountDict){
                /*console.log("currentDom2: " + currentDom.join("."));
                console.log("increment existing");*/
                domainCountDict[currentDom.join(".")] += parseInt(curCnt);

              }
              if (!(currentDom.join(".") in domainCountDict)){
                /*console.log("currentDom3: " + currentDom.join("."));
                console.log("increment new");*/
                domainCountDict[currentDom.join(".")] = parseInt(curCnt);

                //console.log(domainCountDict);
              }

            }

          }

  }

  return domainCountDict;

}

console.log(getDomainHits(counts));

If you want to see a complete walkthrough of my logic then you can see my answer to my question in Stack Overflow


texts: PDO prepared statement to insert data into MySQL

texts:
I am changing all mysqli queries to use PDO now and just want to make sure I'm doing it right.  Here is an old one:

$sql = "INSERT into profile (profileid, name, description) values ('$profileid', '$name', '$description')";
        $sql= mysqli_query($connection,$sql);
        if (!$sql) {
        die("Database query failed: " . mysqli_error($connection));
        } else {
        redirect_to('/my-account');
        }

And here is how I rewrote it:

$stmt = $pdo->prepare("INSERT into pools (profileid, name, description) values (:profileid, :name, :description)");

$stmt->execute([':profileid' => $profileid, ':name' => $name, ':poolname' => $poolname, ':description' => $description]);

redirect_to('/my-pools');

It seemed to work fine when I tested, just want to make sure I did EVERYTHING right.  Does it all look good?

Also, prior to my old mysqli query, I would do this to "sanitize" the data:

$description = mysqli_real_escape_string($connection,$_POST['description']);

With PDO, I do NOT have to have that AT ALL anymore, is that correct?  Just want to confirm before I delete all the escaping stuff from my code after switching to PDO.


texts:
I have a rating system where users can vote between 1-6. I'd like to normalize the votes a bit to better accommodate for extreme voting, where individuals tend to vote as high or as low as possible. To do this, I have the following algorithm which seems to work well. However, it's extremely inefficient and not very well written.

What might I do to improve it?

protected function calculateWeightedAverage($ratings)
{
    $values = array_values($ratings);
    sort($values);

    $count = count($values);
    $weights = array_fill(0, $count, 1);

    $out = (int) ($count / 3);
    $out2 = pow($out + 1, 2);

    $max = $count - 1;
    $min = 0;

    for ($i = 0; $i < $out; $i++) {
        $j = $i + 1;
        $weights[$min + $i] = $j * $j / $out2;
        $weights[$max - $i] = $j * $j / $out2;
    }

    $sum = array_sum($weights);

    for ($i = 0; $i < $count; $i++) {
        $weights[$i] /= $sum;
    }

    $rating = 0;
    for ($i = 0; $i < $count; $i++) {
        $rating += $values[$i] * $weights[$i];
    }

    return $rating;
}


texts:
The program is running immensely slow even when moving around for only a small amount of distance. When zooming, I can't get any deeper of it and even if I can my computer starts lagging and I have to terminate it by force.

The program outputs the Mandelbrot set correctly but I can't really be sure if my computation is right and maybe that's what causing it very very slow.
Can you please review my code in terms of efficiency and how should I make it fast?.

My computer specs are:

CPU: Intel i5-4590 3.30Ghz

GPU: Intel HD Graphics 4600

RAM: 8GB

 #include <SFML\Graphics.hpp>

    using namespace sf;

    int mandelSet(double dx, double dy, double c_Re, double c_Im, int maxIterator);
    Color  setPixelColor(int z, int maxIterator);

    int main()
    {
        unsigned int width = 700;
        unsigned int height = 700;

        double minRe = -1.2;
        double minIm = -2.0;
        double maxRe = 1.2;
        double maxIm = 2.0;
        float zoom = 1;

        double re = (maxRe - minRe) / (width);
        double im = (maxIm - minIm) / (height);

        const int maxIterator = 7000;

        sf::RenderWindow window(sf::VideoMode(width, height), "Mandelbrot set");

        Image image;
        image.create(width, height, sf::Color(0, 0, 0.0, 0));

        Texture texture;
        texture.loadFromImage(image);
        Sprite sprite(texture);
        sf::Event event; Keyboard keyboard;

        while (window.isOpen())
        {

            while (window.pollEvent(event))
            {
                if (event.type == sf::Event::Closed)
                    window.close();
            }

            if (keyboard.isKeyPressed(keyboard.E))
            {
                zoom *= .9;
            }

            for (size_t y = 0; y < height; y++)
            {
                // transform cartesian coordinate Y to Imaginary complex number or scale Y
                double c_Im = ((y * im) + minIm) * zoom;

                for (size_t x = 0; x < width; x++)
                {
                    // transform cartesian coordinate X to Real complex number or scale x
                    double c_Re = ((x * re) + minRe) * zoom + minRe;
                    double dy = 0, dx = 0;

                    int z = mandelSet(dx, dy, c_Re, c_Im, maxIterator);
                    Color color = setPixelColor(z, maxIterator);
                    image.setPixel(x, y, color);
                }
            }
            texture.update(image);

            window.clear();
            window.draw(sprite);
            window.display();
        }
        return 0;
    }

Methods:

  int mandelSet(double dx, double dy, double c_Re, double c_Im, int maxIterator)
    {
        int z = 0;
        while (dx * dx + dy * dy < 4 && z < maxIterator)
        {
            double temp = ((dx * dx - dy * dy) + c_Re);
            dy = 2 * dx * dy + c_Im;
            dx = temp;
            z++;
        }
        return z;
    }

  Color setPixelColor(int z, int maxIterator)
    {
        Color color;
        if (z == maxIterator)
        {
            color = Color::Black;
        }
        else
        {
            color.r = z % 255 * z % 255;
            color.g = z % 255 * z % 255;
            color.b = z % 255;
        }
        return color;
    }

worst_mandelbrot_ever.jpg


texts: Utilize loop or other efficient way to find string and copy offset columns to certain cells

texts:
I am trying to find certain strings in MasterSheet and copy offset columns (3 columns) values in the specific columns in receiver sheet. So far i have this code doing exactly what i want to do

Sub FindString()

Dim MasterSheet As Workbook     'Master sheet where data is coming from
Dim WSLHD As Worksheet          'Slave sheet receiving the data from mastersheet
Dim Findstring1 As Range        'Transfer <= 30 minutes
Dim Findstring2 As Range        'End of Month Performance (EMP)

Set MasterSheet = Workbooks.Open("\\mypath\test.xlsx")
Set WSLHD = ThisWorkbook.Worksheets("WSLHD")

'list of strings which will be searched for (this are just examples, there are many more strings)

Set Findstring1 = MasterSheet.Sheets("sheet1").Cells.Find(what:="Transfer <= 30 minutes")
Set Findstring2 = MasterSheet.Sheets("sheet1").Cells.Find(what:="End of Month Performance (EMP)")

'copy values from offset columns
WSLHD.Range("B8").Value = Findstring1.Offset(0, 1).Value
WSLHD.Range("C8").Value = Findstring1.Offset(0, 2).Value
WSLHD.Range("F8").Value = Findstring1.Offset(0, 3).Value

WSLHD.Range("B9").Value = Findstring2.Offset(0, 1).Value
WSLHD.Range("C9").Value = Findstring2.Offset(0, 2).Value
WSLHD.Range("F9").Value = Findstring2.Offset(0, 3).Value

MasterSheet.Close

end Sub

.. but i want to do this in more efficient way..i did try to use filter but that will be again filtering and choosing texts one by one so wont be any difference in terms of efficiency. Any help will be appreciated.


texts:
This is the fifth project in my CS1 class.  It's a bit more drab than my past projects, so my titles are getting worse unfortunately. :(

  Write a program that computes the annual after-tax cost of a new house
  for the first year of ownership.  The cost is computed as the annual
  mortgage cost minus the tax savings.  The input should be the price of
  the house and the down payment.  The annual mortgage cost can be
  estimated as \$ 3\% \$ of the initial loan balance credited toward
  paying of the loan principal plus \$ 6\% \$ of the initial loan
  balance in interest.  The initial loan balance is the price minus the
  down payment.  Assume a \$ 35\% \$ marginal tax rate and assume that
  interest payments are tax deductible.  So, the tax savings is \$ 35\% \$
  of the interest payment.  Your program should use at least two
  function definitions and should allow the user to repeat this
  calculation as often as the user wishes.

I may have cheated a bit with my required two function definitions...

mortgage.cpp:

/**
 * @file mortgage.cpp
 * @brief Computes the annual after-tax cost of a new house
 * @author syb0rg
 * @date 10/9/14
 */

#include <cctype>
#include <iostream>
#include <limits>

/**
 * Makes sure data isn't malicious, and signals user to re-enter proper data if invalid
 */
long double getSanitizedDouble()
{
    long double input = 0.0L;
    while(!(std::cin >> input) || input < 0)
    {
        // clear the error flag that was set so that future I/O operations will work correctly
        std::cin.clear();
        // skips to the next newline
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Invalid input.  Please enter a positive number: ";
    }
    return input;
}

/**
 * Safetly grabs and returns a lowercase version of the character (if the lowercase exists)
 */
char32_t getSanitizedChar()
{
    // absorb newline character (if existant) from previous input
    if(std::cin.peek() == '\n') std::cin.ignore();
    return std::tolower(std::cin.get());
}

int main()
{
    do
    {
        long double housePrice = 0.0L;
        long double downPayment = 0.0L;

        // get input for house price, re-read input if not a positive number
        std::cout << "Enter the price of the house: $";
        housePrice = getSanitizedDouble();

        // get input for down payment, re-read input if not a positive number
        std::cout << "Enter the down-payment: $";
        downPayment = getSanitizedDouble();

        long double loanBalance = housePrice - downPayment;
        long double interest = .06 * loanBalance;
        long double annualMortgage = (.03 * loanBalance) + interest;
        long double savings = .35 * interest;
        long double totalCost = annualMortgage - savings;

        std::cout << "The annual after-tax cost of the house is $" << totalCost << std::endl;

        std::cout << "Run the program again (y/N): ";  // signify n as default with capital letter
    } while ('y' == getSanitizedChar());
}


texts:
I have a class with some mandatory properties which I set via constructor, like this (properties omitted for sake of simplicity):

    public SqlDependencyEx(
        string connectionString,
        string databaseName,
        string tableName,
        string schemaName = "dbo",
        NotificationTypes listenerType = NotificationTypes.Insert | NotificationTypes.Update | NotificationTypes.Delete,
        bool receiveDetails = true,
        int identity = 1)
    {
        this.ConnectionString = connectionString;
        this.DatabaseName = databaseName;
        this.TableName = tableName;
        this.SchemaName = schemaName;
        this.NotificaionTypes = listenerType;
        this.DetailsIncluded = receiveDetails;
        this.Identity = identity;
    }

I am trying to use SqlDependencyEx class as a dependency in one of the service like this:

    private readonly IMemoryCache _memoryCache;
    private readonly IAlbumRepo _albumRepo;
    private readonly SqlDependencyEx _listener;
    private readonly string _masterTable = "Armada_Album";
    public AlbumService(IMemoryCache memoryCache, IAlbumRepo albumRepo)
    {
        _memoryCache = memoryCache;
        _albumRepo = albumRepo;
        _listener = new SqlDependencyEx(connectionString: "SERVER=localhost;DATABASE=dbsample;User Id=usr;pwd=cE$6adadZ'[:3;", databaseName: "KEMITEKS", tableName: _masterTable);
    }

The problem is, I don't think it is good to creating a new instance of SqlDependencyEx class in AlbumService class, but at the same time, I want to force consumer of the SqlDependencyEx class to use those properties, since they are all mandatory in order to SqlDependencyEx class to work. So, I don't want to remove those properties and instead of using them in a constructor of SqlDependencyEx class, setting them in separate method etc. I am also using a Ninject as a DI. Is there a better code design to solve this problem, or is it good to leave it as it is?


texts:
I have an immutable Point class and a CollectionPoint class which manages instances of my Point class. The CollectionPoint class owns points under its control and must synchronize concurrent activity. I have below what I think is a thread-safe solution but would like another opinion. Is this solution thread-safe?

class Main {
    public static void main(String[] args) {
        int N = 10;

        double x = 0.0, y = 0.0;

        for(int i=0;i<N;i++) {
            x = (Math.random()*N);
            y = (Math.random()*N);
            Point p = new Point(x,y);
            Thread cp = new CollectionPoint(p);
            cp.start();

            try {
                cp.join();
            } catch(InterruptedException e) {}

        }

    }
}

class CollectionPoint extends Thread{
    // Class Needs to be thread safe
    private List<Point> list = new ArrayList<>();
    Point p;

    public CollectionPoint(Point pi) {
        p = pi;
    }

    public void run() {
        synchronized(this) {
            for(int i=0;i<1;i++) {
                add(p);
            }
        }
        display();
    }

    synchronized void add(Point x) {
        list.add(x);
    }

    synchronized boolean search(Point p) {
        for(int i=0;i<list.size();i++) {
            if(list.contains(p)) {
                return true;
            }
        }
        return false;
    }
    synchronized double getAllX(int x) {
        for(int i=0;i<list.size();i++) {
            if(list.contains(p.x() == x)) {
                return p.x();
            }
        }

        return 0.0;
    }

    synchronized void replace(Point p, Point new_p) {
        for(int i=0;i<list.size();i++) {
            if(list.contains(p)) {
                list.set(i, new_p);
            }
        }
    }

    synchronized void display() {
        for(Point x : list) {
            System.out.println("Point: "+x);
        }
    }
}

final class Point {
    // Class Needs to be thread safe
    private final double x,y;

    public Point(double x0, double y0) {
        x = x0;y = y0;
    }

    public double x() {return x;}
    public double y() {return y;}
    public String toString() {return "("+x+","+y+")";}
}


texts: Generate points for smooth movement between two given points

texts:
This is one of the methods in a project for generating points between two given points. We add points of route with a 25ms delay in an array and a camera on Google Maps is always at the last point. So we need to move it smoothly. This method adds those extra points between any two given points to make it move smoothly.

public List<Tuple<double, double>> GeneratePointsForSmoothMovement(double x1, double y1, double x2, double y2, double divider)
{
    // If points are same, return empty list
    if (x1 == x2 && y1 == y2)
        return new List<Tuple<double, double>>();

    // get difference between x and y cordinates
    double xi = (x2 - x1);
    double yi = (y2 - y1);

    // divide difference into n parts
    xi = xi / divider;
    yi = yi / divider;

    // set new temp vars equal to first point
    double xf = x1;
    double yf = y1;

    // initialize list to save new points
    List<Tuple<double, double>> points = new List<Tuple<double, double>>();

    // increment temp vars by difference-division parts
    for (int i = 0; i < divider; i++)
    {
        xf += xi;
        yf += yi;

        points.Add(Tuple.Create(xf, yf));
    }

    // last cordinate in the list will be equal to point 2
    // return
    return points;
}

Is this the most efficient way ?


texts:
Requirements:

To store strings into variables, check if they are valid for the field.
To be able to easily unit test the validity checks with different parameters.
To throw exception when a check fails
To scale appropiately for dozens of field types
To have a good API for users.
To be expandable.

I have the following code. A class that will hold a fund

Public Class FundElement
    Public Name As New FundDetail
    Public Price As New FundDetail
    Public Code As New CodeDetail
End Class

A base class for each individual data field.

Public Class FundDetail
    Protected _value As String

    Public Property value As String
        Get
            Return _value
        End Get

        Set(valueToAssign As String)
            If isValid(valueToAssign) Then
                _value = valueToAssign
            Else
                Throw New ArgumentException
            End If
        End Set
    End Property

    Shared Function isValid(detail As String) As Boolean
        Return True
    End Function
End Class

And some inherited classes that will hold logic specific to certain fields. This is the reason I wanted a class for rather than just a string for each field. It inherits from FundDetail, but it could have been an interface. I chose inheritance so I could have default implementations.

Public Class CodeDetail
    Inherits FundDetail

    Public Shared Shadows Function isValid(value As String) As Boolean
        Dim intPattern As Regex = New Regex("[a-zA-Z]{3}[0-9]{12}")
        Return intPattern.IsMatch(value)
    End Function
End Class

Now, my problem is that the API for my class is as follows

Dim fund as new FundElement

FundElement.Name.Value = "Google Inc"
FundElement.Code.Value = "USD451234151234"

Which means that coders have access to the NAV element, which I want to hide completely. And the API is more verbose than it needs to be. I want the interface to be as follows

FundElement.Name = "Google Inc"
FundElement.Price = "USD451234151234"

I can implement this by changing the class so that each fundDetail instance is private, and by adding a new property as follows

Public Class FundElement

    Private _Name As New FundDetail
    Public Property Name As String
        Set(valueToAssign As String)
            _Name.value = valueToAssign
        End Set
        Get
            Return _Name.value
        End Get
    End Property

    Private _Code As New FundDetails
    Public Property _Code As String
        Set(valueToAssign As String)
            _Code.value = valueToAssign
        End Set
        Get
            Return _Code.value
        End Get
    End Property

    Private _Price As New PriceDetail
    Public Property _Price As String
        Set(valueToAssign As String)
            _Price.value = valueToAssign
        End Set
        Get
            Return _Price.value
        End Get
    End Property

End Class

Now this ended up very verbose for just 3 members. Additionally, the code for each property was almost exactly the same. It's tedious to type and cluttery to read.

Is there any way I can achieve this without having to type the properties every time I want to add a new member? I feel like I should take a more simple approach. But every simple approach comes with a deficiency I have trouble overcoming.


texts:
Description:

I am building a quiz based learning system in Python. The idea is once a day you have to give this test to improve your learning, it's different from regular rote learning. The user will be shown question first and optionally series of hints, the user then can match his answer to the original answer and honestly gives score to his attempt. I didn't go for programmatically checking the answers because it would be difficult to check semantics of two strings.

Goal:

The end goal is to provide a flexible way to add new questions and hints and add new question types. I am not favour of very fancy UI but something
which feels intuitive should work.

In the long run, I will be integrating it with Slack as a bot.

Code:

from enum import Enum

class Category(Enum):
  CS, MATH, PUZZLE = range(3)

class Score(Enum):
  BAD, OK, GOOD = range(3)

data = [{
  'question': 'What does the fox say?',
  'hints': ['not the sound of cat', 'not the sound of dog'],
  'answer': 'Its a mystery',
  'category': Category.PUZZLE,
  'score': Score.BAD
}, {
  'question': 'What is the worst case run time of binary search of n elements?',
  'hints': [
    'Think about the best case',
    'Would need to search exhaustively until one element'],
  'answer': 'Log(n) base 2',
  'category': Category.CS,
  'score': Score.BAD
}];

def runQuiz(questions, category):
  total = 0
  needHint = '/h'
  for q in filter(lambda q: q['category'] == category, questions):
    answer = input(q['question'])
    if answer == needHint:
      for hint in q['hints']:
        moreHints = input(hint)
        if moreHints != needHint:
          break
    print('Correct answer is: {0}'.format(q['answer']))
    rating = int(input('Rate your solution(1-3): '))
    q.update({'score': rating})
    total += rating
  print('You are done for today, your score is {0}'.format(total))
  return input('Want to start again?(y/*)')

def selectCategory():
  category = input("""
    Select category
      1. Computer Science
      2. Mathematics
      3. Puzzles
      4. Random (Default)
  """)
  selectedCategory = {
    1: Category.CS,
    2: Category.MATH,
    3: Category.PUZZLE
  }.get(int(category), Category.CS)
  return selectedCategory

def main():
  print('Make sure you are not feeling thirsty')
  input()
  print('Clean your surrounding')
  input()
  print('Remember your goal')
  input()
  print('If you need any hint type /h')
  input()
  print('Lets go')
  selectedCategory = selectCategory()
  print('You have selected {0} category'.format(selectedCategory.name))
  print('')
  shouldStartAgain = runQuiz(data, selectedCategory)
  if shouldStartAgain == 'y':
    main()
  else:
    print('You are done for today, sleep well!')

if __name__ == '__main__':
  main()

Note:

Although the current solution doesn't meet all the requirements but it is complete in itself as its fully functional code. Its in early stage of development so I would like to take proper design decisions as soon as possible.

TODO:

Find a way to persist the questions with updated score.
Make the questions with lower score come first.

Questions:

Is there any better way to deal with terminal?
Keeping in mind that I would like to use this system as web service too, what design decisions would be helpful?
It may be too broad, but what good programming practices should I follow, for example when and where to choose objects, enums etc?


texts:
I place various divs on screen by adding random x and y positions successively normalized with this function. My question is, how well is it written? Can I improve it? If so, then how?

I am worried not only about the coding style but also performance since I'm using multiple Math.random()s.

   function normalize(n) {
        var x = 0, i = 0;
        while (i < n) {
            x += Math.random();
            i++;
        }
        return (x / n);
    }


texts: Showing a JDialog whenever there is an exception

texts:
I have made a method which I use to show the exception error through a JDialog window whenever there is one in my program.

For now I can pass it either a String or a subclass of Exception. At first I had two different methods for each one but now I combined them into one.

The showError method:

public static void showError(Object error) {
        String mainMessage = null;
        String title = null;
        if (error instanceof String) {
            mainMessage = (String) error;
            title = "Error!";
        } else if (error instanceof Exception) {
            Exception exceptionError = (Exception) error;
            mainMessage = "Message: " + exceptionError.getMessage()
                    + "\nStackTrace: " + Arrays.toString(exceptionError.getStackTrace());
            title = exceptionError.getClass().getName();
        }

        JOptionPane.showMessageDialog(null, mainMessage, title, JOptionPane.ERROR_MESSAGE);
    }


texts: Return the first recurring character in a string

texts:
The task:

  Given a string, return the first recurring character in it, or null if
  there is no recurring character.

  For example, given the string "acbbac", return "b". Given the string
  "abcdef", return null.

My imperative solution:

function getFirstRecurringChar(str) {
  let i = 0;
  const len = str.length;
  const letters = {};
  while(i < len && !letters[str[i]]) { letters[str[i++]] = true; }
  return i < len ? str[i] : null;
};

console.log(getFirstRecurringChar("acbbac"));

My functional solution:

const getFirstRecurringChar2 = str => {
  const letters = {};
  let lastLetter;
  return Array.from(str).some(x => {
    if(letters[x]) {
      lastLetter = x;
      return true;
    }
    letters[x] = true;
    return false;
  }) ? lastLetter : null;
};

console.log(getFirstRecurringChar2("abcdef"));


texts:
I'm working on improving my Python skills and have been doing a daily code problem. For the problem:

Given a word W and a string S, find all starting indices in S which are anagrams of W

For example s = "abxaba" and w = "ab" should return [0, 3, 4],
s = "cbaebabacd", w = "abc" should return [0, 6]

Is there more efficient/pythonic solution than the code I wrote? Storing the queue as a list and casting it to set twice per loop feels like it must be inefficient.

def anagram_indices(w, s):

  w = set(list(w))

  queue = []
  index = []

  for x, i in enumerate(list(s)):
    queue.append(i)

    while(w.issubset(set(queue[1:]))):
      queue.pop(0)

    if w == set(queue):
      index.append(x-len(w)+1)

  return(index)

word = "ab"
string = "abxaba"

print(anagram_indices(word, string))


texts:
I am developing a project that converts SQL server file to MySQL file based on some assumptions. I have written a function that takes the string source as input and it extracts the database name. Is there any way to improve the code?

public String getDatabaseNameFromMySqlServerFile(String source) {

    String sourceFile = null;
    String databaseName = "";
    Path file = Paths.get(source);
    try (InputStream in = Files.newInputStream(file);
            BufferedReader reader
            = new BufferedReader(new InputStreamReader(in))) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (line.toLowerCase().contains("create database")) {
                String[] Arrline = line.split(" ");
                for (String s : Arrline) {
                    if (!s.toLowerCase().equals("create") && !s.toLowerCase().equals("database")) {
                        databaseName = s;
                        return s;
                    }
                }
            }
            sourceFile = sourceFile + line;
        }
    } catch (IOException x) {
        System.err.println(x);
    }

    return null;
}


texts:
I tried writing my very first template engine today. I designed it to just replace variables in templates, and keep it basic for now. Can anyone give me some constructive criticism?

I'm getting ready to write my own mini framework, and want to improve as much as I can. I just need to know if this is the default way (logic) to write one, or is there a better way?

<?php

class Template {

    public $variables = [];

    public function assign($key, $value) {
        $this->variables[$key] = $value;
    }

    public function render($template, $variables = []) {
        if (empty($variables)) {
            $variables = $this->variables;
        }

        $code = file_get_contents($template);

        foreach ($this->variables as $key => $variable) {
            $code = str_replace('%' . $key . '%', $this->variables[$key], $code);
        }

        return $code;
    }
}


texts: Is there a better way to avoid repeated 'Len == 1' when interpreting booleans from strings?

texts:
My solution to string interpretation is pretty fast. However, I worry about repeated if (Len == 1). That might make the function bigger in the executable. How can I improve my function, to not be as redundant while checking if Len is equal to 1?
#include <ctype.h>
signed char BoolFromStr(const char *const StrIn, register const unsigned char Len) {
    if (!Len || Len > 5 || !StrIn) {
        return -1;
    }
    switch (tolower(*StrIn)) {
        case '0':
            if (Len == 1) {
                return 0;
            }
            break;
        case 'f':
            if (Len == 1 || (Len == 5 && !memcmp(Str+1, (const char[]){'a', 'l', 's', 'e'}, 4))) {
                return 0;
            }
            break;
        case 'n':
            if (Len == 1 || (Len == 2 && Str[1] == 'o')) {
                return 0;
            }
            break;
        case '1':
            if (Len == 1) {
                return 1;
            }
        case 'y':
            if (Len == 1 || (Len == 3 && !memcmp(Str+1, (const char[]){'e', 's'}, 2))) {
                return 1;
            }
            break;
        case 't':
            if (Len == 1 || (Len == 4 && !memcmp(Str+1, (const char[]){'r', 'u', 'e'}, 3))) {
                return 1;
            }
            break;
    }
    return -1;
}


texts: Bloom filter implementation using a BitArray

texts:
I am following the Wikipedia definition of the Bloom filter. My implementation uses the BitArray I created here. Here is an alternative implementation by Ilya Grigorik.

# n = Number of items in the filter
# p = Probability of false positives, float between 0 and 1 or a number indicating 1-in-p
# m = Number of bits in the filter
# k = Number of hash functions

require_relative '../bitarray/bit_array'
require 'digest'

class BloomFilter

  def initialize k: 1, m: 10
    @k = k
    @m = m
    @n = 0
    @b = BitArray.new
  end

  # Probability of a false positive based on formula in wikipedia
  def false_positive_rate
    fp_rate = (1-(1-1/@m.to_f)**(@k.to_f*@n.to_f))**@k.to_f
    p fp_rate
    fp_rate.round(2)
  end

  def insert item
    @n += 1
    @k.times do |n|
      hash_val = Digest::MD5.hexdigest( item.to_s + n.to_s ).to_i(16)
      position = hash_val % @m
      @b.set position
    end
    self
  end

  def include? item
    @k.times do |n|
      hash_val = Digest::MD5.hexdigest( item.to_s + n.to_s ).to_i(16)
      position = hash_val % @m
      return @b.get(position) == 1
    end
    return false
  end

end

The test:

require 'minitest/autorun'
require_relative 'bloom_filter'

class BloomFilterTest < MiniTest::Unit::TestCase

  # Verified probability formula and tests from http://hur.st/bloomfilter?n=1&p=0.01
  def test_stats
    assert_equal 0.01, BloomFilter.new(k: 7, m: 10).insert("a").false_positive_rate
    b = BloomFilter.new(k: 2, m: 29)
    10.times { |n| b.insert(n) }
    assert_equal 0.25, b.false_positive_rate
  end

  def test_include
    b = BloomFilter.new(k: 2, m: 100)
    b.insert "The Trumpet of the Swan"
    assert_equal true, b.include?("The Trumpet of the Swan")
    refute b.include?("E. B. White")
  end

end


texts: Algorithm for dividing a number into largest "power of two" buckets?

texts:
For example, these are expected outputs:
3: 2, 1
4: 4
5: 4, 1
6: 4, 2
7: 4, 2, 1
8: 8
9: 8, 1
...
20: 16, 4
...
25: 16, 8, 1
...
36: 32, 4
...
50: 32, 16, 2

Up to the max of 32 being the largest subunit. So then we get larger:
100: 32, 32, 32, 4
...
201: 32, 32, 32, 32, 32, 32, 8, 1
...

What is the equation / algorithm to implement this most optimally in JavaScript? By optimal I mean the fastest performance, or fewest primitive steps for example, with the least amount of temporary variables, etc. I feel like my solution below is a "brute force" approach which lacks elegance and it seems like it could be optimized somehow. Ideally there would be no Math.floor or division as well, if possible to use some sort of bit magic.

log(20)
log(25)
log(36)
log(50)
log(100)
log(200)

function log(n) {
  console.log(generate_numbers(n).join(', '))
}

function generate_numbers(n) {
  const chunks = count_chunks(n)
  const sum = chunks.reduce((m, i) => m + i, 0)
  const result = new Array(sum)
  const values = [ 1, 2, 4, 8, 16, 32 ]
  let i = chunks.length
  let j = 0
  while (i--) {
    let x = chunks[i]
    while (x--) {
      result[j++] = values[i]
    }
  }
  return result
}

function count_chunks(n) {
  let chunks = [0, 0, 0, 0, 0, 0]
  if (n >= 32) {
    let i = Math.floor(n / 32)
    chunks[5] = i
    n = n - (i * 32)
  }
  if (n >= 16) {
    chunks[4] = 1
    n = n - 16
  }
  if (n >= 8) {
    chunks[3] = 1
    n = n - 8
  }
  if (n >= 4) {
    chunks[2] = 1
    n = n - 4
  }
  if (n >= 2) {
    chunks[1] = 1
    n = n - 2
  }
  if (n >= 1) {
    chunks[0] = 1
  }
  return chunks
}


texts: Check if number is divisible by three and two

texts:
Looks next nested if a little structure redundancy? Any better way for next nested if?
# !/usr/bin/python3

num = int(input("enter number"))
if num%2 == 0:
   if num%3 == 0:
      print ("Divisible by 3 and 2")
   else:
      print ("divisible by 2 not divisible by 3")
else:
   if num%3 == 0:
      print ("divisible by 3 not divisible by 2")
   else:
      print  ("not Divisible by 2 not divisible by 3")


texts:
Please review my class which is responsible of serialization and deserialization of the StringTuple data class.
data class StringTuple(
    val first: String,
    val second: String
)

The idea is to serialize StringTuple to ByteArray in the following format:
| first string size | first string serialized | second string serialized |

Here is the code:

import java.nio.ByteBuffer
import java.nio.charset.Charset

private val charset = Charset.forName("UTF-8")

class StringTupleSerializer {

    fun serialize(value: StringTuple): ByteArray {
        val first = value.first.toByteArray(charset)
        val firstSize = encodeSize(first.size)
        val second = value.second.toByteArray(charset)
        return firstSize + first + second
    }

    private fun encodeSize(size: Int): ByteArray {
        val buffer = ByteBuffer.allocate(Int.SIZE_BYTES)
        buffer.putInt(0, size)
        return buffer.array()
    }

    fun deserialize(byteArray: ByteArray): StringTuple {
        val firstSize = decodeSize(byteArray)
        val withoutFirstSize = byteArray.drop(Int.SIZE_BYTES)
        val first = withoutFirstSize.take(firstSize).toByteArray().toString(charset)
        val second = withoutFirstSize.drop(firstSize).toByteArray().toString(charset)
        return StringTuple(first, second)
    }

    private fun decodeSize(byteArray: ByteArray): Int {
        val buffer = ByteBuffer.allocate(Int.SIZE_BYTES)
        buffer.put(byteArray, 0, Int.SIZE_BYTES)
        buffer.flip()
        return buffer.int
    }
}

I'm looking mainly for the review of correctness of this solution.


texts: How do I make this simple addition code less verbose?

texts:
I really don't get why it has to take so much to make such a little function. Here's what I have.

template <typename A, typename B> auto add(A a, B b) -> decltype(a + b) {
   return a + b;
}

Is there a way to shrink this code while maintaining its ability to take different arguments? For a comparison, here is it in Python; there is a big difference between the two.

def add(a, b):
    return a + b


texts:
Trying to combine functional style (immutable objects) and flexibility of property setters. For the sake of example, let’s say we have a soil types table with two attributes: Color and Name. I am looking for a way to alternate Names, but not Color. Here is how I solved it:

        // retrieving: all objects are immutable
        SoilTypes types = SoilTypes.Default;
        ISoilType clay1 = types.Clay;
        ISoilType clay2 = types[3];

        // derive an alternated immutable copy
        SoilTypes altTypes = types
            .With(tt =>
            {
                // tt.SensitiveFines.Color is still read only
                tt.SensitiveFines.Name = "Very sensitive fines!";
                tt[2].Name = "Purely Organic soil!";
            });

        // retrieving: everything is immutable
        ISoilType sensitiveFines = altTypes.SensitiveFines;

Where this interface is immutable:

public interface ISoilType
{
    Color Color { get; }
    string Name { get; }
}

And this class is mutable:

public class SoilType : ISoilType
{
    public static implicit operator SoilType((Color Color, string Name) tuple) =>
         new SoilType(tuple.Color, tuple.Name);

    internal SoilType(ISoilType source)
        : this(source.Color, source.Name)
    {
    }

    internal SoilType(Color color, string name)
    {
        Color = color;
        Name = name;
    }

    public Color Color { get; }
    public string Name { get; set; }
}

And this non-generic class is immutable:

public class SoilTypes : SoilTypes<ISoilType>
{
    public static SoilTypes Default = new SoilTypes(
        (White, "Undefined"),
        (Red, "Sensitive Fines"),
        (Green, "Organic Soil"),
        (Blue, "Clay"),
        (Orange, "Silty Clay"));

    public SoilTypes(params SoilType[] types)
        : base(types)
    {
    }

    public SoilTypes With(Action<SoilTypes<SoilType>> update)
    {
        var copy = this
            .Select(t => new SoilType(t))
            .ToArray();

        update(new SoilTypes<SoilType>(copy));
        return new SoilTypes(copy);
    }
}

while this generic base used in both situations:

public class SoilTypes<TType> : ReadOnlyCollection<TType>
    where TType : ISoilType
{
    internal SoilTypes(TType[] types)
        : base(types)
    {
    }

    public TType Undefined => this[0];
    public TType SensitiveFines => this[1];
    public TType OrganicSoil => this[2];
    public TType Clay => this[3];
    public TType SiltyClay => this[4];
}


texts: Reads paragraphs of common artists separated by commas

texts:
I want to make this faster, I'm not a great coder and just want to learn. This program reads paragraphs of common artists separated by commas. The user inputs the name of a desired artist and the program searches through the paragraphs to find all related artists and sorts them into order of most common to least common. The artist text file is very large 600kb of text so perhaps that's the reason it's slow.

class ArtistSuggester:
    fileName = "list_of_artists.txt"
    arrayOfLists = []
    artist = input("Enter Artist Name: ")

    @classmethod
    def make_array(cls):
        # sets text to 2D-array
        f = open(cls.fileName, 'r', encoding="utf8")
        curr_par = f.read().split("\n")
        for line in curr_par:
            cls.arrayOfLists.append(line.split(","))

    @classmethod
    def get_locations(cls):
        # searches array for given artist and returns array with areas where the artist was found
        locations = []
        for x in range(0, len(cls.arrayOfLists)):
            for y in range(0, len(cls.arrayOfLists[x])):
                if cls.arrayOfLists[x][y] == cls.artist:
                    locations.append(x)
        return locations

    @staticmethod
    def search_array_for_artist(the_list, artist):
        # searches given array for the given artist's name and returns the position
        # if found nothing returns negative number to symbolize non-existence
        pos = 0
        for x in range(0, len(the_list)):
            if the_list[x] == artist:
                pos = x
                break
            else:
                pos = -1
        return pos

    @classmethod
    def ordered_suggestion_list(cls):
        # makes the final suggestion list in correct order
        # makes two arrays, one with the names and the other with the counts of each throughout the text file.
        check = cls.get_locations()
        final_list = cls.arrayOfLists[check[0]]
        final_list.remove(cls.artist)
        count = [1] * int(len(final_list))
        for x in range(1, len(check)):
            for y in range(0, len(cls.arrayOfLists[check[x]])):
                if cls.arrayOfLists[check[x]][y] == cls.artist:
                    continue
                elif cls.search_array_for_artist(final_list, cls.arrayOfLists[check[x]][y]) > 0:
                    count[cls.search_array_for_artist(final_list, cls.arrayOfLists[check[x]][y])] += 1
                else:
                    final_list.append(cls.arrayOfLists[check[x]][y])
                    count.append(1)
        # makes a dict based off the count and names list to combine values to the keys
        combined_list = dict(zip(final_list, count))
        new_list = []
        for key, value in sorted(combined_list.items(), key=lambda x: x[1], reverse=True):
            new_list.append(key)
        print(new_list)


texts:
Given a smaller strings and a bigger string b, design an algorithm to find all permutations of the shorter string within the longer one.

def findPermutations(large: String, small: String): Int =
    large.sliding(small.length).filter(_.diff(small).isEmpty).length

@ findPermutations("cbabadcbbabbcbabaabccbabc", "abbc")
res11: Int = 7

@ findPermutations("xaabx", "abb")
res12: Int = 0

Archived (faulty)
@ def findPermutations(large: String, small: String): Int =
  large.sliding(small.length)
       .toList
       .filter(_.toSet == small.toSet)
       .length
defined function findPermutations

Please evaluate it for correctness and speed.


texts: Making the basic accumulator in Real World OCaml use Async

texts:
I was going through Real World OCaml and wanted to make the program in "A Complete Program" use Async. It works now, but I'm wondering how idiomatic it is, and if I'm doing anything weird?

open Core.Std
open Async.Std

let read_and_accumulate () =
  Reader.lines (Lazy.force Reader.stdin)
  |> Pipe.filter ~f:(Fn.non String.is_empty)
  |> Pipe.map ~f:Float.of_string
  |> Pipe.fold ~init:0. ~f:(fun x y -> return (x +. y))

let () =
  ignore (read_and_accumulate ()
          >>| printf "Result is %f\n"
          >>| fun () -> exit 0);
  ignore (Scheduler.go ())

Also, I feel like I should be able to Fn.compose return (+.) for the Pipe.fold line but it doesn't work. Why not?


texts: Project Euler+ #35 - Summing circular primes less than N

texts:
Overview

The following code is a solution for a Project Euler+ problem on Hackerrank. A circular prime is a prime number whose rotations are also prime. For example, 197 is a circular prime since it and all it's rotations (197, 971, 719) are prime.

The sum of all circular primes less than 100 is:

sum(2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, 97) = 446

Code Redability

After learning about list comprehensions in python, I'm concerned that my code readability may have taken a nosedive. I'd like to make my code as understandable as possible so that someone reading it could quickly deduce the strategy I used to solve the problem.

I'm mostly concerned with my generate_circular_primes_less_than function as it goes 5 nested blocks deep and seems to be more confusing than it could be.

Here's the code for my solution:

from math import sqrt, ceil
from functools import reduce

# generates a list of n booleans where indexes correspond to primality
def prime_sieve(n):
    N = [True] * n
    N[0] = False
    N[1] = False
    for i in range(2, int(ceil(sqrt(n)))):
        if N[i]:
            for j in range(i*2, n, i):
                N[j] = False
    return N

# rotates the first i chars of a string to the end
def rotate(s, i):
    return s[i:] + s[:i]

def generate_circular_primes_less_than(n):
    large = 10**len(str(n))
    is_prime = prime_sieve(large)

    for num in range(n):
        if is_prime[num]:
            s = str(num)

            rotations = [int(rotate(s, i)) for i in range(len(s))]

            if reduce(lambda y, x: y and is_prime[x], rotations, True):
                for circular_prime in (r for r in rotations if r < n and is_prime[r]):
                    is_prime[circular_prime] = False # remove duplicates (like 11)
                    yield circular_prime
            else:
                for r in rotations:
                    is_prime[r] = False # no need to recheck non-circular primes

#
# MAIN
if __name__ == "__main__":
    n = int(input())
    print(sum(generate_all_circular_primes_less_than(n)))

However, the pseudocode I wrote when designing my solution is much simpler:

1. sieve all primes less than the maximum rotation value
2. get the rotations for each prime less than n
     if all rotations are prime:
       add the rotations less than n to the sum

Sometimes it seams that adding comments only masks unintuitive code (like putting lipstick on a pig). What would you suggest to improve the readability?


texts:
if(selectedGroup == 0 && model.selectedParameterItem != null)
    {
        foreach (var i in model.selectedParameterItem)
        {
            parameters.Add(db.ParametersMethods.Where(f => f.ID == i).FirstOrDefault());
        }
        methods.AddRange(methodlogicclass.GetMethodFromParameters(parameters));
        ViewBag.methods = convertMethod(method);

        return View(methodModel);
    }

    else if (selectedGroup !=0 && model.selectedParameterItem == null)
    {
        methods = db.Methods.Where(f => f.MethodGroupID == selectedGroup).ToList();
        ViewBag.methods = convertMethod(methods);

        return View(methodModel);
    }

    else if(selectedGroup != 0 && model.selectedParameterItem != null)
    {
        List<Methods> groupMethods = db.Methods.Where(f => f.MethodID == selectedGroup).ToList();
        foreach (var i in model.selectedParameterItem)
        {
            parameters.Add(db.ParametersMethods.Where(f => f.ID == i).FirstOrDefault());
        }
        List<Methods> parameterMethods = methodlogicclass.GetMethodsFromParameters(parameters);

        foreach(var methods1 in groupMethods)
        {
            foreach(var methods2 in parameterMethods)
            {
                if(methods1.ID == methods2.ID)
                {
                    methods.Add(method2);
                }
            }
        }

        ViewBag.methods = convertMethods(methods);

        return View(methodModel);
    }

So I'm trying to create a searchmenu, with multiple options that don't necessarily have to be selected. However, search results obviously have to meet every option selected.

What would be the best way to write code like this, with the least amount of duplication, while keeping into account that model.selectedParameterItem (for instance) can be null and thus can't be used. Right now the code isn't closed for modification at all, which is far from optimal.

WHat would be best practice in a case like this? Check for each element if it is null, then get the results for each of them seperatly, then merge all the results?

Code explained:

Search by group => search for methods by group
Search by parameter => search for methods by parameters
Etc, more will be added
When searching for both, only return the methods that meet both group and parameter requirement (and in the future, other requirements).
Group can be empty (0), list of parameters can be empty (null).
Future added requirements will be able to be empty (null)


texts:
I have the following method which creates a like for a post:

def create
  post.likes.create(user: current_user)
  respond_to do |format|
    format.html { redirect_to post_redirect(post) }
    format.js
  end
end

We don't really care whether the create was successful or not and either redirect the user to the post (the page where the method is called) or return some js if done via AJAX (usually).

The js partial looks like:

// create.js.erb
$("#content").html("<%= j render(:partial => 'likes/like_button') %>");

However I didn't like that it expects the AJAX request to request JS and then having a partial render inside a jQuery method that then makes an assumption about #content existing to render it inside. So effectively the response is also handling how it should be used.

My alternative approach was:

def create
  post.likes.create(user: current_user)
  request.xhr? ? (render :partial => 'likes/like_button') : (redirect_to post_redirect(post))
end

This way we just return the partial or redirect depending on if the request was via AJAX.

The former seems to be the standard Rails approach (according to most docs) but I find the latter far cleaner as it means I can handle how the response is handled as it just returns HTML rather than having the actual handling of the response being returned with the response.

Is there a better way to handle AJAX responses? Or reasons why my approach would be considered bad practice? Of course using the first approach means using Rails UJS and my own uses custom JS to make the request and handle the response.


texts: Need to pass cookie information to a child iFrame - Are there any security concerns?

texts:
I have a child iframe in my page that will load content from a different web application in a different virtual directory than the parent page.

The DOM will look roughly like this:

The user will log in to www.contoso.com/WebApp1.
The user will load www.contoso.com/WebApp1/Home which contains an iframe with content from www.contoso.com/WebApp2/Home.
To load content from www.contoso.com/WebApp2/Home the user must be logged in.

My Question:

Could I simply load the iframe with src=www.contoso.com/WebApp2/Home?sessionId={sessionIdFromTheParentCookie}, and write server-side code to trust the incoming sessionId and set a cookie for the child iframe?
At present, I can't see how this is any worse than the reality that a user could tamper with his/her client-side cookie an insert an arbitrary sessionId in it.
The sessionId must always be validated at the server, so what's the harm in supplying an arbitrary sessionId in the query string and asking the server to set the cookie?


texts: A utility class for running up to two Tasks serially, where the last task to be queued "wins"

texts:
Edit: Use cases for this class - I needed this class in the case where I had processes I needed to execute (in the form of tasks - they were all asynchronous) that I needed to issue to a UI control when certain events occurred. However, these events are something I dont control and can sometimes occur in close succession. This class is used to make sure only the last event to have issued the task will "win" and run the task only once.

This class lets you run multiple tasks serially. If a task is already running (Task1), the next task (Task2) is "queued". However, if, before Task1 completes, Task3 is executed, it will replace Task2 and will be executed next.

The class is NOT thread safe.

/// <summary>
/// Lets you run multiple tasks serially. If a task is already running (Task1), the next task (Task2) is "queued". However, if,
/// before Task1 completes, Task3 is executed, it will replace Task2 and will be executed next.
/// THe class is NOT thread safe.
/// </summary>
public class LastTaskWins
{
    private object m_pendingToken;
    private Task m_currentTask;

    public async Task<bool> TryRunAsync(Func<Task> taskFunc)
    {
        bool result = true;

        // If there is no task running, just run the one queued.
        if (m_currentTask == null)
        {
            await ExecuteTaskNowAsync(taskFunc);
        }
        else
        {
            // Save a token so we know if we can run.
            object token = m_pendingToken = new object();

            // Make sure the current task completes.
            await m_currentTask;

            // Check to see if a new task has been "queued".
            result = token == m_pendingToken;
            if (result)
            {
                // If we can run (we own the last-queued task token), run the new task.
                await ExecuteTaskNowAsync(taskFunc);
            }

        }

        return result;
    }

    /// <summary>
    /// Helper method. Will run the relevant task, maintaining class state.
    /// </summary>
    private async Task ExecuteTaskNowAsync(Func<Task> taskFunc)
    {
        m_currentTask = taskFunc();
        await m_currentTask;
        m_currentTask = null;
    }
}


texts:
I'm looking for some feedback on my first Javascript app. I've built an app that calculates tax for Australian tax payers. Specific feedback on areas that could be object orientated and any errors I have made would be great.

//Inputs
var income = 250000;
var superAnnuationPercentage = 9.25;
var superAnnuationTaxRate = 15;

//Defines the tax brackets
var taxBracket = [
    {from: 0, to: 18200, percentage: 0, amount: 0},
    {from: 18201, to: 37000, percentage: 19, over: 18200, amount: 0},
    {from: 37001, to: 80000, percentage: 32.5, over: 37000, amount: 3752},
    {from: 80001, to: 180000, percentage: 37, over: 80000, amount: 17547},
    {from: 180001, to: Infinity, percentage: 45, over: 180000, amount: 54547}
];

//Defines HECS/HELP repayment brackets
var hecsHelp = [
{from:0,     to:53345, percentage:4},
{from:53344, to:59421, percentage:4},
{from:59422, to:65497, percentage:4.5},
{from:65498, to:68939, percentage:5.0},
{from:68940, to:74105, percentage:5.5},
{from:74106, to:80527, percentage:6.0},
{from:80258, to:84481, percentage:6.5},
{from:84482, to:92970, percentage:7.0},
{from:99070, to:99069, percentage:7.5},
{from:99070, to:Infinity, percentage:8.0},
];

//Calculates superannuation based on a percentage
var superannuationCalc = function (int) {
    var percent = superAnnuationPercentage/100;
    return  int * percent;
};

//define income after removing superannuation element. Superannuation is taxed at a lower rate.
var grossIncome = income - superannuationCalc(income);

//The end result of alll the code.
var workoutTax = taxCalc(grossIncome);

//bringing it all together
function workOutSuperTax(){
var a = superannuationCalc(income);
var b = superAnnuationTaxRate;
var c = superannuationTaxCalc(a,b);
return c;
}

var superTax = workOutSuperTax();

var workOutHECS = hecsHelpCalc(income);

totalTax = workoutTax + superTax + workOutHECS;

//The end result!
console.log(totalTax);

//Loops through taxBracket object and finds the tax bracket for the post deduction gross income amount
function taxCalc(grossSuperIncome){
    for(var x = 0; x < taxBracket.length; x++){
        if(grossSuperIncome <= taxBracket[x].to){
            var amountOver = grossSuperIncome - taxBracket[x].over;
            var percent = taxBracket[x].percentage / 100;
            return taxBracket[x].amount + (amountOver * percent);

        }

    };
};

//calculates super tax amount by usuing superTaxRate and superAnnuation variables
function superannuationTaxCalc(superAmount,superTaxRate){
    var percent = superTaxRate / 100;
    return superAmount * percent;
};

//calculates HECS bracket
function hecsHelpCalc(hecsIncome){
        for (var x =0; x < hecsHelp.length; x++){
            if(hecsIncome <= hecsHelp[x].to){
            var percentage = hecsHelp[x].percentage / 100;
            return hecsIncome * percentage;
            }
        };
};


texts: Minimum number of coins problem using dynamic programming - follow up

texts:
I previously posted a code here. It turns out that the code is not following the correct dynamic programming principles and instead it was based on a greedy approach. Hence, I started again, keeping in mind helpful guidelines from here and here. I would now like to know if my code is efficient, or if it can be further optimized in terms of time and space complexity.

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

int i , no_of_denominations , denominations [ 10000 ] , total_cost , cost [ 10000 ] ;

int min ( int idx )
{
    int min_cost = 99999 , j ;
    cost [ 0 ] = 0 ;
    for ( j = 0 ; j < no_of_denominations ; j++ )
    {
        if( ( i >= denominations [ j ] ) && ( min_cost > cost [ i - denominations [ j ] ] ) )
        {
            min_cost = cost [ i - denominations [ j ] ] ;
        }
    }
    return min_cost ;
}

void input()
{
    printf ( "Coin Change with min no. of coins\nEnter the total change you want: " ) ;
    scanf ( "%d" , &total_cost ) ;

    printf ( "Enter the no. of different denominations of coins available: " ) ;
    scanf ( "%d" , &no_of_denominations ) ;

    printf ( "Enter the different denominations in ascending order: \n" ) ;
    for ( i = 0 ; i < no_of_denominations ; i++ )
    {
        scanf ( "%d" , &denominations [ i ] ) ;
    }
}

void calc_print ()
{
    for ( i = 1 ; i <= total_cost ; i++ )
     {
         cost [ i ] = 1 + min ( i ) ;
     }

     printf ( "min no of coins = %d" , cost [ total_cost ] ) ;
}

int main()
{
    input () ;
    calc_print () ;
    return 0;
}


texts:
I am using a sieve to return all primes under N:

def prime_gen(n):
    a = [x for x in range(2, n+1)]
    for b in range(2, round(n**.5)):
        c = 2
        while b*c <= n:
            if b*c in a:
                a.remove(b*c)
            c += 1
    return(a)

Is the conditional if b*c in a iterating through the list again? Without using a different algorithm entirely, how do I make this code more efficient and pythonic?


texts:
In my code, I'm trying to manipulate data for an audit between 3 sheets in a workbook.The first block of my code is to paste the data of items I need to find for the audit from the original sheet onto the 3rd sheet by setting each row equal to the data of the original row in the first sheet. The second block is used to re-paste the data of found objects in the Audit to only have values rather then formulas.Then the code will iterate through the Audit list to check for the same values and delete those values on the list in the 3rd sheet. The 2nd sheet will have the list of found audit items being pasted in at the same time. The end result is 3 sheets, 1st being just the main list where all the data is collected, the 2nd being a list of found audit items, and the 3rd being left over items that need to be found at a later date. The code works and has a few kinks in it where the screen would be buzzing because of all of the activate lines so I was wondering if there were better ways to manipulate data between different sheets in a workbook.

Sub Update_Audit()
    Dim j As Integer
    Dim i As Integer
    Dim k As Integer
    Dim Aud_Tot As Integer
    i = 2
    Aud_Tot = Application.InputBox("How big is your audit", , , , , , , 1)
    k = 2
    Worksheets(1).Activate
    Do While Cells(k, 24) <> ""
        Tab_Data = Range(Cells(k, 24), Cells(k, 44)).Value
        Worksheets(3).Activate
        Range(Cells(k, 1), Cells(k, 21)).Value = Tab_Data
        Worksheets(1).Activate
        k = k + 1
    Loop
    Do While Cells(i, 1).Value <> "" And Not IsError(Cells(i, 2).Value)
        Dataset = Range(Cells(i, 1), Cells(i, 22)).Value
        Range(Cells(i, 1), Cells(i, 22)).Value = Dataset
        Worksheets(2).Activate
        Range(Cells(i, 1), Cells(i, 22)).Value = Dataset
        Worksheets(1).Activate
        For j = 2 To Aud_Tot
            If CStr(Cells(j, 24).Value) = CStr(Cells(i, 2).Value) Then
                Worksheets(3).Activate
                Range(Cells(j, 1), (Cells(j, 22))).Delete Shift:=xlShiftUp
                Worksheets(1).Activate
                Exit For
            End If
        Next j
        i = i + 1
    Loop
End Sub


texts:
The code I wrote performs a mean blur on an image (I hardcoded it as zebra.jpg for testing purposes).
My problem is that for an image of 39KB image it take minutes to perform, is there any way of making this code more efficient?
Preferably using built in python modules.
Also is there any way of improving my code in other ways?

from PIL import Image
img = Image.open('zebra.jpg')

img_w = img.size[0]
img_h = img.size[1]

# The bigger the kernel size, the more intense the blur
kernel = [[1]*10]*10

outputIm = Image.new("RGB", (img_w, img_h))
d = []
for y in range(0, int(img_h)):
    for x in range(0, int(img_w)):
        r, g, b, count = 0, 0, 0, 0
        index_y = int((len(kernel[0]) - 1) / 2.0) * -1

        for kernel_offset_y in kernel:
            index_x = int((len(kernel_offset_y) - 1) / 2.0) * -1

            for kernel_val in kernel_offset_y:

                if img_w > x + index_x+1 > 0 and img_h > y + index_y+1 > 0:
                    temp_r, temp_g, temp_b = img.getpixel((int(x + index_x), int(y + index_y)))
                    r += temp_r * kernel_val
                    g += temp_g * kernel_val
                    b += temp_b * kernel_val
                    count += 1
                    index_x += 1
            index_y += 1

        if (r > 0):
            r = r / count
        if (g > 0):
            g = g / count
        if (b > 0):
            b = b / count

        d.append((r,g,b))

outputIm.putdata([tuple(pixel) for pixel in d])
outputIm.save('blurred.jpg')