texts: Finding array indices that add up to another number

texts:
I'm writing a method that takes (1) an array of ints and (2) an int.  The purpose of the method is to find the indices of the two numbers in the array that add up to the value passed in as the second parameter to the method (sum) and return those values in an int[].  Exactly two numbers in the passed in array will add up to "sum", so as soon as they are identified the method should finish.  I have come up with two solutions so far, but both seem ugly to me:

//this method is bad because it has multiple returns
private int[] findIndexes(int[] intAr, int sum) {
    for (int i = 0; i < intAr.length; ++i) {
        for (int k = i + 1; k < intAr.length; ++k) {
           if(intAr[i] + intAr[k] == sum) {
              return new int[] {i + 1, k + 1};
           }
        }
    }
    //should never reach here
    return null;
}
//this method is bad because it uses "break" outside of a switch statement
private int[] findIndexes(int[] intAr, int sum) {
    int[] indexAr = new int[2];
    outer:
    for (int i = 0; i < intAr.length; ++i) {
        for (int k = i + 1; k < intAr.length; ++k) {
            if(intAr[i] + intAr[k] == sum) {
                indexAr[0] = i + 1;
                indexAr[1] = k + 1;
                break outer;
            }
        }
    }
    return indexAr;
}

Is there a better way to write this method that does not violate the coding standards mentioned above?

The coding standards I was looking at are located here.


texts: Reading analog moisture signal from Arduino over USB to RPi3 and publishing via paho MQTT

texts:
This program is meant to read a moisture sensor attached to an Arduino UNO board via USB to a Raspberry Pi3 which broadcasts it over MQTT.

I am looking for any constructive criticism.

import serial
import time
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt

def main():
    try:
        while 1:
            sendMQTT(read_sensor("clean"),"Planty/moisture_readings")
            alerts()
    except KeyboardInterrupt:
        print "\n\nExiting via Keyboard Interrupt"

def debugger():
    # This is just to test each reading
    moisture_clean = read_sensor("clean")
    output = "Soil Moisture is " + str(moisture_clean) + "%"
    moisture_raw_adjusted = read_sensor("raw_adjusted")
    output += "\nRaw_adjusted is " + str(moisture_raw_adjusted)
    moisture_raw = read_sensor("raw")
    output += "\nRaw is " + str(moisture_raw)
    sendMQTT(output, "Planty/debug")

def alerts():
    # Generates alerts that are humanly readable for certain moisture thresholds
    moisture = read_sensor("clean")
    alert_low = 10
    alert_high = 90
    alert_threshold = 30
    if moisture <= alert_low:
        output = "**Moisture is below 10%**"
    if moisture <= alert_threshold and moisture > alert_low:
        output = "***Moisture is between 10%` and 30%, watering***"
        relay(14)
        time.sleep(60*1)
    if moisture >= alert_high:
        output = "***Moisture is above 90%***"
    sendMQTT(output, "Planty/alerts")

def read_sensor(choice):
    # Read analog moisture data from moisture probe via Arduino UNO plugged into
    # the RPi via USB
    min = 330
    max = 970
    ser = serial.Serial('/dev/ttyACM0', 9600)
    #Line below handles the problem of the Arduino returning more than 1 reading
    raw_data = int(str.split(ser.readline())[0])
    if choice == "raw":
        moisture = raw_data
    #Stop readings going over or under 0 or 100%
    if raw_data < min:
        raw_data = min
    if raw_data > max:
        raw_data = max
    if choice == "raw_adjusted":
        moisture = raw_data
    if choice == "clean":
        #Get moisture as  % reading
        moisture = int(round(100-(100/float(max-min))*(raw_data-min), 0))
    return moisture

def relay(pin):
    # Turn on relay via PIN.HIGH
    try:
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        GPIO.setup(pin,GPIO.OUT,initial=1)
        sendMQTT("Turning Relay1 ON", "Planty/relay")
        GPIO.output(pin,0)
        time.sleep(5)
        sendMQTT("Turning Relay1 OFF", "Planty/relay")
        GPIO.output(pin,1)
    finally:
        GPIO.cleanup()

def sendMQTT(output, topic):
    # Publish to MQTT for given topic
    host = "MQTTBroker.local"
    user = "user"
    password = "password"
    mqttc = mqtt.Client()
    mqttc.username_pw_set(user, password)
    mqttc.connect(host, 1883)
    mqttc.publish(topic, output)

if __name__ == '__main__':
    main()


texts:
Could the time complexity of this definite integral algorithm be improved?

import numpy as np

def integral(f, left, right, epsilon):
    w = int((right-left)/epsilon)
    domain = np.linspace(left, right, w)

    heights = [f(((a+b)*0.5)) for a, b in zip(domain[:-1], domain[1:])]

    return sum(heights)*epsilon

# Test an example
print('Result:', integral(lambda x: np.sin(x), 1, 10, 0.01))


texts: if-elseif chain. Is there a better pattern?

texts:
I'm working on a TCP Server using .NET and the following code is my first attempt to process the received data (from the socket) to create a packet to deliver. Basically, the packet has a header (7 bytes) where the first 3 bytes are always 0x12 0x34 0x89 and the next 7 bytes are the message length. For example:

0x12 0x34 0x89 0x00 0x00 0x00 0x02 0x20 0x20

The packet then is a 2 length packet and the sent data is 0x20 0x20.

To process this I am using an if-elseif chain, which I don't like. Is there a better pattern to take away that if-elseif chain?

    public void ProcessIncomingData(byte[] buffer, int length)
    {
        for (int i = 0; i < length; i++)
        {
            ProcessByte(buffer[i]);
        }
    }

    private void ProcessByte(byte b)
    {
        if (_status == PacketStatus.Empty && b == FirstHeaderByte)
        {
            _status = PacketStatus.FirstHeaderReceived;
        }
        else if (_status == PacketStatus.FirstHeaderReceived && b == SecondHeaderByte)
        {
            _status = PacketStatus.SecondHeaderReceived;
        }
        else if (_status == PacketStatus.SecondHeaderReceived && b == ThridHeaderByte)
        {
            _status = PacketStatus.ThirdHeaderReceived;
        }
        else if (_status == PacketStatus.ThirdHeaderReceived || _status == PacketStatus.ReceivingPacketLenght)
        {
            const int sizeOfInt32 = sizeof (int);
            const int sizeOfByte = sizeof (byte);

            _packetLength |= b << (sizeOfInt32 - ++_packetLenghtOffset) * sizeOfByte;
            _status = _packetLenghtOffset < 4 ? PacketStatus.ReceivingPacketLenght : PacketStatus.ReceivingData;
        }
        else if (_status == PacketStatus.ReceivingData)
        {
            _packet.Add(b);
            var receivedByteCount = _packet.Count;
            if (receivedByteCount == _packetLength)
            {
                var packetData = new byte[_packet.Count];
                _packet.CopyTo(packetData);

                var receivedPacketHandler = PacketReceived;
                if(receivedPacketHandler != null)
                {
                    receivedPacketHandler(this, new PacketReceivedEventArgs{ Packet = packetData });
                }
                ResetControlVariables();
            }
        }
    }


texts: How to refactor this groupby alike method but with index?

texts:
I have got such 2d jagged array (row is 1st dimension, column is 2nd dimension, bottom to up, left to right)

0   0   b   b   b   c
0   0   h   g   g   c
0   0   h   a   a   c
0   0   f   f   d   d
0   0   i   j   e   e
0   0   i   j   0   0

I would like to get a 2d jagged array summarize the positions of consecutive elements for each row, and ignore all 0 or single elements (assume that things like x x x y x x would not occur, so there won't be 2 blocks of same chars in a row)

the ideal outcome would be

{(b,3,5,2)}  // char, length, rowID, columnID
{(g,2,4,3)}
{(a,2,3,3)}
{(f,2,2,2), (d,2,2,4)}
{(e,2,1,4)}
{}

this is my code, i feel it is not that readable, so I appreciate any suggestion in C# or F# (Linq extension method is welcomed as well)

   Tuple<char, int, int, int>[][] GetHorizontalBricks()
    {
        List<Tuple<char, int, int, int>[]> ret = new List<Tuple<char, int, int, int>[]>();

        for (int rowID = 0; rowID < rowNum; rowID++)
        {
            List<Tuple<char, int, int, int>> rowBricks = new List<Tuple<char, int, int, int>>();
            var row = myBoard[rowID];

            int recentCount = 1;
            int columnID = 0;
            while (columnID < columnNum)
            {
                char recent = row[columnID];
                int next = columnID + 1;
                for (; next < columnNum; next++)
                {
                    if (row[next] == recent)
                    {
                        recentCount++;
                    }
                    else
                    {
                        break;
                    }
                }

                if (recentCount > 1 && recent != '0')
                {
                    rowBricks.Add(Tuple.Create(recent, recentCount, rowID, columnID));

                }
                columnID = next;
                recentCount = 1;
            }

            ret.Add(rowBricks.ToArray());
        }
        return ret.ToArray();
    }


texts: Parallel computation to be merged, depending on single call

texts:
Steps:

Get AMOUNT from a call to API endpoint /a, e.g. AMOUNT == 5 (in the code it is set to 2)
Use this AMOUNT to make AMOUNT calls to endpoint /b receiving JSON

Result might be: [{a: 1, b: 2}, {...}, {...}, {...}, {...}]

Use this AMOUNT to make AMOUNT calls to endpoint /c receiving JSON

Result might be: [{c: 3, d: 4}, {...}, {...}, {...}, {...}]

Merge such that there is a resulting array of JSON objects

Result might be: [{a:1, b:2, c: 3, d: 4}, {...}, {...}, {...}, {...}]

So pretty much it looks like this:

          a
         / \
        b   c
         \ /
        result

I'm really trying to understand how to write nice NodeJS code (coming from Python), so I'm specifically looking for the most elegant way to do this. I hope people can give advice on my current code below, as well as perhaps just suggesting different though clearly better methods. E.g. doing everything in async but still merging into the same result.

I'm also interested in which of the 3 styles of options (1/2/3) is best for writing NodeJS apps.

Promise = require("bluebird");
u = require("underscore")

function get_phase_count() {
    return new Promise(function(resolve, reject) {
        resolve(2); // AMOUNT == 2
    });
}

function get_phase_info(amount) {
    console.log(amount) // this would be used but now it is mocked
    return new Promise(function(resolve, reject) {
        // note that I got this AMOUNT calls solved to deliver this
        resolve([ { a: 1, b: 2 }, { a: 1, b: 2 } ]);
    });
}

function get_phase_votes(amount) {
    console.log(amount) // this would be used but now it is mocked
    return new Promise(function(resolve, reject) {
        // note that I got this AMOUNT calls solved to deliver this
        resolve([ { c: 3, d: 4 }, { c: 3, d: 4 } ]);
    });
}

function join_phase_promises(p1, p2) {
    return Promise.all([p1, p2]);
};

Using those functions I wrote 3 style options:

// Option 1
get_phase_count().then(function(amount) {
    join_phase_promises(get_phase_info(amount), get_phase_votes(amount)).then(function(args) {
        console.log(u.map(u.zip(args[0], args[1]), function(x) {return u.extend(x[0], x[1])}));
    })
});

// Option 2
get_phase_count()
.then(function(amount) {
    return join_phase_promises(get_phase_info(amount), get_phase_votes(amount));
})
.then(function(args) {
    console.log(u.map(u.zip(args[0], args[1]), function(x) {return u.extend(x[0], x[1])}));
})

// Option 3
get_phase_count().then(function(amount) {
    return join_phase_promises(get_phase_info(amount), get_phase_votes(amount));
}).then(function(args) {
    console.log(u.map(u.zip(args[0], args[1]), function(x) {return u.extend(x[0], x[1])}));
})


texts: Is this node replacement code reasonable?

texts:
JSFiddle: http://jsfiddle.net/yMSHa/ (Note: Real code uses JQuery 1.4.1)

HTML:

Do It A 1

Do It A 2

Do It A 3

Do It A 4

Do It A 5

Do It B

JS:

var RepDiv = $('#DoIt2');
var OldDiv = null;

$('div[data-name="action"]').each(function (i, f) {
    var actionid = $(f).attr('data-id');
    if (actionid) {
        $(f).css('cursor', 'pointer');
        var OnClick = function () {
            if (OldDiv) {
                RepDiv.replaceWith(OldDiv);
                OldDiv.click(OnClick);
            }
            OldDiv = $(this).replaceWith(RepDiv);
        };
        $(f).click(OnClick);
    }
});

Below is some simple JavaScript which replaces one node at a time when that node is clicked.  The idea behind this code is that a user can click on a node for that node to be expanded with more options.

I'm looking for a general review.  My main concern is whether this code is written properly in terms of good practices.


texts:
I have learned to make a carousel image slideshow script with JavaScript. I think it's better to learn it from the basic than just from the framework (instant script), but I'm a newbie. I wrote this script using my technique, but I think it's terrible.

var runCarousel, runTimer;
        firstval = 0;
        secondval = 0;

        function Carousel(){
        firstval += 10;
        document.getElementById('abc-container').style.left = "-" + firstval + "px";
        document.getElementById('asas').innerHTML = "-" + firstval;
            if(firstval == 400)
            {
                StopRun();
                StartTimer()
                return;
            }
            if(firstval == 800)
            {
                StopRun();
                StartTimer()
                return;
            }
        runCarousel = setTimeout(Carousel, 10);
        }

        function StartTimer(){
        secondval += 1;
        document.getElementById('asass').innerHTML = "-" + secondval;
        if(secondval == 10)
        {
            StopTimer();
            Carousel();
            return;
        }
        if(secondval == 20)
        {
            StopTimer();
            Carousel();
            return;
        }
        runTimer = setTimeout(StartTimer, 1000);
        }

        function StopRun(){
        window.clearTimeout(runCarousel);
        }

        function StopTimer(){
        window.clearTimeout(runTimer);
        }

        function firstStart(){
            setTimeout("Carousel()", 10000);
        }

        firstStart();
#wrapper {
width:400px;
height:140px;
position:absolute;
left:50%;
top:50%;
margin: -70px 0 0 -200px;
background: #383838;
overflow: hidden;
}

#abc-container {
position: absolute;
width:1200px;
height:140px;
}

#a {
width:400px;
height:140px;
background: #FF0000;
float: left;
}

#b {
width:400px;
height:140px;
background: #FFFF00;
float: left;
}

#c {
width:400px;
height:130px;
background: #00FFFF;
float: left;
}


texts: Entity Framework Code First Softball Stats Database Schema

texts:
I am creating a website for my buddies and I to track all of our offensive softball stats. I am getting tired of maintaining a huge excel spreadsheet and emailing it out every week, so a website is the way to go.

I've created the DB a few times but I want to make sure I am making this thing right without duplicating data. Here is what I have for models:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string NickName { get; set; }
}

public class Player : Person
{
    public int Id { get; set; }

    public virtual ICollection<Team> Teams { get; set; }
}

public class Manager : Person
{
    public int ID { get; set; }

    public ICollection<Team> Teams { get; set; }
}

public class Game
{

    public int ID { get; set; }
    public int TeamID { get; set; }
    public String Opponent { get; set }
    public DateTime? GameDate { get; set; }
    public string Score { get; set; }
    public Results Result { get; set; }

    public virtual Team Team { get; set; }
    public virtual ICollection<Stat> Stats { get; set; }
}

public class League
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Team> Teams { get; set; }
}

public enum Results
{
    W, L
}

public class Stat
{
    public int ID { get; set; }
    public int PlayerID { get; set; }
    public int GameID { get; set; }

    public virtual Player Player { get; set; }
    public virtual Game Game { get; set; }

    public int? BattingOrder { get; set; }
    public int? PA { get; set; }
    public int? Single { get; set; }
    public int? Double { get; set; }
    public int? Triple { get; set; }
    public int? HR { get; set; }
    public int? RBI { get; set; }
    public int? BB { get; set; }
    public int? SAC { get; set; }
    public int? RBoE { get; set; }
    public int? R { get; set; }

    public int? H { get { return Single + Double + Triple + HR; } }
    public int? AB { get { return PA - (BB + SAC + RBoE); } }
    public double? BA { get { return Math.Round(((double)H / (double)AB), 3); } }
    public int? TB { get { return Single + 2 * Double + 3 * Triple + 4 * HR; } }
    public double? SLG { get { return Math.Round(((double)TB / (double)AB), 3); } }
    public double? OBP { get { return Math.Round(((double)(H + BB) / (double)(AB + BB + SAC)), 3); } }
    public double? TBP { get { return Math.Round(((double)(H + BB) / (double)(AB + BB)), 3); } }
    public double? RC { get { return Math.Round(((double)OBP * (double)TB), 3); } }
}

public class Team
{
    public int ID { get; set; }
    public string Name { get; set; }
    public WeekNights WeekNight { get; set; }
    public int? Year { get; set; }

    public int ManagerID { get; set; }
    public virtual Manager Manager { get; set; }
    public virtual League League { get; set; }
    public virtual ICollection<Game> Games { get; set; }
}

public enum WeekNights
{
    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}

The 1-1 relationships aren't an issue, it's relating players to a team and a game and linking the stats that's hanging me up. If anyone has any advice or better, a schema drawing, that would be awesome.

Also, is it better to have Angular calculate the 'calculated' stats on the front end instead of trying to save them in the database? I didn't know how much that would slow down the sight calculating the stats every time you click a new player or game.


texts:
100 Doors

  100 doors is a relatively simple mathematical problem. If you have 100 doors that are initially closed, and follow this procedure:

  Walk past the doors 100 times, the first time you toggle every door (if the door is closed, you open it, and vice versa). The second time, you only visit every second door, the third time every third door. This continues until you only visit the 100th door.

  .. what doors are remaining open?

class Door {
  state {_state}
  construct new() {
    _state = false
  }
  changeState() {
    _state = !_state
  }
}

class Doors {
  get {_array}
  construct new(size) {
    _array = []
    for (i in 1..size) {
      _array.add(Door.new())
    }
  }
}

var doors = Doors.new(100)
var step = 1
var result = 1

while (step != 100) {
  var count = 1
  var stepNextPoint = step

  for (door in doors.get) {
    if (count >= stepNextPoint) {
      door.changeState()
      stepNextPoint = stepNextPoint + step
    }
    count = count + 1
  }

  step = step + 1
}

for (door in doors.get) {
  if (door.state) {
    System.print("%(result) door is open")
  }
  result = result + 1
}


texts: TweetResolver class, to be used in a graphql project

texts:
This is my module TweetResolver (tweet-resolver.js) :

import Tweet from '../../models/Tweet';
import { requireAuth } from '../../services/auth';

export default {
    getTweet: async (_, { _id }, { user }) => {
        try {
            await requireAuth(user);
            return Tweet.findById(_id);
        } catch (error) {
            throw error;
        }
    },
    getTweets: async (_, args, { user }) => {
        try {
            await requireAuth(user);
            return Tweet.find({}).sort({ createdAt: -1 });
        } catch (error) {
            throw error;
        }
    },
    createTweet: async (_, args, { user }) => {
        try {
            await requireAuth(user);
            return Tweet.create(args);
        } catch (error) {
            throw error;
        }
    },
    updateTweet: async (_, { _id, ...rest }, { user }) => {
        try {
            await requireAuth(user);
            Tweet.findByIdAndUpdate(_id, rest, { new: true });
        } catch (error) {
            throw error;
        }
    },
    deleteTweet: async (_, { _id }, { user }) => {
        try {
            await requireAuth(user);
            await Tweet.findByIdAndRemove(_id);
            return {
                message: 'Tweet has been deleted'
            }
        } catch (error) {
            throw error;
        }
    }
}

It is used in my graphql project like this:

import GraphQLDate from 'graphql-date';
import TweetResolvers from './tweet-resolvers';
import UserResolvers from './user-resolvers';

export default {
    Date: GraphQLDate,
    Query: {
        getTweet: TweetResolvers.getTweet,
        getTweets: TweetResolvers.getTweets
    },
    Mutation: {
        createTweet: TweetResolvers.createTweet,
        updateTweet: TweetResolvers.updateTweet,
        deleteTweet: TweetResolvers.deleteTweet,
        signup: UserResolvers.signup,
        login: UserResolvers.login
    }
}

Correct me if I am wrong, but I feel there is a lot of code duplication in my tweet-resolver.js module.

Almost every method signature on this module is identical (as I only want authenticated users to be able to do anything via graphql).

Every execution is inside a try/catch block.

Is there a way to remove code duplication in this. Or is this style of coding acceptable?


texts: Representing an adjacency list (graph) using a hash table of lists

texts:
While writing a C++ implementation for weighed, labeled graphs, I started to doubt the effectiveness/correctness of my chosen structure and I would like to hear some reviews.

I tried to implement the graph as follows:

template <typename T, typename K> struct graph {
    unordered_map< T, list< pair<T, K> > > adjList;
    bool directed = 1;
};

This allowed me to store a list of pairs (where first is the destination vertex, and second is the weight) for every vertex, and the adjacency list can be indexed by the vertex content.

So far, I was able to implement the basic operations successfully:

insertEdge()
removeEdge()
searchEdge()
printGraph() (prints all edges)

These operations behave correctly for both directed and undirected graphs.

template <typename T, typename K> struct graph {
    unordered_map< T, list< pair<T, K> > > adjList;
    bool directed = 1;
};

template <typename T, typename K> void reinit(graph<T, K>& g, bool directed)
{
    g.directed = directed;
    g.adjList.clear();
}

template <typename T, typename K> void insertEdge(graph<T, K>& g, T v1, T v2, K weight)
{
    g.adjList[v1].push_front(std::make_pair(v2, weight));
    if (!g.directed)
        g.adjList[v2].push_front(std::make_pair(v1, weight));
}

template <typename T, typename K> void printGraph(graph<T, K>& g)
{
    cout << "Graph is " << (g.directed ? "directed" : "undirected") << endl;
    for (const auto& v : g.adjList) //for every vertex
        for (const auto& e : v.second)
            cout << v.first << "---" << e.second << "---" << e.first << endl;
}

template <typename T, typename K> K searchEdge(graph<T, K>& g, T v1, T v2)
{   //test if edge(v1,v2) is graph
    auto l = g.adjList.find(v1);
    if (l != g.adjList.end())
        for (auto e : l->second)
            if (e.first == v2)
                return e.second;

    return numeric_limits<K>::min();
}

template <typename T, typename K> void removeEdge(graph<T, K>& g, T v1, T v2)
{
    if (GRAPH::searchEdge(g, v1, v2) != numeric_limits<K>::min())
    {
        auto l = g.adjList.find(v1);
        for (auto e = l->second.begin(); e != l->second.end(); e++)
            if (e->first == v2)
            {
                l->second.erase(e);
                return;
            }
    }
}

For the most part, I found trouble implementing breadth-first search and depth-first search algorithms. If the current structure is not that great, please suggest any changes/reformulations. If it's passable, please suggest how I can approach those mentioned algorithms.


texts: Inject settings as a dependency, and serve them using a Web API

texts:
I used an opportunity to learn about Dependency Injection and DDD, therefore, althought any feedback is welcome, I am interested in feedback about those software design principles.

I have a small project where I have to display some information queried from several similar databases (= DB that have the same purpose, but are assigned to different plants).

The back-end is coding using C#/Web API 2.

I have organized it in 3 projects (plus one test project per actual project), organized as follows (Only showing the file I believe are relevant to the review).

I am submitting for review the very first step of the program, reading the different servers that exist from configuration, and serve them to the front-end.

Backend.sln
|-> Backend.API (WebApi2 project)
 |-> Controllers/ServersController.cs
 |-> App_Start/UnityConfig.cs
 |-> Settings/Servers (a string, JSON-formatted)
|-> Backend.Domain (Class Library)
 |-> Server/AServer.cs
 |-> Server/SettingsServerRepository.cs
|-> Backend.Infra (Class Library)
 |-> Server/IServer.cs
 |-> Server/IServerRepository.cs

Backend.API

Controllers/ServersController.cs

namespace Backend.API.Controllers
{
    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*", SupportsCredentials = true)]
    public class ServersController : ApiController
    {
        Infra.Server.IServerRepository serverRepository;
        public ServersController(Infra.Server.IServerRepository serverRepo)
        {
            serverRepository = serverRepo;
        }

        public HttpResponseMessage Get()
        {
            IEnumerable<Infra.Server.IServer> servers = serverRepository.Servers;
            return Request.CreateResponse(HttpStatusCode.OK, servers);
        }
    }
}

App_Start/UnityConfig.cs

namespace Backend.API
{
    public static class UnityConfig
    {
        public static void RegisterComponents()
        {
            var servers = Properties.Settings.Default.Servers;

            var container = new UnityContainer();
            container.RegisterType<Infra.Server.IServerRepository,
                Domain.Server.SettingsServerRepository>(new InjectionConstructor(servers));

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
    }
}

Settings/Servers

[
  {
    "$type": "Backend.Domain.Server.AServer, Backend.Domain",
    "HostName": "foo",
  },
  {
    "$type": "Backend.Domain.Server.AServer, Backend.Domain",
    "HostName": "bar",
  }
]

Backend.Domain

Server/AServer.cs

namespace Backend.Domain.Server
{
    public class AServer: Infra.Server.IServer
    {
        public string HostName { get; }

        public AServer (string HostName)
        {
            this.HostName = HostName;
        }
    }
}

Server/SettingsServerRepository.cs

namespace Backend.Domain.Server
{
    public class SettingsServerRepository : Infra.Server.IServerRepository
    {
        public IEnumerable<Infra.Server.IServer> Servers {get;}

        public SettingsServerRepository(string jsonSettings)
        {
            Servers = JsonConvert.DeserializeObject<IEnumerable<Infra.Server.IServer>>(
                jsonSettings,
                new JsonSerializerSettings
                {
                    TypeNameHandling = TypeNameHandling.Auto
                });
        }
    }
}

Backend.Infra

Server/IServer.cs

namespace Backend.Infra.Server
{
    public interface IServer
    {
        string HostName { get; }
    }
}

Server/IServerRepository.cs

namespace Backend.Infra.Server
{
    public interface IServerRepository
    {
        IEnumerable<IServer> Servers { get; }
    }
}


texts: Computing sums of weird pattern in 2D array as efficiently as possible

texts:
This is a problem from Hackerrank (https://www.hackerrank.com/challenges/2d-array/problem). We're given a 6x6 (always) 2D array and asked to compute the sums of all the hourglass patterns in the array. An hourglass pattern is of the shape
1 1 1
  1
1 1 1

where the 1's form the hourglass. In this case the sum is 7, but it could be any integer from -63 to 63, the constraints being: -9 <= arr[i][j] <= 9. There are 16 hourglasses in each 6x6 2D array, and we're asked to return the greatest hourglass value.
As an example, the following 2D array has a maximum hourglass value of 28:
-9 -9 -9  1 1 1
 0 -9  0  4 3 2
-9 -9 -9  1 2 3
 0  0  8  6 6 0
 0  0  0 -2 0 0
 0  0  1  2 4 0

My code:
def hourglassSum(arr):
    max_hourglass = -63
    for column in range(len(arr)-2):
        for row in range(len(arr)-2):
            max_hourglass = max(arr[row][column] + arr[row][column+1] + arr[row][column+2] \
            + arr[row+1][column+1] + arr[row+2][column] + arr[row+2][column+1] \
                                + arr[row+2][column+2], max_hourglass)
    return max_hourglass

Is there any way to make this faster / more efficient? I'm reusing a lot of the same numbers in my calculations, which seems wasteful; is there a dynamic programming solution I'm not seeing, anything else? I appreciate any comments or optimization opportunities on my code, thank you.


texts: onResize and onLoad handlers to toggle mobile layout

texts:
I'm currently using onResize and onLoad in javascript code. Both events are coded identically so I was wondering if there is a way I could combine both into just one.

function MobileNavigation(el)
{
    this.$el = el;
}

MobileNavigation.prototype.init = function ()
{
    // Event handlers
    window.addEventListener('load', this._onLoad.bind(this));
    window.addEventListener('resize', _.debounce(this._onResize.bind(this), 150));
};

MobileNavigation.prototype._onLoad = function ()
{

    var windowHeight = $(window).outerHeight();
        headerHeight = $('header .wrapped').outerHeight();
        navigationHeight = windowHeight - headerHeight;

    // only apply to minimum width for sticky navigation to appear
    if (window.innerWidth >= MIN_WIDTH_BREAKPOINT)
    {
        $('.responsive-navigation .nav-wrap').insertAfter('header .navigation-context .mobile-menu');
        $('header .nav-wrap .region-secondary-menu').insertBefore('header .nav-wrap .region-primary-menu');
    }

    else
    {
        $('.responsive-navigation').append($('header .navigation-context .nav-wrap'));
        $('.responsive-navigation .nav-wrap .region-secondary-menu').insertAfter('.responsive-navigation .nav-wrap .region-primary-menu');
    }

    $('.responsive-navigation').css({'max-height' : navigationHeight, 'height' : navigationHeight});

    // Toogle Mobile Navigation
    $('header .mobile-menu').on('click', function() {
       $(this).toggleClass('active-menu')
       $('.responsive-navigation').toggleClass('show-navigation');
    })

    // Toggle AIM Sub Menus
    $('header .navigation > .menu > li').on('click', function() {
        console.log('expand menu');
        $(this).toggleClass('display-sub-menu');

        // $('.region-primary-menu > nav > .menu > li.display-sub-menu').removeClass('display-sub-menu');
        // $(this).addClass('display-sub-menu');
    })
};

MobileNavigation.prototype._onResize = function ()
{

    var windowHeight = $(window).outerHeight();
        headerHeight = $('header .wrapped').outerHeight();
        navigationHeight = windowHeight - headerHeight;

    // only apply to minimum width for sticky navigation to appear
    if (window.innerWidth >= MIN_WIDTH_BREAKPOINT)
    {
        console.log('normal');
        $('.responsive-navigation .nav-wrap').insertAfter('header .navigation-context .mobile-menu');
        $('header .nav-wrap .region-secondary-menu').insertBefore('header .nav-wrap .region-primary-menu');
    }

    else
    {
        console.log('mobile')
        $('.responsive-navigation').append($('header .navigation-context .nav-wrap'));
        $('.responsive-navigation .nav-wrap .region-secondary-menu').insertAfter('.responsive-navigation .nav-wrap .region-primary-menu');
    }

    $('.responsive-navigation').css({'max-height' : navigationHeight, 'height' : navigationHeight});

};


texts: Finding the largest not-necessarily contiguous alternating binary string after inverting any sub-string from a given string

texts:
I'm having problems solving this problem within the time limit.

  Alternative Thinking
   http://codeforces.com/contest/603/problem/A
  Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise.
  However, all is not lost. Kevin is a big proponent of alternative thinking and believes that his score, instead of being the sum of his points, should be the length of the longest alternating subsequence of his string. Here, we define an alternating subsequence of a string as a not-necessarily contiguous subsequence where no two consecutive elements are equal. For example, {0, 1, 0, 1}, {1, 0, 1}, and {1, 0, 1, 0} are alternating sequences, while {1, 0, 0} and {0, 1, 0, 1, 1} are not.
  Kevin, being the sneaky little puffball that he is, is willing to hack into the USAICO databases to improve his score. In order to be subtle, he decides that he will flip exactly one substring—that is, take a contiguous non-empty substring of his score and change all '0's in that substring to '1's and vice versa. After such an operation, Kevin wants to know the length of the longest possible alternating subsequence that his string could have.
  Input
  The first line contains the number of questions on the olympiad n (1 ≤ n ≤ 100 000).
  The following line contains a binary string of length n representing Kevin's results on the USAICO.
  Output
  Output a single integer, the length of the longest possible alternating subsequence that Kevin can create in his string after flipping a single substring.

My Code
A little explanation: I try every substring and invert that, then I find the longest alternating substring by taking every first occuring 0 and 1. 'f' is the value 0 or 1 which I'm finding, which alternates. I try f=0 and 1 both for index=0 for the string for which we are calculating the score. e.g. the score for 10011101001100001 will be calculated by 10011101001100001, i.e. 9.

import java.util.Scanner;

public class Problem_A {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        final int n = sc.nextInt();
        sc.nextLine();
        final String str = sc.nextLine();
        sc.close();
        int maxScore = score(str);
        for (int i = 0; i < n-1; i++) {
            for (int j = i + 1; j < n; j++) {
                String str2 = invert(str, i, j);
                int score = score(str2);
                if (score > maxScore) {
                    maxScore = score;
                }
            }
        }
        System.out.println(maxScore);
    }

    private static int score(String str) {
        char[] chArr = str.toCharArray();
        int finalScore = 0;
        for (int f = 0; f < 2; f++) {
            int fval = f;
            int score = 0;
            for (int i = 0; i < chArr.length; i++) {
                if (chArr[i] - '0' == f) {
                    score++;
                    f = 1 - f;
                }
            }
            if (score > finalScore) {
                finalScore = score;
            }
            f = fval;
        }
        return finalScore;
    }

    private static String invert(String str, int i, int j) {
        char[] chArr = str.toCharArray();
        for (int k = i; k <= j; k++) {
            chArr[k] = (char) (1 - chArr[k] + 2 * '0');
        }
        return new String(chArr);
    }
}


texts:
I have two divs as seen in this JSFiddle. To recreate the problem, keep clicking on the Gray container till both divisions touch each other.

The purpose is to execute a certain function once the green div touches the red one. The problem is that, this step callback as seen from the following code and demo, gets called multiple times. It is not something that I want to happen.

One method that would fix the problem is to keep a certain flag variable which turns True once step is executed. But I'm not sure that's enough as there needs to be a way to break out of the step callback.

I want to know:

If there is a better/efficient way to detect collision of two divs than using jQuery Collision.
How to stop the step callback after its executed once.

HTML:

JavaScript:

$(document).ready(function () {
    var hit_list;
    $(".container").click(function () {

        $(".menu").stop().animate({
            left: "+=100px"
        }, {
           duration: 300,
           complete: function () {
               $(".menu").animate({
                   left: "0"
               }, 800);
           },
           step: function(){
               //Test for collision
               hit_list = $(".menu").collision(".test");
               if (hit_list.length != 0) {
                   $(".container").append("Welcome Earthling");
               }
           }
         });
     });
 });


texts:
I'm working on a webpage with language detection and I have the following script so far (it's simple).  I still haven't done the user detection, so it's not available to find the user language (yet), but this will be easily implemented. Though I'm not asking for that, I'm asking for other ways to improve this code. So far as I've tested it, it's bug-free, but I want it to be bulletproof. How can I improve or expand it?

//LANGUAGES
//Language detection
if ( !empty($_POST['lang']) )
    {
    $Lang = $_POST['lang'];
    $_SESSION['lang']= $_POST['lang'];
    }
else
    {
    if ( !empty ($_SESSION['lang']))
        $Lang = $_SESSION['lang'];
    else
        $Lang = substr ($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
    }

//After this, $Lang will have the webpage preference


texts: C++ minimal threadsafe array based on std::deque

texts:
Here is a minimal example of a threadsafe array I want to build on for a timeseries application, with the following characteristics:

Ever-growing, and the already contained elements remain constant
(Usually) a single writer calling push_back
Multiple dependent readers

Here is the corresponding implementation, or rather an early attempt of it:

template<typename T>
struct threadsafe_array
{
    auto operator[](int i) const
    {
        return deq[i];
    }

    auto size() const
    {
        return deq_size.load(std::memory_order_acquire);
    }

    void push_back(T const& t)
    {
        std::unique_lock<std::mutex> lock(mut);
        deq.push_back(t);
        lock.unlock();
        deq_size.fetch_add(1, std::memory_order_release);
    }

private:
    std::deque<T> deq;
    std::atomic<int> deq_size{0};
    std::mutex mut;
};

My underlying ideas:

reads of the available elements through operator[](int) are carried out lock-free.
a std::deque is used as the underlying container because it does not invalidate concurrent reads when doing a push-back (--in contrast, a std::vector could as it potentially does a reallocation)
the push_back is forwarded to the underlying deque, on which it is applied in an atomic way through locking the std::mutex. Thereafter, the variable deq_size of type std::atomic<int> variable is adjusted using release semantics (so that the previous push_back is not reordered after the fetch_add).
if there are reads occurring in between adding an element to the deque and the adjustment of the size, they have have to get along with a smaller size(), i.e. as if the array had not been updated. Calling operator[size()] therefore does not need to be undefined behvaiour as it is for std::deque (but that's more an inconsistency than a feature).

Questions:

Is this thing already threadsafe and doing what I wrote, or am I missing some points?
Are the memory orders in the atomic operations ok, or are there better choices (e.g. memory_order_relaxed for the load in size())?
Is it preferable doing the update of the size in push_back() under the lock (and thus, if I see it right, limit the size difference between size() and the underlying std::deque::size() to only one)?


texts: Drawing a triangle and some concentric circles

texts:
For class, I had to use Java to draw a triangle and some concentric circles:

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

public class JComponentDemo {

    private static final JComponent triangleComponent = new JComponent() {
        private static final long serialVersionUID = 1L;

        @Override
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            g2.draw(new Line2D.Double(180, 100, 100, 0));
            g2.draw(new Line2D.Double(20, 100, 100, 0));
            g2.draw(new Line2D.Double(180, 100, 20, 100));
        }
    };

    private static final JComponent ConcentricCircleMaker = new JComponent() {
        private static final long serialVersionUID = 1L;

        @Override
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g;
            double[] circles = {40, 80, 120, 160, 200};
            Color[] colors = {Color.red, Color.green, Color.orange, Color.MAGENTA, Color.cyan};
            int count = 0;
            for (double i : circles) {
            g2.setColor(colors[count++]);
            g2.draw(Factory.get().makeCircle(200 - i / 2, 200 - i, i));
            }
        }
    };

    public static void main(String[] args) {
        JFrame frame = new JFrame("Drawing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(50, 50, 500, 500);
        frame.setVisible(true);
        frame.setContentPane(triangleComponent);
        JOptionPane.showMessageDialog(null, "Click OK to Continue");
        frame.setVisible(false);
        frame.setContentPane(ConcentricCircleMaker);
        frame.setVisible(true);
    }

    private static class Factory {

        private static final FactorySingle factory;

        static {
            factory = new FactorySingle();
        }

        static FactorySingle get() {
            return factory;
        }

        private static class FactorySingle {

            public Ellipse2D.Double makeCircle(double x, double y, double length) {
            return new Ellipse2D.Double(x, y, length, length);
            }
        }
    }
}

I admit that I am terrible at commenting. I have some questions:

Is it a good practice just to import everything so I don't have to go back and add stuff?
Is it bad just to let NetBeans do serialVersionUID for me? (I don't like yellow squiggles!)
Are those anonymous classes smart or unnecessarily confusing?
Am I instantiating more than I need to?
Is this the best way to handle graphics/Graphics?
Do all those fields have to be final?
Should I make all of the objects final that don't need to change?
I tried to implement a Circle factory singleton in order not to repeat code. Are there problems? Is this worth it?
In general, are there ways to make my code more succinct?


texts: I'm practicing turning for loops into recursive functions. what do you think?

texts:
I am trying to turn this function:

collection = ['hey', 5, 'd']
for x in collection:
    print(x)

Into this one:

def printElement(inputlist):
        newlist=inputlist
        if len(newlist)==0:
                Element=newlist[:]
                return Element
        else:
                removedElement=newlist[len(inputlist)-1]
                newlist=newlist[:len(inputlist)-1]
                Element=printElement(newlist)
                print(removedElement)

collection = ['hey', 5, 'd']

printElement(collection)

It works, but I wonder if it's okay there's no "return" line under "else:"
Is this as "clean" as I can make it?
Is it better code with or without the newlist?


texts: Initializing global object from one thread and waiting for it in other threads

texts:
Is everything OK with this code?

I need this mechanism:

I want to initialize global object of type A (named 'gA'), which may take very long time
I don't want to wait for gA to be initialized, I want to start other threads at the same time (in order for the program to be responsive)
Other threads also take some time to initialize their own stuff, and when they are ready, they want to use the gA. It can happen at any moment, before or after gA is initialized. I must assume that other threads are ready before gA is initialized and must wait therefore wait for gA.

I came up with this simple solution using shared_future. The code works and does what I want. I only wonder if there are some dangers hidden within this approach. Maybe you can spot some bug in this code?

#include <iostream>
#include <chrono>
#include <memory>
#include <future>
#include <functional>

using namespace std;
using namespace chrono_literals;

struct A
{
    A() { cout << "ctor A" << endl; }
    ~A() { cout << "dtor A" << endl; }
    void talk(string name) { cout << "[" << this_thread::get_id() << "] A is talking from thread " << name << endl; }
};

// global A object which threads of type B want to use
unique_ptr<A> gA;

bool initA()
{
    int i = 0;
    while (i++ < 7)
    {
        this_thread::sleep_for(1s);
        cout << "[" << this_thread::get_id() << "] Initializing global object gA, it takes a lot of time... (" << i << ")" << endl;
    }
    gA.reset(new A());
    cout << "[" << this_thread::get_id() << "] gA is ready to use!" << endl;
    return true;
};

void funB(string name, shared_future<bool> futA)
{
    int i = 0;
    while (i++ < 3)
    {
        this_thread::sleep_for(1s);
        cout << "[" << this_thread::get_id() << "] Initializing thread " << name << "... (" << i << ")" << endl;
    }
    cout << "[" << this_thread::get_id() << "] Now thread " << name << " waits to use global gA" << endl;
    futA.wait();

    cout << "[" << this_thread::get_id() << "] Ok, now thread " << name << " can use global gA" << endl;
    gA->talk(name);
}

int main()
{
    cout << "[" << this_thread::get_id() << "] Starting main..." << endl;

    shared_future<bool> sharedFutA(async(launch::async, initA));

    thread tB1(funB, string("B1"), sharedFutA);
    thread tB2(funB, string("B2"), sharedFutA);
    thread tB3(funB, string("B3"), sharedFutA);

    tB1.join();
    tB2.join();
    tB3.join();

    cout << "Done" << endl;
}


texts: Sort by year and day descending, yet time ascending

texts:
I recently discovered a hugely inefficient portion of code in my program, and have gone about rewriting it. I am however, not quite sure if the rewritten program actually does exactly what I want, due to its (relative) mathematical complexity. I am especially uncertain about how this new code will handle changes of the day (so 24:00 -> 00:00).

Here are the old and the new piece of code, in said order:

Collections.sort(listEntries, new Comparator<LogEntry>() {
            @Override
            public int compare(LogEntry lhs, LogEntry rhs) {
                Calendar lhsCreatedAt = Calendar.getInstance();
                Calendar rhsCreatedAt = Calendar.getInstance();
                lhsCreatedAt.setTimeInMillis(lhs.getCreatedAt());
                rhsCreatedAt.setTimeInMillis(rhs.getCreatedAt());
                if (lhsCreatedAt.get(Calendar.YEAR) != rhsCreatedAt.get(Calendar.YEAR)) {
                    return rhsCreatedAt.get(Calendar.YEAR) - lhsCreatedAt.get(Calendar.YEAR);
                }
                if (lhsCreatedAt.get(Calendar.DAY_OF_YEAR) != rhsCreatedAt.get(Calendar.DAY_OF_YEAR)) {
                    return rhsCreatedAt.get(Calendar.DAY_OF_YEAR) - lhsCreatedAt.get(Calendar.DAY_OF_YEAR);
                }
                return (int) (lhs.getCreatedAt() - rhs.getCreatedAt());
            }
        });

versus

Collections.sort(listEntries, new Comparator<LogEntry>() {
            @Override
            public int compare(LogEntry lhs, LogEntry rhs) {
                long lhsCreatedAt = lhs.getCreatedAt();
                long rhsCreatedAt = rhs.getCreatedAt();
                long millisecondsPerDay = 86400000;

                if (Math.floor(lhsCreatedAt/millisecondsPerDay) != Math.floor(rhsCreatedAt/millisecondsPerDay)){
                    return (int) (rhsCreatedAt - lhsCreatedAt);
                }
                return (int) (lhsCreatedAt - rhsCreatedAt);
            }
        });

If there are any flaws in this new code, or any other performance increases to be gained, I would love to know.


texts:
So I'm working through a beginners C++ book and they had this example demonstrating class hierarchy, which was originally in a single file. I tried recreating it with multiple files (header files + source files) to test my understanding, but I wanted to make sure that I did everything in the "optimal" way. Specifically, I had to use more #includes than I thought I would need to, so I'm wondering if I can make improvements there. Here is what the project looks like:
main.cpp
#include "FDeepDishPizza.h"
#include <iostream>
using std::cout, std::endl;

int main()
{
    cout << "Hello world!" << endl;
    FDeepDishPizza deepPizza(12, 13, 14, 15);
    deepPizza.DumpDensity();
    return 0;
}

FrozenFood.h
#ifndef FROZENFOOD_H_INCLUDED
#define FROZENFOOD_H_INCLUDED

class FrozenFood {
private:
    int Price;

protected:
    int Weight;

public:
    FrozenFood(int APrice, int AWeight);
    int GetPrice();
    int GetWeight();
};

#endif // FROZENFOOD_H_INCLUDED

FrozenFood.cpp
#include "FrozenFood.h"
#include <iostream>
using std::cout, std::endl;

FrozenFood::FrozenFood(int APrice, int AWeight) {
    Price = APrice;
    Weight = AWeight;
}

int FrozenFood::GetPrice() {
    cout << Price << endl;
}

int FrozenFood::GetWeight() {
    cout << Weight << endl;
}

FrozenPizza.h
#ifndef FROZENPIZZA_H_INCLUDED
#define FROZENPIZZA_H_INCLUDED

#include "FrozenFood.h"

class FrozenPizza : public FrozenFood {
protected:
    int Diameter;
public:
    FrozenPizza(int APrice, int AWeight, int ADiameter);
    void DumpInfo();
};

#endif // FROZENPIZZA_H_INCLUDED

FrozenPizza.cpp
#include "FrozenPizza.h"
#include <iostream>
using std::cout, std::endl;

FrozenPizza::FrozenPizza(int APrice, int AWeight, int ADiameter) :
    FrozenFood(APrice, AWeight) {
    Diameter = ADiameter;
}

void FrozenPizza::DumpInfo() {
    cout << "\tFrozen Pizza Info:" << endl;
    cout << "\t\tWeight: " << Weight << " ounces" << endl;
    cout << "\t\tDiameter: " << Diameter << " inches" << endl;
}

FDeepDishPizza.h
#ifndef FDEEPDISHPIZZA_H_INCLUDED
#define FDEEPDISHPIZZA_H_INCLUDED

#include "FrozenPizza.h"

    class FDeepDishPizza : public FrozenPizza {         //public inherit from FrozenPizza, which itself inherits FrozenFood
    private:
        int Height;
    public:
        FDeepDishPizza(int APrice, int AWeight, int ADiameter, int AHeight);
        void DumpDensity();
    };

    #endif // FDEEPDISHPIZZA_H_INCLUDED

FDeepDishPizza.cpp
#include "FDeepDishPizza.h"
#include <iostream>
using std::cout, std::endl;

FDeepDishPizza::FDeepDishPizza(int APrice, int AWeight, int ADiameter, int AHeight) :
    FrozenPizza(APrice, AWeight, ADiameter) {
        Height = AHeight;
    }

void FDeepDishPizza::DumpDensity() {
    cout << "\tDensity: ";
    cout << Weight * 2 << " pounds per cubic foot" << endl; //doesn't actually give density just a test
}


texts:
In several places I need to compute the next value, given a N:

double size = 1.0 / Math.Pow(2, N);

Since I won't be computing this value for N > 15 I have thought of the following performance optimization:

    public static readonly double[] RegionSizes =
{
    1, 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125,
    0.00390625, 0.001953125, 0.000976563, 0.000488281, 0.000244141, 0.00012207, 0.00006103515625, 0.000030517578125
};

//Usage
    double size = RegionSizes[N];

Is this a good solution? Why / why not?


texts: Is any further optimization possible? (Codeforces)

texts:
I am an average coder trying to improve my Python by doing solved problems in it.

One of the problem I did is this, here is the code I tried which
I have based on the official solution:

def area(A, B, C):
  return float((x[B] - x[A])*(y[C] - y[B]) - (y[B] - y[A])*(x[C] -x[B]))/2
x, y = {}, {}
n = int(raw_input())
for i in xrange(n):
  arr = raw_input().split()
  x[i] , y[i] = int(arr[0]), int(arr[1])

maxarea = 0
for i in xrange(n):
  for j in xrange(i+1, n):
    maxminus, maxplus = -1, -1
    for k in xrange(n):
      if k != i and k != j:
        a = area(i,j,k)
        if(a<0):
          maxminus = max(maxminus, -a)
        else:
          maxplus = max(maxplus, a)
    if maxplus >= 0 and maxminus >=0:
      maxarea = max(maxarea, (maxplus+maxminus))
print maxarea

The code is still giving me TLE on test case 7.
Can anybody suggest further optimization?


texts: Web-App for to determine gender, age, emotions of a person (shown on an image)

texts:
I have made an app using Microsoft's Face API: Face API JavaScript Quick Start

It shall analyze an image, showing a person's portrait, concerning the gender of the person, her/his age and emotions.

One pastes the URL of an image into the text-box. Then clicks the button.

The results are then listed below the image.

Caution! I'm using a free, temporary key in there. The app might stop working some time after my post.

(function(window) {
  var headersObject = new Headers();
  var photo = document.getElementById('analyzedPhoto');
  var attributesList = document.getElementById('attributes');

  headersObject.append('Ocp-Apim-Subscription-Key', '32fee7696d9545bdab41fd09ffb00034');
  headersObject.append('Content-Type', 'application/json');

  document
    .getElementById('analyse')
    .addEventListener('click', () => {
      var imgUrl = document.getElementById('imageUrl').value;

      var initObject = {
        headers: headersObject,
        method: 'post',
        body: '{"url": "' + imgUrl + '"}'
      }

      photo.src = imgUrl;

      fetch('https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceAttributes=emotion,age,gender', initObject)
        .then((response) => {
          !response.ok &&
            Promise.reject(new Error('The request of analysis data has failed.'));

          return response.json();
        })
        .then((json) => {
          let facesAttributes =
            Object.assign({},
              json[0].faceAttributes,
              json[0].faceAttributes.emotion);
          let listItems = [];
          // Otherwise emotion-properties AND emotion-object self are contained in attributes-object.
          delete facesAttributes.emotion;

          for (let key in facesAttributes) {
            listItems.push('
' +
              (key.slice(0, 1).toUpperCase()) +
              (key.slice(1)) + ': ' + facesAttributes[key] +
              '
');
          }

          attributesList.innerHTML = listItems.join('');
        })
        .catch((error) => {
          console.dir(error);
          attributesList.innerHTML = 'Have you entered a valid image URL?';
        });
    });
})(window);
html {
  overflow-y: scroll;
  background-color: rgba(245, 245, 245, 1.0);
  font-family: "Trebuchet MS", "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Tahoma, sans-serif;
}

.main-wrap {
  margin: 0 auto 30px;
  max-width: 800px;
}

#imageUrl {
  display: inline-block;
  width: 100%;
  max-width: 780px;
}

#analyzedPhoto {
  margin: 15px;
  border-radius: 3px;
  max-width: 100%;
  height: auto;
}

#attributes {
  list-style: none;
  padding-left: 0;
}

#attributes .list-item {
  margin-bottom: 10px;
}

.list-item-key {
  font-weight: 900;
  color: rgba(20, 20, 20, 1.0);
}

Enter Image URL

      <input type="text" value="https://upload.wikimedia.org/wikipedia/commons/thumb/5/56/Tesla3.jpg/220px-Tesla3.jpg" id="imageUrl" />

    <button id="analyse">Analyse</button>

Attributes

Is my usage of the fetch-API and Promises correct and done in a good way?

These concepts are fairly new to me.

Moreover: I had a bit of hassle merging the two objects into one. Please see my comment within the code.

Is there a better solution than deleting the unnecessary sub-object?


texts:
I often find myself abusing dictionary objects just for the exist method like this,

For Each x in Something
    If Not dict.Exists(x) Then dict.Add x, False
Next x

Then just exploit the .Exists(x) method.  It happens often enough that I thought it merited it's own class.

Instead of composing Scripting.Dictionary, I decided to just maintain a sorted list of unique items.  Usage is simple; unique items are inserted into the collection sorted.  Non-unique items are not added.

Attributes

Let's just get this out of the way.  Attribute VB_PredeclaredId must be set to True and NewEnum allows the class to be iterable.  I still haven't found a way to replicate this using an array instead of a collection.  With an array I could offload some of my code to my standard library, but then this wouldn't be standalone or portable.

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1
END
Attribute VB_Name = "UniqueList"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False

Option Explicit

Private list As Collection

Public Sub Class_Initialize()
    Set list = New Collection
End Sub
Public sub Class_Terminate()
    Set list = Nothing
End Sub
Public Property Get NewEnum() As IUnknown
Attribute NewEnum.VB_UserMemId = -4

    Set NewEnum = list.[_NewEnum]

End Property

Data Manipulation

Public Sub Add(ByVal element As Variant)

    If IsEmpty Then

        list.Add element
        Exit Sub

    End If

    Dim index As Long
    index = LocateIndex(element)

    If (list(index) > element) Then
        list.Add element, Before:=index
    ElseIf list(index) < element Then
        list.Add element, After:=index
    End If

End Sub
Public Sub Merge(ByVal list_ As Variant)

    Dim element As Variant
    For Each element In list_
        Add element
    Next element

End Sub
Public Sub Remove(ByVal element As Variant)

    Dim index As Long
    index = LocateIndex(element)

    If (list(index) = element) Then list.Remove index

End Sub
Public Sub Clear()

    Set list = Nothing
    Set list = New Collection

End Sub

Introspection

Note I don't implement an Item(x) method.  I don't want users to be able to scramble the data.

Public Function Exists(ByVal element As Variant) As Boolean
    Exists = (element = list(LocateIndex(element)))
End Function
Public Function Count() As Long
    Count = list.Count
End Function
Public Function IsEmpty() As Boolean
    IsEmpty = (Count = 0)
End Function

Searching

The only private method is a binary search that returns where the element is or where it should be.

Private Function LocateIndex(ByVal element As Variant) As Long

    Dim upper As Long
    upper = Count

    Dim lower As Long
    lower = 1

    While lower < upper

        Dim middle As Long
        middle = (lower + upper) \ 2

        If list(middle) >= element Then
            upper = middle
        Else
            lower = middle + 1
        End If

    Wend

    LocateIndex = upper

End Function


texts: Show/hide image in each list individually with same class

texts:
I have a list of images that are used as links and at the bottom of each image there is another image to show/hide. So far all the images show at the same time because they have the same class.

Is there any way to get around that? I don't know how to give them all the unique ID.

 Click Picture for Family page

JavaScript:

$('.name').hide();

$(".first").hover(function() {
    $(".name").stop().show();

}, function() {
    $(".name").stop().hide();
});


texts:
I am doing a small GUI program for a practice exercise and in order to save myself some typing I took it upon myself to subclass some Tkinter widgets so I can pass the grid placement in the instantiation.  One of my subclasses looks like this:

import tkinter as tk
class EntryBox(tk.Entry):
    def __init__(self, master=None, width=1, relief=None, row=None, column=None, sticky=None, padx=None, pady=None, **kwargs):
        super().__init__(master=master, width=width, relief=relief, **kwargs)
        self.grid(row=row, column=column, sticky=sticky, padx=padx, pady=pady)

And one of my instances of this widget looks like this:

window = tk.Tk()

title_entry = EntryBox(window, 10, 'sunken', 0, 1)

window.mainloop()

My initial thinking for the subclass is that if I am creating these entry widgets, they will clearly be visible on the screen (similar for some Labels, text areas, buttons, etc...).  So this would save many lines of code and typing.

Is it appropriate to subclass these widgets to save typing, or does this typically cause more confusion when another programmer reads it?  Also, will this be considered more error-prone? (Perhaps it would still be best to pass named parameter in my instantiation?)

I'd like to get some comments on when it's good practice / appropriate to subclass and when it causes more confusion.

I wanted to add that I decided to pass default values in the init subclass method so that if someone wanted to call the grid methods in the traditional way they still could in the code.


texts:
I'm currently working through Getting Started with EF5 using MVC 4 in Visual Studio 2010 (.NET 4.0) to learn about how to use ASP.NET and Entity Framework. During the beginning of the tutorial I ran into an issue with enum support when creating a database with Code First Migrations. For reasons unknown I have to work in this environment and create my own support for enums so I decided to make the property int instead then I would convert it to Enum when I want to display it like so:

using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Linq;
using System.Linq.Expressions;

namespace ContosoUniversity.Extensions
{
    public static class Extensions
    {
        public static String DisplayAsEnum<TModel, TValue>(this HtmlHelper<TModel> cHtml,
                                                           Expression<Func<TModel, TValue>> cExpression,
                                                           Type cType,
                                                           String strDisplay = "Unknown")
        {
            try
            {
                if (cType.IsEnum)
                {
                    object cResult = cExpression.Compile().DynamicInvoke(cHtml.ViewData.Model);

                    if (cResult != null)
                    {
                        strDisplay = Enum.ToObject(cType, cResult).ToString();
                    }
                }
            }
            catch (Exception cExc)
            {
                strDisplay = cExc.ToString();
            }

            return (strDisplay);
        }
    }
}

In my razor cshtml file I display it to the webpage with this call:

@Html.DisplayAsEnum(modelItem => item.Grade, typeof(Grade), "No Grade")

I have a feeling that this is not the "professional" or "right" way of handling the lack of enum support so I was wondering if there is anyway to improve this function or is there a better way of handling enumerations in EF 5 with .Net 4.0 support?

I was shown a Stack Overflow question that provides me with a better solution to handling the enum support. It is very helpful and I am using it at the moment, but since I do like the function that I made, is it possible to improve it?


texts:
Any tips to reduce lines, improve speed, or any cool thing, are welcome.

I have been using this for years and I just realized, why not improve ...?

Sub AtualizarRelatorioGeral()
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.DisplayAlerts = False
    SaveChanges = False

    Dim Arquivo(18) As String

    Arquivo(1) = "zpp03ontem"
    Arquivo(2) = "vl10a"
    Arquivo(3) = "mb51consumomensal"
    Arquivo(4) = "mb51repassegerado"
    Arquivo(5) = "mb52peixerev"
    Arquivo(6) = "mb52peixepro"
    Arquivo(7) = "mb52exp"
    Arquivo(8) = "mb52repassesaldo"
    Arquivo(9) = "zsd17"
    Arquivo(10) = "zsd25fat"
    Arquivo(11) = "zsd25dev"
    Arquivo(12) = "mc.9estoquecd"
    Arquivo(13) = "mc.9consumo"
    Arquivo(14) = "mc.9centro"
    Arquivo(15) = "mc.9cdhipet"
    Arquivo(16) = "mc.9valor"
    Arquivo(17) = "zpp25"
    Arquivo(18) = "mc.9produto"

    For i = 1 To 18
        Sheets(Arquivo(i)).Visible = True
    Next i

    Set WBgeral = ActiveWorkbook

    'IMPORTAR ARQUIVOS
    For i = 1 To 18
        WBgeral.Activate
        Sheets(Arquivo(i)).Activate
        Cells.Select
        Selection.Clear
        Workbooks.OpenXML ("C:\macrosm\prerelatoriolucimara\" & Arquivo(i) & ".xls")
        Range("A1").Select
        Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
        Selection.Copy
        WBgeral.Activate
        Sheets(Arquivo(i)).Activate
        ActiveSheet.Paste
        Workbooks(Arquivo(i)).Close SaveChanges:=False
    Next i
    'IMPORTAR ARQUIVOS

    Sheets("Principal").Activate

    For i = 1 To 18
        Sheets(Arquivo(i)).Visible = False
    Next i

    Cells(4, 16).Value = Date
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.DisplayAlerts = True
    SaveChanges = True
End Sub


texts: Java function to format seconds as minutes, hours, days

texts:
Anyone know how I write this code shorter, with modulos maybe? I also want to add weeks and years do this code, but it kind of got too long for that. Maybe there is some smart algoritm? Something in a for-loop?

public static String formatSeconds (long seconds)
{
    if (seconds < 60)
        return seconds != 1 ? seconds + " seconds" : "1 second";

    if (seconds < 3600)
    {
        seconds /= 60;
        return seconds != 1 ? seconds + " minutes" : "1 minute";
    }

    if (seconds < 86400)
    {
        seconds /= 3600;
        return seconds != 1 ? seconds + " hours" : "1 hour";
    }

    if (seconds < 2629743)  //month
    {
        seconds /= 86400;
        return seconds != 1 ? seconds + " days" : "1 day";
    }

    seconds /= 2629743;
    return seconds != 1 ? seconds + " months" : "1 month";
}


texts: Speeding up filtering function in Pandas

texts:
I have a CSV file with 400 000 rows and the following headers:

header_names = ['LEAGUE', 'YEAR', 'DATE', 'HOME', '1', 'X', '2', 'AWAY', 'SCORE', 'SCORE_1', 'SCORE_2', 'FTR', 'FAVORITE', 'UNDER-OVER']

The aim of my function is for every row to take all the previous, filter them by items in the current row and return some statistic.

This is my script so far:

import pandas as pd

filepath = 'data.csv'
header_names = ['LEAGUE', 'YEAR', 'DATE', 'HOME', '1', 'X', '2', 'AWAY', 'SCORE', 'SCORE_1', 'SCORE_2', 'FTR', 'FAVORITE', 'UNDER-OVER'] # Add appropriate headers
df = pd.read_csv(filepath, sep=',', na_values=['', '-'], parse_dates=True, header=None, names=header_names, skiprows=1, nrows=1000)

def mid_func(x):
    global mid
    mid += 1
    return mid

mid = -1
df.insert(0, 'MID', df.apply(mid_func, axis=1))

new_df = df.copy()

def home_1_simple_filter(x):
    mid_stop = x[0] - 1
    home = x[4]
    odd_1 = x[5]
    start = time.time()
    filtered = df[(df['HOME'] == home) & (df['1'] == odd_1)].ix[:mid_stop]['FTR']
    stop = time.time() - start
    print round(stop*1000.,2), 'ms', home, odd_1, mid_stop
    return filtered

start = time.time()
new_df['HOME_1'] = df.apply(home_1_simple_filter, axis=1)
stop = time.time() - start
print stop

The mid_func is to help me take the previous row. The whole process takes 3 seconds for the first 1000, and 0.002 seconds on average.


texts: Refactoring coordinates for Minecraft Pi buildings written in Python

texts:
I'm fairly new to coding and I wrote this script in Python for a house with a roof in Minecraft Pi. I've found different ways to write the coordinates to make the code base shorter, but I'm wondering if it is possible for me to refactor it any further so I don't have to list each coordinate line by line.

import mcpi.minecraft as minecraft
import mcpi.block as block
mc = minecraft.Minecraft.create()
p = mc.player.getTilePos()

mc.setBlocks(p.x+1, p.y, p.z+1, #Main structure starting coordinates (DO NOT ALTER)
             p.x+19, p.y+4, p.z+6, #Structure size/coordinates (Alters cube size)
             block.STONE_BRICK)

mc.setBlocks(p.x+2, p.y+1, p.z+2, #Hollowing out main structure interior
             p.x+18, p.y+3, p.z+5,
             block.AIR)

mc.setBlocks(p.x, p.y+4, p.z, #Main Structure Roof (Front Side, 1st Row)
             p.x+12, p.y+4, p.z,
             block.STAIRS_WOOD.id, 2)

mc.setBlocks(p.x+20, p.y+4, p.z,
             p.x+20, p.y+4, p.z,
             block.STAIRS_WOOD.id, 2)

mc.setBlocks(p.x, p.y+5, p.z+1, #Main Structure Roof (Front Side, 2nd Row)
             p.x+13, p.y+5, p.z+1,
             block.STAIRS_WOOD.id, 2)

mc.setBlocks(p.x+19, p.y+5, p.z+1,
             p.x+20, p.y+5, p.z+1,
             block.STAIRS_WOOD.id, 2)

mc.setBlocks(p.x, p.y+6, p.z+2, #Main Structure Roof (Front Side, 3rd Row)
             p.x+14, p.y+6, p.z+2,
             block.STAIRS_WOOD.id, 2)

mc.setBlocks(p.x+18, p.y+6, p.z+2,
             p.x+20, p.y+6, p.z+2,
             block.STAIRS_WOOD.id, 2)

mc.setBlocks(p.x, p.y+7, p.z+3, #Main Structure Roof (Front Side, 4th Row)
             p.x+20, p.y+7, p.z+3,
             block.STAIRS_WOOD.id, 2)

mc.setBlocks(p.x, p.y+4, p.z+7, #Main Structure Roof (Rear Side, 1st Row)
             p.x+20, p.y+4, p.z+7,
             block.STAIRS_WOOD.id, 3)

mc.setBlocks(p.x, p.y+5, p.z+6, #Main Structure Roof (Rear Side, 2nd Row)
             p.x+20, p.y+5, p.z+6,
             block.STAIRS_WOOD.id, 3)

mc.setBlocks(p.x, p.y+6, p.z+5, #Main Structure Roof (Rear Side, 3rd Row)
             p.x+20, p.y+6, p.z+5,
             block.STAIRS_WOOD.id, 3)

mc.setBlocks(p.x, p.y+7, p.z+4, #Main Structure Roof (Rear Side, 4th Row)
             p.x+20, p.y+7, p.z+4,
             block.STAIRS_WOOD.id, 3)

mc.setBlocks(p.x+1, p.y+5, p.z+2, #Main Structure Roof End (Right Side, 1st Row)
             p.x+1, p.y+5, p.z+5,
             block.STONE_BRICK)

mc.setBlocks(p.x+1, p.y+6, p.z+3, #Main Structure Roof End (Right Side, 2nd Row)
             p.x+1, p.y+6, p.z+4,
             block.STONE_BRICK)

mc.setBlocks(p.x+19, p.y+5, p.z+2, #Main Structure Roof End (Left Side, 1st Row)
             p.x+19, p.y+5, p.z+5,
             block.STONE_BRICK)

mc.setBlocks(p.x+19, p.y+6, p.z+3, #Main Structure Roof End (Left Side, 2nd Row)
             p.x+19, p.y+6, p.z+4,
             block.STONE_BRICK)


texts:
public class diceGame {
    public static void main(String[] args) {
        int dice1;
        int dice2;
        int count = 0;
        int theSum = 0;
        int lowest = Integer.MAX_VALUE;
        int finalSum = 0;
        int diceSum;
        int totalSum=0;
        while (count < Integer.parseInt(args[0])) {
            count = count + 1;
            diceSum=0;
            theSum=0;
            while (diceSum!=7) {
                diceSum = 0;
                dice1 = 1 + (int) ((Math.random() * (6 - 1)) + 1);
                dice2 = 1 + (int) ((Math.random() * (6 - 1)) + 1);
                diceSum = dice1 + dice2;
                if (diceSum != 7) {
                    theSum = theSum + diceSum;
                }
                //System.out.println("the sum is "+theSum);
            }
            if (theSum > finalSum) {
                finalSum = theSum;
            }
            if (theSum < lowest) {
                lowest = theSum;
            }
            totalSum=totalSum+theSum;
        }
        double average=(double)totalSum/(Double.parseDouble(args[0]));
        System.out.println("After " + args[0] + " simulations: ");
        System.out.println("Biggest sum: " + finalSum);
        System.out.println("Smallest sum: " + lowest);
        System.out.println("The average is: "+average);

    }
}

I would like to execute this with much less code and want to learn other/better ways to do some of things I did, such as a random ints.


texts:
Here I implement N-Ary tree in C#.

namespace ConsoleApplication1
{

    public class tree {
        public int info;
        public tree child;
        public tree siblings;

        public tree(int data)
        {
            info = data;
        }
    }

    public class NAryTree
    {
        public tree ROOT;
        public tree search(tree root, int data)
        {
            if (root == null)
                return null;

            if (data == root.info)
                return root;

            tree t = search(root.child, data);
            if (t == null)
                t = search(root.siblings, data);

            return t;
        }

        public void CreateNarray( int[] data)
        {  tree temp  = null;
            if(ROOT != null)
             temp = search(ROOT,data[0]);

            if (temp == null)
            {
                temp = new tree(data[0]);

            }
            if (this.ROOT == null)
                ROOT = temp;
            tree parent = temp;

            for (int j = 0; j < data[1]; j++)
            {
                // for first child
                if (j == 0)
                {
                    parent.child = new tree(data[j+2]);
                    parent = parent.child;
                }
                //for all other childs
                else
                {
                    parent.siblings = new tree(data[j+2]);
                    parent = parent.siblings;
                }

            }

        }

        public void Print()
        {
            preorder(ROOT);
        }
       public void preorder( tree p)
         {
        if(p==null)
        return;
         Console.WriteLine(""+p.info);
         preorder(p.child);

        preorder(p.siblings);
           }
    }

    class Program
    {
        static void Main(string[] args)
        {

            NAryTree naryTree = new NAryTree();
            //1st element in each row is node Value, 2nd - no of child, ,>=3rd....=>value of child

              int[][] data={new int[] {1,3,2,3,4}, new int[] {2,3,1,6,50},new int[]{3,3,8,9,10},new int[]{4,3,0,0,0,0}};

              for (int i = 0; i < data.GetLength(0); i++ )
              {
                 naryTree.CreateNarray(  data[i]);
              }

              naryTree.Print();
            Console.ReadLine();
        }
    }
}

Sorry for My Sub Standard English.


texts:
I am having some issue to use PHP5 password_hash() function. My server is not supporting it, so I am using a function to hash.  Is this one secure?

public function Pass_Hash ($password) {

      $blowfish_salt = bin2hex(openssl_random_pseudo_bytes(22));
      $hash = md5(crypt($password, "X1;G^COU8U`Bo*A6@9<on5yQ6P87M]".$blowfish_salt));
      return $hash;

}

I read lot of articles regarding password hashing.  Can anyone help me rewrite it more securely?


texts:
The software that I develop uses large floating-point arrays up to the maximum size that can be allocated in C#. I have a large number of algorithms such as convolutions and filters that get executed over those large arrays. I am currently updating as many algorithms as possible to fully threaded and vectorized.

By utilizing the System.Numerics.Vector<T> methods, I am seeing typically a 300%+ performance improvement in many of the algorithms on computers equipped with AVX (where Vector<float>.Count returns 4) and a 600%+ performance improvement in many of the algorithms on computers equipped with AVX2 (where Vector<float>.Count returns 8).

NET Standard 2.1 System.Numerics.Vector<T> here:

https://docs.microsoft.com/en-us/dotnet/api/system.numerics.vector-1?view=netstandard-2.1

One of the functions that I require on a number of the algorithms is to Clamp the array element value to a bounds Minimum or Maximum value after performing some mathematical operation on it. That is of course really easy to do with the single-threaded and multi-threaded algorithms that use standard arithmetic operations.

The issue that I am having is that System.Numerics.Vector<T> doesn't include any kind of Clamp method (Vector2, 3, 4 do). So, for example, if I loop over a large array, modifying the array in Vector<float>.Count chunks, I need to clamp each vector result to a min and/or max bounds prior to writing that vector-sized chunk back to the array.

I tried doing the Clamp in a loop on the array chunk data after the Vector operations, but the performance is abysmal. It is as slow or slower than simply doing the algorithm without vectorization.

Is there any way that I can conceivably improve the performance of this Clamp method?

This is some typical code of how I tried clamping. I fill the vector with a chunk of the array, perform some vector math, write the chunk back to the array, this is all nice and speedy, but then Clamping the array chunk in a loop after just kills the vectorization performance advantage.

int length = array.Length;

int floatcount = System.Numerics.Vector<float>.Count;

for (int i = 0; i < length; i += floatcount)
{
    System.Numerics.Vector<float> arrayvector = new System.Numerics.Vector<float>(array, i);

    arrayvector = System.Numerics.Vector.Multiply<float>(arrayvector, 2.0f);
    // There may be different or multiple vector operations in here.

    arrayvector.CopyTo(array, i);

    // This is how I tried clamping the array data after the vector operation:
    for (int j = 0; j < floatcount; j++)
    {
        if (array[i + j] > maximimum) { array[i + j] = maximimum; }
    }

}

I'm probably being myopic and missing something really simple. That's what months of 16-hour programming days gets you. ;) Thanks for any insight.


texts: Attempt at Abstracted YAML Configuration Loader

texts:
I've been playing around with writing a simple static blog generator in Haskell (mostly for experience, since there's probably more than a few already made choices that fit my needs). I don't have very much experience with functional programming, but I've been doing a lot of C++ lately, so using typeclasses as "interfaces" seems natural to me.

For the beginnings configuration, I've come up with this typeclass:

module BlogGenerator.Config where

class Config t where
    outputPath      :: t -> FilePath
    templatePathFor :: String -> t -> FilePath

And for a YAML implementation (using this):

module BlogGenerator.YamlConfig
    ( YamlConfig
    , toYamlValue
    , toYamlConfig
    ) where

import qualified Data.HashMap.Strict as HashMap
import Data.Maybe
import Data.ByteString
import Data.Text as Text
import BlogGenerator.Config
import qualified Data.Yaml as Yaml

newtype YamlConfig = YamlConfig
    { toYamlValue :: Yaml.Value
    }

toYamlConfig :: ByteString -> YamlConfig
toYamlConfig = YamlConfig . fromJust . decode
  where
    decode = (Yaml.decode :: ByteString -> Maybe Yaml.Value)

instance Config YamlConfig where
    templatePathFor name = stringYamlLookup ["templates", name] . toYamlValue
    outputPath = stringYamlLookup ["output", "path"] . toYamlValue

-- helpers
yamlLookup :: [String] -> Yaml.Value -> Yaml.Value
yamlLookup []         _     = Yaml.Null
yamlLookup (key:[])   value = fromJust $ look key $ toObject value
  where
    look k v = HashMap.lookup (Text.pack k) v
    toObject = fromJust . toOptionalObject
    toOptionalObject (Yaml.Object object) = Just object
    toOptionalObject _                    = Nothing
yamlLookup (key:rest) value = yamlLookup rest (yamlLookup [key] value)

stringYamlLookup :: [String] -> Yaml.Value -> String
stringYamlLookup ks v = Text.unpack (toText (yamlLookup ks v))
  where
    toText = fromJust . toOptionalText
    toOptionalText (Yaml.String text) = Just text
    toOptionalText _ = Nothing

I know the YAML package contains support for automagic binding to records, but tight coupling between the external format and the internal format is fairly unappealing to me, and before I start trusting advanced code like that I feel better about writing a "low-tech" version of my own.

Is this general approach "idiomatic" for Haskell, and am I following good practices/idioms in general?


texts:
I have written the below code for quick sort in Java:

void quicksort (int[] a, int lo, int hi)
    {
 //  lo is the lower index, hi is the upper index
 //  of the region of array a that is to be sorted
 int i=lo, j=hi, h;

 // comparison element x
 int x=a[(lo+hi)/2];

 //  partition
 do
 {
     while (a[i]<x) i++;
    while (a[j]>x) j--;
    if (i<=j)
    {
        h=a[i];
        a[i]=a[j];
        a[j]=h;
        i++;
        j--;
    }
 } while (i<=j);

 //  recursion
  if (lo<j) quicksort(a, lo, j);
 if (i<hi) quicksort(a, i, hi);
}

Please review and possibly offer a better solution.


texts: PowerShell script to automate the search of DLL files

texts:
I often write different applications in C++ using different libraries, and sometimes it takes a lot of time to find where are the *.dll files to distribute. I use Dependency Walker but it still takes a lot of time to look in the GUI. I wrote a PowerShell script that will find all used libraries and do something with them. Please review my code.

Param
(
    [Parameter(Mandatory=$true, Position=0)]
    [ValidateScript({Test-Path $_ -PathType Leaf})]
    [String]$Path,

    [Parameter()]
    [ValidateScript({Test-Path $_ -PathType Container})]
    [String[]]$Exclude
)

function likeAnyOf($obj,$array)
{
    foreach($item in $array)
    {
        if($obj -like $item)
        {
            return $item
        }
    }
    return $null
}

Set-StrictMode -Version Latest
$systemPath = [System.Environment]::SystemDirectory
$tempName = [System.IO.Path]::GetTempFileName() # generate a temporary filename

Start-Process depends.exe -ArgumentList '/c','/f:1',"/oc:$tempName",$Path -Wait -NoNewWindow # wait until it writes all the data
$modules = Import-Csv $tempName -Encoding Default | Select-Object -Property Module -Unique # read the output of depends.exe and select all unique DLL paths
Remove-Item -Path $tempName -Force # delete the temporary file

$dllsToCopy = @{}

foreach($module in $modules)
{
    $modulePath = $module.Module
    $moduleParent = Split-Path $modulePath -Parent
    $moduleName = Split-Path $modulePath -Leaf

    if( $moduleParent -like $systemPath )
    {
        Write-Verbose "Skipped $moduleName as a system module ($moduleParent)"
        continue
    }
    $excluded = likeAnyOf $moduleParent (Resolve-Path $Exclude)
    if($excluded -ne $null)
    {
        Write-Host "Skipped $moduleName as explicitly excluded ($excluded)"
        continue
    }

    $exists = Test-Path $modulePath -PathType Leaf
    if($exists)
    {
        $dllsToCopy.Add($moduleName, $modulePath)
        Write-Host "Added $moduleName found at $moduleParent"
    }
    else
    {
        Write-Error "Couldn't find $moduleName"
    }
}


texts:
Still pretty new to coding. I posted that Twin Primes Finder the other day and you guys were a great help so thanks. Here's my quadratic equation solver:

import math

#variables for initial equation
a = int(raw_input("Enter a:"))
b = int(raw_input("Enter b:"))
c = int(raw_input("Enter c:"))

#variables for quad. equation
negative_b = -b
b_squared = b**2
four_a_c = 4*a*c
determinant = b_squared - four_a_c

#prints initial equation
equation = [str(a)+"x^2", str(b)+"x", str(c)]

print "Solve: " + " + ".join(equation)

if determinant < 0:
    print "No real solutions."
elif a == 0:
    y_int = float(-c)/b
    print "x =", y_int
    print "But this is a straight line."
else:
    root_determinant = math.sqrt(determinant)
    two_a = 2*a
    numerator_one = negative_b - root_determinant
    answer_one = numerator_one/two_a
    if determinant == 0:
      print "x =", answer_one
    else:
      numerator_two = negative_b + root_determinant
      answer_two = numerator_two/two_a
      print "x =", answer_one, "or", answer_two


texts: Implement total savings function on a record type

texts:
the TotalSavings() function on the record below has a code smell that I can't exactly detail. Is there a more readable alternative for implementing this function on a record type?

type ProvidersCharged = ProvidersCharged of decimal
type InsuranceSavings = InsuranceSavings of decimal

type ClaimsSummary =
    { Claims:Claim seq
      ProvidersCharged:ProvidersCharged
      InsuranceSavings:InsuranceSavings
    } member this.TotalSavings() = match this.ProvidersCharged with
                                   | ProvidersCharged charged ->
                                        match this.InsuranceSavings with
                                        | InsuranceSavings savings -> charged - savings


texts:
In my quest for learning Objective-C, I have created the common FizzBuzz code in it.  This is due to a suggestion/challenge from @nhgrif to re-implement anything he does in Swift in Objective-C.

#import <Foundation/Foundation.h>

int main(int argc, const char* argv[])
{
    @autoreleasepool
    {
        for (int i = 1; i <= 100; ++i)
        {
            if (i % 15 == 0) NSLog(@"FizzBuzz");
            else if (i % 3 == 0) NSLog(@"Fizz");
            else if (i % 5 == 0) NSLog(@"Buzz");
            else NSLog(@"%d", i);
        }
    }
}


texts: Polling implemented using reactive framework (project reactor)

texts:
I have a use case where I need to poll a certain service till all data has arrived. The service accepts a list of ids and responds with data corresponding to these ids. Data is asynchronously made available by an external service and currently polling is the only option. There is an overall time out of 1min.

return Mono.fromSupplier(() -> poll(ids))
                   //poll every 2 seconds, poll 25 times (total 50 secs)
                   .repeatWhen(completed -> completed.zipWith(Flux.range(1, 25)).delayElements(Duration.ofSeconds(2)))
                   //stop polling if all responses have arrived
                   .takeUntil(PollingService::isCompleted)
                   //slow producer fast consumer scenario
                   .subscribeOn(Schedulers.elastic())

I have tried to delegate the polling to reactor as much as possible and my understanding is that this will be more efficient than doing it on a single thread and blocking it for the whole duration.


texts: Generating Pythagorean triples below an upper bound

texts:
I've got an assigment where I have to print all the Pythagorean triples smaller than a given n. Even though I could print them directly in pythagoreanTriple function, I decided to structure everything, as I want to go deply into programming structure.(my teacher does not teach us a lot, so I'll have to study on my own).

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        System.out.println("Starting program...");
        int n = readFromKeyboard();
        printResult(pythagoreanTriple(n));
    }

    private static int  readFromKeyboard(){
        Scanner keybInput = new Scanner(System.in);
        return keybInput.nextInt();
    }

    private static List<List<Integer>> pythagoreanTriple(int n){
        List<List<Integer>> pytTri = new ArrayList<List<Integer>>();
        int i,j,k;
        for (i = 3; i < n; i++)
            for (j = n; j > i; j--)
                for (k = n; k > j; k--)
                    if (i * i + j * j == k * k){
                        ArrayList<Integer> tempArray = new ArrayList<Integer>(); //we create a list of integers
                        tempArray.add(i);
                        tempArray.add(j);
                        tempArray.add(k);
                        pytTri.add(tempArray);
                    }
        return pytTri;
    }

    private static void printResult(List<List<Integer>> resultList){
        for (List<Integer> ls: resultList){
            for (Integer i: ls){
                System.out.print(i);
                System.out.print(" ");
            }
            System.out.println(";");
        }
    }

}

Knowing these:

I am curious about the following: How are the variable/function's name, should I use underscore _ for private variables etc...
I am not new to programming

(I know both C++ and Python so far), but I'm more interested in learning Java next.)


texts: Splitting a string into groups of up to 3 numbers, or one letter and up to 3 numbers

texts:
There was an interesting idea brought up in The 2nd Monitor where one of our regulars was trying to split a bunch of strings into a specific format.

The format should be similar to the following:

A000
A00
900
90

Where A is any alphabetical letter, 0 is any number, and 9 is any number 1-9. No result string should begin with 0, it should always begin with A-Z or 1-9, and all alphabet characters will always be capitalized.

The input comes in a format similar to any of the following:

Input         | Result
900A000       | 900, A000
900900        | 900, 900
90            | 90
99099         | 990, 99
A009A09       | A009, A09
A009A09900    | A009, A09, 900
A0990A09900   | A09, 90, A09, 900
A099090A09900 | A09, 90, 90, A09, 900
A09A990       | A09, A990
A990          | A990

The input will always parse to a valid group of strings.

The method:

public List<string> SpecialSplit(string input)
{
    var result = new List<string>();

    var currentString = new StringBuilder(4);
    for (var i = 0; i < input.Length; i++)
    {
        var c = input[i];

        if (currentString.Length > 0)
        {
            // Determine whether we're at constraints or not.
            var firstCharLetter = currentString[0] >= 'A' && currentString[0] <= 'Z';
            var atMaxLetterLength = firstCharLetter && currentString.Length == 4;
            var atMaxNumberLength = !firstCharLetter && currentString.Length == 3;

            // Split if at max letter/number length, or if we're on a letter.
            var mustSplit = atMaxLetterLength || atMaxNumberLength || c >= 'A' && c <= 'Z';

            if (mustSplit)
            {
                // If we must split our string, then verify we're not leaving an orphaned '0'.
                if (c == '0')
                {
                    // Go back a letter, take it out of the new string, and set our `c` to it.
                    i--;
                    currentString.Length--;
                    c = input[i];
                }

                // Add and clear the string to our result.
                result.Add(currentString.ToString());
                currentString.Clear();
            }
        }

        // Add our `c` to the string.
        currentString.Append(c);
    }

    // Add our string to the result.
    result.Add(currentString.ToString());

    return result;
}

And the test code:

var tests = new string[] {
    "909A999",
    "909999",
    "90",
    "99099",
    "A009A09",
    "A009A09900",
    "A0990A09900",
    "A099090A09900",
    "A09A990",
    "A990"
};

var resultStrings = new List<string>();

foreach (var test in tests)
{
    var split = SpecialSplit(test);
    Console.WriteLine(test + ": {" + string.Join(", ", split) + "}");
    resultStrings.AddRange(split);
}

if (resultStrings.Any(x => x[0] == '0'))
    Console.WriteLine("Test failed");
else
    Console.WriteLine("Test passed");


texts:
I have a list of contacts, classified into categories. Each category is represented with a different class.

Base class:

class Contact
{
    public ushort Id { get; private set; }
    public Phone Phone { get; private set; }

    public Contact(ushort id, Phone phone)
    {
        Id = id;
        Phone = phone;
    }
}

And here are the categories:

PrivateServiceProvider (meaning - private person):

class PrivateServiceProvider : Contact
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }
    public ServiceField ServiceField { get; private set; }

    public PrivateServiceProvider(ushort id, string firstName, string lastName,
                                  ServiceField serviceField, Phone phone)
        : base(id, phone)
    {
        FirstName = firstName;
        LastName = lastName;
        ServiceField = serviceField;
    }
}

BusinessServiceProvider:

class BusinessServiceProvider : Contact
{
    public string Name { get; private set; }
    public ServiceField ServiceField { get; private set; }
    public Email Email { get; private set; }

    public BusinessServiceProvider(ushort id, string name,
                                   ServiceField serviceField, Phone phone, Email email)
        : base(id, phone)
    {
        Name = name;
        ServiceField = serviceField;
        Email = email;
    }
}

PrivateGenericContact:

class PrivateGenericContact : Contact
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }

    public PrivateGenericContact(ushort id, string firstName, string lastName, Phone phone)
        : base(id, phone)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

BusinessGenericContact:

class BusinessGenericContact : Contact
{
    public string Name { get; private set; }
    public Email Email { get; private set; }

    public BusinessServiceProvider(ushort id, string name, Phone phone, Email email)
        : base(id, phone)
    {
        Name = name;
        Email = email;
    }
}

It works, but how could I improve it1?

Also, it drives me CRAZY that the names of the classes are so lengthy. I think it's a smell but I am not sure what to do about it. If some day I decide to create another specification of Contact, let's say - for people who lives in the city versus in the country2, will I call the class CountryPrivateServiceProvider? It's NUTS.

An example of use is when the user creates a contact. So he chooses the type of contact and inserts all of the information into a form (a View - I am using MVP). Then the View notify the Presenter that the user pressed the "Save" and creates an object of the selected type. Then the Presenter ask the Model to insert the information into the database.

How can I improve my code, both generally and specifically to this naming problem?

1. They are deliberately immutable.

2. Apparently, I am not good with examples.


texts:
Today I created a script in Excel that migrates data from a specific Word document and copies a portion of it to a cell in Excel (the date to be specific).

The file input is

  Last name, First Name, Grade - (Rank) (Completed On YYYY-MM-DD HH:mm:ss)

and each person is on a new "paragraph" (aka line) in Word.

Sub SearchTextFile()
Dim i As Integer
Dim currentCellNumberLname As String
Dim currentCellNumberFname As String
Dim currentCellData As String
Dim firstPlusLastName As String
Dim filePath As String
filePath = "C:\Users\<user>\Desktop\CyberAwareness.docx"

For i = 2 To 4
    currentCellNumberLname = "C" & i
    currentCellNumberFname = "D" & i
    currentCellToAdd = "L" & i
    ActiveSheet.Range(currentCellToAdd).Activate
    ActiveWindow.ScrollRow = ActiveCell.Row
    firstPlusLastName = Range(currentCellNumberLname).Value & ", " & Range(currentCellNumberFname).Value
    Range(currentCellToAdd) = SearchWordDoc(filePath, firstPlusLastName)
Next
End Sub

'Searches word file for name, finds the associated paragraph, and returns the date'
Function SearchWordDoc(strPath, strName)
Set objword = CreateObject("word.application")
Set a = objword.documents.Open(strPath)

For i = 1 To a.Paragraphs.Count
    If InStr(a.Paragraphs(i).Range.Text, strName) <> 0 Then
        SearchWordDoc = Left(Right(a.Paragraphs(i).Range.Text, 22), 11)
    End If
Next i
a.Close
objword.Quit
'    objword.Visible = False'
Set objword = Nothing
End Function

I have about 300 personnel that need information entered into this document and about 8 different columns I need to populate. The script works surprisingly well, however, it is pretty slow and takes ~10 minutes for one column. I'm fine with it since it gets the job done, but I'm curious if there is any way to streamline it further and possibly add error checking (for name mismatches).


texts:
I have a web scraper that I use in a part of a larger program. However, I feel like I semi-repeat my code a lot and take up a lot of room. Is there any way I can condense this code?

def read_mail(mail):
        url = [mail] # Ignore this line, please.
        i = 0 # Ignore this line, please.
        droppedSource = '(.+?)	' # Gets whatever is inbetween the tags
        destroyedSource = '(.+?)	'
        totalSource = '(.+?)'

        droppedText = re.compile(droppedSource) # Converts regex string into something that can be interpreted by regular library
        destroyedText = re.compile(destroyedSource)
        totalText = re.compile(totalSource)

        html = urllib.urlopen(url[i]).read() # ignore the url[i] part of this line, please.

        dropped = re.findall(droppedText,html)
        destroyed = re.findall(destroyedText,html)
        total = re.findall(totalText,html)

        return("Info: " + str(dropped[0])+str(destroyed[0])+str(total[0]))


texts:
I am wondering which method code is more "Pythonic":

def load_job(self, identifier, job_name):
    i = 5
    ex = None
    while i:
        try:
            for ep in iter_entry_points(group='core.account', name=identifier):
                self.modules[identifier] = ep
            # load_entry_point(ep.dist, 'core.account', ep.name)
            # The following is the same
            loaded = ep.load()
            job = getattr(loaded, job_name)
            return job
        except ImportError as e:
            ex = e
            i -= 1
            time.sleep(2)
            continue

    raise ex

Or

def load_job(self, identifier, job_name):

    i = 5
    job = None
    ex = None
    while i:
        try:
            for ep in iter_entry_points(group='core.account', name=identifier):
                self.modules[identifier] = ep
                # load_entry_point(ep.dist, 'core.account', ep.name)
                # The following is the same
                loaded = ep.load()
                self.info("Loaded %s", ep.module_name)
                job = getattr(loaded, job_name)

            break
        except ImportError as er:
            ex = er
            i -= 1
            time.sleep(2)

    if job:
        return job
    else:
        raise ex

While the later is a bit longer, I feel it's easier to read. My main concern is whether I should return or break from within the while loop.