texts:
Visual Studio somehow optimizes the below code to be 20 times faster (release with optimization vs. release with no optimization). What could it be doing?

for (unsigned n = 1; n != units.size(); n++)
        for (unsigned j = 0; j != (units.size() - n); j++)
        {
            unsigned sizesMap[11] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

            for (auto it = units.begin() + n; it != (units.begin() + (n + j + 1)); it++)
            {
                for (unsigned k = 1; k != 11; k++)
                {
                    sizesMap[k] += (*it).sizes[k];

                }
            }
            //do something with sizesmap
        }

Unit class has a sizes array (10 members). The first two loops give all the possible sequences of "unit" in the vector. (1-2, 1-3, 1-100, 2-3, 2-4, 2-100, etc), which I then compare with one another using the sizesmap. I tried unrolling the inner loop and just adding sizesmap 10 times, that gave about 2% performance improvement. I compiled with Visual Studio 2013. Could it be vectorization (adds the (*it).sizes to sizesmap in one go)? Or are the loops ineffective somehow?


texts: Compare two columns in an Excel spreadsheet

texts:
I have a VBA code that compares values in two columns (Column A & B), which runs slow. Please advise me the changes to make it run fast

The below code works just fine, but is running slow. Please advise me on how to make it run fast

 Sub compare()
       Dim ListA As Range
       Dim ListB As Range
       Dim c As Range
       Call Unprotect
       Set ListA = Range("A2:A1048576")
       Set ListB = Range("B2:B1048576")

       Application.ScreenUpdating = False

       Range("C1").Value = "Files in A that are NOT in B"
       Range("D1").Value = "Files in B that are Not in A"
       Range("E1").Value = "Matching Files"

       For Each c In ListA
       If Application.CountIf(ListB, c) = 0 Then
       Cells(Cells(Rows.Count, "C").End(xlUp).Row + 1, "C").Value = c
       End If
       Next c

       For Each c In ListA
       If Application.CountIf(ListB, c) >= 1 Then
       Cells(Cells(Rows.Count, "E").End(xlUp).Row + 1, "E").Value = c
       End If
       Next c

       For Each c In ListB
       If Application.CountIf(ListA, c) = 0 Then
       Cells(Cells(Rows.Count, "D").End(xlUp).Row + 1, "D").Value = c
       End If
       Next c

     Application.ScreenUpdating = True

     Call Protect
     End Sub

Any code changes to make the code run fast will be appreciated. Thanks


texts:
I am a Spanish programming teacher in a vocational training course and I want my students to make a CRUD exercise on arrays.
I want them to start using OOP as well and as an example, I'm going to give them this example of OO Console Menu. We haven't seen Java 8 so far.
Any comments or improvements would be very appreciate.

MenuOption.java

package es.primerok.menu;

/**
* Created by Miguel-David Orrico on 18/02/2017.
*/
public abstract class MenuOption {
private String option;
private String menuLine;

public MenuOption(String option, String menuLine) {
    this.option = option;
    this.menuLine = menuLine;
}

@Override
public String toString() {
    return this.option+" - "+this.menuLine;
}

public String getOption() {
    return option;
}

public abstract void doAction();

}

Menu.java

package es.primerok.menu;

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

/**
 * Created by Miguel-David Orrico on 18/02/2017.
 */
public class Menu {
private static final String OPTION_EXIT="0";
private static final String LEVEL_INDENTATION ="    ";
private List<MenuOption> menuOptions=new ArrayList<>();
private int level=0;

public Menu(){}

public Menu(int level){
    this.level=level;
}

public void add(MenuOption m){
    this.menuOptions.add(m);
}

public void loopUntilExit(){

    String input;
    try(Scanner sc=new Scanner(System.in)) {
        while (true) {
            System.out.println(this);
            input = sc.nextLine();
            if (input.equals(OPTION_EXIT)) {
                return;
            }
            boolean foundOption = false;
            for (MenuOption m : menuOptions) {
                if (m.getOption().equalsIgnoreCase(input)) {
                    m.doAction();
                    foundOption = true;
                }
            }
            if (!foundOption) {
                System.out.println("Sorry, unrecognized option");
            }
        }
    }
}

@Override
public String toString(){
    StringBuilder sb = new StringBuilder();
    sb.append("Choose an option, "+OPTION_EXIT+" to exit.\n");
    for(MenuOption m:menuOptions){
        for(int i=0;i<level;i++){
            sb.append(LEVEL_INDENTATION);
        }
        sb.append(m).append("\n");
    }
    return sb.toString();
}
}

MenuTest.java

package es.primerok.menu;

/**
 * Created by Miguel-David Orrico on 18/02/2017.
 */
public class MenuTest {
public static void main(String[] args){

    System.out.println("es.primerok.menu.Menu Test");
    Menu mainMenu=new Menu();
    Menu subMenu=new Menu(1);

    subMenu.add(new MenuOption("+","Add numbers") {
        @Override
        public void doAction() {
            System.out.println("5+7=12");
        }
    });

    subMenu.add(new MenuOption("-","Subtract some numbers") {
        @Override
        public void doAction() {

            System.out.println("we're subtracting 6 and 5. The result is 1");
        }
    });
    mainMenu.add(new MenuOption("1","Option number 1") {
        @Override
        public void doAction() {
            System.out.println("This is number one");
        }
    });
    mainMenu.add(new MenuOption("A","Print an A") {
        @Override
        public void doAction() {
            System.out.println("I'm in Option A");
        }
    });
    mainMenu.add(new MenuOption("sub","This has a submenu") {
        @Override
        public void doAction() {
            subMenu.loopUntilExit();
        }
    });

    mainMenu.loopUntilExit();
}
}


texts:
Inspired by this question, I decided to implement a Disjoint-set data structure in Python 3. I mainly followed this description for understanding the algorithm (but did not do the optimizations for path compression, union by rank etc. -- so mine is a "naive" implementation).
Here is the Wikipedia article for reference.

In short, the data structure can hold n disjoint sets, and do two operations on them:

merge any two sets into a single one
for any element, tell to which set it belongs

My implementation is as follows:

#!/usr/bin/python

class Disjoint:

    def __init__(self):
        self.sets = []

    def createSet(self, repr):
        self.sets.append([repr])

    def mergeSets(self, repr1, repr2):
        set1 = self.findSet(repr1);
        set2 = self.findSet(repr2);
        if set1 != set2:
            set1.extend(set2);
            self.sets.remove(set2);

    def findSet(self, repr1):
        for oneSet in self.sets:
            if repr1 in oneSet:
                return oneSet

    def getSets(self):
        return self.sets;

The test class:

import unittest
import disjoint

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        pass;

    def test_empty(self):
        dis = disjoint.Disjoint();
        self.assertEqual([], dis.getSets())
        self.assertEqual(None, dis.findSet(1))

    def test_init(self):
        dis = disjoint.Disjoint();
        for i in range(1, 6):
            dis.createSet(i);
        for i in range(1, 6):
            found = dis.findSet(i);
            self.assertEqual(1, len(found))
            self.assertEqual(i, found[0])
        expected = [[i] for i in range(1, 6)]
        self.assertEqual(expected, dis.getSets())

    def test_simple(self):
        dis = disjoint.Disjoint();
        for i in range(1, 6):
            dis.createSet(i);
        pairs = [[1, 2], [2, 4], [4, 5]]
        for p in pairs:
            p1 = p[0];
            p2 = p[1];

            if dis.findSet(p1) != dis.findSet(p2):
                dis.mergeSets(p1, p2);

        expetctedSets = [[1, 2, 4, 5], [3]];
        self.assertEqual(expetctedSets, dis.getSets())

if __name__ == '__main__':
    unittest.main()

Any suggestion for improvement is welcome, but in particular, I'm interested in the following:

Do you see any problem in the (naive) implementation of the algorithm?
Can the code be improved in any way to have similar functionality, but either be more elegant or more efficient in Python? (I'm thinking of things like using list comprehensions instead of for-itertions, etc.)
Is there any other test case that would be worth adding?

N.B.: For now, I'm not interested in how to implement the optimizations suggested in the linked source (that will be the next step, also using any new unit tests suggested here).


texts: JavaScript string manipulation with certain logic in it

texts:
How would I make this code look less ugly?

// we are looping over an array of images
// width is a parameter passed to the current function
//
// the resulting string looks like this: "30px 0"
// (it's a tool that returns coordinates for a CSS sprite)
// when iterating over the first item, we don't need
// to add "-" and "px" to X coordinate
result.push(
    ( i === 0 ? "0" : "-" + i * ( ( is2PixelRatio ? width / 2 : width ) + 10 ) + "px" ) + " 0"
);


texts: Calculating the sum of the digits in 2^1000

texts:
I have a program which calculates the sum of the digits in the number 21000. The program is not beautiful and I was hoping for some advice on how to improve it.

The idea I have used is to create an array with the first element equal to 20. The first element in the array represent 100 the second 101 and so on.
Then go through and double every element in the array. After every element is doubled I check if an element in the array is greater than 9, if it is I subtract 10 and add a 1 to the next element in the array. For example if the element at place 40 is equal to 13 and element at place 41 is equal to 3 then I will change the element at place 40 to 3 and element at place 41 to 4.

#include <stdio.h>
int main(void){
 int sum = 0;
 int dec[320] = {1, };
 int i,j,p,q;
 for(i = 1; i < 1001; i++){

   for (j = 0; j < 302; j++) {
     dec[j] = 2*dec[j];
     }

     for(q = 0; q < 302; q++){
       if(dec[q] > 9){
         dec[q] = dec[q] % 10;
         dec[q+1] = dec[q+1] + 1;
     }
   }

 }

 for(p = 0; p < 302; p++){
   sum += dec[p];
 }
 printf("sum = %d sista %d \n", sum, dec[301]);
}


texts:
I'm  learning data structures. I'm working on linked lists at the moment, and I'd like to have a strong grasp on them. Below is the last problem I solved. I'd like to know what you think of the solution and what can be done better.

The problem consists of reversing a linked list from position m to position n.
1 ≤ m ≤ n ≤ length of list. If we have a list 1->2->3->4->5->NULL, m = 2 and n = 4, the function should return 1->4->3->2->5->NULL.

   /**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
    if (head == NULL || head->next == NULL || m - n == 0)
    {
        return head;
    }
    struct ListNode* prev = NULL, *cur = head;
    struct ListNode* before_m_node, *m_node, *after_n_node;
    int count = 0;

    // find m node, after loop cur points to m node, prev gets node befor or  NULL if there is none
    while (count != m)
    {
        ++count;
        if (count == m)
        {
            break;
        }
        prev = cur, cur = cur->next;
    }
    m_node = cur;
    before_m_node = prev;
    prev = cur, cur = cur->next;

    // now we look for n node, cur is currently pointing to node after m, prev points to node before
    // we will reverse links as we go and after loop cur will point to n node
    while (count != n)
    {
        ++count;
        if (count == n)
        {
            break;
        }
        struct ListNode* temp = cur->next;
        cur->next = prev;
        prev = cur, cur = temp;
    }

    after_n_node = cur->next;

    // if first node is not head of the list
    if (before_m_node != NULL)
    {
        cur->next = prev;
        m_node->next = after_n_node;
        before_m_node->next = cur;
        return head;
    }
    else
    {
        cur->next = prev;
        m_node->next = after_n_node;
        return cur;
    }
}


texts:
I wrote a BFS implementation that walks a tile-based field. It takes a function that should return true for walkable tiles and false for walls. It also takes the start and end points. It currently takes about 5 seconds to find the shortest path from (0, 0) to (1000, 1000) which isn't bad, but it really isn't great.

import qualified Data.HashSet as H
import Data.Maybe (mapMaybe, isNothing)
import Data.List (foldl')

bfs ::
    (Int -> Int -> Bool) -> -- The field function. Returns True if tile is empty, False if it's a wall
    (Int, Int) -> -- Starting position
    (Int, Int) -> -- Final position
    Int -- Minimal steps
bfs field start end = minSteps H.empty [start] 0
    where
        minSteps visited queue steps
            |end `elem` queue = steps + 1
            |otherwise = minSteps newVisited newQueue (steps + 1)
            where
                (newVisited, newQueue) = foldl' aggr (visited, []) queue
                aggr (vis, q) node = if H.member node vis
                    then (H.insert node vis, neighbors node ++ q)
                    else (vis, q)
                neighbors (nx, ny) = filter (uncurry field) $ map (\(x, y) -> (nx + x, ny + y)) [(1, 0), (0, -1), (-1, 0), (0, 1)]

hugeField x y = x >= 0 && x <= 1000 && y >= 0 && y <= 1000

main = print $ bfs hugeField (0, 0) (1000, 1000)


texts:
The basic idea is this:

There are two buttons: a DoWork button and a Cancel button.

The DoWork button should launch a thread to do some work, unless that thread was already launched and not canceled.

The Cancel button should cancel the worker thread, if it's running.

Please ignore the fact that it calls Thread.Abort() for the moment, that is a separate issue that I will address later.

Also, how does one generally show the correctness of one's own multithreaded code?  It seems much more difficult to debug.

Here's the code:

    private Thread m_WorkingThread;
    private bool m_finishedWorking;

    public Form()
    {
        InitializeComponent(); // initialize all the form controls.
        m_WorkingThread = null;
        m_finishedWorking = false;
    }

    private void bDoWork_Click(object sender, EventArgs e)
    {
        if (m_WorkingThread != null)
            if(m_WorkingThread.IsAlive  || m_finishedWorking)
                return;

        ThreadStart ts = new ThreadStart(DoWork);
        Thread t = new Thread(ts);
        t.Start();
        m_WorkingThread = t;

    }
    private void bCancel_Click(object sender, EventArgs e)
    {
        AbortThread(m_WorkingThread);
        m_finishedWorking = false;
    }
    private void AbortThread(Thread t)
    {
        if (t != null)
            if (t.IsAlive)
                t.Abort();
    }
    private void DoWork()
    {
        // do some work here, maybe using Invokes / BeginInvokes to update any controls.

        m_finishedWorking = true;
    }


texts:
My code makes the four tests pass, but I'm worried I'm missing something. Is the code too simple and not encompassing enough? I'm just beginning to learn so any feedback is welcome!

Here's the Rspec followed by my code; notice there's no 1-100 requirement like on some other FizzBuzz challenges:

describe "fizzbuzz" do
  it 'returns "Fizz" when the number is divisible by 3' do
fizz_3 = fizzbuzz(3)

expect(fizz_3).to eq("Fizz")
  end
  it 'returns "Buzz" when the number is divisible by 5' do
fizz_5 = fizzbuzz(5)

expect(fizz_5).to eq("Buzz")
  end
 it 'returns "FizzBuzz" when the number is divisible by 3 and 5' do
fizz_15 = fizzbuzz(15)

expect(fizz_15).to eq("FizzBuzz")
  end
  it 'returns nil when the number is not divisible by 3 or 5' do
fizz_4 = fizzbuzz(4)

    expect(fizz_4).to eq(nil)
  end
end

def fizzbuzz(int)
  if int % 3 == 0 && int % 5 == 0
   return "FizzBuzz"
  end

  if int % 5 == 0
   return "Buzz"
  end

  if int % 3 == 0
   return "Fizz"
  end

end


texts: Serializing object graph to proprietary binary file

texts:
I'm creating a class library to read/write .3di files which are binary files describing 3D models for a video game. This review is for the write/serialization process.

I've mapped the different structures in the .3di file (header, textures, vertices, etc.) to the classes shown below. Each class implements the IBinarySerializable interface and is thus responsible for its own serialization logic. I've omitted many parts of the 3D model here for brevity, but they follow the same pattern.

Clients would use the library by building out a Model object and then calling SaveToFile().

interface IBinarySerializable
{
    byte[] Serialize();
}

public class Model
{
    public ModelHeader Header { get; set; }
    public List<Texture> Textures { get; set; }
    public List<Vertex> Vertices { get; set; }

    public void SaveToFile(string filePath)
    {
        using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
        using (BinaryWriter writer = new BinaryWriter(fileStream))
        {
            writer.Write(Header.Serialize());
            writer.Write(Textures.SelectMany(texture => texture.Serialize()).ToArray());
            writer.Write(Vertices.SelectMany(vertex => vertex.Serialize()).ToArray());
        }
    }
}

public class ModelHeader : IBinarySerializable
{
    public string Name { get; set; }
    public int TextureCount { get; set; }

    public byte[] Serialize()
    {
        using (var buffer = new MemoryStream())
        using (var writer = new BinaryWriter(buffer))
        {
            // Hardcoded values.
            writer.Write(Encoding.ASCII.GetBytes("3DI"));
            writer.Write((byte)8);

            // Header data.
            writer.Write(Encoding.ASCII.GetBytes(Name.PadRight(8, '\0')));
            writer.Write(TextureCount);

            return buffer.ToArray();
        }
    }
}

public class Texture : IBinarySerializable
{
    public string Name { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }

    public byte[] Serialize()
    {
        using (var buffer = new MemoryStream())
        using (var writer = new BinaryWriter(buffer))
        {
            writer.Write(Encoding.ASCII.GetBytes(Name.PadRight(28, '\0')));
            writer.Write(Width);
            writer.Write(Height);

            return buffer.ToArray();
        }
    }
}

public class Vertex : IBinarySerializable
{
    public short X { get; set; }
    public short Y { get; set; }
    public short Z { get; set; }

    public byte[] Serialize()
    {
        using (var buffer = new MemoryStream())
        using (var writer = new BinaryWriter(buffer))
        {
            writer.Write(X);
            writer.Write(Y);
            writer.Write(Z);

            return buffer.ToArray();
        }
    }
}

My Concerns

Since the .3di file schema is proprietary, I don't believe I can use the binary serialization that comes with .NET (e.g., BinaryFormatter) since it adds .NET-specific data to the file. Is that correct?
Should each class be responsible for its own serialization logic? I've considered centralizing all of that logic to a dedicated class, e.g., ModelSerializer, ModelFileWriter, etc. One benefit of that approach is that I wouldn't have to map the file structures to classes so literally.
I repeat this in each Serialize() method:

using (var buffer = new MemoryStream())
using (var writer = new BinaryWriter(buffer))

Should I extract those lines to a helper function and just pass in what I want to do with the writer, e.g., BinaryUtils.Serialize(Action<BinaryWriter> writeAction)?


texts:
I have already addressed this issue and corrected something .really..now the graph looks different
Please tell me if the program works correctly?You can see the results in the picture above.I will be grateful if you find any mistakes (if there are any, of course..)
/I'm just not sure if the average number of swaps and comps is calculated correctly.I thought that with this sort there should be fewer of them, but the data obtained from the classic Insertion sort is not much different.Maybe that's how it should be, which is why I'm asking./
Thank you all in advance
 #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>

    int main(int argc, char *argv[]) {

        FILE *f=fopen("stat18.csv","w");
        int n=100;
        int i,s;
        while (n<=10000){
        int st=0;
        for (s=0;s<5;s++)
        {
            int *a;
            a=(int *)malloc(n*sizeof(int));
            srand(time(NULL));
            int k;
            for (k=0;k<n;k++)
            {
                *(a+k)=rand()%50;
            }
            int j,comps,swaps;
            swaps=0;
            comps=0;
        int rem = a[0];
        a[0] = -1;

        for( i = 2, j; i < n; i++)
        {
            int x = a[i];
            j = i;
            while(j > 1 && a[j-1] > x)
            {
                comps += 2;
                swaps++;
                a[j] = a[j-1];
                j--;
            }
            comps += 2;
            a[j] = x;
        }
        a[0] = rem;
        for(i = 0; i < n-1; i++)
        {
            if(a[i] > a[i+1])
            {
                comps++;
                swaps++;
                int temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
            }
            comps++;
            i++;
        }
        st+=swaps + comps;
        free(a);
    }

        st=st/5;
        fprintf(f,"%d ; %d\n", n , st);
        if (n<1000){
            n+=100;}
        else {n+=1000;}
        }
        fclose(f);
        return 0;
    }


texts:
I am a new programmer and I sill don't know how to write a clean code.
please suggest me ways to improve my skill and how to write a proper code.

import pygame
import time
import random

pygame.init()

# defines the width and height of the display
display_width = 800
display_height = 600

white = (255, 255, 255)
d_white = (250, 250, 250)
black = (0, 0, 0)
teal = (0, 128, 128)
blue_black = (50, 50, 50)
game_display = pygame.display.set_mode((display_width, display_height))

factor = 10

food_x = random.randrange(5, display_width - 5)
food_y = random.randrange(5, display_height - 5)
print(food_x, food_y)
score = 60
clock = pygame.time.Clock()

class snake_body:
    x = 0
    y = 0

    def __init__(self, x_position, y_position):
        self.x = x_position
        self.y = y_position

snake = [snake_body(20, 20), snake_body(20, 30), snake_body(20, 40), snake_body(20, 50), snake_body(20, 60),
         snake_body(20, 70), snake_body(20, 80), snake_body(20, 90), snake_body(20, 100), snake_body(20, 110),
         snake_body(20, 120), snake_body(20, 130), snake_body(20, 140), snake_body(20, 150), snake_body(20, 160),
         snake_body(20, 170)]

# class food():
#     x=0
#     y=0
#
#     def __init__(self):

def update_snake(score):
    i = len(snake) - 1

    while i > 0:
        snake[i].x = snake[i - 1].x
        snake[i].y = snake[i - 1].y
        i -= 1

def check_death():
    if snake[0].x < 1 or snake[0].x > display_width or snake[0].y < 1 or snake[0].y > display_height:
        pygame.quit()
        quit()
    for i in range(1, len(snake)):
        if snake[0].x == snake[i].x and snake[0].y == snake[i].y:
            pygame.quit()
            quit()

def drawsnake(snake):
    for i in range(len(snake)):
        pygame.draw.rect(game_display, teal, (snake[i].x, snake[i].y, factor, factor))

x = 0
y = 0
x_change = 0
y_change = 0
first_time = True
eat = True
while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:
            first_time = False
            if event.key == pygame.K_a:
                if x_change is not 10:
                    x_change = -10
                    y_change = 0
            elif event.key == pygame.K_d:
                if x_change != -10:
                    x_change = 10
                    y_change = 0
            elif event.key == pygame.K_w:
                if y_change is not 10:
                    x_change = 0
                    y_change = -10
            elif event.key == pygame.K_s:
                if y_change != -10:
                    x_change = 0
                    y_change = 10
            elif event.key == pygame.K_c:
                x_change = 0
                y_change = 0

    if not first_time:
        update_snake(score)
    if score % 10 == 0 and eat:
        snake.append(snake_body(snake[len(snake)-1].x, snake[len(snake)-1].y))
        print(len(snake))
        eat = False

    snake[0].x += x_change
    snake[0].y += y_change
    if snake[0].x < food_x+10 and snake[0].x > food_x-10 and snake[0].y < food_y+10 and snake[0].y >food_y-10:
        score = score + 10
        food_x = random.randrange(5, display_width - 5)
        food_y = random.randrange(5, display_height - 5)
        eat = True

    check_death()
    game_display.fill(white)

    pygame.draw.rect(game_display, black, (food_x, food_y, factor, factor))
    drawsnake(snake)

    pygame.display.update()
    time.sleep(0.035)
    clock.tick(60)


texts: C++-safe way to use using inside headers

texts:
I have this C++ 14 code in a project of mine.

Enhedron/Util/Enum.h:

#ifndef ENHEDRON_UTIL_ENUM_H_
#define ENHEDRON_UTIL_ENUM_H_

#include <stdexcept>
#include <type_traits>

namespace Enhedron { namespace Util { namespace Impl { namespace Enum {
    using std::runtime_error;
    using std::underlying_type_t;

    /**
     * Convert a value to an enum safely. The enum must have "LAST_ENUM_VALUE" as the last
     * enumerated value, and must be a simple enum starting at 0 and being densely populated. For example:
     *
     *      enum class MyEnum {
     *          VALUE_0,
     *          VALUE_1,
     *          LAST_ENUM_VALUE = VALUE_1
     *      };
     */
    template<typename Enum, typename Value>
    Enum toEnum(Value value) {
        if (value >= 0 && value <= static_cast<underlying_type_t<Enum>>(Enum::LAST_ENUM_VALUE)) {
            return static_cast<Enum>(value);
        }

        throw runtime_error("Value out of range for enum");
    }

    /**
     * Tag a type with an enumerated value to create a distinct type. Useful to differentiate values of the same type.
     * For example, to stop first and last names being interchangeable in the type system:
     *      enum class Name {
     *          FIRST,
     *          LAST
     *      };
     *
     *      using FirstName = TaggedValue<Name, Name::FIRST, string>;
     *      using LastName = TaggedValue<Name, Name::LAST, string>;
     */
    template<typename Enum, Enum tag, typename Value>
    class TaggedValue final {
        Value value;
    public:
        TaggedValue(Value value) : value(move(value)) { }

        Value& operator*() { return value; }
        const Value& operator*() const { return value; }

        Value* operator->() { return &value; }
        const Value* operator->() const { return &value; }
    };
}}}}

namespace Enhedron { namespace Util {
    using Impl::Enum::toEnum;
    using Impl::Enum::TaggedValue;
}}

#endif /* ENHEDRON_UTIL_ENUM_H_ */

Some specific things I'm unsure of:

Is there a better way to define TaggedValue so that you don't have to mention the enum type and the enum value you want to use? i.e. getting the template argument Enum inferred from the type of tag.
I'm using a namespace scheme where every header file has a namespace Enhedron::Module::Impl::FileName which is by convention private to that file. Then at the end of the file, it will export those names into the module namespace Enhedron::Module. My concern is that use of using inside the "private" namespace. Any thoughts on whether this would cause problems?


texts: Shifting an 128-bit integer consisting of four 32-bit integers

texts:
For a little project of mine I have written two versions for shifting a 128-bit unsigned integer consisting of four 32-bit unsigned integers in x86 assembly. I cannot really decide which is better in performance, style, etc..

UPDATE:
I have written another two different functions. The first one doesn't need any conditional jumps, so there is no problem with branch mispredictions. However, it needs 40 bytes (on a 32-bit platform) to store the jump-tables that I have created in static memory.
The second one uses conditional jumps, but in a better way than before, I think.
Both functions doesn't really care about shift-values >=128/=0.

UPDATE 2:
Because I was unsatisfied with the size of the jump-table (especially on a 64-bit platform) I rewrote the first function as a compromise between conditional jumps and jump-table size.

       .data
   JTABLE:
       .long L0,L1,L2,L3
       .text
       .global _shl_128
       .intel_syntax
   _shl_128:
       push ebx
       push esi
       mov edx, [esp+12]            //pointer to array of integers
       mov ecx, [esp+16]            //value of bits to shift
       mov esi, ecx
       shr esi, 5
       mov esi, [JTABLE+esi*4]
       mov eax, [edx]
       mov ebx, [edx+4]
       and ecx, 31
       jmp esi
   L0:
       mov esi, [edx+8]
       shld [edx+12], esi, cl
       shld esi, ebx, cl
       shld ebx, eax, cl
       shl eax, cl
       mov [edx], eax
       mov [edx+4], ebx
       mov [edx+8], esi
       jmp L4
   L1:
       mov esi, [edx+8]
       je L5
       shld esi, ebx, cl
       shld ebx, eax, cl
       shl eax
   L5:
       mov [edx+4], eax
       mov [edx+8], ebx
       mov [edx+12], esi
       jmp L7
   L2:
       je L6
       shld ebx, eax, cl
       shl eax
   L6:
       mov [edx+8], eax
       mov [edx+12], ebx
       jmp L8
   L3:
       shl eax, cl
       mov [edx+12], eax
       mov dword ptr [edx+8], 0
   L8:
       mov dword ptr [edx+4], 0
   L7:
       mov dword ptr [edx], 0
   L4:
       pop esi
       pop ebx
       ret

Function:

    .text
    .global _shl_128
    .intel_syntax
_shl_128:
    push ebx
    push esi
    mov edx, [esp+12]            //pointer to array of integers
    mov ecx, [esp+16]            //value of bits to shift
    mov esi, ecx
    and ecx, 31
    cmp esi, 96
    mov eax, [edx]
    jae L1
    cmp esi, 64
    mov ebx, [edx+4]
    jae L2
    cmp esi, 32
    mov esi, [edx+8]
    jae L3
    shld [edx+12], esi, cl
    shld esi, ebx, cl
    shld ebx, eax, cl
    shl eax, cl
    mov [edx], eax
    mov [edx+4], ebx
    mov [edx+8], esi
    jmp L4
L3:
    je L5
    shld esi, ebx, cl
    shld ebx, eax, cl
    shl eax
L5:
    mov [edx+4], eax
    mov [edx+8], ebx
    mov [edx+12], esi
    jmp L6
L2:
    je L7
    shld ebx, eax, cl
    shl eax
L7:
    mov [edx+8], eax
    mov [edx+12], ebx
    jmp L8
L1:
    je L9
    shl eax, cl
L9:
    mov [edx+8], eax
    mov dword ptr [edx+8], 0
L8:
    mov dword ptr [edx+4], 0
L6:
    mov dword ptr [edx], 0
L4:
    pop esi
    pop ebx
    ret


texts:
I am getting a date range from form inputs - the "from" month, day, and year, and the "to" month, day, and year, and then running a report on data for within that date range. I want to first check that the dates are valid and if not display an error indicating dates are not valid, then run the report only if valid. I want to

make sure the dates themselves are valid, i.e., no blank inputs, and nothing like February 30th, then
make sure the "from" date is before the "to" date.

I am having trouble doing this in a clean way with repeating myself a bunch. Here's the long way. Please help refactor with assigning to variables but only if valid.

unless Date.valid_date?(params[:from][:year].to_i,
                        params[:from][:month].to_i,
                        params[:from][:day].to_i) &&
  Date.valid_date?(params[:to][:year].to_i,
                   params[:to][:month].to_i,
                   params[:to][:day].to_i)
  redirect_to :back, alert: "Please provide valid date values." and return
end
unless Date.new(params[:from][:year].to_i,
                params[:from][:month].to_i,
                params[:from][:day].to_i) <
  Date.new(params[:to][:year].to_i,
           params[:to][:month].to_i,
           params[:to][:day].to_i)
  redirect_to :back, alert: "Please provide valid date values." and return
end
from_date = Date.new(params[:from][:year].to_i,
                     params[:from][:month].to_i,
                     params[:from][:day].to_i)
to_date = Date.new(params[:to][:year].to_i,
                   params[:to][:month].to_i,
                   params[:to][:day].to_i)
run_report(from_date, to_date)


texts: Java function to rotate an image by 180 degrees

texts:
I want to 180 rotate an Image. Here's what I wrote but it seems way too complicated. Is there any way to do this in a simpler way?

public void rotateImage180Deg() {
        for (int x = 0; x < width / 2; x++) {

            int y = width - 1 - x;
            for (int i = x; i < y; i++) {
                int offset = i - x;
                RGBColor top = imageMatrix[x][i];
                imageMatrix[x][i] = imageMatrix[y][y - offset];
                imageMatrix[y][y - offset] = top;
                RGBColor leftBottom = imageMatrix[y - offset][x];
                imageMatrix[y - offset][x] = imageMatrix[i][y];
                imageMatrix[i][y] = leftBottom;
            }
        }
    }


texts:
I am developing a website and I want to use PDO and MVC.

Before, I was coding in procedural MySQL, but I'm starting to understand the object-oriented programming.

My problem is the following:

If I understand the MVC pattern, there are 3 parts

View (It's my Html)
Model (PHP requests)
Controller (Control and form validation)

Right?

I want to know if I have the right approach to MVC.

So, I put code that works and I try to change in MVC. (My test MVC is lower in the page.)

$db = new DbConnect();
$error = '';
if(isset($_POST['login_submit'])){
   if(empty($_POST['login']) || empty($_POST['password'])){
       $error = 'All fields required';
   }else{
       $db->query('SELECT * FROM users WHERE u_login = :login AND u_password = :password');
       $db->bind(':login', $_POST['login']);
       $db->bind(':password', md5(sha1($_POST['password'])));
       $row = $db->single();
       if($db->rowCount() > 0){
           echo 'I can save some informations by sessions';
           echo '
';
           print_r($row);
           echo '
';
       }else{
           $error .= 'Not find in the Data Base';
       }
   }
}
if(!empty($error)){
    echo $error;
}

Here the html form:

<form action="login" method="post" name="login">
Login:
    <input type="text" name="login" id="login">

Mot de passe:
    <input type="password" name="password" id="password">

<input type="submit" name="login_submit" value="Se connecter">

Now I try to evolve towards the MVC model like this:

1. My Model called model.login.php:

class Auth extends DbConnect{
    protected $login;
    protected $password;
    protected $email;

    public function ConnectSecure(){
        if(isset($_POST['login_submit'])){
            CheckPostLogin();
            $this->query('SELECT * FROM users WHERE u_login = :login AND u_password = :password');
            $this->bind(':login', $_POST['login']);
            $this->bind(':password', md5(sha1($_POST['password'])));
            $this->single();
            if($this->rowCount() > 0){
                echo 'OK and I put some informations by sessions';
            }else{
                echo 'No in DB or error combination user/password';
            }
            echo '
';
            print_r($result);
            echo '
';
        }
    }
}

2. My controller called controller.login.php:

require 'models/model.login.php';
function CheckPostLogin(){
    if(empty($_POST['login']) || empty($_POST['password'])){
        Message::ShowError('All fields required.');
        return false;
    }
}

3. My view has the same HTML code listed above.

I have also a global class that will handle static functions to display messages for error, success, etc. like this (just an example):

class Message{
    public static function ShowError($message){
        echo $message;
    }
}

I have another problem:

Inside my model, after the query, I check if I have some result. I think this part need go on the controller. Right? If yes, how can I do this properly?

I'm new to OOP. If you see any errors or discrepancies, your advice is welcome.


texts:
I still consider myself a newbie to functional programming, and I still have some trouble wrapping my head around a lot of functional concepts. Anyway, here goes:

import Control.Monad.Writer
import Data.Monoid

bubblesort' :: (Ord a) => [a] -> Writer All [a]
bubblesort' (x:y:xs)
  | x > y = tell (All False) >>
    (y:) <$> bubblesort' (x:xs)
  | otherwise =
    (x:) <$> bubblesort' (y:xs)
bubblesort' xs = return xs

bubblesort :: (Ord a) => [a] -> [a]
bubblesort xs
  | ok = ys
  | otherwise = bubblesort ys
  where (ys, All ok) = runWriter (bubblesort' xs)


texts: Web crawler that charts stock ticker data using matplotlib

texts:
I've built a web crawler using the BeautifulSoup library that pulls stock ticker data from CSV files on Yahoo finance, and charts the data using matplotlib.  I'm wondering if there are any ways to improve the code I've written, because there are some parts that I think could be a lot better.

import urllib.request
from matplotlib import pyplot as plt
from bs4 import BeautifulSoup
import requests

def chartStocks(*tickers):

    # Run loop for each ticker passed in as an argument
    for ticker in tickers:

        # Convert URL into text for parsing
        url = "http://finance.yahoo.com/q/hp?s=" + str(ticker) + "+Historical+Prices"
        sourceCode = requests.get(url)
        plainText = sourceCode.text
        soup = BeautifulSoup(plainText, "html.parser")

        # Find all links on the page
        for link in soup.findAll('a'):
            href = link.get('href')
            link = []
            for c in href[:48]:
                link.append(c)
            link = ''.join(link)

            # Find the URL for the stock ticker CSV file and convert the data to text
            if link == "http://real-chart.finance.yahoo.com/table.csv?s=":
                csv_url = href
                res = urllib.request.urlopen(csv_url)
                csv = res.read()
                csv_str = str(csv)

                # Parse the CSV to create a list of data points
                point = []
                points = []
                curDay = 0
                day = []
                commas = 0
                lines = csv_str.split("\\n")
                lineOne = True
                for line in lines:
                    commas = 0
                    if lineOne == True:
                        lineOne = False
                    else:
                        for c in line:
                            if c == ",":
                                commas += 1
                            if commas == 4:
                                point.append(c)
                            elif commas == 5:
                                for x in point:
                                    if x == ",":
                                        point.remove(x)
                                point = ''.join(point)
                                point = float(point)
                                points.append(point)
                                day.append(curDay)
                                curDay += 1
                                point = []
                                commas = 0
                points = list(reversed(points))

                # Plot the data
                plt.plot(day,points)
                plt.ylabel(ticker)
                plt.show()


texts:
I am a beginner and I have made Colorful Lights using check-boxes in HTML. I'm pretty sure it will look horrible to any developer out there, but hey, that's why I've posted it.

I'd like a general review of this. I'm especially concerned about the quality and enhancements of this form.

<title>
Javascript
</title>


texts: Loop + Take for repeatedly taking elements from the same collection

texts:
I sometimes need to enumerate the same collection multiple times so I wrote an extension that does this for me. I call it Loop. It takes one optional parameter startAt which allows it to start at an offset.

The extension works with enumerators. If it could not MoveNext then it gets a new enumerator and tries again. If the second try failed then the collection is empty, otherwise it starts from the beginning. It uses a local function that handles the enumerator by resetting it if necessary.

public static IEnumerable<T> Loop<T>(this IEnumerable<T> values, int startAt = 0)
{
    if (values == null)
    {
        throw new ArgumentNullException(nameof(values));
    }

    var moves = 0;

    // ReSharper disable once PossibleMultipleEnumeration
    var enumerator = values.GetEnumerator();

    try
    {
        while (true)
        {
            if (TryMoveNext(enumerator, out enumerator))
            {
                moves++;

                if (startAt > 0 && moves <= startAt)
                {
                    continue;
                }

                yield return enumerator.Current;
            }
            else
            {
                yield break;
            }
        }
    }
    finally
    {
        enumerator.Dispose();
    }

    bool TryMoveNext(IEnumerator<T> currentEnumerator, out IEnumerator<T> newEnumerator)
    {
        if (currentEnumerator.MoveNext())
        {
            newEnumerator = currentEnumerator;
            return true;
        }
        else
        {
            // Get a new enumerator because we took all elements and try again.

            currentEnumerator.Dispose();

            // ReSharper disable once PossibleMultipleEnumeration
            newEnumerator = values.GetEnumerator();

            // If we couldn't move after reset then we're done trying because the collection is empty.
            return newEnumerator.MoveNext();
        }
    }
}

I have the feeling like I might have overcomplicated the implementation.

Here are the tests I wrote for it:

[TestClass]
public class enumerableTest
{
    [TestMethod]
    public void Loop_EmptyCollection_NoneTakes()
    {
        var numbers = new int[0];
        Assert.IsFalse(numbers.Loop().Take(2).Any());
    }

    [TestMethod]
    public void Loop_LessThanAvailable_NoLoop()
    {
        var numbers = new[] { 1, 2, 3 };
        Assert.That.Collection().AreEqual(new[] { 1, 2 }, numbers.Loop().Take(2));
    }

    [TestMethod]
    public void Loop_MoreThanAvailable_OneLoop()
    {
        var numbers = new[] { 1, 2, 3 };
        Assert.That.Collection().AreEqual(new[] { 1, 2, 3, 1 }, numbers.Loop().Take(4));
    }

    [TestMethod]
    public void Loop_TwiceTheAvailable_TwoLoops()
    {
        var numbers = new[] { 1, 2, 3 };
        Assert.That.Collection().AreEqual(new[] { 1, 2, 3, 1, 2, 3, 1, 2 }, numbers.Loop().Take(8));
    }

    [TestMethod]
    public void Loop_MoreThanAvailableWithStartAt_OneLoop()
    {
        var numbers = new[] { 1, 2, 3 };
        Assert.That.Collection().AreEqual(new[] { 2, 3, 1, 2, 3, 1 }, numbers.Loop(1).Take(6));
    }

}


texts: Running a block of code on every interval except the first iteration

texts:
I am working with an encryption algorithm that looks like this

The key is a number stored in 4 bytes.
For each byte in the message, XOR it with the corresponding byte in the key
When you reach the end of the key, multiply the key by 13, and then continue looping

Translated, it looks like this

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

   // Increase the key as per the algorithm
   if (i > 0 && (i % 4 == 0)) {
      key *= 13
   }

   // Shift over i bytes, as per the algorithm
   data[i] ^= key >> (8 * (i % 4));
}

What I don't like is that check for i > 0, as it looks like wasteful processing. How can I modify this code so that I don't have that extra check that is basically redundant after the first iteration of the loop?

If the size of the data is 5 MB I don't want to run an extra 5 million or so i > 0 checks when i is always increasing.


texts:
I am a beginner in Python-3. I was solving a level 2 challenge in Google Foobar. Given an initial amount of items (LAMBs) I have to distribute it among individuals, who are ranked according to seniority, while adhering to the following rules:

The junior most individual gets 1 Lamb
An immediately senior individual can't get more than twice their juniors lambs, otherwise the junior will rebel
A senior individual can't get less lambs than the sum of their 2 previous juniors, otherwise the senior will rebel
In case lambs are leftover and adding a senior does not violate any previous rules, they must be added.

The goal is to find the difference between how many individuals can be paid if we pay the minimum amount to each (stingy) and the maximum amount to each (generous). I noticed that stingy condition resembles a Fibonacci sequence and the generous condition is sum of powers of 2. My code is as follows:
from math import log2

def solution(total_lambs)
    return (stingy(total_lambs) - generous(total_lambs))

def stingy(total_lambs)
    if (total_lambs == 1): # from condition 1 at least 1 individual gets paid
        return 1
    elif (total_lambs == 2): # from condition 2 and 4 the most each can is 1
        return 2
    else:
        ind, total, x0, x1 = 2, 2, 1, 1 # no. individuals, sum of Fib seq, intial Fib nos.
        while (total <= total_lambs):
            x0, x1 = x1, x0 + x1 # advancing the Fib seq
            total = total + x1 # total is the sum of lambs paid
            if (total > total_lambs):
                return ind
            else:
                ind = ind + 1

def generous(total_lambs):
    if (total_lambs == 1):
        return 1
    if (total_lambs == 2):
        return 2
    else:
        ind = int(log2(capital + 1)) # typecasting to int removes decimals
        if (total_lambs - 2**n + 1 >= 2**(n - 1) + 2**(n - 2)): # condition 2, 3 and 4
            return ind + 1
        else:
            return ind

Please suggest improvements wherever possible.


texts: Replacing all the 'u' with specific character that is given by the user

texts:
I got this question for a Junior Software Developer interview. And came up with this solution in Java:

public class Main {

  public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    if (!in.hasNextLine()) {
      System.out.println("error");
    }

    String str = in.nextLine();

    char ch = in.next().charAt(0);

    replaceChar(str, ch);
  }

  private static void replaceChar(String str, char ch) {

    String newStr = "";
    for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) == 'u') {

        newStr = str.replace(str.charAt(i), ch);
      } else {
        System.out.println("there is no \'u\'");
      }
    }

    System.out.println(newStr);
  }
}

The interviewer said this question can be tricky and didn't say anything after my question. What do you think?

After the interview I realized that I messed up with this part:

System.out.println("there is no \'u\'");

I thought this is going to be useful if there is no 'u' in the string but instead it's printed after every character thats no 'u'


texts:
An error in a live environment was detected when trying to convert string geo coordinates into a double.

The current culture (hu-HU) uses comma instead of point for the decimals and that produced an exception when trying to parse Double.Parse(47,545874)
That's why I'm using CultureInfo.InvariantCulture and the reason to wrap the conversion up in a try/catch statement.

Is there a better way to handle these exceptions?

public void UpdateJobGeoCoordinates(Job job)
{
    var address = _kernel.GetKernel();

    var gpsCoordinate = _locator.GetGpsCoordinates(address);

    try
    {
        job.Lat = Double.Parse(gpsCoordinate.Item1, CultureInfo.InvariantCulture);
        job.Lng = Double.Parse(gpsCoordinate.Item2, CultureInfo.InvariantCulture);
    }
    catch (FormatException)
    {
        ResetCoordinates(job);
        Logger.Warn("Geo location issue for Job [{0}] , Format error when convert '{1}', '{2}' to a Double.", job.ERPServiceOrderId, gpsCoordinate.Item1, gpsCoordinate.Item2);
    }
    catch (OverflowException)
    {
        ResetCoordinates(job);
        Logger.Warn("Geo location issue for Job [{0}] , Overflow when convert '{1}', '{2}' to a Double.", job.ERPServiceOrderId, gpsCoordinate.Item1, gpsCoordinate.Item2);
    }
    catch (Exception ex)
    {
        ResetCoordinates(job);
        Logger.Warn("Geo location issue for Job [{0}] , Exception message: {1}", job.ERPServiceOrderId, ex.Message);
    }
}


texts:
I have translated the following F# code to C# and would appreciate constructive criticism. This code computes the symbolic derivative of the expression f(x)=x³-x-1:

type Expr =
  | Int of int
  | Var of string
  | Add of Expr * Expr
  | Mul of Expr * Expr

let rec d f x =
  match f with
  | Var y when x=y -> Int 1
  | Int _ | Var _ -> Int 0
  | Add(f, g) -> Add(d f x, d g x)
  | Mul(f, g) -> Add(Mul(f, d g x), Mul(g, d f x))

let f =
  let x = Var "x"
  Add(Add(Mul(x, Mul(x, x)), Mul(Int -1, x)), Int -1)

d f "x"

My translation from F# to C# fragments the d function into member functions in classes that implement an Expr interface and adds a hand-written structural pretty printers:

using System;

public interface Expr
{
    Expr d(string x);
}

public class Int : Expr
{
    int n;

    public Int(int m)
    {
        n = m;
    }

    public int Value
    {
        get { return n; }
    }

    public Expr d(string x)
    {
        return new Int(0);
    }

    public override string ToString()
    {
        return "Int " + n.ToString();
    }
}

public class Var : Expr
{
    string x;

    public Var(string y)
    {
        x = y;
    }

    public string Value
    {
        get { return x; }
    }

    public Expr d(string y)
    {
        return (x == y ? new Int(1) : new Int(0));
    }

    public override string ToString()
    {
        return "Var \"" + x + "\"";
    }
}

public class Add : Expr
{
    Expr f, g;

    public Add(Expr a, Expr b)
    {
        f = a;
        g = b;
    }

    public Tuple<Expr, Expr> Value
    {
        get { return Tuple.Create(f, g); }
    }

    public Expr d(string y)
    {
        return new Add(f.d(y), g.d(y));
    }

    public override string ToString()
    {
        return "Add(" + f.ToString() + ", " + g.ToString() + ")";
    }
}

class Mul : Expr
{
    Expr f, g;

    public Mul(Expr a, Expr b)
    {
        f = a;
        g = b;
    }

    public Tuple<Expr, Expr> Value
    {
        get { return Tuple.Create(f, g); }
    }

    public Expr d(string y)
    {
        return new Add(new Mul(f, g.d(y)), new Mul(g, f.d(y)));
    }

    public override string ToString()
    {
        return "Mul(" + f.ToString() + ", " + g.ToString() + ")";
    }
}

class SymbolicDerivative
{
    static void Main(string[] args)
    {
        var x = new Var("x");
        var f = new Add(new Add(new Mul(x, new Mul(x, x)),
                                new Mul(new Int(-1), x)),
                        new Int(-1));
        Console.WriteLine("{0}", f.d("x").ToString());
    }
}

I have also written the derivative function externally to the class hierarchy using the is operator to inspect the type of a given value but I chose this code because I believe it is more idiomatic OOP style.


texts:
Refactor this code so that I don't have to insert the parameters any time I need to use one of the functions.

I have a class, say julian, for calculating Julian dates of today, a date I insert and the difference between these two Julian dates.

        int julian::calc_julianToday()
        {
            time_t t = time(0);
            struct tm *now = localtime( &t );
                todDay = now->tm_mday;
                todMonth = now->tm_mon+1;
                todYear = now->tm_year+1900;

              int at = (14 - todMonth) / 12;
              int yt = todYear + 4800 - at;
              int mt = todMonth + 12 * at - 3;
              if (todYear > 1582 || (todYear == 1582 && todMonth > 10) ||
    (todYear == 1582 && todMonth == 10 && todDay >= 15))
                return julToday =  todDay + (153 * mt + 2) / 5 + 365 * yt
    + yt / 4 - yt / 100 + yt / 400 - 32045;
              else
                return julToday = todDay + (153 * mt + 2) / 5 + 365 * yt + yt / 4 - 32083;

        }
        int julian::calc_juliandate(int day, int month, int year)
        {

              int a = (14 - month) / 12;
              int y = year + 4800 - a;
              int m = month + 12 * a - 3;
              if (year > 1582 || (year == 1582 && month > 10) ||
(year == 1582 && month == 10 && day >= 15))
                return julStart = day + (153 * m + 2) / 5
    + 365 * y + y / 4 - y / 100 + y / 400 - 32045;
              else
                return julStart = day + (153 * m + 2) / 5 + 365 * y + y / 4 - 32083;

        }

        int julian::dates_diff(int day, int month, int year)
        {
            int start = calcJulStartDate(day, month, year);
            int today = calcJulTodayDate();
            differ = today-start;
            return differ;
        }

Please note that all the variable types are declared in a header file. What I would like to do in main() is to be able to use calc_juliandate() without having to call it and pass its attributes each and every time I need it in another function, as in dates_diff().
Any suggestions about coding style or implementing this?


texts:
I started to learn programming in Go and came up with a Breakable Toy, which is a CLI for Gitlab. To get something up and running fast, I used some Go libraries:

Ginkgo for testing
Cobra for basic CLI stuff
Sling for HTTP requests and JSON mapping

The project can be found in this repository on Github.

I am looking for any feedback / code review that could help me to better understand the concepts and conventions of Go. I come from the Java world and have the impression that I try to stick too much on the object oriented world. So any feedback concerning code style and best-practices is highly appreciated.

Besides general feedback, here are some specific questions:

1. Error Handling in Go

Being used to the try catch mechanism in Java, the _, err := mechanism in Go seems a little unhandy to me. To me it looks as if I have to implement the "bubble up" of exceptions all by myself. Example:

// HTTP client
func (client *GitlabClient) Do(req *http.Request, value interface{}) (*http.Response, error) {
    resp, err := client.sling.Do(req, value, nil)
    return resp, err
}

// service
func (service *ProjectsService) List() (*[]model.Project, error) {
    // ...
    _, err = service.Client.Do(req, projects)
    if err != nil {
        return nil, err
    }
    return projects, nil
}

// CLI command
func(cmd *cobra.Command, args []string) error {
    projects, err := gitlabClient.Projects.List()
    if err != nil {
        return err
    }
    err = OutputJson(projects)
    return err
}

so there are really many LOCs only for error handling - is that the "way to go"?

2. Global Variables

The Cobra library seems to store values for CLI flags in global variables:

var id string

// ...

projectGetCmd.PersistentFlags().StringVarP(&id, "id", "i", "", "(required) Either ID of project or 'namespace/project-name'")
viper.BindPFlag("id", projectGetCmd.PersistentFlags().Lookup("id"))

This makes it really hard to figure out which flags belong to which command and it's easy to re-initialize the same variable. See group.go, line 31 for the full example.

Is there any rule of thumb / best practice of how to namespace variables in Go besides structs?

3. Mocking in Unit Tests

I wrote some integration tests with Ginkgo that also simulate an HTTP server. This works quite nicely. But now I wanted to test, whether my CLI commands are calling the expected service methods and therefore I wanted to mock the services classes in the Unit tests for the commands. I couldn't find a convincing way for how to mock objects in Go. Can you give me any hint / resources for that?

Disclaimer

I am not expecting a full code review of my application. But if you have any suggestions for improvement, I'd be glad the get them.


texts:
I use bluebird promises. I want to promisify my requests from communication layer:

Utils.js

//Question: is there more beautiful way to do that?
promisifyXMLHttpRequest(xhr, timeout = 0, timeoutCallback = _.noop, responseHandler = response => JSON.parse(response).data) {
    const requestPromise = new Promise((resolve, reject) => {
        xhr.onload = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(responseHandler(xhr.responseText));
                } else {
                    reject(xhr.statusText);
                }
            }
        };
        xhr.onerror = function (e) {
            reject(xhr.statusText);
        };
    });

    if (timeout) {
        requestPromise.timeout(timeout)
            .catch(TimeoutError, error => {
                timeoutCallback(error);
            });
    }

    return requestPromise;
}

Communication

_sendRequest(body, sessionId, timeout, timeoutCallback, responseHandler) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', SOME_URL, true);
    if (sessionId) xhr.setRequestHeader('swarm-session', sessionId);
    const requestPromise = Utils.promisifyXMLHttpRequest(xhr, timeout, timeoutCallback, responseHandler);
    xhr.send(JSON.stringify(body));
    return requestPromise;
}


texts: Allowing developers to quickly create image hover effects

texts:
I've created a simple jQuery plugin to allow developers to quickly create image hover effects with very simple markup. I also created an option to automatically create the mouseover or mouseout versions of the image via TimThumb.

Here is a link. for more information and a demo.

(function($){
$.fn.hovr = function(options) {

    // Default Options
    var defaults = {
        speed:           'normal',
        animateOver:     {'opacity': '0'},
        animateOut:      {'opacity': '1'},
        timThumb:        false,
        timThumbInverse: false,
        timThumbPath:    'images/img.php',
        timThumbParams:  'f=2'
        //http://www.binarymoon.co.uk/2012/02/complete-timthumb-parameters-guide/
    };
    var options = $.extend({}, defaults, options);

    // Create Images
    if (options.timThumb) {
        this.each(function() {
            var strOrig = $(this).prop('src');
            var strNew  = options.timThumbPath +
                '?src=' + strOrig +
                '&w=' + $(this).prop('width') +
                '&h=' + $(this).prop('height') +
                '&' + options.timThumbParams;

            if (options.timThumbInverse) {
                $(this)
                    .prop('src', strOrig)
                    .attr('data-hovr', strNew);
            }
            else {
                $(this)
                    .prop('src', strNew)
                    .attr('data-hovr', strOrig);
            }
        });
    }

    // Create Rollovers
    return this.each(function() {
        $(this).hover(
            function() {
                $(this).stop().animate(options.animateOver, options.speed);
            },
            function() {
                $(this).stop().animate(options.animateOut, options.speed);
            }
        ).each(function() {
            var intWidth  = ($(this).attr('width'))  ? $(this).attr('width')  : $(this).prop('width');
            var intHeight = ($(this).attr('height')) ? $(this).attr('height') : $(this).prop('height');
            var strAlign  = ($(this).attr('align'))  ? $(this).attr('align')  : '';
            var strClass  = ($(this).attr('class'))  ? $(this).attr('class')  : '';
            var strStyle  = ($(this).attr('style'))  ? $(this).attr('style')  : '';

            $(this).wrap('

');

            $(this).before($(this).clone(true))
                .attr('style', 'position:absolute; left:auto; top:auto;')
                .prop('src', $(this).attr('data-hovr'))
                .removeAttr('data-hovr')
                .removeAttr('class');

            $(this).prev('img')
                .attr('style', 'position:absolute; left:auto; top:auto; z-index:10;')
                .removeAttr('data-hovr')
                .removeAttr('class');
        });
    });

};
})(jQuery);


texts: Signature verifier for a javascript/node.js function

texts:
I wrote a function that verifies the arguments against an expected set of arguments.

test('hello', 'world');

function test() {
    verifySignature(arguments, String, [Number], String)
    // returns true
}

function test() {
    verifySignature(arguments, String, Number)
    // returns false
}

test('hello', 'world');
function test() {
  alert(verifySignature(arguments, String, Number));
}

function verifySignature() {
    var args = arguments[0];
    var expectations = Array.prototype.slice.call(arguments, 1);
    for (var i = 0; i < expectations.length; i++) {
        // Going through each expectation
        if (expectations[i] instanceof Array) {
            console.log('Comparing [', args[i], '] with [', Object.prototype.toString.call(new expectations[i][0]));
            // optional expectation
            if (Object.prototype.toString.call(args[i]) == Object.prototype.toString.call(new expectations[i][0])) {
                // good
            } else {
                // or maybe the next one will be good
                expectations.shift();
                i--;
            }
        } else {
            console.log('Comparing [', args[i], '] with [', Object.prototype.toString.call(new expectations[i]));
            // required! expectation
            if (Object.prototype.toString.call(args[i]) == Object.prototype.toString.call(new expectations[i])) {
                // good
            } else {
                // error!
                return false;
            }
        }
    };
    return true;
}

I was actually looking for a library that already does this, if I missed one, please point me to it.

I initially thought something like this would be a big project in itself. So I'm not really confident and fully expect to improve a lot on it as I use it more and more. Please review and suggest corrections and improvements.


texts:
I have inherited a function which calculates a first payment due after a certain age.
Using the function I typically pass in database values to custom calculate certain dates:

    Dim result = FPDA("#1/12/1952#", "9/29/1948", 1, 55)
    MsgBox(result) 'in this example, I am returning first payment due after age 55

As far as the parameters, EffDate is the date the account became active, DOB is date of birth, mode is a payment mode value and age is the attained age to check. The function looks like this:

Public Function FPDA(ByVal EffDate As Date, ByVal DOB As Date, ByVal Mode As Integer, ByVal Age As Integer) As Date
    'FUNCTION TO CALCULATE THE FIRST PAYMENT DUE AFTER SPECIFIED AGE.

    Select Case Mode
        Case "1"
            Do Until EffDate > DateAdd("yyyy", Age, [DOB])
                EffDate = DateAdd("yyyy", 1, EffDate)
            Loop

        Case "2"
            Do Until EffDate > DateAdd("yyyy", Age, [DOB])
                EffDate = DateAdd("m", 6, EffDate)
            Loop

        Case "4"
            Do Until EffDate > DateAdd("yyyy", Age, [DOB])
                EffDate = DateAdd("q", 1, EffDate)
            Loop

        Case "12"
            Do Until EffDate > DateAdd("yyyy", Age, [DOB])
                EffDate = DateAdd("m", 1, EffDate)
            Loop

    End Select

    Return EffDate

End Function

Is there a better or more efficient way than to achieve this?


texts: Converting a graph to a directed graph with order of the nodes defined by post-order traversal

texts:
Background:
I'm implementing an algorithm from the paper Polygon Area Decomposition for Multiple-Robot Workspace Division and one of the steps is to represent a polygon as a graph. This is done by splitting a polygon to convex parts that will become the nodes of the graph, and the edges of the graph will represent those parts that touch each other:

What I'm required to do by the algorithm is:

to have the nodes of the graph ordered as in post-order traversal;
to be able to get for a given node all the nodes that go before it in the ordering and that are accessible from the given node without entering the nodes that go after in the ordering (NetworkX calls these nodes ancestors);
to keep information about the touching sides of the polygon parts in some manner so that I wouldn't have to recalculate them again every time.

To convert a polygon to a graph was fairly simple. The problems arise when I want to satisfy the given requirements. I wrote the following function that would convert a simple graph to a directed graph with the necessary ordering and which would allow me to easily get ancestors of any given node.
Code:
import networkx as nx

def to_ordered(graph: nx.Graph) -> nx.Graph:
    """
    Makes a directed graph out of the input graph.
    Nodes will be ordered in a depth-first-search post-ordering.
    :param graph: graph representing convex parts of a polygon
    :return: directed graph with touching sides as edges' attributes
    """
    ordered_graph = nx.DiGraph()
    ordered_nodes = list(nx.dfs_postorder_nodes(graph))
    ordered_graph.add_nodes_from(ordered_nodes)
    directed_edges = (sorted(edge, key=ordered_nodes.index)
                      for edge in graph.edges)
    ordered_graph.add_edges_from(directed_edges)
    for *edge, side in graph.edges.data('side'):
        if edge in ordered_graph.edges:
            ordered_graph.edges[edge]['side'] = side
        else:
            ordered_graph.edges[edge[::-1]]['side'] = side
    return ordered_graph

Usage example:
import networkx as nx

# Creating an example input graph:
edges = [(5, 4), (5, 1), (3, 5), (2, 3), (6, 2), (1, 6)]
sides = list(map(str, edges))  # example data to keep as attributes
graph = nx.Graph()
for edge, side in zip(edges, sides):
    graph.add_edge(*edge, side=side)
nx.draw(graph, with_labels=True)

# converting to a directed graph with desired characteristics
ordered_graph = to_ordered(graph)
nx.draw(ordered_graph, with_labels=True)

# new graph is ordered according to the post-order graph traversal:
print(ordered_graph.nodes)
# [4, 3, 2, 6, 1, 5]

# finding nodes' ancestors:
for node in ordered_graph.nodes:
    print(node, nx.ancestors(ordered_graph, node))
# 4 set()
# 3 set()
# 2 {3}
# 6 {2, 3}
# 1 {2, 3, 6}
# 5 {1, 2, 3, 4, 6}

# accessing edges' attributes:
for edge in ordered_graph.edges:
    print(edge, ordered_graph.edges[edge])
# (4, 5) {'side': '(5, 4)'}
# (3, 5) {'side': '(3, 5)'}
# (3, 2) {'side': '(2, 3)'}
# (2, 6) {'side': '(6, 2)'}
# (6, 1) {'side': '(1, 6)'}
# (1, 5) {'side': '(5, 1)'}

What I want reviewed:
As you can see from the given example the code works correctly, but I find my code too complicated for such a simple task. I especially dislike the part with copying the attributes from one graph to another. Most probably I simply miss some NetworkX functionality that would help me write it much more concisely. Any comments on this or any other matter are welcome.


texts: Simpler method to find users in child categories

texts:
I am using the ancestry gem to organize my post categories tree.
I have 8 parent categories, and they all have many child categories.
To retrieve an array of child categories, I use:

parent_category.children

I defined these relations in my category model:

  has_ancestry
  has_many :posts
  has_many :users, through: :posts

The last relation allows me to find the users who post in each category.

What I am trying to do: on first login, users have to choose their categories of interest. On the next screen, they are suggested users who post in the categories they chose.

To find the suggested users, I wrote a method:

def recommendations
    @users = []
    (current_user.get_voted Category).each do |category|
      category.children.each do |cat|
        @users << cat.users
      end
    end
    @users = @users.flatten.uniq
 end

This works, but it seems overly complicated. Is there any way to do this in a "best practice" way ?


texts: Displaying data from from many-to-many table

texts:
The goal is to display all posts with their categories underneath them.  The code below accomplishes this, however I'm thinking it's bad and was hoping someone could review and offer some feedback.

Because each post can have many categories and because each category can belong to many posts, I used a many-to-many table.

I have three tables:

table 1: Posts
columns: | id | post_name | post_text |
table 2: categories
columns: | id | category_name |
table 3: cats_to_posts
columns: | cats_id | post_id |

index.php:

$posts = Posts::read_all();

foreach ( $posts as $post )
{
    echo $post->post_name ."
";
    echo $post->post_text ."
";

    $categories_array = Posts::get_cats_by_post_id($post->id);

    foreach ($categories_array as $category)
    {
        echo "&bull;". $category->category_name ."
";
    }
}

Posts class:

public static function get_cats_by_post_id($id)
{
    $db = new Database();

    $sql = "SELECT  cats_to_posts.cats_id
            FROM    cats_to_posts
            WHERE   cats_to_posts.post_id = {$id}";

    $result = $db->exe_query($sql);

    $cat_id_array = array(); // stores array of category ids that match post ids

    while ( $record = $result->fetch_object() )
    {
        $cat_id_array[] = $record;
    }

    $cat_name_array = array(); // stores array of category names that match category ids
    foreach($cat_id_array as $cat_id)
    {
        $new_sql = "SELECT  category_name
                    FROM    categories
                    WHERE   id = ". $cat_id->cats_id;

        $new_result = $db->exe_query($new_sql);

        while ( $new_record = $new_result->fetch_object() )
        {
            $cat_name_array[] = $new_record;
        }

    }

    return $cat_name_array;
}

My main curiosity is on the get_cats_by_post_id() method inside the Posts class. Is there is a better way to get all category names based on the post_id than using two SQL commands like I am doing?


texts:
I worked on a script that takes as input a multi-sequence .fasta file and outputs the number of each aminoacid/sequence in a .tsv format.
This is how a .fasta file looks:
>sp|P21515|ACPH_ECOLI Acyl carrier protein phosphodiesterase OS=Escherichia coli (strain K12) OX=83333 GN=acpH PE=1 SV=2
MNFLAHLHLAHLAESSLSGNLLADFVRGNPEESFPPDVVAGIHMHRRIDVLTDNLPEVREAREWFRSETRRVAPITLDVMWDHFLSRHWSQLSPDFPLQEFVCYAREQVMTILPDSPPRFINLNNYLWSEQWLVRYRDMDFIQNVLNGMASRRPRLDALRDSWYDLDAHYDALETRFWQFYPRMMAQASRKAL

I know there are libraries which do the same thing, however, I had to write this script as a homework, without the help of BioPython or other similar libraries.
My question is: how can I make this code more efficient?
import sys
import os

def readFasta( path ):

    seq = { }
    aCount = { }
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWYZX*-"

    for fileName in path:

        with open( fileName ) as file:
            fastaLine = file.readlines( )

            # sequence storage

            for line in fastaLine:
                if line[ 0 ] == ">" :
                    headerTitle = line.split( "|" )[ 1 ]
                    seq[ headerTitle ] = ""
                else:
                    seq[ headerTitle ] += line.strip( )

            # aminoacid count

            for id in seq:
                aCount[ id ] = { }
                for sequence in seq[ id ]:
                    if sequence not in alphabet:
                        print( "Check your sequence! Character: " + str(sequence) + " from sequence: " + id )
                    for letter in alphabet:
                        aCount[ id ][ letter ] = 0

            # count aminoacid occurence/sequence

            for name in seq:
                for char in seq[ name ]:
                    if char in aCount[ name ]:
                        aCount[ name ][ char ] += 1

    # write to .csv file

    outFile = open( "output.csv" , "w" )

    outFile.write( "Name" + '\t' )

    header = ""
    for letter in alphabet:
        header += letter + '\t'

    outFile.write( header + "Total" )
    outFile.write( '\n' )

    for name in aCount:
        entry = ""
        counter = 0
        for letter in aCount[ name ]:
            entry += str(aCount[ name ][ letter ]).strip( ) + '\t'
            counter += aCount[ name ][ letter ]
        outFile.write( name + '\t' + entry + '\t' + str( counter ) )
        outFile.write( '\n' )

# files to list

entries = os.listdir( path )

# filter for .fasta/.fa files

new_list = [ ]
for entry in entries:
    if ".fasta" in entry:
        new_list.append( entry )
    elif ".fa" in entry:
        new_list.append( entry )

# execute func

readFasta( new_list )


texts:
The task was to build a simple parallel server in erlang that prints what it receives through a socket and alerts when the socket is closed.

-module(server).
-export([start/0]).

start() ->
    {ok, ListenSocket} = gen_tcp:listen(8211,[binary,{packet,4},{active, once}]),
    spawn(fun() -> accepter(ListenSocket) end),
  sleep().

sleep() ->
    receive
        cancel -> void
    end.

accepter(ListenSocket) ->
    {ok, Socket} = gen_tcp:accept(ListenSocket),
    spawn(fun() -> accepter(ListenSocket) end),
    Proc = spawn(fun() -> worker(Socket) end),
    gen_tcp:controlling_process(Socket, Proc).

worker(Socket) ->

    receive
        {tcp, Socket, Data} ->
            io:format("Received ~p",[Data]),
            inet:setopts(Socket, [{active, once}]),
            worker(Socket);
        {tcp_closed, Socket} ->
            io:format("Socket ~p closed",[Socket])
    end.

Is this the correct way of building such a thing?


texts: Representation of the formula P(n) = (n!)(6^n)

texts:
I'm trying to represent the following mathematical expression in Python:

$$P(n) = (n!)(6^n)$$

The program should compute the answer to expression when n = 156. I have attempted to create the program in python and it produces the correct answer (when compared with wolfram alpha's answer). The answer is approximately \$10^{397}\$.

Is there any way that I could improve the code? (I'm fairly new to programming):

import math
n=156
F = math.factorial(n)
pwr = pow(6,n)
P = F*pwr
print P


texts:
I've been doing some self-imposed exercises to get accustomed to Python and below is my code.

import random
from random import randint
from random import randrange
from mainlist import legendaryitems
from mainlist import waystodie
from mainlist import powerup
from mainlist import mood
from mainlist import ponder
import time

class Player(object):
    def __init__(self, name):
        self.name = name
        self.lifecondition = True
        self.hitpoints = 100
        self.items = []
        self.waystodie = []
        self.mood = ""

    def death(self):
        self.lifecondition = False

    def ways_to_die(self, death):
        self.waystodie.append(death)

    def  add_items(self, item):
            self.items.append(item)

    def change_hp(self, hp):
        self.hitpoints = hp

    def change_mood(self, mood):
        self.mood = mood

    def __repr__(self):
        return repr(self.name)

def addplayers(alist):
    players = []
    for item in alist:
        item = Player("%s" % item)
        players.append(item)
        print "%s enters the game with %s HP of life and feels pretty much alive" %  (item.name, item.hitpoints, )
    return players

def player_mood(playerlist, moodlist):
    for item in playerlist:
        mood = random.choice(moodlist)
        item.change_mood(mood)

playerlist = ["Player1", "Player2", "Player3", "Player4", "Player5", "Player6", "Player7", "Player8", "Player9", "Player10"]

players = addplayers(playerlist)
player_mood(players, mood)

print players[1].mood
print players[2].mood

player_mood(players, mood)

print players[1].mood
print players[2].mood

My intention is to create actions depending on the mood of characters. Basically it's gonna be a "There can be only one!" game. The reason of my post is not so that someone else can write the code for me but for feedback on how to write more clean, efficient code following Python's philosophy at the same time.

I am calling the instances through the players list but is there any other way I should be using to recall them from the class?

I'm able to convey what I want to do into code but is it ok to interact with standalone functions with my class? Or should I be building methods within another Class (utilize inheritance as well) to interact with Player()?


texts: Get information about the USB device from Win32_DiskDrive and Win32_LogicalDisk

texts:
I want to know the information about a USB device from Win32_DiskDrive and Win32_LogicalDisk.

I use the following code:

private void Add(string letter) // letter is a logical name of the USB device, e.g. "G:\\"
{
  foreach (var drive in new ManagementObjectSearcher("SELECT DeviceID, SerialNumber, Partitions FROM Win32_DiskDrive WHERE InterfaceType='USB'").Get())
  {
    var partition = new ManagementObjectSearcher(string.Format("ASSOCIATORS OF {{Win32_DiskDrive.DeviceID='{0}'}} WHERE AssocClass = Win32_DiskDriveToDiskPartition", drive["DeviceID"])).First();

    if (partition != null)
    {
      var logical = new ManagementObjectSearcher(string.Format("ASSOCIATORS OF {{Win32_DiskPartition.DeviceID='{0}'}} WHERE AssocClass = Win32_LogicalDiskToPartition", partition["DeviceID"])).First();

      if (logical != null)
      {
        var volume = new ManagementObjectSearcher(string.Format("SELECT Name, FreeSpace FROM Win32_LogicalDisk WHERE Name='{0}'", logical["Name"])).First();

        string name = (string)volume["Name"];
        string serialNumber = (string)drive["SerialNumber"];
        ulong freeSpace = (ulong)volume["FreeSpace"];
        break;
      }
    }
  }
}

  public static class WmiExtensions
  {
    // Fetch the first item from the search result collection.
        public static ManagementObject First(this ManagementObjectSearcher searcher)
        {
          ManagementObject result = null;
          foreach (ManagementObject item in searcher.Get())
          {
            result = item;
            break;
          }
          return result;
        }
      }
    }

Is there a way to make it shorter and more elegant?


texts: Partitioning array elements into two subsets

texts:
Problem:

  Given a randomly ordered array of n-elements, partition the elements
  into two subsets such that elements <= x are in one subset and elements

    x are in the other subset.

  One way to do this is to sort the array in ascending order. But with
  this solution we actually ordered the array in addition to partition.
  Also sort is costly.

  For example, let's take this array \$[37,36,27,11,15,12,34,29,4,10]\$
  and partition value is 17.

  So the array after partition should be
  \$[10,4,12,11,15,27,34.29.36,37]\$

  Comparing these two data sets we can see that elements from left side
  greater than 17 must be moved to right side and at the right side
  elements less than 17 to left side.

  Initially we do not know how many elements are less than < 17. One
  way to solve this, pass through the array and count the number of
  elements less than 17. Once we know the partition value (here it is
  15), then make another pass through the array to make the exchange.
  But this is \$0(n^2)\$.

  We need to find a solution where this can be done with only pass
  through the array. Looking at these data sets we can find that even if
  we do not know the partition value(here it is 17), 37 can be exchanged
  with 10, 36 can be exchanged with 4 and so on.

  This is something like left partition is growing to right and right is
  growing to left.

| Left Partition ->    ||   <- Right Partition |
^                    ^                       ^
i=0            partition point           j=n (length of array)

  So we get the basic mechanism to exchange, while two partitions have
  not met do

  Extend the left and right partitions inward exchanging wrongly  placed elements.
  Exchange can be done by the standard technique

t = a[i];
a[i] = a[j];
t = a[j];

  Moving inwards from left and right can be done by,

  from left to right: while(a[i] <= x) i = i + 1;

  from right to left: while(x < a[j]) j = j - 1;

  where a is the array, i is the starting index 0, j is last index
  that is the length of the array.

  One case is, initially we don't know a[i] and a[j] should be
  exchanged since there is no initial move inwards from the left and
  right to check if an exchange is really necessary. we can overcome
  this by placing a check before passing through the array:

while(a[i] <= x) i = i + 1;
while(x < a[j]) j = j - 1;

  Algorithm (it is based on R. G. Dromey's How to solve it by computer):

  Establish an array \$a[1...n]\$ and partition value x.
  Move the two partitions towards each other until a wrongly placed pair of    elements is encountered.
  While two partitions have not met or crossed do

  exchange wrongly placed pairs and extend both partitions inwards    by one element.
  extend left partition while elements less than or equal to x
  extend right partition while elements greater than x

  Print partitioning index p and partitioned array.

Here is my solution:

public class PartitionArray {

  public static void main(String args[]) {

    int[] elements = {37, 36, 27, 11, 15, 12, 34, 29, 4, 10};

    int x = 17;
    int p = 0;

    int i = 0;
    int j = elements.length - 1;

    while (elements[i] <= x && i < j) i = i +1;
    while (x < elements[j] && i < j) j = j - 1;

    int tmp;

    while (i < j) {
      tmp = elements[i];
      elements[i] = elements[j];
      elements[j] = tmp;

      i = i + 1;
      j = j - 1;

      while (elements[i] <= x && i < j) i = i +1;
      while (x < elements[j] && i < j) j = j - 1;

      p = j;
    }

    print("P: " + elements[p]);
    print("Partitioned Array: " + Arrays.toString(elements));
  }
}


texts: Extracting text fields from  tags in an HTML message

texts:
What i'm doing

I have a string with html information like this:

 Some text this is a test

My goal in the method is to create a dictionary with this value:

**key**     **value**
field-4    Some text

This is the code that i'm using to accomplish my task:

public static Dictionary<int,String> getFields(String mensaje)
    {
        Dictionary<int,String> fields = new Dictionary<int,string>();
        Match m = Regex.Match(mensaje, @"^(.*?(.*?).*?)+$", RegexOptions.Singleline);
        for (int i = 0; i < m.Groups[2].Captures.Count; i++)
        {
            String value = m.Groups[1].Captures[i].Value;
            Match m2 = Regex.Match(value, "^(.*?fieldId=.*?\"(.*?)\">.*?)+$", RegexOptions.Singleline);
            String fieldId = m2.Groups[2].Captures[0].Value;
            fieldId = fieldId.Replace("field-", String.Empty);
            fields.Add(int.Parse(fieldId),m.Groups[2].Captures[i].Value);
        }

        return fields;
    }

How can i improve my code?


texts: Square root calculation with Newton's method

texts:
I am currently learning Haskell in parallel of following the Scala course proposed by Coursera.

To practice Haskell I try to implement exercices and/or course example from this course.

So there is a simpler square root estimation implementation:

sqrt' :: Double -> Double -> Double
sqrt' x guess
  | guessIsGoodEnough = guess
  | otherwise         = sqrt' x improvedGuess
  where
    -- Test the precision of the guess
    precision          = 0.001
    guessIsGoodEnough  = abs (guess * guess - x) < precision * x
    -- Improve our guessed square
    improvedGuess      = (guess + x / guess) / 2

I welcome any feedback on this, I mostly aim for clarity and simplicity (one-liner welcome, but I do not specificaly aim for that ;) ).


texts: Using 'switch to choose different rates to calculate net pay

texts:
My task is ask this from the user:

Enter the number corresponding to the desired pay rate or action:

1) $8.75/hr           2) $9.33/hr

3) $10.00/hr          4) $11.20/hr

5) quit

If choices 1 through 4 are selected, the program should request the hours
worked. The program should recycle until 5 is entered. If something other than
choices 1 through 5 is entered, the program should remind the user what the
proper choices are and then recycle. And i have to use switch

My code:

#include <stdio.h>
#define RATE1 8.75
#define RATE2 9.33
#define RATE3 10.00
#define RATE4 11.20

int main()

{
    int rateSelected;
    int weeklyHours;
    double totalPayed, rateToCalculate;

    printf("Enter the number corresponding to the desired pay rate or action:\n");
    printf("1) %.2lf$/hr                               2) %.2lf$/hr\n", RATE1, RATE2);
    printf("3) %.2lf$/hr                              4) %.2lf$/hr\n", RATE3, RATE4);
    printf("5) Quit\n");

    while ((scanf("%d", &rateSelected)) != EOF && rateSelected != 5)
    {

        if (rateSelected > 4)
        {
            printf("please enter a valid number:\n");
            continue;
        }

            switch (rateSelected)
        {
            case 1:
                rateToCalculate = RATE1;
                break;
            case 2:
                rateToCalculate = RATE2;
                break;
            case 3:
                rateToCalculate = RATE3;
                break;
            case 4:
                rateToCalculate = RATE4;
                break;

        };

        printf("please enter you weekly hours:\n");
        scanf("%d", &weeklyHours);
        totalPayed = weeklyHours * rateToCalculate;
        printf("your paychack for this week is: %.2lf\n\n",totalPayed);

        printf("Enter the number corresponding to the desired pay rate or action:\n");
        printf("1) %.2lf$/hr                               2) %.2lf$/hr\n", RATE1, RATE2);
        printf("3) %.2lf$/hr                              4) %.2lf$/hr\n", RATE3, RATE4);
        printf("5) Quit\n");

    }

    return 0;
}

How bad is it?
And one thing didn't work for me is if a user put a letter its not cycling..(any suggestion for that too?)

Thank you,


texts:
Recently, I was asked to develop a way to easily create a branched narrative, where the user can select options to progress the story in their own path. After a couple hours of fiddling around with different options I managed to produce this simple code.

### STORY BRANCH MANAGEMENT

class Branch:

    def __init__(self, dialogue, options={}):
        self.dialogue = dialogue
        self.options = options
        self.keys = list(options.keys())
        self.canbranch = options != {}

    def __iter__(self):
        for x in self.keys:
            yield x

    def __str__(self):
        return self.dialogue

    def choose(self, choice):
        return self.options[self.keys[choice]]

story_main = Branch("You find yourself in a room with three doors, which one do you choose?", {
    "Left door":
        Branch("You fell in a hole and died"),
    "Middle door":
        Branch("Oh hey, you win a free Parker pen"),
    "Right door":
        Branch("You tripped over the door frame", {
            "Get up and walk away":
                Branch("Oh well, at least you lived"),
            "Die on the spot":
                Branch("Nevermind...") } ),
    "All of the above":
        Branch("Well I guess that works") } )

### PLAY THE STORY

def play():
    br = story_main

    while br.canbranch:
        # Output the current branch's dialogue
        print(br)

        # Create blank line, then displays the sub-branch choices as an enumerated list
        print("")
        for i,x in enumerate(br):
            print("\t{}) {}".format(i + 1, x))

        # Have the user to select an option
        print("")
        c = -1
        while c not in range(len(br.keys)):
            c = int(input("Select --> ")) - 1

        # Update the current branch to the sub-branch that the user just chose
        br = br.choose(c)
        print("---")

    # If the user reaches a 'final' branch (i.e, no choices), output it's dialogue and close the program after enter is hit.
    input(str(br) + "\n---")

play()

The code itself makes sense I hope, but the main concern I have is with the part in the middle where we can create a story: story_main = Branch( ... ). It seems a bit... strange. I've been told that it is readable, but it doesn't seem very 'pythonic'. I assume this is because of the way I've used dictionaries to store a choice and its corresponding sub-branch as the key and value respectively.

If you can't understand how the story is written, I'll brief over what it does so that it may be easier to grasp. When the program is opened, you're told "You find yourself in a room ... " Then, you are given a list of options, "Left door", "Right door", and so on. If you chose to enter the right door, the program would output "You tripped over the doorframe" and give you some more options, "Get up and walk away" and "Die on the spot". If you chose to die on the spot, it would output "Nevermind..." and the story would end.

This is what the program looks like when run:

So as you can see it works, but is it acceptable to use this method?

EDIT: The answers so far have both recommended to save the story as an external file in some way, and then access it from within the code. I imagine this is for organisation, and it was actually what I originally had in mind. The program from which the code I provided is from did do something like this (although likely less convenient than suggested methods in most respects). If anyone has more suggestions on how storing the narrative could be optimised, that would also be appreciated.


texts:
I want to first search for a specific regular expression.
If it is not found then I would like to search for another regular expression
If that one is also not found then I would like to search for a third
(And so on...)

Whenever a matching regular expression is found, I want to return a String array containing:

The text before the match
The match itself
The text after the match

I've only come up with this horribly if-else nesting way of doing it. There's gotta be a better (more extensible and more clean) way but I can't come up with how...

Here is the code, it is currently only containing two regular expressions to search for and it's getting nasty already:

private static String[] findNumbers(String string) {
    Matcher match = Pattern.compile("\\d+[\\:\\.\\,]\\d+").matcher(string);
    if (match.find()) {
        String found = string.substring(match.start(), match.end());
        return new String[]{ string.substring(0, match.start()),
            found, string.substring(match.end()) };
    }
    else {
        match = Pattern.compile("\\d{3,}").matcher(string);
        if (match.find()) {
            String found = string.substring(match.start(), match.end());
            return new String[]{ string.substring(0, match.start()),
                found, string.substring(match.end()) };
        }
        else {
            // Another if-else could be added here
            return new String[]{ string, "", "" };
        }
    }
}

@Test
public void test() {
    assertArrayEquals(new String[]{ "ABC ", "2000", " DEF" }, findNumbers("ABC 2000 DEF"));
    assertArrayEquals(new String[]{ "42 ABC ", "2000", " DEF" }, findNumbers("42 ABC 2000 DEF"));
    assertArrayEquals(new String[]{ "42 ABC ", "18:47", " DEF" }, findNumbers("42 ABC 18:47 DEF"));
}

I want to put priority to one regular expression before trying the next, that's why I have written this code.


texts:
I solved the Hackerrank Luck Balance problem the "C" way (I am much more used to C) and I wanted to know if there were any C++ features I could have used that would have made my code more concise/neater. That's it! Any other criticism is welcome, of course.

All the stuff that I wrote is in the LuckBalance() function. Pay no attention to anything else - that was provided by the challenge (which wasn't really a challenge)

  Lena is preparing for an important coding competition that is preceded by a number of sequential preliminary contests. She believes in "saving luck", and wants to check her theory. Each contest is described by two integers, \$L[i]\$ and \$T[i]\$. \$L[i]\$ is the amount of luck associated with a contest. If Lena wins the contest, her luck balance will decrease by \$L[i]\$; if she loses it, her luck balance will increase by \$L[i]\$.

  \$T[i]\$ denotes the contest's importance rating. It's equal to \$1\$ if the contest is important, and it's equal to \$0\$ if it's unimportant.

  If Lena loses no more than \$k\$ important contests, what is the maximum amount of luck she can have after competing in all the preliminary contests? This value may be negative.

Note that the k parameter in the luckBalance function is the maximum number of important contests Lena can lose, and the vector<vector<int>> contests input is a column vector of \$L[i]\$ along with a column vector of \$T[i]\$.

#include <bits/stdc++.h>
#include <stdlib.h>

using namespace std;

vector<string> split_string(string);

// Complete the luckBalance function below.
int luckBalance(int k, vector<vector<int>> contests) {

    int totalLostLuck = 0;
    int totalGainedLuck = 0;
    int totalRegainedLuck = 0;
    vector<int> regainedLuck(k, 0);

    for(int i = 0; i < contests.size(); i++)
    {
        if(contests[i][1] == 1)
        {
            totalLostLuck += contests[i][0];
            for(int j = 0; j < k; j++)
            {
                // Choose to win the contests that have the greatest
                // amount of luck
                if(regainedLuck[j] < contests[i][0])
                {
                    regainedLuck[j] = contests[i][0];
                    sort(regainedLuck.begin(), regainedLuck.end());
                    j = k;
                }
            }
        }
        // If it is a non-important contest, we get the luck for free!
        else
        {
            totalGainedLuck += contests[i][0];
        }
    }

    for(int i = 0; i < k; i++)
    {
        totalRegainedLuck += regainedLuck[i];
    }

    return totalGainedLuck - totalLostLuck + (2*totalRegainedLuck);
}

int main()
{
    //ofstream fout(getenv("OUTPUT_PATH"));

    string nk_temp;
    getline(cin, nk_temp);

    vector<string> nk = split_string(nk_temp);

    int n = stoi(nk[0]);

    int k = stoi(nk[1]);

    vector<vector<int>> contests(n);
    for (int i = 0; i < n; i++) {
        contests[i].resize(2);

        for (int j = 0; j < 2; j++) {
            cin >> contests[i][j];
        }

        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    int result = luckBalance(k, contests);

    cout << result << "\n";

    //fout.close();

    return 0;
}

vector<string> split_string(string input_string) {
    string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
        return x == y and x == ' ';
    });

    input_string.erase(new_end, input_string.end());

    while (input_string[input_string.length() - 1] == ' ') {
        input_string.pop_back();
    }

    vector<string> splits;
    char delimiter = ' ';

    size_t i = 0;
    size_t pos = input_string.find(delimiter);

    while (pos != string::npos) {
        splits.push_back(input_string.substr(i, pos - i));

        i = pos + 1;
        pos = input_string.find(delimiter, i);
    }

    splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

    return splits;
}