texts:
I've written a very light wrapper around Dapper to help with unit testing and streamlining the Dapper commands I need.

Execute() is a method created to remove the code duplication of opening and closing the database connection and enlisting it in a transaction. The code is very quick at inserts with this method (200,000 inserts in less than 30 secs).

I'm wondering if I've made any obvious mistakes with regards to Dapper and performance.

For instance, should a single insert or read explicitly enlist a transaction, or would they be faster with an ambient transaction?

public class DappperService
{
    private readonly string sqlConnection;

    public DappperService(string sqlConnection)
    {
        this.sqlConnection = sqlConnection;
        DapperExtensions.DapperExtensions.DefaultMapper = typeof(PluralizedAutoClassMapper<>);
    }

    public T Get<T>(int id) where T : class
    {
        return Execute((x, t) => x.Get<T>(id, t));
    }

    public bool Delete<T>(T dto) where T : class
    {
        return Execute((x, t) => x.Delete(dto,t));
    }

    public dynamic Insert<T>(T dto) where T : class
    {
        return Execute((x, t) => x.Insert(dto,t));
    }

    public void Insert<T>(List<T> dtoList) where T : class
    {
        IEnumerable<T> enu = dtoList;

        using (var con = new SqlConnection(sqlConnection))
        {
            con.Open();
            var trans = con.BeginTransaction();
            con.Insert(enu, trans);
            trans.Commit();
            con.Close();
        }
    }

    public IEnumerable<T> GetList<T>() where T : class
    {
        return Execute((x, t) => x.GetList<T>(transaction:t));
    }

    public dynamic Execute(Func<SqlConnection, SqlTransaction, dynamic> action)
    {
        using (var con = new SqlConnection(sqlConnection))
        {
            con.Open();
            var trans = con.BeginTransaction();
            var result = action(con, trans);
            trans.Commit();
            con.Close();
            return result;
        }
    }
}


texts:
I'm writing a program for magic square and I'm a relative beginner to C++ and programming. I was hoping someone could help me find alternate or better ways to implement my code. This is the main function. I also entered a function to check if the input is odd, max 19, and to quit.

Is there a way to not have back-to-back for  and if statements?

#include <iostream>
#include <limits>
#include <iomanip>

using namespace std;
int oddfunction(int &a);
int endfunction(int &exit);
int maxfunction();
int main()
{
    int r, c, d, e, z=0;
    int *f = new(nothrow) int;
    int *g= new(nothrow) int;
    int magic[120][120];
    cout << "EML 2032 Final Project: Magic Square (odd numbers) " << endl;

    while(*g != 0)
    {
        cout << "\n\nMagic Squares for integers less than 20. ";
        for ( r=0 ; r<120 ; r++ )
        for ( c=0 ; c<120 ; c++ )
        magic[r][c] = 0;
        *f = oddfunction(*f);
        z = *f;
        cout <<"\n\n";
        d = 0 ;
        e = (z-1) / 2;
        magic[d][e] = 1;
        for ( r=2 ; r <= z * z ; r++ )
        {
            d--;
            e++;
            if ( d < 0 && e == z )
            {
                d  = d + 2;
                e--;
            }
            if ( d < 0 ) { d = z - 1; } if ( e >= z ) { e = 0; } if ( magic[d][e] != 0 )
            {
                d = d + 2;
                e = e - 1;
            }
            magic[d][e] = r;
        }
        for(r=0;r < z;r++)
        {
            for(c = 0; c < z; c++)
            {
                cout << setw(4) << magic[r][c];
            }
            cout << endl;
        }
        endfunction(*g);
   }
   cout << endl;
   cout << "Have a nice day!        THE END \n";
   system("pause");
   return 0;
}

int maxfunction()
{
    int c=0;
    cin >> c;
    while(c >= 20)
    {
        cin.clear();
        cin.ignore(numeric_limits<int>::max(),'\n');
        cout << "Input an odd integer up to 19.\n";
        cin >> c;
    }
    return c;
}
int oddfunction(int &a)
{
    int cont=0;
    while(cont == 0)
    {
        cout << "Input an odd number: " << endl;
        a = maxfunction();
        if(a % 2 == 0 )
        {
            if(a % 2 == 0 )
            {
                cout << "That wasn't odd! (odd numbers aren't divisible by 2)\nEnter any number to continue:" << endl;
                a = maxfunction();
            }
            else
            {
                a = maxfunction();
                cont++;
            }
        }
        else
        {
            cont++;
        }
    }
    return a;
}
int endfunction(int &exit)
{
    int h=0;
    int i=2032;
    h = exit;
    cout << "\n-Input 2032 to quit... \n-Input any other number to continue..." << endl;
    cin >> h;
    if(h == i)
    {
        exit = 0;
        return exit;
    }
    else
    {
        exit = 1;
        return exit;
    }
}


texts:
I just created a simple gallery with scroll. Everything works fine but I'm not sure how should I optimize this code:

document.addEventListener("DOMContentLoaded", function() {

    var smallImages = document.querySelectorAll('li img');
    var bigPhotoDiv = document.querySelector('.bigPhoto img');
    var scroller = document.querySelector('#scroller');
    var list = document.querySelector('ul');

    scroller.max = smallImages.length - 1;
    scroller.defaultValue = 0;
    smallImages[scroller.defaultValue].classList.add('centralTheBiggest');

    bigPhotoDiv.src = smallImages[0].src;
    bigPhotoDiv.classList.add('fullSize')

    scroller.addEventListener('input', function(event) {
        //changing the big photo in div
        var currentLink = smallImages[scroller.value].src;
        bigPhotoDiv.src = currentLink;

        //move the list with photos
        list.scrollLeft = scroller.value * 70; //poprawka

        //emphesasise choosen photo

        for (var i = 0; i < smallImages.length; i++) {
            smallImages[i].classList.remove('centralTheBiggest')
        }
        if (smallImages.index = scroller.value) {
            smallImages[scroller.value].classList.add('centralTheBiggest');
        }
    });
    var body = document.querySelector('body');

    //clicking on big photo display it on fullscreen
    bigPhotoDiv.addEventListener('click', function(event) {
        var fullScreen = document.createElement('div');
        fullScreen.classList.add('fullScreenDiv');

        var fullScreenImgContainer = document.createElement('div');
        fullScreenImgContainer.classList.add('fullScreenImgContainer');

        var fullScreenImg = document.createElement('img');
        fullScreenImg.src = smallImages[scroller.value].src;
        fullScreenImg.classList.add('fullScreenImg')

        fullScreenImgContainer.appendChild(fullScreenImg)
        fullScreen.appendChild(fullScreenImgContainer);
        body.appendChild(fullScreen);
        //adding buttons:
        var nextButton = document.createElement('button');
        nextButton.classList.add('nextButton');
        fullScreenImgContainer.appendChild(nextButton);

        var prevButton = document.createElement('button');
        prevButton.classList.add('prevButton');
        fullScreenImgContainer.appendChild(prevButton);

        var closeButton = document.createElement('button');
        closeButton.classList.add('closeButton');
        fullScreenImgContainer.appendChild(closeButton);

        closeButton.addEventListener('click', function(event) {
            fullScreen.parentNode.removeChild(fullScreen);
        });
        //adding events to new buttons
        nextButton.addEventListener('click', function(event) {
            scroller.value++
                fullScreenImg.src = smallImages[scroller.value].src;
            bigPhotoDiv.src = smallImages[scroller.value].src;
        });

        prevButton.addEventListener('click', function(event) {
            scroller.value--
                fullScreenImg.src = smallImages[scroller.value].src;
            bigPhotoDiv.src = smallImages[scroller.value].src;
        });
        //hiding and showing prev and next button
        fullScreenImgContainer.addEventListener('mouseover', function() {
            nextButton.style.display = "block";
            prevButton.style.display = "block";
        });
        fullScreenImgContainer.addEventListener('mouseout', function() {
            nextButton.style.display = "none";
            prevButton.style.display = "none";
        });
    });
});

Is it a good way to put so many Events inside another event? or should I create all possible elements (like nextButton, prevButton for example) outside the 'click' event? And what about hiding and showing those buttons? Is it a good idea to put it inside 'mouseover' event?


texts: Utility method to create custom popup in jquery-mobile

texts:
Is there a better way to write this?

function(content,redirectUrl,customButtons, headerMsg){
    var $popUp = $("
").popup({
        theme:"a",
        dismissible: false,
        overlayTheme: "b",
        transition: "pop"
    }).on("popupafterclose", function (){
        //remove the popup when closing
        $(this).remove();
    }).css({
        'width':  $(window).width()*80/100,
        'font-size':'0px'
    });
    if(headerMsg)
        header = $('
'+headerMsg+'
').appendTo($popUp)
    if(!content)
        content = $("#generalErr").val() || 'An error occurred during processing, please try again after some time';

    //create a message for the popup
    $("
", {
        html: content
    }).addClass("mid-font").appendTo($popUp);

    if(customButtons){
        var popUpWidth = $(window).width()*80/100,
        buttonWidth = popUpWidth/customButtons.length;
        $.each(customButtons, function(i,button){
            addButtons($popUp,button.text,'',button.action, buttonWidth);
        });
        $popUp.find("a:last-child").css({
            'border-right': '0px'
        });
    } else {
        addButtons($popUp,$("#ok").val() || 'Ok',redirectUrl);
    }
    $popUp.popup('open').trigger("create");
}

function addButtons(popUpObj,text,redirectUrl,buttonAction,buttonWidth){
    var button = $("", {
        text: text
    }).on('click',function(){
        if(buttonAction){
            buttonAction(popUpObj);
        } else {
            if(redirectUrl){
               window.location.href = redirectUrl;
            }
            popUpObj.popup("close");
        }
    }).buttonMarkup({
        inline: false,
        mini: false,
        theme: "a"
    });
    if(buttonAction){
        button.css({
           'width':buttonWidth-1,
           'display':'inline-block',
           'margin-bottom':'0px',
           'padding-left': '0px',
           'padding-right':'0px'
        }).addClass("popup_button_border");
    }
    button.appendTo(popUpObj);
}


texts: Parsing argument list specifying a player to be added

texts:
I want to start off by saying sorry, I wasn't able to search for this problem as I couldn't exactly describe it myself.

I have a series of if-statements to account for each scenario. As you can see in the mammoth block of code below, I want arguments to come in any order. How, if possible, can I shorten this?

if(args[1].startsWith("u:") && args[2].startsWith("r:") && args[3].startsWith("l:")){ // u / r / l
    Player p = player.getServer().getPlayer(args[1].split(":")[1]);
    String r = args[2].split(":")[1];
    String l = args[3].split(":")[1];
    Config.addPlayer(p, r, l, player);
    return true;
}else if(args[1].startsWith("r:") && args[2].startsWith("l:") && args[3].startsWith("u:")){ // r / l / u
    Player p = player.getServer().getPlayer(args[3].split(":")[1]);
    String r = args[1].split(":")[1];
    String l = args[2].split(":")[1];
    Config.addPlayer(p, r, l, player);
    return true;
}else if(args[1].startsWith("l:") && args[2].startsWith("u:") && args[3].startsWith("r:")){ // l / u / r
    Player p = player.getServer().getPlayer(args[2].split(":")[1]);
    String r = args[3].split(":")[1];
    String l = args[1].split(":")[1];
    Config.addPlayer(p, r, l, player);
    return true;
}else if(args[1].startsWith("u") && args[2].startsWith("l:") && args[3].startsWith("r:")){ // u / l / r
    Player p = player.getServer().getPlayer(args[1].split(":")[1]);
    String r = args[3].split(":")[1];
    String l = args[2].split(":")[1];
    Config.addPlayer(p, r, l, player);
    return true;
}else if(args[1].startsWith("l:") && args[2].startsWith("r:") && args[3].startsWith("u:")){ // l / r / u
    Player p = player.getServer().getPlayer(args[2].split(":")[1]);
    String r = args[2].split(":")[1];
    String l = args[1].split(":")[1];
    Config.addPlayer(p, r, l, player);
    return true;
}else if(args[1].startsWith("r:") && args[2].startsWith("u:") && args[3].startsWith("l:")){ // r / u / l
    Player p = player.getServer().getPlayer(args[2].split(":")[1]);
    String r = args[1].split(":")[1];
    String l = args[3].split(":")[1];
    Config.addPlayer(p, r, l, player);
    return true;
}


texts:
table_with_headers = $(this.dom.table).find("thead tr th").map(->
  $(this).text()
).get().join("\t")

Can one write it nicer? I especially don't like the inner function in map syntax enforced by CoffeeScript and jQuery.


texts: De-serializing and serializing objects to be sent over the network

texts:
I am serializing and de-serializing a class object within the class which is then sent over the network like this:

class data
  public name as string
  public cmd as Commands
  public  message  as String

 Public Sub New(ByVal byteData As Byte())
        Try
            ' convert byte array to memory stream
            Using _ms As New MemoryStream(byteData)
                ' create new BinaryFormatter
                Dim _bf As New BinaryFormatter()
                ' set memory stream position to starting point
                _ms.Position = 0
                ' Deserializes a stream into an object graph and return as a object.
                dim oData as data =_bf.Deserialize(_ms)
                name = oData.name
                message = oData.Message
                cmd = oData.cmd
            End Using

        Catch ex As Exception
              Throw
        End Try

    End Sub

'Converts the Data structure into an array of bytes
    Public Function ToByte() As Byte()

        Dim bf As New BinaryFormatter()
        Try
            Using ms As New MemoryStream()
                bf.Serialize(ms, Me)
                Return ms.ToArray()
            End Using
        Catch ex As SerializationException
            Return Nothing
        Finally
            bf = Nothing
        End Try
    End Function
end class

Is this proper and efficient?


texts: React.js hook to move a car on a 5×5 board

texts:
I've got this custom hook that is suffering from a bad case of violation of SRP
This is a simple 5x5 board where a car can move around. Together with a server side check if the move is valid or not.

I'm thinking of moving directions to a useReducer hook. But problem is that I'm calling that using its index when I do things like rotate and move. I'm also putting the x, y and degrees in the same data object.

What's a good way to split this up following React Hooks best practices?

import { useState } from 'react'
import { createContainer } from "unstated-next"
import axios from 'axios'

const useController = () => {
  const directions = [
    {x: 0, y: -1, degrees: 0}, // up
    {x: 1, y: 0, degrees: 90}, // right
    {x: 0, y: 1, degrees: 180}, // down
    {x: -1, y: 0, degrees: 270}, // left
  ]
  const [initiatedGame, setInitiatedGame] = useState(false)
  const [degrees, setDegrees] = useState(0)
  const [direction, setDirection] = useState(0)
  const [position, setPosition] = useState({'x': 0, 'y': 0})
  const [carPlaced, setCarPlaced] = useState(false)

  const chooseDirection = direction => {
    setDirection(direction)
    setDegrees(directions[direction].degrees)
    setInitiatedGame(true)
  }

  const changeDirection = direction => {
    if(direction === -1) {
        setDirection(3)
    } else if(direction === 4) {
        setDirection(0)
    } else {
        setDirection(direction)
    }
  }

  const rotateLeft = () => {
    setDegrees(degrees - 90)
    changeDirection(direction - 1)
  }

  const rotateRight = () => {
    setDegrees(degrees + 90)
    changeDirection(direction + 1)
  }

  const move = () => {
    const root = process.env.REACT_APP_API_ROOT
    const {x, y} = directions[direction]
    axios.post(`${root}/move`, {
        x: position.x + x,
        y: position.y + y
      })
      .then((response) => {
        if(response.data.valid) {
          setPosition({x: position.x + x, y: position.y + y})
        }
      })
  }

  const placeCar = (x, y) => {
    if(!carPlaced) {
      setCarPlaced(true)
      setPosition({x, y})
    }
  }

  const onKeyDown = e => {
    switch (e.which) {
      case 37: // Left
        rotateLeft()
        break
      case 38: // Up
        move()
        break
      case 39: // Right
        rotateRight()
        break
      default:
        break
    }
  }

  return {
    rotateLeft,
    rotateRight,
    move,
    degrees,
    position,
    placeCar,
    carPlaced,
    chooseDirection,
    initiatedGame,
    onKeyDown
  }
}

export const Controller = createContainer(useController)
export default useController


texts:
#include <iostream>
#include <iomanip>

#ifdef USE_OLD_RAND

#include <stdlib.h>
inline double getRandDart() {return rand() * 1.0 / RAND_MAX;}

#else

#include <random>
std::default_random_engine              generator;
std::uniform_real_distribution<double>  distribution(0,1);
inline double getRandDart() {return distribution(generator);}

#endif

// Monte Carlo Simulator to estimate the value of PI.
//
// If we have a circle with a radius of 1.
// Then the smallest square that encloses the circle as sides of length 2.
//
//      Area of circle pi r^2   = pi
//      Area of square 2.r.2.r  = 4
//
//          Ratio of overlapping area:      pi/4
//
// If we throw darts randomly at a dart board (with an even distribution) and always hit the square.
// Then the ratio of darts falling into the circle should be pi/4 of the total number of darts thrown.
//
//      pi/4 * countInSquare  = countInCircle
//
//      pi = 4 . countInCircle / countInSquare
//
// To simplify the maths.
// We will set the center point as 0,0 and only use the top right quadrant of the circle.
// We have 1/4 the size of the square and circle but the same maths still apply.
//
// A dart thrown has a random x/y value in the range 0->1 (top right quadrant).
// A dart is outside the circle if x^2 + y^2 > 1  (note 1^2 is 1)
//

int main()
{

    long     countInSquare   = 0;
    long     countInCircle   = 0;

    for(long iteration = 0; iteration <= 10'000'000'000; ++iteration) {
        double x = getRandDart();
        double y = getRandDart();

        double d = (x * x) + (y * y);

        countInSquare   += 1;
        countInCircle   += (d >= 1.0) ? 0 : 1;

        if (iteration % 10'000'000 == 0) {
            std::cout << iteration << " " << (4.0 * countInCircle / countInSquare) << "\n";
        }
    }
    std::cout << "\n\n" << std::setprecision(9) << (4.0 * countInCircle / countInSquare) << "\n";

}

Output:

> ./a.out
9990000000 3.14158
10000000000 3.14158

3.14158355


texts:
This is the algorithm I am using to flip an image in-place. Though it works perfectly, I would like if any one can spot any potential problems or offer any points on improvement and optimizations.

/**
 * pixels_buffer - Pixels buffer to be operated
 * width - Image width
 * height - Image height
 * bytes_per_pixel - Number of image components, ie: 3 for rgb, 4 rgba, etc...
 **/
void flipVertically(unsigned char *pixels_buffer, const unsigned int width, const unsigned int height, const int bytes_per_pixel)
{
    const unsigned int rows = height / 2; // Iterate only half the buffer to get a full flip
    const unsigned int row_stride = width * bytes_per_pixel;
    unsigned char* temp_row = (unsigned char*)malloc(row_stride);

    int source_offset, target_offset;

    for (int rowIndex = 0; rowIndex < rows; rowIndex++)
    {
        source_offset = rowIndex * row_stride;
        target_offset = (height - rowIndex - 1) * row_stride;

        memcpy(temp_row, pixels_buffer + source_offset, row_stride);
        memcpy(pixels_buffer + source_offset, pixels_buffer + target_offset, row_stride);
        memcpy(pixels_buffer + target_offset, temp_row, row_stride);
    }

    free(temp_row);
    temp_row = NULL;
}


texts: Python configuration module for a web framework

texts:
I'm currently writing a web framework and I wanted to add a configuration module for reading environment variables and a configuration toml file.

Here is the code. The comment in the Config class should explain it all.

import os
import sys
import toml

BASEPATH = os.path.dirname(sys.modules['__main__'].__file__)
print(BASEPATH)
FILEPATH = os.path.abspath(os.path.join(BASEPATH, 'config.toml'))
print(FILEPATH)

class ConfigError(KeyError):
    """ Raised when a requested configuration can not be found """

class ConfigBase:
    def __init__(self):
        self.basename = ''
        self.default_options = {}
        raise TypeError('Should not use ConfigBase directly')

    def __getitem__(self, item):
        """ called when access like a dictionary
                config['database']['username']
        """
        default = self.default_options.get(item)
        if isinstance(default, dict):
            return ConfigSection(self.basename + '.' + item, default)
        # Check for env var
        envvar_string = '_'.join(self.basename.split('.') + [item]).upper()
        env = os.getenv(envvar_string)
        if env is None:
            if default is None:
                raise ConfigError(
                    'No configuration found for {}. '
                    'Add the environment variable {} or add'
                    ' the key to your config.toml file'.format(
                        '.'.join((self.basename, item)),
                        envvar_string
                    ))
            return default
        return env

class Config(ConfigBase):
    """ load configuration from envvar or config file
        You can get settings from environment variables or a config.toml file
        Environment variables have a higher precedence over the config file

        Use `config['section']['subsection']['key']` to get the value
        SECTION_SUBSECTION_KEY from environment variables or
        section.subsection.key from a toml file
        (usually written:
            [section.subsection]
            key = value
        in a toml file)
    """
    def __init__(self):
        self.default_options = self.load_config()
        self.basename = ''

    def load_config(self):
        with open(FILEPATH, 'r') as f:
            config = toml.load(f)
            return config

class ConfigSection(ConfigBase):
    def __init__(self, basename, defaults):
        self.basename = basename.lstrip('.')
        self.default_options = defaults


texts: Clean Code / OOP on Monty Hall Simulation Implementation

texts:
can you review the this code for the Monty Hall simulation, mainly on the aspects of OOP and CleanCode

public static void main(String[] args) {
    final int iterations = 10000;
    System.out.println("chance with    change = " + getChanceForPlay(iterations, true));
    System.out.println("chance without change = " + getChanceForPlay(iterations, false));
}

private static double getChanceForPlay(int iterations, boolean doChange) {
    double win = 0;
    for (int i = 0; i < iterations; i++) {
        List<Price> doors = createDoors();
        int selectedDoor = random.nextInt(3); //the player selects one of three doors

        //let's remove one goat (but not the selected door)
        for (int currentDoor = 0; currentDoor < 3; currentDoor++) {
            if (currentDoor != selectedDoor && doors.get(currentDoor) == Price.GOAT) {
                doors.remove(currentDoor);

                //re-Index, if required
                selectedDoor = currentDoor < selectedDoor? selectedDoor-1:selectedDoor;
                break;
            }
        }

        //player changes door
        if (doChange) {
            selectedDoor = selectedDoor == 0 ? 1 : 0;
        }

        if (doors.get(selectedDoor) == Price.CAR) {
            win++;
        }
    }
    return win / iterations;
}

private static List<Price> createDoors() {
    List<Price> doors = new ArrayList<>();
    doors.add(Price.GOAT);
    doors.add(Price.GOAT);
    doors.add(Price.CAR);
    Collections.shuffle(doors);
    return doors;
}

private enum Price {
    GOAT, CAR
}

I know many other people made the same thing. It's more of an academical question...

some thoughs upon it done by myself:

should i break up the code more? maybe one method for removing one door by the showmaster?
usage of integer for doors - i think that's not so fancy...
overusage of brackets
too much comments (tell don't ask)
too complicated (brain overload)

Edit:

there exists an follow up question on how to do it better


texts: Return Y integer with same bit sets as X & having | X - Y | minimum value

texts:
I happened to come across one question:

  Given an integer 'x' (Only positive), write an algorithm that returns
  integer 'y' such that it has the same number of bits set as 'x' and is
  not equal to 'x' and the distance |x-y| is minimized.

  Example:

x: 01
y: 10

Now I wrote some bit manipulation as follows and it's working correctly. But I wanted to know if there is a more compact algorithm (we are not allowed to use any built-in functions).

  Algorithm

  If the Zeroth bit '0':

  find first occurrence of '1'
  find last occurrence of '0' before first '1'
  reverse them (I used OR and AND function to do that)

  If the Zeroth bit '1':

  find first occurrence of '0'
  find last occurrence of '1' before first '0'
  reverse them (I used OR and AND function to do that)

  Input:

x = 324095 <1001111000111111111>

  Output:

324351 <1001111001011111111>

  Input:

x = 12 <1100>

  Output:

10 <1010>

private static int MinDiff(int x)
{
    int y=0,a=0,b=0,countOne=0, countZero=0;
    if(x == 0)
        return -1;

    if( (x&1)!=1)
    {
        y=x;
        while( (y & 1) !=1  )
        {
            countOne++;
            y=y>>1;
        }
        y=x;
        while( (y&3) != 2 )
        {
            countZero++;
            y=y>>1;
        }
        a=1;
        while(countZero != 0)
        {
            a = a<<1;
            countZero--;
        }
        b=1;
        while(countOne != 0)
        {
            b = b<<1;
            countOne--;
        }
    }
    else
    {
        y=x;
        while( (y&1) != 0  )
        {
            countOne++;
            countZero++;
            y=y>>1;
        }
        countOne--;
        y=x;

        a=1;
        while(countZero != 0)
        {
            a = a<<1;
            countZero--;
        }
        b=1;
        while(countOne != 0)
        {
            b = b<<1;
            countOne--;
        }
    }

    b = ~b;
    y = (x | a) & b;
    return y;
}


texts: Hiding odd rows in a table on click event

texts:
Problem Statement

  Write JavaScript code hideOddRows.js that attaches to the button click event and hides the odd rows of the table when clicked.

Expected Output

When you click on "Hide Odd Rows":

Solution

/* hideOddRows.js */
document.querySelector('[name=HideRows]').onclick = hideRows;

function hideRows(){
    var elements = document.getElementsByClassName('hide');
    Array.prototype.forEach.call(elements, function(element){
        element.style.display = "none";
    });
    return true;
}
<!DOCTYPE html>

        <title>Hide odd rows</title>
        <meta charset="UTF-8">

                row 1

                row 2

                row 3

                row 4

                row 5

        <button type="button" name="HideRows">Hide Odd Rows</button>

Questions

I could not manage to place script tag in head due to DOM loading issue. How do I improve this solution to place script tag in head?
Can I improve the HTML code?

Note: I've yet to learn jQuery.


texts:
I was trying to solve one programming challenge :

First input is a list of connections which is made of pair of IPv4
address.  Each IP has its own state which starts with false, each
connection also has state which is made up by logical AND of state of
its IPs
Second input is a toggle IPs list , these toggles the state of IP
address ( false to true or true to false). For each toggle action ,
calculate the impact on connections which is defined as how many
connections state changed due to change in one IP address.

I solved the above challenge by using below Java program, but I'm not sure if there could be any scope of improvement for memory consumption and run time.
Please pardon my programming knowledge, I would appreciate any positive feedback to cover corener cases
public class NumberOfDevices {

    public static void main(String[] args) {
        String [][]connections ={{"192.167.0.0","192.167.0.1"},{"192.167.0.2","192.167.0.0"},{"192.167.0.0","192.167.0.3"}};
        String []toggleIps= {"192.167.0.1","192.167.0.0","192.167.0.2","192.167.0.0", "0.0.0.0"};
        int[] result = numberOfDevices(connections, toggleIps);

        for(int i:result) {
            System.out.print(i + " ");
        }
    }

    public static int[] numberOfDevices(String[][] connections, String [] toggleIps) {
        int count =0;
        int [] result = new int[toggleIps.length];
        if(connections.length>0) { // already a given contaraint that the length of toggle IPs is >=1

            Map<String,Ipv4Address> ip = new HashMap<>();
            for(int i=0; i<connections.length; i++) {
                Ipv4Address ip1, ip2;

                if(!ip.containsKey(connections[i][0])) {
                    ip.put(connections[i][0], new Ipv4Address(connections[i][0]));
                }
                if(!ip.containsKey(connections[i][1])) {
                    ip.put(connections[i][1], new Ipv4Address(connections[i][1]));
                }

                ip1=ip.get(connections[i][0]);
                ip2=ip.get(connections[i][1]);

                ip1.addConnection(ip2);
                ip2.addConnection(ip1);

            }

            for(int j=0; j<toggleIps.length; j++) {
                if(!ip.containsKey(toggleIps[j])) {
                    result[j]=0;
                }
                else {
                    Ipv4Address ipv4 = ip.get(toggleIps[j]);
                    ipv4.setState(!(ipv4.getState()));
                    for(Ipv4Address conn:ipv4.getConnections()) {
                        if(conn.getState()) {
                            result[j]++;
                        }
                    }
                }
            }
        }

        return result;
    }

}

// class representing the IPv4 address , it has IP address, current state and the connections where its present
class Ipv4Address{
    String ipAddress;
    boolean state;
    List<Ipv4Address> connections;

    public Ipv4Address(String ipAddress) {
        this.ipAddress = ipAddress;
        this.state=false;
        connections= new ArrayList<>();
    }

    public boolean getState() {
        return this.state;
    }
    public void setState(boolean state) {
        this.state=state;
    }

    public void addConnection(Ipv4Address ipaddress) {
        this.connections.add(ipaddress);
    }
    public List<Ipv4Address> getConnections(){
        return this.connections;
    }

}


texts:
f-strings is a new feature in the upcoming python release which basically lets you do this:

>>> s = 'qwerty'
>>> f'{s} {1+2}'
'qwerty 3'

Not pleased at having to wait until f-strings are widely supported, I came up with the following function, which should work for any Python version starting with 2.6.

def f(s):
    return s.format(**inspect.currentframe().f_back.f_locals)

>>> s = 'qwerty'
>>> f('{s} abc')
'qwerty abc'

Switching to f-strings in the future should be as easy as removing the two parentheses.

Of course, my function doesn't support the more advanced features of f-strings (like evaluation of any expression).

My questions are:

If I start widespread use of this function in my code, is there a chance this bites me in the future? Is there anything objectionable in my current implementation?
How would you implement a more advanced f-function, supporting evaluation of arbitrary expressions? Preferably without having performance suffer too much - my benchmark shows the f-function is only slightly slower than directly calling format.

Python version 2.6.


texts:
Last semester in my Masters Program I developed this code for sieving. My professor wants me to write a report that he might use locally within the school, but I feel like I've done nothing that new, despite coming up with my algorithm without doing any research other than the bare numbers.

Essentially it skips over a large percentage of numbers (I estimate about 66%). It skips all factors of 2 and 3. The first loop throws in primes and potential primes through a modified formula of 6k+-1. The second nested loop takes the outer prime numbers and finds all multiples.

The inner if statement skips numbers as well - if the number is a factor of 3, it skips ahead. For instance if B = 13, B+2 = 15%3 = 0, then B jumps straight to 17. I've found this method to be faster for some reason than accessing the array every b+=2; and switching the boolean. Unfortunately, I wish I could find a way to make it more efficient (I may be able to use an additional counter to just figure out when the number is going to fall on a five or three).

Psuedo-code as follows (of course this implementation is different, but follows similar principles):

Initialize list with initial values (2,3).
Use the formula 6k±1 where k = 1 and must increment by 1. Store values to list.
Compute step 2 up to a product n, where n > 7 if k = 1.
Starting with x=5, remove all products of x*y (to n), where y starts at x and
increments to the next number in the list as x remains the same.
Repeat step four by assigning x to the next number in the list - stop when x*y > N.
Final step: We must remove all factors of the square of every prime number (25, 49)

Is this any decent, or is my implementation really slow?

//-----------------------------------------------------------------
//
//  Class:   SixSieve.java
//
//  Author:  Alex Lieberman
//
//  Purpose: Finds all prime numbers up to a specified
//           maxNumber and marks them as true in the boolean array.
//
//-----------------------------------------------------------------

public class SixSieve

 {

  public static void main (String[] args)

  {

   int maxNumber = 1000;

   boolean[] Numbers = new boolean [maxNumber];

   Numbers[2] = true;
   Numbers[3] = true;

   int num = Numbers.length;

   //----------------------------
   //
   //  The following loop finds
   //  potential primes and primes.
   //
   //----------------------------

   for (int i = 5, j = 7; i < num; i+=6, j+=6)

    {

     Numbers[i] = true;

     if (j < num)

      Numbers[j] = true;

    }

   //----------------------------
   //
   //  The following loop eliminates
   //  non-primes (multiples of everything
   //  in the previous loop).
   //
   //----------------------------

   for (int a = 5; a*a <= num; a+=2)

    {

     if (Numbers[a])

      {

       for (int b = a; b*a <= num; )

        {

         Numbers[b*a] = false;

         if ((b+2)%3 == 0)

          b+=4;

         else

          b+=2;

        }

      }

    }

    System.out.println("Done");

   //----------------------------
   //
   //  The following loop prints
   //  all the primes found.
   //
   //----------------------------

    for (int i = 0; i < num; i++)

     {

      if (Numbers[i] == true)

       System.out.print(i + " ");

     }

  }

 }


texts:
This is a follow-up question to Sorting algorithms - Bubble sort

Again, for practice purposes only, I took on an implementation of the well known insertion sort as a method to be used similarly to std::sort.

As expected, the code lives inside a header file called insertion_sort.h:

#pragma once

#include <iterator>
#include <algorithm>

namespace sorting_algorithms {
    template <typename BidirectionalIterator,
            typename Comparator = std::less<>>
    void insertion_sort(BidirectionalIterator begin, BidirectionalIterator end,
            Comparator cmp = {}) {

        if (std::distance(begin, end) < 2) {
            return;
        }

        for (auto current_element = std::next(begin); current_element != end;
                ++current_element) {
            for (auto i = std::prev(current_element), i_next = current_element;
                    i_next != begin; --i, --i_next) {
                auto& i_val = *i;
                auto& i_next_val = *i_next;
                if (cmp(i_val, i_next_val)) {
                    break;
                }
                std::iter_swap(&i_val, &i_next_val);
            }
        }
    }
}

I tried to follow most hints and suggestions I received for my previous question about bubble sort. I am aware of the fact that the algorithm can also be implemented in a way that only requires forward iterators, but I decided to require bidirectional iterators here for ease of implementation.

Again, I also provide you a main file for simple compilation and testing purposes:

#include <random>
#include <vector>
#include <iostream>
#include <iomanip>
#include <chrono>
#include <algorithm>

#include "insertion_sort.h"

int main() {
    unsigned seed =
        std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine engine(seed);
    std::uniform_int_distribution<unsigned> distribution(0, 10000);

    std::vector<unsigned> vec;
    for (std::size_t i = 0; i < 100; ++i) {
        unsigned num = distribution(engine) + 1;
        std::cout << num  << ' ';
        vec.push_back(num);
    }
    std::cout << "\n\n";

    sorting_algorithms::insertion_sort(vec.begin(), vec.end());

    for (const auto& e : vec) {
        std::cout << e << ' ';
    }

    std::cout << std::boolalpha;
    std::cout << "\nSorted? " << std::is_sorted(vec.begin(), vec.end())
        << "\n\n";

    sorting_algorithms::insertion_sort(vec.begin(), vec.end(),
            [] (const auto& v0, const auto& v1) {
                return v0 > v1;
            });

    for (unsigned e : vec) {
        std::cout << e << ' ';
    }
    std::cout << "\nSorted (in reverse order)? "
        << std::is_sorted(vec.begin(), vec.end(),
            [] (const auto& v0, const auto& v1) {
                return v0 > v1;
            }) << '\n';
}


texts: Multithreaded web scraper with proxy and user agent switching

texts:
I am trying to improve the performance of my scraper and plug up any possible security leaks (identifying information being revealed).

Ideally, I would like to achieve a performance of 10 pages per second. What would I need to do to achieve the biggest performance boost besides get a faster connection / dedicated server? What could be improved?

PS: I am only using eBay.com as an example here. The production version of the scraper will obey robot.txt requests, avoid peak traffic hours, and be throttled so I am not effectively DDoSing the site.

import requests
from bs4 import BeautifulSoup
from multiprocessing.dummy import Pool as ThreadPool

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logging.getLogger("requests").setLevel(logging.WARNING)

# NOTE: The next two sections are for demo purposes only, they will be imported from modules
# this will be stored in proxies.py module
from random import choice
proxies = [
    {'host': '1.2.3.4', 'port': '1234', 'username': 'myuser', 'password': 'pw'},
    {'host': '2.3.4.5', 'port': '1234', 'username': 'myuser', 'password': 'pw'},
]
def check_proxy(session, proxy_host):
    response = session.get('http://canihazip.com/s')
    returned_ip = response.text
    if returned_ip != proxy_host:
        raise StandardError('Proxy check failed: {} not used while requesting'.format(proxy_host))
def random_proxy():
    return choice(proxies)
# / end of proxies.py

# this will be stored in user_agents.py module
from random import choice
user_agents = [
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/600.8.9 (KHTML, like Gecko) Version/8.0.8 Safari/600.8.9',
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
]
def random_user_agent():
    return choice(user_agents)
# / end of user_agents.py

def scrape_results_page(url):
    proxy = random_proxy()  # will be proxies.random_proxy()
    session = requests.Session()
    session.headers = random_user_agent()  # will imported with "from user_agents import random_user_agent"
    session.proxies = {'http': "http://{username}:{password}@{host}:{port}/".format(**proxy)}
    check_proxy(session, proxy['host'])  # will be proxies.check_proxy(session, proxy['host'])

    response = session.get(url)
    soup = BeautifulSoup(response.text, 'lxml')
    try:
        first_item_title = soup.find('h3', class_="lvtitle").text.strip()
        return first_item_title
    except Exception as e:
        print url
        logging.error(e, exc_info=True)
        return None

page_numbers = range(1, 10)
search_url = 'http://www.ebay.com/sch/Gardening-Supplies-/2032/i.html?_pgn='
url_list = [search_url + str(i) for i in page_numbers]

# Make the Pool of workers
pool = ThreadPool(8)
# Open the urls in their own threads and return the results
results = pool.map(scrape_results_page, url_list)
# Close the pool and wait for the work to finish
pool.close()
pool.join()

To get it working you will need to enter valid proxies or comment out the session.proxies = ... and check_proxy(session, proxy['host']) lines.


texts: Calculation of Energy Spectrum using C++

texts:
My purpose is to calculate the energy spectrum of three-dimensional turbulent flow from three velocity components. The calculation is too expensive. Therefore, I hope the calculation time can be reduced. The above code is a sample of calculating the energy spectrum. I expect to receive some suggestions on parallel computing using OpenMP for the energy E[k]. The size of i and j loops are 1000 000 while that of k is 100. Some parameters, x, y, z are velocity components and d1 is velocity magnitude, are created for code structure. I desire that the calculation is designed well on a pc with 40 cores.
This code is compiled as g++ test.cpp -o run -fopenmp
How can i parallelize this following code using openmp:
#include <iostream>
#include <math.h>
#include <vector>
#include <math.h>
#include <cmath>
#include <omp.h>

using namespace std;

int main()
{

    int i,j,k;
    int np = 1000000;  // number of fluid particle
    int kmax = 100;   // wavenumber
    double E[kmax+1] = {0.0};  //energy

    // need to be parallelized
    for (i = 0; i < np-1; i++){
        for (j = i+1; j < np; j++){

            double x = sin(double(2*i+j)/(3.0*np));//x,y,z,d1 for test.
            double y = sin(double(i+j)/(2.0*np));//x,y,z are velocity
            double z = sin(double(i*j)/np/np); //d1 velocity magnitude
            double d1 = sqrt(x*x + y*y + z*z);

            for (k = 1; k <= kmax; k++){

                double d2 = k * d1;
                E[k] += x + y + sin(d2) / d2;
            }

        }
    }

    return 0;
}


texts: Solving this Python implementation for Stock Gains

texts:
I wanted to ask for a code review for the following interview question:

  Problem: Max Gain

  Given an list of integers, write a method - max_gain - that returns the maximum gain. Maximum Gain is defined as the maximum difference between 2 elements in a list such that the larger element appears after the smaller element. If no gain is possible, return 0.

Example:

max_gain([100,40,20,10]) ==> 0
max_gain([0,50,10,100,30]) ==> 100

Solution

def max_gain(input_list):
    if len(input_list) < 2:
        return 0
    a = input_list[0]
    max_val = 0
    for i in input_list[1:]:
        max_val = max(max_val, i-a)
        a = min(a, i)
    return max_val


texts:
Here is my Boyer Moore code in Python:

def BoyerMoore(stringy, substring):
    if stringy == substring:
        return 0
    ASCIIcharset = [-1]*256
    for x in xrange(len(stringy)):
        ASCIIcharset[ord(stringy[x])] = x

    stringLen = len(stringy)
    substringLen = len(substring)
    for i in xrange(stringLen - substringLen):
        skip = 0
        for j in xrange(substringLen - 1 , 0, -1):
            if stringy[i + j] is not substring[j]:
                skip = max(1, j - ASCIIcharset[ord(stringy[i + j])])
                i += skip
                break
        if skip == 0:
            return i
    return -1

I was wondering what are some small tweaks here and there that I can do to increase the efficiency. Redesigning this code is fine too.


texts: Find the area of the bounding box of a robot's moves on a grid

texts:
Given a string of directions (example: "LLRUDDULRDRU") find the area of the rectangle defined by the lowest-left point (minx, miny) and the highest-right point (maxx, maxy) the robot was in.

The canonical solution I think would be.

int area(char* directions) {
    char * c = directions;
    int x=0, y=0, minx=0, maxx=0, miny=0, maxy=0;
    while (*c) {
        if (*c == 'U') {
            y++;
        } else if (*c == 'D') {
            y--;
        } else if (*c == 'R') {
            x++;
        } else if (*c == 'L') {
            x--;
        }

        if (y < miny)
            miny = y;
        if (x < minx)
            minx = x;
        if (y > maxy)
            maxy = y;
        if (x > maxx)
            maxx = x;

        c++;
    }
    return (maxx - minx) * (maxy - miny);
}

The problem I see with this is that the indentation is switched often making it hard to read. That's why I tend to exploit the fact C's logical operators return numbers 1 or 0.

int area(char * directions) {
    char * c = direction;
    int x=0, y=0, minx=0, maxx=0, miny=0, maxy=0;
    while (*c) {
        y += (*c == 'U') - (*c == 'D');
        x += (*c == 'R') - (*c == 'L');

        minx = (x < minx) ? x : minx;
        miny = (y < miny) ? y : miny;
        maxx = (x > maxx) ? x : maxx;
        maxy = (y > maxy) ? y : maxy;

        c++;
    }

     return (maxx - minx) * (maxy - miny);
}

However doing this feels 'too hacky'.

Is doing this a good practice at all?


texts: Functionaly Finding Prime Factors with Multiplicity

texts:
I am quite new to Haskell so any suggestions are welcome, also I noticed that it works quite slow even for something like

prime_factors_mult (2*2*2*2*3*3*3*5*5*7*7*7*7*13*13*13*17*19)

Also I may not know of coding conventions/formatting styles and better ways to do things,so you may also help me with that:

prime_factors_mult :: Int -> [(Int, Int)]
prime_factors_mult n =
    reverse . fst $
        foldl
            (\acc@(factors, val) x
                -> if val `mod` x == 0 then
                    let (k, v) = reduce val x in ((x, k) : factors, val `div` v)
                else
                    acc
            )
        ([], n)
        [2 .. floor . sqrt . fromIntegral $ n]

reduce :: Int -> Int -> (Int, Int)
reduce val x =
    if val `mod` x == 0 then
        let (k, v) = reduce (val `div` x) x in (1 + k, v * x)
    else
        (0, 1)


texts: Finding the intersection of two sets of integers

texts:
I need to pass a programming exam in order to graduate but I'm having a hard time passing it because most of my programs are too slow. Can someone give me some tips on how to make my programs faster please? Below is an example of a question we had in the last exam and the code i wrote. My code passed the first test case but for the other 3 it exceeded the time limit. Please let me know if you have any suggestions on how to improve my code.

  Description Given two sets of numbers, output their intersection set.

  Input There are multiple test cases. Each case contains four lines. The first line begins with an integer N. The second line contains N integers, representing the numbers in the first set. The third line has one integer M, and the fourth line contains M integers, represent the numbers in the second set.

  All the numbers are 32 bit signed integers.

  The input is terminated if N = 0.

  For case 1, 1 <= N, M <= 10^3  (Time Limit: 1 sec)
  For case 2, 1 <= N, M <= 10^4  (Time Limit: 1 sec)
  For case 3, 1 <= N, M <= 10^5  (Time Limit: 1 sec)
  For case 4, 1 <= N, M <= 10^6  (Time Limit: 3 sec)

  Output For each test case, print the intersection of the two sets. Output them in ascending order. If the intersection of the two
  sets is an empty set, print 「empty」 (without quotes).

  Sample Input 3 1 2 3 3 4 5 6 8 4 10 13 8
  9 2 1 5 4 4 2 3 1 5 1 2 2 3 2 5 1 2 2 3
  1 0

  Sample Output empty 1 2 4 1 2 2 3

This is my code:

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

int set1[2][1000000];
int set2[2][1000000];
int intersection[1000000];

int main()
{
    int n;
    scanf("%d",&n);

    while( n!= 0)
    {
        int m, i, x, num, y = 0;
        int w, u, xx;

        for(i = 0; i < n; i++) //initialise set1 to 0
        {
            set1[1][i] = 0;
        }

        for(x = 0; x < n; x++) //put set1 in array
        {
            scanf("%d", &num);
            set1[0][x] = num;
        }

        scanf("%d",&m);
        for(i = 0; i < m; i++) //initialise set2 to 0
        {
            set2[1][i] = 0;
        }

        for(x = 0; x < m; x++) //put set2 in array
        {
            scanf("%d", &num);
            set2[0][x] = num;
        }

        for(x = 0; x < n; x++)
        {
            for(i = 0; i < m; i++)
            {
                if((set1[1][x] == 0) && (set1[0][x] == set2[0][i]) && (set2[1][i] == 0))
                {
                    intersection[y] = set2[0][i];//put in printing array
                    y++;
                    set2[1][i] = 1;
                    set1[1][x] = 1;
                }
            }
        }

        for(x = 0; x < y; ++x) //sort
        {
            for(i = x + 1; i < y; ++i)
            {
                if(intersection[x] > intersection[i])
                {
                    w = intersection[x];
                    intersection[x] = intersection[i];
                    intersection[i] = w;
                }
            }
        }

        for(x = 0; x < y; x++)//print
        {
            if(x == 0)
            {
                printf("%d", intersection[x]);
            }
            else printf(" %d", intersection[x]);
        }

        if (y == 0)
        {
            printf("empty");
        }
        printf("\n");

        scanf("%d",&n);
    }
    return 0;
}


texts:
I have an asp.net core app that sends emails with a link. When they click the link they can start taking an online test without logging in. The link contains a number that is validated by the controller who then returns their test.

I log into my app and create a project. Here I enter a list of emails in a textbox separated by commas. In the backend I put this textbox string into a list like so:

string emailList;
List<string> list = emailList.Split(',').ToList();
//removes whitespace in list:
for (int i = 0; i < list.Count(); i++)
{
 list[i] = string.Join("", list[i].Split(default(string[]),
                       StringSplitOptions.RemoveEmptyEntries));
}

The only way i can see on how to send many unique emails would be to loop over this list and then use the normal SendEmail method in mimekit:

string message = "Press this link to take the test";
int number = 0;

foreach(var email in emailList)
{
  //gets a unique number stored in a table for each person:
  number = GetNumber(email);
  message = $"http://www.mywebsite.com/Test/{number}";
  await _emailSender.SendEmailAsync(email, "Subject", message);
}

Now the emailSender uses the normal mimekit method to send one email for each in the list.

This takes a long time for a big list. Are there any other ways to do it, or can I write this more effectively? What could be the bottlenecks of my solution? Any feedback would be great, from my bad async code to security . I suspect that I use too much async when I should return only a task, but i'm not sure how to do it. I also wonder how I can even test this on a larger scale as I don't have a big emaillist to use.

Here is the mimekit code to send the email:

public async Task SendEmailAsync(string email, string subject, string message)
{
  var melding = new MimeMessage();
  melding.From.Add(new MailboxAddress("Frank", _options.Option1));
  melding.To.Add(new MailboxAddress(email));
  melding.Subject = subject;

  melding.Body = new TextPart("plain")
  {
     Text = message
  };
  Try
  {
     await SendMessage(melding);
  }
  catch(Exception ex)
  {
     //log error
     throw new ApplicationException($"something went wrong:'{ex.Message}'.");
  }
}
private async Task SendMessage(MimeMessage message)
{
   using (var client = new SmtpClient())
   {
      await client.ConnectAsync("smtp.WebSiteLive.net", 587, SecureSocketOptions.None);
      client.AuthenticationMechanisms.Remove("XOAUTH2"); // Must be removed for Gmail SMTP
      await client.AuthenticateAsync(_options.Option1, _options.Option2);
      await client.SendAsync(message);
      await client.DisconnectAsync(true);
    }
}

any help much apprechiated!!


texts:
I have created a little console tool that simply does commands that you enter.

The commands are stored in a txt file.  Right now I only got 2 commands: getTime and getCommands.

Pretty simple, but I'm not sure I'm doing anything the most optimal way, which is why I am asking here. I was thinking about creating a whole class to get the time but I wasn't sure that would make any sense (as it seems SYSTEMTIME is already a class).

Also, I was thinking about the next command I would add is something where you can input "open 'file' ", where file is the program you want to open. I googled a bit and found a function called filefindnext and filefindfirst (to search for the file), but I'm not sure if this is the best way to do it? (I was also thinking about just adding a .txt file with the dir to the predefined files)

I hope you can help clear up my code and in general make my code better.  I'm still fairly new to programming, so all constructive feedback is appreciated.

main.cpp (just a little test for my command class)

int main()
{
    command list;
    list.setCommandList();
    list.printCommands();
    while (1)
    {list.getCommand();
    }
}

commands.h

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
class command
{
public:
    command();
    ~command();
    void printCommands();
    string verifyCommand(string);
    void getCommand();
    void executeCommand(string);
    void setCommandList();
private:
    std::string userinput_;
    std::ifstream file;
    string *commandlist;
    int cNr; //command number
};

commands.cpp

#include "commands.h"
#include "Time.h"
command::command(){
file.open("commands.txt");
cNr = 0;
}
command::~command()
{
    file.close();
    delete[] commandlist;
}
void command::printCommands()
{
    string line;
    cout <<"Command list:\n\n";

    for (int i = 0;i<cNr;i++)
    {
        cout <<commandlist[i] <<endl;
    }
    cout <<endl;
}
void command::setCommandList()
{
    int nrOfLines = 0;
    string cline;
    string line;
    while (getline(file,cline))
{
    nrOfLines++;
}
    file.clear();
    file.seekg(0, file.beg);
    commandlist = new string[nrOfLines];
    while (getline(file,line))
    {
        commandlist[cNr] = line;
        cNr++;
    }
}
string command::verifyCommand(string command)
{
    string line;
for (int i = 0;i<cNr;i++)
{
    if (command==commandlist[i])
        return command;
}
    return "";
}

void command::getCommand()
{
    string userinput;
    cout <<"Enter command:"<<endl;
    cin >> userinput;
    userinput_ = verifyCommand(userinput);
    if (userinput_ == "")
    {cout <<"Error, can´t find that command. Please try again"<<endl;
    getCommand();
    }
    else
    executeCommand(userinput_);
}

void command::executeCommand(string com)
{
    if (com == "getTime")
    {
        cout << string( 100, '\n' ); //clear screen
        SYSTEMTIME t;
        GetLocalTime(&t);
        cout<< "H:"<<t.wHour<<" M:"<<t.wMinute<<" S:"<<t.wSecond<<endl;
    }
    if (com == "getCommands")
    {
        cout << string( 100, '\n' );
        printCommands();
    }
}


texts:
I am working on a ADDIN that works on 3D drafting program. This ADDIN has historically grown and now I am doing a big rewrite.

During this rewrite I came across a issue. I have 2 (fairly similar) types of models I am trying to edit using the same code block ADDIN. They both have a property name (inside the 3D drafting progam) that does the same but the property name is different.

This difference is giving me a exception. But I am sure that there is only are two different names.

Is it acceptable to use Try and Catch like this?

' Set reference to the user defined property set
Dim oUserProperties As PropertySet =
    ReferencedDocument.PropertySets.Item("Inventor User Defined Properties")

Try
    oUserProperties.Item("Noz_Eccentric").Value = Eccentric
Catch ex As Exception
    oUserProperties.Item("Noz_Radius").Value = Eccentric
End Try

OR would it be better to rename the property when the exception is encountered? (sort of a file migration)

' Set reference to the user defined property set
Dim oUserProperties As PropertySet =
    ReferencedDocument.PropertySets.Item("Inventor User Defined Properties")

Try
    oUserProperties.Item("Noz_Eccentric").Value = Eccentric
Catch ex As Exception
    oUserProperties.Item("Noz_Radius").Name = "Noz_Eccentric"
    oUserProperties.Item("Noz_Eccentric").Value = Eccentric
End Try

Please do not comment on the o prefix used. It is common within the 3D drafting program API sample and I kinda inherited this behavior..


texts: Find the smallest positive integer that is absent from a given array

texts:
I made the acquaintance of big-O a couple of weeks ago and am trying to get to grips with it, but although there's a lot of material out there about calculating time complexity, I can't seem to find out how to make algorithms more efficient.

I've been practising with the the demo challenge in Codility:

  Write a function that, given an array A of N integers, returns the
  smallest positive integer (greater than 0) that does not occur in A.
  For example, given A = [1, 3, 6, 4, 1, 2], the function should return
  5. The given array can have integers between -1 million and 1 million.

I started with a brute-force algorithm:

public int solution(int[] A)
{
    for ( int number = 1; number < 1000000; number ++)
    {
        if (doesContain(A, number)){}
        else return i;
    }
    return 0;
}

This passed all tests for correctness but scored low on performance because the running time was way past the limit, time complexity being \$O(N^2)\$.

I then tried putting the array into an arraylist, which reduces big-O since each object is "touched" only once, and I can use .Contains which is more efficient than iteration (not sure if that's true; I just sort of remember reading it somewhere).

public int solution(int[] A)
{
    ArrayList myArr = new ArrayList();
    for (int i=0; i<A.Length; i++)
    {
        myArr.Add(A[i]);
    }
    for ( int i = 1; i < 1000000; i++)
    {
        if (myArr.Contains(i)){}
        else return i;
    }
    return 0;
}

Alas, the time complexity is still at \$O(N^2)\$ and I can't find explanations of how to cut down time.

I know I shouldn't be using brute force, but can't seem to think of any other ways... Anyone have an explanation of how to make this algorithm more efficient?


texts:
So, I am either a glutton for punishment, or I have no life, but I wrote a script to answer a question over on Ask Ubuntu as a solution for selecting a random MP3 file in a given directory, and playing it in the specified player of choice.  I am half-embarrassed to share this because I know it's not my best work and relies on user input for pretty much anything.

The script is designed to be passed the executable name for the media player the user wants to use, and select a random MP3 file to play in that player.  There is a small level of Evil in here, because the person executing this script must specify a media player.  It also assumes it's in the user's /home/$USER/Music directory on Linux-based systems, so to use another dir it has to be specified.

Any improvements you want to give me, feel free.  I know this works, though.  Main concerns are if I derped anywhere and did a bad thing.

randommp3.py (or, in a Gist if you want pretty):

#!/usr/bin/python

import getpass
import subprocess as sp
import os
import glob
import random
import argparse

if __name__ == "__main__":
    # Parse arguments to the script
    argparser = argparse.ArgumentParser(description="Open a random MP3 in the player of choice, or the default player",
                                        add_help=True)
    argparser.add_argument('--dir', '--directory', '--music-dir', dest='dirpath', type=str,
                           default=str('/home/' + getpass.getuser() + '/Music'), required=False,
                           help="The path to the directory where your music is stored. If the path has spaces, wrap the "
                                "entire path in single-quotes ('/home/ubuntu/My Music/' for example). If not specified, "
                                "the current user's Music directory in their /home/ folder is used.")
    argparser.add_argument('player', type=str, help="The executable name of the media player "
                                                    "to open the MP3 with. If none specified, "
                                                    "uses the system default player.")

    # Using the above 'argparser' items, get the arguments for what we're going to be using.
    args = argparser.parse_args()

    # Gp to the directory your music is in.
    os.chdir(args.dirpath)
    mp3s = glob.glob('*.mp3')

    # Modify the directory path to make sure we have the trailing slash
    dirpath = args.dirpath
    if dirpath[-1] not in '/\\':
        dirpath += '/'

    # Actually open the MP3 file, and /dev/null to suppress output messages from the process.
    DEV_NULL = open(os.devnull, 'w')
    execpath = [args.player, '%s%s' % (dirpath, str(random.choice(mp3s)))]
    sp.Popen(execpath, stdout=DEV_NULL, stderr=DEV_NULL)


texts: Improving readability of 3d math in Java

texts:
Doing graphics in Java, I find myself writing lines like these regularly:

Vector3f b = mid.add( a.mult(yOffset + length / 2) ).add( up.cross(a).mult(xOffset) );

It gets even worse when I'm reusing objects.

Vector3f vTemp = VarPool.getVector3f();
Vector3f b = VarPool.getVector3f();

b.set(mid).addMutable( a.multAndStore(yOffset + length / 2, vTemp) ).addMutable( up.crossAndStore(a, vTemp).multMutable(xOffset) );

//...do some useful computation...

VarPool.recycle(vTemp, b);

I've tried coping using a combination of these two methods:

1. Place 'translations' in comments above dense lines

//i.e. Vector3f b = ( mid + a * (yOffset + length / 2) + (up X a) * xOffset );
//this calculates such and such
b.set(mid).addMutable( a.multAndStore(yOffset + length / 2, vTemp) ).addMutable( up.crossAndStore(a, vTemp).multMutable(xOffset) );

Disadvantages: Extra noise. 'Translation' comments can look like actual code that's been commented out. There's no getting around the real code being hard to read.

2. Break dense chains into more readable lines

b
    .set(mid)
    .addMutable( a.multAndStore(yOffset + length / 2, vTemp) )
    .addMutable( ( vTemp = up.crossAndStore(a, vTemp)
                    .multMutable(xOffset) ) );

Disadvantages: Some calculations don't chain up quite as nicely. When different return types are involved (e.g. matrices, quaternions, scalars), chaining is not always logical or possible.

Any other suggestions? Switching language is not really viable.


texts: Python functions to determine if a given ticker symbol is an ETF

texts:
I am working on a stock analysis application in Python and I have the need to determine whether an input ticker symbol is an Exchange Traded Fund (ETF) or not.  First I need to determine if the given ticker is even valid.  Second I need to determine if it is an ETF or a company stock.  So, I have some simple functions to request info from Yahoo! Finance (modified from ystockquote)

from urllib.request import Request, urlopen

def _yahoo_request(symbol, tag):
    """
    Retrieve stock data from Yahoo! Finance.

    Args:
        symbol (str): Stock ticker symbol for company of interest.
        tag (str): Yahoo! finance tag for a given property.

    Returns:
        str: The property requested.
    """
    url = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s' % (symbol, tag)
    request = Request(url)
    response = urlopen(request)
    content = response.read().decode().strip().strip('"')
    return content

So to determine if a stock is valid, I check to see if it's name exists in Yahoo! Finance.  Getting the name:

def get_name(symbol):
    """
    Retrieve company name for given ticker.

    Args:
        symbol (str): Ticker symbol for a given company's stock.

    Returns:
        str: The company name. Returns 'N/A' if ticker not in Yahoo! Finance.
    """
    return _yahoo_request(symbol, 'n')

and checking if it is a valid ticker:

def valid_ticker(ticker):
    """
    Check whether given ticker is a valid stock symbol.

    NOTE: Assumes that a stock is valid IF Yahoo! Finance returns a
    name for the given ticker.

    Args:
        ticker (str): Ticker symbol in question.

    Returns:
        bool: True if valid ticker (returned name != 'N/A'),
            otherwise False.
    """
    ticker = ticker.upper()
    return True if get_name(ticker) != 'N/A' else False

Finally, to determine if a given ticker is for an ETF or not, I will check the number of shares outstanding.

def get_shares_outstanding(symbol):
    """
    Retrieve number of shares outstanding for given stock ticker.

    Args:
        symbol (str): Ticker symbol for a given company's stock.

    Returns:
        str: The company name.
    """
    return _yahoo_request(symbol, 'j2')

This is not a valid data point for ETF's, so again, Yahoo! will return 'N/A'.  So, if the response can be cast as an integer, the ticker is not an ETF.

def is_etf(ticker):
    """
    Determine whether a given ticker symbol is for an Exchange
    Traded Fund (ETF).

    NOTE: Assumes that ticker is an ETF IF it is a valid ticker AND
    Yahoo! Finance does not return a numeric value for 'shares
    outstanding.'

    Args:
        ticker (str): Ticker symbol in question.

    Returns:
        bool: None if not a valid ticker, True if an etf (ticker is
        valid and returned shares outstanding cannot be converted to
        an int), otherwise False.
    """
    ticker = ticker.upper()
    if valid_ticker(ticker):
        try:
            int(get_shares_outstanding(ticker))
            return False
        except ValueError:
            return True
    else:
        return None

Code is working as expected. Does this seem a reasonable way to check this? In particular the last function.  Should I just use if get_shares_outstanding(ticker) == 'N/A': return True ?


texts:
I was asked to implement a hash map in this phone interview (screen-share), so time was limited and this is what I came up with. I'd appreciate if someone can take a minute to critique/review it and help me improve.

Here is an online version of the code.

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

const int SIZE = 10;

class Node{
public:
    Node(){}
    Node(int k, int v):key(k), value(v){}
    int key, value;
};

class HashMap {
private:
    list<Node*> data[SIZE];

public:
    ~HashMap();
    Node* get(int key);
    void put(int key, int value);

    int hashFn(int val){ return val % 13; }
};

Node* HashMap::get(int key){
    int hashValue = hashFn(key);
    int bucket = hashValue % SIZE;
    list<Node*>::iterator it = data[bucket].begin();

    while(it != data[bucket].end()){

        Node ** d = &(*it);
        if((*d)->key == key){
            return *d;
        }

        it++;
    }
    return NULL;
}

void HashMap::put(int key, int value){
    int hashValue = hashFn(key);
    int bucket = hashValue % SIZE;
    Node* node = this->get(key);
    if(node == NULL){
        data[bucket].push_front(new Node(key, value));
    }
    else{
        node->value = value;
    }
}

HashMap::~HashMap(){
    for(int i = 0; i < SIZE; ++i){
        list<Node*>& val = data[i];
        for(list<Node*>::iterator it = val.begin(); it != val.end(); it++){
            Node* n = *it;
            delete n;
        }
    }
}

int main(){
    HashMap map;
    cout << "Finding 5: " << map.get(5) << endl;  // -1
    map.put(5, 10);
    map.put(5, 11);
    cout << "Finding 5: " << map.get(5)->value;  // 11
    return 1;
}


texts: Sorting email address according to occurrences of each domain

texts:
My code:

import re
mbox = open('mailbox.txt')
ndict = {}
for line in mbox:
    domain = re.findall('From [^ ].*@([^ ]*)', line)
    if domain:
        if domain[0] in ndict:
            ndict[domain[0]] += 1
        else:
            ndict[domain[0]] = 1

print_list = [print(i) for i in sorted([(i, ndict[i]) for i in
          list(ndict.keys())], key=lambda x: x[1], reverse=True)]

I don't like how I create a dictionary and then immediately convert it into a list (which I'm doing in order to sort it), as it seems un-Pythonic to me. Is there a more Pythonic way to do this without using dictionaries?

i.e. Can you do this by making a list and appending tuples of the domains and number of occurrences?


texts:
This is a wrapper for an API. For now all it does is get a certain document or search for relevant documents from a document store -- although I plan to build out more features later. I'm new to PHP and want to both improve my PHP skills and develop "idiomatic" PHP style. It depends on HTTPFUL, which, for now, is being loaded from code that uses the class.

<?php

class PHPDocumentCloud
{
    // property declaration
    public $var = 'a default value';

    public function get($id){
        $url = "http://www.documentcloud.org/api/documents/" . $id . ".json";
        $answer = \Httpful\Request::get($url)->send()->raw_body;
        $answer = (json_decode($answer)->document);
        return $answer;
    }

    private function get_search_page($query, $page, $perpage){
        $url = "http://www.documentcloud.org/api/search.json?q=" . $query . '&page=' . $page . '&per_page=' . $perpage. '&mentions=3';
        $answer = \Httpful\Request::get($url)->send();
        $answer = (json_decode($answer));
        $docs = $answer->documents;
        return $docs;
    }

    public function search($query){
        //check for &page=2
        $page = 1;
        $arr = array();
        $document_list = array();
        $loop = True;
        while ($loop) {
            $results = $this->get_search_page($query, $page, 1000);
            if (!empty($results)){
                $document_list = array_merge($results, $document_list);
                $page++;
            }else{
                $loop = False;
            }
        }
        return $document_list;
    }

}

?>


texts:
This method finds the common ancestor of two nodes in a binary tree.

Any style suggestions or ways to make it more idiomatic? Is the algorithm correct? Rubocop says the cyclomatic complexity is too high, how would you break this up?

class Node
  def initialize(value = nil, left = nil, right = nil)
    @value = value
    @left = left
    @right = right
  end
end

def common_ancestor(node, value1, value2)
  return node unless node
  return node if node.value == value1 || node.value == value2
  anc_left = common_ancestor(node.left, value1, value2)
  anc_right = common_ancestor(node.right, value1, value2)
  return node if anc_left && anc_right
  anc_left || anc_right
end


texts: Copy and paste formatting is slow using VBA

texts:
The following code is a function that works. It's just slow and I don't know how to speed it up. It takes an Excel row number and the value of its headerval (string) and finds the same headerval on a different sheet then copies the formatting and applies it to our new sheet. The true false is because the source sheet has 2 different formatting options. It passes in the row to use either 23 or 24. ZROW is a public variable which is set with the ROW to start looking. srccolbyname function gets a col number from the source sheet which has the same headerval.

Function formatrow(roww As Long, header As Boolean)

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

Dim headerval As String
Dim sht As Worksheet
Set sht = ThisWorkbook.Sheets("DEALSHEET")
Dim sht2 As Worksheet
Set sht2 = ThisWorkbook.Sheets("Sheet1")
If header = True Then: srcrow = 23: Else: srcrow = 24
LastColumn = sht.Cells(ZROW + 1, sht.Columns.Count).End(xlToLeft).Column

For x = 2 To LastColumn
headerval = sht.Cells(ZROW + 1, x).Value
srccol = srccolbyname(headerval)
sht2.Cells(srcrow, srccol).Copy 'THIS IS SLOW
sht.Cells(roww, x).PasteSpecial Paste:=xlPasteFormats,    Operation:=xlNone, _
    SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Next x

Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

End Function

As requested here is the support function referenced above.

Public Function srccolbyname(strng_name As String) As Integer
Call findcol 'find ZROW
Dim x As Integer
Dim sht As Worksheet
Set sht = ThisWorkbook.Sheets("Sheet1")
LastColumn = sht.Cells(22, sht.Columns.Count).End(xlToLeft).Column
    For x = 2 To LastColumn
        chkval = sht.Cells(22, x).Value
            If Trim(UCase(chkval)) = Trim(UCase(strng_name)) Then
            srccolbyname = x
            Exit For
        Else
        srccolbyname = 2
        End If
    Next x
End Function


texts: Implementation of the binary search algorithm

texts:
This is my first implementation the binary search algorithm. I have tested it and so far it is okay. But I need an experienced eye to review the code and recommend best practices.

bool search(int value, int values[], int n) {
  bool x = false;
  int *max;
  int *min;
  int *mid;
  min = values;
  max = min + n - 1;
  mid = min + n / 2;
  while (true) {
    if ((value == *mid || value == *min || value == *max)) {
      x = true;
      break;
    } else if (max - min <= 1) {
      x = false;
      break;
    } else if (value < *mid) {
      n = n / 2;
      mid = min + n / 2;
      max = min + n - 1;
    } else if (value > *mid) {
      n = n / 2;
      mid = max - n / 2;
      min = max - n - 1;
    }
  }

  return x;
}


texts: Prevent Double Form Submit within X seconds

texts:
I want to prevent double form submissions within a small window, then allow the form to be submitted again.

I wrote this script after looking at several examples, but the global variable is bugging me. I'd welcome any suggestions on improving it.

var aLockedForms=   [];
jQuery.fn.preventDoubleSubmit=  function() {

    jQuery( this ).submit( function() {
        if ( this.beenSubmitted )
            return false;

        this.beenSubmitted= true;

        aLockedForms.push( this );

        setTimeout( function() {
                        var domTarget=  aLockedForms.shift();
                            domTarget.beenSubmitted=    false;

                    } ,
                    1984 );

    });

};

After the DOM is loaded, I run the following:

$( "form" ).preventDoubleSubmit();


texts:
I'm writing a class that will sort multiple types {arrays, arraylist, linkedlist} but I see there's a lot of code duplication. For instance, method to swap in list, and in arrays, method to sort list, and arrays etc. While I know code duplication is a bad practise, I am wondering if there's a better way to avoid writing duplicate code.

package utils;

import java.util.Arrays;
import java.util.List;

public class Sort {
    private static <E extends Comparable<E>> void swap(List<E> sequence,
                                                       int positionOne, int positionTwo) {
        E temp = sequence.get(positionOne);
        sequence.set(positionOne, sequence.get(positionTwo));
        sequence.set(positionTwo, temp);
    }

    private static <E extends Comparable<E>> void swap(E[] sequence,
                                                       int positionOne, int positionTwo) {
        E temp = sequence[positionOne];
        sequence[positionOne] = sequence[positionTwo];
        sequence[positionTwo] = temp;
    }

    public static <E extends Comparable<E>> List<E> selectionSort(List<E> sequence) {
        for (int i = 0; i < sequence.size(); i++) {
            int minPosition = -1;
            E minValue = sequence.get(i);
            for (int j = i + 1; j < sequence.size(); j++) {
                E secondPosition = sequence.get(j);
                if (minValue.compareTo(secondPosition) > 0) {
                    minPosition = j;
                    minValue = sequence.get(j);
                }
            }
            if (minPosition >= 0) {
                swap(sequence, i, minPosition);
            }
        }
        return sequence;
    }

    public static <E extends Comparable<E>> E[] selectionSort(E[] sequence) {
        for (int i = 0; i < sequence.length; i++) {
            int minPosition = -1;
            E minValue = sequence[i];
            for (int j = i + 1; j < sequence.length; j++) {
                E secondPosition = sequence[j];
                if (minValue.compareTo(secondPosition) > 0) {
                    minPosition = j;
                    minValue = sequence[j];
                }
            }
            if (minPosition >= 0) {
                swap(sequence, i, minPosition);
            }
        }
        return sequence;
    }

    public static void main(String[] args) {
        Integer[] integers = {1, 6, 88, 7, 44, 3, 11};
        System.out.println("Before: " + Arrays.toString(integers));
        Sort.selectionSort(integers);
        System.out.println("Later: " + Arrays.toString(integers));
    }
}


texts: Checking if a git repository needs to be updated

texts:
I made a small Vim distribution that uses vundle. I decided to make a small function that checks if the repository must be updated.

""""""""""""""""""""""""""""""""""""""""""""""""""
"Update the repository
""""""""""""""""""""""""""""""""""""""""""""""""""
"A function to update if necessary
function! Get_update()
    "Get the current path and change the directory to update the good
    "repository
    let l:current_path = expand("<sfile>:p:h")
    let l:path = '~/.vim-mahewin-repository'
    exec 'cd' l:path

    let l:last_local_commit = system('git rev-parse HEAD')
    let l:last_remote_comit = system('git ls-remote origin -h refs/heads/master |cut -f1')

    if l:last_local_commit != l:last_remote_comit
        echo  'Need to be updated, launches updated'
        :!git pull `git remote` `git rev-parse --abbrev-ref HEAD`
    endif

    exec 'cd' l:current_path
endfunction

It's not very nice, but I have not found out how to do it better. I'm open to advice.


texts:
The sole purpose of this post is to see how a production quality developer would approach this very simple problem. I am a fresh graduate and do not have a professional development experience. What are the cases and approaches that I should start considering when developing in a production environment? Please feel free to provide any suggestion.

public class RecursiveFinonacci {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(getFibonacci(10));
    }

    public static int getFibonacci(int n){
        if(n==0 || n ==1)
            return 1;
        else
            return getFibonacci(n-2) + getFibonacci(n-1);
    }
}


texts: Speed up a simple edge connecting algorithm

texts:
I have a list of edges and a similar list of links (linking edges) telling which edges to connect (how to order them). Connected edges form polygons and there can be many disconnected polygons (ordering of which doesn't matter). For example:

edges = [((2, 1), (3, 1)), ((4, 1), (6, 1)), ((6, 4), (4, 4)), ((3, 6), (2, 6))]
links = [((2, 6), (2, 1)), ((3, 1), (3, 6)), ((4, 4), (4, 1)), ((6, 1), (6, 4))]

We would connect the edge ((2, 1), (3, 1)) with the edge ((3, 6), (2, 6)) because the linking edge ((3, 1), (3, 6)) is in links, etc. The result would be ordering of edges as:

[((2, 1), (3, 1)), ((3, 6), (2, 6)), ((4, 1), (6, 1)), ((6, 4), (4, 4))]

where ((2, 1), (3, 1)), ((3, 6), (2, 6)) forms a polygon and ((4, 1), (6, 1)), ((6, 4), (4, 4)) another one.

So the idea is to check if (edge[i][1], edge[j][0]) is in links, for all i!=j. If true, then connect the edge[i] with edge[j] by putting the latter after the former, and repeat with (edge[j][1], edge[k][0]) etc.

I use the following function to do it:

def connect_edges(edges, links):
    edges = dict(edges)
    links = dict(links)
    seen = set()
    edges_connected = []
    for e in edges.items():
        while e not in seen:
            seen.add(e)
            edges_connected.append(e)
            e = (links[e[1]], edges[links[e[1]]])
    return edges_connected

It is quite fast, but for a very large number of edges (e.g. 1 million) it takes almost 20 seconds on my old laptop. Is there a way to speed it up? I think it is more or less optimal and maybe could be cynthonized for a gain in speed, but the problem is that it is very pythonic (having lists of tuples, dictionaries, sets) and I don't know if it will work (my knowledge of cython is very limited). Simply cythonizing without declaring types gives minuscule speed-up.


texts: Using a webservice with blocks and returning data via callback

texts:
I load some data from from my webservice via a method using blocks and callbacks.

From my ViewController I make a request to the data loading class and pass the callback block:

- (void)loadRadioStationList
{
    [self.radioDataLoader getRadioStationList:^(NSArray *data, NSDictionary *dictData){

        self.alphabetizedDictionary = [[NSDictionary alloc] initWithDictionary:dictData];
        self.sectionIndexTitles = [[NSArray alloc] initWithArray:data];

        [self.radioStationTableView reloadData];
    }];
}

Then in the dataloading class the method is as so:

-(void) getRadioStationList:(void (^)(NSArray *data, NSDictionary *dictData))callback
{

    NSString *string = RadioStationListURL;
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFXMLParserResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSXMLParser *XMLParser = (NSXMLParser *)responseObject;
        [XMLParser setShouldProcessNamespaces:YES];
        XMLParser.delegate = self;
        [XMLParser parse];

         callback((NSArray*)self.sectionIndexTitles, (NSDictionary*)self.alphabetizedDictionary);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Radio List"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];

    }];

    [operation start];

}

It loads the XML file and parses out the data and send the data back to my VC via the callback block.

I've a couple of questions:

Is this an acceptable way of doing this? Would you prefer to see it done another (better) way?
If I was to write an API, would passing the data from the API back to the calling class be a good way to work it, or is there a more suitable method for an API?


texts:
This snippets works, but I think it can be optimized:

/* highlight input, if it is empty */
$(function() {
    var highlight_if_no_val=function () {
        $(this).toggleClass('highlight-input', !$(this).val());
    }
    $('#id_index-EditForm-gpnr').keyup(highlight_if_no_val).each(highlight_if_no_val);
}
);

Is there a simpler solution?

The .each(hightlight_...) is done to set the highlight after the page loaded (it can be initially empty or initially filled).


texts: Indexing documents in Elastic Search using Refresh.True - Performance hit and how can it be improved?

texts:
I have an AWS Elastic Search server.
Using mapping template and an index strategy.

{
  "index_patterns": "users*",
  "order": 6,
  "version": 6,
  "aliases": {
    "users": {}
  },
  "settings": {
    "number_of_shards": 5
  },
  "mappings": {
    "_doc": {
      "dynamic": "strict",
      "properties": {
        "id": { "type": "keyword" },
        "emailAddress": { "type": "keyword" }
      }
    }
  }
}

Index strategy is {index_patterns}-{yyyy}-{MM}-{order}-{version}

Using NEST SDK to index document in a background application consuming SQS messages with the below method.

public async Task<Result> IndexAsync(
            T document,
            string indexName = null,
            string typeName = null,
            Refresh? refresh = null,
            CancellationToken cancellationToken = default)
        {
            var response = await Client.IndexAsync(
                                                document,
                                                i => i.Index(indexName ?? DocumentMappings.IndexStrategy)
                                                        .Type(typeName ?? DocumentMappings.TypeName)
                                                        .Id(document.Id)
                                                        .Refresh(refresh),
                                                cancellationToken);

            var errorMessage = response.LogResponseIfError(_logger);

            return errorMessage.IsNullOrEmpty() ? Result.Ok() : Result.Fail(errorMessage);
        }

This is a base method and is called like this.

var result = await _usersRepository.IndexAsync(userDocument, refresh: Refresh.True, cancellationToken: cancellationToken);

Here I am using Refresh.True because this is a user signup and I want the document to be available ASAP but noticed a performance hit, it takes a while for example to index 50,000 users in a load test.

Refresh.True refreshes all shards for this index, now I do this for each request of 50,000 calls and it seems like I get the hit.
Any input how can I improve this?


texts: Sort a linkedlist with 3 elements 0, 1 and 2

texts:
Given a linked list of 0s, 1s and 2s, sort it. Looking for code review, optimizations and best practices

public final class SortZeroesOnesTwos {

    private Node first;
    private Node last;
    private int size;

    public SortZeroesOnesTwos(List<Integer> items) {
        for (Integer item : items) {
            add(item);
        }
    }
    public void add(Integer item) {
        Node node = new Node(item);
        Node l = last;
        last = node;
        if (first == null) {
            first = node;
        } else {
            l.next = node;
        }
        size++;
    }

    private static class Node {
        private int item;
        private Node next;

        public Node(int item) {
            this.item = item;
        }
    }

    public void sortZeroesOnesAndTwos() {
        int[] a = new int[3];

        Node node = first;
        while (node != null) {
            a[node.item] = a[node.item] + 1;
            node = node.next;
        }

        node = first;
        int i = 0;
        while (node != null) {
            if (a[i] == 0) {
                i++;
            } else {
                node.item = i;
                node = node.next;
                a[i] = a[i] - 1;
            }
        }
    }

    public int[] toArray() {
        int[] result = new int[size];
        int i = 0;
        for (Node x = first; x != null; x = x.next)
            result[i++] = x.item;
        return result;
    }
 }

public class SortZerosOnesTwosTest {

    @Test
    public void test1() {
        SortZeroesOnesTwos sortList = new SortZeroesOnesTwos(Arrays.asList(0, 1, 2, 1, 2, 0));
        sortList.sortZeroesOnesAndTwos();
        int[] expected = {0, 0, 1, 1, 2, 2};
        assertTrue(Arrays.equals(expected, sortList.toArray()));
    }

    @Test
    public void test2() {
        SortZeroesOnesTwos sortList2 = new SortZeroesOnesTwos(Arrays.asList(1, 2, 1, 2));
        sortList2.sortZeroesOnesAndTwos();
        int[] expected2 = {1, 1, 2, 2};
        assertTrue(Arrays.equals(expected2, sortList2.toArray()));
    }

    @Test
    public void test3() {
        SortZeroesOnesTwos sortList3 = new SortZeroesOnesTwos(Arrays.asList(0, 2, 0, 2));
        sortList3.sortZeroesOnesAndTwos();
        int[] expected3 = {0, 0, 2, 2};
        assertTrue(Arrays.equals(expected3, sortList3.toArray()));
    }

    @Test
    public void test4() {
        SortZeroesOnesTwos sortList4 = new SortZeroesOnesTwos(Arrays.asList(0, 1, 0, 1));
        sortList4.sortZeroesOnesAndTwos();
        int[] expected4 = {0, 0, 1, 1};
        assertTrue(Arrays.equals(expected4, sortList4.toArray()));
    }
}


texts: Loading a file in vim via piped output of ag

texts:
I feel as if my scenario is fairly simple but that I might be overcomplicating it.

I am searching through files looking for a special condition, that is where the method .all with arguments exists.  In the real world that looks like:

ba_mbn_programs = Program.ba_and_managed_bar.all(:conditions => "user_programs.user_id = #{current_user.id} and brand_id = #{brand.id}", :order => :name, :joins => [:user_programs], :select => "distinct programs.*")

I'm able to find those using ag like this:

ag '\.all\(.*\)'

That gives me a big list of file names and line numbers (here's a snippet):

lib/ui_elements.rb
4:      self.active.all(:select => ["name, #{model}.id"], :order => :name).collect{|m| [m.name, m.id]}.insert(0, ["All", nil])

So in no particular order, I need to address these lines in my editor.  So what I really want to do is open up the file lib/ui_elements.rb in vim and go right to line 4.

I've learned that using vim +line_num file_name is a way to do that.  However just isolating the line number and file name from the ag output has forced me to do something like this:

vim `ag '\.where\(.*\)' app | tail -1 | sed -E 's/([^:]*):([0-9]*):.*/\1 \2/' | awk -v q="+" '{print q $2, $1}'`

So that just reads the last file from that search and opens the file in vim to that line number.  Surely there is a better way then this?


texts: Optimize Data Sending/Querying to Parse Swift iOS

texts:
I have a swift method that I'm using to update Parse in the backend when the button is tapped. Votes are being updated: The method acts as a voting system, incrementing a label every time it's tapped. This action is happening in a Custom Cell:

    @IBOutlet weak var votesLabel: UILabel!

    var parseObject:PFObject?
   @IBAction func happyBtn(sender: AnyObject) {

    if(parseObject != nil) {

        if var votes: Int? = parseObject!.objectForKey("votes") as? Int {

            votes!++
            parseObject!.setObject(votes!, forKey: "votes")
            parseObject!.saveInBackground()

          votesLabel?.text = "+\(votes!)"
            // print(votes)
        }

    }
}

Was wondering how I can optimize this function to send the data to and from Parse in the most efficient manner?

All help is appreciated!


texts:
While setting up my Jenkins instance with Ansible to connect to our local GitHub Enterprise instance, I need to recreate what the Github Branch Plugin does to scan an Organizations projects and pre-create the directory structure for all valid projects.  I have a solution using multiple levels of include_tasks which is shown below:

main.yml

---
# tasks file for create-organisation-repos
- name: get the all repositories for your organisation
  uri:
    url: "{{ organisation.repos_url }}"
    method: GET
    user: "{{ github.username }}"
    password: "{{ github.password }}"
    force_basic_auth: yes
    body_format: json
  register: organisation_repos

- debug: var=organisation_repos

- set_fact:
    repositories: "{{ organisation_repos.json }}"

- name: create each repository
  include_tasks: create-repo.yml
  loop: "{{ repositories }}"
  loop_control:
    loop_var: repository

- debug:
    msg: "{{ item.branches_url | regex_replace('\\{.*\\}', '') }}"
  loop: "{{ organisation_repos.json }}"

create-repo.yml

---

- name: "create folders for repo {{ repository.name }} with default branch {{ repository.default_branch }}"
  file:
    name: "{{ organisation_config_dir }}/{{ github.organisation }}/jobs/{{ repository.name }}"
    state: directory
    mode: 0755

- name: "create the repo {{ repository.name }}"
  template:
    src: "{{ item }}"
    dest: "{{ organisation_config_dir }}/{{ github.organisation }}/jobs/{{ repository.name }}/{{ item }}"
  loop: "{{ job_config_files }}"

- name: "get the branches for {{ repository.name }}"
  uri:
    url: "{{ repository.url }}/branches"
    method: GET
    user: "{{ github.username }}"
    password: "{{ github.password }}"
    force_basic_auth: yes
    body_format: json
  register: branches
  failed_when: false

- set_fact:
    branches="{{ branches.json }}"

- debug: var=branches

- name: Create branch job
  include_tasks: create-branch.yml
  loop: "{{ branches }}"
  loop_control:
    loop_var: branch

create-branch.yml

---

- set_fact:
    branch_name: "{{ branch.name | regex_replace('/','-') }}"

- name: "get branch_info for {{ branch.name }}"
  uri:
    url: "{{ repository.url }}/branches/{{ branch.name }}"
    method: GET
    user: "{{ github.username }}"
    password: "{{ github.password }}"
    force_basic_auth: yes
    body_format: json
  ignore_errors: true
  register: branch_info

- debug: var=branch_info

- name: "Does the Jenkinsfile exist for this branch"
  uri:
    url: "{{ repository.url }}/contents/{{ jenkinsfile_name }}?ref={{ branch.name }}"
    method: GET
    user: "{{ github.username }}"
    password: "{{ github.password }}"
    force_basic_auth: yes
  ignore_errors: true
  register: jenkinsfile
  when: branch_info is success

- debug: var=jenkinsfile

- name: "directory is present for {{ branch.name }}"
  file:
    name: "{{ organisation_config_dir }}/{{ github.organisation }}/jobs/{{ repository.name }}/branches/{{ branch_name }}"
    state: directory
    mode: 0755
  when: jenkinsfile is success

- name: copy configuration files for branch
  template:
    src: "branch/{{ item }}"
    dest: "{{ organisation_config_dir }}/{{ github.organisation }}/jobs/{{ repository.name }}/branches/{{ branch_name }}/{{ item }}"
  loop: "{{ branch_config_files }}"
  when: jenkinsfile is success

I'm sure there must be a better way to get a list of branches which contain a Jenkinsfile, but I cannot work out how to build the list and filter it.

There must be a simpler solution.  Anyone?


texts: Limit characters by line without splitting word

texts:
I got this question in an interview. Given a string of words, print it such as each line has at most limit characters, if a word does not fit on the line, print it on the next line and so on.
This is my implementation:
public static void main(String[] args) {
        String s = "Even aside from the rain and wind it hadn't been a happy practice session. Fred and George, who had been spying on the Slytherin team, had seen for themselves the speed of those new Nimbus Two Thousand and Ones. They reported that the Slytherin team was no more than seven greenish blurs, shooting through the air like missiles.";
        wordWrapper(s, 11);

    }

    public static void wordWrapper(String s, int limit) {
        // Time complexity: O(n) - n size of s
        // Space complexity: O(n) - n number of words in s
        int charCount = 0;
        int i = 0;
        String[] words = s.split(" ");
        while (i < words.length) {
            if (charCount + words[i].length() > limit) {
                System.out.println();
                charCount = 0;
            }
            charCount += words[i].length();
            System.out.print(words[i] + " ");
            i++;
        }
    }

I'm trying to reduce the space complexity, and just use pointers instead of split(), this is what I have so far, I'm thinking of keeping track of the last whitespace and going back to insert a line before that word when the limit is reached, if you run the code the new line is inserted correctly but half of the word would still print before the new line. Please let me know what I'm missing. I also would love to look at better approaches. Thank you!
public static void wordWrapper1(String s, int limit) {
    int i = 0;
    int lastWhitespaceIdx = -1;
    int lineCount = 0;
    if (s.length() == 0) {
        return;
    }
    while (i < s.length()) {
        if (Character.isWhitespace(s.charAt(i))) {
            lastWhitespaceIdx = i;
        }
        if (lineCount + 1 > limit) {
            if (!Character.isWhitespace(s.charAt(i + 1))) {
                i = lastWhitespaceIdx + 1;
                System.out.println();
                lineCount = 0;
                continue;
            } else {
                System.out.println();
                lineCount = 0;
            }
        }
        lineCount += 1;
        System.out.print(s.charAt(i));
        i++;
    }
}


texts: Merge sort algorithm implementation using C++

texts:
I'm trying to learn proper C++ and algorithms at the same time.

I particularly feel weird about my iterators usage in merge function. Is this a good way to handle it? I've modeled the signature after the STL std::merge method in <algorithm>.

I've tagged it as C++11 as well, because ideally I would've liked to make use of the new features like move semantics and rvalues, but it seems that I'm misunderstanding how they're supposed to work - no matter where I try to use them, my running time actually drops...

#include <vector>

typedef std::vector<int>::iterator vec_it;
void merge(vec_it left, vec_it left_end, vec_it right, vec_it right_end, vec_it numbers)
{
    while (left != left_end) {
        if (*left < *right || right == right_end) {
            *numbers = *left;
            ++left;
        } else {
            *numbers = *right;
            ++right;
        }

        ++numbers;
    }

    while (right != right_end) {
        *numbers = *right;
        ++right;
        ++numbers;
    }
}

void merge_sort(std::vector<int>& numbers)
{
    if (numbers.size() <= 1) {
        return;
    }

    std::vector<int>::size_type middle = numbers.size() / 2;
    std::vector<int> left(numbers.begin(), numbers.begin() + middle);
    std::vector<int> right(numbers.begin() + middle, numbers.end());

    merge_sort(left);
    merge_sort(right);

    merge(left.begin(), left.end(), right.begin(), right.end(), numbers.begin());
}