texts: Loads two columns from excel - cleans up the data - and makes a new list of unmatched values

texts:
I am comparing two columns of data (~20k rows) to find the items that do not match. Actually one of my files is an export from an Oracle database, but I have not gotten to the point of working with databases in python yet.

The code works as intended, but as I am new to this I am wondering if there is a more efficient way to do all of this.

First I read the columns into a list:

 import openpyxl
 wb = openpyxl.load_workbook('file.XLSX')
 ws = wb['dirtyfile']
 dirtysource = []
 cleansource = []
 for col in ws['A']:
     dirtysource.append(col.value)
 ws2 = wb['Database Export']
 for col in ws2['A']:
     cleansource.append(col.value)

The data I have extracted from the database is already cleaned. The other data set is in an inconsistent format:

dirtysource = [u'Tom Jones (01134)', u'Bob Smith (On Leave) (598711)', u'Jane Doe (00004)', u'100627 - Juan Carlos' ]

Next I clean the data up. I am slicing out the name, and just keeping the ID. The ID can be of a variable length. When it appears at the end of the string it is enclosed in parentheses. When it is at the beginning it is delimited by a '-'.

j = 0
for i in dirtysource:
    if i.endswith(')'):
        dirtysource[j] = str(i[i.rfind('(')+1:len(i)-1])
    else:
        dirtysource[j] = str(i[0:i.find('-')-1])
    j = j +1

The only thing I am doing to the clean list is to convert it from unicode:

j = 0
for i in cleansource:
    cleansource[j] = str(i)
    j = j + 1

Finally I compare the two lists to find the non-matching values:

delta = []
for i in dirtysource:
    if i in cleansource: continue
    else:
        delta.append(i)
print delta

delta1 = []
for i in cleansource:
    if i in dirtysource: continue
    else:
        delta1.append(i)
print delta1

Eventually I will be passing the two lists into some queries, but I have more to learn before I do that.


texts: Three identical AJAX button handlers in three views

texts:
In my Rails 4 app I have this event listener:

$('.remove-tag-button').on('click', function () {
    $.ajax({
      type: "POST",
      data: {id: <%= @item.id %>, tag: $(this).data("tag-name")},
      url: "/remove_tag"
    });
  });

in three places and I'm wondering if there's a way to refactor.

I have an items controller with some actions including show, add_tag, and remove_tag.

def show
  @item= Item.find_by_id(params[:id])
end

def add_tag
  (omitted for brevity)
  respond_to do |format|
    format.js
end

def remove_tag
  (omitted for brevity)
  respond_to do |format|
    format.js
end

My show.html.erb has a form with a button to remove tags (class="remove-tag-button") that the event listener is referring to.  I have the listener inside script tags at the bottom of my show.html.erb (inside a $(document).ready()) and also inside my add_tag.js.erb and remove_tag.js.erb.

show.html.erb

  <%= render partial: 'items/tag_list', locals: {item: @item} %>

 <form action="<%= add_tag_path %>" method="post" id="custom-tag" class="input-group" autocomplete="off" data-remote="true">
   <%= text_field_tag :tag, nil, placeholder: 'Add tag', class: "form-control typeahead", id: 'add-tag' %>

     <%= submit_tag 'Add', id: "add-button", class: "btn btn-default" %>

 </form>

add_tag.js.erb

$("#taglist").html('<%= escape_javascript(render partial: "items/tag_list", locals: {item: @item}) %>');

$('.remove-tag-button').on('click', function () {
  $.ajax({
    type: "POST",
    data: {id: <%= @item.id %>, tag: $(this).data("tag-name")},
    url: "/remove_tag"
  });
});

remove_tag.js.erb

$("#taglist").html('<%= escape_javascript(render partial: "items/tag_list", locals: {item: @item}) %>');

$('.remove-tag-button').on('click', function () {
  $.ajax({
    type: "POST",
    data: {id: <%= @item.id %>, tag: $(this).data("tag-name")},
    url: "/remove_tag"
  });
});

items/_tag_list.html.erb

<% item.all_tags_list.each do |t| %>

    <%= link_to t, tag_path(t), class: "item-tag" %>
    <% if item.tags_from(current_user).include?(t) %>

        <%= link_to "×", '', class: "remove-tag-button", :'data-tag-name' => t, remote: true %>

    <% end %>

<% end %>

I have 3 instances of this code because a user needs to be able to add and remove tags through AJAX requests while on the page. So it listens when the page loads, then I need it to still be listening after a user has added and/or removed a tag (both which are done through AJAX).

This seems sloppy.  I'm wondering if theres a better way to do it.


texts:
I wrote this function in scala that uses tail recursion to remove nested blocks from a text.

Usage examples:

removeBlocks("123{456}789", "{", "}")                            yields "123789"
removeBlocks("123{a{b{c}b}a}789", "{", "}")                      yields "123789"
removeBlocks("123
456
789", "
", "
")          yields "123789"
removeBlocks("123<<
<<<
>>789", "
", "
")      yields "123<<>>789"

This is one of my first attempts in a functional language, and I'm deeply dissatistied with my code. It's too long, too nested, and could probably be made more readable. I'm coming from C# and hope to be forgiven for this bad functional code. I'll be happy to hear how it can be improved.

  def removeBlocks(text: String, startMarker: String, endMarker: String) = {
    val startMarkerSize = startMarker.size
    val endMarkerSize = endMarker.size
    val startMarkerHead = startMarker.head
    val endMarkerHead = endMarker.head

    def removeBlocksAcc(s: String, acc: String, nestingLevel: Int): String =
    if (s.isEmpty) acc
      else {
        val (startMarkerCandidate, tail1) = s.splitAt(startMarkerSize)
        if (startMarkerCandidate == startMarker)
          removeBlocksAcc(tail1, acc, nestingLevel + 1)
        else {
          val (endMarkerCandidate, tail2) = s.splitAt(endMarkerSize)
          if (endMarkerCandidate == endMarker)
            removeBlocksAcc(tail2, acc, math.max(nestingLevel - 1, 0))
          else {
            val (safePart, candidate) = s.tail.span(c => c != startMarkerHead && c != endMarkerHead)
            if (nestingLevel == 0)
              removeBlocksAcc(candidate, acc + s.head + safePart, nestingLevel)
            else
              removeBlocksAcc(candidate, acc, nestingLevel)
          }
        }
      }
    removeBlocksAcc(text, "", 0)
  }


texts: Create a histogram of the lengths of words

texts:
I am reading through K&R C 2nd Edition, and I am on exercise 1-13. The exercise is to write a program to print a histogram of the lengths of words in
its input. I wrote a program that successfully does this; however, after looking at the program, I noticed that it was somewhat messy, and I'm sure that there is a better way to implement it. I'm looking for some tips as to how I can improve programs like this in the future.

Here is the code:

#include <stdio.h>
#define IN 1
#define OUT 0
#define MAXVAL 11

int main(){
    int i, j, c, state;
    int wordLengths[MAXVAL];
    int currentWord = 0;
    int greaterThanMax = 0;

    for(i = 0; i < MAXVAL; i++){
        wordLengths[i] = 0;
    }

    while((c = getchar()) != EOF){
        ++currentWord;
        state = IN;
        if(c == '\n' || c == ' ' || c == '\t'){
            state = OUT;
            --currentWord;
        }
        if(state == OUT){
            if(currentWord < MAXVAL){
                ++wordLengths[currentWord];
            }
            else{
                ++greaterThanMax;
            }
            currentWord = 0;
        }
    }
    for(i = 1; i < MAXVAL; i++){
        printf("%d letter(s): ", i);
        for(j = 0; j <= wordLengths[i] - 1; j++){
            putchar('=');
        }
        putchar('\n');
    }
    printf(">%d: ", MAXVAL - 1);
    for(i = 0; i < greaterThanMax; i++){
        putchar('=');
    }
    return 0;
}


texts: Conditionally truncating a filename to a max length without damaging the file extension

texts:
Yes, I'm bad at conditionals. I don't use them so much and I feel a bit lost with them. How would you (if possible) refactor or change this little piece of code?

Second improved version:

$MAX_FNAME_LEN   = 255;
$clientFilename  = $this->file->getClientOriginalName();
$clientExtension = $this->file->guessExtension();

// Assume a failure in reading client filename
$defFilename = $defRandFilename = uniqid('fid_', true);

if(!is_null($clientFilename))
{
    $clientFilenameLength = strlen($clientFilename);
    $hasClientExtension   = !is_null($clientExtension);

    $removeFromEnd = $hasClientExtension ? - (1 + strlen($clientExtension)) : 0;
    $appendAtEnd   = $hasClientExtension ? ".$clientExtension" : '';

    if($clientFilenameLength > $MAX_FNAME_LEN) // Truncate original filename
    {
        $excessFromEnd = $MAX_FNAME_LEN - $clientFilenameLength - $removeFromEnd;
        $defFilename   = substr($clientFilename, 0, $excess) . $appendAtEnd;
    }
    else
        $defFilename  = $clientFilename; // User original filename

    if(strlen($defRandFilename) + abs($removeFromEnd) > $MAX_FNAME_LEN) // Truncate sanitized
        $defRandFilename = substr($defRandFilename, 0, $removeFromEnd) . $appendAtEnd;
    else
        $defRandFilename .= $appendAtEnd; // Use sanitized plus extension
}


texts: Go function to generate permutations of a given integer array

texts:
I'm writing a function to generate a permutation of given []int:

// Input: [1,2,3]
// Output:
// [
//   [1,2,3],
//   [1,3,2],
//   [2,1,3],
//   [2,3,1],
//   [3,1,2],
//   [3,2,1]
// ]

func permute(nums []int) [][]int {
    var tmp []int
    var res [][]int
    invalid_pos := make([]bool, len(nums))
    res = backtrack(nums, tmp, invalid_pos, res)
    return res
}

// backtrack generates all the permutations of the given `nums` and put them into `res`.
// `invalid_pos` keeps track of which number is valid to pick from `nums` to form a permutation
// `tmp`
func backtrack(nums []int, tmp []int, invalid_pos []bool, res [][]int) [][]int {
    if len(tmp) == len(nums) {
        tmp2 := make([]int, len(tmp))
        copy(tmp2, tmp)
        res = append(res, tmp2)
    } else {
        for i, num := range nums {
            if invalid_pos[i] {
                continue
            }
            invalid_pos[i] = true
            tmp = append(tmp, num)
            res = backtrack(nums, tmp, invalid_pos, res)
            invalid_pos[i] = false
            tmp = tmp[:len(tmp)-1]
        }
    }
    return res
}

My question is do I need to make a copy copy(tmp2, tmp)? I read about capturing iteration variables and I was wondering if this will have any side effect? I think I can simplify the code by removing copy...


texts:
This was a code test I was asked to complete by employer, and since they rejected me, I wonder what should I have done differently.

var w = 7, h = 6;
var currentPlayer = 1;
var animationInProgress = 0;
var winner = 0;

var map = new Array(h);
var mapHtml = "";

for (var i = 0; i < w; i++) {
    map[i] = new Array(h);
    mapHtml = mapHtml + "
";
    for (var j = 0; j < h; j++) {
        map[i][j] = 0;
        mapHtml = mapHtml + "

";
    }
    mapHtml = mapHtml + "
";
}

$("#map").html(mapHtml);

function makeTurn(col) {
    if (animationInProgress == 0 && winner == 0) {
        for (var i = h-1; i >= 0; i--) {
            if (map[col][i] == 0) {
                map[col][i] = currentPlayer;
                animateTurn(col, i);
                checkForWin(col, i);
                currentPlayer = 3 - currentPlayer;
                break;
            }
        }
    }
}

function animateTurn(col, row) {
    animationInProgress = 1;
    $("#map #col"+col+" .next-ball").addClass("animation-in-progress");

    $("#map #col"+col+" .next-ball").animate({
        top: '+='+(52*(row+1)-1)
    }, {
        duration: Math.round((row+1)*500/h),
        complete: function() {
            $("#map #col"+col+" div:nth-child("+(row+2)+")").html("");
            $("#map #col"+col+" .next-ball").css("top", "0px");
            $("#map .animation-in-progress").removeClass("animation-in-progress");
            $("#map .next-ball").removeClass("player"+(3-currentPlayer));
            $("#map .next-ball").addClass("player"+currentPlayer);
            animationInProgress = 0;
        }
    });
}

function checkForWin(x, y) {
    var delta, dx, dy, n = 0;
    //horizontal win
    for (i = 0; i < w; i++) {
        if (map[i][y] == currentPlayer) {
            n++;
            if (n == 4) win(currentPlayer);
        } else {
            n = 0;
        }
    }

    //vertical win
    n = 0;
    for (i = 0; i < h; i++) {
        if (map[x][i] == currentPlayer) {
            n++;
            if (n == 4) win(currentPlayer);
        } else {
            n = 0;
        }
    }

    //diagonal / win
    n = 0;
    delta = Math.min(x, h-y-1);
    for (dx = x-delta, dy = y+delta; dx < w && dy > 0; dx++, dy--) {
        if (map[dx][dy] == currentPlayer) {
            n++;
            if (n == 4) win(currentPlayer);
        } else {
            n = 0;
        }
    }

    //diagonal \ win
    n = 0;
    delta = Math.min(x, y);
    for (dx = x-delta, dy = y-delta; dx < w && dy < h; dx++, dy++) {
        if (map[dx][dy] == currentPlayer) {
            n++;
            if (n == 4) win(currentPlayer);
        } else {
            n = 0;
        }
    }
}

function win(player) {
    alert('Win by player '+player+'. Refresh page to restart');
    winner = 1;
}

What are the problems with this code?

Non-descriptive variable names?
Too many constants in code?
Not using comments?


texts: Using 2 threads to compute the nth Fibonacci number (with memoization)

texts:
If the 5th Fibonacci number has to be computed, I'm trying to split the 2 recursive trees into 2 threads:

                       5

         4                           3

   3           2                2        1

2     1     1     0         1       0

       Thread 1                 Thread 2

My attempt:

public class ParallelFibbonaci
{

static ExecutorService executor = Executors.newFixedThreadPool(2);
// Memoized map.
private static Map<Integer, Long> mem = new ConcurrentHashMap<>();

public static void main(String[] args) throws ExecutionException, InterruptedException{
    final long then = System.nanoTime();

    System.out.println(fib_wrapper(Integer.parseInt(args[0])));

    final long millis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - then);
    System.out.println("Time(ms): " + millis);
    executor.shutdown();
}

public static int fib_wrapper(int n) throws ExecutionException, InterruptedException {
    Future<Integer> future = executor.submit(() -> fib(n-1));
    Future<Integer> future2 = executor.submit(() -> fib(n-2));

    return future2.get() + future.get();
}

public static int fib(int n) throws ExecutionException, InterruptedException {
    if (n == 1)
        return 1;
    if (n == 0)
        return 0;

    if (mem.containsKey(n)) {
        return mem.get(n);
    }

    long x = fib(n-1) + fib(n-2);
    mem.put(n, x);
    return x;
  }
}

I couldn't prove the parallel version to run faster than the simple version, in fact, all my profiling (done with System.nanoTime() which I believe is not the most reliable) revealed it to be 20-30 times slower:

Sid:Programs siddhartha$ java -Xms2G -Xmx4G parallelfibbonaci 1000
817770325994397771
Time(ms): 60

Sid:Programs siddhartha$ java -Xms2G -Xmx4G simplefibbonaci 1000
817770325994397771
Time(ms): 4

Sid:Programs siddhartha$ java -Xms2G -Xmx4G parallelfibbonaci 500
2171430676560690477
Time(ms): 59

Sid:Programs siddhartha$ java -Xms2G -Xmx4G simplefibbonaci 500
2171430676560690477
Time(ms): 2

Any higher n's crashed my program with a stackoverflow error.

In theory, I'd expect using 2 threads on a tree-recursive algorithm to work faster than a single-threaded implementation, however it seems this is clearly not the case. What am I missing here?


texts: Avoiding Boundaries `if` Cases When Filtering Image Matrix

texts:
I have the following MATLAB Code which I want to optimize.
It's related to an image matrix (2D) which I want to filter.
Though it is MATLAB code, the same problem would arise in C code.

The problem is that I'm trying to access neighbors of the pixel which might cause problems at the boundaries of the image matrix.

vWeightsCoeff = zeros((2 * numRows * numCols), 1);

weightsIdx = -3;

% Filteration
for iColIdx = 1:numCols
    for iRowIdx = 1:numRows
        if(mod((iRowIdx + iColIdx), 2) == 0)
            continue;
        end

        weightsIdx = weightsIdx + 4;

        refPixel = mOutputImage(iRowIdx, iColIdx);

        if(iRowIdx < numRows)
            relPixel1 = mOutputImage((iRowIdx + 1), iColIdx);
            relWeight1 = vRangeTable(round((refPixel - relPixel1) * RANGE_RESOLUTION) + RANGE_CENTER_IDX);
        else
            relPixel1 = 0;
            relWeight1 = 0;
        end

        if(iRowIdx > 1)
            relPixel2 = mOutputImage((iRowIdx - 1), iColIdx);
            relWeight2 = vRangeTable(round((refPixel - relPixel2) * RANGE_RESOLUTION) + RANGE_CENTER_IDX);
        else
            relPixel2 = 0;
            relWeight2 = 0;
        end

        if(iColIdx < numCols)
            relPixel3 = mOutputImage(iRowIdx, (iColIdx + 1));
            relWeight3 = vRangeTable(round((refPixel - relPixel3) * RANGE_RESOLUTION) + RANGE_CENTER_IDX);
        else
            relPixel3 = 0;
            relWeight3 = 0;
        end

        if(iColIdx > 1)
            relPixel4 = mOutputImage(iRowIdx, (iColIdx - 1));
            relWeight4 = vRangeTable(round((refPixel - relPixel4) * RANGE_RESOLUTION) + RANGE_CENTER_IDX);
        else
            relPixel4 = 0;
            relWeight4 = 0;
        end

        weightsNormalizationFactor = PREDICT_NORMALIZATION_FACTOR / (relWeight1 + relWeight2 + relWeight3 + relWeight4);

        relWeight1 = relWeight1 * weightsNormalizationFactor;
        relWeight2 = relWeight2 * weightsNormalizationFactor;
        relWeight3 = relWeight3 * weightsNormalizationFactor;
        relWeight4 = relWeight4 * weightsNormalizationFactor;

        mOutputImage(iRowIdx, iColIdx) = mOutputImage(iRowIdx, iColIdx) - ((relWeight1 * relPixel1) + (relWeight2 * relPixel2) + (relWeight3 * relPixel3)+ (relWeight4 * relPixel4));

        vWeightsCoeff(weightsIdx:(weightsIdx + 3)) = [relWeight1; relWeight2; relWeight3; relWeight4];

    end
end

Just to clarify the variables:

mOutputImage is the image matrix.
numCols and numRows are the matrix dimensions.
vWeightsCoeff is the vector of the weights.

Since each pixel is related to 4 others yet working only on half the pixels its size is 2 times the number of pixels.

Now, the questions are:

Can I do something smart to go over the same pixels yet skip the first if which works like dividing the pixels as in chess board (White Black Board)?
Can I do something to avoid the if which secures I'm not stepping out of boundaries and yet go through the same pixels?

If someone comes which a completely different arrangement I will be open for that as well.


texts: Finding tuples of numbers subject to constraints

texts:
I just watched the video from "Think Like a Programmer, Episode 2: Puzzles & Problems".

The problem is:

  Assign number 1-7 to three departments in a city: Fire, Police,
  Sanitation.

  Requirement:

  Each department should have a unique number
  Police should be an even number
  Fire + Police + Sanitation = 12

  Generate a list of permutations for these department numbers.

Here is my Python attempt:

def valid_department_number(f, p, s):
    if (f != p != s) and (f+p+s == 12) and p % 2 == 0:
        return True
    else:
        return False

numbers = range(1, 8)

for f in numbers:
    for p in numbers:
        for s in numbers:
            if valid_department_number(f, p, s):
                print(f, p, s)

I searched the python documentation and found that I could use the permutations function from itertools:

import itertools

all_permutations = list(itertools.permutations(numbers, 3))

for each_p in all_permutations:
    f, p, s = each_p[0], each_p[1], each_p[2]
    if valid_department_number(f, p, s):
        print(each_p)

The permutation function gets rid of three levels of nested for loops. I'm wondering whether there's a better way to deconstruct the tuples from permutation generated list of tuples.


texts: Trigonometry Circle representation using Python and Pygame

texts:
I wrote this code using Python 3.5 and Pygame to help me learn more about sine waves. Its goal is to show the variations in the sine and cosine values in the Trigonometry Circle as the distance covered by a point in the circumference increases.

I'd appreciate suggestions and advices about the code, specially about the math involved and my usage of Pygame.

Thanks.

import pygame
import math

SCR_WIDTH = 220
SCR_HEIGHT = 480

RAD_SIZE = 100
CIRCLE_X = int(105)
CIRCLE_Y = int(285)

STD_FONT_SZ = 25

def drawChart(frequency, time, turns, sin, cos, surface):
    """Draws the frequency, time, distance, and sine and cosine values on the given surface"""

    freq_txt = font.render("Frequency: {:.3}Hz".format(frequency), False, (0,0,0))
    time_txt = font.render("Time: {:.3}s".format(time), False, (0,0,0))
    turn_txt = font.render("Turns: {:.3}".format(turns), False, (0,0,0))
    sin_txt = font.render("Sine: {:.3}".format(sin), False, (0,0,0))
    cos_txt = font.render("Cosine: {:.3}".format(cos), False, (0,0,0))

    surface.blit(time_txt,(0,0))
    surface.blit(freq_txt,(0,STD_FONT_SZ))
    surface.blit(sin_txt,(0,STD_FONT_SZ*2))
    surface.blit(cos_txt,(0,STD_FONT_SZ*3))
    surface.blit(turn_txt,(0,STD_FONT_SZ*4))

def drawCircle(x,y, surface):
    """Draws the Trigonometry circle on the given surface in position x, y"""

    pygame.draw.line(surface,(0,0,0),(x-RAD_SIZE,y),(x+RAD_SIZE,y))  #x-axis
    pygame.draw.line(surface,(0,0,0),(x,y-RAD_SIZE),(x,y+RAD_SIZE))  #y-axis
    pygame.draw.circle(surface,(0,0,0), (x,y), RAD_SIZE, 1) #main circle
    surface.blit(x_txt,(x+RAD_SIZE, y)) #x character
    surface.blit(y_txt,(x,y-RAD_SIZE-STD_FONT_SZ-4)) #y character

pygame.init()
pygame.display.set_caption("SineRep v. 1.0")

screen = pygame.display.set_mode((SCR_WIDTH, SCR_HEIGHT), 0, 32)
font = pygame.font.SysFont("arial",STD_FONT_SZ)

frequency = 0.1

x_txt = font.render("x", False, (0,0,0))
y_txt = font.render("y", False, (0,0,0))

while True:
    screen.fill((255,255,255))

    time = pygame.time.get_ticks()/1000
    distance = 2*math.pi*time*frequency
    turns = time*frequency
    cos = math.cos(distance)
    sin = math.sin(distance)

    #size of cosine and sine in pixels
    cos_pxl = int(cos*RAD_SIZE)
    sin_pxl = int(-sin*RAD_SIZE)

    ##### Draw stuff in the screen
    drawChart(frequency, time, turns, sin, cos, screen)
    drawCircle(CIRCLE_X, CIRCLE_Y, screen)

    pygame.draw.circle(screen,(255,0,0), (CIRCLE_X+cos_pxl,CIRCLE_Y+sin_pxl), 5, 0) #dot

    #Auxiliary shapes
    pygame.draw.circle(screen,(255,0,0), (CIRCLE_X+cos_pxl,CIRCLE_Y), 3, 1) #cosine dot
    pygame.draw.circle(screen,(255,0,0), (CIRCLE_X,CIRCLE_Y+sin_pxl), 3, 1) #sine dot

    pygame.draw.line(screen,(255,0,0),(CIRCLE_X,CIRCLE_Y),(CIRCLE_X+cos_pxl,CIRCLE_Y), 2)  #projection in x (cos)
    pygame.draw.line(screen,(255,0,0),(CIRCLE_X,CIRCLE_Y),(CIRCLE_X,CIRCLE_Y+sin_pxl),2) #projection in y (sine)

    event = pygame.event.poll()
    if event.type == pygame.QUIT:
        break

    pygame.display.update()

pygame.quit()


texts:
Is there a more efficient way of achieving the same result besides setting up a database?

# In reality, contains 4 million tuples.
stuff_tuple = (
    ('hello', 241, 1),
    ('hi', 243, 3),
    ('hey', 242, 2)
)

# Convert tuple to set for faster searching?
stuff_set = set(stuff_tuple)

# Only first two values are known ("hello", 241), ('hi', 243), etc.
for item in stuff_set:
    if item[0] == 'hello' and item[1] == 241:
        print item[2]


texts:
The user will input two numbers, say 19 and 5. We need to equally divide 19 equally into 5 groups and output the start index and the end index of each group (using zero-based indexes). Example:

  Grp 1: 0   1   2   3

  Grp 2: 4   5   6   7

  Grp 3: 8   9   10  11

  Grp 4: 12  13  14  15

  Grp 5: 16  17  18

The output should be

  Grp 1: 0   3

  Grp 2: 4   7

  Grp 3: 8   11

  Grp 4: 12  15

  Grp 5: 16  18

I have written the program. But I feel it is not good. Can you please tell me if there is any other way.

#include<stdio.h>
#define A 19
#define B 5
#define PER_ENTRY A/B
struct divide {
    int start;
    int end;
};
void calc_even(struct divide *div, int no)
{
    int remain = A % B ;
    int extra_add = 1;
    if (no > remain) {
        extra_add = 0;
    }
    static int priv_end = 0;
    if (no == 1) {
        div->start = 0;
        div->end = (PER_ENTRY - 1) + extra_add ;
    } else {
        div->start = priv_end + 1;
        if (no == B) {
            div->end = A - 1;
        } else {
            div->end = div->start + (PER_ENTRY - 1) +  extra_add ;
        }
    }
    priv_end = div->end;
}
int main()
{
    int i = 0;
    struct divide num_diff[B];

    for (i = 1 ; i <= B ; i++ ){
        num_diff[i-1].start = 0;
        num_diff[i-1].end = 0;
        calc_even(&num_diff[i-1], i);
    }
    for (i = 1 ; i <= B ; i++ ) {
        printf("Grp%d: %d %d \n", i, num_diff[i-1].start, num_diff[i-1].end);
    }
}

Can anyone tell me how the solution could be optimized?


texts: Singleton implementation of a database connection

texts:
I have implemented as follows, a class applying singleton pattern to get a global single access to database.
I intend to provide a thread-safe implementation.

using System.Data.SqlClient;

public sealed class Database
    {
        private static volatile SqlConnection instance;
        private static object syncRoot = new object();
        private const string connectionString = "Data Source=ServerName;" +
                                                "Initial Catalog=DataBaseName;" +
                                                "User id=UserName;" +
                                                "Password=Secret;";

        private Database() { }

        public static SqlConnection Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new SqlConnection(connectionString);
                    }
                }

                return instance;
            }
        }
    }


texts:
I'm trying to write a function that produces an infinite list containing strings of the form \$a^nb^nc^n\$.

My first idea was to do it using comprehensions.

f = [replicate n 'a' ++ replicate n 'b' ++ replicate n 'c' | n <-[0..]]

But this does a lot of duplicate work. I then decided it would be better to do the following

import Data.List

f = "" : (abc "")

abc s = string : (abc string)
        where string = sort $ "abc" ++ s

How can I do this more efficiently without having to sort and use ++ as frequently? Would changing to ByteStrings help?


texts:
Please critique my word frequency generator. I am a beginner programmer so any criticism are welcome.

Original Code: http://pastebin.com/rSRfbnCt

Here is my revised code after the feedback:

import string, time, webbrowser, collections, urllib2

def timefunc(function):
    def wrapped(*args):
        start = time.time()
        data = function(*args)
        end = time.time()
        timetaken = end - start
        print "Function: "+function.__name__+"\nTime taken:",timetaken
        return data
    return wrapped

@timefunc
def process_text(text_file):
    words = text_file.read().lower().split()
    words = [word.strip(string.punctuation+string.whitespace) for word in words]
    words = [word for word in words if word]#skips ''(None) elements
    return words

@timefunc
def create_freq_dict(wordlist):
    freq_dict = collections.Counter(wordlist)
    return freq_dict

@timefunc
def create_sorted_list(freqdict):
    sorted_list = [(value,key) for key,value in list(freqdict.items())]#list() provides python 3 compatibility
    sorted_list.sort(reverse=True)
    return sorted_list

@timefunc
def write_results(sorted_list):
    text_file = open('wordfreq.txt','w')
    text_file.write('Word Frequency List\n\n')
    rank = 0
    for word in sorted_list:
        rank += 1
        write_str = "[{0}] {1:-<10}{2:->10}\n".format(rank, word[1],word[0])
        text_file.write(write_str)
    text_file.close()

## The Brothers Grimm
## This file can be obtained from Project Gutenberg:
## http://www.gutenberg.org/cache/epub/5314/pg5314.txt
web_file = urllib2.urlopen('http://www.gutenberg.org/cache/epub/5314/pg5314.txt')

wordlist = process_text(web_file)
freqdict = create_freq_dict(wordlist)
sorted_list = create_sorted_list(freqdict)
results = write_results(sorted_list)

webbrowser.open('wordfreq.txt')

print "END"


texts: Dynamic programming solution for cross river algorithm (part 2)

texts:
I'm working on the cross river problem (previous post here). Any advice on performance improvement in terms of algorithm time complexity, code bugs or code style advice is appreciated.

More specifically, my idea is:

build a DP set to represent if we can reach a location by a certain speed;
when checking whether we are reach a certain location by a certain speed, we check if we can reach (1) location - speed with speed, (2) location - speed with speed + 1, (3) location - speed with speed - 1, if any (1), (2) or (3) is true, it means we can reach a certain location with such specific speed;
For the last location, (1) if it is not land, we will check if it could be reached by any speed, return True, (2) if it is not land, we will check if we can reach end position + 1 with any speed.

Problem

  Given a string representation of the rocks in the river e.g. "*****  *
  * * *  *  *", determine whether the river is crossable. Where,

* = landable
  = cannot land there

  Suppose Initial location: 0 and Initial speed: 0

in each step:
    1. choose a new speed from {speed, speed + 1, speed - 1} (but not negative)
    2. move speed spaces: loc += speed
    3. if I land on water, I fail
    4. if I land past end of river, I win
    5. otherwise, keep going

  For example, below river could be crossed by the first method. So, it
  should return True.

X~~~~~~~~~~~~~~~~~~~~~_______($)
*****  *   * * *  *  *
011 2  3   4   4  3  3   4 (crossed)
01 2 2 (failed)
01111 2 (failed)

def can_cross_river(river):
    # a set of tuple (position, speed), means we can reach
    # a specific position by a specific speed
    dp = set()
    dp.add((0,0))
    for i,v in enumerate(river):
        if i == 0 or v != '*':
            continue
        for speed in range(0,i+1):
            if (i-speed, speed) in dp or (i-speed, speed-1) in dp or (i-speed, speed+1) in dp:
                dp.add((i, speed))
                if i == len(river) - 1:
                    return True
    if river[-1] != '*':
        for speed in range(0,len(river)+1):
            if (len(river)-speed, speed) in dp or (len(river)-speed, speed-1) in dp or (len(river)-speed, speed+1) in dp:
                return True
    return False

if __name__ == "__main__":
    river = "*****  *   * * *  *  *" # should return True
    river = "* *" # should return False
    river = "******  " # should return True
    print can_cross_river(river)


texts:
I am trying to solve NGON problem. I am using bottom up dynamic programming here. Recurrence function is:

$$\begin{array}{rl}
    f(a,b) &= f(a-1,b) + f(a-1,b-1)\,a_i +\frac{f(a-1,b-2)\,a_i(a_i-1)}{2}, a>0,b>0 \\
    f(a,0) &= 1, \\
    f(0,b) &= 0, \\
\end{array}$$

\$a_i\$ being the points on \$a^{th}\$ side.

I have used a \$O(n^2)\$ algorithm. I can't think anything other algorithm asymptotically faster than this but this is still getting TLE on SPOJ may be due to heavy modulo and long long int calculations. Can you please help me optimize it or recommend a better algorithm (if any)?

#include<stdio.h>
#define MAX 1010
#define MODULO 1000000007

int main()
{
    int test_cases,i,a,b;
    int sides,points[MAX];
    unsigned long long int result[MAX][MAX],temp;
    for(scanf("%d",&test_cases);test_cases>0;test_cases--)
    {
        scanf("%d",&sides);
        for(i=0;i<sides;i++)
        {
            scanf("%d",&points[i]);
        }

        result[0][0]=1;
        for(a=1;a<=sides;a++)
        {
            result[a][0]=1;
        }
        for(b=1;b<=sides;b++)
        {
            result[0][b]=0;
        }

        for(a=1;a<=sides;a++)
        {
            for(b=1;b<=sides;b++)
            {
                result[a][b]=(result[a-1][b]+result[a-1][b-1]*points[a-1])%MODULO;
                if(b>1)
                {
                    temp=(result[a-1][b-2]*points[a-1]*(points[a-1]-1))%MODULO;
                    temp=temp/2;
                    result[a][b]=(result[a][b]+temp)%MODULO;
                }
            }
        }
        printf("%lld\n",result[sides][sides-1]);
    }
    return 0;
}


texts:
Here is my very first code which fetch data and add it to MySql. Please review my code and let me know if I'm on the right path. Is there anything I can improve?

postsData class = fetch and add data blog posts

categoriesData class = fetch and add data for categories of my blog. Ex: bmw, nissan, opel, ford, etc

connect.php

class dbh{

        private $host = "localhost";
        private $user = "root";
        private $pwd = "";
        private $dbname = "test_blog";

        public $conn;

        public function __construct()
        {
            $this->conn = $this->connect();
        }

        private function connect() {
            $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
            $pdo = new PDO ($dsn, $this->user, $this->pwd);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
            $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            return $pdo;

    }
}

func.class.php

  class postsData extends dbh{

    public function getPosts() {

        $sql = "SELECT * FROM posts_tbl";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll((PDO::FETCH_OBJ));

        return $result;

    }

    public function addPost($filter_author, $filter_title, $filter_txt) {

        $sql = "INSERT INTO posts_tbl (post_author, post_title, post_txt) VALUES (?, ?, ?)";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute([$filter_author, $filter_title, $filter_txt]);

    }

}

class categoriesData extends dbh{

    public function getCategories () {

        $sql = "SELECT * FROM categories_tbl";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetchAll((PDO::FETCH_OBJ));

        return $result;

    }

    public function adCategory ($filter_name, $filter_slug) {

        $sql = "INSERT INTO categories_tbl (category_name, category_slug) VALUES (?, ?)";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute([$filter_name, $filter_slug]);

    }

}

    //test
    $post = new PostsData();
    $posts = $post->getPosts();

    foreach ($posts as $post) {
        echo $post->post_title . '<br>';
    }


texts: Reading a .raw file while looking for .jpeg signatures

texts:
The code reads 512 bytes at a time and stores them in a buffer. When the code sees a .jpeg signature it will proceed by writing to a .jpeg file until another signature is found, thereafter the process repeats.

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

#define infile "card.raw"
#define BLOCK 512

/**
 * recover.c
 *
 * Computer Science 50
 * Problem Set 4
 *
 * Recovers JPEGs from a forensic image.
 */

// Declarations and prototype(s)
char * name();

FILE* outptr = NULL;
int increment = 0;

int main(void)
{

    // Open input file, plus error check
    FILE* inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        printf("Could not open %s.\n", infile);
        return 3;
    }

    // Allocate memory for one BLOCK and read from infile
    unsigned char * buffer = malloc(BLOCK);

    if (buffer == NULL)
        return 3;

    while (fread(buffer, BLOCK, 1, inptr) != 0) {

        /* Shall modify to operate on bitwise operations in the future. */

        // If the first four bytes of buffer is equal to a jpg file signature,
        // then copy all contents to a new jpg until another signature is found
        if (buffer[0] == 0xff &&
        buffer[1] == 0xd8 &&
        buffer[2] == 0xff &&
        buffer[3] >= 0xe0 && buffer[3] <= 0xef) {

            // If outptr does not yet refer to a file, close it
            if (outptr != NULL)
                fclose(outptr);

            // Open ###th output file, plus error-checking
            outptr = fopen(name(), "w");
            if (outptr == NULL) {
                fprintf(stderr, "Could not create outfile.\n");
                fclose(outptr);
                return 3;
            }

        }
        if (outptr != NULL)
            fwrite(buffer, BLOCK, 1, outptr);
    }
    // Check if the file was looped through correctly
    if ( !(feof(inptr)) )
        return 3;

    free(buffer);

    fclose(inptr);

    return 0;
}

// Name files incrementally starting from '000'
int filenum = 0;
char filename[7];

char * name()
{
    if (filenum < 10)
        sprintf(filename, "00%d.jpg", filenum);
    else
        sprintf(filename, "0%d.jpg", filenum);

    filenum++;
    return filename;
}


texts: Optimizing nested loop for calculating geodesic distance

texts:
I segmented an image into N superpixels and constructed a graph based on that in which each superpixel is considered as a node. The information about neighbor superpixels is stored in glcms array. The weight between each pair of neighboring superpixels is stored in matrix W.

Finally, I want to compute geodesic distance between non-adjacent superpixels using graphshortestpath function. The following code does the mentioned process, however it is very time-consuming. Specifically, the last section of the code that computes geodesic distance takes more time than expected (more than 15 sec).

    Img=imread('input.jpg');
    [rows, columns, numberOfColorChannels] = size(Img);
    [L,N] = superpixels(Img,250);

    %Identifying neighborhood relationships
    glcms = graycomatrix(L,'NumLevels',N,'GrayLimits',[1,N],'Offset',  [0,1;1,0]); %Create gray-level co-occurrence matrix from image
    glcms = sum(glcms,3);    % add together the two matrices
    glcms = glcms + glcms.'; % add upper and lower triangles together, make it symmetric
    glcms(1:N+1:end) = 0;    % set the diagonal to zero, we don't want to see "1 is neighbor of 1"

    data = zeros(N,3);
    for labelVal = 1:N
    redIdx = idx{labelVal};
    greenIdx = idx{labelVal}+numRows*numCols;
    blueIdx = idx{labelVal}+2*numRows*numCols;
    data(labelVal,1) = mean(Img(redIdx));
    data(labelVal,2) = mean(Img(greenIdx));
    data(labelVal,3) = mean(Img(blueIdx));

    end

   Euc=zeros(N);
% Euclidean Distance
for i=1:N
    for j=1:N
        if glcms(i,j)~=0
            Euc(i,j)=sqrt(((data(i,1)-data(j,1))^2)+((data(i,2)-data(j,2))^2)+((data(i,3)-data(j,3))^2));
        end
    end
end

W=zeros(N);
W_num=zeros(N);

W_den=zeros(N);
OMG1=0.1;
for i=1:N
    for j=1:N
        if(Euc(i,j)~=0)
         W_num(i,j)=exp(-OMG1*(Euc(i,j)));
         W_den(i,i)=W_num(i,j)+W_den(i,i);
        end
    end
end

for i=1:N
    for j=1:N
         if(Euc(i,j)~=0)
             W(i,j)=(W_num(i,j))/(W_den(i,i));   % Connectivity Matrix W

         end
    end
end

s_star_temp=zeros(N);   %temporary variable for geodesic distance measurement
W_sparse=zeros(N);
W_sparse=sparse(W);
for i=1:N
    for j=1:N
        if W(i,j)==0 & i~=j;
            s_star_temp(i,j)=graphshortestpath(W_sparse,i,j); % Geodesic Distance
        end
    end
end

The question is how to optimize the code to be more efficient , i.e. less time-consuming.


texts:
Description:

  Huffman coding assigns variable length codewords to fixed length input
  characters based on their frequencies. More frequent characters are
  assigned shorter codewords and less frequent characters are assigned
  longer codewords. A Huffman tree is made for the input string and
  characters are decoded based on their position in the tree. We add a
  '0' to the codeword when we move left in the binary tree and a '1'
  when we move right in the binary tree. We assign codes to the leaf
  nodes which represent the input characters.

  You have to decode an encoded string using the Huffman tree.

  You are given pointer to the root of the Huffman tree and a binary
  coded string. You need to print the actual string.

Code:

void decode(String S ,Node root)
    {
        if (root == null) return;
        StringBuilder sb = new StringBuilder();
        int pos = 0;
        Node current = root;
        char[] chars = S.toCharArray();
        while (pos < chars.length) {
            char c = chars[pos];
            if (c == '0' && current.left != null) {
                current = current.left;
            }
            else if (c == '1' && current.right != null) {
                current = current.right;
            }
            if (current.left == null && current.right == null) {
                sb.append(current.data);
                current = root;
            }
            pos++;
        }
        System.out.print(sb.toString());
    }


texts: Simple asynchronous echo server using yield's and deferred's

texts:
I am trying to understand how we can use generator based coroutines to write asynchronous code in a sequential style without using any of the new features in Python so that the fundamental idea is clear.

Is this approach fine? One thing I can probably improve upon is the idea of using other coroutines. Is there any feedback on this code?

#!/usr/bin/python

import socket
import selectors

select = selectors.DefaultSelector()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

hostname = socket.gethostname()

print("Server starting on port 9000")

s.bind((hostname, 9000))

s.listen(5)

# library starts here

class Deferred(object):

    def __init__(self):
        self.state = "pending"
        self.value = None
        self.task = None

    def done(self, value):
        self.state = "complete"
        self.value = value
        if self.task:
            self.task(value)

    def future(self, task):
        if self.state == "complete":
            self.task(value)
        else:
            self.task = task

def watch(fd, event):
    deferred = Deferred()
    select.register(fd, event, deferred.done)
    return deferred

def unwatch(fd):
    select.unregister(fd)

def run_till_complete(g):
    try:
        d = g.send(None)
        d.future(lambda value: run_till_complete(g))
    except StopIteration:
        pass

# library ends here

# application starts here

def handle_client(s):
    c, a = s.accept()
    message = "Connection recieved from %s" % str(a)
    print(message)
    run_till_complete(echo_client(c))

select.register(s, selectors.EVENT_READ, handle_client)

def echo_client(c):
    while True:
        yield watch(c, selectors.EVENT_READ)
        unwatch(c)
        r = c.recv(1024)
        yield watch(c, selectors.EVENT_WRITE)
        unwatch(c)
        c.send(bytes(r))

# application ends here

# event loop starts here

try:
    while True:
        events = select.select()
        for key, mask in events:
            callback = key.data
            callback(key.fileobj)
except KeyboardInterrupt:
    print(" recieved")
finally:
    print("Server stopping on port 9000")
    select.unregister(s)
    s.close()

# event loop ends here

A simple client looks like this:

#!/usr/bin/python

import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

hostname = socket.gethostname()

client_socket.connect((hostname, 9000))

chunks = []

while True:
    message = bytes(input("Message: "), 'utf-8')
    client_socket.send(message)
    print(client_socket.recv(1024))


texts:
I have asked a question on how to make a CLI calculator accept infinite numbers until you specify that you want the answer. Now I have figured out how to do it, but I do really want to know how can I improve my code.

package ribchinski;

import java.util.Scanner;

public class Calculator {
    public static double answer;
    public static Scanner in = new Scanner(System.in);
    public static boolean done = false;

    public static void main(String[] args) {

        System.out.println("Enter your expression:");
        System.out.println("Num: ");
        double firstNum = in.nextDouble();
        in.nextLine();

        while (!done) {
            System.out.println("Operator: ");
            String operand = in.nextLine();

            if (operand.equals("=")) {
                break;
            }
            System.out.println("Num: ");
            double secondNum = in.nextDouble();
            in.nextLine();

            calculate(firstNum, operand, secondNum);
            firstNum = answer;
        }
        System.out.println("Answer: " + answer);
    }

    public static void calculate(double num1, String equ, Double num2) {

        switch (equ) {

        case ("+"):
            answer = (num1 + num2);
            break;

        case ("-"):
            answer = (num1 - num2);
            break;

        case ("*"):
            answer = (num1 * num2);
            break;

        case ("/"):
            answer = (num1 / num2);
            break;
        }
    }
}

Any comments on this would be helpful!


texts:
I wrote this code so I could figure out the number of molecules within a plasmid and an insert of DNA. I then get the amount of insert DNA I would need to use (in uL) for a ligation with the DNA at different insert ratios and dilutions.

How can I clean up this code? It works correctly. However, I feel like I typed this out all the extremely long way and I would love to know how to make this more performant.

In my next project I would like to not have to type all of these out. I imagine that I am missing some functions or loops. I am still a very new beginner and this is my first project outside of a classroom.

print "Please put the amount of BPs: "
number = int(raw_input())
solution = (number * 660)
Avo = (6.022 * (10 ** 23))
Grams_Avo = ( solution / Avo)
print "Put in Concentration (ng/ul): "
conc = float(raw_input())
multiple = (10 ** -9)
amount = (conc * multiple)
total = float(amount / Grams_Avo)
print "Amount of molecules:  %s" % total

print "Amount of ul used by the plasmid: "
plasmid = float(raw_input())
particles = float(plasmid * total)
print "What ratio amount will you use?: "
ratio = int(raw_input())
molecules_needed = float(particles * ratio)
print molecules_needed

print "Conc. of your oligo?: "
oligo = float(raw_input())
oligo_num = float(oligo * multiple) # amount
print "Enter number of G in Oligo: "
G = int(raw_input())
print "Enter number of A in Oligo: "
A = int(raw_input())
print "Enter number of T in Oligo: "
T = int(raw_input())
print "Enter number of C in Oligo: "
C = int(raw_input())
sumG = (G * 329)
sumA = (A * 313)
sumT = (T * 304)
sumC = (C * 289)
daoligo = (sumG + sumA + sumT + sumC) # g/mol

print "Total amount of your insert %s" % daoligo

oligototal = float(oligo_num / (daoligo/Avo)) # molecules for insert
complete = float(molecules_needed/oligototal) #amount of insert needed from stock ul

print "What dilution will you use?"
print "1. Stock"
print "2. 1:10"
print "3. 1:20"
print "4. 1:30"
print "5. 1:50"
code = float(raw_input())
if code == 1:
    print complete #stock
elif code == 2:
    code2 = (oligototal/10)
    complete1 = float(molecules_needed/code2)
    print complete1 #1:10
elif code == 3:
    code3 (oligototal/20)
    complete2 = float(molecules_needed/code3)
    print complete2 #1:20
elif code == 4:
    code4 = (oligototal/30)
    complete3 = float(molecules_needed/code4)
    print complete3 #1:30
elif code == 5:
    code_5 = (oligototal/50)
    complete4 = float(molecules_needed/code_5)
    print complete4 #1:50


texts:
I'm trying to learn how to structure my jQuery code better. I'm only about a week into jQuery so if something looks way off please tell me. I'm attempting to use object literals and it appears to work ok, but I am wondering if there is possibly a better way to structure my code.

var application = {
    wrapper: $('#wrapper'),
    addButton: $('#add'),
    init: function() {
        this.addButton.click(this.buttonHandlers.clickHandler);
        this.wrapper.on("contextmenu", "#wrapper div", this.buttonHandlers.contextMenuHandler);
    },
    buttonHandlers: {
        clickHandler: function(e) {
            console.log("clickyHandler");
        },
        contextMenuHandler: function(e) {
            console.log("right click");
            return false;
        }
    }
};

application.init();


texts:
Is there any way I could make this code more efficient?

def processOrder(quantity, item_list):
    global total
    if quantity > item_list[2]:
        print("There is not enough stock!")
        pass
    else:
        total += item_list[1] * quantity
        item_list[2] -= quantity

total = 0
A = ["Big Mac", float(2.50), 50], ["Large Fries", float(0.50), 200], ["Vegetarian Burger", float(1.00), 20]

print("Welcome to McDonald's")
print("[1]", A[1][0:2],
      "\n[2]", A[1][0:2],
      "\n[2]", A[1][0:2])

while True:
    choice, quantity = (input("\nWhat would you like?\n")).upper(), int(input("\nHow many would you like?\n"))

    if choice == "BIG MAC":
        processOrder(quantity, A[0])
    elif choice == "LARGE FRIES":
        processOrder(quantity, A[1])
    elif choice == "VEGETARIAN BURGER":
        processOrder(quantity, A[2])
    else:
        print("Invalid Item")

    more_items = (input("Do you want to order more items?")).lower()
    if more_items == "yes":
        pass
    else:
        break

print("Thank you for ordering!\nYour total cost is: £" +  str(total))


texts: Using VBA to "apply names" to named range references

texts:
So there's a known bug in excel where applying named ranges via ribbon doesn't work properly (for 2010 and 2013 and possibly 2016). There was a question about it on superuser - Apply names in excel bugged?. I took a shot at it.

This code will find all of the named ranges in the book and then search a specified range for any cells that have formulas containing a reference tied to the named range's address and replace that with the named range.

This does that, but only works for absolute references when searching as I couldn't figure out a simple way to get the named range's relative reference.

I guess I'm wondering if there's a better way to do this (maybe with a dictionary so I don't need two loops?) and also capture the relative references. Or if there are any properties I didn't use that will do what I want.

Option Explicit
Sub FixNames()

Dim ClctNames As Variant
Set ClctNames = ActiveWorkbook.Names

Dim rngName As String
Dim rngNameLoc As String
Dim strFrmla As String

Dim c As Range
Dim n As Integer

'Define as needed
Dim srchRng As Range
Set srchRng = ActiveSheet.UsedRange

'For each name (n) in the collection
For n = 1 To ClctNames.Count

    'I'm storing the Named Range's name and address as strings to use below
    rngName = ClctNames(n).Name
    rngNameLoc = ClctNames(n).RefersToRange.Address

    '--Should I break this out into a function? If so, at what point?
    For Each c In srchRng
        'We only want to test cells with formulas
        If c.HasFormula = True Then
           'We have to check if the cell contains the current named range's address
           If InStr(1, c.Formula, rngNameLoc, vbTextCompare) <> 0 Then
              'Since these are perfect matches, no need to look for length or location, just replace
              strFrmla = Replace(c.Formula, rngNameLoc, rngName)
              c.Formula = strFrmla
           End If
        End If
    Next
Next

'No error handling should be needed

End Sub


texts: Implementing numerical integration in Python

texts:
I have this Python code that implements a rectangular numerical integration. It evaluates the (K-1)-dimensional integral for arbitrary integer \$K \geq 1\$

$$\int_{u_K = 0}^{\gamma}\int_{u_{K-1} = 0}^{\gamma-u_K}\cdots\int_{u_2}^{\gamma-u_K-\cdots-u_3}F_U(\gamma-\sum_{k=2}^Ku_k)f_U(u_2)\cdots f_U(u_K)\,du_2\cdots du_K$$

where \$F_U\$ corresponds to the cdf function in the code, and \$f_U\$ to the pdf. I implemented it using recursion as follows:

    #************************** Import necessary libraries******************************************
import numpy as np
import matplotlib.pyplot as plt
import time
#******************************Set the constant scalars and vectors***************************
start_time = time.time()
KU = 3
eta_dB = 3
eta = 10**(eta_dB/10)
ExpanF = 50

tdB = np.arange(-5,11,4)
tVec = 10**(tdB/10)
thVec = (tVec/eta)*(ExpanF-eta*(KU-1))

N = 10000 # For simulation

du = 0.01

#******************************Define functions to be used***************************************
#Define the CDF of U
def CDF(u):
      return 1-1/(u+1)

#Define the PDF of U
def pdf(u):
     return 1/((1+u))**2

def FK(h, k):
    #print(f'h is {h}, and k is {k}')
    if k == 1:
        res = CDF(h)
    else:
        #n_iter = int(h/du)
        res =  0
        u = 0
        while u < h:
            res += FK(h-u, k-1)*pdf(u)*du
            u += du
    return res

#*******************Find the numerical and simulation values of the integral******************
ResultNum = []
ResultSim = []

if (ExpanF-eta*(KU-1)) > 0:
    for t in thVec:
    # Numerical
        ResultNum.append(1-FK(t, KU))
    # Simulation
        count = 0
        for n in range(0, N):
            if np.sum(np.random.exponential(1, (1, KU))/np.random.exponential(1, (1, KU))) <= t:
                count += 1
        ResultSim.append(1-count/N)

The parameter du is the resolution of the numerical integral, and the smaller, the more accurate the numerical approximation is. However, decreasing du comes at the expense of more computational time using the above code. For example I tried to run the above code on my machine Intel i5 @2.5 GH with 6 GB of RAM for du=0.0001, and it took 15 hours and didn't finish, at which case I had to abort it.

Is there anyway the above code can be optimized to run significantly faster? I tried C++, and I got a 30x speed factor using the same code and algorithm, but I was wondering if I can get a similar or better speed up factor in Python.


texts: Array duplicate removal for duplicates exceeding `N`-number

texts:
I recently encountered a front-end interview coding challenge question that required one to create a function which returned an array that excluded numbers that occurred more than n-number of times (i.e. duplicate-removal).  In this example it was all numbers repeated >= three (3) times.  I managed to submit an answer, but admittedly struggled solving it.
I am looking for any feedback / suggestions on how to make it more concise and efficient (the for loop inside the forEach method is especially repulsive).
Here is what I came up with:

// Remove duplicates that occur 3 or more times in an array
// keeping unique values and those with less than 3
function removeMany(arr) {
  const newArr = Array.from(arr).sort()
  let count = 0;
  let result = []

  newArr.forEach((value, index, ar) => {
    count += 1;
    // refactored afterwards from (ar[index + 1] !== value)
    if (ar.lastIndexOf(value) <= index && count <= 2) {
      for (var i = 0; i < arr.length; i++) {
        if (arr[i] === value) {
          result.push(arr[i])
        }
      }
      count = 0
    } else if (ar[index + 1] !== value) {
      count = 0;
    }
  });

  // +1 is there anyway to return a result that mimicks the original order of `numbers`?
  return result;  // [1, 2, 2, 3, 4, 4]
}

// Ex. 1
const numbers = [1, 2, 3, 2, 4, 4, 5, 5, 5, 5];
console.log(removeMany(numbers));


texts:
I have to create a website in Classic ASP, and I really want to do a clean design so I will try to put everything in Classes and Models to emulate the ViewModel Pattern.

So can you tell me if this approach of creating objects is good because I will use it everywhere

Class User
    Public Name
    Public Adress
    Public Title
    Public Text
    Public Rights 'ArrayList of Right objects

    Private Sub Class_Initialize()
       Initialize
    End Sub

    Private Sub Class_Terminate()
       Dispose
    End Sub

   Private Sub Initialize()
       Name    = ""
       Adress  = ""
       Title   = ""
       Text    = ""
       Set Rights = Server.CreateObject("System.Collections.ArrayList") ' Arraylist .net
   End Sub

   Private Sub Dispose()
   End Sub

End Class

Class Right

    Public Name

    Private Sub Class_Initialize()
        Initialize
    End Sub

   Private Sub Class_Terminate()
       Dispose
   End Sub

   Private Sub Initialize()
       Name    = ""
   End Sub

   Private Sub Dispose()
   End Sub
End Class

And then I do this for instantiating objects :

Dim myUser
Set myUser = New User

'Do some work

Set myUser = nothing 'Dispose the object

Any idea, suggestion or correction is welcome.


texts: Showing a "back-to-top"-button after scrolling a certain amount

texts:
I have a "back to top"-button on the page, It should be visible after the user has scrolled a certain amount*.

This means I have to add or remove a class active every now and then.

I have two solutions:

Update the class on every scroll.
Test whether the class is set/ not et and then test, whether it is necessary to interact.

The setup:

this.button = document.querySelector('.some-class');

window.addEventListener('scroll', event => {
  this.onScroll(event);
});

The long version, which does add or remove the class only if needed:

onScroll(event) {
  if (
    !this.button.classList.contains('active') &&
    (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100)
  ) {
    this.button.classList.add('active');
  }

  if (
    this.button.classList.contains('active') &&
    (document.body.scrollTop <= 100 || document.documentElement.scrollTop <= 100)
  ) {
    this.button.classList.remove('is-active');
  }
}

The alternativ short version, that adds or removes the class everytime:

onScroll(event) {
  if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
    this.button.classList.add('active');
  } else {
    this.button.classList.remove('active');
  }
}

My questions are:

Does the longer version have a better performance?
Does the browser optimize it itself – i.e. in the short version if the class is already present, it doesn't repaint?

* For simplicity this value is hard-coded here. It's a variable in the implemented version.


texts: String search algorithm for finding if a long list of long strings string exists in a similarly sized haystack

texts:
My use case is that I have a list of emails and I need to find if the email is in the chain:

emails = [
    ['    RE: I just got your test || This is a top level email roughly 300+ words in length on average'],
    ['RE:RE: Something | RE: Something | This is another entirely distinct email that is the top level'],
    ['RE: FooBar | A third email that is entirely distinct']
    ... #performance issues start occurring with emails growing to > 50 items
]

Now I would search for an email which is a reply:

test_email = """
A third email that is entirely distinct
"""

Currently I am using a KMP type search but I believe this is inefficient because it searches for multiple copies of the needle. I also believe the in operator is inefficient because it is using the niave method of searching the string.

An implementation of KMP in python I found and modified slightly:

class KMP:
    @classmethod
    def partial(self, pattern):
        """ Calculate partial match table: String -> [Int]"""
        ret = [0]

        for i in range(1, len(pattern)):
            j = ret[i - 1]
            while j > 0 and pattern[j] != pattern[i]:
                j = ret[j - 1]
            ret.append(j + 1 if pattern[j] == pattern[i] else j)
        return ret

    @classmethod
    def search(self, T, P):
        """
        KMP search main algorithm: String -> String -> [Int]
        Return all the matching position of pattern string P in S
        """
        partial, ret, j = KMP.partial(P), [], 0

        for i in range(len(T)):
            while j > 0 and T[i] != P[j]:
                j = partial[j - 1]
            try:
                if T[i] == P[j]: j += 1
            except:
                return False
            if j == len(P):
                return True
        return False

Used here:

for choice in choices: #choice[0] is email in the reply chain
    if current_email == choice[0]:
        incident_type = choice[1]
        break
    elif len(current_email) > len(choice[0]):
        if KMP.search(current_email, choice[0]):
            incident_type = choice[1]
            break
    else:
        if KMP.search(choice[0], current_email):
            incident_type = choice[1]
            break

Should I fix this implementation or scrap it in favor of another algo?


texts: How to determine the order of letters by regex?

texts:
I want to write a regular expression to determine whether a given string is uppercase and sorted in non-descending order.

^A*B*C*D*E*F*G*H*I*J*K*L*M*N*O*P*Q*R*S*T*U*V*Q*X*Y*Z*$

I was just wondering if it is possible to improve the above regex.

Examples of correct strings:

  AEHIIEFKLZ

Examples of wrong strings:

  AbCDE YABKL


texts:
The task
is taken from leetcode

  In a array A of size 2N, there are N+1 unique elements, and exactly
  one of these elements is repeated N times.

  Return the element repeated N times.

  Example 1:

  Input: [1,2,3,3] Output: 3

  Example 2:

  Input: [2,1,2,5,3,2] Output: 2

  Example 3:

  Input: [5,1,5,2,5,3,5,4] Output: 5

  Note:

  4 <= A.length <= 10000 0 <= A[i] < 10000 A.length is even

My solution

var repeatedNTimes = function(A) {
    const set = new Set();
    for (const n of A) {
        if (set.has(n)) { return n; }
        set.add(n);
    }
};

I didn't do much with the information size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. I think these information is not needed to solve the problem efficiently. I also wonder whether there is a bitwise or purely math based solution to the task.


texts:
What is the best way to move _add and _preorder methods in class Node to add_node and preorder methods in class BinaryTree such that they have the below class structure:

class Node:
    __init__
    __repr__

class BinaryTree:
    __init__
    add_node
    preorder

Complete Code::

class Node(object):

    def __init__(self, item, left=None, right=None):
        self.item = item
        self.left = None
        self.right = None

    def __repr__(self):
        return '{}'.format(self.item)

    def _add(self, value):
        new_node = Node(value)

        if not self.item:
            self.item = new_node
        elif not self.left:
            self.left = new_node
        elif not self.right:
            self.right = new_node
        else:
            self.left = self.left._add(value)
        return self

    def _preorder(self):
        print(self.item)
        if self.left:
            self.left._preorder()
        if self.right:
            self.right._preorder()

class BinaryTree(object):

    def __init__(self):
        self.root = None

    def add_node(self, value):
        if not self.root:
            self.root = Node(value)
        else:
            self.root._add(value)

    def preorder(self):
        if self.root:
            return self.root._preorder()

if __name__ == '__main__':

    binary_tree = BinaryTree()
    print( "Adding nodes 1 to 10 in the tree...")
    for i in range(1, 11):
        binary_tree.add_node(i)

    print()
    print( "Printing preorder...")
    binary_tree.preorder()


texts:
As I've described in a StackOverflow question, I'm trying to fit a NumPy array into a certain range.

Here is the solution I currently use:

import numpy as np

def scale_array(dat, out_range=(-1, 1)):
    domain = [np.min(dat, axis=0), np.max(dat, axis=0)]

    def interp(x):
        return out_range[0] * (1.0 - x) + out_range[1] * x

    def uninterp(x):
        b = 0
        if (domain[1] - domain[0]) != 0:
            b = domain[1] - domain[0]
        else:
            b =  1.0 / domain[1]
        return (x - domain[0]) / b

    return interp(uninterp(dat))

print(scale_array(np.array([-2, 0, 2], dtype=np.float)))
# Gives: [-1., 0., 1.]
print(scale_array(np.array([-3, -2, -1], dtype=np.float)))
# Gives: [-1., 0., 1.]

Is there a way to make this code cleaner? Is there a built-in function in NumPy or scikit-learn? This feels like a really common data pre-processing step and it feels weird that I keep re-implementing it.


texts:
Description:

Given a linked list reverse it and return the new head.

Code:

class Main {
  static class Node {
    public int data;
    public Node next;

    Node(int data) {
      this(data, null);
    }

    Node(int data, Node next) {
      this.data = data;
      this.next = next;
    }

    // Just a helper method, not optimised
    Node append(int data) {
      Node newNode = new Node(data, null);
      Node current = this;

      while (current.next != null) {
        current = current.next;
      }
      current.next = newNode;
      return this;
    }
  }
  // 10 -> 20 -> 30
  // 10    20 -> 30
  // 10 <- 20 -> 30
  //       c     n
  // 10 <- 20 <- 30
  public static Node reverse(Node head) {
    if (head == null || head.next == null) {
      return head;
    }

    Node prev = null;
    Node curr = head;
    Node next = null;

    while (curr != null) {
      next = curr.next;
      curr.next = prev;
      prev = curr;
      curr = next;
    }

    return prev;
  }

  public static void main(String[] args) {
    Node head = new Node(10)
        .append(20)
        .append(30)
        .append(40);

    Node newHead = reverse(head);
    System.out.println(newHead); // 40 30 20 10
  }
}

Question:

The idea is quite simple i.e. we need to go one by one and we need to reverse the link, for this we need three pointers but I really struggled to put the idea into code. I know that understanding about invariants can help
to write code in a more robust way. How can I help form invariants in this situation to improve the logic?


texts: A simple decorator written as a class, which counts how many times a function has been called

texts:
Can I improve its typing? Is there any other improvement or pythonic change that you would do?

F = TypeVar('F', bound=Callable[..., Any])

# This is mostly so that I practice using a class as a decorator.
class CountCalls:
    """Logs to DEBUG how many times a function gets called, saves the result in a newly created attribute `num_calls`."""
    def __init__(self, func: F) -> None:
        functools.update_wrapper(self, func)
        self.func = func
        self.num_calls: int = 0
        self._logger = logging.getLogger(__name__ + '.' + self.func.__name__)
        self.last_return_value = None

    def __call__(self, *args: Any, **kwargs: Any) -> Any:
        self.num_calls += 1
        self._logger.debug(' called %s times', self.num_calls)
        self.last_return_value = self.func(*args, **kwargs)
        return self.last_return_value

Here's the decorator in action:

>>> @CountCalls
... def asdf(var: str):
...     print(var)
...     return len(var)
...
>>> asdf('Laur')
Laur
4
DEBUG:__main__.asdf: called 1 times
>>> asdf('python 3')
DEBUG:__main__.asdf: called 2 times
python 3
8
>>> asdf(3)
DEBUG:__main__.asdf: called 3 times
3
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:/Projects/Python/he/src/he/decorators.py", line 156, in __call__
    self.last_return_value = self.func(*args, **kwargs)
  File "<input>", line 4, in asdf
TypeError: object of type 'int' has no len()
>>> asdf.num_calls
3


texts:
Consider the following piece of code.

public static String[] choosePatterns(int total, int toChoose, int numOfPatterns1) {
    String[] patterns = new String[numOfPatterns1];
    int x = 0;
    StringBuilder data = new StringBuilder("");
    List<Integer> indices = IntStream.range(1, toChoose + 1).mapToObj(i -> Integer.valueOf(0)).collect(Collectors.toList());
    resetIndex(indices, 0, 1, total);
    while (true) {

        for (Integer i = 1; i <= total; i++) {
            if (! indices.contains(Integer.valueOf(i))) {
                data.append(i.toString());
            }
        }
        patterns[x++] = data.toString();
        data = new StringBuilder("");

        if (! incrementIndices(indices, indices.size() - 1, total)) {
            break;
        }
    }
    return patterns;
}

public static boolean resetIndex(List<Integer> indices, int posn, int value, int total) {
    if (value <= total) {
        indices.set(posn, value);
        return posn == indices.size() - 1 ? true : resetIndex(indices, posn + 1, value + 1, total);
    } else {
        return false;
    }
}

public static boolean incrementIndices(List<Integer> indices, int posn, int total) {
    if (indices.get(posn) < total) {
        indices.set(posn, indices.get(posn) + 1);
    } else {
        int resetPosn = posn;
        do {
            if (resetPosn-- == 0) return false;
        } while (! resetIndex(indices, resetPosn, indices.get(resetPosn) + 1, total));
    }
    return true;
}

Now, this currently prints out all the remanants of a choose operation on a piece of data. For instance, if I call the method as choosePatterns(4,1, 4) then it will print 234, 134, 124, 123. Similarly, if it was choosePatterns(4,2, 6), then it will print all the possibilities when two data points are removed in the string.

First and foremost, is there a way to generalize this function so that I can input any type of data and output the combination patterns on that? For instance, instead of 1234 being permuted and removed in different ways, what if my original data was ABCD? I am having a hard time being able to alter this method.

Secondly, are there ways to optimize these methods so it runs in the faster time possible?


texts: Implementation in Azure Blob Function Trigger for Insert into Database

texts:
I have created Azure Blob Trigger function. If file is inserted in Azure Blob Container at that time this function is trigger and based on that file data we need to insert into our database table.
My Trigger Function Class be like below
public static class StockCountTrigger
{
    [FunctionName("StockCountTrigger")]
    public static void Run([BlobTrigger("importstockcount/{name}", Connection = "AzureWebJobsStorage")] CloudBlockBlob cloudBlockBlob, TraceWriter log)
    {
        try
        {
            log.Info($"FileName:{cloudBlockBlob.Name}");
            var environment = Constants.Environment;
            IStockCountService stockCountService;
            if (environment.IsIn(Helper.Environment.Client1))
            {
                stockCountService = new StockCountServiceClient1(cloudBlockBlob, log);
            }
            else
            {
                throw new NotImplementedException();
            }
            stockCountService.Import();
        }
        catch (Exception ex)
        {
            log.Error($"Error.", ex);
            throw ex;
        }
    }
}

same function is use for multiple client with different file format and that data is inserting into StockCount table.
my service be like below
public class StockCountServiceClient1: IStockCountService
{
    private readonly CloudBlockBlob cloudBlockBlob;
    private readonly TraceWriter log;
    private readonly IStockCountRepository _stockCountRepository;
    public StockCountServiceClient1(CloudBlockBlob cloudBlockBlob, TraceWriter log)
    {
        this.cloudBlockBlob = cloudBlockBlob;
        this.log = log;
        _stockCountRepository = new StockCountRepository();
    }

    public void Import()
    {
        var stockCounts = GetFromCSV();
        if (!stockCounts.Any())
            return;

        log.Info($"Total Records:{stockCounts.Count}");
        _stockCountRepository.Insert(stockCounts);
    }

    private List<StockCountModel> GetFromCSV()
    {
        using (var stream = cloudBlockBlob.OpenRead())
        {
            TextReader reader = new StreamReader(stream);
            using (var csvReader = new CsvReader(reader))
            {
                var records = csvReader.GetRecords<dynamic>().ToList();
                return records.Select(x => new StockCountModel
                {
                    StoreNo = x.StoreNo,
                    ArticleNo = x.ArticleNo,
                    Quantity = x.Quantity,
                    StockDateTime = x.StockDateTime,
                    Reference = cloudBlockBlob.Name
                }).ToList();
            }
        }
    }
}

Here in repository i have created object and insert into database.
here my question is that Function class is static and its method Run is also Static. Is it right way written code to create repository and object and based on environment assign instance to it.
which approach is best is need to create static method in repository also ?
Frequency of file coming is every 10 minutes in container.


texts: batch progress visualization In React.js

texts:
I am slowly digesting React.js, found couple of ways to write the same piece of code:
Please tell where all I went wrong in below code.

I try to put logic inside render(), is that Ok?
Not using React life cycles for simple components?
Use Functional components instead of class components?

File 1: batch_progress.js

Description: Shows batch progress, expects 3 values:

current batch.
target batch count.
state of the batch (based on which the progress bar color changes).

import React, { Component } from 'react';
import ProgressBar from '../progress_bar/progress_bar';

export default class BatchStatus extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    let color;
    let percentage = (this.props.batch.number / this.props.targetBatchCount) * 100;

    switch (this.props.batch.status) {
      case 100:
        color = '#e7e4f1';
        break;
      case 200:
        color = '#c3dcec';
        break;
      case 300:
        color = '#ecc6eb';
        break;
      case 400:
        color = '#ecdec3';
        break;
      case 500:
        color = '#c8ecc7';
        break;
      default:
        color = '#e7e4f1';
    }

    return (
      <ProgressBar foregroundColor={color} percentage={percentage}>
        {this.props.batch.number}&nbsp;/&nbsp;{this.props.targetBatchCount}
      </ProgressBar>
    );
  }
}

File 2: progress_bar.js

import React, { Component } from 'react';
import './progress_bar.css';

export default class ProgressBar extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    let foregroundColor = this.props.foregroundColor || '#e7e4f1';
    let percentage = this.props.percentage || 0;
    let backgroundColor = this.props.backgroundColor || '#eceeef';

    let style = {
      backgroundImage:
        'linear-gradient(to right, ' +
        foregroundColor +
        ' ' +
        percentage +
        '%, ' +
        backgroundColor +
        ' 0%)'
    };

    return (
      <div className="progress-bar-container" style={style}>
        {this.props.children}
      </div>
    );
  }
}


texts:
I implemented Quicksort in JavaScript. I'm trying to follow the best principles in JavaScript. In Ruby when you declare classes your able to use private  for the methods that are private. I don't think there is anything like that in JavaScript.
class QuickSort {
  sort(a) {
    a = this.shuffle(a); //Shuffling is needed for perfomance guarantee.
    this.privateSort(a,0, a.length - 1)
    return a;
  }

  privateSort(a, lo, hi) {
    if(hi <= lo) { return }
    let j = this.partition(a, lo, hi);
    this.privateSort(a, lo, j - 1)
    this.privateSort(a, j + 1, hi)
  }

  partition(a, lo, hi) {
    let i = lo;
    let j = hi + 1;
    let v = a[lo];

    while (true) {
      while (a[++i] < v) {
        if (i >= hi) { break; };
      }
      while (v < a[--j]) {
        if (j <= lo) { break; };
      }
      if (i >= j) { break; }
      this.swap(a, i, j);
    }
    this.swap(a, lo, j);
    return j;
  }

  swap(a, firstEl, secondEl) {
    let temp = a[firstEl];
    a[firstEl] = a[secondEl];
    a[secondEl] = temp;
    return
  }

  // Knuth-Fisher-Yates shuffle algorithm
  shuffle(arr) {
    for (var i = arr.length - 1; i > 0; i--) {
      const swapIndex = Math.floor(Math.random() * (i + 1))
      const currentEl = arr[i]
      const elToSwap  = arr[swapIndex]

      arr[i] = elToSwap;
      arr[swapIndex] = currentEl;
    }
    return arr;
  }
}

I'm also thinking of adding a method to verify input, make sure input is array, not nil, etc. Ideas for how I can go about implementing such method are welcome.
Is there anything I can improve, are there principles being violated? Am I following best practices in class implementation in JavaScript.
here is a test:
var obj = new QuickSort();
sample = obj.sort(sample);
console.log(sample)


texts:
Given I have a linked list, and I want to move a given node to the end of the list, is there a more elegant way of doing this, than what I've done here?

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

typedef struct node {
  int val;
  struct node *next;
} node_t;

void insert(node_t **head, int val)
{
  node_t *new_node = malloc(sizeof(node_t));
  node_t *tmp;

  new_node->val = val;
  new_node->next = NULL;

  // Empty list?
  if(*head == NULL) {
    *head = new_node;
    return;
  }

  tmp = *head;

  while(tmp->next != NULL)
    tmp = tmp->next;

  tmp->next = new_node;
}

void movetoend(node_t **head, int val)
{
  node_t *curr;
  node_t *tmp = NULL;
  node_t *old = NULL;

  // Find val in list
  for(curr = *head; curr != NULL; old = curr, curr = curr->next) {
    if(curr->val == val) {
      // Matched node is the only one in the list, don't do anything
      if(curr->next == NULL)
        return;

      // Matched node is first, set next to jump over
      if(old == NULL)
        *head = curr->next;

      // Matched node is in the middle, set next to jump over
      else
        old->next = curr->next;

      // Set a pointer to matched node for later use
      tmp = curr;

      // Loop through the rest of the list
      // "old" will have the pointer to last node
    }
  }

  // No matches?
  if(tmp == NULL)
    return;

  // Terminate list
  tmp->next = NULL;

  // Append matched node
  old->next = tmp;
}

void print(node_t *head)
{
  while(head) {
    printf("%d\n", head->val);
    head = head->next;
  }
}

int main()
{
  node_t *head = NULL;

  insert(&head, 10);
  insert(&head, 20);
  insert(&head, 30);
  movetoend(&head, 10);
  print(head);

  return 0;
}

EDIT: Added comments, modified movetoend function a bit slimmer.


texts:
I'm trying to improve my code and i want to know if this is the best way to write this Switch or if  there are other methods.

for(String word : words) {
        switch(word.toLowerCase()) {
        case "a":
            a++;
            break;
        case "the":
            the++;
            break;
        case "bird":
            bird++;
            break;
        case "animal":
            animal++;
            break;
        case "is":
            is++;
            break;
        }
    }

Here is the complete code if you need it.

public static void main(String[] args) throws IOException {
ArrayList<String> words = new ArrayList<>();
int a = 0, the = 0, bird = 0, animal = 0, is = 0;

    for(String line : Files.readAllLines(Paths.get("C:\\Users\\n\\Desktop\\Text.txt"))) {
        line.split("\\s+");
        line.replaceAll("[!?.,]", "");
        for(String word : line.split("\\s+")) {
            words.add(word);
        }
    }

    for(String word : words) {
        switch(word.toLowerCase()) {
        case "a":
            a++;
            break;
        case "the":
            the++;
            break;
        case "bird":
            bird++;
            break;
        case "animal":
            animal++;
            break;
        case "is":
            is++;
            break;
        }
    }
System.out.println(a + " " + the + " " + bird + " " + animal + " " + is);
}


texts:
I'm looking for feedback as to how I've structured the async calls, and If anything should be written differently.

endpoints.js

module.exports = {
  lotto: 'https://www.norsk-tipping.no/api-lotto/getResultInfo.json?drawID=',
  keno: 'https://www.norsk-tipping.no/api-keno/getResultInfo.json?drawID=',
  extra: 'https://www.norsk-tipping.no/api-extra/getResultInfo.json?drawID=',
  vikinglotto: 'https://www.norsk-tipping.no/api-vikinglotto/getResultInfo.json?drawID=',
  joker: 'https://www.norsk-tipping.no/api-joker/getResultInfo.json?drawID=',
  eurojackpot: 'https://www.norsk-tipping.no/api-eurojackpot/getResultInfo.json?drawID='
};

service.js

var request      = require('request');
var gametypes    = require('./endpoints');

function toJSON(response){
    var data    = response.toString(),
        result  = data.match(/(^{[\s\w\W]+}$)/gm).join('');

    return JSON.parse(result);
}

function getResults(opts, callback){
    var url                     = gametypes[opts.type],
        fromDrawID              = opts.fromDrawID,
        toDrawID                = opts.toDrawID,
        numberOfRequestsWanted  = toDrawID - fromDrawID,
        numberOfRequestsDone    = 0,
        data                    = [];

    //If either the object is missing or
    //the object with no key of 'type' is passed in - return error.

    if(!opts.type){
        return callback(new Error('Missing required param: Object with key: type'), null);
    }

    if(fromDrawID && toDrawID) {
        console.log('Fetching the requested results from https://www.norsk-tipping.no...');

        while(fromDrawID <= toDrawID) {
            doRequest(url + fromDrawID++, callback);
        }
    } else {
        console.log('Fetching the latest result from https://www.norsk-tipping.no...');
        doRequest(url, callback);
    }

    function doRequest(url, callback) {

        request(url, function(error, response, body) {
            if(!error && response.statusCode === 200) {
                data.push(toJSON(body));

                if(numberOfRequestsDone++ === numberOfRequestsWanted) {
                    return callback(null, data);
                }

            } else {
                return callback(error, null);
            }
        });
    }
}

module.exports = getResults;

example usage

var lotto    = require('./service');
var options  = { type: 'vikinglotto', fromDrawID: 1, toDrawID: 500};

lotto(options, function(err, results) {
    if (err) console.log(err);

    else {
        console.log(data);
    }
});


texts: Ability to forget the memoized supplier value

texts:
Guava has a feature request which is asking to provide the ability to forget memoized value on a given supplier.

On top on that I needed another functionality where if during the calculation of expensive value another thread would invalidate the data, the memoisation should retry (guava LoadableCache doesn't provide this feature: invalidation during calculation is ignored).

I couldn't wait for this feature so I wrote this myself. First, an interface for forgettable supplier:

public interface ForgettableSupplier<T> extends Supplier<T> {
    public void forget();
}

Then, a base class, mostly taken from here:

public abstract class DoubleCheck<T> extends ReentrantReadWriteLock {

    protected abstract T create();

    protected abstract T retrieve();

    protected abstract boolean invalid(T value);

    public T get() {
        try {
            readLock().lock();
            T value = retrieve();
            while (invalid(value)) { // this spins until no more invalidations are made
                readLock().unlock();
                writeLock().lock();
                value = retrieve();
                try {
                    if (invalid(value)) {
                        value = create();
                    }
                } finally {
                    readLock().lock();
                    writeLock().unlock();
                }
            }
            return value;
        } finally {
            readLock().unlock();
        }
    }
}

And finally, the static utility that combines everything together:

public class Suppliers {

    private Suppliers() {
    }

    public static <T> ForgettableSupplier<T> memoize(Supplier<T> delegate) {
        return new ForgettableMemoizingSupplier<>(delegate);
    }

    private static final class ForgettableMemoizingSupplier<T> implements ForgettableSupplier<T> {

        private final Supplier<T> delegate;

        private volatile T t;

        private final AtomicBoolean needsToBeForgotten = new AtomicBoolean(false);

        private final DoubleCheck<T> doubleCheck = new DoubleCheck<T>() {
            @Override
            protected T create() {
                needsToBeForgotten.set(false);
                return ForgettableMemoizingSupplier.this.t = delegate.get();
            }

            @Override
            protected T retrieve() {
                return ForgettableMemoizingSupplier.this.t;
            }

            @Override
            protected boolean invalid(final T t) {
                return (ForgettableMemoizingSupplier.this.t == null) || needsToBeForgotten.get();
            }
        };

        private ForgettableMemoizingSupplier(final Supplier<T> delegate) {
            this.delegate = delegate;
        }

        @Override
        public void forget() {
            needsToBeForgotten.set(true);
        }

        @Override
        public T get() {
            return doubleCheck.get();
        }
    }
}


texts:
In Flatten to get all child controls of certain type in a UIView, methods were discussed to
recursively flatten a tree-like structure in Swift, resulting in an array
of all elements.

Motivated by that thread, I have written a flatten function which creates
a sequence instead. This can be an advantage if the resulting elements are to be post-processed (e.g. filtered), because they can be created
"lazily" or "on-demand", instead of creating an array with all
resulting elements first.

func sequentialFlatten<S : SequenceType>
    (seq : S, children : (S.Generator.Element) -> S) -> SequenceOf<S.Generator.Element>
{
    return SequenceOf {
        () -> GeneratorOf<S.Generator.Element> in

        // Current generator, or `nil` if all sequences are exhausted:
        var gen : S.Generator? = seq.generate()
        // Queue of generators for sequences which still have to be enumerated:
        var queue : [S.Generator] = []

        return GeneratorOf {

            while gen != nil {
                if let next = gen!.next() {
                    queue.append(children(next).generate())
                    return next
                }
                // Current generator is empty, try to deque next one:
                gen = queue.first // `nil` if queue is empty
                if (gen != nil) {
                    queue.removeAtIndex(0)
                }
            }
            return nil
        }
    }
}

The function arguments are an initial sequence, and a closure which
transforms any sequence element into a new sequence (which may be
empty). One can view seq as a set of root nodes in a tree
or forest,  and children as the mapping from each node to its children.

(Swift has a related flapMap() function which takes a sequence and a
transformation as argument, but that does not work recursively, and
returns an array and not a sequence.)

Example 1:

let someView : UIView = ...
let views = sequentialFlatten([someView], { $0.subviews as! [UIView] })
let labels = lazy(views).filter( { $0 is UILabel } ).map( { $0 as! UILabel } )

creates a sequence of all views in the view hierarchy of someView,
and then extracts all labels from that sequence. (Note that no intermediate array of all views is created.)

Example 2:

let seq = sequentialFlatten([0], { n in n < 50 ? [ 2*n+1, 2*n+2] : []})
for x in seq { println(x) }

is an unconventional method to print the numbers 0 ... 100.

I wrote this function mainly for my own educational purpose, to get
more familiar with Swift sequences and generators. All feedback is
welcome, for example:

Naming (function and variables).
Swifty-ness: things which should be done different in Swift.
Implementation: can the same be achieved easier, perhaps using
available functions from the Swift standard library?
Can sequentialFlatten() be implemented in a way that it calls itself
recursively?


texts: How can I improve this code to display contact numbers?

texts:
I am making an Address Book like application .
I have a contactType enum.

public enum ContactType
{
  //just a cut down version
  MOBILE,PHONE,FAX,EMAIL;

}

Then I have a Contact class

public class Contact
{
   private ContactType contactType;
   private String value;//e.g phone number or email
   private String areaCode;//does not apply to email or mobile
   //....getters and setters
}

Then I have a Person class

public class Person
{
    private List<Contact>contacts;
    //----Other attributes and getters and setters

}

I thought I have nailed very well :) but as it turns out probably not:(  Because

I now needs to display a list of people(list of person) and in the table along with some other things (name etc)I have these columns:

Name|......|Phone|Mobile|Fax  |Email

I now realised that I can not just loop through the list of people and display contact numbers since these contacts are in list inside every object in list of people.
In simple words as you might know by now already if I have a list of people e.g

List<Person>people ;

Then this is not a valid option

for(Person person: people)
{
  //can not get phone number for example by going
  person.getPhone();
}

but this is

for(Person person: people)
    {
      //but will have to get it from the list of contacts e.g
      List<Contact>contacts = person.getContacts();
      for(Contact contact:Contacts)
      {
         if (contact.getContactType.isPhone())
         {
            contact.getValue();
         }
      }
    }

So I have now introduced a Rowitem Class

  public class Rowitem {

        private String phone;
        private String fax;
        private String mobile;
        private String email;

        ....

     }

and populating is like this

private void populateForDisplay(Rowitem item,List<Contact> contacts)
 {
        for (Contact contact : contacts)
        {
            if (contact.getType().isEmail()) {
                item.setEmail(contact.getValue());
            }
            if (contact.getType().isFax()) {
                item.setFax(contact.getValue());
            }
            if (contact.getType().isMobile()) {
                item.setMobile(contact.getValue());
            }
            if (contact.getType().isPhone()) {
                item.setPhone(contact.getValue());
            }
        }

    }

While this approach works I just do not think it is right. Firstly I do not like the fact that I have to introduce this RowItem class and then all these if statements do not look right. How can I improve this?
The front end framework that I am using is JSF2 but probably not relevant here.

I need someone to review my approach rather than line by line code.I have read https://codereview.stackexchange.com/faq and I think my question is with the rules if not then please guide me and I will move this.Because not code problem I did not think will go to StackOverFlow


texts:
Given an array of ints, return a string identifying the range of
  numbers.

  Example:

  Input arr - [0 1 2 7 21 22 1098 1099]
  Output - "0-2,7,21-22,1098-1099"

Is there any improvement possible in this implementation?

#include<iostream>
#include<vector>
#include<algorithm>
#include<sstream>

std::string  range_creator(std::vector<int> & vec)
{
    std::sort(std::begin(vec),std::end(vec));

    int first=vec.at(0);
    int prev=first-1;

    std::stringbuf buffer;
    std::ostream os (&buffer);

    for(auto &x : vec)
    {
       if(++prev == x)
           continue;
        else
        {

           if(first != --prev)
           {
               os << first<<"-"<<prev<<",";
               prev=x;
               first=x;
           }
           else
           {
               os<<first<<",";
               prev=x;
               first=x;
           }

        }

    }
    if(first != prev)
    {
        os<<first<<"-"<<prev;
    }
    else
    {
       os<<first;
    }
    return buffer.str();
}

int main()
{
    std::vector<int> vec={0,1,2,7,8,9,10,21,22,23,24,25,27,1098,1099,1100,2000};
    std::cout<<range_creator(vec);

    return 0;
}


texts: Minimizing string length checker in C# + format(ish) function

texts:
I'm taking on a project from a previous programmer. My goal is to make it a bit smaller and hopefully better. Originally the code has a bunch of length checks and Booleans as shown below.

C#

string[] splitStrArray = SNString.Split('-');
string part1 = splitStrArray[0];
string part2 = splitStrArray[1];
string part3 = splitStrArray[2];

bool part1ok = false;
bool part2ok = false;
bool part3ok = false;

if (part1.Length == 3)
{
    part1ok = true;
}

if (part2.Length == 8)
{
    part2ok = true;
}

if (part3.Length == 3)
{
    part3ok = true;
}

if(part1ok && part2ok && part3ok)
{
    return true;
}
else
{
    return false;
}

Is it a good practice to keep that or should I change it to my following idea?

string[] splitStrArray = SNString.Split('-');
string part1 = splitStrArray[0];
string part2 = splitStrArray[1];
string part3 = splitStrArray[2];

if(part1.Length == 3 && part2.Length == 8 && part3.Length == 3)
{
    return true;
}
else
{
    return false;
}

Basically a barcode is scanned, and a SN is passed to the application. The goal is to make sure the SN scanned is of a format XXX-XXXXXXXX-XXX. Sometimes there are occurrences of SNs that are formatted XXXXXXXXXXXXX or XXX-XXXXXXXXXX not complete or missing a specific dash.


texts:
Basically, I want to write a huge file of numbers. Each line in that file should contain one number. This program below is extremely slow (obviously) but it works. It writes one line after line and always one number until the limit of an unsigned long has been reached.

#include <iostream>
#include <limits>
#include <fstream>

int main() {

    unsigned long max = std::numeric_limits<unsigned long>::max();
    unsigned long i = 0;
    std::ofstream myFile;
    myFile.open( "/home/awesome/Desktop/large_numbers.txt" );
    while( i < max ) {

        myFile << i << "\n";
        i++;

    }
    myFile.flush();
    myFile.close();
}

This program wrote in 2 minutes on my desktop computer 12GB. On my laptop only 117 MB in 10 minutes. On both computers I had to stop the program because it was making my computer slow and still wasn't done. Any way to optimize it so it'll be faster and maybe run more smooth so my other programs will still run perfectly fine?


texts: Rewrite BehaviorSuject that takes either localStorage or Observable in Angular

texts:
I have this code
employee = this.identityService.me;
employeeToken: Observable<string> = this.employee.pipe(map((e) => e.token));

currentHead = new BehaviorSubject(localStorage.getItem('head'));

What I need to do is to change the currentHead if the local storage is empty. So I do this in the ngOnInit
ngOnInit() {
    this.employeeToken.subscribe(e => {
        if (!this.currentHead.value || this.currentHead.value === '') {
            this.currentHead.next(e);
        }
    });
}

It works, but somehow I feel like this should e feasible with rxjs in the initialization of currentHead, no?
Where I failed is, that the local storage is not an observable but this.employee is, so I struggle to compare them. I tried some convert observable to behaviorsubject but that didn't work either.