texts: Google Script - Calendar events not owned by me

texts:
I'm trying to write a script to delete event invites from my personal google calendar. I get invited to multiple events everyday such as "Click here to win an iPhone" etc.

I have written a google script to run each hour and delete any events where I am not the owner. However this is getting all events and then iterating through them to see if I am the owner in a for loop. This seems quite inefficient and takes a long time to run.

Is there a better way to achieve this.

Current code below:

function deleteScamCalendarInvites() {

  var date = new Date();
  var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
  var lastDay = new Date(date.getFullYear() + 5, date.getMonth(), 1);

  var myCalendar = CalendarApp.getDefaultCalendar();
  var myEvents = myCalendar.getEvents(firstDay, lastDay);

  for(var i in myEvents){
    if(myEvents[i].isOwnedByMe() == false){
       var eventId = myEvents[i];
       eventId.deleteEvent();
    }
  }
}


texts:
Essentially what I've done here is written an Interpreter that takes in Python math, such as this, 23 ** 374748, and prints out the result. This program relies on the fact that in Python 2.7 input() is "broken". This means it can take in Python math.

# Main parser class
class Parser(object):
    def __init__(self):
        self.PROMPT = "MaTh @ ==> "
        self.ERR_MSG = "Error: Invalid math!"

    # Parse inputted math
    def parse_math(self):
        while True:
            try:
                math = input(self.PROMPT)
                print "{}\n".format(math)
            except:
                print self.ERR_MSG

# Run the program
if __name__ == "__main__":
    Parser().parse_math()

Can I improve anything here? Is it possible for this to be Python3 compatible?


texts: More efficient and readable nested loop to compare keywords

texts:
I've created an algorithm which weighs the relevance of a list of articles against two lists of keywords that correlate to attributes of the article.

It works great and is super efficient... but it's a mess. It's not terribly readable, so it's difficult to discern what's going.

The operation in pseudo code goes something like this:

Loop through every article in a list called articles(List<Article>)
For every article, loop through every role in a list of roles (List<string>)
Check to see if the current article has any roles (Article.Roles = List<string>)
If yes, then loop through each role in the article and try to match a role in the article to the role in the current loop
If a match is found, add weight to the article. If the index of the role on the article and the role in the roles list are both index 0 (in primary position) add extra weight for two matching primaries
Repeat for topics, but with no bonus for primary matches

What would be a better way to write the following code? I can't use foreach except in one or two places, because I need to match indexes to know what value to add on a match.

private static List<Article> WeighArticles(List<Article> articles, List<string> roles, List<string> topics, List<string> industries)
{
    var returnList = new List<Article>();
    for (int currentArticle = 0; currentArticle < articles.Count; currentArticle++)
    {
        for (int currentRole = 0; currentRole < roles.Count; currentRole++)
        {
            if (articles[currentArticle].Roles != null && articles[currentArticle].Roles.Count > 0)
            {
                for (int currentArticleRole = 0; currentArticleRole < articles[currentArticle].Roles.Count; currentArticleRole++)
                {
                    if (articles[currentArticle].Roles[currentArticleRole].ToLower() == roles[currentRole].ToLower())
                    {
                        if (currentArticleRole == 0 && currentRole == 0)
                            articles[currentArticle].Weight += 3;
                        else
                            articles[currentArticle].Weight += 1;
                    }
                }
            }
        }
        for (int currentTopic = 0; currentTopic < topics.Count; currentTopic++)
        {
            if (articles[currentArticle].Topics != null && articles[currentArticle].Topics.Count > 0)
            {
                for (int currentArticleTopic = 0; currentArticleTopic < articles[currentArticle].Topics.Count; currentArticleTopic++)
                {
                    if (articles[currentArticle].Topics[currentArticleTopic].ToLower() == topics[currentTopic].ToLower())
                    {
                        articles[currentArticle].Weight += 0.8;
                    }
                }
            }
        }
        returnList.Add(articles[currentArticle]);
    }

    return returnList;
}

//Article Class stub (unused properties left out)
public class Article
{
    public List<string> Roles { get; set; }
    public List<string> Topics { get; set; }
    public double Weight { get; set; }
}


texts:
I'm making a calendar and this is one part of the larger project. This adds a tooltip with more information when a calendar event is clicked. It then disappears after 10 seconds, or earlier if a click is detected. The exception being if the click in on the tooltip itself. This code works but feels kind of "cheaty" to me. I wanted a fresh pair of eyes to let me know if there's a better way of doing this all or a specific part I could do differently.

setUpCalendar: function() {
    var self = this; //Refers to the main Calendar Object
    //Render Calendar
    this.elem.fullCalendar({
        height:     this.options.elemHeight,
        events:     this.entries,
        eventClick: function(event, jsEvent, view) {
            var left = parseInt($(this).css("left")) - 4;
            var top =  parseInt($(this).css("top")) - 80;
            self.placeTooltip(left, top, event);
            return false;
        }
    });
},

placeTooltip: function(left, top, event) {
    var toolTip = $(".tooltip"),
        date = $.fullCalendar.formatDate(event.start, "MM dd yyyy hh TT");

    //Format date
    date = date.replace(" ", "/");
    date = date.replace(" ", "/");

    toolTip
        .css({
            "display": "block",
            "position": "absolute",
            "z-index": 10,
            "left": left,
            "top": top
        })
        .html(event.title + "<br />" + date)
        .on("click", function(e) {
            e.stopPropagation(); //Stop click from closing tooltip
        });

    //Remove it later
    $(document).on("click", function() {
        toolTip.hide(); //Hide if clicked anywhere
    });

    if(this.closeTool)
        clearTimeout(this.closeTool);

    this.closeTool = setTimeout(function() {
        toolTip.fadeOut(); //Run this timeout to hide tooltip if not clicked
    }, 10000);
}


texts: Laravel - Repository and Entity patterns

texts:
I've spent quite a bit of time studying the repository and entity patterns and this is what I came up with. I would appreciate it if you could post suggestions and critique.

User entity:

<?php
    namespace App\Entities\Entities\User;

    use
    App\Entities\Abstracts\AbstractEntity,
    App\Repositories\Interfaces\UserRepositoryInterface as UserRepository,
    App\Services\Validation\Laravel\UserLoginValidator,
    Str,
    Exception,
    ExceptionHandler,
    stdClass,
    MessageBag;

    class UserEntity extends AbstractEntity
    {
        protected $loginValidator;

        public function __construct(
            UserRepository $repository
            UserLoginValidator $loginValidator
            )
        {
            $this->repository = $repository;
            $this->loginValidator = $loginValidator;
        }

        public function login(array $input)
        {
            $result = $this->validate($this->loginValidator, $input);
            if(!$result instanceof MessageBag)
            {
                try
                {
                    $user = $this->repository->authenticate(array(
                        'email'     =>  $input['email'],
                        'password'  =>  $input['password']
                        ), false);
                    $this->save($user);
                    $user->type = $user->getGroups()[0]->id;

                    $result = new stdClass;
                    $result->errors = false;
                    $result->status_code = 23;
                    $result->user = $user->toArray();
                    return $result;
                }
                catch (Exception $e)
                {
                    return ExceptionHandler::returnException($e);
                }
            }
            else
                return $this->loginValidator->returnErrors();
        }

    }

User Repository:

<?php

    namespace App\Repositories\Eloquent\User;

    use
    App\Repositories\Abstracts\AbstractRepository,
    App\Repositories\Interfaces\UserRepositoryInterface,
    Cartalyst\Sentry\Sentry as Sentry,
    Cartalyst\Sentry\Users\Eloquent\User as SentryUser;

    class EloquentUserRepository extends AbstractRepository implements UserRepositoryInterface
    {
        public function __construct(Sentry $model)
        {
            $this->model = $model;
        }

        public function find($id)
        {
            return $this->model->findUserById($id);
        }

        public function save(SentryUser $model)
        {
            return $model->save();
        }

        public function getAccessToken()
        {
            return $this->model->getUser()->access_token;
        }
    }
?>

User controller:

<?php
    namespace Controllers\API;
    use
    BaseController,
    Input,
    ResponseSender,
    App\Entities\Entities\User\UserEntity;

    class UserController extends BaseController
    {
        protected $user;

        public function __construct(UserEntity $user)
        {
            $this->user = $user;
        }

        public function postLogin()
        {
            return ResponseSender::send($this->user->login(Input::all()));
        }

    }
?>


texts:
I have a Vue.js computed property as follows.

odds() {
    if(this.course && this.time && this.runner) {
      let race = this.data.events.runners.filter(item => item.course === this.course && item.time === this.time)
      let runner = race[0].data.filter(item => item.name === this.runner)
      return runner[0].odds
    } else {
      return false
    }
}

Although it returns the expected value I think it looks dirty. Can any one suggest best way to write this code.

Sample JSON is as follows.

{
"courses": [{
    "type": "horses",
    "course": "Exeter"
}],
"runners": [{
    "course": "Exeter",
    "time": "14:10",
    "data": [{
        "number": "1",
        "name": "White Lilac",
        "odds": "6\/1"
    }, {
        "number": "2",
        "name": "Sauvignon",
        "odds": "5\/1"
    }, {
        "number": "3",
        "name": "Foxy Lass",
        "odds": "33\/1"
    }, {
        "number": "4",
        "name": "Hot Ryan",
        "odds": "8\/1"
    }, {
        "number": "5",
        "name": "Arqalina",
        "odds": "11\/8"
    }, {
        "number": "6",
        "name": "Presenting Lucina",
        "odds": "14\/1"
    }, {
        "number": "7",
        "name": "Persistantprincess",
        "odds": "12\/1"
    }, {
        "number": "8",
        "name": "Windy Bottom",
        "odds": "20\/1"
    }, {
        "number": "9",
        "name": "Shotgun Sally",
        "odds": "33\/1"
    }, {
        "number": "10",
        "name": "Rule The Ocean",
        "odds": "9\/1"
    }, {
        "number": "11",
        "name": "Avithos",
        "odds": "12\/1"
    }, {
        "number": "12",
        "name": "Monet Moor",
        "odds": "16\/1"
    }]
}]}

I would like to know if there is a much better way to do this. Thanks in advance.


texts: Searching within a data model using an array matching multiple terms

texts:
I have a standard tableview app that displays information from a data model array that uses a custom class. There is a UISearchController to filter the data.

A simplified version of the custom class is shown. I use a computed property for a string that is checked when searching the data.

class myObject: NSObject {

    // Inherits from NSObject as I use NSCoding for persistence

    var id: String = UUID().uuidString // These are unique for each item

    var name: String = ""
    var type: String = ""
    var batch: String = ""

    var searchableString: String {
        // This is a concatenation of some of the properties
        return self.name + " " + self.type + " " + self.batch
    }

    // etc...
}

Every time the user types a new character into the search bar of the UISearchController, the following method is called, which filters the main data array into a filteredItems array. Initially, I used a very basic form where the entire search text had to match.

func searchItems() {
    if let searchText = searchController.searchBar.text {
        filteredItems = allItems.filter { item in
            return item.searchableString.lowercased().contains(searchText.lowercased())
        }
    }
}

filteredItems is then displayed in the tableview.

I wanted to improve this so that each word typed in the search bar is searched for separately. I tried this, but of course it filters using OR logic (any word can match).

func searchItems() {
    if let searchText = searchController.searchBar.text?.split(separator: " ") {
        // Need to convert substring from split back to string
        let searchArray = searchText.map() { substring in
            String(substring)
        }
        filteredItems = allItems.filter { item in
            return searchArray.contains(where: drug.searchableString.lowercased().contains)
        }
    }
}

In order to get the desired AND logic (every word typed must match), I had to use this.

func searchItems() {
    if let searchText = searchController.searchBar.text?.split(separator: " ") {
        // Need to convert substring from split back to string
        let searchArray = searchText.map() { substring in
            String(substring)
        }
        filteredItems = allItems.filter { item in
            for word in searchArray {
                if !item.searchableString.lowercased().contains(word) {
                    return false
                }
            }
            return true
        }
    }
}

This works as intended, but it does not seem elegant. Is there a better way to filter the array allItems to filteredItems based on matching text in those String properties of the objects in my data model?


texts: Calculate next position and velocity after "bounce"

texts:
Intro and code

I have the following function that calculates an object's "next" position and velocity (in 1 dimension) given a boundary [0, max].

public TwoVector<Double> getNextPositionAndVelocity(double position, double velocity, double max) {
    if (position + velocity < 0) {
        return TwoVector.<Double>builder()
                .x(Math.abs(position + velocity))
                .y(Math.abs(velocity))
                .build();
    }
    if (position + velocity > max) {
        return TwoVector.<Double>builder()
                .x(max - ((position + velocity) % max))
                .y(-Math.abs(velocity))
                .build();
    }
    return TwoVector.<Double>builder()
            .x(position + velocity)
            .y(velocity)
            .build();
}

Explanation

The first condition checks if adding the current velocity to the current position would cause the object to be beyond the "left" boundary.  If that's the case, the next position should be equal to the amount the object would be beyond the left boundary added to the left boundary and the next velocity should point the object to the "right".
The second condition checks if adding the current velocity to the current position would cause the object to beyond the "right" boundary.  If that's the case, the next position should be equal to the amount the object would be beyond the boundary subtracted from the boundary and the next velocity should point the object to the "left".
If neither condition is true, we can add the current velocity to the current position to get the next position without issue.

Question

Are there more straightforward functions to calculate each of these "next" values?  Perhaps a function that "collapses" these branches?


texts:
I'm new to C# and I have some questions regarding Tasks, Async, Await.
I wanted to ask what the difference between the following codes (check TestAsyncAwaitMethods definition)
class Program
{
    static void Main(string[] args)
    {
        TestAsyncAwaitMethods();
        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }

    public async static void TestAsyncAwaitMethods()
    {
        await LongRunningMethod();
    }

    public static async Task LongRunningMethod()
    {
        Console.WriteLine("Starting Long Running method...");
        await Task.Delay(5000);
        Console.WriteLine("End Long Running method...");
    }
}

and
class Program
{
    static void Main(string[] args)
    {
        TestAsyncAwaitMethods();
        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }

    public static void TestAsyncAwaitMethods()
    {
       LongRunningMethod();
    }

    public static async Task<int> LongRunningMethod()
    {
        Console.WriteLine("Starting Long Running method...");
        await Task.Delay(5000);
        Console.WriteLine("End Long Running method...");
        return 1;
    }
}

Also I wanted to ask, if someone can re-edit the code in order to show how TestAsyncAwaitMethods() can be blocking, in that way the Console.WriteLine will not happen?

Also I would like to know the difference between:
        public static void TestAsyncAwaitMethods()
        {
            Task.Run(() =>
            {
                LongRunningMethod().Wait();
            });
        }

and
  public static void TestAsyncAwaitMethods()
        {
            Task.Run(async () =>
            {
                await LongRunningMethod();
            });
        }

In the same program, Thanks!


texts: VBA Excel - Conditional Formatting Colour Grab

texts:
This code gets the cell's colour regardless of whether it's set from conditional formatting or not. It currently works on 2010 and unsure about older versions of excel.

My question is is there a way to make this code more efficient?

Such as being able to highlight an area for the code to search rather than setting For stantments
Getting it to search for a specific colour you set rather than red or whatever has been set
Anything else anyone can think of

Sub myCFtest()

For q = 1 To 26

sCol = Split(ActiveCell.Address, "$")(1)
sColNum = sCol & 1
Range(sColNum).Select

For i = 1 To 100

sColNum = ActiveCell.Address

    If Range(sColNum).DisplayFormat.Interior.Color = 255 Then
        Y = ActiveCell.Address
        MsgBox ("Red Cell Found At " & Y)
    End If

ActiveCell.Offset(1, 0).Select

Next i

ActiveCell.Offset(0, 1).Select

Next q

MsgBox ("No Red Cell Found")

End Sub


texts: Another way to run reports on a SpiceWorks SQLite database using a linked server in SSMS?

texts:
I created a linked server in SSMS so that I could run reports on a SpiceWorks SQLite database.  there are a few quirks in the whole system.

These simple queries are becoming some of the most expensive queries on my reporting SQL Server, I kind of know why, is there a way that I can do this differently?

The Code

I have two queries.

TimeToCloseByAssignee

SELECT
    id AS ticketNum
    , Summary
    , Assignee
    , closed_at
    , created_at
    , ROUND((DATEDIFF(Hour, created_at, closed_at))/24. , 2) AS DaysOpen
FROM OPENQUERY(SPICEWORKS,'
    SELECT tickets.id
        , users.email as Assignee
        , substr(tickets . summary, 1,100) AS Summary
        , tickets.closed_at
        , tickets.created_at
    FROM tickets
        INNER JOIN users ON tickets.assigned_to = users.id
WHERE status=''closed''
        AND
        master_ticket_id IS NULL;')

GetCreatorByTicketID

SELECT * FROM OPENQUERY(SPICEWORKS, '
    SELECT users.email
        , tickets.id
    FROM tickets
        INNER JOIN users ON tickets.created_by = users.id')
WHERE id = @TicketID

I am using SSRS to handle the nice presentation of the data.

the problem with this, is that I can't give the underlying SQLite query boundaries from SSRS Parameters, it just doesn't like it. There are some questions on StackOverflow with answers and ways to do it, but this was the only way that I could make it work the way I wanted it to.   perhaps I wasn't interpreting the answers correctly.  either way I don't think it would have been clean and straightforward anyway.

Any thoughts?


texts:
I have a time-critical calculation running on an ARM Cortex-M0. This is the fastest 32x32 bit -> 64 bit multiplication that I can come up with.

The following C compiles almost 1-1 to assembly instructions:

//consider each arg as two 16-bit parts.
//r0 is Aa is A<<16+a. r1 is Bb is B<<16+b
//then Aa * Bb = (A*B)<<32 + (a*B+A*b)<<16 + a*b
//     result  =  Hh<<32   +  KmM<<16      + Ll

uint64_t mul32x32(uint32_t r0, uint32_t r1)
    register uint32_t r2= r1&0xFFFF;  // b
    register uint32_t r3= r1>>16;     // B
    register uint32_t r4= r0&0xFFFF;  // a
    r1 = r0 >> 16;                    // A
    r0 = r4;                // a
    r4 *= r2;               // Ll = a*b
    r0 *= r3;               // a*B
    r3 *= r1;               // Hh = B*A
    r2 *= r1;               // b*A
    r1 = 0;                 // K
    ADD_W_CARRY(r1,r0,r2);  // 0K.mM = a*B + b*A
    r1 <<= 16;              // K0
    r2 = r0 >> 16;          // 0m
    r0 <<=16;               // M0
    DBL_ADD_W_CARRY(r1,r0,r2,r4); // K0.M0 += 0m.Ll
    r1 += r3;                     // Km += Hh
    return (((uint64_t)r1)<<32)|r0;
}

It uses this bit of inline assembly, to deal with C's inability to express the carry flag:

//R.r+=x // clears x to avoid consuming another register
#define ADD_W_CARRY(R,r,x) __asm {\
        ADDS r,r,x;\
        MOVS x,0x0;\
        ADCS R,R,x;}
//pure C equiv is:  {r+=x;R+=(r<x);x=0;}

//R.r+=X.x
#define DBL_ADD_W_CARRY(R,r,X,x) __asm{\
        ADDS r,r,x;\
        ADCS R,R,X;}
//Pure C equiv is:  {r+=x;R+=X+(r<x); }

This compiles to:

PUSH     {r4}         ;// 2
LSRS     r3,r0,#16    ;// 1
UXTH     r2,r1        ;// 1
UXTH     r0,r0        ;// 1
MOV      r4,r0        ;// 1
LSRS     r1,r1,#16    ;// 1
MULS     r4,r2,r4     ;// 1
MULS     r0,r1,r0     ;// 1
MULS     r1,r3,r1     ;// 1
MULS     r2,r3,r2     ;// 1
ADDS     r0,r0,r2     ;// 1
MOVS     r3,#0        ;// 1
MOVS     r2,#0        ;// 1
ADCS     r3,r3,r2     ;// 1
LSLS     r2,r3,#16    ;// 1
LSRS     r3,r0,#16    ;// 1
LSLS     r0,r0,#16    ;// 1
ADDS     r0,r0,r4     ;// 1
ADCS     r2,r2,r3     ;// 1
POP      {r4}         ;// 2
ADDS     r1,r2,r1     ;// 1
BX       lr           ;// 3

                      ;== 26 cycles

Is it possible to do better?


texts: Billing and recurrent payment db structure

texts:
I am designing my first payment service and here is my db structure.

Each user can have many businesses, each business can have many products. Some are recurring, some are paid once. Each product is tied to payment method. Some products are always free, and some are paid every X days.

CREATE TABLE `payment_method` (
  `payment_method_id` int(11) NOT NULL auto_increment,
  `payment_method_name` VARCHAR(20) DEFAULT NULL,
  `payment_method_status` ENUM('active','disabled') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'active',
  PRIMARY KEY  (`payment_method_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1;

CREATE TABLE IF NOT EXISTS `product_type` (
  `product_type_code` varchar(50) NOT NULL,
  `product_type` varchar(150) NOT NULL,
  `product_type_name` varchar(150) NOT NULL,
  PRIMARY KEY (`product_type_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `product` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `product_price` decimal(12,2) DEFAULT NULL,
  `product_duration` int(11) DEFAULT NULL,
  `product_currency` varchar(50) NOT NULL,
  `recurring` enum('yes','no') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'yes',
  `daily_limit` int(11) DEFAULT NULL,
  `monthly_limit` int(11) DEFAULT NULL,
  `lifetime_limit` int(11) DEFAULT NULL,
  `product_type_code` varchar(50) NOT NULL,
  `product_description` varchar(150) DEFAULT NULL,
  PRIMARY KEY (`product_id`),
  FOREIGN KEY (product_type_code) REFERENCES product_type(product_type_code)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `product_detail` (
  `product_detail_id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `key` varchar(150) DEFAULT NULL,
  `value` varchar(150) DEFAULT NULL,
  PRIMARY KEY (`product_detail_id`),
  KEY `product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `business_product` (
  `business_product_id` int(11) NOT NULL,
  `product_id` int(11) DEFAULT NULL,
  `business_id` int(11) DEFAULT NULL,
  `added_by_user_id` int(11) NOT NULL,
  `product_price` decimal(12,2) DEFAULT NULL,
  `product_currency` varchar(5) NOT NULL,
  `product_type` varchar(150) NOT NULL,
  `business_product_status` enum('paid','canceled') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
  `start_date` date NOT NULL,
  `end_date` date DEFAULT NULL,
  `last_update_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`business_product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `user_authorized` (
  `user_authorized_id` int(11) NOT NULL auto_increment,
  `payment_method_id` int(11),
  `authorized`  varchar(150),
  `autopay` enum('yes','no') CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'yes',
  PRIMARY KEY  (`user_authorized_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1;

CREATE TABLE `billing` (
  `billing_id` int(11) NOT NULL auto_increment,
  `external_id` VARCHAR(100) DEFAULT NULL,
  `invoice_date` datetime,
  `bill_date` datetime,
  `start_date` date,
  `end_date` date,
  `payment_method_id` int(11) default NULL,
  `user_id` int(11) default NULL,
  `authorized` VARCHAR(200) DEFAULT NULL,
  `fee` decimal(12,2) default NULL,
  `notes` varchar(500) default NULL,
  `billing_status` ENUM('new','paid','returned','canceled', 'pending', 'overdue')  CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT 'new',
  PRIMARY KEY  (`billing_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 ;

CREATE TABLE `billing_detail` (
  `billing_detail_id` int(11) NOT NULL auto_increment,
  `billing_id` int(11) NOT NULL,
  `product_id` int(11),
  `business_id` int(11),
  `product_price` decimal(12,2),
  PRIMARY KEY  (`billing_detail_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 ;

```

What do you think am I missing something?


texts: parallel processing of files from a directory

texts:
This code does parallel processing of files read from a directory. It divides the directory into 'core' number of file chunks and process those chunks in parallel. 'cores' is the number of cores in the linux system.
from multiprocessing import Process
import os
from time import sleep
import multiprocessing

pros = []

def getFiles(directory):
    '''returns the files from a directory'''
    for dirpath,_,filenames in os.walk(directory):
        for f in filenames:
            yield os.path.abspath(os.path.join(dirpath, f))

def countFiles(directory):
    return len([name for name in os.listdir(directory) if os.path.isfile(os.path.join(directory, name))])

def foo(fileList):
    print(fileList)

def isCommon(a, b):
    aSet = set(a)
    bSet = set(b)
    if len(aSet.intersection(bSet)) > 0:
        return(True)
    return(False)

if __name__ == "__main__":
  '''get count of files in directory and split it in based on number of cores'''
  directory = ""
  noCores = multiprocessing.cpu_count()
  totalFilesCount = countFiles(directory)
  chunkSize = totalFilesCount/noCores
  totalChunks = noCores
  print("total files", totalFilesCount, "total chunks", totalChunks, "chunk size", chunkSize)
  filesProcessed = 0
  currentChunk = 0
  fileObj = getFiles(directory)

  listOFFiles = []
  while filesProcessed < totalFilesCount:
      filesList = []

      # if it is last chunk and totalFilesCount can't be divided equally then put leftover files in last core to get processed
      if currentChunk == totalChunks - 1 and totalFilesCount%noCores:
          chunkSize += totalFilesCount%noCores

      reached = 0
      for f in fileObj:
          filesList.append(f)
          if chunkSize == reached:
              break
          reached += 1

      listOFFiles.append(filesList)
      p = Process(target=foo, args=(filesList,))
      pros.append(p)
      p.start()

      currentChunk += 1
      filesProcessed += chunkSize

  for t in pros:
     t.join()

  for a, b in zip(listOFFiles, listOFFiles[1:]):
     assert isCommon(a, b) == False


texts: 'join' MongodDB collections with a for loop

texts:
This is a very simplified version of my query. Is it acceptable to join the two collections for the client with the use of for loops?

There could be up to 2,000 books, which also means there could be an equal number of favorite books per user in the favoriteBooksCollection.

return favoriteBooksCollection
.find({user: current_userId})
.then(function(favorites){

    var bookIds = favorites.map(function (a) {
        return a.bookId
    };

    return BooksCollection
    .find({_id : {$in: bookIds}})
    .sort({timestamp: -1})
    .then(function(books){

     for(var i = 0; i < books.length; i++){
        for(var j = 0; j < favorites.length; j++){
          if(favorites[j].bookId  == books[i]._id){

           //'join' user's myRating to book document here
            books[i].userRating = favorites[j].myRating;

           };
        };
    };

      // return books array of objects with newly added UserRating property
      return books;

    });

});


texts: Good Vs. Evil - Battle For Middle Earth - CodeWars

texts:
This is the code that I'm submitting for the "Good vs Evil" Kata on CodeWars:

https://www.codewars.com/kata/good-vs-evil/train/javascript

function goodVsEvil(good, evil) {
  good = good.split(' ');
  evil = evil.split(' ');

  //hobbits, men, elves, etc
  let goodWorth = [1, 2, 3, 3, 4, 10];
  //orcs, men, wargs, etc
  let evilWorth = [1, 2, 2, 2, 3, 5, 10];

  let goodArmyPoints = [];
  //multiply goodWorth by type:
  for (let i = 0; i < goodWorth.length; i++) {
    goodArmyPoints.push(good[i] * goodWorth[i]);
  }

  goodArmyPoints = goodArmyPoints.reduce(function (sum, value) {
    return sum + value;
  });

  let evilArmyPoints = [];
  for (let j = 0; j < evilWorth.length; j++) {
    evilArmyPoints.push(evil[j] * evilWorth[j]);
  }

  evilArmyPoints = evilArmyPoints.reduce(function (sum, value) {
    return sum + value;
  });

  if (evilArmyPoints < goodArmyPoints) {
    return "Battle Result: Good triumphs over Evil";
  } else if (evilArmyPoints > goodArmyPoints) {
    return "Battle Result: Evil eradicates all trace of Good";
  } else {
    return "Battle Result: No victor on this battle field";
  }

}

But I'm not sure what:

goodArmyPoints = goodArmyPoints.reduce(function (sum, value) {
    return sum + value;
  });

is doing exactly.

I see that reduce "executes a reducer function (which I've provided?) on each member of the array, resulting in a single output value".

But can someone please walk me through what .reduce(function (sum, value) is doing, exactly? Where is this function coming from? What are sum and value?

I'm still learning JavaScript and this is new to me. Thanks.


texts: Calculation of Reynolds number for a pipe

texts:
I'm new to coding and want to pick up some good habits with regards to coding conventions and general readability (I am using PEP8 as a guideline). Below I added a very simple function. Feel free to give me some pointers on what to improve/change about the commenting. Should I be catching any other errors?

def reynolds(den, vel, dia, vis):
    """Calculate the Reynolds number for a given pipe flow.

    Arguments:
    den -- density of the fluid in [kg/m3]
    vel -- the mean velocity of the fluid in [m/s]
    vis -- dynamic viscosity of the fluid in [Pa*s]
    dia -- inside diameter of the pipe in [m]

    The Reynolds number itself is dimentionless.
    It is used to charakterize flow patterns.
    """
    try:
        return den*vel*dia/vis       # regular execution of the function
    except ZeroDivisionError:
        print ('divide by zero')     # catch devision by zero


texts:
A couple months ago I made an interactive dijktra visualizer that allowed the user to setup the map nodes and run the algorithm. I thought it was a good way to solidify my algorithm and html/css knowledge. I'd like for you guys to test my application out and give any advice in any way I could make it better.
One particular element that i'd like to improve is the map rendering, which I did by making a table and updating it's rows and columns. This solution worked out good but I found it to be slow with maps with larger dimensions.
function render () {
    let html = ''

    for (let row = 0; row < mapHeight; row++) {
        html += '<tr>'

        for (let column = 0; column < mapWidth; column++) {
            // Ignore "nodeIndex", "colorIndex" and such
            nodeIndex = column + ( row * mapWidth )
            let colorIndex = myNodes[nodeIndex].colorIndex

            html += `<td style="background-color:${nodeColors[colorIndex]};"></td>`
        }

        html += '</tr>'
    }

    //"mapTable" being the element in which this table is rendered
    mapTable.innerHTML = html
}

Hope you guys like it and please feel welcome to give any criticism, have fun!
My page: https://github.com/Tlomoloko/Dijkstra_Visualizer


texts:
I have a simple ASP.NET Web API project. Now I want to make all basic methods as asynchronous. I tried to do something, and it's working but I'm not sure that it was implemented properly.

Please check whether I properly implemented async/await in my project.

I had implemented methods like below in my repository:

        public T GetById(object id)
        {
            return this.Entities.Find(id);
        }
        public void Insert(T entity)
        {
            try
            {
                if (entity == null)
                {
                    throw new ArgumentNullException("entity");
                }
                this.Entities.Add(entity);
                this.context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        errorMessage += string.Format("Property: {0} Error: {1}",
                        validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
                    }
                }
                throw new Exception(errorMessage, dbEx);
            }
        }

I tried to create async methods:

        public Task InsertAsync(T entity)
        {
            return Task.Run(() => Insert(entity));
        }
        public Task<T> GetByIdAsync(object id)
        {
            return Task.Run(() => GetById(id));
        }

And now I'm using it as:

      public async virtual Task<HttpResponseMessage> Post([FromBody]T entity)
      {
                try
                {
                    await repository.InsertAsync(entity);
                    return Request.CreateResponse(HttpStatusCode.Created, entity);
                }
                catch (Exception ex)
                {
                    return ErrorMsg(HttpStatusCode.InternalServerError, ex.Message);
                }

       }
       public async virtual Task<HttpResponseMessage> GetById(int id)
       {
            var entity = await repository.GetByIdAsync(id);

            if (entity == null)
            {
                var message = string.Format("No {0} with ID = {1}", GenericTypeName, id);
                return ErrorMsg(HttpStatusCode.NotFound, message);
            }
            return Request.CreateResponse(HttpStatusCode.OK, entity);
       }


texts: Return the state of collection based on individual object states

texts:
The following code is a simplified version of what I want to achieve. Each object may have one of several states, and the overall collection state depends on the state of each of these objects. Currently, the code is written in the form of several if-else blocks, however, it seems ugly and non-extensible. By that, I mean, tomorrow if additional object states are added, I would end up adding several more flags and if-conditions, making the code difficult to read and maintain. Can this be done in a better way?

internal enum State
{
    Error,
    Warning,
    Okay
}

internal enum CollectionState
{
    Error,
    AllWarnings,
    AllOkay,
    OkayAndWarnings
}

internal class MyClass
{
    //other properties...

    internal State State { get; set; }
}

internal class MyBusinessLogic
{
    /// <summary>
    /// 1. If any object is in Error state, CollectionState is Error.
    /// 2. If all objects are in Warning state, CollectionState is AllWarnings.
    /// 3. If all objects are in Okay state, CollectionState is AllOkay.
    /// 4. If some objects are in Okay state and some in Warning state, CollectionState is OkayAndWarnings
    /// </summary>
    internal CollectionState GetCollectionState(IList<MyClass> objectList)
    {
        bool isError, isOkay, isWarning;
        isError = isOkay = isWarning = false;
        foreach (var myObject in objectList)
        {
            if (myObject.State == State.Error)
            {
                isError = true;
                break;
            }
            if(myObject.State == State.Okay)
            {
                isOkay = true;
            }
            else if (myObject.State == State.Warning)
            {
                isWarning = true;
            }
        }

        if (isError)
        {
            return CollectionState.Error;
        }
        else if(!isOkay && isWarning)
        {
            return CollectionState.AllWarnings;
        }
        else if (isOkay && !isWarning)
        {
            return CollectionState.AllOkay;
        }
        else //if(isOkay && isWarning)
        {
            return CollectionState.OkayAndWarnings;
        }
    }
}


texts: LeetCode 560: Subarray Sum Equals K - C++/Java

texts:
According to LeetCode, the following question is one of the most frequent interview questions asked by companies such as Facebook and Google. Here, I'm posting C++/Java codes, if you'd like to review, please do so.
LeetCode 560

Given an array of integers and an integer target (K), you need to find the
total number of continuous subarrays whose sum equals to target.
Example 1:
Input:nums = [1,1,1], target = 2 Output: 2
Constraints:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer target is [-1e7,
1e7].

C++
class Solution {
public:
    int subarraySum(vector<int> &nums, int target) {
        map<int, int> prefix_sum;
        int sum = 0, subarrays = 0;
        prefix_sum[0]++;
        for (int index = 0; index < nums.size(); index++) {
            sum += nums[index];
            subarrays += prefix_sum[sum - target];
            prefix_sum[sum]++;
        }

        return subarrays;
    }
};

Java
class Solution {
    public int subarraySum(int[] nums, int target) {
        int sum = 0, subarrays = 0;
        Map<Integer, Integer> prefixSum = new HashMap<>();
        prefixSum.put(0, 1);

        for (int index = 0; index != nums.length; index++) {
            sum += nums[index];

            if (prefixSum.get(sum - target) != null)
                subarrays += prefixSum.get(sum - target);

            prefixSum.put(sum, -~prefixSum.getOrDefault(sum, 0));
        }

        return subarrays;
    }
}

Reference

LeetCode 560
LeetCode 560 Discussion Board


texts: Gather all IP addresses of a host as a vector

texts:
I have the following working code to get IPv4/v6 addresses from host names:
#include <array>
using std::array;

#include <iostream>
using std::cout;

#include <netdb.h>

#include <stdexcept>
using std::domain_error;

#include <sys/socket.h>

#include <string>
using std::string;

#include <vector>
using std::vector;

#include <boost/asio.hpp>
using boost::asio::ip::address;
using boost::asio::ip::address_v4;
using boost::asio::ip::address_v6;

vector<address> getAddresses(string const &hostname)
{
    struct addrinfo req = {.ai_family = AF_UNSPEC, .ai_socktype = SOCK_STREAM};
    struct addrinfo *pai;
    int error = getaddrinfo(hostname.c_str(), nullptr, &req, &pai);
    if (error)
        throw domain_error("Could not resolve host name.");

    vector<address> addresses;

    for(struct addrinfo *info = pai; info != nullptr; info = info->ai_next) {
        if (info->ai_family == AF_INET) {
            auto ipv4socket = reinterpret_cast<struct sockaddr_in*>(info->ai_addr);
            auto ipv4addr = address_v4(htonl(ipv4socket->sin_addr.s_addr));
            addresses.emplace_back(ipv4addr);
        } else {
            auto ipv6socket = reinterpret_cast<struct sockaddr_in6*>(info->ai_addr);
            auto ipv6base = reinterpret_cast<unsigned char*>(ipv6socket->sin6_addr.s6_addr);
            array<unsigned char, 16> bytearray = {
                ipv6socket->sin6_addr.s6_addr[0],
                ipv6socket->sin6_addr.s6_addr[1],
                ipv6socket->sin6_addr.s6_addr[2],
                ipv6socket->sin6_addr.s6_addr[3],
                ipv6socket->sin6_addr.s6_addr[4],
                ipv6socket->sin6_addr.s6_addr[5],
                ipv6socket->sin6_addr.s6_addr[6],
                ipv6socket->sin6_addr.s6_addr[7],
                ipv6socket->sin6_addr.s6_addr[8],
                ipv6socket->sin6_addr.s6_addr[9],
                ipv6socket->sin6_addr.s6_addr[10],
                ipv6socket->sin6_addr.s6_addr[11],
                ipv6socket->sin6_addr.s6_addr[12],
                ipv6socket->sin6_addr.s6_addr[13],
                ipv6socket->sin6_addr.s6_addr[14],
                ipv6socket->sin6_addr.s6_addr[15]
            };
            auto ipv6addr = address_v6(bytearray, ipv6socket->sin6_scope_id);
            addresses.emplace_back(ipv6addr);
        }
    }

    return addresses;
}

int main()
{
    auto addresses = getAddresses("heise.de");

    for (auto ipa : addresses)
        cout << "Address: " << ipa << "\n";

    return 0;
}

I find the conversion fom uint8_t[16] (ipv6socket->sin6_addr.s6_addr) to std::array<unsigned char, 16> a bit verbose.
I also considered doing it in a for-loop, but this would still seem cumbersome to me, somehow.
I tried static_cast and reinterpret_cast to no avail.
Is there a possibility to do this conversion in a simpler way, preferably a one-liner?


texts: C++ choose between runtime and compile time implementation functions

texts:
I wrote a small wrapper function to choose between runtime (std) sqrt and a constexpr version, as a continuation of the vector class I published here earlier:

C++ mathematical n-dimensional vector template using fold expressions

It seems to work fine and Compiler Explorer shows that the sqrt function is completely compiled out.

The relevant code (sqrt coming from the standard library):

constexpr T cx_sqrt(const T& m) const {
    int i = 0;
    while((i*i) <= m) {
        i++;
    }
    i--;
    T d = m - (i * i);
    T p = d / (2 * i);
    T a = i + p;
    return a - (p * p) / (2 * a);
}

constexpr T choose_sqrt(const T& m) const {
    return (__builtin_constant_p(m) && __builtin_constant_p(*m)) ?  cx_sqrt(m) : sqrt(m);
}

template <size_t... I>
constexpr T magnitude_impl(std::index_sequence<I...>) const {
    return choose_sqrt(((values[I] * values[I]) + ...));
}

Any gotchas using a method like this?


texts:
I have a dataset and I want to search task name inside initialTasks array.
const stagesTasks = [
    {
      "dataTestID": "stage-0",
      "headerText": "Backlog",
      "initialTasks": ["task 1", "task 2", "task 3"]
    },
    {
      "dataTestID": "stage-1",
      "headerText": "To Do",
      "initialTasks": ["task 4", "task 5", "task 6"]
    },
    {
      "dataTestID": "stage-2",
      "headerText": "Ongoing",
      "initialTasks": ["task 7", "task 8"]
    },
    {
      "dataTestID": "stage-3",
      "headerText": "Done",
      "initialTasks": ["task 9"]
    }
  ]

For example if I want to know dataTestID for "task 8", I have to make two loops. Like below :-
getStageName = task => {
    for(let record of stagesTasks){
      for(let data of record.initialTasks){
        if(data === task){
          return record
        }
      }
    }
    return null
  }

Just need your guidance to identify is there any way to avoid two loops?


texts:
I have followed this format in my application to call the API and get data from it:

getCheckoutDetails(): Observable<UserDetail> {
    let query = `7668`;
    return this.http
        .get(this.appConfig.getAPIUrl()
            + `/buy/getDetails?${query}`)
        .map(this.extractData)
        .catch(this.handleErrors);
}

private extractData(res: Response) {
    let data = res.json();
    return data.body ? data.body.message ? data.body.message : {} : {};
}

private handleErrors(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
        const body = error.json() || '';
        const err = body.error || JSON.stringify(body);
        errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
        errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
}

This is sample code on one service. Now this has been followed in all services to handle data and error. When I run gulp cpd command to detect the duplicate code, it lists down all the files. Is there a way to handle this without duplicating?


texts: Define a range based on passed arguments

texts:
TL;DR I'm self teaching VBA, learning about functions and passing arguments from a subroutine into the function and want to know if my very basic function to define a range is optimal and follows correct referencing/standards/practices.

I'm teaching myself VBA (mostly in MS Excel) as a starting point into programming in my spare time (what little of it I have) with the goal of a career change and am now learning how to utilise functions.

Below is a function I have written to define a range based on the variables passed as arguments. As you will see the worksheet, first row and first column are required arguments and the second row and second column are optional.

The function will assign the value of the first row (or column) to the second row (or column) if the optional argument is omitted.

Function defineRange(mySheet As Object, startRow As Long, firstColumn As Long, Optional endRow As Long, Optional secondColumn As Long) As Object

'will create a single row range
If endRow = 0 Then
    endRow = startRow
End If
'will create a single column range
If secondColumn = 0 Then
    secondColumn = firstColumn
End If

'Define the A1 reference for the range with cells.address parameter using arguments as the row and column index.
Set defineRange = mySheet.Range(Cells(startRow, firstColumn).Address, Cells(endRow, secondColumn).Address)

End Function

As an example I'd call it from a subroutine as follows:

Sub test()

Dim myRange As Object

Set myRange = defineRange(ThisWorkbook.Sheets(1), 5, 2, 10, 4)

myRange.Select

End Sub

The result is Range("B5:D10") is selected on sheet1 of the workbook.

Is the function code optimal?
Have best practices been followed?


texts: Write a lock free singleton factory using generics in c#

texts:
I am writing a generic CacheProvider factory which contains a concurrent dictionary to keep the "Named" cache objects (a custom implementation of memory cache based on concurrent dictionary) to be shared among different state machines/pipelines.

I found this article and came up with below implementation

public class CacheProvider<TKey, TType>
{
    private Eventing.Tracer tracer;
    public delegate TType CreateObjectDelegate();
    private readonly ConcurrentDictionary<TKey, CreateObjectDelegate> FactoryMap;
    private ConcurrentDictionary<TKey, TType> cachePool;
    private static object _lock = new object();

    /// <summary>
    /// This class is a singleton wrapper on custom memory cache class to be shared with different state machines
    /// </summary>
    /// <param name="tracer"></param>
    public CacheProvider(Eventing.Tracer tracer)
    {
        Contract.Requires<ArgumentException>(tracer != null, "tracer cannot be null");
        this.tracer = tracer;
        cachePool = new ConcurrentDictionary<TKey, TType>();
        FactoryMap = new ConcurrentDictionary<TKey, CreateObjectDelegate>();
    }

    public void Register(TKey key, CreateObjectDelegate ctor)
    {
     // This method registers a delegate to the method used to create the
       object so that it can be created later.
       //
      FactoryMap.TryAdd(key, ctor);
    }

    public TType CreateOrGetMemoryCache(TKey key)
    {
            if (cachePool.TryGetValue(key, out TType memoryCache))
            {
                tracer.Trace(SplitterTraceCodes.CacheProvider, $"MemoryCache with cache key: {key} already created.");
                return memoryCache;
            }
            else
            {
                tracer.Trace(SplitterTraceCodes.CacheProvider, $"MemoryCache with cache key: {key} not found.");

                // Create a new one
                CreateObjectDelegate constructor = null;
                if (FactoryMap.TryGetValue(key, out constructor))
                {
                    cachePool.TryAdd(key,constructor());
                    cachePool.TryGetValue(key, out TType memoryCache);
                    return memoryCache;
                }

                throw new ArgumentException("Error in Creating MemoryCache. No Type registered for this Cache Key");
            }
    }
}

TType is as follows:

MyBase
{
  string BaseProperty1;
}
MyChild1 : MyBase
{
  string ChildProperty1;
}
MyChild2 : MyBase
{
 string ChildProperty2;
}

I am looking to setup this at service startup as follows:

CacheProvider<string, object> cacheProvider= new CacheProvider<string, object>();
CacheProvider<string, object>.CreateObjectDelegate createCacheForMyChild1 = new CacheProvider<string, object>.CreateObjectDelegate(CustomConcurrentCache<string,MyChild1>());
CacheProvider<string, object>.CreateObjectDelegate createCacheForMyChild2 = new CacheProvider<string, object>.CreateObjectDelegate(CustomConcurrentCache<string,MyChild2>());
cacheProvider.Register("MyChild1Cache", createCacheForMyChild1 );
cacheProvider.Register("MyChild2Cache", createCacheForMyChild2 );

and use it wherever I need the named cache instance:

CustomConcurrentCache<string,MyChild1> cache =  (MyChild1)cacheProvider.CreateOrGetMemoryCache<object>("MyChild1Cache");

Can this be done without using the delegates? Is there any other better way to achieve this?


texts: Function measuring time of another function

texts:
I wanted to have a function called timeit which can measure the time of execution of n iterations of any other function. I still learning C++ but I come up with that : Any thought ?
#include<chrono>

using namespace std;

template<typename output, typename ...ArgsT, typename ...Input>
double timeit(output (*function)(Input...), int n, ArgsT ...args)
{
   auto start = chrono::high_resolution_clock::now();
   for(int k = 0; k < n; ++k)
   {
      function(args...);
   }
   auto end = chrono::high_resolution_clock::now();
   chrono::duration<double> elapsed = (end-start);
   return elapsed.count();
}


texts:
I feel like I can make my switch statements more elegant with a function pointer, i.e. I'd like to set the digestLength and a pointer to a function in the same switch statement instead of setting the length, declaring the result array, then calling the function.

- (NSString *)hashWithDigestType:(NSStringDigestType)type {
    const char *s = [self UTF8String];
    int digestLength;

    switch (type) {
        case NSStringDigestTypeMD5:
            digestLength = CC_MD5_DIGEST_LENGTH;
            break;
        case NSStringDigestTypeSHA1:
            digestLength = CC_SHA1_DIGEST_LENGTH;
            break;
        case NSStringDigestTypeSHA512:
            digestLength = CC_SHA512_DIGEST_LENGTH;
            break;
    }

    unsigned char result[digestLength];

    switch (type) {
        case NSStringDigestTypeMD5:
            CC_MD5(s, strlen(s), result);
            break;
        case NSStringDigestTypeSHA1:
            CC_SHA1(s, strlen(s), result);
            break;
        case NSStringDigestTypeSHA512:
            CC_SHA512(s, strlen(s), result);
            break;
    }

    NSMutableString *digest = [NSMutableString stringWithCapacity:(digestLength * 2)];
    for (NSUInteger i = 0; i < digestLength; i++)
        [digest appendFormat:@"%02x",result[i]];

    return [NSString stringWithString:digest];
}


texts: Scan over parameter iterator for model simulation

texts:
I'm writing a small Python application that performs model simulation for many different parameters. The iterator of parameters isn't completely known ahead of time. Rather, the iterator needs to change and adapt based on the results of the previous simulations.

The code illustrates how I implemented a prototype of the parameter scanning algorithm, but the solution feels non-pythonic (ugly, implicit, complex,....). Specifically, it feels problematic to modify the iterator over which I'm looping inside the for loop. I've consulted google looking for pythonic constructs that meet my needs, but have been unable to find any ("adaptable iterator", "modifiable generator",....).

Is there a more pythonic way to express the logic in the function scan()?

import random as r

def scan(simulate, iterator, process):
    """A simple scanning procedure of parameters in an iterator. Perform a simulation on
    each parameter in the iterator, process the output of the simulation, update the iterator"""
    for parameter in iterator:
        print(parameter)  # for prototype logging

        # simulate a model for a particular parameter value
        result = simulate(parameter)

        # update the process object via the call method
        process.call(result)

        # update the iterator based on the currently processed simulations (e.g. stochastic optimization)
        iterator.update(process)

    return process.finish()

# toy simulator
def mysimulate(p):
    return r.random() > .5

# example adaptable iterator
class MyIter:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        return self

    def __next__(self):
        if self.i < self.n:
            i = self.i
            self.i += 1
            return i
        else:
            raise StopIteration()

    def update(self, process):
        """update takes in a process object and modifies the iterator according to some algorithm to change
        the values returned by __next__"""
        if r.random() < .4:
            self.i -= 1

class MyProcess:
    """Toy processing object."""
    log = []

    def call(self, trajectory):
        self.log.append(trajectory)

    def finish(self):
        return sum(self.log)

out = scan(mysimulate, MyIter(20), MyProcess())

print(out)


texts:
Please review and recommend improvements.  It looks horrible to me, difficult to read, too lengthy, and just plain old inelegant.  But I don't see the potential improvements.

private boolean useCachedReportBean(BeanReport cachedReportBean, String strRequestedReportID)
    throws ExceptionInvalidReportRequest
{
    /*  There may or may not be a cached report
     * bean, and their may or may not be a requested
     * report ID.  If both exist, and they match, use
     * the cached report bean.  If only one of
     * the two exist, use it.   Finally if neither exist,
     * throw an Exception.
     */
    if (strRequestedReportID == null || "".equals(strRequestedReportID)) {
        if (cachedReportBean == null) {
            throw new ExceptionInvalidReportRequest(
                    "The request ID is invalid and no cached report exists.");
        } else {
            /* There was no requested ID but there is a cached bean.
             * Returning true causes the cache to be used. */
            return true;
        }
    }
    /* If we are here, we know that there is a requested ID.
     * If there is no cached bean, use the request id. */
    if (cachedReportBean == null) {
        return false;
    }
    /* There is a requested ID and cached bean.  If they match, use the cached bean. */
    if (strRequestedReportID.equalsIgnoreCase(cachedReportBean.getConfigBean().getReportID())) {
        return true;
    } else {
        return false;
    }
}


texts: Function to download anonymous type data into excel

texts:
As far as I know, I cannot create function to accept anonymous type as parameter and I am reluctant to create new class to store those anonymous type because their difference is calculatedPrice.

How else can I remove\minimize repeated code in code below?

//.NET Framework 4
protected void btnDownload_Click(object sender, EventArgs e)
{
    var vwTransactionInfoItemProcesses = DAL.TransactionItemProcessHandler.GetVwTransactionInfoItemProcess(dropDownListTransactionStatus.SelectedValue.Trim(), BLL.SessionFacade.currentUserDeptCode.Trim(), true, txtSearchVendorCode.Text.Trim(), txtSearchCreateBy.Text.Trim(), txtSearchTransactionNumber.Text.Trim(), DateTime.Parse(txtCreateFrom.Text.Trim()), DateTime.Parse(txtCreateTo.Text.Trim()).Add(new TimeSpan(23, 59, 59)), txtSearchProductionOrder.Text.Trim(), txtSearchPartNumber.Text.Trim());

    if (BLL.UserRole.CheckUserRoleExist(BLL.SessionFacade.currentUserId, "purchaser"))
    {
        var vwTransactionInfoItemProcessesInDownloadFormat = vwTransactionInfoItemProcesses.Select(x => new
        {
            transactionNumber = x.transactionNumber,
            processName = x.processName,
            processOrder = x.processOrder,
            processQuantity = x.processQuantity,
            processUOM = x.processUOM,
            calculatedPrice = x.calculatedPrice
        }).ToList();
        DataTable transactionInfoItemProcessesInDownloadFormat = BLL.General.ConvertToDatatable(vwTransactionInfoItemProcessesInDownloadFormat);
        HSSFWorkbook workbook = BLL.General.GenerateNPOIExcelXLS(transactionInfoItemProcessesInDownloadFormat);
        ExportToExcel(workbook);
    }
    else
    {
        var vwTransactionInfoItemProcessesInDownloadFormat = vwTransactionInfoItemProcesses.Select(x => new
        {
            transactionNumber = x.transactionNumber,
            processName = x.processName,
            processOrder = x.processOrder,
            processQuantity = x.processQuantity,
            processUOM = x.processUOM
        }).ToList();
        DataTable transactionInfoItemProcessesInDownloadFormat = BLL.General.ConvertToDatatable(vwTransactionInfoItemProcessesInDownloadFormat);
        HSSFWorkbook workbook = BLL.General.GenerateNPOIExcelXLS(transactionInfoItemProcessesInDownloadFormat);
        ExportToExcel(workbook);
    }
}


texts: Separating logic per class and being able to use dependency injection

texts:
I use Laravel, but hopefully this doesn't matter. I have a user and user's state. Say, simple integer or a string. I want to run some logic depending on user state in my service class.

So, the first approach is pretty simple:

<?php

class UserStateManager
{
    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function handle(UserRepository $userRepository)
    {
        $user = $this->userRepository->find(1);
        switch ($user->state) {
            case 'new':
                $this->handleUserNewState();
                break;
            case 'banned':
                $this->handleUserBannedState();
                break;
            // ...
        }
    }

    private function handleUserNewState()
    {
        // Do some logic
        // Here we have access to userRepository which was injected in UserStateManager constructor
    }

}

Pay attention that I injected UserRepository in the constructor.

So, using this approach I keep UserStateManager dependencies injected, without creating them manually.

But now I want to put every state handler to a separate class. Like, to have UserNewState class with handle method.

The problem is that in this case:

public function handle(UserRepository $userRepository)
    {
        $user = $this->userRepository->find(1);
        switch ($user->state) {
            case 'new':
                (new UserNewState)->handle();
                break;
            case 'banned':
                (new UserBannedState)->handle();
                break;
            // ...
        }
    }

if I create UserNewState object I cannot inject dependencies into this class since I manually create it using new operator. Passing lots of dependencies in the constructor (like new UserNewState($this->userRepository, ...)) is not an option, ugly solution.

So how to deal with this case? Because it's very common: on the one hand I can separate logic into several methods inside one class, on the other hand I cannot separate logic into many classes.

The problem is dependency injection and creating these class manually. And I reckon that DI is a good thing.

Of course I can create dependencies inside UserNewState class, directly in the constructor:

public function __constructor() {
    $this->userRepository = new UserRepository;
}

but this is not testable. Even though I don't test my apps, I just want to follow best practices.


texts: Parsing an array of comma-numbers obtained from an input dialog

texts:
I made this nice bit of code that I can insert into any of my projects requiring user input. It seems quite long for what it does and I would love some incite as to how I can do this more efficiently i.e. fewer lines of code.

I love to make my code elegant, but I don't see how to do it any better.

    String x = (JOptionPane.showInputDialog(". Each patamater should be separated with a ',' and without spaces. (eg. 1,2,3)") + ",");
    int w = 0, a = 0, y = -1;
    for(int i = 0; i < x.length(); i++)
    {
        if(x.charAt(i) == ',')
        {
            w++;
        }
    }
    Double[] z = new Double[w];
    for(int i = 0; i < x.length(); i++)
    {
        if(x.charAt(i) == ',')
        {
            z[a] = Double.parseDouble(x.substring((y + 1), i));
            y = i;
            a++;
        }
    }


texts:
Finding the nearest polygon out of a list of polygons seems to be quite a challenge on performance, due to lack of optimization.

Consider the following image:

I'll give the concept behind this. The "purple" pointer under the mouse is an entity and each blue blob is a polygon. The red ring denotes the nearest polygon, while the pink line denotes the nearest line of that polygon.

Here is the system:

Entity: performs a loop through ALL polygons.
Polygon Loop: loops through ALL vertices of the polygon in the current iteration.
Vertex Loop: if the distance between the entity and the current vertex is lower than the distance between the entity and the previous vertex, save the current vertex and the ID of the polygon the vertex belongs to.
Once all loops are finished, take the nearest polygon/vertex and get the vertex of the polygon to the left and right of the nearest vertex.
Check the left and right vertices to see which is closest to the nearest vertex. Doing so, finds the nearest line of collision to the entity.

In short, I loop through all polygons and all vertexes of each polygon to find the nearest collision line of the nearest polygon to the entity. This allows me to handle terrain, collisions, gravity, etc.

The reason for this, is that the polygons can have any shape. Since this is the case, I have to dynamically find the nearest polygon based off of the vertex of each polygon to the entity. It's costly, but gets the job done...

I know this method is inefficient, but how could I go about making this system better? Or using an entirely different and existing system that is better?

The partial code below does not include finding the nearest line. That part I am not worried about as it's very easy/fast to do.

// srce -> list(1d-array) of polygon object-IDs;
// updated -> polygon vertex array of each polygon object;
// polygon -> current iteration in the srce list(1d-array);
// with( ... ) -> current polygon of the current iteration;
// vertex -> the current vertex in the iteration of vertices of the polygon;
// srcex and srcey -> entity x,y position;
// xvertex -> x-position of the current vertex in the iteration;
// yvertex -> x-position of the current vertex in the iteration;
// nearest* vars -> store the nearest vertex/polygon data;
// size -> total vertexes in the nearest polygon;
// NOTE: Each vertex takes up 2 indexes in the list(1d-array);

// Iterate through all polygon objects;
repeat( ds_list_size( srce ) ) {
   with( ds_list_find_value( srce , polygon ) ) {
      vertex = 0;

      // Iterate through the polygon's vertices;
      repeat( ds_list_size( updated ) div 2 ) {
         xvertex = ds_list_find_value( updated , vertex );
         yvertex = ds_list_find_value( updated , vertex + 1 );
         vertex_dist = point_distance( srcex , srcey , xvertex , yvertex );

         // Here we get the current nearest point IF it's closer than the previous;
         // Here -1 means there is current NO nearest vertex;
         if ( vertex_dist < nearest_dist || nearest_dist == -1 ) {
            // If this vertex is closer than the previous, store it's data;
            nearest_dist = vertex_dist;
            nearestx = xvertex;
            nearesty = yvertex;

            // This one is confusing: nearestv stores the INDEX of the vertex in...
            // ... the array of vertices, this is a reference point for the vertex;
            nearestv = vertex;

            nearest_polygon = id;
            size = ds_list_size( id );
         }

         vertex += 2;
      }
   }

   polygon += 1;
}


texts:
As a casual Rubyist I am mainly interested, how ideomatic my solution is.

class Integer
  def divisible_by?(n)
    (self % n).zero?
  end
end

def fizzbuzz(upper_bound)
  1.upto(upper_bound).map do |number|
    next "fizzbuzz" if number.divisible_by? 3 and number.divisible_by? 5
    next "fizz" if number.divisible_by? 3
    next "buzz" if number.divisible_by? 5
    next number
  end
end

puts fizzbuzz 100

Remarks: I borrowed the idea for monkeypatching Integer from @tokland here


texts:
I currently have a very very basic js script that runs something 30 times per second. This is later to be used in a game engine.

But now I'm not quite sure how I can best do that. This little script alone cost me some time to write. What could be improved here?

function main()
{
    var framerate = 60;
    gameWindow = $('#game-window'); // Der Canvas als JQuery Objekt
    gameWindow.height( gameWindow.closest( '.gamewindow' ).height( ) );
    gameWindow.width( gameWindow.closest( '.gamewindow' ).width( ) );
    // Die Größe des Canvas dem Gamewindow anpassen
    canvasJQ = $('#game-canvas'); // Der Canvas als JQuery Objekt
    canvasJS = canvasJQ[0]; // Der Canvas als Javascript Objekt
    ctx = canvasJS.getContext("2d");
    ctx.canvas.height = canvasJQ.closest('.gamewindow').height();
    ctx.canvas.width = canvasJQ.closest('.gamewindow').width();
    // Setzten des Hintergrundes
    ctx.fillStyle = "#00FFFF";
    ctx.fillRect(0,0,canvasJQ.width(),canvasJQ.height());
    // Zeichne das canvas
    ctx.save();
    var render = function() {
        draw.render();
    }
    var update = function() {
        game.update();
    }
    var game = new Game();
    var draw = new Drawer(ctx);
    var control = new Controller();
    var engine = new Engine(framerate, render, update);
    $(document).click({param1: engine}, function(e) {
        if(e.target.id == "game-canvas")
        {
            e.data.param1.resume();
            return;
        }
        e.data.param1.stop();
    });
    engine.init();

}

class Game {
    constructor() {
    }
    update() {
        //console.log("Updating...");
    }
}

class Drawer {
    constructor(canvas) {
        this.field = canvas;
    }
    render() {
        //console.log("Rendering...");
    }
}

class Controller {
    constructor() {
    }
    startListening() {
        // Stuff to do
    }
}

class Engine {
    constructor(framerate, render, update) {
        this.framerate = framerate;
        this.render = render;
        this.update = update;
        this.isPaused = this.getPaused;

        this.frames = 0;
        this.pause = false;

        this.time_diff = 1000 / this.framerate;
    }
    init() {
        var temp = this.pause;
        this.intervalID = setInterval(this.gameloop.bind(this), this.time_diff);
        setInterval(this.framecount.bind(this), 1000);
    }
    framecount() {
        console.log(this.frames);
        this.frames = 0;
    }
    gameloop() {
        if (!this.pause) {
            this.update();
            this.render();
            this.frames ++;
        }
    }
    stop() {
        console.log("Game Paused");

        this.pause = true;
    }
    resume() {
        console.log("Game Resumed");
        this.pause = false;
    }
    getPaused() {
        return this.pause;
    }
}

main();

Currently I load this script via Angular:

export class PlayerComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    this.loadScript('../../assets/game/game.js')
  }

  public loadScript(url: string) {
    const body = document.body as HTMLDivElement;
    const script = document.createElement('script');
    script.innerHTML = '';
    script.src = url;
    script.async = false;
    script.defer = true;
    body.appendChild(script);
  }
}

Is this the right way?


texts: Reversing k-sized sequences in a linked-list

texts:
Here is my solution to this problem; please be brutally honest/strict, if I would have written this code, in a 45 minute interview, what would you think? (I am aiming for Google,Facebook).

Here is the problem I solved:

*Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.

  For example

  Given this linked list: 1->2->3->4->5

  For k = 2, you should return: 2->1->4->3->5

  For k = 3, you should return: 3->2->1->4->5

Thanks.

  public class ListNode {
     int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
  }

public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
     int count=1;
     ListNode cursor = head;
     ListNode current = null;
     ListNode remainingHalf = null;
     Queue linkQueue = new LinkedList();

     if(head==null){
         return null;
     }

     if(k<=1){
         return head;
     }
     if(k>findSize(head)){
         return head;
     }
     if(k==2){
         return reverse(head);
     }

     while(cursor!=null || cursor.next!=null){

         while(count!=k){
             if(cursor!=null){
                cursor = cursor.next;
             }
             count++;
         }
         if(cursor!=null){
             remainingHalf = cursor.next;
             cursor.next=null;

             ListNode partial = reverse(head);
             linkQueue.add(partial);

             cursor = remainingHalf;
             head = remainingHalf;
         }
         else{
             linkQueue.add(remainingHalf);
             break;
         }
         count=1;
         if(cursor==null || cursor.next==null){
             linkQueue.add(remainingHalf);
             break;
         }

     }
     boolean headFlag=false;
     ListNode toRet=null;
     while(!linkQueue.isEmpty()){
         ListNode first = (ListNode)linkQueue.poll();
         ListNode end=null;
         if(first!=null){
            end =  findEnd(first);
            if(headFlag==false){
                toRet = first;
                headFlag=true;
            }
         }
         else{
             break;
         }
         ListNode second = (ListNode)linkQueue.poll();
         if(second==null){
             ListNode temp = findEnd(toRet);
             temp.next=first;
             break;
         }
         end.next=second;

         if(linkQueue.size()==1 || linkQueue.size()==0){
             ListNode last = findEnd(toRet);
             last.next = (ListNode)linkQueue.poll();

         }
     }
     return toRet;

    }

    public int findSize(ListNode head){
        int count=0;
        while(head!=null){
            count++; head=head.next;
        }
        return count;
    }

    public ListNode findEnd(ListNode head){
        while(head.next!=null){
            head = head.next;
        }
        return head;
    }

    public ListNode reverse(ListNode head){
        if(head==null){
            return null;
        }
        if(head.next==null){
            return head;
        }
        ListNode remaining = head.next;
        head.next = null;
        ListNode temp = reverse(remaining);
        remaining.next = head;
        return temp;
    }
}


texts: A Dockerfile for Composer (a dependency manager for PHP)

texts:
I recently built a Docker image for Composer. I'd love to get a review of the image, the Bash based wrapper script, its recommended use, and the repository structure.

Here's the Dockerfile for the latest tag:

FROM alpine:edge

MAINTAINER Samuel Parkinson <sam@graze.com>

RUN echo "http://dl-4.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories && \
    apk add --no-cache \
    ca-certificates \
    git \
    mercurial \
    subversion \
    php7 \
    php7-curl \
    php7-json \
    php7-openssl \
    php7-phar \
    php7-posix

RUN /usr/bin/php7 -r "readfile('https://getcomposer.org/installer');" | \
    /usr/bin/php7 -- --install-dir=/usr/local/bin --filename=composer

COPY ./composer-wrapper /usr/local/bin/composer-wrapper

VOLUME ["/usr/src/app", "/root/.composer"]

WORKDIR /usr/src/app

ENTRYPOINT ["/usr/local/bin/composer-wrapper"]

The wrapper script, which adds the --ignore-platform-reqs flag for supported commands, so that users don't have to do it themselves as the image doesn't contain many of the common php extensions library's require:

#!/bin/sh

# Loop over each argument.
for argument in "$@"; do
    case "$argument" in
        # Append the argument if the command matches one we need to use `--ignore-platform-reqs` with.
        # Found using the following search: https://github.com/composer/composer/search?q=ignore-platform-reqs+path%3Asrc%2FComposer%2FCommand%2F
        # Uses `set` to update the arguments, see https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html.
        create-project|install|remove|require|update) set -- --ignore-platform-reqs "$@";;

        # Otherwise just pass it on.
        *) ;;
    esac
done

# Call composer with the updated arguments.
exec /usr/bin/php7 /usr/local/bin/composer "$@"

The recommended way to use the image, mounting the source and composer user folder, and read only mounting the users ssh key for use when using git based dependencies:

docker run --rm -it \
    -v $(pwd):/usr/src/app \
    -v ~/.composer:/root/.composer \
    -v ~/.ssh:/root/.ssh:ro \
    graze/composer

And finally the repository itself (which includes tests of the image!):

https://github.com/graze/docker-composer

I'm no expert at bash, and pretty new to Docker too so I'd love to know if there's anything I'm missing, or anything I'm doing that's unconventional.


texts:
I wrote this to scrape album review data from AOTY into a spreadsheet. Check it out and let me know what I could've done better.

Option Explicit

Const classAlbum As String = "listLargeTitle"
Const classScore As String = "listScoreContainer"
Const classRating As String = "listScoreValueContainer"
Const classReview As String = "listScoreText"
Const classNext As String = "pageSelect"

Sub ScrapeAOTY()

    Dim IE As MSXML2.XMLHTTP60
    Dim HTMLDoc As MSHTML.HTMLDocument
    Dim HTMLBody As MSHTML.HTMLBody
    Dim Albums As Object
    Dim Ratings As Object
    Dim Reviews As Object
    Dim MetaData As Object
    Dim InnerMeta As Object
    Dim nextPage As Object
    Dim selection As Object
    Dim sheet As Worksheet
    Dim aotyYear As String
    Dim url As String
    Dim bookmark As String
    Dim album As String
    Dim review As String
    Dim releaseDate As String
    Dim genre As String
    Dim test As String
    Dim rating As Double
    Dim index As Long
    Dim row As Long
    Dim page As Long
    Dim pageLoading As Boolean
    Dim exitFlag As Boolean

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    aotyYear = InputBox("Input the year you're scraping")
    If aotyYear < 1900 Then Exit Sub
    url = "http://www.albumoftheyear.org/ratings/6-highest-rated/" & aotyYear & "/1"
    Set sheet = ThisWorkbook.Worksheets("ScrapeSheet")
    row = 2
    exitFlag = False
    page = 1

    Do
        Set IE = New MSXML2.XMLHTTP60
        url = "http://www.albumoftheyear.org/ratings/6-highest-rated/" & aotyYear & "/" & page
        IE.Open "GET", url, False
        IE.send

        Do While IE.ReadyState <> 4
            DoEvents
        Loop

        Set HTMLDoc = New MSHTML.HTMLDocument
        Set HTMLBody = HTMLDoc.body
        HTMLBody.innerHTML = IE.responseText
        Set Albums = HTMLDoc.getElementsByClassName(classAlbum)
        Set Ratings = HTMLDoc.getElementsByClassName(classRating)
        Set Reviews = HTMLDoc.getElementsByClassName(classReview)
        Set MetaData = HTMLDoc.getElementsByClassName(classScore)

        For index = 0 To Albums.Length - 1
            Set InnerMeta = MetaData(index).parentElement.parentElement
            Set InnerMeta = InnerMeta.getElementsByTagName("div")

            album = Albums(index).innerText
            rating = CDbl(Ratings(index).getAttribute("title"))
            review = Reviews(index).innerText
            releaseDate = InnerMeta(0).innerText

            If InnerMeta.Length < 10 Then
                genre = ""
            Else
                genre = InnerMeta(1).innerText
            End If

            sheet.Cells(row, 1) = Mid(album, InStr(1, album, " ") + 1, InStr(1, album, " - ") - InStr(1, album, ".") - 2)
            sheet.Cells(row, 2) = Right(album, Len(album) - InStr(1, album, " - ") - 2)
            sheet.Cells(row, 3) = rating
            sheet.Cells(row, 4) = Left(review, Len(review) - 8)
            sheet.Cells(row, 5) = releaseDate
            sheet.Cells(row, 6) = genre

            row = row + 1
        Next index

        Set nextPage = HTMLDoc.getElementsByClassName(classNext)

        If nextPage.Length = 2 _
        Or nextPage(0).innerText = "Next >" Then
            page = page + 1
        Else
            exitFlag = True
        End If

        Set IE = Nothing
    Loop Until exitFlag = True

    MsgBox ("Done!")

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic

End Sub


texts: Threads listening on TCP and rendering in a loop

texts:
I have two threads, where one listens on TCP and the other renders in a loop:

  private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (ReceiveCheck.Checked)
                {
                    tcplisten.Start();
                    ListenThread = new Thread(new ThreadStart(Listen));
                    ListenThread.Start();
                    RenderThread = new Thread(new ThreadStart(Render));
                    RenderThread.Start();

                }
                else
                {
                    tcplisten.Stop();
                    RenderThread.Abort();
                    ListenThread.Abort();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Checkbox");
            }

        }

Is this a good way of handling the threads, to just start them and later kill them when I want to?


texts: Determining if two Strings have common subtrings of a given length in Java

texts:
Problem:

  Given 2 strings, consider all the substrings within them of length
  len. Len will be 1 or more. Returns true if there are any such
  substrings which appear in both strings. Compute this in linear time
  using a HashSet.

I know as a matter of fact that there are many areas upon which my code could be improved. However, rather than asking other people to correct my code, I would much prefer to be given hints or general principles as to how my code could be improved. I think this way, me,  and everyone that read this post could get more out of this exercise this way.

So could someone please provide me with some comments or suggestions? Critics of any level and kind are welcomed! Feel free to pick apart my code!

Class:

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

// CS108 HW1 -- String static methods
public class StringCode {

    public static boolean stringIntersect(String firstString, String secondString, int lengthOfSubstring) {

        boolean sameSubstringInBothStrings = false;

        Set<String> setOne = StringCode.getSubstringsSet(firstString, lengthOfSubstring);
        Set<String> setTwo = StringCode.getSubstringsSet(secondString, lengthOfSubstring);

        //compare setOne and setTwo to find out if there is any matching elements
        outerForLoop:
        for(String aSubstringInSetOne : setOne){
            for(String aSubstringInSetTwo : setTwo){
                if(aSubstringInSetOne.equals(aSubstringInSetTwo)){
                    sameSubstringInBothStrings = true;
                    break outerForLoop;
                }
            }
        }

        return sameSubstringInBothStrings;
    }

    static Set<String> getSubstringsSet(String aString, int lengthOfSubstring){
        Set<String> setOfSubstrings = new HashSet<>();

        if(aString.length() < lengthOfSubstring){
            return setOfSubstrings;
        }

        if(aString.length() == lengthOfSubstring){
            setOfSubstrings.add(aString);
            return setOfSubstrings;
        }

        char[] charArray = aString.toCharArray();

        //starting from the first index, going through aString
        for(int i = 0; i <= aString.length() - lengthOfSubstring; i++){

            StringBuilder sb = new StringBuilder();

            //add each substring of length (lengthOfSubstring) to the setOfSubstrings.
            for(int j = 0; j < lengthOfSubstring; j++){
                sb.append(charArray[i + j]);
            }

            setOfSubstrings.add(sb.toString());
        }

        return setOfSubstrings;
    }

}

Test:

import assign1.StringCode;
import static org.junit.Assert.*;
import org.junit.Test;

public class StringCodeTest {

    @Test
    public void testStringIntersectNormalStrings(){
        assertEquals(true, StringCode.stringIntersect("abcdickefg" , "zyxqdick", 4));
    }

    @Test
    public void testStringIntersectNormalStrings2(){
        assertEquals(false, StringCode.stringIntersect("abcdef", "zzzzzz", 1));
    }

    @Test
    public void testEmptyString(){
        assertEquals(false, StringCode.stringIntersect("abc", "", 2));
    }

    @Test
    public void testLengthOfSubstringGreaterThanTheStringItself(){
        assertEquals(false, StringCode.stringIntersect("abc", "xyz", 5));
    }

    @Test
    public void testTwoEmptyStrings(){
        assertEquals(false, StringCode.stringIntersect("", "", 2));
    }

}


texts: Prepending textbox to Wikipedia thumbnail picture

texts:
I'm working on small Javascript code that adds text from a clicked-href to the top right corner of the Wikipedia page. So for example, if I click the "Jamaican" link in Sly and Robbie, a textbox would be appended to the page on the top right.

Note: to test this code, copy it and paste it to your console, then click some links.

/**
 * My Name
 * November 24th 2015
 * Device: Mac OS X Yosemite 10.10.5
 * Editor - vim
 * Browser - Google Chrome Version 46.0.2490.86 (64-bit)
 */

'use strict';

// Detect click on href
$("a").click(function (event) {
    // Capture the href from the selected link
    var link = this.href;
    $.ajax({
        type: 'get',
        url: link
    }).done(function (data) {

        isValidWikiPage(link);

        // Find only the body text (not the titles.. or unnecessary text tips)
        var bodyText = $(data).find('#bodyContent #mw-content-text p').text();

        // Prepend the text only if there is text in the clicked link
        if (bodyText.length > 0) {
            prependText(bodyText);
        } else {
            alert("No text found!");
        }
    });

    // Prevent the link from being executed
    return false;
});

/**
 * Checks the URL to see if the link clicked
 * is a valid Wikipedia page
 * @param  {[type]}  link The clicked URL
 */
function isValidWikiPage(link) {
    // Check if link clicked is a Wikipedia page
    if (link.indexOf('wikipedia.org') <= 0) {
        // Show an alert
        alert(link + " is not a Wikipedia page!");
        // Redirect user to the new page
        window.location.href = link;
        return;
    }
}

/**
 * Prepend the thumbnail with clicked body text
 * @param  {string} text Body text
 */
function prependText(text) {
    $(".infobox .vcard .plainlist").addClass($(".infobox tbody").prepend(text));
}


texts: Find GCD of two numbers without using multiplication, division or modulus operators

texts:
If either a or b is 0 return the other number. If both even return gcd of a/2 and b/2. If either a or b is even divide it by 2 and return gcd of the pair. If a less than or equal to b, return the gcd of a, a-b else return gcd of b, a-b

private int gcd(int a, int b){
        if(a == 0) return b;
        if(b == 0) return a;
        boolean isAEven = (a & 1) == 0;
        boolean isBEven = (b & 1) == 0;
       // if a and b are divisible by 2
        if(isAEven && isBEven){
            return gcd( a >> 1,  b >> 1) << 1;
        }
        if(isAEven && !isBEven){
            return gcd( a >> 1, b);
        }
        if(!isAEven && isBEven){
            return gcd(a, b >> 1);
        }
        if(a <= b){
            return gcd(a, b-a);
        } else {
            return gcd(b, a-b);
        }
    }


texts: Inherit docstrings from specified parent

texts:
I was recently working on some python where I was working with multiple inheritance and mixins and stuff like that, and I wanted to inherit docstrings for specific functions, from specific parents (particularly in the case of the mixins).  Anyways, I came up with this recipe for inheriting docstrings and was hoping for some feedback on the strategy I used.

def get_doc(func, class_, check_self=True):
    check_self = int(not check_self)
    for parent in class_.__mro__[check_self:]:
        doc = parent.__dict__.get(func.__name__, None).__doc__
        if doc is not None:
            return doc
    return ""

def prepend(parent, child):
    return f"{parent}\n{child}"

def doc_inherit(class_, check_self=True, combine=prepend):
    def decorator(func):
        doc = get_doc(func, class_, check_self)
        func.__doc__ = combine(doc, "" if func.__doc__ is None else func.__doc__
        return func
    return decorator

Usage:

In [1]: class A:
   ...:     def instance_method(self, *args):
   ...:         "A.instance_method"
   ...:         pass
   ...:

In [2]: class B(A):
   ...:     @doc_inherit(A)
   ...:     def instance_method(self, *args):
   ...:         "B.instance_method"
   ...:         pass
   ...:

In [3]: help(B.instance_method)
Help on function instance_method in module __main__:

instance_method(self, *args)
    A.instance_method
    B.instance_method

In [4]: help(B().instance_method)
Help on method instance_method in module __main__:

instance_method(*args) method of __main__.B instance
    A.instance_method
    B.instance_method


texts: Calculate Hamming distance between DNA sequences in Ruby

texts:
I am requesting a review for my solution to this problem from exercism.io. I'm posting it here since there is not always input on solution submitted through exercism.

The problem is as stated:

  Calculate the Hamming difference between two DNA strands.

  A mutation is simply a mistake that occurs during the creation or
  copying of a nucleic acid, in particular DNA. Because nucleic acids
  are vital to cellular functions, mutations tend to cause a ripple
  effect throughout the cell. Although mutations are technically
  mistakes, a very rare mutation may equip the cell with a beneficial
  attribute. In fact, the macro effects of evolution are attributable by
  the accumulated result of beneficial microscopic mutations over many
  generations.

  The simplest and most common type of nucleic acid mutation is a point
  mutation, which replaces one base with another at a single nucleotide.

  By counting the number of differences between two homologous DNA
  strands taken from different genomes with a common ancestor, we get a
  measure of the minimum number of point mutations that could have
  occurred on the evolutionary path between the two strands.

  This is called the 'Hamming distance'.

  It is found by comparing two DNA strands and counting how many of the
  nucleotides are different from their equivalent in the other string.

GAGCCTACTAACGGGAT
CATCGTAATGACGGCCT
^ ^ ^  ^ ^    ^^

  The Hamming distance between these two DNA strands is 7.

The tests for the problem were provided:

require 'minitest/autorun'
require_relative 'hamming'

# Common test data version: 2.0.1 f79dfd7
class HammingTest < Minitest::Test
  def test_empty_strands
    # skip
    assert_equal 0, Hamming.compute('', '')
  end

  def test_identical_strands
    # skip
    assert_equal 0, Hamming.compute('A', 'A')
  end

  def test_long_identical_strands
    # skip
    assert_equal 0, Hamming.compute('GGACTGA', 'GGACTGA')
  end

  def test_complete_distance_in_single_nucleotide_strands
    # skip
    assert_equal 1, Hamming.compute('A', 'G')
  end

  def test_complete_distance_in_small_strands
    # skip
    assert_equal 2, Hamming.compute('AG', 'CT')
  end

  def test_small_distance_in_small_strands
    # skip
    assert_equal 1, Hamming.compute('AT', 'CT')
  end

  def test_small_distance
    # skip
    assert_equal 1, Hamming.compute('GGACG', 'GGTCG')
  end

  def test_small_distance_in_long_strands
    # skip
    assert_equal 2, Hamming.compute('ACCAGGG', 'ACTATGG')
  end

  def test_non_unique_character_in_first_strand
    # skip
    assert_equal 1, Hamming.compute('AAG', 'AAA')
  end

  def test_non_unique_character_in_second_strand
    # skip
    assert_equal 1, Hamming.compute('AAA', 'AAG')
  end

  def test_same_nucleotides_in_different_positions
    # skip
    assert_equal 2, Hamming.compute('TAG', 'GAT')
  end

  def test_large_distance
    # skip
    assert_equal 4, Hamming.compute('GATACA', 'GCATAA')
  end

  def test_large_distance_in_off_by_one_strand
    # skip
    assert_equal 9, Hamming.compute('GGACGGATTCTG', 'AGGACGGATTCT')

  end

  def test_disallow_first_strand_longer
    # skip
    assert_raises(ArgumentError) { Hamming.compute('AATG', 'AAA') }

  end

  def test_disallow_second_strand_longer
    # skip
    assert_raises(ArgumentError) { Hamming.compute('ATA', 'AGTG') }

  end

And here is the solution I came up with to solve this problem:

class Hamming
  def self.compute(original, copy)
    unless original.length == copy.length
      raise(ArgumentError)
    end

    hamming = 0
    copy_char = copy.split('')
    original.each_char.with_index do |character, index|
      unless copy_char[index] == character
        hamming += 1
      end
    end
      hamming
  end
end

Please critique and/or suggest how I can improve this solution using Ruby with explanations.


texts: Day finder program, inputs date, outputs day of the week

texts:
I have made this simple program that computes the day the week for the years 1700 - 2399. I am looking for suggestions/ improvement advice. I am not well versed with OOP and would like suggestions on making this program more compliant with its principles.
(I do know that this can be done after importing packages but wanted to do it manually for practice).

based on: http://blog.artofmemory.com/how-to-calculate-the-day-of-the-week-4203.html

import java.util.Scanner;

public class DayFinderLaunch {

    public static void main(String[] args) {

        DayFinderLaunch ob = new DayFinderLaunch();
        ob.accepter();

    }

    public void accepter() {

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the day, the month and year of concern in that order, all in numbers. \nNote: Year must be within 18th and 24th Century.\n");
        int d = sc.nextInt();
        int m = sc.nextInt() - 1;
        int y = sc.nextInt();

        DayFinder ob1 = new DayFinder();
        ob1.validCheck(d, m, y);
        sc.close();
    }
}

public class DayFinder {

    DayFinderLaunch ob2 = new DayFinderLaunch();

    public boolean isLeap(int y) {

        boolean leap = false;

        if (y % 4 == 0 && y % 100 != 0) {
            leap = true;
        }

        else if (y % 100 == 0 && y % 400 == 0) {
            leap = true;
        }

        return leap;
    }

    public void compute(int d, int m, int y) {

        int yc = ((y % 100) / 4 + (y % 100)) % 7;

        int[] mArr = { 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5 };

        String[] dArr = { "Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday" };

        int mc = mArr[m];

        int cc;

        int[] cArr = { 4, 2, 0, 6, 4, 2, 0 };
        cc = cArr[y / 100 - 17];

        int sum = yc + mc + cc + d;

        if (isLeap(y) && m < 2) {

            sum = sum - 1;
        }

        int fcode = sum % 7;

        System.out.printf("\nThe day of the week on %d/%d/%d : %s", d, m + 1,
                y, dArr[fcode]);
    }

    public void validCheck(int d, int m, int y) {

        int[] mDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

        if (isLeap(y)) {
            mDays[1] = 29;
        }

        if (m > 11 || m < 0 || d > mDays[m] || d < 1 || y < 1700 || y > 2399) {

            System.out.println("Invalid date, please try again.\n");
            ob2.accepter();
        }

        else {
            compute(d, m, y);
        }
    }
}


texts: A Python script to plot data and save to PDF

texts:
I have a very simple Python script. All it does is open two data files from a given directory, read the data, make a series of plots and save as PDF. It works, but it is very slow. It takes almost 20 seconds for data files that have 50-100 lines and <30 variables.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

with open('file1.out') as f:
    var1 = f.readline().split()
with open('file2.out') as f:
    var1 = f.readline().split()

df1 = np.loadtxt('file1.out', skiprows=1, unpack=True)
df2 = np.loadtxt('file2.out', skiprows=1, unpack=True)

nc1 = df1.shape[0]
nc2 = df2.shape[0]

with PdfPages('file_output.pdf') as pdf:

    ## file1.out
    fig = plt.figure(figsize=(11,7))
    j = 1
    for i in range(1,nc1):
        ax = fig.add_subplot(3,2,j)
        ax.plot(df1[0], df1[i], linestyle='-', color='black')
        ax.set(title=var1[i], xlabel='seconds', ylabel='')
        if j == 6:
            pdf.savefig(fig)
            fig = plt.figure(figsize=(11,7))
            j = 1
        else:
            j = j + 1
    pdf.savefig(fig)

    ## file2.out
    fig = plt.figure(figsize=(11,7))
    j = 1
    for i in range(1,nc2):
    ... # and it continues like the block of code above

My questions are:

Do I need all those imports and are they slowing down the execution?
Is there a better way to read the data files then opening them twice (once to get the file header and once to get data)?
Am I using the matplotlib commands correctly/efficiently (I am not very familiar with matplotlib, and this is basically my first attempt to use it)?

Please keep in mind that ideally this script should have as few dependencies as possible, because it is meant to be used on different systems by different users.

The data files have the following format:

              t             X1             X2             X3             X4             X5             X6             X7             X8            X11            X12            X13            X14            X15            X16
  6.000000E+001  4.309764E-007  2.059219E-004  9.055840E-007  2.257223E-003  1.148868E-002  7.605114E-002  4.517820E-004  3.228596E-008  2.678874E-006  7.095441E-006  1.581115E-007  1.010346E-006  1.617892E-006  9.706194E-007
  1.200000E+002  4.309764E-007  2.059219E-004  9.055840E-007  2.257223E-003  1.148868E-002  7.605114E-002  4.517820E-004  3.228596E-008  2.678874E-006  7.095441E-006  1.581115E-007  1.010346E-006  1.617892E-006  9.706194E-007
  1.800000E+002  3.936234E-007  2.027775E-004  8.644279E-007  2.180931E-003  1.131226E-002  7.476778E-002  4.353550E-004  3.037527E-008  2.534515E-006  6.778434E-006  1.470889E-007  9.488175E-007  1.531702E-006  9.189112E-007