texts:
My task is to write a function that would take an array of zip codes and spit out only the zip codes that do not qualify. A non-qualifying zip code will not exist in the database and does NOT have other input zip codes within 140 miles.

For example, if I input 90210, 90211, 77389 into the function, it should only spit out 77389 since it is not close to 90210 and 90211. Both 90210 and 90211 are disqualifying zip codes because they are close to one another.

Here are the two functions I am using:

//Accepts an input array of zips and outputs an array of zips that are not in proximity of any other input zip by a predefined distance

    protected function qualifyZips($zips, $radius=70){
        $validInputZips = array();
        //looping through input zips to validate them against the zip master table
        foreach ($zips as $key => $zip) {
            $inputZip = ZipCode::where('zip', $zip)->first(); //some zip data from DB
            //While we are at it, let's grab the lat/lon
            if ($inputZip) {
                $validInputZips[$zip]['latitude'] = $inputZip->latitude;
                $validInputZips[$zip]['longitude'] = $inputZip->longitude;
                $validInputZips[$zip]['hits'] = 0;
            }
        }

       $maskedInputZips = $validInputZips;
       $outputArray = array();

        foreach ($validInputZips as $zip => $latlon) {

            foreach ($maskedInputZips as $maskedZip => $maskedLatlon) {

                if ($zip != $maskedZip) {
                    $miles = $this->haversineGreatCircleDistance($latlon['latitude'], $latlon['longitude'], $maskedLatlon['latitude'], $maskedLatlon['longitude'], 3959);

                    if ($miles < ($radius * 2)) {
                        $validInputZips[$zip]['hits'] += 1;
                    }
                }
            }
            if ($validInputZips[$zip]['hits'] == 0){
                $outputArray[] = $zip;
            }
        }

        return $outputArray;
    }

   protected function haversineGreatCircleDistance($latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 3959)
    {
        // convert from degrees to radians
        $latFrom = deg2rad($latitudeFrom);
        $lonFrom = deg2rad($longitudeFrom);
        $latTo = deg2rad($latitudeTo);
        $lonTo = deg2rad($longitudeTo);
        $latDelta = $latTo - $latFrom;
        $lonDelta = $lonTo - $lonFrom;
        $angle = 2 * asin(sqrt(pow(sin($latDelta / 2), 2) +
                cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2), 2)));
        return $angle * $earthRadius;
    }

Some data:

array:3 [
  90210 => array:3 [
    "latitude" => "34.0900"
    "longitude" => "-118.4100"
    "hits" => 0
  ]
  90211 => array:3 [
    "latitude" => "34.0600"
    "longitude" => "-118.3800"
    "hits" => 0
  ]
  77389 => array:3 [
    "latitude" => "30.0600"
    "longitude" => "-95.3800"
    "hits" => 0
  ]
]


texts: Session generator/checker utility for a server

texts:
I wrote a utility for generating and saving sessions in a MongoDB database as well as checking the session to make sure it's valid.

I'm a beginner when it comes to promises and I have a feeling that either I'm using them improperly or I'm not taking full advantage of them.

Here's the session utility:

// Dependencies
var crypto = require('crypto'),
    config = require('../../config'),
    Session = require('../database/schemas/session');

// Generate Function
var generate = function(length) {
  // Return a promise
  return new Promise(function(resolve, reject) {
    // Create a random value
    crypto.randomBytes(length, function(error, buffer) {
      // Determine if an error occurred
      if (error) {
        // Reject with error
        reject(error);
      } else {
        // Resolve with session ID
        resolve(buffer.toString('hex'));
      }
    });
  });
}

// Create Function
exports.create = function(account_id) {
  // Return a promise
  return new Promise(function(resolve, reject) {
    // Generate the session ID and fetch the promise
    generate(config.session.length)
      .then(function(sid) {
        // Save the session in the database and return the promise
        return(new Session({_id: sid, account_id: account_id}).save());
      })
      .then(function(session) {
        // Determine if session is not defined
        if (!session) {
          // Reject
          reject();
        } else {
          // Resolve with the session ID
          resolve(session._id);
        }
      })
      .catch(reject);
  });
}

// Check Function
exports.check = function(sid) {
  // Return a promise
  return new Promise(function(resolve, reject) {
    // Query for a session with the provided ID and fetch the promise
    Session.findOne({_id: sid}).lean().exec()
      .then(function(session) {
        // Determine if no session was found or if it expired
        if (!session) {
          // Resolve with false
          resolve(false);
        } else if (session.expires < Date.now()) {
          // Resolve with false
          resolve(false);
        } else {
          // Resolve with true by default
          resolve(true);
        }
      })
      .catch(reject);
  });
}

Here's the session schema:

// Dependencies
var mongoose = require('mongoose'),
    config = require('../../../config');

// Session Schema
var sessionSchema = mongoose.Schema({
  _id: {type: String},
  account_id: {type: mongoose.Schema.Types.ObjectId, required: true},
  expires: {type: Date, required: true, default: Date.now() + config.session.expires}
});

// Export the model of the schema
module.exports = mongoose.model('session', sessionSchema);


texts: List directories, subdirectories and files, while ignoring some dirs

texts:
In my application, the user may or may not want to ignore some directories. I can do that, but it seems like I am repeating myself. Does anyone have an idea to refactor that?

from os import walk, path
exclude = ['dir1/foo']
for root, dirs, files in walk('.', topdown=True):
    if exclude != None:
        dirs[:] = [d for d in dirs if d not in exclude]
        for name in files:
            for excluded in exclude:
                if excluded not in root:
                    print path.join(root, name)
    else:
        for name in files:
            print path.join(root, name)

exclude is None when there are no dirs to exclude. I thought of setting it to an empty list, but then, this loop for excluded in exclude: won't execute at all. My ambition was to avoid such a big if/else. Any ideas?

Example:

gsamaras@pc:~/mydir$ ls */*
dir1/bar:
test.txt

dir1/foo:
test.txt

dir2/bar:
test.txt

dir2/foo:
test.txt

I am getting:

./dir2/foo/test.txt
./dir2/bar/test.txt

./dir1/bar/test.txt

If I want, I can do an exclude = ['foo'], and then get:

./dir2/bar/test.txt
./dir1/bar/test.txt

meaning that I ignored all directories named "foo".


texts: Python snippet for finding word in string

texts:
I wrote a simple function that finds a word in a string without use of the re module.

My function looks like this:

def find_in_string(string, word):
    Indices = ()
    wordlength = len(word)
    for i in range(0, len(string)):
        if string[i:i + wordlength] == word:
            Indices += (i,)
    return Indices

Is there any way to improve it?


texts: Randomly select + place an image within a div

texts:
I'm working on a proof of concept idea I want to use in a Brutalist styled web page.

This would involve having transparent image being placed randomly behind the content on load, I have this working with mostly vanilla JS, minus a few jQuery methods that I wasn't sure how I could translate back to vanilla. (I learned jQuery helper functions before having a concrete understanding of vanilla JS and now I regret it. lol)

Anyways, here's the JS Fiddle, for you to see the concept, and below is the code with comments.

Javascript

/* Set Variables at the start of the document *
*
* Frame = Parent of the image element (absolute pos within body content) *
* Top/Left Position = the top/left walls of the document *
* Tag = variable for Image element *
*/

var frame = document.getElementById("frame");
var top_position = (Math.random() * ($(document).width() - 500)).toFixed();
var left_position = (Math.random() * ($(document).width() - 500)).toFixed();
var tag = document.getElementById('random');

// Create array of images to randomly select one
var image = [];
image[0] = "https://via.placeholder.com/350x150";
image[1] = "https://via.placeholder.com/150x150";
image[2] = "https://via.placeholder.com/150x350";
image[3] = "https://via.placeholder.com/500x150";
var size = image.length

// randomly selects number of array 0 through size(array.length)
var x = Math.floor(size * Math.random());

//Apply image src/styles to image on load
tag.src = image[x];
tag.style.position = 'absolute';
tag.style.top = top_position + "px";
tag.style.left = left_position + "px";
top_position += 20;
left_position += 20

Is there anyways I can simplify this and combine some functions, while still keeping it readable?

Example of the effect I was trying to implement

multiple images, within grids


texts:
For my latest app I wanted to be able to code the front-end first, without having to do super extensive documentation and without forgetting my data types later on while coding the back-end.
I thus tried to make some kind of JSON Validator that expects something and outputs true or false depending on the input fed to it. (Meaning that I can define my data structures that way)

What I have works, but I'm not sure if that was the right way to go. Any comments?

export class ArrayValidator {

/**
 * Array-Template Syntax:
 * {
 *      "layer_type": "object"|"array"|"value",
        (if array):
        "items": -1,
        "item": {"layer_type": ...}
        (end if array)
        (if value)
        "value": 'regexp'
        (end if value)
        (if object)
        "properties": [
            {
                "name": "string",
                "null_allowed": true|false,
                "value": {"layer_type": etc ...}
            },
            {...}
        ]
        (end if object)
 *  }
**/
public static testUpon(arrayToTest, arrayTemplate) : boolean {
    if(arrayTemplate.layer_type == "object"){
        for(let prop of arrayTemplate.properties){
            if(arrayToTest[prop.name] == null && prop.nullAllowed == 'false'){
                console.log("[ArrayValidator][Error]Nonexistent property: " + prop.name);
                return false;
            }
            if(arrayToTest[prop.name] != null && !ArrayValidator.testUpon(arrayToTest[prop.name], prop.value)) return false;
        }
    }else if(arrayTemplate.layer_type == "array"){
        if(arrayTemplate.items!=-1 && arrayToTest.length != arrayTemplate.items){
            console.log("[ArrayValidator][Error]Array of wrong length.");
            return false;
        }
        for(let item of arrayToTest){
            if(!ArrayValidator.testUpon(item, arrayTemplate.item)) return false;
        }
    }else if(arrayTemplate.layer_type == "value"){
        let regexp = new RegExp(arrayTemplate.value);
        let res = regexp.test(arrayToTest);
        if(!res) console.log("[ArrayValidator][Error]Value Regexp doesn't match. [Regexp: " + arrayTemplate.value + ", Value: " + arrayToTest + "]");
        return res;
    }
    return true;
}

public static test(){
    let template = JSON.parse('{"layer_type": "object", "properties": [{"name": "obj", "nullAllowed": "false", "value": {"layer_type": "object", "properties": []}}, {"name": "embed", "nullAllowed": "false", "value": {"layer_type": "array", "items": -1, "item":{"layer_type": "value", "value": "(.+?)"}}}, {"name": "testVal", "nullAllowed": "false", "value": {"layer_type": "value", "value": "^[A-Za-z]+$"}}]}');
    let test = JSON.parse('{"testVal": "Hello", "embed": ["test", "another test", 24], "obj": {}}');
    console.log("Output: " + ArrayValidator.testUpon(test, template));
}
}


texts:
I use SQL Server, and though not pertinent here, Railo's CFML engine.

I'm not great at SQL Joins, but I worked through this one and got the result set that I want. This particular SQL will only ever return 10 to 20 records, so even if it's a weak method, I'd probably never see a lot of grief from it since it's on an admin page to edit user profiles.

However, obviously it's best to learn early to improve, before habits set in. It's conceivable, and likely, that I'll encounter a similar situation in the future where the potential size of the result could be several times larger.

It's also possible that there's a faster way to retrieve the same results.

The goal of this page is to list out the user details, and a list of roles along the side with checkboxes. That's easy to code. I'm not asking for help with that.

This is the SQL that I came up with, and I'll explain my db layout below it.

select r.roleID, r.roleTitle, pu.*, 'constant' as qc from roles r
    left outer join (select u.*, p.roleID as xrole from permissions p
         left join users u on p.userID = u.userID
              and p.userID = 2) pu on pu.xrole = r.roleID
         and pu.userID = 2
order by len(username) desc

(Both occurrences of the number 2 are merely to test, this will naturally be replaced with a variable in my .cfm page)

I have three tables:

Users - typical users table (UserID, Username, other personal details
Permissions Table (UserID, RoleID)

Permissions, likely obvious, links the other two tables. If a User doesn't have an entry matching their userID and the role they're trying to access, can't access the role.

Roles (RoleID, RoleTitle)

Notes
- I'm not sure if I would naturally always get a row with userdata first, so I added an order by clause.
- 'constant' as qc is added so that I have one column that has a reliable value so that I can always group by that (cfoutput grouping, not sql grouping, I then cfoutput-group by roleID for the checkboxes for roles)


texts:
I'm creating many builders where I use inheritance.

My resources have many properties and are stored in a Repository.
In rare case I need to update them.
When I update, I need to keep the same objectId (I track update on the repository).

I use the same Builder/Updater as it's easier for my users (there are more than 10 concrete builders).

The code with only one builder (and properties removed):

     public interface IBuilder<T, P>
        {
            P Build();
            P Update();
        }

    public abstract class BuilderBase<T, P>: IBuilder<T, P>
        where T : BuilderBase<T, P>
        where P : class, new()
        {
            protected P Result;
            protected P Source;
            protected T This;

            protected BuilderBase()
            {
                Result = new P();
                This = (T) this;
            }

            protected BuilderBase(P source):this()
            {
                Source = source;
            }

            public P Build()
            {
                var result = Result;
                Result = null;
                return result;
            }

            public abstract P Update();
    }

   public abstract class ResourceBuilder<T, P> : BuilderBase<T, P>
        where T : ResourceBuilder<T, P>
        where P : ResourceBase, new()
        {

            protected ResourceBuilder():base(){}

            protected ResourceBuilder(P resource):base(resource)
            {
                Result.Name = Source.Name;
            }

            public new P Build()
            {
                var result = Result;
                return base.Build();
            }

            public override P Update()
            {
                if (Source != null)
                    Result.ResourceId = Source.ResourceId;
                return Build();
            }

            public T Name(string name)
            {
                Result.Name = name;
                return This;
            }

        }

    public abstract class ColorResourceBuilder<T, P> : ResourceBuilder<T, P>
           where T : ColorResourceBuilder<T, P>
           where P : ColorResource, new()
    {

        public T Color(Color color)
        {
            Result.Color = color;
            return This;
        }

        protected ColorResourceBuilder(P colorResource) : base(colorResource)
        {
            Result.Color = Source.Color;
        }

        protected ColorResourceBuilder() : base()
        {
        }
    }

       public class ColorResourceBuilder : ColorResourceBuilder<ColorResourceBuilder, ColorResource> {
        public ColorResourceBuilder(ColorResource colorResource) : base(colorResource)
        {
        }

        public ColorResourceBuilder()
        {
        }
    }

The main problem with this approach is for the Update():

var colorResource2 = new ColorResourceBuilder(colorResource1).Name("Blue").Update();

colorResource2 != colorResource1  => two different object have the same Id...

hypothetical improvement:

var colorResource2 = new ColorResourceBuilder(ref colorResource1).Name("Blue").Update();
var colorResource2 = new ColorResourceBuilder(ref colorResource1).Name("Blue").Build();

It could be OK for the Update(). But weird with Build() as ref suggest update.

Another hypothetical improvement:

var colorResource2 = new ColorResourceBuilder().Name("Blue").Update(ref colorResource1);
var colorResource2 = new ColorResourceBuilder(colorResource1).Name("Blue").Build();

Will incur another usage inconsistency problem.

I'm looking for any advice to make it more clean and natural. Or any other pattern which could do the job.


texts:
I've made two functions for image processing:

First one is for rotating an image
Second one is to set all pixels of one color to another color

Rotate Image:

private static void roateImage(BufferedImage pic1) throws IOException {
    int width = pic1.getWidth(null);
    int height = pic1.getHeight(null);

    double angle = Math.toRadians(90);
    double sin = Math.sin(angle);
    double cos = Math.cos(angle);
    double x0 = 0.5 * (width - 1);     // point to rotate about
    double y0 = 0.5 * (height - 1);     // center of image

    WritableRaster inRaster = pic1.getRaster();
    BufferedImage pic2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster outRaster = pic2.getRaster();
    int[] pixel = new int[3];

    // rotation
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            double a = x - x0;
            double b = y - y0;
            int xx = (int) (+a * cos - b * sin + x0);
            int yy = (int) (+a * sin + b * cos + y0);

            if (xx >= 0 && xx < width && yy >= 0 && yy < height) {
                outRaster.setPixel(x, y, inRaster.getPixel(xx, yy, pixel));
            }
        }
    }
    ImageIO.write(pic2, "bmp", new File("Images/Output2.bmp"));
}

Please help me to optimize this code.


texts: Generating a game board with squares in a rectangle

texts:
I am trying to generate a game board (similar to a Monopoly board). I am new to Scala and am thinking that there may be a better way to do this. But improvements to the code are also welcome.

class BoardGenerator(squaresPerPlayer: Int, numberOfPlayers: Int) {
  val directionTuples = Array((1, 0), (0, 1), (-1, 0), (0, -1))

  def generate: List[Square] = {
    val squaresPerSide = squaresPerPlayer * numberOfPlayers / 4

    def generateBoard(squaresLeft: Int, direction: Int, x: Int, y: Int): List[Square] = {
      if (direction == 4)
        Nil
      else if (squaresLeft > 1)
        Square(x, y) :: generateBoard(squaresLeft - 1, direction,
          x + directionTuples(direction)._1, y + directionTuples(direction)._2)
      else
        Square(x, y) :: generateBoard(squaresPerSide, direction + 1,
          x + directionTuples(direction)._1, y + directionTuples(direction)._2)
    }
    generateBoard(squaresPerSide, 0, 0, 0)
  }
}


texts:
I'd like to know if the following class design is good or bad:

#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
struct Student {
    string Firstname;
    string Surname;
    string IDNumber;
    int Age;
};

class Exam {
    string ExamNo;
    int Questions;
    int PassScore;
    string Subject;
    map <string,string> ExamTaken;
public:
    Exam(string exam,int Q , string s) : ExamNo(exam), Questions(Q),  Subject(s) {};
    void TakeExam(const string S) { ExamTaken[S] = ExamNo; };
};

class Teacher {
    int studentscore;
    string ClassRoom;
public:
    bool StudentPassed ();
    void setScore (int studentsc) ;
};

class ClassRoom {
    vector<Student> students;
    string ClassName;
    double ClassAverage;
public:
    ClassRoom(string classname) : ClassName(classname) {};
    void AddStudent(Student &s) { students.push_back(s); };
    void ListStudents() const;
    int StudentCount() const { return students.size(); };
    void StudentLookup () const;
    string getClassName() const { return ClassName; };
};
// list all students in class
void ClassRoom::ListStudents() const {
/* old c++ style iterator
    for (vector<Student>::const_iterator it = students.begin();
    it != students.end();++it){
        cout << it->Firstname << " , ";
        cout << it->Surname << " , ";
        cout << it->Age;
        cout << endl;
    }
*/
// c++11
    for (auto &x : students){
        cout << x.Firstname << ",";
        cout << x.Surname << ",";
        cout << x.Age << endl;
    }
}

int main(){
    Student a,b;
    ClassRoom c("CS1002");
    Exam e("A002", 200 , "Biology");

    a.Firstname = "John";
    a.Surname = "Doe";
    a.IDNumber = "8123295073081";
    a.Age = 30;

    e.TakeExam(a.IDNumber);

    b.Firstname = "Jane";
    b.Surname = "Doe";
    b.IDNumber = "8123225073281";
    b.Age = 27;

    c.AddStudent(a);
    c.AddStudent(b);

    c.ListStudents();
    cout << "There are "
         << c.StudentCount()
         << " students in the classroom "
         << c.getClassName() << endl;

}

Maybe the Teacher class should be removed and replaced with a database class, that keeps a record of grades for each student.

I was thinking of changing the student class and adding object composition, for the exam class. I'm not sure how to do it properly yet, so I'm still experimenting with that.


texts:
What follows is a piece of code that essentially toggles an array of filters (if the filter doesnt exist it adds it, if it does, it removes it).

What would you suggest is the best way to write the following imperative approach declaratively?

var selectedFilters = [ {name:"SomeName"} , ... ]
var inputFilter = {name:"OtherName"};

var indexFound = -1;
for (let i = 0; i < selectedFilters.length; i++) {
    if (selectedFilters[i].name === inputFilter.name) {
        indexFound = i;
    }
}

if (indexFound != -1) {
    selectedFilters.splice(indexFound, 1);
} else {
    selectedFilters.push(inputFilter);
}

An idea would be to use filter first to weed out the item if it exists by name, then if the resulting array is equal to the original, push. But it still doesnt feel right.


texts:
I have completed an application which gathers specific records and marks them as Collected. As of now, the application runs perfectly and does exactly what I need it to, but the problem comes in when a large data set is reviewed. If I am pulling records for one day or even maybe a week, it runs at a decent pace, but once you get a month of data or more, it takes a fairly long amount of time.

DataTable ModelData = getModelData() // Returns all records to search.
...
EnumerableRowCollection<DataRow> modelRows = (from model in ModelData.AsEnumerable()
                                              where (model.Field<object>(GeographicalKey) ?? (object)String.Empty).ToString() == GeographicCode
                                              select model);
ModelResults = modelRows.Any() ? modelRows.CopyToDataTable() : ModelData.Clone();

for (int i = 0; i < ModelResults.Rows.Count; i++)
{
    for (int j = 0; j < ModelData.Rows.Count - 1; j++)
    {
        if (ModelResults.Rows[i]["Request ID"].ToString() == ModelData.Rows[j]["Request ID"].ToString())
        {
            ModelData.Rows[j]["Collected"] = "1";
        }
    }
}

The only part that executes slowly would be the for and the nested for. Is there possibly a better way that I can code this? I can't imagine this is the optimal coding for data table update operations, but it might be.  Is this a possibility in LINQ (I'm completely new to LINQ)? I think this is enough code to make sense of what I'm doing, but if more is needed just let me know and I can post it up as well.


texts: github page/ DHH Score Challenge in ruby

texts:
I wrote the following code which when executed prints the score of https://github.com/dhh.

require 'typhoeus'
require 'json'

class DHHScoreChallenge
    def getData
        req = Typhoeus.get("https://api.github.com/users/dhh/events/public")
        body =  req.body
        json_body = JSON.parse(body)
   end

   def calculateScore json_body
       type_and_score = {
          :IssuesEvent => 7,
          :IssueCommentEvent =>  6,
          :PushEvent => 5,
          :PullRequestReviewCommentEvent => 4,
          :WatchEvent => 3,
          :CreateEvent => 2
       }
       score = 0
       json_body.each do |commit|
          commit_type =  commit['type']
          if type_and_score.has_key? commit_type.to_sym
             score = score + type_and_score[commit_type.to_sym]
          else
             score = score + 1
         end
       end
       score
   end

   def showScore score
      puts "DHH's github score is #{score}"
   end
end

begin
    d = DHHScoreChallenge.new
    json_body = d.getData
    score = d.calculateScore(json_body)
    d.showScore(score)
end

I am a beginner in ruby programming and would like to know the best practices of Ruby. I am trying to include portability, encapsulation, reusability in my code. Please let me know if they have been achieved and if there are any improvements that I can make.
Thanks in advance!


texts: Find value that occurs in odd number of elements

texts:
I am trying to solve the following exercise using Javascript:

A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

For example, in array A such that:

  A[0] = 9  A[1] = 3  A[2] = 9
  A[3] = 3  A[4] = 9  A[5] = 7
  A[6] = 9

the elements at indexes 0 and 2 have value 9,
the elements at indexes 1 and 3 have value 3,
the elements at indexes 4 and 6 have value 9,
the element at index 5 has value 7 and is unpaired.

I have written the following code.

function solution(A) {
    var pop;

    if(!A.length)
        return 0;

    while(A.length){
        pop = A.shift();
        let pos = A.indexOf(pop);
        if(pos >-1){
            A.splice(pos,1);
        } else {
            return pop
        }
    }
    return pop;
}

The correctness seems to be fine but it fails the performance test. The order shown is O(N**2).

Any explanation why it shows exponential timing (I have not used any
nested loops)?
Any suggestions on what would be the optimized code which will run on O(N) having space complexity O(1)?


texts:
I completed this Codewars exercise. Here are the instructions:

  You are given an array (which will have a length of at least 3, but
  could be very large) containing integers. The integers in the array
  are either entirely odd or entirely even except for a single integer
  N. Write a method that takes the array as an argument and returns N.

  For example:

  [2, 4, 0, 100, 4, 11, 2602, 36]

  Should return: 11

  [160, 3, 1719, 19, 11, 13, -21]

  Should return: 160

Any comments on the following code appreciated. (I used Python 2.7)

def ifeven(list):
     #Determine if we are dealing with list of evens or odds
    sum = 0
    for ran in (0,1,2):
        sum += abs(list[ran])%2
    avg = float(sum)/3
    r_avg = round(avg)
    return r_avg == 0

def find_outlier(integers):
    even =  ifeven(integers)
    new = []
    for num in integers:
        new.append(num%2)
    if even:
        loc = new.index(1)
    else:
        loc = new.index(0)
    return integers[loc]


texts: Run two computations in parallel, and return the results together

texts:
I am reading the "Learning Concurrent Programming in Scala" and there are exercises in the end of each chapter.
One of exercises is

  Implement a parallel method which takes two computation blocks a and
  b, and starts each of them in a new thread. The method must return a
  tuple with the result values of both the computations. It should have
  the following signature: def parallel[A, B](a: => A, b: => B):(A, B)

I have implemented it in this way:

def parallel[A, B](a: => A, b: => B):(A, B) = {
  var aResult:Option[A] = Option.empty
  var bResult:Option[B] = Option.empty
  val t1 = thread{aResult = Some(a)}
  val t2 = thread{bResult = Some(b)}
  t1.join()
  t2.join()
  (aResult.get, bResult.get)
}

where thread is

def thread(block: =>Unit):Thread = {
  val t = new Thread{
    override def run(): Unit = block
  }
  t.start()
  t
}

My question is if this implementation is free of race condition? I have seen that other people had a similar implementations but declared result holder variables aResult and bResult to be volatile. I am not sure that this is necessary, and also I was not able to design a test which would break the correctness of my implementation.

From my point of view the implementation is free of race condition because the parallel method does not access any shared variables. All its state is in its local variables so is not shared. Thus I think that adding @volatile to aResult and bResult is not needed in this case.


texts: Answer to an implementation of Project Euler #8


texts:
Base Info

Two tables: tData, tData2
Exactly the same columns
About 200,000 records
SQL Server 2008 R2

Logic

At first sight we need to insert tData rows into tData2. What else?

We need a renamed version of a column inside another (tData2)
with the condition checking it won't be an existing item when it's renamed.
Here's the code:

INSERT INTO [tData2]
(
    [Key],
    Info1,
    Info2
)
SELECT
    REPLACE([Key],'_',' '),
    Info1,
    Info2
FROM
    [tData]
WHERE
    (REPLACE([Key],'_',' ') = [Key]) OR
    (REPLACE([Key],'_',' ') NOT IN (SELECT [Key] FROM [tData]))

The problem is it's really slow for me on a top-notch 64 bit system. It has taken more than an hour so far and it's still executing.

How to speed it up? Any alternatives? Any ideas?


texts:
I have the following code which loads in a URL based on the id of a user-clicked button. I'm looking to compress it down as much as possible, and make it more modular and reusable:

function loadDoc(UrlString) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("storybox").innerHTML = xhttp.responseText;
    }
  };
  console.log("URL = " + UrlString);
  xhttp.open("GET", UrlString, true);
  xhttp.send();
}

function buttonClicked(buttonid)  {
  console.log("entered case statement");
  var UrlString = "templates/story/pt1/Start.html";
  switch(buttonid) {
    case "YesStart":
        UrlString = "templates/story/pt1/YesStart.html";
        console.log("test");
        loadDoc(UrlString);
        break;
    case "Sleep":
       UrlString = "templates/story/pt1/Sleep.html";
        loadDoc(UrlString);
        break;
     case "Swindon":
        UrlString = "templates/story/pt1/Swindon.html";
        loadDoc(UrlString);
        break;
    default:
        document.getElementById("storybox").innerHTML = "
That part of the story hasn't been written yet. Click to
<button type='button' class='btn btn-danger' id='nobtn' onclick='buttonClicked('YesStart')'>Restart</button>";

        console.log(buttonid);
    };
};

The case statement actually goes on a lot longer but I've cut it down. What I want to do is to shorten this code down as much as possible, so it dynamically creates URLs based on buttonid. Does anyone have an ideas about the best way to do this?


texts: Multiple custom file input fields with jQuery

texts:
I've modified this example to better suit my needs in handling multiple custom file uploads on the same page. It also renders the filename or truncates if it is too long for each of the 3 file fields. This solution works well however, I think it could be DRY'd out a lot? This is where I landed:

$(document).on('change', '.compliance-guide :file', function() {
  var input = $(this),
      label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
  input.trigger('fileselect', [label]);
});

$(document).on('change', '.compliance-other :file', function() {
  var input = $(this),
      label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
  input.trigger('fileselect', [label]);
});

$(document).on('change', '.agreement-file :file', function() {
  var input = $(this),
      label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
  input.trigger('fileselect', [label]);
});

$(document).ready( function() {
    $('.compliance-guide :file').on('fileselect', function(event, label) {
        var log = label;
        if( log.length > 14 ) {
            $('.compliance-guide-name').html(log.substring(0,14)+'...');
        } else {
            $('.compliance-guide-name').html(log);
        }
    });
    $('.compliance-other :file').on('fileselect', function(event, label) {
        var log = label;
        if( log.length > 14 ) {
            $('.compliance-other-name').html(log.substring(0,14)+'...');
        } else {
            $('.compliance-other-name').html(log);
        }
    });
    $('.agreement-file :file').on('fileselect', function(event, label) {
        var log = label;
        if( log.length > 14 ) {
            $('.agreement-file-name').html(log.substring(0,14)+'...');
        } else {
            $('.agreement-file-name').html(log);
        }
    });
});


texts: Fix last n commits to previous commit automatically

texts:
I often find myself doing rebase manually in an interactive form in a way as follows. Say I want to squash two last commit to third commit.
First I execute:
$ git rebase -i HEAD~3

Now editor pops up, I mark two last commits as fixup. I close the editor and then rebasing is done (if there are no errors). I'd like to automate this by executing a script with a parameter that gives a number of commits, i.e. when 2 is given as parameter, last two commits are fixup to third commit. Please see an example:

some other commits...
add nice feature
fix 1
fix 2

In that scenario I'd like add nice feature to incorporate changes from fix 1 and fix 2, and I like to fix 1 and fix 2 not be present at all.
I wrote a bash script that does what I want. It works seems to work fine.
UPDATE
In this review, I'm most interested in knowing whether my approach to git is a proper one, especially if it doesn't break anything during rebasing.
fixup() {
  local no_of_commits="$1"
  if [ -z "$no_of_commits" ]; then
    echo "You must provide a number of commits to fixup!"
    return 1
  elif ! [[ $1 =~ ^[0-9]+$ ]]; then
    echo "$no_of_commits is not a number!"
    return 2
  fi

  #git stash save

  git reset --soft "HEAD~$(no_of_commits)" &&
    git add --all &&
    git commit --fixup "$(git rev-parse HEAD)" &&
    GIT_SEQUENCE_EDITOR=true git rebase --interactive --autosquash --no-fork-point "$(git rev-parse HEAD~2)" &&
    echo "Rebased $(no_of_commits) succesfully!"

  #git stash pop
}


texts:
I am trying to write a lab/program that loops through a .txt input file. Reads an entire line of data as a string, then splits that string into an array delimited by a space. If there are 4 items in the resulting array, and each item is a valid double, I want it to determine the distance between the points & return info to a separate output.txt file.

RLabs.java

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

public class RLabs {

    public static void main(String[] args) throws FileNotFoundException {
        double dealtaX, deltaY, distance,x1, y1, x2, y2;
        String Line, item1, item2, item3, item4;
        String[] Sect;
        Scanner inFile;
        PrintWriter outFile;

        System.out.println("I/O File Line Distance Program Starting. Opening file...");
        System.out.println("Please ensure data is entered per line in the format of (X1 Y1 X2 Y2).");
        inFile = new Scanner(new File("input.txt"));
        outFile = new PrintWriter(new File("countresults.txt"));

        while(inFile.hasNext()){

            Line = inFile.nextLine();
            Sect = Line.split(" ");
            if(Sect.length == 4) {
                item1 = Sect[0];
                item2 = Sect[1];
                item3 = Sect[2];
                item4 = Sect[3];

                if(testDoubleLow(item1,0)&&(testDoubleLow(item2,0)&&(testDoubleLow(item3,0)&&(testDoubleLow(item4,0))))){
                    x1 = Double.parseDouble(item1);
                    y1 = Double.parseDouble(item2);
                    x2 = Double.parseDouble(item3);
                    y2 = Double.parseDouble(item4);
                    dealtaX = (x2-x1);
                    deltaY = (y2-y1);

                    distance = Math.sqrt(Math.pow(deltaY,2)+ Math.pow(dealtaX,2));
                    outFile.printf(Line);

                    outFile.printf(" The distance between (%1.1f,%1.1f) and (%1.1f,%1.1f) is %1.1f\n", x1,y1,x2,y2,distance);

                }
                else {
                    outFile.println("Line did not correct data");
                }

            }
            else {
                outFile.println("Line did not have 4 item(s)");
            }
        }

        outFile.close();
        inFile.close();

        System.out.println("Done...");
    }

        private static boolean testDoubleLow(String token, double l){

            if(testDouble(token)) {
                double num = Double.parseDouble(token);
                if(num > l ) {
                    return true;
                }
            }

            return false;
        }

        private static boolean testDouble(String s) {
            try {
                Double.parseDouble(s);
                return true;
            }
            catch(Exception e) {
                return false;

    }

    }
}

Input data I'm using

17.2 23.2 15.6 17.76

1

frog

123 frog 2 98

22 99 19 76

-13 03 92 03

l 123 03 96

1293.333333333333333 3 4 111111111111111111

2 1 1 2

21.4518345 94 21 mom

12 67 tti 30

128 30 -2 69

670 20 49 100

1230 230 304 500 60 30 60 606 59

Output from program

17.2 23.2 15.6 17.76 The distance between (17.2,23.2) and (15.6,17.8) is 5.7

Line did not have 4 item(s)

Line did not have 4 item(s)

Line did not have correct data

22 99 19 76 The distance between (22.0,99.0) and (19.0,76.0) is 23.2

Line did not have correct data

Line did not have correct data

1293.333333333333333 3 4 111111111111111111 The distance between (1293.3,3.0) and (4.0,111111111111111104.0) is 111111111111111104.0

2 1 1 2 The distance between (2.0,1.0) and (1.0,2.0) is 1.4

Line did not have correct data

Line did not have correct data

Line did not have correct data

670 20 49 100 The distance between (670.0,20.0) and (49.0,100.0) is 626.1

Line did not have 4 item(s)


texts: Given a string, return a string where every character in the original is doubled

texts:
For example, given the string "xyz", return the string "xxyyzz".

I was given this as a part of a test. I would really appreciate if you can help me to find a better way of doing it.

I came up with two methods to do the same thing but one was an extension method.

I have a couple more questions which I will post in separate posts.

public class RepeatCharactersInString
{
    public string RepeatAString(string sInputString, int repeatCount)
    {

        StringBuilder sOutputString = new StringBuilder();
        if (string.IsNullOrEmpty(sInputString))
        {
            Console.WriteLine("Empty string !");
        }
        else
        {
            foreach (char c in sInputString)
            {
                sOutputString.Append(new String(c, repeatCount));
            }
        }

        return sOutputString.ToString();
    }

}

// Method 2 Using extension methods
public static class RepeatCharactersInStingExtensions
{

    public static string RepeatAllCharactersInThisString(this string sInputString, int repeatCount)
    {
        StringBuilder sOutputString = new StringBuilder();
        if (string.IsNullOrEmpty(sInputString))
        {
            Console.WriteLine("Empty string !");
        }
        else
        {
            foreach (char c in sInputString)
            {
                sOutputString.Append(new String(c, repeatCount));
            }
        }

        return sOutputString.ToString();
    }
}


texts:
I am trying to learn Golang.
This is a problem from Robert Sedgewick's Algorithms book:

  You have a mixed pile of N nuts and N bolts and need to quickly find
  the corresponding pairs of nuts and bolts. Each nut matches exactly
  one bolt, and each bolt matches exactly one nut. By fitting a nut and
  bolt together, you can see which is bigger. But it is not possible to
  directly compare two nuts or two bolts. Given an efficient method for
  solving the problem.

This code applies an algorithm similar to quicksort to solve the problem:

// NutsAndBolts.go
package main

import (
    "fmt"
)

type nutsBolts struct {
    nuts  []int
    bolts []int
}

type array []int

func newNutsBolts(nuts []int, bolts []int) *nutsBolts {
    nb := new(nutsBolts)
    nb.bolts = bolts
    nb.nuts = nuts
    return nb
}

func (nb *nutsBolts) sort(lo int, hi int) {

    if hi <= lo {
        return
    }
    pivotNut := array(nb.nuts).partition(lo, hi, nb.bolts[lo])
    array(nb.bolts).partition(lo, hi, nb.nuts[pivotNut])

    nb.sort(lo, pivotNut-1)
    nb.sort(pivotNut+1, hi)
}

func (a array) partition(lo int, hi int, pivot int) int {
    i := lo
    j := hi

    var hold int

    for {

        for a[i] < pivot && i < hi {
            i++
        }
        for a[j] > pivot && j > lo {
            j--
        }

        if i >= j {
            break
        }

        hold = a[j]
        a[j] = a[i]
        a[i] = hold

    }

    return j
}

func main() {
    nb := newNutsBolts([]int{5, 8, 4, 3, 1}, []int{3, 5, 4, 1, 8})

    nb.sort(0, len(nb.nuts)-1)

    fmt.Println(nb.nuts)
    fmt.Println(nb.bolts)

}

Are there any mistakes with respect to writing good Golang code?


texts: Asynchronously Iterable Queue Implementation for JavaScript

texts:
While studying Deno which is a kind of Node with everything normalized to modern JS and TS, I quickly met the;
import { serve } from "https://deno.land/std@0.87.0/http/server.ts";

const server = serve({ hostname: "0.0.0.0", port: 8080 });

for await (const request of server) {
  request.respond({ status: 200, body: "Whatever" });
}

Here the server object is an asynchronous iterator. Whenever a request is received it turns the for await of loop once. I believe server must be instantiated from an Asynchronously Iterable Queue type.
So i tried to implement a similar asynchronous Queue over the best synchronous Queue type in JS that i am aware of.
Obviously, in an AsyncQueue we can not have .dequeue() or .peek() functions since in this case dequeueing happens automatically by the resolution of the first promise and there is no point to peek at the first promise in a Queue of promises. Instead here we have a .next() function for dequeueing alongside with an .enqueue() function to insert new promises.
An important aspect of this AsyncQueue is that it must be able to accept new promises both sychronously and asynchronously which means it will run forever.
So the code is below and i would like to know if it can be simplified any further or perhaps there are things to enhance the performance or whatnot. Please bear with my indentation style since i will not change it. Also i like to use the Private Class Fields very much.

class AsyncQueue {

  #HEAD;
  #LAST;

  static #LINK = class {
    #RESOLVER;

    constructor(promise,resolver){
      this.promise = new Promise(resolve => ( this.#RESOLVER = resolve
                                            , promise.then(value => resolver({value, done: false}))
                                            ));
      this.next    = void 0;
    }

    get resolver(){
      return this.#RESOLVER;
    }
  }

  constructor(){
    new Promise(resolve => this.#HEAD = new AsyncQueue.#LINK(Promise.resolve(null),resolve));
  };

  enqueue(promise){
    this.#LAST = this.#LAST ? this.#LAST.next = new AsyncQueue.#LINK(promise,this.#LAST.resolver)
                            : this.#HEAD      = new AsyncQueue.#LINK(promise,this.#HEAD.resolver)
  }

  next(){
    var promise = this.#HEAD.promise.then(value => ({value, done: false}));
    this.#HEAD.next ? this.#HEAD = this.#HEAD.next
                    : this.#LAST = void 0;
    return promise;
  };

  [Symbol.asyncIterator]() {
    return this;
  };
};

var aq = new AsyncQueue();

async function getAsyncValues(){
  for await (let item of aq){
    console.log(`The Promise resolved with a value of ${item.value}`);
  };
};

getAsyncValues();
// synchronous insertion of promises
for (var i=1; i <= 5; i++) aq.enqueue(new Promise(resolve => setTimeout(resolve, 1000*i, `done at ${1000*i}ms`)));
// asynchronous insertion od a promise
setTimeout(aq.enqueue.bind(aq),7500,Promise.resolve("this is an asynchronnous insertion"));


texts:
Online challenge on Hacker Rank.

  Problem Statement

  Steve has a string, S, consisting of n lowercase English alphabetic >letters. In one operation, he can delete any pair of adjacent letters with same >value. For example, string "aabcc" would become either "aab" or "bcc" >after operation.

  Steve wants to reduce  as much as possible. To do this, he will repeat the >above operation as many times as it can be performed. Help Steve out by finding >and printing S's non-reducible form!

  Note: If the final string is empty, print Empty String.

  Input Format

  A single string, S.

  Constraints

  \$1 ≤ n ≤ 100\$

  Output Format

  If the final string is empty, print Empty String; otherwise, print the final >non-reducible string.

  Sample Input

  aaabccddd

  Sample Output

  abd

Solution Code

public class Solution {
    private static String solve(String input) {
        int len = input.length();

        int i = 0;
        while (i < len - 1) {
            char current = input.charAt(i);
            char next = input.charAt(i+1);

            if (current == next) {
                input = input.substring(0, i) + input.substring(i+2);
                len = input.length();
                i = 0;
                continue;
            }
            i++;
        }
        if (input.length() == 0) {
            return "Empty String";
        }
        return input;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println(solve(s.next()));
    }
}

This is a brute-force solution, as I feel kind of confused when dealing with string algorithms. Hope for some good suggestions here.


texts:
I wrote JavaScript code for finding the first two consecutive prime numbers (that doesn't have divisors except one and itself) with a specific gap between them. It works well but take too much time to give results for large numbers.

When I tested this, it took about 48s to give the result:

  gap = 8 ,start = 3,000,000 and end = 4,000,000

I read about how to cache to minimize access for properties as length and put variables in local scope to make the code more efficient, but it didn't help me a lot. I then tried to optimize the for loops, but it affects the functionality of the code.

Link to challenge

function gap(gap, start, end){
 var arr = [];
 var counter = [];
 var result;
 for(var x = start; x <= end; x++){
  if(x % 2 == 1){
   arr.push(x)
  }
 }
 for(var cache = arr.length, j = cache ; j >= 0; j--){
  for(var i = 2; i <= Math.sqrt(arr[j]); i++){
   if(arr[j] % i === 0){
    if(i != arr[j]/i || i * i == arr[j]){
      counter.push(arr[j] / i)
      arr.splice(j, 1)
      break;
    }
   }
  }

  if((arr[j+1] - arr[j]) == gap){
   result = [arr[j], arr[j+1]]
  }else if (result == undefined){
   result = null
  }
 }

 return result
}


texts: Creating a loading sequence of an application

texts:
I am using Webpack to create a sort of loading sequence of the application. I can simply call prepareInfosite().render() and I don't need to care about the hidden async nature of it.

export function prepareInfosite() {
    return setupRenderer((resolve) => {
        require.ensure(['./infosite'], (require) => resolve(require('./infosite')), 'infosite');
    });
}

export function prepareLoading() {...}
export function prepareGame() {...}

const uiContainerElement = document.createElement('div');
document.body.appendChild(uiContainerElement);

function setupRenderer(resolver) {
    let uiModule = null;
    let rendered = false;
    const renderArgs = [uiContainerElement];

    function executeRender() {
        if (rendered === true && uiModule !== null) {
            uiModule.render(...renderArgs);
        }
    }

    resolver((resolvedUiModule) => {
        uiModule = resolvedUiModule;
        executeRender();
    });

    return {
        render(...args) {
            rendered = true;
            renderArgs.push(...args);
            executeRender();
        },
    };
}

Originally, the setupRenderer looked like this, but since I am using Babel, it has polyfilled the Promise and size has grown from like 6kB to 22kB (after uglify2!), which isn't very nice.

function setupRenderer(resolver) {
    const promise = new Promise(resolver);
    return {
        render(...args) {
            promise.then((uiModule) => uiModule.render(uiContainerElement, ...args));
        },
    };
}

Do you think there is a nicer way how to express this without any external dependency?

Additionally, I would like to DRY up the lines with require.ensure. I am not entirely sure how this works, but is there some way how to specify name of loaded file dynamically, perhaps using context?


texts:
This is the first time I tried to write some code in Python.
I think it gives proper answers but probably some "vectorization" is needed

import numpy as np
import math
import operator

data = np.genfromtxt("KNNdata.csv", delimiter = ',', skip_header = 1)
data = data[:,2:]

np.random.shuffle(data)
X = data[:, range(5)]
Y = data[:, 5]

def distance(instance1, instance2):
    dist = 0.0
    for i in range(len(instance1)):
        dist += pow((instance1[i] - instance2[i]), 2)
    return math.sqrt(dist)

# Calculating distances between all data, return sorted  k-elements list (whole element and output)
def getNeighbors(trainingSetX, trainingSetY, testInstance, k):
    distances = []
    for i in range(len(trainingSetX)):
        dist = distance(testInstance, trainingSetX[i])
        distances.append((trainingSetX[i], dist, trainingSetY[i]))
    distances.sort(key=operator.itemgetter(1))
    neighbour = []
    for elem in range(k):
        neighbour.append((distances[elem][0], distances[elem][2]))
    return neighbour

#return answer
def getResponse(neighbors):
    classVotes = {}
    for x in range(len(neighbors)):
        response = int(neighbors[x][-1])
        if response in classVotes:
            classVotes[response] += 1
        else:
            classVotes[response] = 1
    sortedVotes = sorted(classVotes.items(), key=operator.itemgetter(1), reverse = True)
    return sortedVotes[0][0]

#return accuracy, your predicitons and actual values
def getAccuracy(testSetY, predictions):
    correct = 0
    for x in range(len(predictions)):
        if testSetY[x] == predictions[x]:
            correct += 1
    return (correct / (len(predictions))) * 100.0

def start():
    trainingSetX = X[:2000]
    trainingSetY = Y[:2000]
    testSetX = X[2000:]
    testSetY = Y[2000:]

    # generate predictions
    predictions = []
    k = 4
    for x in range(len(testSetX)):
        neighbors = getNeighbors(trainingSetX, trainingSetY, testSetX[x], k)
        result = getResponse(neighbors)
        predictions.append(result)
    accuracy = getAccuracy(testSetY, predictions)
    print('Accuracy: ' + str(accuracy))

start()


texts: Making a function which takes char* exception-proof

texts:
I should preface this question by saying that I'm a Java programmer working on my first C++ application, so perhaps there are certain obvious things I don't know.

Some background on the problem:

Our application had data read from a socket stored in a character array, which was a fixed length message header, containing various fixed length fields i.e.:

char[15] data;

The field positions were 0-5,6-7,8-10,11-13 (the last char is a delimiter). The class which wrapped this header offered convenience functions to retrieve the values for each field:

    int ApiHeader::msg_size(void)
    {
        return std::atoi(std::string(data, 6).c_str());
    }

    int ApiHeader::msg_type(void)
    {
        return std::atoi(std::string(data,6,2).c_str());
    }

    int ApiHeader::msg_subtype(void)
    {
        return std::atoi(std::string(data,8,3).c_str());
    }

    int ApiHeader::seqno(void)
    {
        return std::atoi(std::string(data,11,3).c_str());
    }

I was trying to leverage the std::atoi which requires a c-string, but I needed to "slice" the character array into the sub-arrays which contained each separate field, which I did by constructing a string built from the positions in the data array for each field.

The code worked fine, but a user who was doing some code analysis pointed that the msg_subtype() function (and the 2 other similar ones), were actually unintentionally creating an extra string object.

They were invoking this constructor:

basic_string(const basic_string& other,
              size_type pos,
              size_type count = std::basic_string::npos,
              const Allocator& alloc = Allocator() );

So the code was first constructing a new string to turn the char[] to a string&, and then it was constructing another string invoking the string(string&, int, int) constructor.

I redesigned the code to be more efficient:

int atoi(char* string, int start, int length)
{
    double result = 0;
    char* index = string + start*sizeof(char);
    for(int i=length;i>0; i--)
    {
        result += (*index++ - '0') * pow((float) 10, (float) (i-1));
    }
    return (int) result;
}

There are no strings constructed, and it just iterates the part of the data array specified.  The problem is that this code requires that there is no way to detect whether the user passed bad values for start and length.  (I'm not exactly sure what happens if user passes a length outside of the array.  In my unit test, I just saw it got an uninitialized value).

What can be done to make this code more exception proof?

Some ideas I have are:

If *index is not within valid range ('0' to '9'), break out of the loop.
Same as above, except throw an Exception (which at least lets user know something went wrong).
Just document the method to tell user that if values are bad, behavior is "undefined" (I have seen some methods documented this way).

What would be the best C++ way of handling this issue? Or is there a completely different approach which should be used for this function?


texts: Graph Implementation in Java using adjacency list - v2

texts:
Updated version from Graph Implementation in Java using adjacency list

public class MyGraph {
    // add vertex name as key, and neighbors as values in set
    HashMap<String, HashSet<String>> adjList = new HashMap<>();

    public void addVertex(String name) {
        if (adjList.containsKey(name)) {
            throw new IllegalArgumentException();
        }
        adjList.put(name, new HashSet<>());
    }

    public void addEdge(String source, String destination) {
        // are both vertexes already in the graph?
        if (!adjList.containsKey(source) || !adjList.containsKey(destination)) {
            throw new IllegalArgumentException();
        }

        // does edge already exist?
        if (adjList.get(source).contains(destination)) {
            throw new IllegalArgumentException();
        } else {
            adjList.get(source).add(destination);
        }
    }

    public HashSet<String> getNeighbors(String name) {
        return adjList.get(name);
    }

    // return true if there is an edge from source -> destination
    public boolean isNeighbor(String source, String destination) {
        if (!adjList.containsKey(source) || !adjList.containsKey(destination)) {
            throw new IllegalArgumentException();
        }
        return adjList.get(source).contains(destination);
    }

    public void removeEdge(String source, String destination) {
        if (!adjList.containsKey(source) || !adjList.containsKey(destination)) {
            throw new IllegalArgumentException();
        }
        adjList.get(source).remove(destination);
    }

    public void removeVertex(String name) {
        if (!adjList.containsKey(name)) {
            throw new IllegalArgumentException();
        }
        // remove vertex and its neighbors, if any
        adjList.remove(name);

        // remove vertex as a neighbors from other vertexes
        Set vertexes = adjList.keySet();
        Iterator i = vertexes.iterator();
        while (i.hasNext()) {
            String vertex = (String) i.next();
            if (adjList.get(vertex).contains(name)) {
                adjList.get(vertex).remove(name);
            }
        }
    }

    // removes all vertexes/edges from graph
    public void clear() {
        adjList = new HashMap<>();
    }

    // returns the number of vertexes
    public int size() {
        return adjList.size();
    }

    public boolean isEmpty() {
        return adjList.isEmpty();
    }
}


texts:
I am trying to perform a loop and then stop the loop when the last line of code in the if statement is printed to screen saving on CPU cycles.

I want to start a while loop and then kill the loop after it is complete, but not breaking out of the loop so I can re-initiate the loop once again by pressing a GPIO button "B1".

My end goal is to have the RGB LED cycle and not continue to loop once it is complete.

Setup: RPi 3, RGB LED, button and breadboard.

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <bcm2835.h>

#define LED_RED RPI_GPIO_P1_12 //GPIO 18
#define LED_GRN RPI_GPIO_P1_16 //GPIO 23
#define LED_BLU RPI_GPIO_P1_18 //GPIO 24
#define B1 RPI_GPIO_P1_22 //GPIO 25

int main(int argc, char **argv)
{
    if (!bcm2835_init()) return 1;
    bcm2835_gpio_fsel(LED_RED, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(LED_GRN, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(LED_BLU, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_fsel(B1, BCM2835_GPIO_FSEL_INPT);
    bcm2835_gpio_set_pud(B1, BCM2835_GPIO_PUD_UP);

    bcm2835_gpio_len(B1);

    unsigned int delay = 1000;
    while (1){
        printf("Light cycle machine\n");

        if(bcm2835_gpio_eds(B1)!=0){

            printf("Button Pressed!!!\n");
            printf("\n");
            bcm2835_gpio_set(LED_RED);
            printf("Red LED on!!!\n");
            bcm2835_delay(delay);
            bcm2835_gpio_clr(LED_RED);
            printf("Red LED off!!!\n");
            bcm2835_gpio_set(LED_GRN);
            printf("Green LED on!!!\n");
            bcm2835_delay(delay);
            bcm2835_gpio_clr(LED_GRN);
            printf("Green LED off!!!\n");
            bcm2835_gpio_set(LED_BLU);
            printf("Blue LED on!!!\n");
            bcm2835_delay(delay);
            bcm2835_gpio_clr(LED_BLU);
            printf("Blue LED off!!!\n");
            delay(delay);
            bcm2835_gpio_set_eds(B1);
            printf("\n");
            printf("System Idle\n");
            }

        else{

            delay(delay);
            //printf("Done!\n");

            }
        if (bcm2835_gpio_eds(B1)!=1)
            {
            }
        else{

            }

}
    return 0;
}


texts:
I was wondering which time.time() of from datetime import timedelta was the quickest and best way to find how long a programme had been running for example.

import time
start = time.time()

#do stuff

print(start - time.time())

or (although longer)

from datetime import datetime
from datetime import timedelta

start_time = datetime.now()

def millis():
   dt = datetime.now() - start_time
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   return ms
def tickscheck(start):
    x = 0
    count = 0
    while millis() - start < 1000:
        x = 4+5
        #counting up
        count = count + 1
        print("It Took " + str(count) + " Counts\nOver " + str(millis()- start) + "ticks")

running = True
while(running == True):
    tickscheck(millis())


texts: Code which buffers objects and schedules saving them from buffers, after applied some actions to it

texts:
Originally i have a function like this:

 private fun rxSaveEvents(
        events: List<LocationEvent>,
        locationUpdatesAboutToStop: Boolean): Boolean {

    synchronized(mEventsMonitor) {
        if (events.isNotEmpty()) {
            val locationEvents = LocationEvents()
            segregateLocationEvents(events, locationEvents)
            scoreReadings(locationEvents)
            sendLocationEventsInternal(locationEvents, locationUpdatesAboutToStop)

            Completable.fromCallable { updateLocationEventsToDb(locationEvents) }.subscribeOn(Schedulers.io()).subscribe()

        }
        if (locationUpdatesAboutToStop) {
            stopLocationUpdates()

            Completable.fromCallable { cleanAllReadingsData() }.subscribeOn(Schedulers.io()).subscribe()
            Completable.fromCallable { removeExpiredData() }.subscribeOn(Schedulers.io()).subscribe()
        }

        locationEvents.clear()

        return true
    }
}

This function is triggered after some amount of time. It can be triggered in 2 different ways - scheduled with boolean as true or false. Here are the schedulers, which schedules this method invokation:

 val scheduleNormalSave = Completable.timer(locationEventsSaveThrottlingSeconds, TimeUnit.SECONDS).doOnSubscribe(Consumer { normalSaveScheduled.set(true) }).doOnComplete(Action { normalSaveScheduled.set(false) })
val scheduleStopAndSave = Completable.timer(locationStopUpdatesSeconds, TimeUnit.SECONDS).doOnSubscribe(Consumer { stopAndSaveScheduled.set(true) }).doOnComplete(Action { stopAndSaveScheduled.set(false) })

The booleans:

  private var normalSaveScheduled: AtomicBoolean = AtomicBoolean(false)
private var stopAndSaveScheduled: AtomicBoolean = AtomicBoolean(false)

If some event is triggered it will configure scheduler and and the start the schedule invokation:
E.g

   if (!normalSaveScheduled.get()) {
                        configureNormalSaveCompletable()
                    }

And the configure normalSaveCompletable method:

  fun configureNormalSaveCompletable() {
    scheduleNormalSave.subscribe(Action { rxSaveEvents(locationEvents, false) })
}

The locationEvents is just an arrayList, which buffers some events asynchronously.

private val locationEvents: ArrayList<LocationEvent> = ArrayList<LocationEvent>()

So when some event occurs(for example location update) it insert the LocationEvent to this ArrayList.

So my question is how to make my function, this rxSaveEvents more reactive? Do you need to see its other functions in this method implementation?


texts: D-flop with enable and clear, translated from VHDL to Haskell

texts:
I am in the process of translating an implementation of dflop_en_clr from VHDL to Haskell:

if (reset = '1') then
     out_1 <= '0';
elsif rising_edge(clk) then
   if (clear_n = '0') then
      out_1 <= '0';
   elsif (enable = '1') then
      out_1 <= in_1;
   end if;
end if;

Types to know:

data PIn = PIn { _in_1    :: Bit
               , _clk     :: Bit
               , _reset   :: Bool
               , _enable  :: Bool
               , _clear_n :: Bool
               } deriving (Eq)

data St = St { _out_1 :: Bit
             } deriving (Eq)

First attempt

 onTrue :: St -> PIn -> Bool -> St
 onTrue st PIn{..} edgeDetect = shouldReset
   where
     shouldReset = if _reset then St 0 else risingEdge
     risingEdge  = if edgeDetect then shouldClear else st
     shouldClear = if _clear_n then St 0 else enabled
     enabled     = if _enable then st{ _out_1 = _in_1 }  else st

Another:

onTrue'' :: St -> PIn -> Bool -> St
onTrue'' st PIn{..} risingEdge = if _reset then St 0
                                 else if risingEdge  $
                                       if not _clear_n then St 0
                                       else if _enable then st{ _out_1 = _in_1 }
                                            else st
                                     else st

If I were to covert a more complicated nest logic then there would possible be a lot of extra "else"

Current:

ifTrueApplyFun :: Bool -> a -> (a -> a) -> a
ifTrueApplyFun cond value fun = if cond then fun value
                                else value
ifTrueReturnFun :: Bool -> (a -> a) -> (a -> a)
ifTrueReturnFun cond fun = if cond then fun
                           else id
onTrue' :: St -> PIn -> Bool -> St
onTrue' st PIn{..} risingEdge = if _reset then St 0
                                else ifTrueApplyFun risingEdge st $
                                       if not _clear_n then (\_ -> St 0)
                                       else ifTrueReturnFun _enable (\newSt -> newSt{ _out_1 = _in_1 })

This is code that needs to be readable and testable.


texts:
I was doing some reading on the Wagner Fischer algorithm algorithm for computing the edit distance on strings. None of the examples in the literature I have read showed how to recover the edit sequences from the final populated matrix. The examples only showed total number of edits.

The logic I am using is simply calling min() on the 4 x 4 submatrix of matrix L that ends L[m][n] until I reach L[0][0]. It seems like the logic should be to compare the value returned by min() and compare it to the current L[i][j] to recover the edit at that position. Then we simply append this to an array that represents the total edit operations and finally reverse the list.

I have tested this code and compared it against the Python Levenshtein module on pypi.org and it looks to be OK. However, I wanted to get some feedback on this methodology of how to output the actual edit sequence. Is there some boundary case I might be missing?

def edit_distance(x, y):

    m = len(x)
    n = len(y)

    L  = [ [0] * (n+1) for i in xrange(m+1) ]

    for i in range(0, m+1):
        L[i][0] = i

    for j in range(0, n+1):
        L[0][j] = j

    for i in range (1, m+1):
        for j in range(1, n+1):
            if x[i-1] == y[j-1]:
                L[i][j] = L[i-1][j-1]
            else:
                L[i][j] = min(L[i][j-1], L[i-1][j], L[i-1][j-1]) + 1

    edits = []

    i = m
    j = n

    while i > 0 and j > 0:
        back = min(L[i][j-1], L[i-1][j], L[i-1][j-1])
    if back == L[i-1][j-1]:
        if back == L[i][j]:
            edits.append('NOOP')
        elif back == L[i][j] - 1:
                edits.append('SUBST')
        i -= 1
        j -= 1
    elif back == L[i][j-1]:
        edits.append('INSERT')
        j -= 1
    elif back == L[i-1][j]:
        edits.append('DELETE')
        i -= 1

    print x
    print edits[::-1]
    print y


texts:
I'm running code which works fast locally, but when it's on Heroku it's slow. Heroku says this is because there is less memory and CPU power on my hosting than locally. I'm trying to rewrite my code so it's more efficient, but I'm not sure how.

This is what they said:

  ...[my] method (especially, a.each part) is taking time. I think a
  itself is pretty long, and you're transpose it with subs.keys, and do
  some process for each of them. Even though s.gsub!(*pair) is not "long
  running" code, if you run this million times (actually runs 1,161,216
  times for the word "startup"), it'll be "slow" request.

Here is my code:

def substitute(word)
    subs = Hash.new
    Section.all.to_a.each do |s|
        alternates_array = Array.new
        s.substitutions.each do |alt|
            alternates_array << alt.alternate
        end
        alternates_array << s.part
        new_hash = Hash.new
        subs[s.part] = alternates_array
    end
    a = subs.values
    a = a.first.product(*a.drop(1))
    alternates = Array.new
    a.each do |a|
        new_string = [subs.keys, a].transpose.each_with_object(word.dup){|pair, s| s.gsub!(*pair)}
    end
    return alternates
end

Section Model

class Section
  include Mongoid::Document
  field :part, type: String

  embeds_many :substitutions

  accepts_nested_attributes_for :substitutions
end

Substitution Model

class Substitution
  include Mongoid::Document
  field :alternate, type: String

  embedded_in :section
end


texts: Find the nth term of a sequence that consists of Fibonacci and prime numbers interleaved

texts:
I have given a series problem 1,2,1,3,2,5,3,7,5.... in which the odd terms forms the Fibonacci series and even terms form the prime number series. I have to write a code in which I have to find the nth term. Following is the code for finding the nth term, I want to know whether it can be written more efficiently or not and how?

 def fib(n):
     t1=0
     t2=1
     for i in range(1,n+1):
         add = t1+t2
         t1 = t2
         t2 = add
     print(t1)

 def prime(n):
     count =1
     for i in range(2,100):
         flag =0
         for j in range(2,i):
             if (i%j==0):
                flag=1
                break
         if (flag==1):
             continue
         else:
             if (count==n):
                 print(i)
                 break
             else:
                 count = count+1

 n= int(input('enter the positive number: ' ))

 if (n%2==0):
     prime(int(n/2))
 else:
     fib(int(n/2)+1)


texts:
I wrote the following Forth code for sorting a string with the Bubble Sort method.
It looks nice to my eyes, but I'd like your experienced opinion and any comments about the code you might have.

In the compare-and-swap-next word, is using the return stack to save base address of string ok?
the bubblesort word uses 2 pick which is not so bad? A previous version had 5 pick (!), anyway ... is 2 pick fine: don't overthink about that or maybe try some more refactoring?
How would I go about adding a check for any swaps in each round and terminate the sort early? A variable? A stack cell (on TOS)? Rethink all of the implementation?

: compare-and-swap-next ( string i -- )
   2dup + dup >r c@ rot rot 1 + + c@ 2dup >
   if     r@ c! r> 1 + c!
   else   r> drop 2drop
   then ;

: bubblesort ( string len -- string len )
   dup 1 -
   begin  dup 0>
   while  dup 0
          do   2 pick i compare-and-swap-next
          loop
          1 -
   repeat
   drop ;

\ s" abracadabra" bubblesort \ cr type
\ s" The quick brown fox" bubblesort \ cr type
\ s" a quick brown fox jumps over the lazy dog." bubblesort \ cr type

Code available on github
Nitpicks welcome! Pedantism welcome!
Thank you!


texts:
Just a small PHP exercise to write some simple reports, I thought I'd do it without a framework for fun and profit. I'm particularly concerned about the potential for SQL injection, since the user could pass their own values to $_GET['status'].

I also understand that mysql_connect() et. al are deprecated in PHP since 5.5, but I assume better equivalents work the same way.

<?php

$server = "deleted";
$username = "deleted";
$password = "deleted";
$database = "deleted";

$conn = mysql_connect($server, $username, $password);

if (!$conn)
{
        die('Could not connect: ' . mysql_error());
}

mysql_select_db($database, $conn);

// Get the status from the last form submission, otherwise use default.
$choice = isset($_GET['status']) ? $_GET['status'] : '7';

// Get all the current statuses to populate the drop down list.
$options = mysql_query("SELECT name, id FROM issue_statuses", $conn);

// Get all the results for issues matching the chosen status id.
$result = mysql_query("SELECT id, subject FROM issues WHERE status_id = " . $choice, $conn);

// Get the name of the chosen status.
$chosen_status = mysql_query("SELECT name FROM issue_statuses WHERE id = " . $choice, $conn);
$status_name = mysql_fetch_array($chosen_status, MYSQL_ASSOC);

if (!$options || !$result || !$chosen_status)
{
        echo("
Error performing query: " . mysql_error() . "
");
        exit();
}

mysql_close($conn);

?>

<!DOCTYPE html>

        <title>RM Rep</title>

        <form name="status_choice" action="index.php" method="get">
                <select name="status">
                <?php
                        // Load all the statuses into a select list.
                        while ($row = mysql_fetch_array($options, MYSQL_ASSOC))
                        {
                                echo('<option value="' . $row['id'] . '">' . $row['name'] . '</option>');
                        }
                ?>
                </select>
                <input type="submit" value="Submit">
        </form>

<?php echo($status_name['name']); ?>

        <?php echo(mysql_num_rows($result) . " results"); ?>

        <?php
                // Print results.
                while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
                {
                        echo("
");
                        echo("" . $row['id'] . "	");
                        echo("" . $row['subject'] . "	");
                        echo("
");
                }
        ?>


texts:
First time I'm using stackexchange. I'm in 8th standard. I tried to implement Queue in Java. I wrote something like this> Right now I'm not able to test it because I don't have JVM in my machine. So I just wanted to know Is this correct implementation? Am I going in the right direction?

 import java.lang.*;
 import java.util.*;

 public class Queue
{
public static void main(string[] args)
{
    LinkedList l1=new LinkedList();
    InputstreamReaderir=new InputstreamReader(System.in);
    BufferReader bf=new BufferReader(ir);
    System.out.println("Enter the number of elements to be inserted into queue");
    string str;
    str=bf.readline();
    System.out.println("Enter your Choice: ");
    System.out.println("1->Insert 2->Delete 3->Display 3->Exit");
    string choice;
    choice.readline();
    for(;;)
    {
        switch
        {
            case 1:l1.insertrear();
                   break;
            case 2:l1.deletefront();
                break;
            case 3: system.out("Contents of Queue are:" +l1);
                break;
            default: exit;
        }
    }
}


texts: 1 Producer, N Consumers working in parallel, each doing ~1/nth of a task

texts:
I am not wondering about error checking (I will add that soon). I would instead like to know about correctness, efficiency and simplicity.

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

#define  NTHREADS    7
#define  RUN_N_TIMES 37

pthread_cond_t      new_task_available  = PTHREAD_COND_INITIALIZER;
pthread_cond_t      task_complete       = PTHREAD_COND_INITIALIZER;
pthread_mutex_t     mutex               = PTHREAD_MUTEX_INITIALIZER;

volatile int producerCond           = 0;
volatile int consumerCond[NTHREADS] = {};
volatile int no_more_tasks          = 0;
volatile int mini_tasks_complete    = - NTHREADS;

void do_work(unsigned int* current_level){
  /* Some work done */
  ++*current_level;
}

void *threadfunc(void *parm){
  volatile int* thread_cond;
  unsigned int level = 0;
  thread_cond = (volatile int*)parm;
  while(!no_more_tasks){
    pthread_mutex_lock(&mutex);
    mini_tasks_complete++;
    if(mini_tasks_complete > 0)
      printf("Thread %u has completed %u units of work.\nIt was #%d to complete it's task this round..\n", \
        (unsigned int)pthread_self(), level, mini_tasks_complete);
    if(mini_tasks_complete == NTHREADS){
      producerCond = 1;
      pthread_cond_signal(&task_complete);
    }
    *thread_cond = 0;
    while (!*thread_cond) {
      pthread_cond_wait(&new_task_available, &mutex);
    }
    pthread_mutex_unlock(&mutex);
    if(no_more_tasks){
      return NULL;
    } else {
      do_work(&level);
    }
  }
  return NULL;
}

void reset_cond(int val){
  int i;
  for (i=0; i<NTHREADS; ++i)
    consumerCond[i] = val;
}

int main(int argc, char **argv)
{
  int                   i;
  pthread_t             threadid[NTHREADS];

  for(i=0; i < NTHREADS; ++i) {
    pthread_create(&threadid[i], NULL, threadfunc, (void*)&(consumerCond[i]));
  }

  while(mini_tasks_complete < 0){
    /* Do nothing */
  }

  printf("Waking up all waiting threads " "#RUN_N_TIMES" " times...\n");
  for(i = 0; i < RUN_N_TIMES; i++){
    pthread_mutex_lock(&mutex);
    mini_tasks_complete = 0;
    printf("New tasks available.\n");
    reset_cond(1);
    /* Wake them up */
    pthread_cond_broadcast(&new_task_available);
    producerCond = 0;
    while (!producerCond) {
      printf("Main waiting\n");
      /* Go to sleep */
      pthread_cond_wait(&task_complete, &mutex);
    }
    pthread_mutex_unlock(&mutex);
  }
  pthread_mutex_lock(&mutex);
  reset_cond(1);
  no_more_tasks = 1;
  printf("Go home everybody!\n");
  pthread_cond_broadcast(&new_task_available);
  printf("Wait for threads and cleanup...\n");
  pthread_mutex_unlock(&mutex);

  for (i=0; i<NTHREADS; ++i) {
    pthread_join(threadid[i], NULL);
  }

  pthread_cond_destroy(&new_task_available);
  pthread_cond_destroy(&task_complete);
  pthread_mutex_destroy(&mutex);

  printf("Main done\n");
  return 0;
}


texts:
Find the last element of a list from codewars.com

  Example:

last( [1,2,3,4] ) # => 4

last( "xyz" ) # => z

last( 1,2,3,4 ) # => 4

I completed this kata several times tonight.  My current answer is a mashup of several other people's solutions.

I do not understand why I cant change .respond_to?(:index) into .is_a? Array
Should I use ternary operators in Ruby?
Other suggestions?

def last (*arg, arg_last)
  arg_last.respond_to?(:index) ? arg_last[-1] : arg_last
end


texts: Creating many random test database entries

texts:
I'm working on a simple time sheet webapp. I have created the following query (simplified - I actually have several mapped columns of a similar type to project_id) to generate test data:

INSERT INTO `entries` (`entry_id`, `user_id`, `project_id`, `date`, `comment`, `hours`)
VALUES
( null,
  0,
  (SELECT `project_id` FROM projects ORDER BY RAND() LIMIT 1),
  CURRENT_DATE(),
  '# TEST DATA #',
  (SELECT ROUND((0.25 + RAND() * (24 - 0.24)), 2))
);

I'm currently running this query inside a PHP loop.

This code is currently adequate for my needs now, as I can iterate 50 loops in 0.3037 seconds. However, I fear that when it comes time to test large data sets (searching and report generation for rows > 1 000 000), I may run into problems creating them.

How can I optimize this algorithm? Should I consider using a stored procedure? Or should I just not worry about it, and run the loop to longer iterations, more times?

DROP PROCEDURE IF EXISTS `create_test_entries`;

DELIMITER //

CREATE PROCEDURE `create_test_entries` (IN number INT)
LANGUAGE SQL
DETERMINISTIC
SQL SECURITY INVOKER
COMMENT 'Creates `number` of random test entries in the timesheet'
BEGIN
    DECLARE i INT;
    SET i = 0;

    WHILE i < number DO
        INSERT INTO `entries` (`entry_id`, `user_id`, `project_id`, `department_id`, `task_id`, `date`, `comment`, `hours`)
        VALUES
        ( null,
          0,
          (SELECT `project_id` FROM projects ORDER BY RAND() LIMIT 1),
          CURRENT_DATE(),
          '# TEST DATA #',
          (SELECT ROUND((0.25 + RAND() * (24 - 0.24)), 2))
        );
        SET i = i + 1;
    END WHILE;
END //


texts:
I have the following SQL query that computes for every date the week it falls in (a week begins on Sunday and ends on Saturday):

SELECT EntryDate
      ,CAST(DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS DATE) AS 'SundayDate'
      ,CAST(DATEADD(DAY ,7-DATEPART(WEEKDAY, EntryDate), EntryDate) AS DATE) AS 'SaturdayDate'
      ,CONVERT(VARCHAR, DATEADD(DAY ,1-DATEPART(WEEKDAY, EntryDate), EntryDate), 103) + ' - ' +
       CONVERT(VARCHAR, DATEADD(DAY ,7-DATEPART(WEEKDAY, EntryDate), EntryDate), 103) AS 'Week'
FROM MyTable
WHERE CAST(DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS DATE) <=
      CAST(DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), GETDATE()) AS DATE)
ORDER BY CAST(DATEADD(DAY, 1-DATEPART(WEEKDAY, EntryDate), EntryDate) AS DATE)

It works fine, but I don't like the repeated function calls because they cluster the query and make it less readable.

How can I make the query cleaner and more readable? (I'm using SQL Server 2008.)


texts: Simplification of Python code (HTML extraction)

texts:
I'd like to extract HTML content of websites and save it into a file. To achieve this, I have the following (working) code:

output = codecs.open("test.html", "a", "utf-8")

def first():
    for i in range(1, 10):

        root = lxml.html.parse('http://test'+str(i)+'.xyz'+'?action=source').getroot()

        for empty in root.xpath('//*[self::b or self::i][not(node())]'):
            empty.getparent().remove(empty)

        tables = root.cssselect('table.main')
        tables = root.xpath('//table[@class="main" and not(ancestor::table[@class="main"])]')

        txt = []

        txt += ([lxml.html.tostring(t, method="html", encoding="utf-8") for t in tables])

        text = "\n".join(re.sub(r'\[:[\/]?T.*?:\]', '', el) for el in txt)

        output.write(text.decode("utf-8"))
        output.write("\n\n")

Is this "nice" code? I ask because I'm not sure if it's a good idea to use strings, and because of the fact that other HTML texts I've seen use one tag-ending (for example
) per line. My code produces partly more tag-endings per line.

Is it possible not to use strings or/and to achieve that we receive not things like

	 but things like:

? Thanks for any proposition :)


texts:
Can the following code to swap two bits be optimized?

  //ecx = bita, the index of the first bit to be swapped
  //edx = bitb, the index of the second bit to be swapped.
  //r8 = data, the int32 who's bits are to be swapped
  //code        ;latency //comments
  mov eax,1     ;1
  shl eax,cl    ;1     // Set bitA
  mov ecx,[r8]  ;3     // ecx = input
  bts eax,edx   ;0     // Set bitB
  mov edx,eax   ;1     // save the mask for later
  and eax,ecx   ;0     // Let's see if bitA = BitB, if so we don't need to swap
  popcnt eax,eax ;1    // if the bits are not the same, popcount will be 1
  xor edx,ecx    ;0    // Invert the bits in the input, just in case
  sub eax,1      ;1    // is eax odd?, i.e. are the bits different?
  cmovnz ecx,edx ;2    // Bits are different, result is swapped, if not result = input
  mov [r8],ecx   ;3    // write the result

Total latency: 13 cycles.
The code exploits the fact that bit xor 1 inverts and only bits that are different need to be swapped. Still it's a lot of instructions just to swap two bits.


texts:
This is my 1st F# program so I'm open to any and all criticism on my syntax and the way I approached the problem.

Challenge

Project Euler 16: Power Digit Sum

2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?

open System
open System.Numerics

let digitPower (n:bigint) p = pown n p
let digitToPowerSum (n:bigint) p =
    (digitPower n p) |>
    string |>
    (fun s -> s.ToCharArray()) |>
    Array.map (fun x -> Int32.Parse (x.ToString())) |>
    Array.sum

[<EntryPoint>]
let main argv =
    let n = new bigint(2)
    let p = 1000
    let value = digitPower n p
    let sum = digitToPowerSum n p

    Console.WriteLine(String.Format("{0}^{1} = {2:n}", n, p, value))
    Console.WriteLine()
    Console.WriteLine(String.Format("Its digit sum is {0}", sum))
    Console.ReadKey() |> ignore
    0

I'm primarily concerned with


texts:
While solving a problem from HackerRank, though it's an easy one, I wrote this big program. Not sure if recursion is applicable and hold good but to me it looked like it isn't. However when I run the program I see my code executed fairly well.
Here is the problem statement ("Sherlock and The Beast"):

Print the largest decent number.
A 'Decent' Number can have:

Only 3 and 5 as its digits.
Number of times 3 appears is divisible by 5.
Number of times 5 appears is divisible by 3.
Input should be the number of digits (N) where 1 <= N <= 100000.

For 10 such test cases if I have the inputs:
3647
8884
1233
99999
130
11111
3455
23454
123211
345

My code ran in 0.008688 seconds.
Is there any room for improvement?
int filldigits(num) {
    int max_div, num_of_5s, num_of_3s;
    if (num/3 == 0) {
        num_of_5s = num;
        print(num_of_5s, 0);
        return 0;
    }
    max_div = num/3;
    for (max_div; max_div>0; max_div--) {
        num_of_5s = max_div * 3;
        num_of_3s = num - num_of_5s;
        if (num_of_3s % 5 == 0 ) {
            print(num_of_5s, num_of_3s);
            return 0;
        }
        else
            continue;
    }

    max_div = num/5;
    for (max_div; max_div>=1; max_div--) {
        num_of_3s = max_div * 5;
        num_of_5s = num - num_of_3s;
        if (num_of_5s % 3 == 0)  {
            print(num_of_5s, num_of_3s);
            return 0;
        }
        else
            continue;
    }
    return -1;
}


texts:
I made an brute force algorithm to find the longest palindrome within the string. This palindrome is a substring of the input. Below is the code.

def generate_substrings(string):
    """
    avg time: O(len(string) * len(string))
    avg space: O(1)

    amortized time: O(len(string) * len(string))
    amortized space: O(1)
    """
    col = 0
    for row in range(len(string)):
        col = row + 1
        while col < len(string) + 1:
            yield string[row:col]
            col = col + 1

def test_generate_substrings():
    assert list(generate_substrings('')) == []
    assert list(generate_substrings('a')) == ['a']
    assert list(generate_substrings('ab')) == ['a', 'ab', 'b']

def is_palindrome(string):
    """
    avg time: O(len(string))
    avg space: O(len(string))

    amortized time: O(len(string))
    amortized space: O(len(string))
    """
    return string[::-1] == string

def test_is_palindrome():
    assert is_palindrome('') == True
    assert is_palindrome('ab') == False
    assert is_palindrome('bb') == True
    assert is_palindrome('abc') == False
    assert is_palindrome('ddd') == True

def find_palindrome(string):
    """
    avg time: O(len(string) * len(string))
    avg space: O(len(string))

    amortized time: O(len(string) * len(string))
    amortized space: O(len(string))
    """
    answer = ''
    vec = []

    for string in generate_substrings(string):
        if is_palindrome(string):
            vec.append(string)

    for string in vec:
        if len(answer) <= len(string):
            answer = string

    return answer

def test_find_palindrome():
    assert find_palindrome('ab') == 'b'
    assert find_palindrome('aa') == 'aa'

def main():
"""
entry point for test code
"""
    test_generate_substrings()
    test_is_palindrome()
    test_find_palindrome()

if __name__ == '__main__':
    main()

```


texts: Building a Building - Is the building clean?

texts:
I'm writing a small game and I use Kotlin for that. I want to model my buildings with the following class:

class Building (
    val name: String,
    val inputs: Array<Resource>,
    val outputs: Array<Resource>
) {}

I want to create multiple instances of this class for the map but I don't want to fill the constructor parameters every time with the same data for the same building. So my idea was to make the constructor private and write creator functions in the companion object.

class Building private constructor(
    val name: String,
    val inputs: Array<Resource>,
    val outputs: Array<Resource>
) {

    companion object {
        fun createWoodcutter(): Building = Building(
            "Woodcutter",
            arrayOf(
                Resource(ResourceType.WOOD, 1),
                Resource(ResourceType.WORKFORCE, 3),
                Resource(ResourceType.MONEY, 10)
            ),
            arrayOf(Resource(ResourceType.PLANKS, 1))
        )
    }
}

But I don't know if this strategy counts as clean code or is there a better way or design pattern for this?


texts:
This assignment requires obtaining the deviation and variance of \$n\$ numbers stored in one single array. Is there any way to make this code more efficient?

#include <iostream>
#include <cmath>

using namespace std;
int main()

{
    const int arrSize = 14;
    double average , sum = 0 , dev = 0;
    double deviation[arrSize];

    int grades[arrSize] = { 89, 95, 72, 83, 99, 54, 86, 75, 92, 73, 79, 75, 82, 73 };

    // Calculating the average
    for ( int i = 0; i < arrSize; i++ )
    {
        sum += grades[i];
        average = ( sum / arrSize );
    }
    cout << "average is : " << average << endl;
    cout << endl;

    //Calculating the deviation and variance

    double sumVar = 0 , totalVar = 0;
    for ( int i = 0; i < arrSize; i++ )
    {
        deviation[i] = ( grades[i] - average );

        cout << "Grades = " << grades[i] << " and deviation is = " << deviation[i] << endl;

        double variance = pow( deviation[i] , 2 );
        sumVar = sumVar + variance;
        totalVar = ( sumVar / arrSize );

    }
    cout << endl;
    cout << "variance = " << totalVar << endl;

    system( "pause" );
    return 0;
}


texts: Sum of primes up to 2 million using the Sieve of Eratosthenes

texts:
I've solved question 10 on Project Euler using the Sieve of Eratosthenes, what can I do to optimize my code?

def prime_sum(n):
    l=[0 for i in range(n+1)]

    l[0]=1
    l[1]=1
    for i in range(2,int(n**0.5)+1):
        if l[i]==0:
            for j in range(i * i, n+1, i):
                    l[j]=1
    s=0
    for i in range(n):
        if l[i] == 0:
            s+=i
    print(s)

if __name__ == '__main__':
    prime_sum(2000000)


texts: Java program that relaunches itself in OS's terminal application

texts:
I wrote a Java program that when its executable .jar is opened manually, it re-opens itself inside the operating system's shell console. The purpose of this is to have a C#-style console application where the user can enter commands, without the user needing to manually open the shell console and run the java -jar ... command to open the application.

Would you consider this a good implementation?

Would you make a custom console GUI instead of using the OS's console?

public static void main(String[] args){
    if(args.length == 0){ // then re-open in console with argument to indicate that there's no need to re-open next time.
        try {
            String os = System.getProperty("os.name").toLowerCase();
            String path = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath();
            if(os.contains("mac")){
                String command = "tell application \"Terminal\"\n" +
                        "do script \"java -jar \'" + path + "\' console\"\n" +
                        "activate\n" +
                        "end tell";
                Runtime.getRuntime().exec( new String[]{"osascript", "-e", command} );
                System.exit(0);
            } else if(os.contains("win")) {
                Runtime.getRuntime().exec("cmd /c start cmd.exe /K java -jar \"" + path + "\" console");
                System.exit(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }
    }
    System.out.println("Enter command.  'help' for list of commands.");
    while(true)
        nextCommand();
}


texts:
I am currently adding a voting system to my website. Below is my voting class. I feel that it could be simplified and that there is repeated code regarding the functions, although to the best of my knowledge this is the simplest I can make it. I would love to hear other implementation ideas and systems that have been used.

<?php

class Vote{

    var $db;

    function __construct($db){
        $this->db = $db;
    }

    function vote($user_id, $post_id, $type){
        // check if vote already exists against user and post to prevent duplicates
        if($this->userVoteExists($user_id, $post_id)){
            // retreive vote
            $vote = $this->getVote($user_id, $post_id);
            // check  if the requested vote is the same to prevent needlessly deleting and inserting
            if($vote['type'] != $type){
                if($vote){
                    // remove the vote if it exists
                    $this->removeVote($user_id, $post_id);
                }
                // add the vote
                $this->addVote($user_id, $post_id, $type);
            }
        }
    }

    function userVoteExists($user_id, $post_id){
        $query = $this->db->prepare("SELECT * FROM votes WHERE user_id = :user_id AND post_id = :post_id LIMIT 1");
        $query->execute(array(':user_id' => $user_id, ':post_id' => $post_id));
        return $query->rowCount();
    }

    function getVote($user_id, $post_id){
        $query = $this->db->prepare("SELECT * FROM votes WHERE user_id = :user_id AND post_id = :post_id LIMIT 1");
        $query->execute(array(':user_id' => $user_id, ':post_id' => $post_id));
        return $query->fetch();
    }

    function removeVote($user_id, $post_id){
        $query = $this->db->prepare("DELETE FROM votes WHERE user_id = :user_id AND post_id = :post_id");
        $query->execute(array(':user_id' => $user_id, ':post_id' => $post_id));
    }

    function addVote($user_id, $post_id, $type){
        $timestamp = time();
        $query = $this->db->prepare("
        INSERT INTO votes (
            post_id,
            user_id,
            type,
            timestamp
        ) VALUES (
            :post_id,
            :user_id,
            :type,
            :timestamp
        )");
        $query->execute(array(
            ':post_id' => $post_id,
            ':user_id' => $user_id,
            ':type' => $type,
            ':timestamp' => $timestamp
        ));
    }

}
?>


texts: Evaluation of a solution for Run-length encoding algorithm

texts:
I wrote an answer for the following question and wondering if there is any better approach to it.

  Using the Java language, have the function RunLength(str) take the str
  parameter being passed and return a compressed version of the string
  using the Run-length encoding algorithm. This algorithm works by
  taking the occurrence of each repeating character and outputting that
  number along with a single character of the repeating sequence.

  For example: "wwwggopp" would return 3w2g1o2p. The string will not
  contain any numbers, punctuation, or symbols.

Code

 public class App {
    void runLength(String str) {
        HashMap<Character, Integer> hash = new HashMap<Character, Integer>();
        Character c;
        for (int i = 0; i < str.length(); i++) {
            c = str.toLowerCase().charAt(i);
            if (hash.containsKey(c)) {
                int value = hash.get(c);
                value++;
                hash.put(c, value);
            } else {
                hash.put(c, 1);
            }
        }
        int value = 0;

        StringBuffer buf = new StringBuffer();
        String temp;
        for (int j = 0; j < str.length(); j++) {
            c = str.toLowerCase().charAt(j);
            value = hash.get(c);
            temp = str.substring(j, j + 1);
            if (buf.indexOf(c.toString()) == -1) {
                buf.append(value);
                buf.append(temp);
            }

        }
        System.err.println(buf.toString());

    }

    public static void main(String[] args) {
        new App().runLength("wwwggopp");
    }
}

Output

3w2g1o2p


texts:
Could somebody help me work out how to abstract the recursion from this code for me please?
I'm trying to write something that takes a pandoc structure, and subdivides the tree
whenever it finds a sentence, so:

This sentence. Should split.

becomes:

  This sentence.
   Should split.

I have a working implementation, but the recursive part is a bit repetitive:

segment :: [Inline] -> [Inline]
segment [] = []
segment [el] = [el]
segment els @ (head:tail) =
  case head of
    Emph ch -> map (Emph . toList) (segment ch) ++ segment tail
    Strong ch -> map (Strong . toList) (segment ch) ++ segment tail
    Strikeout ch -> map (Strikeout . toList) (segment ch) ++ segment tail
    Superscript ch -> map (Superscript . toList) (segment ch) ++ segment tail
    Subscript ch -> map (Subscript . toList) (segment ch) ++ segment tail
    SmallCaps ch -> map (SmallCaps. toList) (segment ch) ++ segment tail
    Quoted qt ch -> map (Quoted qt . toList) (segment ch) ++ segment tail
    Cite cs ch -> map (Cite cs . toList) (segment ch) ++ segment tail
    Span attr ch -> map (Span attr . toList) (segment ch) ++ segment tail
    _ ->
      maybe [sentence els] (\i -> (sentence $ take i els) : segment (drop i els))
        $ (1 +) <$> List.findIndex split els
  where
    sentence = Span ("sentence", [], [])

split :: Inline -> Bool
split (Str str) = endsWith "." str || endsWith "?" str || endsWith "!" str
split _         = False

endsWith :: String -> String -> Bool
endsWith suff str = suff `List.isSuffixOf` str

toList :: a -> [a]
toList = (: [])

I'm trying to work out a way to hand in some f that will model the part that splits the structure
(i.e the bottom bit), but I'm struggling as the function has to be [Inline] -> [Inline], it's also
as if it needs to be Inline -> [Inline] -> [Inline] as each of the recursive steps need the original
constructor in order to preserve the structure of the document, ie:

This sentence. Should split.

becomes:

  This sentence.
   Should split.


texts:
I was working on a suggestion for this question, but the method, I would've suggested the OP do something similar to, seems a bit convoluted.

It's supposed to take a String input and return an array of only the integers deliminated by spaces. It does this correctly, but It feels like I may be doing some unnecessary things or there's a more succinct way to do this, such as with regex.

public static int[] getIntegers(String s) {
    int[] result;
    ArrayList<Integer> helper = new ArrayList<>();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == ' ' ^ i == s.length() - 1) {
            if (i == s.length() - 1) { sb.append(s.charAt(i)); }
            if (sb.toString().length() > 0) {
                try { helper.add(Integer.parseInt(sb.toString()));
                } catch(NumberFormatException nfe) {
                        // Ignore non-integers
                }
                sb.setLength(0);
                continue;
            }
        }
        sb.append(s.charAt(i));
    }

    result = new int[helper.size()];
    int i = 0;

    for (Integer n : helper) {
        result[i++] = n;
    }
    return result;
}