texts: Am I reconstructing the buffers correctly

texts:
I am writing a networked audio application that sends the audio in 320 byte chunks, later I need to provide the player a bigger amount of bytes to play so I try to merge 2 or more chunks into one buffer and return it, well the code works but I hear some small audio artifacts, any ideas if the code is correct?

-(NSData*) getRawBufferWithSize:(int) requestedBufferSize
{
    if(audio.isBuffering && audio.bufferTimer>[[NSDate date] timeIntervalSince1970] && !AUDIO_BYPASS_NET)
    {
        return nil;
    }
    audio.isBuffering = NO;
    int readyBufferSize = 0;
    int bytesPending = requestedBufferSize;

    if(returnBufferSize<requestedBufferSize)
    {
        returnBuffer = (char*)realloc(returnBuffer, requestedBufferSize);
        returnBufferSize = requestedBufferSize;
    }

    while (readyBufferSize<requestedBufferSize)
    {
        NSData* newBuffer;
        @synchronized(playbackRawBuffer)
        {
            if([playbackRawBuffer count] != 0)
            {
                newBuffer = [[playbackRawBuffer objectAtIndex:0] retain];
                [playbackRawBuffer removeObjectAtIndex:0];
            }
            else
            {
                break;
            }
        }
        char* bytes = (char*)[newBuffer bytes];

        int readableBytes = newBuffer.length;
        int amountOfBytesToRead = bytesPending;
        int amountOfBytesToSaveForLater = 0;

        if(readableBytes<amountOfBytesToRead)//if we can read less than we want
        {
            amountOfBytesToRead = readableBytes;
        }
        else if(readableBytes>amountOfBytesToRead)//if we can read more bytes than we want (we save the remaining bytes)
        {
            amountOfBytesToSaveForLater = readableBytes - amountOfBytesToRead;
        }

        bytesPending -= amountOfBytesToRead;
        memcpy((char*)returnBuffer+readyBufferSize, bytes, amountOfBytesToRead);
        [newBuffer release];

        readyBufferSize+=amountOfBytesToRead;

        if(amountOfBytesToSaveForLater>0)
        {//save these bytes back in the buffers array
            if(tBufSize<amountOfBytesToSaveForLater)
            {
                tBuf = (char*)realloc(tBuf, amountOfBytesToSaveForLater);
                tBufSize = amountOfBytesToSaveForLater;
            }
            memcpy(tBuf, &(bytes[amountOfBytesToRead]), amountOfBytesToSaveForLater);
            @synchronized(playbackRawBuffer)
            {
                [playbackRawBuffer insertObject:[NSData dataWithBytes:tBuf length:amountOfBytesToSaveForLater] atIndex:0];
            }
            break;
        }
    }

    if(readyBufferSize>0)
    {
        return [NSData dataWithBytes:returnBuffer length:readyBufferSize];
    }
    else
    {
        audio.isBuffering = YES;
        audio.bufferTimer = [[NSDate date] timeIntervalSince1970]+0.1;
        return nil;
    }
}


texts: Check if array A contains all elements of array B and vice versa irrespective of order

texts:
I am trying to check if an Array A contains all the elements of Array B and similarly Array B contains elements of Array A, the order does not matter.

Some examples:

A               B                Result
{1}             {0}              false
{0, 0, 0}       {0, 0, 0}        true
{17, 4, 11}     {4, 17, 11}      true

I have written the following code:

public static bool CheckEquality(int[] a, int[] b)
{
    return Array.TrueForAll(a, m => b.Count(z => m == z) == a.Count(z => m == z)) && a.Length == b.Length;
}

Both arrays contain just integers. Both arrays should strictly contain the same number of the same elements, and their lengths should be equal.

Is there a better and efficient way to do this?


texts: Calculating an object's stopping distance

texts:
I'm trying to smooth the movement of a cursor which has a set acceleration and max speed. I wrote this function to calculate the stopping distance of an object given its speed and acceleration, and it works, but it seems a little ridiculous.

function getStoppingDist(speed, accel) {
  var dist = 0;
    while (speed > 0) {
    dist += speed;
    speed -= accel;
  }
  return dist;
}

If the speed is 5 and acceleration is 1, its stopping distance is 5+4+3+2+1 = 15.

Surely there's a better way of doing this. What am I missing?


texts: changing from function based view to class based view in Django

texts:
This is my attempt to convert my password reset function based view to a class based view. Please suggest improvements.
This is my function based view
from django.contrib.auth.views import password_reset, password_reset_confirm

def reset(request):
    return password_reset(request, template_name='login/reset.html',
        email_template_name='login/reset_email.html',
        subject_template_name='login/reset_subject.txt',
        post_reset_redirect=reverse('success'))

TO change this view to the class based view I have to written this
class ResetPassword(View):
    def get(self, request):
        return password_reset(self.request, template_name='login/reset.html',
            email_template_name='login/reset_email.html',
            subject_template_name='login/reset_subject.txt',
            post_reset_redirect=reverse('success'))
    def post(self, request):
        return password_reset(self.request, template_name='login/reset.html',
        email_template_name='login/reset_email.html',
        subject_template_name='login/reset_subject.txt',
        post_reset_redirect=reverse('success'))


texts:
We are given a map of sides of length n and m (both n and m are less than 1000), divided into n*m fields (squares of side 1). The map looks (for example) like this:

. z x . x
. x x . .
. . x . x
x . . n .

Here n=4 and m=5. We start from the field with "z" and we have to get to the field with "n". Suppose we are at position (x, y). Then, we can only move to fields with coordinates: (x+1, y+2), (x+1, y-2), (x-1, y+2), (x-1, y-2), (x+2, y+1), (x+2, y-1), (x-2, y+1), (x-2, y-1).

The next restriction is that we can only move to fields with "." (or "n") - we must avoid fields with "x". We have to compute the smallest number of moves required to get from the field with "z" to the field with "n" (if it's impossible, we have to output "NO"). The correct answer for the given sample map is 3.
My program works as follows: we input the map, then we represent it as graph - and then we run the breadth-first search. As far as I've tested, my program outputs correct values.

My biggest concern is that I use too much memory. Also, I wonder if there's a better method for solving such problems.

Here's the code:

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

int n, m, start, finish;

vector <int> graph[990000];

bool visited[990000];

int mydistance[990000];

queue <int> myqueue;

void BFS(int s){

    mydistance[s]=0;

    myqueue.push(s);

    while (!myqueue.empty()){

        if (visited[finish]){

            return;

        }

        int u=myqueue.front();

        myqueue.pop();

        for (int i=0; i<graph[u].size(); i++){

            if (!visited[graph[u][i]]){

                mydistance[graph[u][i]]=mydistance[u]+1;

                myqueue.push(graph[u][i]);

            }

        }

        visited[u]=true;

    }

}

int main(){

    cin >> n >> m;

    char map[n][m];

    for (int i=0; i<n; i++){

        for (int j=0; j<m; j++){

            char x;

            cin >> x;

            map[i][j]=x;

        }

    }

    for (int i=0; i<n; i++){

        for (int j=0; j<m; j++){

            int a=i*m+j;

            if (map[i][j]=='z'){ start=a; }
            if (map[i][j]=='n'){ finish=a; }

            if ((j<m-1) && (i<n-2)) { if (map[i+2][j+1]!='x'){ graph[a].push_back(a+2*m+1); }} // x+1 y+2
            if ((j<m-1) && (i>1)) { if (map[i-2][j+1]!='x'){ graph[a].push_back(a-2*m+1); }} // x+1 y-2
            if ((j>0) && (i<n-2)) { if (map[i+2][j-1]!='x'){ graph[a].push_back(a+2*m-1); }} // x-1 y+2
            if ((j>0) && (i>1)) { if (map[i-2][j-1]!='x'){ graph[a].push_back(a-2*m-1); }} // x-1 y-2
            if ((j<m-2) && (i<n-1)) { if (map[i+1][j+2]!='x'){ graph[a].push_back(a+m+2); }} // x+2 y+1
            if ((j<m-2) && (i>0)) { if (map[i-1][j+2]!='x'){ graph[a].push_back(a-m+2); }} // x+2 y-1
            if ((j>1) && (i<n-1)) { if (map[i+1][j-2]!='x'){ graph[a].push_back(a+m-2); }} // x-2 y+1
            if ((j>1) && (i>0)) { if (map[i-1][j-2]!='x'){ graph[a].push_back(a-m-2); }} // x-2 y-1

            mydistance[a]=-1;

        }

    }

    BFS(start);

    if (mydistance[finish]==-1) {

        cout <<  "NO";

    } else {

        cout << mydistance[finish];

    }

    return 0;

}


texts:
MVC 5 doesn't seem to like JavaScript that much.
I am creating link in JavaScript to a success method in my Ajax call.

Razor:

@Html.ActionLink("Amount", "Action", "Controller", new { id1 = "a", id2 ="b"}, new { target = "_blank"})

JavaScript:

$('#element').html('' + data[1] + '');

This link works, but, I am not sure it's the best solution. Tried with a onclick method on the element instead, and with a separate method for handling the link, but still doesn't really get around this replacing.

And if it has more parameters should I just be chaining them?

.replace("__id2__", id2).replace("__id3__", id3).replace("__id4__", id4) etc


texts: Find common items between two collections, and set values in one collection when matched

texts:
I want to find common items between two collection, and set values from one collection to another collection. I am aware of similar posts on the web, but they are different from this post. I want to know if there is a better algorithm or method than my current code below

class Job
{
    public Job(int id)
    {
        this.Id = id;
    }
    public int Id { get; private set; }

    public DateTime DiscountDate;

    //more properties
}

class JobManager
{
    public List<Job> GetJobs()
    {

        //Step 1: initialize the first collection
        List<Job> jobs = new List<Job>()
        {
            new Job(1),  //more other properties initialization
            new Job(2),
            new Job(3),
            new Job(4)
        };

        //Step 2: get second collection (id, and DiscountDate) by ids. The ids might be part or whole of collection in step 1
        List<int> idsForDiscountDate = new List<int> {2, 4}; //all ids must be part or whole of jobs list above, ie 1-4
        DataView dataView = GetDisccountDatesFromdatabaseBy(idsForDiscountDate);  //all rows must be part or whole of jobs list above, ie 1-4

        //Step 3: Find match, and set the value from dataView to jobs when matched.
        foreach (var job in jobs)
        {
            foreach (DataRowView dataRowView in dataView)
            {
                if (int.Parse(dataRowView["ID"].ToString()) == job.Id
                    //&& other logic here
                 )
                {

                   //once matched, it sets the value. This is what I need
                    job.DiscountDate = (DateTime) dataRowView["DiscountDate"];
                    break;
                }
            }
        }

        return jobs;
    }

    //get discount dates from database
    private DataView GetDisccountDatesFromdatabaseBy(List<int> idsForDisccountDate)
    {
        throw new NotImplementedException();

    }
}


texts: Using NSPredicate with NSFetchRequest in a NSFetchedResultsController

texts:
I am learning CoreData and I wanted to have my code reviewed.  As usual, I get something to work, then I attempt to refine it.
I have a data model that consists of an Item entity and a subItem entity.  The Item has a 'to many' relationship with the subItem and subItem has a 'to one' relationship with Item.  Basically Item can have multiple subitems, but subitem can only be tied to one Item.  My initial tableview displays the items and selecting a row segues to a tabbarcontroller that consists of other controllers, one being another tableview.  That tableview displays the subitems of the Item.  This is the code I have in my viewDidLoad:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

NSEntityDescription *subItemEntity = [NSEntityDescription entityForName:@"KFPSubItem" inManagedObjectContext:self.managedObjectContext];

[fetchRequest setEntity:subItemEntity];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"item = %@", self.record];

//add sort descriptors
[fetchRequest setSortDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]]];

//initialize fetchedresultscontroller
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

//configure fetched results controller
[self.fetchedResultsController setDelegate:self];

[self.fetchedResultsController.fetchRequest setPredicate:predicate];

//perform Fetch
NSError *error = nil;
[self.fetchedResultsController performFetch:&error];

if (error) {
    NSLog(@"Unable to perform fetch");
    NSLog(@"%@, %@", error, error.localizedDescription);
}


texts: Filter table with drop down values given multiple constraints

texts:
I have a table that stores drop down list values.
The table looks like this:

id | display_text | value | context | special_case
------------------------------------------------------------
0 | X            | x      | Global  | -
1 | a            | a      | Screen1 | No
2 | b            | b      | Screen1 | No
3 | c            | c      | Screen2 | No
4 | d            | d      | Screen2 | Yes

I have the following constraints

Whether or not a value is spl case depends on another table.
Global is always shown.
If it's screen1, I show - x, a, b
if it's screen2, I show x, c
if it's screen2 + spl case, I show x, c, d

I came up with

(
    select
        *
    from
        MY_TABLE
    where
        context = 'Global'
)
UNION(
select
    *
from
    MY_TABLE
where
    context = 'Screen1' and
    special_case=false
)
UNION(
select
i.*
from
MY_TABLE i,
MY_TABLE_2 r
where
and r.id = 'id'
and i.context = 'Screen1'
and i.spl_case =(
    CASE
        WHEN UPPER( r.cond ) like upper( '%cond%' ) THEN TRUE
    END
)
)

Is there a better way to either write the SQL or re-organize my tables?


texts: Core location background update and upload to server

texts:
I want to upload a user's location to a server to send them a location-sensitive alert, so the location needs to be fairly accurate:

import Foundation
import CoreLocation

protocol LocationServiceDelegate {
    func tracingLocation(currentLocation: CLLocation)
    func tracingLocationDidFailWithError(error: NSError)
}

class LocationService: NSObject, CLLocationManagerDelegate {

class var sharedInstance: LocationService {
    struct Static {
        static var onceToken: dispatch_once_t = 0

        static var instance: LocationService? = nil
    }
    dispatch_once(&Static.onceToken) {
        Static.instance = LocationService()
    }
    return Static.instance!
}

var locationManager: CLLocationManager?
var lastLocation: CLLocation?
var delegate: LocationServiceDelegate?

override init() {
    super.init()

    self.locationManager = CLLocationManager()
    guard let locationManager = self.locationManager else {
        return
    }

    if #available(iOS 9.0, *) {
        locationManager.allowsBackgroundLocationUpdates = true
    } else {
        // Fallback on earlier versions
    };

    if CLLocationManager.authorizationStatus() == .NotDetermined {
        // you have 2 choice
        // 1. requestAlwaysAuthorization
        // 2. requestWhenInUseAuthorization
        locationManager.requestAlwaysAuthorization()
    }
    locationManager.desiredAccuracy = kCLLocationAccuracyBest // The accuracy of the location data
    locationManager.distanceFilter = 2000 // The minimum distance (measured in meters) a device must move horizontally before an update event is generated.

    locationManager.delegate = self
}

func startUpdatingLocation() {
    print("Starting Location Updates")
    self.locationManager?.startUpdatingLocation()
}

func stopUpdatingLocation() {
    print("Stop Location Updates")
    self.locationManager?.stopUpdatingLocation()
}

// CLLocationManagerDelegate
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    guard let location = locations.last else {
        return
    }

    // Check if Application is active
        // Check Current View Controller
            // Refresh Weather

    // singleton for get last location
    self.lastLocation = location

    // use for real time update location
    updateLocation(location)
}

func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {

    // do on error
    updateLocationDidFailWithError(error)
}

// Private function
private func updateLocation(currentLocation: CLLocation){
    let todaysDate:NSDate = NSDate()
    let dateFormatter:NSDateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
    let DateInFormat:String = dateFormatter.stringFromDate(todaysDate)

    print(DateInFormat)
    print(currentLocation.coordinate.latitude.description + ", " + currentLocation.coordinate.longitude.description)
    guard let delegate = self.delegate else {
        return
    }

    delegate.tracingLocation(currentLocation)
}

private func updateLocationDidFailWithError(error: NSError) {

    guard let delegate = self.delegate else {
        return
    }

    delegate.tracingLocationDidFailWithError(error)
}
}

This code does work, although I'm not sure how well the location accuracy and update works.  Please review this code.


texts: Largest Triple Products without using sort?

texts:
I implemented the Largest Triple Products algorithm, but I use sort which makes my time complexity O(nlogn). Is there a way to implement it without a temporary sorted array?
The problem:
You're given a list of n integers arr[0..(n-1)]. You must compute a list output[0..(n-1)] such that, for each index i (between 0 and n-1, inclusive), output[i] is equal to the product of the three largest elements out of arr[0..i] (or equal to -1 if i < 2, as arr[0..i] then includes fewer than three elements).
Note that the three largest elements used to form any product may have the same values as one another, but they must be at different indices in arr.
Example:
var arr_2 = [2, 4, 7, 1, 5, 3];
var expected_2 = [-1, -1, 56, 56, 140, 140];

My solution:
function findMaxProduct(arr) {
  // Write your code here
  if(!arr || arr.length === 0)  return [];

  let helper = arr.slice();
  helper.sort((a,b)=>a-b);   // THIS IS THE SORT

  let ans = [];
  let prod = 1;
  for(let i=0; i<arr.length; i++) {
    if(i < 2) {
      prod *= arr[i];
      ans.push(-1);
    }
    else {
      if(i === 3) {
        prod *= arr[i];
        ans.push(prod);
      } else if(arr[i] < helper[0]) {
        ans.push(prod);
      } else {
        const min = helper.shift();
        prod /= min;
        prod *= arr[i];
        ans.push(prod);
      }
    }
  }

  return ans;
}


texts:
I am new in R and I have to implement simulated annealing for schaffer function and I did it. However I am not sure about the correctness of the code.

simulated_annealing <- function(schaffer, step, s0, niter) {
s_n <- s0
iter_count <- 0
for (k in 1:niter) {
    T <- (1 - step)^k
    s_new <- rnorm(2, s_n, 1)
    dif <- func(s_new) - func(s_n)
    if (dif < 0) {
        s_n = s_new
    } else {
        random <- runif(1,0,1)
        if (random < exp(-dif/T)) {
            s_n <- s_new
        }
    }
    iter_count <- iter_count + 1

    print(sprintf("The number of iteration was: %f",iter_count))
    print(sprintf("Function at s_new: %f", func(s_new)))
    print(sprintf("Function at s_n: %f", func(s_n)))
    print(sprintf("Current point: %f", s_n))
    print(sprintf("Temperature: %f", T))
}
return(s_n)
}

schaffer <- function(xx)
{x1 <- xx[1]
x2 <- xx[2]
fact1 <- (sin(x1^2-x2^2))^2 - 0.5
fact2 <- (1 + 0.001*(x1^2+x2^2))^2
y <- 0.5 + fact1/fact2
return(y)
}

It is how the simulated annealing works:

simulated_annealing(schaffer,0.1,c(0,2),10)

Output:

[1] "The number of iteration was: 1.000000"
[1] "Function at s_new: 0.899459"
[1] "Function at s_n: 0.572171"
[1] "Current point: 0.000000" "Current point: 2.000000"
[1] "Temperature: 0.900000"
[1] "The number of iteration was: 2.000000"
[1] "Function at s_new: 0.047084"
[1] "Function at s_n: 0.047084"
[1] "Current point: 1.022082" "Current point: 2.095950"
[1] "Temperature: 0.810000"
[1] "The number of iteration was: 3.000000"
[1] "Function at s_new: 0.153559"
[1] "Function at s_n: 0.047084"
[1] "Current point: 1.022082" "Current point: 2.095950"
[1] "Temperature: 0.729000"
[1] "The number of iteration was: 4.000000"
[1] "Function at s_new: 0.359053"
[1] "Function at s_n: 0.047084"
[1] "Current point: 1.022082" "Current point: 2.095950"
[1] "Temperature: 0.656100"
[1] "The number of iteration was: 5.000000"
[1] "Function at s_new: 0.828496"
[1] "Function at s_n: 0.047084"
[1] "Current point: 1.022082" "Current point: 2.095950"
[1] "Temperature: 0.590490"
[1] "The number of iteration was: 6.000000"
[1] "Function at s_new: 0.075788"
[1] "Function at s_n: 0.075788"
[1] "Current point: 0.344227" "Current point: 0.629732"
[1] "Temperature: 0.531441"
[1] "The number of iteration was: 7.000000"
[1] "Function at s_new: 0.713948"
[1] "Function at s_n: 0.075788"
[1] "Current point: 0.344227" "Current point: 0.629732"
[1] "Temperature: 0.478297"
[1] "The number of iteration was: 8.000000"
[1] "Function at s_new: 0.000717"
[1] "Function at s_n: 0.000717"
[1] "Current point: -0.106265" "Current point: -0.192747"
[1] "Temperature: 0.430467"
[1] "The number of iteration was: 9.000000"
[1] "Function at s_new: 0.844424"
[1] "Function at s_n: 0.000717"
[1] "Current point: -0.106265" "Current point: -0.192747"
[1] "Temperature: 0.387420"
[1] "The number of iteration was: 10.000000"
[1] "Function at s_new: 0.993481"
[1] "Function at s_n: 0.000717"
[1] "Current point: -0.106265" "Current point: -0.192747"
[1] "Temperature: 0.348678"
[1] -0.1062647 -0.1927468

I do not know if it works well and how to estimate the best point - every time it seems that it is the point of last iteration


texts:
About a year ago, I was given a C++ assignment as a preliminary job-interview test.

The assignment included 4 different tasks, from which I had to choose one.

I actually chose and completed 3 out of 4 tasks, but I did not pass the test.

I was not given any specific rejections, so I would like to get an unbiased opinion.

My answer:

File main.cpp:

// --------------------------------
// Input (command-line):
// - Number of beats per bar
// - Number of notes per beat
// - A list of raw beat times
// --------------------------------
// Output (standard):
// - A list of formatted beat times
// --------------------------------

#include <sstream>
#include <iostream>
using namespace std;

static string Compute(int numOfBeatsPerBar,int numOfNotesPerBeat,double beatTime);

int main(int argc,char* argv[])
{
    if (argc < 3)
    {
        cout<<"Invalid Input";
        return -1;
    }

    int numOfBeatsPerBar  = stoi(argv[1]);
    int numOfNotesPerBeat = stoi(argv[2]);

    for (int i=3; i<argc; i++)
    {
        double beatTime = stod(argv[i]);
        string sampTime = Compute(numOfBeatsPerBar,numOfNotesPerBeat,beatTime);
        cout<<beatTime<<' '<<sampTime<<endl;
    }

    return 0;
}

static string Compute(int numOfBeatsPerBar,int numOfNotesPerBeat,double beatTime)
{
    int barId  = (int)beatTime;
    beatTime   = (beatTime-barId)*numOfBeatsPerBar;
    int beatId = (int)beatTime;
    beatTime   = (beatTime-beatId)*numOfNotesPerBeat;
    int noteId = (int)beatTime;

    ostringstream oss;
    oss<<barId+1<<'.'<<beatId+1<<'.'<<noteId+1;
    if (beatTime > 0)
        oss<<'+';
    return oss.str();
}


texts: Rust Book Ch 13 Closures with Generic Parameters and HashMap for memoization

texts:
I have been reading through the rust book. I have made it to chapter 13, at the end of the section called (Storing Closures Using Generic Parameters and the Fn Traits) a couple of improvements are described and left as kind of an exercise.
The task at hand is to change the cache implementation to support not only u32 but any data type and also allow the results to be stored in a hashmap thus allowing us to memoize multiple queries.
I went the route of the everything is copied (since I tried to avoid lifetimes for my first implementation) and I just wanted the feedback from more experienced people on how they would tackle and what pitfall does this version I wrote have.
use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;

struct Cacher<I, O, T>
where
    T: Fn(I) -> O,
{
    calc: T,
    cache: HashMap<I, O>
}

impl<I: Eq + Hash + Copy, O, T> Cacher<I, O, T>
where
    T: Fn(I) -> O
{
    fn new(calc: T) -> Cacher<I, O, T> {
        Cacher {
            calc,
            cache: HashMap::new()
        }
    }

    fn get(&mut self, n: &I) -> &O {
        self.cache.entry(*n).or_insert((self.calc)(*n))
    }
}

fn main() {
    let mut workout = Cacher::new(|x| x + 1);
    println!("{}", workout.get(&4));
    println!("{}", workout.get(&5));
    println!("{}", workout.get(&3));
    println!("{}", workout.get(&4));
}

Another question is where trait are necessary in this case, I realized the compiler doesn't complain if I only put them in the implementation block (but wondered why doesn't it think they are required at the level of the struct since Generic type I has to be both Hashable and Comparable when creating the hashmap right ?)


texts:
I got about 4 days of assembly knowledge, so I need a review on this strcpy function and if it can be done better (at least I have the feeling).

Full code (with the test included):

.data
    s:
        .asciz "Hello world!"

.bss
    .lcomm destination, 4

.text
.globl main
main:
    nop

    pushl $s
    pushl $destination
    call __strcpy
    addl $8, %esp

    pushl $destination
    call puts
    addl $4, %esp

    ret

.globl __strcpy
.type __strcpy, @function
__strcpy:
    movl $0xFFFF, %ecx
    movl 4(%esp), %edi
    movl 8(%esp), %esi

cpy:
    cmpl $0, (%esi)
    je done

    movsb
    loop cpy

done:
    ret

GitHub

Parts that I feel can be optimized:

Because the done label just executes the ret instruction:

cmpl $0, (%esi)
je done

Because the rep instruction-family seems a like better approach:

movsb
loop cpy


texts:
I am an absolute beginner to programming and am learning it using C. I have just learned function pointers and tried to implement a quicksort function using function pointers to determine the nature of sorting.

//Program implementing a quick-sort function using Hoare method
//to partition using a random pivot.
//Function pointer is used to determine the nature of sort (Ascending / Descending).
#include <time.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>

//Typedef: Function Pointer to be used for determining he nature of sort:
typedef int (*p_compare_function)(long long,long long);

enum BOOLEAN{FALSE,TRUE};

//FUNCTION PROTOTYPES:

//Functions to be used for determining the nature of sort:
int Ascending   (long long x,long long y);
int Descending  (long long x,long long y);

//Generates a random number between a lower and a upper limit.
long long my_random(long long min, long long max);

//Functions to be used for the actual functioning of the algorithm:
void my_swap(long long* a, long long* b);

long long quicksort_partition(  long long* array, long long begin,
                                long long end, p_compare_function cmp);

void quicksort( long long* array, long long begin, long long end,
                p_compare_function cmp);

void printarray(long long *pArray, long long nSize);

int main() {

    srand(time(NULL));

    long long array[] = {5,2,9,7,3,1,6,8,4,0,4,3,5,67,22,3,644,335,345,24,
                         33,25,22,5,2,43223,4};

    long long arraysize = sizeof(array)/sizeof(*array);

    //Testing
    quicksort(array,0,arraysize-1,Ascending);
    printarray(array,arraysize);

    quicksort(array,0,arraysize-1,Descending);
    printarray(array,arraysize);

    return 0;
}

void printarray(long long *pArray, long long nSize) {
    for (long long i=0; i < nSize; i++) {
        printf("%lld ",pArray[i]);
    }
    printf("\n");
}

int Ascending   (long long x,long long y) {
    if (x < y) {
        return TRUE;
    }
    else {
        return FALSE;
    }
}

int Descending  (long long x,long long y) {
    return ( !(Ascending(x,y)) );
}

long long my_random(long long min, long long max) {
    long double result;
    result = ((double)rand() / ((double)RAND_MAX + 1.0));
    result = (result * (max - min));
    result += min;
    result = (long long) result;
    return result;
}

void my_swap(long long* a, long long* b) {
    long long temp = *a;
    *a = *b;
    *b = temp;
}

long long quicksort_partition(  long long* array, long long begin,
                                long long end, p_compare_function cmp) {

    //Randomly selecting the pivot.
    long long random_index  = my_random(begin,end);
    long long pivot;
    my_swap(&array[begin],&array[random_index]);
    pivot = array[begin];

    //Partion matheod used : Hoare partition.
    long long i  = begin - 1;
    long long j  = end   + 1;

    while(TRUE) {
        do {
            j--;
        } while (!(cmp(array[j],pivot)) && array[j] != pivot);

        do {
            i++;
        }while ((cmp(array[i],pivot)) && array[i] != pivot);

        if (i < j) {
            my_swap(&array[i],&array[j]);
        }
        else {
            return j;
        }
    }
}

void quicksort(long long* array, long long begin, long long end, p_compare_function cmp) {

    if (begin < end) {
        long long q = quicksort_partition(array, begin, end, cmp);
        quicksort(array, begin  , q, cmp);
        quicksort(array, (q + 1),  end   , cmp);
    }
}

Please point out the bad practises used here and help me to rectify them.


texts: Caching a value just once and update it without blocking other threads

texts:
I need some advice about my code.
The following code will create a new object the first time, and also force other threads to wait for the creation. When the object is created, we return the cached value, and when the value is about to expire, we renew it without blocking other threads, the reference is replaced by the new value.

I'm not sure about the SemaphoreSlim & ManualResetEvet parts, may be somebody can simplify this code.

Thanks.

public class UpdatableLazy<T>
{
    public class Container<T>
    {
        public readonly T Value;

        internal Container(T value)
        {
            Value = value;
        }
    }

    private readonly Func<Task<T>> _updateFunc;
    private readonly Func<T, bool> _isRenewNeeded;
    private volatile Container<T> _container;
    private volatile bool _isUpdating;
    private readonly SemaphoreSlim _ss = new SemaphoreSlim(1, 1);

    public UpdatableLazy(Func<Task<T>> updateFunc, Func<T, bool> isRenewNeeded)
    {
        _updateFunc = updateFunc;
        _isRenewNeeded = isRenewNeeded;
    }

    private readonly ManualResetEventSlim _mre = new ManualResetEventSlim();

    public async Task<T> GetValueAsync()
    {
        //The value doesn't exist yet
        if (_container == null)
        {
            //if a thread is already creating the value, we will wait for the value
            if (!await _ss.WaitAsync(0).ConfigureAwait(false))
            {
                _mre.Wait();
            }

            //After the release of the ManualResetEvent, the value should be available
            if (_container != null)
            {
                return _container.Value;
            }

            try
            {
                //Let's create the value
                _container = new Container<T>(await _updateFunc().ConfigureAwait(false));
                return _container.Value;
            }
            finally
            {
                //We tell awaiting threads that the value is available
                _mre.Set();
                _ss.Release();
            }
        }

        //If the value is not updating and we need to update, we replace the old value by a new one
        if (!_isUpdating && _isRenewNeeded(_container.Value))
        {
            _isUpdating = true;

            try
            {
                _container = new Container<T>(await _updateFunc().ConfigureAwait(false));
            }
            finally
            {
                _isUpdating = false;
            }
        }

        return _container.Value;
    }
}

How I tested it :

class SomeObject
{
    public string Value = "Hello";
    public DateTime Expire = DateTime.UtcNow.AddSeconds(5);
}

class Program
{
    private static int _count;
    static void Main(string[] args)
    {
        var iteration = 10000;
        var cachedObj = new UpdatableLazy<SomeObject>(Create, o => DateTime.UtcNow > o.Expire);
        Parallel.For(0, iteration, new ParallelOptions {MaxDegreeOfParallelism = 2048}, async i =>
        {
            await cachedObj.GetValueAsync().ConfigureAwait(false);
            Interlocked.Increment(ref _count);
        });

        if (iteration != _count)
            throw new Exception("_count and iteration should be equal");

        Console.WriteLine("Done");
        Console.ReadKey();
    }

    static async Task<SomeObject> Create()
    {
        await Task.Delay(1000).ConfigureAwait(false);
        return new SomeObject();
    }
}


texts: Iterating through an array and staying within bounds

texts:
Sorry if this question has been asked before, but I am having trouble searching for the answer I am looking for. This question is in regards to efficiency and overall C# standards.

I have an integer that I manipulate by 1, either by -- or ++ depending on a user's input. I then use this integer as an index to grab an object out of an array. I would like to know what the best way to make sure this variable will always stay within the confines of the array, such that if the user reached the end of the array, it would loop back to the beginning and continue from there. This is an example of the logic I am using for that:

switch(directionMoved)
{
    case MoveDirection.Left:
        currentPageIndex--;
        break;

    case MoveDirection.Right:
        currentPageIndex++;
        break;
}

if (currentPageIndex < 0)
{
    var distanceFromZero = currentPageIndex;
    currentPageIndex = objectArray.Length + distanceFromZero;
}

if (currentPageIndex >= objectArray.Length)
{
    var distanceFromEnd = currentPageIndex - objectArray.Length;
    currentPageIndex = distanceFromEnd;
}

...

(use 'currentPageIndex' to grab from array)

Is there a cleaner way to do this same logic? I hope my questions was clear... =]

Thanks!


texts: ConcurrentLinkedQueue Object Pool implementation

texts:
I have implemented this simple unbounded ObjectPool based on a ConcurrentLinkedQueue of WeakReferences. I have a thread-unsafe object that is pretty expensive to create, and most of the time it will be used from one or two concurrent threads, but it should support any number of threads concurrently. The object has also a large memory footprint, so keeping them in memory indefintely isn't an option.

The pool usage is simple:

ObjectPool<ExpensiveObject> pool = new ObjectPool(ExpensiveObject::new);

try (ObjectPool<ExpensiveObject>.Ref ref = pool.acquire()) {
    ExpensiveObject obj = ref.obj();
    //...
}

I've been using this implementation in production for some time now, but I have never seen any other like that. Most ObjectPool implementations I see are way more complex. I wonder if I'm missing something.

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Supplier;

public class ObjectPool<T> {
    private final ConcurrentLinkedQueue<Ref> queue = new ConcurrentLinkedQueue<>();
    private final Supplier<T> factory;
    private final int maxRetries;

    @SuppressWarnings({"unused", "FieldCanBeLocal"})
    private final List<T> strong;
    //keeping a strong reference to minPoolSize elements to avoid their collection

    public ObjectPool(Supplier<T> factory) {
        this(factory, 1, 5);
    }

    public ObjectPool(Supplier<T> factory, int minPoolSize, int maxRetries) {
        this.maxRetries = maxRetries;
        this.factory = factory;
        this.strong = initMinPool(factory, minPoolSize);
    }

    private List<T> initMinPool(Supplier<T> factory, int minPoolSize) {
        List<T> strong = new ArrayList<>();
        for (int i = 0; i < minPoolSize; i++) {
            try (Ref ref = new Ref(factory.get())) {
                strong.add(ref.obj());
            }
        }
        return strong;
    }

    public Ref acquire() {
        Ref ref = null;

        for (int i = 0; i < maxRetries; i++) {
            ref = queue.poll();

            //either empty pool or valid deref'd object
            if (ref == null || ref.materialize()) break;

            ref = null;
        }

        if (ref == null)
            ref = new Ref(factory.get());

        return ref;
    }

    public class Ref implements Closeable {
        private final WeakReference<T> ref;
        private T obj;

        private Ref(T obj) {
            this.ref = new WeakReference<>(obj);
            this.obj = obj;
        }

        private boolean materialize() {
            this.obj = ref.get();
            return this.obj != null;
        }

        public T obj() {
            return obj;
        }

        @Override
        public void close() {
            if (obj == null) return;
            obj = null;
            queue.offer(this);
        }
    }
}


texts:
So after answering a question about nested linked checkboxes I mentioned it at work and surprisingly it turned out to be similar to something we needed.

The requirements were:

a "Select all" checkbox
a nested "Select all" checkbox (only selects a small portion)
Cannot rely upon the hierarchy of the markup. The given fiddle is an example only. EDIT:- from Discussions with John I now see there was this requirement and so I've added it.

So realising it was different to the aforementioned question I set about writing my own.  I aimed for readability and minimal markup.

(function($) {
    $('input[type=checkbox][data-children]').unbind("change childchange childchangebubble").each(function() {
        var parent = $(this);

        var linkedChildren = $(parent.data("children"));

        //trigger a "childChange" event on the parent when any child is triggered.
        linkedChildren.bind("change childchangebubble", function() {
            parent.trigger("childchange");
        });

        parent.bind({
            "change": function(event) { // Bind change event to check all children
                linkedChildren.prop("checked", parent.prop("checked")).trigger("change");
            },
            "childchange": function() { // have to bind custom event seperately, there seems to be a jQuery bug.
                // When a child is changed recalculate if parent should be checked
                var noChildrenUnchecked = !linkedChildren.is(":not(:checked)");
                parent.prop("checked", noChildrenUnchecked).trigger("childchangebubble");
            }
        });
    });
})(jQuery);

the data-children attributes that are rendered to the page look like: data-children="#child2sub1, #child2sub2" on the parent and nothing extra needed on the children.

I'd love any feedback on readability/maintainability, performance etc.

current jsFiddle.


texts:
I have a contact model, on change I set the state of the contact object, how can I make the below function more readable?
The address field is different because it's an object: ['address', 'city', 'state', 'zip']
  const onFieldChange = (
    key,
    index = 0,
    isMulti = false,
    isAddress = false
  ) => event => {
    const value = event.target.value
    const updatedContact = {...contact}
    if (!isMulti) {
      updatedContact[key] = value
      if (
        key === 'type' &&
        value === 'Individual' &&
        contact.entityFormationDate
      ) {
        delete updatedContact.entityFormationDate
      }
    } else {
      const keyInternal = isAddress ? key : 'value'
      key = isAddress ? 'addresses' : key
      updatedContact[key][index][keyInternal] = value
    }
    setContact(updatedContact)
  }


texts:
I recently tried my hand at writing Go code for a project I'm working on. In order to help myself get a better grasp I decided to write a simple yet somewhat practical program for parsing numeral characters from strings based on the ascii values of the runes within, and appending them to a slice.

My primary concerns with this code are:

It may not be a good solution.
It may not be very performant.
It may not be very idiomatic or reflective of best practices.
It may not be very concise, clean, or readable.

Note: The code below contains the documentation comments. Since this is my first time using Stack Exchange, I'm not entirely certain whether or not this is reasonable and it makes the read a little long.

/*
parseNum package
This is a package which contains a function for converting characters
(charToInt), in the form of runes, into numerals. It also contains a
function for parsing numerals from strings (parseNum).
*/
package main

import (
    "errors"
    "fmt"
)

/*
CharToNum function
This is a function which recieves a rune and converts it to a numeral
based on its ascii code by matching it against the numeral ascii codes
in a for loop. It subtracts 48 from the code to get the actual numeral,
as the ascii codes for numerals are 48-57 and simple subtraction gives
you the actual numeral.
*/
func CharToNum(r rune) (int, error) {
    for i := 48; i <= 57; i++ {
        if int(r) == i {
            return (int(r) - 48), nil
        }
    }
    return -1, errors.New("type: rune was not int")
}

/*
ParseNum function
This is a function which serves the purpose of identifying numerals inside
strings and returning them in a slice. It loops over the string, passing each
character to the charToNum function and identifying whether it should append the
output to the array by testing whether or not the error evaluates to nil.
*/
func ParseNum(str string) []int {
    var nums []int
    for _, val := range str {
        num, err := CharToNum(val)
        if err != nil {
            continue
        }
        nums = append(nums, num)
    }
    return nums
}

func main() {
    fmt.Println(ParseNum("000123456789000"))
}


texts: Selecting three stylesheets in a specific order

texts:
I'm somewhat new to SQL (only had to use it in Database classes). I have a simple table of stylesheets, from which I want to select specific ones in a specific order (e.g. reset, then layout, then colors). Below is an example selector that my current algorithm might generate. Is there a better (more efficient or more intended use of keywords) way to do this?

SELECT *
  FROM `Stylesheets`
  WHERE
    ID = 14

UNION

SELECT *
  FROM `Stylesheets`
  WHERE
    ID = 1

UNION

SELECT *
  FROM `Stylesheets`
  WHERE
    ID = 5
;

See full example on SQLFiddle


texts:
I've been trying several styles of validation code for a form.  I was wondering if this is good or needs some improvement or just trash it and use jQuery validator code?

$("#registration-form").on("submit", function(e) {

    e.preventDefault();
    var error_field = "";

    $(this).find(".input-field").each(function() {

        var field_id = $(this).attr("id");
        var value = $.trim($(this).val());
        var length = value.length;
        var error_value = "";

        // Do field checks
        if (length == 0) {
            error_value = "You missed this field. D:";
        } else if (length > 0 && length < 7) {
            error_value = capitalize(field_id) + " too short";
        } else if (length > 30 && field_id == "username") {
            error_value = capitalize(field_id) + " too long";
        } else if (length > 50 && field_id == "password") {
            error_value = capitalize(field_id) + " too long";
        } else if (passwordCombination(value) === false && field_id == "password") {
            error_value = capitalize(field_id) + " must contain at least one string, number, and symbol.";
        } else if (emailValidate(value) === false && field_id == "email") {
            error_value = "Invalid email! :(";
        }

        // Do show error labels
        if (error_value != null) {
            $("#registration-form .content-row."+ field_id + " .box-error").text(error_value);
            error_field += error_value;
        }
    });

    if (error_field == "") {

        var username = $.trim($("#username").val());
        var email = $.trim($("#email").val());
        var password = $.trim($("#password").val());

        $.ajax({ type: "POST", url: "process/app_usage.php",
            data: { username: username, email: email, process: "validate_user_email" },
            success: function(data) {

                // Do stuff
            }
        });
    }
});


texts: Selecting product variants that satisfy all option criteria

texts:
My current query:

select `t1`.* from `product_variant_values` as t1
inner join (
    select `t1`.* from `product_variant_values` as t1
    where (
    (t1.`option_id` = 1 and t1.`value_id` = 1) or
    (t1.`option_id` = 2 and t1.`value_id` = 4) or
    (t1.`option_id` = 3 and t1.`value_id` = 7) )
    group by t1.variant_id having count(t1.id) = 3
) t2 on t2.variant_id = t1.variant_id

I have this query, and I want to know how I can get rid of the second select and just use a simple join? Here is a link to a picture of my main table: http://prntscr.com/99sxp8 . I set where condition for option_id - value_id pair and want to select those group of rows which have the same variant_id and number of rows is 3.

Update: I do not know the amount of needed rows. I just have an array of needed arguments:

.

The keys are option_id and the value is value_id. These will differ, and I want to select rows which match the arguments, and the number of rows must be equal to the count of options (or count($arguments)) and all rows must have the same variant_id, which is what I'm looking for.

Update 2: Here is the full picture of my tables.

The products table

The Product variants table

Here stock and price will be real numbers.

The Options table

Also I have option_group table, but it consists of just an id and a name. It is as option set. One product will have only one option group.

The table variantable_option_variants

These are values for options.

The product_variant_values table

This table contains all possible combination for option values and parent variant. One example: "red color - s size - long height", matches option_id/value_id set of (1:1, 2:4, 3:7).

I want to find variant_id (from product_variant_values) by a set of combinations of option_id and value_id.

Update 2: The combination for each option, option_id and value_id really exists. They are created when admin saves the option group.

User have dropdown lists for each of the different options. And when he submits the form, I get the combinations of options_id's and value_id's that should be enough to find the variant_id.


texts:
I'm trying to come up with a system to populate my item images on demand, this is what I have so far. One obvious bug is that an item image could be downloaded multiple time since the _image will remain nil until the first download has completed. I could work around this with a loading property.

My main issue is about priority, ideally I would like the images currently visible in the tableview to be downloaded first. ie As soon as the tableview appears it starts downloading the first 20 or so initially visible item.images, but if the users scrolls down to the bottom then items 20-100 all get queued in order which results in the now visible images 80-100 being last to download. Not really sure how to deal with this.

@interface Item : NSObject
@property (nonatomic, strong) UIImage *image;
@end;

@implementation Item

- (UIImage *)image
{
    if (!_image) {

        NSURL *url = [NSURL URLWithString:@"http://loremflickr.com/50/50/paris"];
        NSURLSessionDataTask *imageTask = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            _image = [UIImage imageWithData:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"ItemUpdated" object:self];
            });

        }];
        [imageTask resume];
    }
    return _image;
}

@end

@interface TableViewController : UITableViewController
@property (nonatomic, strong) NSArray *items;
@end

@implementation TableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:100];
    for (int i=0; i<100; i++) {
        Item *item = [[Item alloc] init];
        [items addObject:item];
    }
    self.items = items;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemUpdated:) name:@"ItemUpdated"  object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ItemUpdated"  object:nil];
}

- (void)itemUpdated:(NSNotification *)notification
{
    Item *item = (Item *)notification.object;

    NSUInteger index = [self.items indexOfObject:item];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Item *item = [self.items objectAtIndex:indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.imageView.image = item.image;
    cell.textLabel.text = [NSString stringWithFormat:@"Item %d", indexPath.row];

    return cell;
}

@end


texts: Removing synchronization from an agent for a trading system

texts:
Is there any way to easily remove synchronization from this code, when there is a validation step before acquiring a lock?

I tried an AtomicReference<Pair<Integer, Double>> to hold the state. But that complicates the algorithm a lot because I have to use compareAndSet() in accept(), and then if that returns false, I have to redo the checks for isFinished(), isAboveDailyLimit(), aboveTradingLimit().

import wojtek.events.*;
import wojtek.tinytype.CounterParty;
import wojtek.tinytype.DailyLimit;
import wojtek.tinytype.TradeValue;
import wojtek.tinytype.TradingLimit;

import java.time.Clock;
import java.time.ZonedDateTime;

public class CheckTradeAgent {
    private final CreditCheckAPI creditCheckAPI;
    private final Clock clock;
    private final CounterParty counterParty;
    private final TradingLimit tradingLimit;
    private final DailyLimit dailyLimit;
    private final CheckTradeEventListener eventListener;

    private final Object limitAndFinishLock = new Object();
    private int utilisedDailyLimit;
    private boolean finished;

    public CheckTradeAgent(CreditCheckAPI creditCheckAPI, CheckTradeEventListener eventListener, Clock clock, CounterParty counterParty, TradingLimit tradingLimit, DailyLimit dailyLimit) {
        this.creditCheckAPI = creditCheckAPI;
        this.clock = clock;
        this.counterParty = counterParty;
        this.tradingLimit = tradingLimit;
        this.dailyLimit = dailyLimit;
        this.eventListener = eventListener;
    }

    public void handle(String counterParty, int tradeValue) {
        try {
            handle(new TradeSubmitted(new CounterParty(counterParty), new TradeValue(tradeValue), now()));
        } catch (RuntimeException e) {
            eventListener.onError(e);
        }
    }

    private synchronized void handle(TradeSubmitted trade) {
        if (isFinished()) {
            reject(trade);
            return;
        }

        if (wrongCounterParty(trade)) {
            skip(trade);
        } else {
            if (isAboveDailyLimit(trade)) {
                reject(trade);
            } else {
                if (aboveTradingLimit(trade)) {
                    creditCheck(trade);
                }
                accept(trade);
            }
        }
    }

    private void accept(TradeSubmitted submitted) {
        synchronized (limitAndFinishLock) {
            utilisedDailyLimit = utilisedDailyLimit + submitted.tradeValue.value;
            if (utilisedDailyLimit == dailyLimit.value) {
                this.finished = true;
            }
        }
        eventListener.accepted(new TradeAccepted(submitted, now()));
        if (isFinished()) {
            eventListener.onFinished();
        }
    }

    private void creditCheck(TradeSubmitted submitted) {
        try {
            creditCheckAPI.validate(submitted.counterParty.value, submitted.tradeValue.value);
        } catch (CheckException e) {
            eventListener.onError(e);
        }
    }

    private boolean aboveTradingLimit(TradeSubmitted submitted) {
        return submitted.tradeValue.value > tradingLimit.value;
    }

    private boolean isAboveDailyLimit(TradeSubmitted submitted) {
        return getUtilisedDailyLimit() + submitted.tradeValue.value > dailyLimit.value;
    }

    private boolean wrongCounterParty(TradeSubmitted submitted) {
        return !counterParty.equals(submitted.counterParty);
    }

    private void reject(TradeSubmitted submitted) {
        eventListener.rejected(new TradeRejectedByDailyLimit(submitted, now()));
    }

    private void skip(TradeSubmitted submitted) {
        eventListener.skipped(new TradeSkippedByWrongCounterParty(submitted, now()));
    }

    private ZonedDateTime now() {
        return ZonedDateTime.now(clock);
    }

    public int getUtilisedDailyLimit() {
        synchronized (limitAndFinishLock) {
            return utilisedDailyLimit;
        }
    }

    private boolean isFinished() {
        synchronized (limitAndFinishLock) {
            return finished;
        }
    }
}


texts: Creating an instance of an unit of work (NHibernate)

texts:
I'm trying to figure out how to create a NHibernate UnitOfWork using .NET Core Dependency Injection. I was just hard-coding the connection string before moving it to appsettings.json configuration file. Is this form of creating a UOW in the service.scope valid?

It works, but I'm not sure if this is the intended way to do it.

Startup.cs

services.AddScoped<IUnitOfWork, UnitOfWorkV>( x=> { return new UnitOfWorkV(Configuration); });

UnitOfWorkV.cs

public UnitOfWorkV(IConfiguration configuration)
        {
            _sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(configuration.GetSection("ConnectionStrings:ConexionV").Value))
                .ExposeConfiguration(ConfigureNhibernateValidator)
                .Mappings(m =>
                {
                    m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
                    m.HbmMappings.AddFromAssemblyOf<JobQueue>();
                })
                .BuildSessionFactory();
            Session = _sessionFactory.OpenSession();
            Session.FlushMode = FlushMode.Auto;
        }

appsettings.json

{
  "ConnectionStrings": {
    "ConexionV": "Some connection string"
  }
}


texts: class uploade file(photo,video,..) laravel

texts:
I am working on a project, the previous programmer used this method to save photos, videos, etc.
 if (empty($data['large_image'])) {
$large_image = $article->large_image;} else {
if ($request->hasFile('large_image')) {
    //uploads
    $cover_img_large = $data['cover_img_large'];
    //echo '<pre>'; print_r($cover_path);die;
    if (file_exists($cover_img_large)) {
        unlink($cover_img_large);
    }
    $image_path = $data['large_image'];
    $extension = $image_path->getClientOriginalExtension();
    $New_path = rand(111111, 999999999) . '.' . $extension;
    $path_path = 'upload/articles' . '/' . 'large' . '/';
    $large_image = $path_path . $New_path;
    if (!File::isDirectory($path_path)) {
        File::makeDirectory($path_path, $mode = 0777, true, true);
    }
    Image::make($image_path)->resize(800, 460)->save($large_image);
    //upoload
}}

I intend to use this method, which is close to the structure of the strategy design pattern.
interface Image{
public function image($model,$nameInput,$path);}

class saveArticle implements Image{

private $local_path="upload/articles/";

public function image($model,$nameInput,$path){
    $request = new Request();
    $data = $request->all();
    $path = $this->local_path.$path.'/';

    if (empty($data[$nameInput])) {
        return $model->large_image;
    } else {
        if ($request->hasFile($nameInput)) {
            $image_path = $data[$nameInput];
            $extension = $image_path->getClientOriginalExtension();
            $New_path = rand(111111, 999999999) . '.' . $extension;
            $name_image = $path . $New_path;
            if (!File::isDirectory($path)) {
                File::makeDirectory($path, $mode = 0777, true, true);
            }
            Image::make($image_path)->resize(800, 460)->save($name_image);
            return $name_image;
        }

    }
}}

When I use this method, I have a very simple time to use it and like the following code, I can store information with only one line.
$article = Article::find(1);
$save = new saveArticle();
$save->image($article,'image_large','large');

I have an easier task to develop the code and I can use the same method to add a movie or podcast and just add a new interface.
What is your opinion? Do you think this is the right way? Thank you for guiding me. Your comments are valuable to me.


texts: How to break up long lines of code. (Example Line: Results of method call added to list.)

texts:
Often I generate long lines of code such as the following...

shippedItems.AddRange(OrderItem.Fetch(market: this.MARKET, shipConfirmState: ORDERITEMSHIPCONFIRMSTATE.NONE, orderPlacedAfter: serverTime.AddDays(-7), orderPlacedBefore: serverTime.AddHours(-85)));

... which adds the results of a method call to an existing list.

Adding white space to this line could improve readability. At one point in time or another have rationalized almost every possible behavior between:

Leave everything on a single line and let the editor wrap where it feels is best.
Put even shippedItems.AddRange( on a line by itself.

While over time I feel that the clarity and readability of the code that I write has improved -- and lets hope for reasons other then white space -- I have never come to peace with how to break long lines.

I will up vote any answer that does NOT include as the solution:

shorter variable names.
disregarding named parameters (at least for this example).
creation of variables only used once.


texts:
This method is part of my login system. Could I improve it further?

protected function _hashPassword($password = NULL, $rounds = 1000, $i = 1)
{
    if (! isset($password)) throw new Exception('No password set!');

    $salt   = 'K^^%/m>(|{z= $1^>%>W[=4U5*p|,E';
    $pepper = '08[)^,&%^^771^=>&,E[XP::4})h*I';

    $dinner = $salt.$password.$pepper;

    if ($i >= $rounds) return sha1($dinner);
    return sha1($this->_hashPassword($dinner, $rounds, $i+1).$password);
}


texts: Sort function to sort item numbers separated by colon

texts:
Below is my code. This is a function that will be applied as a sorting method to a grid based data set. The data in the column to be sorted can be stuff like: 123456, 123456:123444, and 12345:12359:139943. So far, I have tested it and it works, but I want to know in which situations might it not work, or if there is a way to optimize/improve the method in any way.

function SkuSorter(a, b, c) {
    // check if either input is a set
    var aMatch = a.match(/\:/g);
    var bMatch = b.match(/\:/g);

    // all items by default should be a regular sku, we'll change this later
    var aType = 0;
    var bType = 0;

    /* types;
     * 0 = regular sku
     * 1 = duo (12345:12345)
     * 2 = trio (1234:1234:1234)
     */

    // has the user sorted asc or desc?
    var direction = c;

    // if 'a' is a set, determine if it is a duo or trio
    if (aMatch) {
        if (aMatch.length == 1) aType = 1;

        if (aMatch.length > 1) aType = 2;
    }

    // save as above
    if (bMatch) {
        if (bMatch.length == 1) bType = 1;

        if (bMatch.length > 1) bType = 2;
    }

    // if 'a' is a set and 'b' isn't, a should come before b (puts sets at the bottom)
    if (aType == 0 && bType != 0) {
        return -1 * direction;
    }

    // save as above, but viceversa.
    if (aType != 0 && bType == 0) {
        return 1 * direction;
    }

    // if both inputs are regular skus, do normal sort operation
    if (aType == 0 && bType == 0) {
        if (direction == -1) {
            return b - a;
        } else {
            return a - b;
        }
    }

    // if 'a' is a set and it is of higher order (i.e. trio > duo)
    if (aType > 0 && aType > bType) {
        return 1 * direction;
    }

    // same as above, but for 'b'
    if (bType > 0 && bType > aType) {
        return -1 * direction;
    }

    // if both inputs are sets
    if (aType > 0 && bType > 0) {

        //break up the individual pieces
        var aP = a.split(':');
        var bP = b.split(':');

        /*
         * The following conditions will compare:
         * The first chunk and sort them based on value
         * Then the second chunk, and if it is a trio, the third.
         */
        if (aP[0] > bP[0]) {
            return 1 * direction;
        }

        if (aP[0] < bP[0]) {
            return -1 * direction;
        }

        // second chunk
        if (aP[1] > bP[1]) {
            return 1 * direction;
        }

        if (aP[1] < bP[1]) {
            return -1 * direction;
        }

        // third chunk
        if (aType > 1 && bType > 1) {
            if (aP[2] > bP[2]) {
                return 1 * direction;
            }

            if (aP[2] < bP[2]) {
                return -1 * direction;
            }
        }
    }
}

Expected behavior:

Before:

1654110
1574698
1189364
1229764
1700004
310425
1626613
36509
1676618
1676832
1536622
1749548
36509:310444
3199:44999:34000
3199:45000:34000
3199:45000:34111
1874361
1551225
1581271
1626076
36509:310425
1676816
1676824

After:

36509
310425
1189364
1229764
1536622
1551225
1574698
1581271
1626076
1626613
1654110
1676618
1676816
1676824
1676832
1700004
1749548
1874361
36509:310425
36509:310444
3199:44999:34000
3199:45000:34000
3199:45000:34111


texts:
Aside: This code assumes a class Option that can be Some or None to represent the presence (Some) or absence (None) of the value it contains.  Haskell calls it Maybe.

Here is my first pass at wrapping Iterator in a thread-safe way:

public synchronized Option<T> nextBlocking() {
    return iter.hasNext() ? Option.of(iter.next())
                          : Option.none();
}

I don't like that it's synchronized - it requires locking in order to work across multiple threads.  On the other hand, if we remove the word synchronized, one thread could call iter.hasNext() which returns true (e.g. for the last item in the Iterator), then a second thread calls iter.next() before the first thread does, using up that last item and causing the first thread to get a NoSuchElementException when it finally calls iter.next().

The following isn't going to win any object-oriented style points, but I think it mostly works around this issue in a non-blocking way:

public Option<T> nextNonBlocking() {
    try {
         return Option.of(iter.next());
    } catch (NoSuchElementException nsee) {
        if(iter.hasNext()) {
            // Oops, exception was thrown for reason other than end-of-iterator.
            // Rethrow that exception.
            throw nsee;
        }
    }
    return Option.none();
}

That could still fail if a nsee is thrown for some reason before end-of-iterator, then another thread reaches the true end-of-iterator before the first thread calls iter.hasNext().  While possible, this situation probably represents a coding failure in the underlying Iterable.  It's very tempting to trade this tiny weakness for a non-blocking iterator wrapper.


texts:
I have been trying to learn JavaScript for the past few days and decided it was time to put what I had learnt into practice.  Here is the program I created. It's a five-question quiz which counts the number of correct questions as you go through the quiz and also ranks you at the end of the program.

//I am going to place a variable here to make initialise the number of correct values at 0
var correct = 0;

// ask questions prompts
var answer1 = prompt("Name a Programming language thats also a gem");
if ( answer1.toUpperCase() === 'RUBY') {
  correct += 1;
}
var answer2 = prompt("Name a Programming language thats also a snake");
if ( answer2.toUpperCase() === 'PYTHON') {
  correct += 1;
}
var answer3 = prompt("What language do we use to style webpages?");
if ( answer3.toUpperCase() === 'CSS' || answer3.toUpperCase() === 'CASCADING STYLE SHEETS') {
  correct += 1;
}
var answer4 = prompt("What language do you use to build the structure of a web page?");
if ( answer4.toUpperCase() === 'HTML' || answer4.toUpperCase() === 'HYPER TEXT MARKUP LANGUAGE') {
  correct += 1;
}
var answer5 = prompt("What core language do you use to add interactivity to a web page");
if ( answer5.toUpperCase() === 'JAVASCRIPT') {
  correct += 1;
}

// OUTPUT RESULTS
document.write("
You got " + correct + " out of 5 questions correct.
");

//output rank

if ( correct === 5 ) {
  document.write("
You earned a gold crown!
");
} else if ( correct >= 3) {
  document.write("
You earned a silver crown.
");
} else if ( correct >= 1) {
  document.write("
You earned a bronze crown.
");
} else {
  document.write("
Sorry, no crown for you. Go home and study.   n
");
}

Have I coded the program with what is considered best practices, and if not, what could I do to improve it?


texts: JS how to optimize function that finds the text value in gematria

texts:
Hello guys i wrote this function code:

function gematria(text){
  var newText = text.toLowerCase(); // handle capital letters
  var startValue=0; //initialize value to zero
  for(let i=0 ; i<newText.length; i++){ // loop through every letter on the text
    let currentCharValue = newText.charCodeAt(i) - 96; // get the distance from the 'a'
    startValue +=currentCharValue;
  }
  return startValue
}

gematria("someText");

it works well but is there any way to do it more short? or better? how good is that code for doing the task?


texts: Project Euler 18/67 : Maximum Path using Memoization

texts:
Problem statement of PE18 is :

By starting at the top of the triangle below and moving to adjacent numbers
on the row below, the maximum total from top to bottom is 23.

   3
  7 4
 2 4 6
8 5 9 3

That is, 3 + 7 + 4 + 9 = 23.

Find the maximum total from top to bottom of the triangle below:

                75
               95 64
              17 47 82
            18 35 87 10
           20 04 82 47 65
          19 01 23 75 03 34
         88 02 77 73 07 63 67
        99 65 04 28 06 16 70 92
       41 41 26 56 83 40 80 70 33
      41 48 72 33 47 32 37 16 94 29
     53 71 44 65 25 43 91 52 97 51 14
    70 11 33 28 77 73 17 78 39 68 17 57
   91 71 52 38 17 14 91 43 58 50 27 29 48
  63 66 04 68 89 53 67 30 73 16 69 87 40 31
 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23

And PE67 is the very same question but,

  NOTE: As there are only 16384 routes, it is possible to solve this problem by trying every route. However, Problem 67, is the same challenge with a triangle containing one-hundred rows; It is not possible to try every route to solve this problem, as there are 2^99 altogether! If you could check one trillion (10^12) routes every second it would take over twenty billion years to check them all. It cannot be solved by brute force, and requires a clever method! ;o)

My Implementation :

public class Euler_18{
// A custom data structure used to store
// the array so that I can seperate the
// logic from the storage
static class TriangularArray{
    HashMap<Integer, int[]> map;
    int someInt;
    int size;
    // All the elements will be stored in
    // HashMap according to their order
    public TriangularArray(int size){
        this.size = size;
        map = new HashMap<Integer, int[]>();
        // Initialise the array
        for(int i=1; i<=size; i++){
            int[] currArray = new int[i];
            map.put(i, currArray);
        }
    }

    // Accept the array
    public void acceptArray(Scanner in){
        for(int i=1; i<=size; i++){
            int[] currArray = map.get(i);
            for(int j=0; j<currArray.length; j++){
                currArray[j] = in.nextInt();
            }
            map.put(i, currArray);
        }
    }

    // Display the array
    public void displayArray(){
        for(int i=1; i<=size; i++){
            int[] currArray = map.get(i);
            System.out.println("Array " + i + " : " + Arrays.toString(currArray));
        }
    }

    // Finds the maximum using Memoization.
    public void findMaximum(){
        for (int i=size-1; i>0; i--) {
            int[] currArray = map.get(i);
            int[] belowArray = map.get(i+1);
            for (int j=0; j<currArray.length; j++) {
                // The value of current element will be the maximum of the 2 values
                // of the array directly below it
                currArray[j] = Math.max(belowArray[j], belowArray[j+1]) + currArray[j];
            }
        }
        System.out.println("The maximum route is of length : " + map.get(1)[0]);
    }
}

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int size = in.nextInt();
    TriangularArray theArray = new TriangularArray(size);
    theArray.acceptArray(in);
    theArray.displayArray();
    theArray.findMaximum();
}
}


texts: Cleanest way to get list of Django objects that have same foreign key and display them in a view

texts:
I am a beginner in Django and would like some advice regarding best practices.

I have the following model:

class Company(models.Model):
    name = models.CharField(max_length=200)

class Interview(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    position = models.CharField(max_length=200)

(I didn't include the __str__ methods for conciseness)

I have the following path:
path('<int:company_id>/', views.detail, name='detail')

Where I want the company to be displayed (let's say its company_id=1, along with all the interview objects that have company=1). So the view should look something like:

Here is my view method:

def detail(request, company_id):
    company = get_object_or_404(Company, pk=company_id)
    return render(request, 'core/detail.html', {'company': company, 'interviews': Interview.objects.filter(company_id=company_id)})

And my detail.html file:

{{ company }}

{% for interview in interviews %}

{{ interview.position }}

{% endfor %}

Which works. However, I am not sure if passing the interviews QuerySet like that is a good practice or not. Is there a way to pass only the company object and get the interviews from that? In general, is there a better way to get a list of objects that have the same foreign key? In this case for example, would it be possible to instead of doing:

Interview.objects.filter(company_id=company_id)

Doing:

company.interviews


texts: Utilizing HTML5 Canvas to apply color theme to .png icons

texts:
Because we have a mix of both icons for core items and .png icons for custom items, I've developed an easy way to theme them (alter the color) all of them easily that will work across all browsers.

Prior to this, I tried CSS and SVG options and they just weren't as simple as this option (but probably less overhead of course). I have to call this after load because of course can't start any canvas work until the items actually hit the DOM and they're parsing through via PHP. There's about 50 of these icons max, more like 25 of them to iterate thought on 90% of users.

Any suggestions on how to streamline this or possibly simplify it? Also I would have posted a test (fiddle or bin) but canvas has a strict cross domain policy.

Update: Found an image on the jsfiddle shell I can use for an example that adheres to the cross-domain policy.

JSFiddle: http://jsfiddle.net/d3c0y/6BSsy/

function changeColor(imgObject, imgColor) {
    // create hidden canvas
    var canvas = document.createElement("canvas");
    canvas.width = 40;
    canvas.height = 40;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(imgObject, 0, 0, 40, 40);

    var map = ctx.getImageData(0, 0, 40, 40);
    var imdata = map.data;

    // convert image to grayscale first
    var r, g, b, avg;
    for (var p = 0, len = imdata.length; p < len; p += 4) {
        r = imdata[p]
        g = imdata[p + 1];
        b = imdata[p + 2];

        avg = Math.floor((r + g + b) / 3);

        imdata[p] = imdata[p + 1] = imdata[p + 2] = avg;
    }

    ctx.putImageData(map, 0, 0);

    // overlay using source-atop to follow transparency
    ctx.globalCompositeOperation = "source-atop"
    ctx.globalAlpha = 0.3;
    ctx.fillStyle = imgColor;
    ctx.fillRect(0, 0, 40, 40);

    // replace image source with canvas data
    return canvas.toDataURL("image/png", 1);
}

jQuery(window).load(function () {
    $('.custom-module').each($.proxy(function () {
        $(this).attr('src', changeColor(this, '#33CC33'));
    }), this).promise().done(function () {
        $('.module-li').removeClass('hidden');
    });
});


texts: Showing/hiding a box containing a Facebook profile

texts:
I see that there are quite some words that are appearing double or more times in my code.

I'm thinking there might be a more efficient way of writing this code, only I don't have the knowledge to do so.

function transitionData(data) {
    if($("div#facebook div#notice").is(":visible")) {
        $("div#facebook div#heading *").fadeOut();
        $("div#facebook div#notice").animate({"opacity":"0"}, function() {
            $("div#facebook div.wrapper > img:first-child").attr("src", "http://graph.facebook.com/"+data.id+"/picture?type=normal");
            $("div#facebook h3").html("Facebook account of "+data.name+"");
            $("div#facebook div#heading a").attr("href", "http://www.facebook.com/"+data.username);
            $("div#facebook tr:first-child td:first-child b").text(data.id);
            $("div#facebook tr:first-child+tr td:first-child b").text(data.first_name);
            $("div#facebook tr:first-child+tr+tr td:first-child b").text(data.last_name);
            $("div#facebook tr:first-child td:first-child+td b").text(data.gender.charAt(0).toUpperCase() + data.gender.slice(1));
            $("div#facebook tr:first-child+tr td:first-child+td b").text(data.locale);
            $("div#facebook tr:first-child+tr+tr td:first-child+td b").text(data.username);

            $("div#facebook div#notice").slideUp();
            $("div#facebook div.wrapper").slideDown();
            $("div#facebook div#heading *").fadeIn();
        });
    } else {
        $("div#facebook div#heading *, div#facebook div.wrapper").fadeOut(function() {
            $("div#facebook div.wrapper > img:first-child").attr("src", "http://graph.facebook.com/"+data.id+"/picture?type=normal");
            $("div#facebook h3").html("Facebook account of "+data.name+"");
            $("div#facebook div#heading a").attr("href", "http://www.facebook.com/"+data.username);
            $("div#facebook tr:first-child td:first-child b").text(data.id);
            $("div#facebook tr:first-child+tr td:first-child b").text(data.first_name);
            $("div#facebook tr:first-child+tr+tr td:first-child b").text(data.last_name);
            $("div#facebook tr:first-child td:first-child+td b").text(data.gender.charAt(0).toUpperCase() + data.gender.slice(1));
            $("div#facebook tr:first-child+tr td:first-child+td b").text(data.locale);
            $("div#facebook tr:first-child+tr+tr td:first-child+td b").text(data.username);

            $("div#facebook div#heading *, div#facebook div.wrapper").fadeIn();
        });
    }
}


texts:
Here is a small program for checking if the parentheses are balanced or not. I am new to the standard library, and this is my first program. How can I improve it?
Any kind of modifications or alternatives and suggestions are welcomed.

#include <iostream>
#include <stack>
#include <string>

using namespace std;

bool checkParentheses(string str, stack<char> s) {
    int flag = 0;
    char top;
    for(int i=0;i<str.length();i++) {
    if(str[i] == '(' || str[i] == '{' || str[i] == '[') {
        s.push(str[i]);
    }
    else {
        if(s.empty()) {
        flag = 1;
        break;
        }
        else {
        top = s.top();
        }
        if(str[i] == ')' && top == '('){
        s.pop();
        }
        else if(str[i] == '}' && top == '{'){
        s.pop();
        }
        else if(str[i] == ']' && top == '['){
        s.pop();
        }
        else {
        flag = 1;
        break;
        }

    }

    }
    if(s.empty() && flag == 0) {
    return true;
    }
    else if (flag == 1) {
    return false;
    }
    else {
    return false;
    }

}

int main() {
    stack <char> s;
    string str;
    cout << "Enter an expression with brackets: " << endl;
    cin >> str;
    cout << str << endl;
    if(checkParentheses(str, s)) {
    cout << "Expression is valid!" << endl;
    }
    else {
    cout << "Expression is not valid" << endl;
    }
}


texts: A program that prints the longest substring of s in which the letters occur in alphabetical order

texts:
Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print

Longest substring in alphabetical order is: beggh

In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print

Longest substring in alphabetical order is: abc

I have been working on a edX course, MITx: 6.00.1x Introduction to Computer Science and Programming Using Python. Encountering the problem mentioned above, I set out to write a piece of code which I found to be the most disgusting to date(excluding Project Euler draft code).
Note: s can be any input, but in my case, edX will automatically input a value for s, so I do not need to define s.
first=0
second=1
strang1=''
strang2=''
while second<len(s):
    if second>=len(s):
        break
    elif s[first]<=s[second]:
        strang1+=s[first:second+1]
        while second<=len(s):
            second+=1
            if second>=len(s):
                break
            elif s[second]>=strang1[-1]:
                strang1+=s[second]
                if len(strang1)>len(strang2):
                    strang2=strang1
            else:
                if len(strang1)>len(strang2):
                    strang2=strang1
                strang1=''
                first=second-1
                break
    else:
        if len(s[first])>len(strang2):
            strang2=s[first]
        first+=1
        second+=1
print("Longest substring in alphabetical order is:" + strang2)

The code can accurately take on any input(if defined) and output it accurately(according to the edX's test runs). I'm looking to make my code more efficient, any suggestions? I'll accept any, fancy newfangled functions or maybe a total rework, I don't mind.


texts:
I am currently writing a C# console application. Part of it is, that the user needs to enter a fairly complex system name. To make it easier I wrote a function that uses a string[] keywords and auto completes the string the user is typing in - on the run (which makes it different to this post in my opinion)

The code is working and acts as expected, but I am curious how the code could be improved (e.g. usability, efficiency). Also, what functionalities are missing, which you'd expect?

Thank you for the feedback!

    class Program
    {
        static void Main(string[] args)
        {
            string[] Keywords = new string[4] { "aX1223", "aE_334", "L_test1", "L_test2" };
            if (Keywords.Length == 0)
                throw new ArgumentException(nameof(Keywords), "No Keywords set!");

            bool searching = true;                 // true while looking for the keyword
            Console.CursorVisible = true;                 // To help users understand where they are typing
            string userInput = "";                   // Initialization of output
            string suggestion = Keywords[0];          // Initialization of default suggestion
            int toClear = suggestion.Length;    // Get the length of the line that needs to be cleared

            while (searching)
            {
                Console.Write(new String(' ', toClear));    // Clear line
                Console.CursorLeft = 0;                     // Relocate cursor to line start
                Console.Write(userInput);                      // Write what has been written previously

                if (suggestion != "")                        // If there is a suggestion fitting the entered string,
                {                                           // complete the string in color and reset the cursor
                    int col = Console.CursorLeft;
                    Console.ForegroundColor = ConsoleColor.Magenta;
                    Console.Write(suggestion.Substring(userInput.Length));
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.CursorLeft = col;
                }

                string tempInput = Console.ReadKey().KeyChar.ToString();

                if (tempInput.Equals("\r"))                 // Evaluate input:
                {                                           //  -> Enter
                    if (!suggestion.Equals(""))             //     Valid entry?
                    {
                        searching = false;
                        userInput = suggestion;           //      -> use suggestion
                    }
                }
                else if (tempInput.Equals("\b"))            // Deleting last sign
                {
                    if (userInput.Length > 0)
                        userInput = userInput.Substring(0, userInput.Length - 1);
                }
                else                                        // Any other sign is added to the string
                    userInput += tempInput;

                // Set length to clear, if suggestion == "", the system string length needs to be cleared
                toClear = (userInput.Length > suggestion.Length) ? userInput.Length : suggestion.Length;

                // Reset suggestion. If no match is found, suggestion remains empty
                suggestion = "";

                // Check keywords for suggestion
                for (int i = 0; i < Keywords.Length; i++)
                {
                    if (Keywords[i].StartsWith(userInput))
                    {
                        suggestion = Keywords[i];
                        break;
                    }
                }
            }

            // reset cursor visibility
            Console.CursorVisible = false;
        }
    }


texts:
Below is the problem taken from Berkeley's Cs61A page here

  Question 9: Insect Combinatorics*

  Consider an insect in an M by N grid. The insect starts at the bottom left corner, (0, 0), and wants to end up at the top right corner, (M-1, N-1). The insect is only capable of moving right or up. Write a function paths that takes a grid length and width and returns the number of different paths the insect can take from the start to the goal. (There is a closed-form solution to this problem, but try to answer it procedurally using recursion.)

  For example, the 2 by 2 grid has a total of two ways for the insect to move from the start to the goal. For the 3 by 3 grid, the insect has 6 diferent paths (only 3 are shown above).

def paths(m, n):
    """Return the number of paths from one corner of an
    M by N grid to the opposite corner.

    >>> paths(2, 2)
    2
    >>> paths(5, 7)
    210
    >>> paths(117, 1)
    1
    >>> paths(1, 157)
    1
    """
    "*** YOUR CODE HERE ***"

This solution is with the knowledge of 'higher order function' and 'recursion'. I've yet to learn data structures and algorithms (if required).

Idea: Started from the destination and found the possibilities. As per the skill level, the solution took 3 hours of my time. Please provide feedback on this.

def paths(m, n):
    """Return the number of paths from one corner of an
    M by N grid to the opposite corner.

    >>> paths(2, 2)
    2
    >>> paths(5, 7)
    210
    >>> paths(117, 1)
    1
    >>> paths(1, 157)
    1
    """
    count_paths = 0
    def find_number_of_paths(x, y):
        if x == 0 and y == 0:
            nonlocal count_paths
            count_paths += 1
            return
        if x > 0:
            find_number_of_paths(x-1, y)
        if y > 0:
            find_number_of_paths(x, y-1)
    find_number_of_paths(m-1, n-1)
    return count_paths

Can we avoid re-assignment operator on count_paths?
Can we avoid nested function definitions?
Is there a name for above solution approach in algorithm world? Any better approach?

Note: As per this assignment, no usage of data model is recommended.


texts: Split an array into m subarrays such that the largest subarray sum is minimized

texts:
This is a Leetcode problem -

  Given an array which consists of non-negative integers and an integer
  m, you can split the array into m non-empty continuous subarrays.
  Write an algorithm to minimize the largest sum among these m
  subarrays.

  Note -

  If n is the length of the array, assume the following constraints
  are satisfied:

  1 ≤ n ≤ 1000
  1 ≤ m ≤ min(50, n)

Here is my solution to this challenge -

class Solution(object):

    def __init__(self, nums, m):
        self.nums = nums
        self.m = m
    def split_array(self, nums, m):
        """
        :type nums: List[int]
        :type m: int
        :rtype: int
        """
        min_res = max(nums)
        max_res = sum(nums)
        low, high = min_res, max_res
        while low + 1 < high:
            mid = low + (high - low)//2
            if self.is_valid(nums, m, mid):
                high = mid
            else:
                low = mid
        if self.is_valid(nums, m, low):
            return low
        return high

    def is_valid(self, nums, m, n):
        count, current = 1, 0
        for i in range(len(nums)):
            if nums[i] > n:
                return False
            current += nums[i]
            if current > n:
                current = nums[i]
                count += 1
        if count > m:
            return False
        return True

Here, I just optimize the binary search method (technique used to search an element in a sorted list), change the condition of low <= high to low + 1 < high and mid = low + (high - low) / 2 in case low + high is larger than the max int.

Here is an example input/output -

output = Solution([7,2,5,10,8], 2)
print(output.split_array([7,2,5,10,8], 2))
>>> 18

Explanation -

There are four ways to split nums into two subarrays.
The best way is to split it into [7,2,5] and[10,8],
where the largest sum among the two subarrays is only 18.

Here is the time for this output -

%timeit output.split_array([7,2,5,10,8], 2)
12.7 µs ± 512 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

So, I would like to know whether I could make this program shorter and more efficient.


texts:
Trying to group elements in a list by the their last element. I think this is a good problem to use groupby() from itertools. Here is my solution:

from itertools import groupby

def match_ends(list1):
    """Returns a dictionary of groups of elements whose end elements match
       Returns empty dic if given list was empty
       Ex: list1 = ["abc", "dbc","aba","baa"]
       matched_ends(list1) = { 'c' : ['abc', 'dbc'], 'a' : ['aba', 'baa'] }
"""
    matched_ends = {}
    list1 = sorted(list1, key = lambda x: x[-1])
    for key, group in groupby(list1, lambda x: x[-1]):
         matched_ends[key] = list(group)
    return matched_ends

Was this a good approach? Am I missing any key points, or any errors I did not forsee that may yield garbage values instead of the program throwing an Error? Is there a quicker way to group elements based on certain criteria that I have yet to see?


texts: Fastest method of getting the bounding box containing all value ranges

texts:
I want to find the fastest method of getting the range object which contains all values in a worksheet, while only containing 1 area. Traditionally one might think this is what UsedRange does, however UsedRange often selects cells outside of the value range.

I believe there is no existing VBA range which will suffice to this criteria alone then so I set out to build my own. I tested 2 versions. The first exploits the SpecialCells() function:

Function ValueBoundingBox(sht As Worksheet) As Range
  'Get used range
  Dim ur As Range
  Set ur = sht.UsedRange

  'If used range is 1x1 then result is 1x1
  If ur.Rows.Count = 1 And ur.Columns.Count = 1 Then
    Set ValueBoundingBox = ur
    Exit Function
  End If

  'Find all non-empty cells
  Dim x As Range
  Set x = Application.Union( _
    ur.SpecialCells(xlCellTypeConstants), _
    ur.SpecialCells(xlCellTypeFormulas) _
  )

  'Loop over all areas
  Dim area As Range, colMin, colMax, rowMin, rowMax, colArea, colAreaMax, rowArea, rowAreaMax As Long

  'Set Initial (Large) values for colMin and rowMin
  rowMin = 1048576
  colMin = 16384

  'Loop over all areas selected by special cells.
  For Each area In x.Areas
    With area
      'Calculate min and max rows/cols of area
      colArea = .Column
      colAreaMax = .Column + .Columns.Count
      rowArea = .row
      rowAreaMax = .row + .Rows.Count

      'Calculate min/max of range based on these values
      If rowAreaMax > rowMax Then rowMax = rowAreaMax
      If rowArea < rowMin Then rowMin = rowArea
      If colAreaMax > colMax Then colMax = colAreaMax
      If colArea < colMin Then colMin = colArea
    End With
  Next

  'Return bounding box
  Set ValueBoundingBox = Range(sht.Cells(rowMin, colMin), sht.Cells(rowMax, colMax))
End Function

The next uses the array of values extracted from a range to determine the minimum and maximum rows:

Function ValueBoundingBox2(sht As Worksheet) As Range
  'Get used range
  Dim ur As Range
  Set ur = sht.UsedRange

  'If used range is 1x1 then result is 1x1
  If ur.Rows.Count = 1 And ur.Columns.Count = 1 Then
    Set ValueBoundingBox2 = ur
    Exit Function
  End If

  'Find via array
  'Get array of all values:
  Dim v As Variant
  v = ur.Value

  'Define required values
  Dim colMin, colMax, rowMin, rowMax, row, col As Long

  'Find min row:
  For row = LBound(v, 1) To UBound(v, 1)
    For col = LBound(v, 2) To UBound(v, 2)
      If Not IsEmpty(v(row, col)) Then
        rowMin = row
        GoTo NextNum
      End If
    Next
  Next
NextNum:
  'Find max row
  For row = UBound(v, 1) To LBound(v, 1) Step -1
    For col = LBound(v, 2) To UBound(v, 2)
      If Not IsEmpty(v(row, col)) Then
        rowMax = row
        GoTo NextNum2
      End If
    Next
  Next
NextNum2:
  'Find min col:
  For col = LBound(v, 2) To UBound(v, 2)
    For row = LBound(v, 1) To UBound(v, 1)
      If Not IsEmpty(v(row, col)) Then
        colMin = col
        GoTo NextNum3
      End If
    Next

  Next
NextNum3:
  'Find max col
  For col = UBound(v, 2) To LBound(v, 2) Step -1
    For row = LBound(v, 1) To UBound(v, 1)
      If Not IsEmpty(v(row, col)) Then
        colMax = col
        GoTo NextNum4
      End If
    Next
  Next
NextNum4:
  Set ValueBoundingBox2 = Range(sht.Cells(rowMin, colMin), sht.Cells(rowMax, colMax))
End Function

Testing the above functions for performance results in the following results:

| Proc name         | Time taken |
|-------------------|------------|
| ValueBoundingBox  | 52s        |
| ValueBoundingBox2 | 1s         |

Clearly the 2nd version I made is far superior than the version which exploits SpecialCells() however I was wondering whether anyone else had any other ideas to speed up the algorithm further?


texts: File-to-fully qualified class name function

texts:
My instincts are telling me a seasoned Scala programmer will find my code less than optimal. As will no doubt be obvious, I'm a Java guy who has just started in with Scala. Is there a more 'functional' way to accomplish this that I'm missing?

/**
   * takes a file object and returns a string representing the fully qualified
   * class name represented by that file.
   *
   * @param file
   * @return string representation of the fully qualified class name
   */
  def makeFqClassName(file: File): String = {
    // pull out the file name - we'll use this for our class name
    val fNameNoExtS = FilenameUtils.removeExtension(file.getName)

    // extract only the path
    val fPathOnlyS =
      file.getPath.substring(0, file.getPath.lastIndexOf(File.separator))

    // create a list of the path name, minus the delimiter
    val fPathDelimList: List[String] = fPathOnlyS.split("/").toList

    // truncate the list to include on the class name info
    val fqNameList: List[String] =
      fPathDelimList.drop(fPathDelimList.lastIndexOf("solutions"))

    // convert the list to a string representation of a class name and return
    // to caller
    fqNameList.mkString(".") + "." + fNameNoExtS
  }

Expected input: .java file object where the file name and the class name enclosed in the file are the same.

  Sp01.scala

Expected output: fully qualified class name:

  solutions.working_with_lists.Sp01

Note that if we were working with one of the problems from another group, the class name would be something like:

  solutions.arithmetic.Sp31

The reason for all this is that I'm new to Scala and working my way through the 99 Scala problems set. This method is part of a test runner that trolls through the project files, picks up solution files, then uses reflection to instantiate an instance of the solution class and executes its solver method. This way I can organize the project files in a way that makes sense - in a way that matches the manner in which the problem set is structured - as well as work on whatever problem I want to work on while simultaneously giving me the freedom to reorganize the package structure w/o having to refactor the runner code.


texts: Project Euler - Smallest multiple (Ruby)

texts:
My code is very slow to run, and I am trying to find a way to make it more efficient. I know there must be a better way than to write each modulo operation.

The goal of the script is to find the smallest possible number than can be divided by numbers 1 to 20 without a remainder.

def divide
  (2..Float::INFINITY).each do |x|
      if x % 2 == 0 && x % 3 == 0 && x % 4 == 0 && x % 5 == 0 && x % 6 == 0 && x % 7 == 0 && x % 8 == 0 && x % 9 == 0 && x % 10 == 0 && x % 11 == 0 && x % 12 == 0 && x % 13 == 0 && x % 14 == 0 && x % 15 == 0 && x % 16 == 0 && x % 17 == 0 && x % 18 == 0 && x % 19 == 0 && x % 20 == 0
        print x
        break
      end
  end
end

divide


texts:
Problem Description:

  Given a 32-bit signed integer, reverse digits of an integer in
  JavaScript.

  Example 1:

  Input: 123
  Output: 321

  Example 2:

  Input: -123
  Output: -321

  Example 3:

  Input: 120
  Output: 21

  Note: It should return zero when it reaches out of limit [−2 ^31,  2 ^31 − 1]

My implementation

var reverse = function (x) {
  var minRange = Math.pow(-2, 31)
  var maxRange = Math.pow(2, 31) - 1

  var isNegative = false;
  if (x < 0) {
    isNegative = true;
    x = (x - x - x);
  }
  var result = Number(x.toString().split('').reverse().join(''));
  (isNegative) ? result = (result - result - result) : result;
  if (result < minRange || result > maxRange) {
    return 0
  } else {
    return result;
  }

};

Please help to improve.


texts:
I am trying to "decode" a file which has every byte shifted its bits.

I have successfully managed to decode this by reading the file, and then byte by byte doing the following (b_int is the integer of the single byte, it will not be 9 bits or 7 bits, always 8 bit):

right shift all bits 1 place b_int >> 1
left shift all bits 7 places b_int << 7
calculate the lower 8 bits of the left_shifted '{0:08b}'.format(left_shifted)[-8:] (and convert this string back to int with int(binary_8_bits, 2))
do an or on the right_shifted, and lower 8 bits of left_shifted right_shifted | lower_8_left_shifted
from int back to byte bytes([shifted])
write the result to a file

All this is working, but is very slow, as it has to process byte for byte done in the for byte in data loop.

My question: is there a faster way of doing this?

Full program:

def shift_bits(b_int):
    return (b_int >> 1) | (int('{0:08b}'.format(b_int << 7)[-8:], 2))

def decode_ss(filename):
    with open(filename, 'rb') as openfile:
        data = openfile.read()
    outputfilename = ''.join(filename.split('.')[:-2]) + '.txt'
    with open(outputfilename, 'wb') as output:
        for byte in data:
            output.write(bytes([shift_bits(byte)]))

filename = r'C:\inputfile.txt.ss'
decode_ss(filename)
print('done')