texts:
I'm learning rust with mostly a background in managed languages. I have a little C background.

As a learning project I am re-implementing a linear-transformations     library I've been working on in C#.

This is my first reusable library I've tried to make in Rust and I'd like feedback on creating and using modules, as well as rust programming in general.

Project structure

+ transforms
    + src
        - lib.rs
        - tests.rs
        - transforms.rs
        - vectors.rs
    + target
    - Cargo.toml

I haven't made any changes to the automatic cargo.toml.
transforms.rs is empty and have the linear transformation code added to it in the future.

lib.rs

pub mod vectors;
mod tests; // tests don't get run if I don't have this, not sure why?

vectors.rs

use std::fmt;

pub struct KVector3{
    pub x : f64,
    pub y : f64,
    pub z : f64,
}

pub trait Vector {
    fn magnitude_squared(&self) -> f64;
    fn magnitude(&self) -> f64;
}

pub trait Vector3 {
    fn dot(&self, v : KVector3) -> f64;
    fn cross(&self, v : KVector3) -> KVector3;

    fn zero() -> KVector3;
    fn i_hat() -> KVector3;
    fn j_hat() -> KVector3;
    fn k_hat() -> KVector3;
}

impl Vector for KVector3 {
    fn magnitude_squared(&self) -> f64 {
        self.x * self.x + self.y * self.y + self.z * self.z
    }

    fn magnitude(&self) -> f64 {
        (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
    }
}

impl Vector3 for KVector3 {
    fn dot(&self, v : KVector3) -> f64 {
        self.x * v.x + self.y * v.y + self.z + v.z
    }

    fn cross(&self, v : KVector3) -> KVector3 {
        KVector3 {
            x : self.y * v.z - self.z * v.y,
            y : self.x * v.z - self.z * v.x,
            z : self.x * v.y - self.y * v.x
        }
    }

    fn zero() -> KVector3 { KVector3 { x: 0., y: 0., z: 0. } }

    fn i_hat() -> KVector3 { KVector3 { x: 1., y: 0., z: 0. } }

    fn j_hat() -> KVector3 { KVector3 { x: 0., y: 1., z: 0. } }

    fn k_hat() -> KVector3 { KVector3 { x: 0., y: 0., z: 1. } }
}

impl PartialEq<KVector3> for KVector3 {
    fn eq(&self, other : &KVector3) -> bool {
        self.x == other.x && self.y == other.y && self.z == other.z
    }
}

impl fmt::Debug for KVector3 {
    fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
        write!(f, "<{},{},{}>", self.x, self.y, self.z)
    }
}

tests.rs

#[cfg(test)]
mod tests {

    use ::vectors::{Vector, Vector3, KVector3};

    #[test]
    fn unit_magnitude_squared() {
        let mag_squared = KVector3::i_hat().magnitude_squared();
        assert_eq!(1., mag_squared);
    }

    #[test]
    fn v3_magnitude_squared() {
        let triangle = KVector3 { x : 3., y : 4., z: 0. };
        let mag_squared = triangle.magnitude_squared();
        assert_eq!(25., mag_squared);
    }

    #[test]
    fn v3_magnitude() {
        let triangle = KVector3 { x : 3., y : 4., z: 0. };
        let mag = triangle.magnitude();
        assert_eq!(5., mag);
    }

    #[test]
    fn cross_product() {
        let product = KVector3::i_hat().cross(KVector3::j_hat());
        assert_eq!(KVector3::k_hat(), product);

    }
}


texts: Displaying a wait cursor while we're waiting

texts:
I come from VB6 where everything is single threaded, so I've never written a lick of multi-threaded code before. I just added a wait cursor to one of our GUI's by stumbling through the docs, but I'm unsure I've done it the best way. Did I?

Control is a Winform view and the code below is located in the presenter class. Full file can be found on GitHub.

    private void RefreshToDoList(object sender, EventArgs e)
    {
        try
        {
            Cursor.Current = Cursors.WaitCursor;
            var getItems = new Task<IOrderedEnumerable<ToDoItem>>(() => GetItems());
            getItems.Start();

            Control.TodoItems = getItems.Result;
        }
        finally
        {
            Cursor.Current = Cursors.Default;
        }
    }

private IOrderedEnumerable<ToDoItem> GetItems()
{
    var items = new ConcurrentBag<ToDoItem>();
    var projects = VBE.VBProjects.Cast<VBProject>();
    Parallel.ForEach(projects,
        project =>
        {
            var modules = _parser.Parse(project);
            foreach (var module in modules)
            {
                var markers = module.Comments.AsParallel().SelectMany(GetToDoMarkers);
                foreach (var marker in markers)
                {
                    items.Add(marker);
                }
            }
        });

    var sortedItems = items.OrderBy(item => item.ProjectName)
                            .ThenBy(item => item.ModuleName)
                            .ThenByDescending(item => item.Priority)
                            .ThenBy(item => item.LineNumber);

    return sortedItems;
}


texts: Converting numbers 1-99 to Spanish in Javascript

texts:
I have written a small program to convert numeric cardinal numbers (i.e, 4, 35) into Spanish. Currently, it only supports numbers 1-99, however I would like to increase it to support numbers of any length.

Before I do this, I am seeking some feedback on my code structure. I feel that I have too many if statements and do not abstract my code enough, and I do not wish for it to be an elongated nightmare of if statements. I am also unsure how I should split up numbers of different sizes, and what variable names to use.

getSpanishCardinal = cardinal => {
  if (0 <= cardinal && cardinal <= 15) {
    return getCardinals()[cardinal];
  }
  if (16 <= cardinal && cardinal <= 19) {
    return sixteenToNineteen(cardinal);
  }
  if (cardinal >= 20 && cardinal <= 99) {
    return twentyToNinetynine(cardinal);
  }
};

twentyToNinetynine = cardinal => {
  if (cardinal % 10 == 0) {
    return getCardinals()[cardinal];
  }
  if (21 <= cardinal && cardinal <= 29) {
    return "veinti" + getSpanishCardinal(rightMostDigit(cardinal)).toString();
  }
  return (
    getCardinals()[leftMostMultiplier(cardinal)].toString() +
    " y " +
    getSpanishCardinal(rightMostDigit(cardinal)).toString()
  );
};

sixteenToNineteen = cardinal => {
  let rightMost = rightMostDigit(cardinal);
  return "dieci" + getSpanishCardinal(rightMost).toString();
};

leftMostMultiplier = cardinal => {
  let newDigit = cardinal.toString()[0];
  const cardinalString = cardinal.toString();
  const length = cardinalString.length;
  for (let i = 1; i < length; i++) {
    newDigit += "0";
  }
  return parseFloat(newDigit);
};

rightMostDigit = cardinal => {
  return cardinal % 10;
};

getCardinals = () => {
  return {
    0: "cero",
    1: "uno",
    2: "dos",
    3: "tres",
    4: "cuatro",
    5: "cinco",
    6: "seis",
    7: "siete",
    8: "ocho",
    9: "nueve",
    10: "diez",
    11: "once",
    12: "doce",
    13: "trece",
    14: "catorce",
    15: "quince",
    20: "veinte",
    30: "treinta",
    40: "cuarenta",
    50: "cincuenta",
    60: "sesenta",
    70: "setenta",
    80: "ochenta",
    90: "noventa",
    100: "cien",
    200: "doscientos",
    300: "trescientos",
    400: "cuatrocientos",
    500: "quinientos",
    600: "seiscientos",
    700: "setecientos",
    800: "ochocientos",
    900: "novecientos",
    1000: "mil",
    1000000: "millón"
  };
};

console.log(getSpanishCardinal(56));


texts:
I'm trying to come up with a unit testing framework for Haskell that is

small and self-contained
produces TAP-compatible output
exits abnormally on failure (instead of relying on the TAP consumer to validate all the output).
has a simple API with easy to understand compile-time errors. (That's the motivation for committing to concrete types in the interface).

With that in mind, this is what I came up with:

I'm mainly looking for things that

are not idiomatic Haskell
would hamper usability in very small to small projects in The Real World.

module TestTrivial
    ( tests
    ) where

import System.Exit (exitSuccess, exitFailure)

testsImpl :: [(Bool, String)] -> Int -> Bool -> IO ()
testsImpl [] nextTest status =
    putStrLn ("1.." ++ show (nextTest - 1)) <> doExit where
        doExit = if status then exitSuccess else exitFailure
testsImpl ((cond, msg):xs) nextTest success =
    putStrLn msg' <> rest where
        ok = if cond then "ok" else "not ok"
        num = show nextTest
        f [] = unwords [ok, num]
        f m  = unwords [ok, num, "-", msg]
        msg' = f msg
        rest = testsImpl xs (nextTest + 1) (success && cond)

tests :: [(Bool, String)] -> IO ()
tests xs = testsImpl xs 1 True

And here's an example test suite using this library.

module TestAdd where

import TestTrivial

main = tests
    [ (1 + 4 == 5, "1 + 4 == 5")
    , (5 + 6 /= 7, "5 + 6 /= 7")
    ]

And what it produces. ... Despite the - sign separating the test number from the message and how strange that looks here, the output is formatted correctly.

ok 1 - 1 + 4 == 5
ok 2 - 5 + 6 /= 7
1..2


texts:
I have made some simple functions to find the first SO chat message. How can I improve my code?

Even if there is a stackoverflow link that will get the job done (I'd be glad to know), I'd like to improve upon my already written code.

import Network.HTTP
import Text.Regex.Posix

type UserID      = String
type MessageLink = String
type PageNumber  = Integer

findLast :: UserID -> IO MessageLink
findLast = searchLast 1 "Not found"

searchLast :: PageNumber -> MessageLink -> UserID -> IO MessageLink
searchLast pg lnk id = do

    let link = "http://chat.stackoverflow.com/users/" ++
               id ++ "?tab=recent&page=" ++ show pg

    c <- simpleHTTP (getRequest link) >>= getResponseBody

    let match = c =~ "/transcript/[^\"]+" :: [[String]]

    if null (c =~ "monologue" :: String)
        then return $ "http://chat.stackoverflow.com" ++ lnk
        else searchLast (pg + 1) (head . last $ match) id


texts:
I'm trying to implement a heap using list data structure. I'd also like to keep track of the position of elements in the list in order to enable easy deletion. My implementation involves looping through the entire list to update the positions after an insert/delete combo. I'm afraid this raises the time complexity from O(log n) to O(n). Is there a better way of keeping track of elements' position? Currently, update method is what takes care of the bookkeeping.

class heap():
    ''' Min-Heap'''
    def __init__(self,G):
        self.list=[0] #to ease dealing with indices, an arbitrary value at index 0
        self.pos={} #holds position of elements with respect to list
        self.G = G #Graph, contains the score for each element in G[element][2]
def update_pos(self):
    self.pos = {}
    for i in xrange(1,len(self.list)):
        self.pos[self.list[i]]=i

def percUp(self): #percolate up, called by insert method
    start = len(self.list)-1
    while start//2>0:
        if self.G[self.list[start/2]][2] > self.G[self.list[start]][2]:
            self.list[start/2],self.list[start] = self.list[start],self.list[start/2]
        start = start//2

def insert(self,element):
    self.list.append(element)
    self.percUp()
    self.update_pos()

def percDown(self,start=1): #percolate down, called by extract_min method
    while 2*start < len(self.list):
        min_ind = self.getMinInd(start)
        if self.G[self.list[start]][2] > self.G[self.list[min_ind]][2]:
            self.list[start],self.list[min_ind] = self.list[min_ind],self.list[start]
        start = min_ind

def extract_min(self):
    self.list[-1],self.list[1] = self.list[1],self.list[-1]
    small = self.list[-1]
    self.list = self.list[:-1]
    self.percDown()
    self.update_pos()
    return small

def delete(self,pos):
    self.list[-1],self.list[pos] = self.list[pos],self.list[-1]
    self.pos.pop(self.list[pos])
    self.list = self.list[:-1]
    self.percDown(pos)
    self.update_pos()

def getMinInd(self,start):
    if 2*start+1 > len(self.list)-1:
        return 2*start
    else:
        if self.G[self.list[2*start]][2]<self.G[self.list[2*start+1]][2]:
            return 2*start
        else:
            return 2*start+1


texts:
I need to generate a minimum and maximum value for a range of speeds (slow, medium, fast), the user can specify any combination of the 3 values, and receive a range that encompasses all.

Given any combination of "slow", "medium", "fast", getRange() will return a [min, max] range.

The function can be called in the following ways:

// Any combination of the values
getRange(['slow', 'medium', 'fast']); // [0, 100]
getRange(['medium', 'fast']); // [36, 100]
getRange(['slow']); // [0, 35]

// Or just a single string
getRange('fast'); // [76, 100]

// No string specified
getRange(); // [0, 100]

Is there any way to simplify my code? It seems a bit clunky and there's probably a simpler way of writing this:

function getRange(speed){
    var min, max;

    if(speed && speed.length){
        var obj = {};

        if(Array.isArray(speed)){
            speed.forEach(function(s){
                obj[s] = true;
            });
        }
        else{
            obj[speed] = true;
        }

        if(obj.slow){
            min = 0;
            max = 35;
        }

        if(obj.medium){
            if(typeof min == 'undefined'){
                min = 36;
            }
            max = 75;
        }

        if(obj.fast){
            if(typeof min == 'undefined'){
                min = 76;
            }
            max = 100;
        }
    }

    if(typeof min == 'undefined'){
        min = 0;
    }

    if(typeof max == 'undefined'){
        max = 100;
    }

    return [min, max];
};


texts: Matching whitespace and non-whitespace characters with RegEx

texts:
I just started watching some regex tutorials on Plural Sight just to learn how to write a proper regex expression. So far so good, it's been alright and I decided to test my knowledge on Hackerrank. Although, the tutorial explains how to use PCRE (Perl Compatible Regular Expressions) and ECMAScript engines but I'm comfortable using PCRE at the moment so hence my code is running on PHP.
A brief overview of the question is:

Task
You have a test string S. Your task is to match the pattern XXxXXxXX
Here, x denotes whitespace characters, and X denotes non-white space characters.
Note
This is a regex only challenge. You are not required to write code.
You have to fill the regex pattern in the blank (_________).

$handle = fopen ("php://stdin","r");
$Test_String = fgets($handle);
if(preg_match($Regex_Pattern, $Test_String, $output_array)){
    print ("true");
} else {
    print ("false");
}

fclose($handle);
?>

I don't really know much about PHP, all I had to do was fill in the blank so I wrote 2 test cases to see how my regex was doing so far in regex 101 e.g AA AA AA, BB BB BC.

$Regex_Pattern = "/\S{2}\s{1}\S{2}\s{1}\S{2}/"; //Do not delete '/'. Replace __________ with your regex.

Final thoughts: I'm fully aware the example isn't meant to be complicated as it's meant to show how to use \S and \s. I attempted using [\S\s]+\S{2}$ but that wasn't greedy enough as it permits multiple spacing.
Are there more refined ways to do this without using \S & \s and if S &\s can be used differently to achieve the same results?


texts: PHP function to compare two Roman numerals

texts:
This was for an assignment. I had to write a function to compare two roman numerals. This had to return true only if the second number was larger than the first and had to be done without converting the letters into integers. Also prefix subtraction didn't apply so all the letters came in descending order.

Here is what I came up with:

<?php

function x_smaller_than_y($x_num,$y_num) {

//Create array with ordered list of roman numerals.
$evaluation= array("M","D","C","L","X","V","I");

//Splits submitted numbers into arrays
$x_num_arr = str_split($x_num);
$y_num_arr = str_split($y_num);

//Loops through each roman numeral in the given list
for ($evaluate = 0; $evaluate<7;$evaluate++)
  {

     //For every letter in the numerals' list loops through
     //every letter in the given numbers looking for a match.
     $counter = 0;
     while ($counter < ((strlen($x_num)))&& $counter < ((strlen($y_num))))
       {

       //If in any specific position x=y, it simply ignores it and moves forward.
       if ($x_num_arr[$counter]==$y_num_arr[$counter])
           {$counter++;}

       //If in any given position the letter in Y is higher in the list than
       //the letter in X then Y is larger than X and the function is true.
       //"break" ends the while loop and "$evaluate=8" ends the for loop.
       elseif(($x_num_arr[$counter]!=$evaluation[$evaluate])&&($y_num_arr[$counter]==$evaluation[$evaluate]))
           {return true;
            $evaluate=8;
            break;}

       //Same as above but this time the letter in X is before the letter
       //in Y so the function is false.
       elseif(($x_num_arr[$counter]==$evaluation[$evaluate])&&( $y_num_arr[$counter]!=$evaluation[$evaluate]))
           {return false;
            $evaluate=8;
            break;}

       //If none of the above cases apply simply move to the next letter.
       else {$counter++;}
        }
    }

//Since the number of iterations in the while loop is determined by the
//shorter number there can still be a case in which 2 numbers are exactly
//the same up to a point but one is simply longer than the other,
//eg. MXVI and MXVII.
//When this happens the for loop will have run through its natural
//course, $evaluate will be equal to 7, and the code below will determine
//the larger number by looking at their lenght.
if ($evaluate<8&&(strlen($x_num) < strlen($y_num)))
{return true;}

elseif ($evaluate<8&&(strlen($x_num) > strlen($y_num)))
{return false;}

}

How could have I made it better?


texts: Find all integers between m and n whose sum of squared divisors is itself a square

texts:
Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared
  are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors
  is 2500 which is 50 * 50, a square!

  Given two integers \$m\$, \$n\$ (\$1 \le m \le n\$) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number.

  The result will be an array of arrays, each subarray having two
  elements, first the number whose squared divisors is a square and then
  the sum of the squared divisors.

I started learning Ruby two weeks ago so I don't know much. This is my first programming language.

Is it possible to rewrite the below code so it runs faster? It currently times out at n>9999.

def list_squared(m, n)

r = (m..n).to_a.map { |z| (1..z).select { |x| z % x == 0} }
#returns the divisors of each number in an array of arrays

squarenumbers = r.map { |x| x.map { |c| c**2 }.inject(:+) }.select { |x| Math.sqrt(x) % 1 == 0 }
#this finds all integers between m and n whose sum of squared divisors  is itself a square

booleans = r.map { |x| x.map { |c| c**2 }.inject(:+) }.map { |x| Math.sqrt(x) % 1 == 0 }
#returns an array of booleans.

indexer = booleans.map.with_index{|x, i| i if x == true }.compact
#returns the index of each of the true values in booleans as an array

unsqr = indexer.map { |x| (m..n).to_a[x] }
#returns the numbers whose squared divisors is a square in an array

unsqr.zip(squarenumbers)
#merges the two arrays together, element for element and creates an array of arrays

end

#for m = 1 and n = 1000 the result would be

#[[1, 1], [42, 2500], [246, 84100], [287, 84100], [728, 722500]]


texts: Thread safety and performance when multiple threads write into same Writer

texts:
Multiple threads write data to a file. When maxLines is reached, the file is closed and a new file is created:

public synchronized void writeLine(String data) throws IOException {
  writer.write(data + "\n");
  lineCounter++;

  if(maxLines != 0 && lineCounter == maxLines) {
    close();

    lineCounter = 0;
    fileCounter++;

    addFile();
    open();
  }
}

As you can see I currently solved this with a synchronized method. This ensures that thread 1 won't write when thread 2 just closed the writer.

I think that's pretty slow. Is there a better solution for this? Maybe with lineCounter as volatile?


texts:
I did an exercise (open-ended - without an answer) from a JavaScript book (chapter about functions).

  Given array of passengers of a flight with their names and ticket types and one need to emulate stewardesses asking passengers for service during the flight depending on their ticket type (first class or coach)  (stewardesses provide all the passengers with one same kind of a service at a time). It's required to make code as extensible and flexible (so you can add ticket types (economy, business), drink types etc. and even new kinds of service like dinners or smth.) as possible.

I want to see suggestions on how I can make this code more flexible, extensible and in a more functional style. Or maybe see any critiques as to why this code is bad, with suggestions of a more correct way of doing the exercise.

var passengers = [{
  name: "Jane Doloop",
  ticket: "firstclass"
}, {
  name: "Dr. Evel",
  ticket: "firstclass"
}, {
  name: "Sue Property",
  ticket: "firstclass"
}, {
  name: "John Funcall",
  ticket: "coach"
}];

function formServices(passengers) {
  for (var i = 0; i < passengers.length; i++) {
    createOrders(passengers[i]);
  }
}

function serveCustomers(passengers) {
  formServices(passengers);
  serveIteration(passengers, "orderDrink");
  console.log("------");
  serveIteration(passengers, "orderDrink");
  console.log("------");
  serveIteration(passengers, "orderMovie");
  console.log("------");
  serveIteration(passengers, "orderDrink");
  console.log("------");
  serveIteration(passengers, "throwGarbage");
}

function createOrders(passenger) {
    if (passenger.ticket === "firstclass") {
      passenger.orderDrink = function() {
        console.log(passenger.name + ", woud you like a cocktail or wine?");
      };
      passenger.orderMovie = function() {
        console.log(passenger.name + ", woud you like a TV-show or movie?");
      };
    } else {
      passenger.orderDrink = function() {
        console.log(passenger.name + ", your choice is cola or water.");
      };
      passenger.orderMovie = function() {
        console.log(passenger.name + ", movies are not available for you.");
      };
    }

    passenger.throwGarbage = function() {
      console.log(passenger.name + ", it's time to throw garbage");
    };
}

function serveIteration(passengers, serviceProperty) {
  switch (serviceProperty) {
    case "orderDrink":
      for (var i = 0; i < passengers.length; i++) {
        passengers[i].orderDrink();
      }
      break;
    case "orderMovie":
      for (i = 0; i < passengers.length; i++) {
        passengers[i].orderMovie();
      }
      break;
    case "throwGarbage":
      for (i = 0; i < passengers.length; i++) {
        passengers[i].throwGarbage();
      }
      break;
    default:
      console.log("No such service");
  }
}

serveCustomers(passengers);

The output is:

Jane Doloop, woud you like a cocktail or wine?
Dr. Evel, woud you like a cocktail or wine?
Sue Property, woud you like a cocktail or wine?
John Funcall, your choice is cola or water.
------
Jane Doloop, woud you like a cocktail or wine?
Dr. Evel, woud you like a cocktail or wine?
Sue Property, woud you like a cocktail or wine?
John Funcall, your choice is cola or water.
------
Jane Doloop, woud you like a TV-show or movie?
Dr. Evel, woud you like a TV-show or movie?
Sue Property, woud you like a TV-show or movie?
John Funcall, movies are not available for you.
------
Jane Doloop, woud you like a cocktail or wine?
Dr. Evel, woud you like a cocktail or wine?
Sue Property, woud you like a cocktail or wine?
John Funcall, your choice is cola or water.
------
Jane Doloop, it's time to throw garbage
Dr. Evel, it's time to throw garbage
Sue Property, it's time to throw garbage
John Funcall, it's time to throw garbage


texts: Sort a binary file without loading it into memory or using a temporary file

texts:
I had a silly assignment:

  You are given a binary file FLOATS.DAT of unknown length, type float
  data has been written in it. Write a program which sorts the data in
  the file (the output is a sorted file FLOATS.DAT). You need to sort it
  without loading the file into memory, or by using a temporary file.
  Use the Shell sort algorithm.

Obviously by using a temp. file it would be easy, even more if you could load it into memory.

Here is my solution:

#include <stdio.h>

// sizeof(float) = 4 on my machine

int main(int argc, char **argv)
{
    size_t sajz = sizeof(float); // for convenience
    int n; // total number of floats in the file

    FILE *dat;

    dat = fopen("FLOATS.DAT", "r+b");

    if (dat == NULL)
    {
        printf("Error while opening.\n");
        return 1;
    }

    // find the number of floats in the file
    fseek(dat, 0, SEEK_END);
    n = ftell(dat)/sajz;
    rewind(dat);

    float tjmh, tx;
    int i,j,h;

    // standard shell sort algorithm, the hard part is when I have to
    // read a position I first have to jump to it, then read it,
    // same when writing to a location
    for (h = n/2; h>0; h/=2)
    {
        for (i=h; i<n; i++)
        {
            j = i;

            fseek(dat, i*sajz, SEEK_SET);
            fread(&tx, sajz, 1, dat);
            rewind(dat);

            fseek(dat, (j-h)*sajz, SEEK_SET);
            fread(&tjmh, sajz, 1, dat);
            rewind(dat);

            for (; j>=h && tx < tjmh; j -= h)
            {

                fseek(dat, j*sajz, SEEK_SET);
                fwrite(&tjmh, sajz, 1, dat);
                rewind(dat);

                // this was tricky to figure out
                // I need the value of `j` after it has been
                // subtracted from h
                fseek(dat, (j - 2*h)*sajz, SEEK_SET);
                fread(&tjmh, sajz, 1, dat);
                rewind(dat);
            }

            fseek(dat, j*sajz, SEEK_SET);
            fwrite(&tx, sajz, 1, dat);
            rewind(dat);

        }
    }

    fclose(dat);

    return 0;
}

Can this be improved in any way?

Code snippet to generate the file with numbers 2.0, 3.0, 10.0, 4.0, 1.0, 7.0, 9.0, 5.0, 6.0, 8.0

int main()
{
    FILE *dat;

    dat = fopen("FLOATS.DAT", "wb");

    float a;
    if (dat)
    {
        a = 2.00;
        fwrite(&a, sizeof(float), 1, dat);
        a = 3.00;
        fwrite(&a, sizeof(float), 1, dat);
        a = 10.00;
        fwrite(&a, sizeof(float), 1, dat);
        a = 4.00;
        fwrite(&a, sizeof(float), 1, dat);
        a = 1.00;
        fwrite(&a, sizeof(float), 1, dat);
        a = 7.00;
        fwrite(&a, sizeof(float), 1, dat);
        a = 9.00;
        fwrite(&a, sizeof(float), 1, dat);
        a = 5.00;
        fwrite(&a, sizeof(float), 1, dat);
        a = 6.00;
        fwrite(&a, sizeof(float), 1, dat);
        a = 8.00;
        fwrite(&a, sizeof(float), 1, dat);

        fclose(dat);
    }

    return 0;
}

You can use an array here as well.


texts:
I wrote the following code for a contest and worked fine for me. Could I make it a bit faster?

#include<iostream>
using namespace std;

int power(int,int,int);

int main(int argc,char** argv){
    int base,exponent,mod;
    cin>>base>>exponent>>mod;
    cout<<power(base,exponent,mod)<<endl;
    return 0;
}

int power(int base,int exponent,int mod){
    if(mod==1)return 0;
    int ans=1;
    for(int i=0;i<exponent;i++){
        ans=(ans*base)%mod;
    }
    return ans;
}


texts: Hiding and showing spreadsheet rows based on cell value

texts:
I'm currently using the following code that is triggered as each cell in a column is updated.  It works fine, but takes a couple seconds for every cell, which is really cumbersome with ~200 cells to complete the sheet.  Is there any way to speed up this code?

Private Sub Worksheet_Change(ByVal Target As Range)

Application.ScreenUpdating = False
Sheet1.Cells.EntireRow.AutoFit

Dim iLastRow As Variant
Dim i As Integer
iLastRow = Range("R1:R" & Cells(Rows.Count, "R").End(xlUp).Row).Value

For i = 1 To UBound(iLastRow, 1)
    If Range("R" & i) = "Show" Then
        Rows(i).EntireRow.Hidden = False
    Else
        Rows(i).EntireRow.Hidden = True
    End If
Next

Application.ScreenUpdating = True

End Sub


texts: How to tweak Tape Equilibrium assignment on Codility to be of complexity O(N)?

texts:
Why Codility detects my solution for Tape Equilibrium to have complexity of \$O(n^2)\$. How can I make my code better?

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.IntStream;

class Solution {
    public int solution(int[] A) {
        boolean eachIntegerIsWithinValidRange = IntStream.of(A).allMatch(i -> (i >= -1000 && i <= 1000));
        boolean numberOfElementsIsWithinDesignatedBounds = A.length >= 2 && A.length <= 100000;

        if (numberOfElementsIsWithinDesignatedBounds && eachIntegerIsWithinValidRange) {
            List<Integer> differences = new ArrayList<Integer>();
            if (A.length < 3) {
                Arrays.sort(A);
                return A[0];
            }

            for (int j = 0; j < A.length - 1; j++) {
                int[] subArrayOne = Arrays.copyOfRange(A, 0, j + 1);
                int[] subArrayTwo = Arrays.copyOfRange(A, j + 1, A.length);
                int sumOne = IntStream.of(subArrayOne).sum();
                int sumTwo = IntStream.of(subArrayTwo).sum();

                differences.add(Math.abs(sumOne - sumTwo));
            }
            Collections.sort(differences, (o1, o2) -> o1.compareTo(o2));
            return differences.get(0);
        } else if (!eachIntegerIsWithinValidRange) {
            throw new RuntimeException("There is/are integer that is out of designated bound: -1000 to 1000");
        } else if (!numberOfElementsIsWithinDesignatedBounds) {
            throw new RuntimeException("Invalid array size. Allowed number of elements is more than 1 and less than 100,001");
        }
        return 0;
    }
}


texts:
Here is my implementation of a segment tree with a sample driver file (I didn't make an update function because I didn't need it for what I was doing).

I'm a huge fan of geeksforgeeks, but I do not understand why this link makes such a complicated implementation.  I didn't use the height or compute the maximum size in order to build mine. Not to mention, their structure really isn't a tree; it's an integer array.

I'm looking for what I implemented well and what I did not implement well.

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

typedef struct segment_tree_node_s
{
  struct segment_tree_node_s * left;
  struct segment_tree_node_s * right;
  int start;
  int end;
  int sum;
} segment_tree_node_t;

typedef struct segment_tree_s
{
  segment_tree_node_t * root;
} segment_tree_t;

int build_tree(segment_tree_node_t **, int, int);
int query_tree(segment_tree_node_t *, int, int);

static const int ra[] = {1,3,5,7,9,11};
int main(int argc, char * argv[])
{
  segment_tree_t * new_tree = (segment_tree_t *) malloc(sizeof(segment_tree_t));
  int length = sizeof(ra)/sizeof(ra[0]);
  int sum = build_tree(&new_tree->root, 0, length - 1);
  int sum_2 = query_tree(new_tree->root, 0, 0);
  int sum_3 = query_tree(new_tree->root, 0, 1);
  int sum_4 = query_tree(new_tree->root, 0, 2);
  int sum_5 = query_tree(new_tree->root, 0, 3);
  int sum_6 = query_tree(new_tree->root, 0, 4);
  int sum_7 = query_tree(new_tree->root, 1, 5);
  int sum_8 = query_tree(new_tree->root, 2, 4);
  int sum_9 = query_tree(new_tree->root, 4, 5);
  int sum_10 = query_tree(new_tree->root, 5, 5);

  printf("Sum of tree [0-5]: %d\n", sum);
  printf("Sum of tree [0-0]: %d\n", sum_2);
  printf("Sum of tree [0-1]: %d\n", sum_3);
  printf("Sum of tree [0-2]: %d\n", sum_4);
  printf("Sum of tree [0-3]: %d\n", sum_5);
  printf("Sum of tree [0-4]: %d\n", sum_6);
  printf("Sum of tree [1-5]: %d\n", sum_7);
  printf("Sum of tree [2-4]: %d\n", sum_8);
  printf("Sum of tree [4-5]: %d\n", sum_9);
  printf("Sum of tree [5-5]: %d\n", sum_10);

  return 0;
}

int build_tree(segment_tree_node_t ** node, int start, int end)
{
  *node = (segment_tree_node_t *)malloc(sizeof(segment_tree_node_t));
  (*node)->sum = 0;

  if(start != end)
  {
    (*node)->start = start;
    (*node)->end   = end;
    int mid = start + (end - start)/2;
    return (*node)->sum = build_tree(&((*node)->left), start, mid) + build_tree(&((*node)->right), mid + 1, end);
  }
  else
  {
    (*node)->start = start;
    (*node)->end   = end;
    (*node)->sum = ra[start];
    return ra[start];
  }
}

int query_tree(segment_tree_node_t * node, int start, int end)
{
    /* Total overlap */
    if(node->start >= start && node->start <= end)
    {
        if(node->end <= end && node->end >= start)
            return node->sum;
    }

    /* Partial overlap */
    if((start >= node->start && start <= node->end) || (end >= node->end && end <= node->start) || (start <= node->start && end >= node->start))
            return query_tree(node->left, start, end) + query_tree(node->right, start, end);

    /* No overlap */
    return 0;
}


texts:
I made a translator for the English language. As of now it only translates from Spanish, Russian, and Arabic (will be adding more languages).

The program pulls the input from a yaml file with a list of words and phrases inside of it. It searches the users input and if it finds a match it returns with the English translation of the word or phrase!

require 'yaml'

def welcome
    puts "Welcome to the Translation Center! Please enter the language you would like to translate to English or you can choose from the list below:
    1. Spanish
    2. Russian
    3. Arabic"
    input = language = gets.chomp!
    case language
    when /spanish/i
        spanish_translate
    when "1"
        spanish_translate
    when /russian/i
        russian_translate
    when "2"
        russian_translate
    when /arabic/i
        arabic_translate
    when "3"
        arabic_translate
    else
        puts "Language is not yet supported within Translation Center."
        exit
    end
end

def spanish_translate
    translations = YAML.load_file 'spanish.yml'
    puts "Enter word or phrase to be translated to English, press 'Q' to quit:"
    input = gets.chomp
    case
    when translations[input]
        puts "The translation from Spanish to English is: #{translations[input]}"
    when input =~ /q/i
        exit
    else
        puts "Invalid word or phrase redirecting..."
        spanish_translate
    end
end

def russian_translate
    translation = YAML.load_file 'russian.yml'
    puts "Enter word or phrase you would like translated to English, press 'Q' to quit:"
    input = gets.chomp!
    case
    when translations[input]
        puts "The translation from Russian to English is: #{translations[input]}"
    when input =~ /q/i
        exit
    else
        puts "Invalid word or phrase redirecting..."
        russian_translate
    end
end

def arabic_translate
    translation = YAML.load_file 'arabic.yml'
    puts "Enter word or phrase you woukd like translated to English, press 'Q' to quit:"
        input = gets.chomp!
        input = gets.chomp!
    case
    when translations[input]
        puts "The translation from Arabic to English is: #{translations[input]}"
    when input =~ /q/i
        exit
    else
        puts "Invalid word or phrase redirecting..."
        arabic_translate
    end
end
welcome

Here's the Spanish yaml file:

a: to
abajo: down
el abancio: fan
buenos dias: good morning
buenos tardes: good afternoon
como se llama usted: what is your name
como esta usted: how are you
estoy bien: i am fine
mucho gusto: nice to meet you
perdoname: excuse me
por favor: please
gracias: thank you
lo siento: i'm sorry
salud: bless you
de nada: you are welcome
hay muchos: there are many
si: 'yes'
no: 'no'
yo no comprendo: i do not understand
yo quiero una tortilla: i want a tortilla

Russian yaml file:

и: and, though
в: in, at
не: not
он: he
на: on, it, at, to
я: I
что: what, that, why
тот: that
быть: to be
с: with and, from, of
а: while, and, but
весь: all, everything
это: that, this, it
как: how, what, as, like

Arabic yaml file:

salam: hi
سلام: hi
Sabah el kheer: good morning
صباح الخير: good morning
massa el kheer: good evening
مساء الخير: good evening
marhaban: welcome
مرحبا: welcome
Kaifa haloka: how are you(male)
kaifa haloki: how are you(female)
كيف حالك؟: how are you
ana bekhair shokran: i'm fine thanks
أنا بخير شكر: im fine thanks
wa ant: and you(male)
wa anti: and you (female)
و أنت؟: and you
jayed: good
'aadee: so-so
عادي: good
جيد: so-so

It now has the ability to translate to three different languages.

How's this looking as an OOP language overall? What can I do differently next time?


texts: Calculate time to the offset of another time zone

texts:
I have a time stamp with UTC +0, i.e.

time_stamp = Sat, 08 Apr 2017 16:01:16 UTC +00:00

I'm converting the time/date part of the time stamp to another time zone's offset, and am using this custom Time method for this:

def tz_adjusted_timestamp(time_zone)
  time_stamp        = self
  offset_in_seconds = time_stamp.in_time_zone(time_zone).utc_offset
  offset_in_minutes = offset_in_seconds / 60
  time_stamp        += offset_in_minutes.minutes
  time_stamp
end

I assume there are many smarter ways to accomplish this?

Expected result:

time_stamp.tz_adjusted_timestamp("Europe/Stockholm")

    Sat, 08 Apr 2017 18:01:16 UTC +00:00


texts: Test a number for primality and return smallest divisor different from 1 if it’s is composite

texts:
In this exercise we were asked to test a number for primality and print the results. Additionally – in the case the number is composite – the smallest divisor different from 1 should be printed out. Negative input values shall not pre processed and result in a message.

The second part of that task to improve the performance of the test and wipe out as many redundant and unnecessary comparisons as possible. We were not allowed to use any built-in methods to check for primality.

I have concerns mainly about properly handling input I’m rejecting and naming things (talking about result here).

/**
 * Tests a positive integer for primality.
 * Prints out whether a number is prime, composite or neither.
 */
public class PrimalityTest {
    public static void main(String[] args) {
        // We only test one number, so no other arguments are allowed.
        if (args.length > 1) {
            System.out.println("Too many arguments. Please enter a positive integer prime canidate.");
            System.exit(1);
        }

        int primeCandidate = 0;
        try {
            primeCandidate = Integer.parseInt(args[0]);
        } catch (NumberFormatException e) {
            System.out.println("The entered value was not an integer.");
            System.exit(1);
        }

        if (primeCandidate < 0) {
            System.out.println("Negative numbers are never prime.");
            System.exit(1);
        }

        int result = smallestDivisor(primeCandidate);
        if (result == -1) {
            System.out.println(primeCandidate + " is prime.");
        } else if (result == 1 || result == 0) {
            System.out.println(primeCandidate + " is neither prime nor composite.");
        } else {
            System.out.println(primeCandidate + " is composite and has the smallest divisor " + result + ".");
        }
    }

    /**
     * Returns the smallest divisor of composite numbers or
     * 1 if the number is 1 (not composite, not prime) or
     * -1 if the number is prime (not composite).
     */
    public static int smallestDivisor(int primeCandidate) {
        if (primeCandidate == 0 || primeCandidate == 1) {
            return primeCandidate;
        } else if (primeCandidate <= 3) {
            // 2 and 3 are prime.
            return -1;
        } else if (primeCandidate % 2 == 0) {
            // All numbers greater 2 and divisable by 2 are not prime and the smallest divisor is 2
            return 2;
        } else if (primeCandidate % 3 == 0) {
            // All numbers greater 3 and divisable by 3 are not prime and the smallest divisor is 3
            return 3;
        } else {
            // Checks divisability of numbers in the form of 6k+1 and 6k-1.
            // It starts with: 5 and 7, 11 and 13, 17 and 19, 23 and 25, ...
            for (int i = 5; i * i <= primeCandidate; i += 6) {
                if (primeCandidate % i == 0) {
                    return i;
                } else if (primeCandidate % (i + 2) == 0) {
                    return i + 2;
                }
            }
            // No divisor found, the number is prime.
            return -1;
        }
    }
}


texts:
I have a stream of sensor data which I want to visualize in a plot with many subplots. Plotting the data is a real bottleneck in my code. Right now I get with small resolution only 16 FPS which is far too slow.

Here is what it looks like:

import time
from matplotlib import pyplot as plt
import numpy as np

def live_plot():
    loops=100
    n = 7
    p = 30
    fig, axes = plt.subplots(ncols=n, nrows=n)
    fig.canvas.draw()
    handles=[]
    axes = np.array(axes)
    for ax in axes.reshape(-1):
        ax.axis("off")
        handles.append(ax.imshow(np.random.rand(p,p), interpolation="None", cmap="RdBu"))
    t0 = time.time()
    for i in np.arange(loops):
        for h in handles: h.set_data(np.random.rand(p,p))
        for h, ax in zip(handles, axes.reshape(-1)): ax.draw_artist(h)
        plt.pause(1e-12)
    print("avg: " + "%.1f" % (loops/(time.time()-t0)) + " FPS")

live_plot()

What can I do to get more frames per second?


texts: Collecting folly::Futures with an associated value

texts:
I'm trying to implement a batch API where requests are associated with an id. In the batch response, the individual success/failure responses should be associated to their corresponding request id.

The code looks like this

class Request {};
class Response {};
class BatchResponse {};
folly::SemiFuture<Response> handle(Request foo) {
  return folly::makeSemiFuture(Response{});
}

folly::SemiFuture<BatchResponse> batchAPI() {
  // input batched requests
  std::map<int, Request> requests = {{1, Request{}}, {2, Request{}}};

  // a collection of handled requests with their ids
  std::vector<folly::SemiFuture<std::pair<int, folly::Try<Response>>>> responses;
  responses.reserve(requests.size());

  // loop and handle requests
  for (auto& entry : requests) {
    int requestId = entry.first;
    // associate response with request id
    responses.push_back(
        handle(entry.second)
            .via(folly::getCPUExecutor().get())
            .thenTry([requestId](const folly::Try<Response>&& tryBar) {
              return std::make_pair(requestId, tryBar);
            }));
  }

  // this is the returned SemiFuture<BatchResponse>
  return folly::collectAllSemiFuture(responses)
      .via(folly::getCPUExecutor().get())
      .thenValue([](const auto& tryResponses) {
        BatchResponse response;
        for (const auto& tryPair : tryResponses) {
          // guaranteed to be successful
          std::pair<int, folly::Try<Response>> pair = tryPair.value();
          int requestId = pair.first;
          folly::Try<Response> handleResult = pair.second;

          if (handleResult.hasValue()) {
            // add value and requestId to response
          } else {
            // add exception and requestId to response
          }
        }
        return response;
      });
}

I don't like that I have to capture the requestId in the response future and transform into a pair of the two. As result, I have to unwrap the std::pair with tryPair.value(); since I know it'll be successful.

An alternative I've considered is maintaining a parallel std::vector of the request ids and capturing that in the SemiFuture returned by collectAllSemiFuture, since they would be in the same order.

Are there cleaner designs?


texts:
I have this piece of code in my program, where I assign 10000 as the size of the buffer. Now How can I check if the file that I am copying is less than 10000, for example 5000, than how to free the remaining 5000 back?
Thank You.
private void copyFile(File in, File out) {
        var buffer = new byte[10000];
        try {
            FileInputStream dis = new FileInputStream(in);
            FileOutputStream dos = new FileOutputStream(out);
            int count;
            do {
                count = dis.read(buffer);
                if (count != -1)
                    dos.write(buffer, 0, count);
            } while (count != -1);
            dis.close();
            dos.close();
        } catch (IOException e) {
            program.print("Error copying file: " + e.toString() + "\n", null);
        }
    }

EDIT: Is there anyway, I can optimize this more?


texts:
I have converted this code from Java to Scala, and I need reviews.  This works fine, but I am sure that something is wrong with this coding pattern.

package models

import org.apache.log4j.ConsoleAppender
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.apache.log4j.PatternLayout
import org.apache.log4j.RollingFileAppender

import me.prettyprint.cassandra.serializers.StringSerializer

object LogFile extends CassandraConnection {

  val loger = Logger.getRootLogger()
  def exceptionLogs(qName: String, data: String) {
    //data is json String
    val logg = Logger.getLogger(qName + "-" + data)
    loger.setLevel(Level.ERROR)
    val layout = new PatternLayout("[%t] %-5p %c %x - %m %d{ISO8601} %n")
    loger.addAppender(new ConsoleAppender(layout))
    try {
      val fileAppender = new RollingFileAppender(layout, "QLog.txt")
      loger.addAppender(fileAppender)
      logg.error("")
      loger.removeAppender(fileAppender)
    } catch {
      case e: Exception =>
        println(e)
        logg.error("");
    }
  }

}


texts:
I am just picking up C++11 and decided to try some algorithmic problems to get better at it. One such problem is the fractional knapsack problem which can be solved by a greedy approach. The idea is to find the most valuable item and fill it in and move on to the next one till the knapsack is filled. Partial items are allowed.

I hope this code can be reviewed for:

Correctness
Correct usage of C++11 features
Code logic improvement
Coding conventions

struct Item {
    float value;
    float size;
    uint32_t index;
};

uint32_t FillKnapsack(std::vector<Item> &Items, const uint32_t MaxCap)
{
    // sorting is done based on value/size ratio of the item
    std::sort(Items.begin(),
              Items.end(),
              [](const Item& A, const Item& B) { return (A.value/A.size) > (B.value/B.size); });

    float c = 0, v = 0;

    for (const auto& item: Items) {
        if (c + item.size <= MaxCap) {
            c += item.size;
            v += item.value;
        }
        else {
            v += (MaxCap - c)/item.size * item.value;
            c = MaxCap;
        }

        std::cout << "adding item " << item.index << " with value " << item.value << std::endl;
        std::cout << "c: " << c << " v: " << v << std::endl;

        // since the knapsack is filled we can break out.
        if (c >= MaxCap)
            break;
    }
    return v;
}

int main()
{
    std::vector<Item> items = { { 10, 30, 0},
                                { 20, 20, 1},
                                { 30, 10, 2} };
    std::cout << FillKnapsack(items, 35) << std::endl;
    return 0;
}


texts:
I was running some rightsizing tests and had to blast random objects of my various class types. Here is the code I came up with.

private static <T> T random(Class<?> recordClass) {

    Constructor<?>[] constructors = recordClass.getConstructors();
    Constructor<?> maxParamConstructor = constructors[0];

    for (Constructor<?> check : constructors) {
        if (check.getParameterCount() > maxParamConstructor.getParameterCount())
            maxParamConstructor = check;
    }

    if (maxParamConstructor.getParameterCount() > 0) {

        Type[] types = maxParamConstructor.getGenericParameterTypes();
        Object[] params = new Object[types.length];

        for (int index = 0; index < types.length; index++) {
            params[index] = getRandom(types[index].getTypeName());
        }

        return (T) maxParamConstructor.newInstance(params);
    } else
        return (T) recordClass.newInstance();
}

private static Object getRandom(String type) {

    switch (type) {

        //TODO add others
        case "java.lang.Long":
            return ThreadLocalRandom.current().nextLong();
        case "java.lang.Boolean":
            return ThreadLocalRandom.current().nextBoolean();
        case "java.lang.String":
            return UUID.randomUUID().toString();
        case "java.lang.CharSequence":
            return UUID.randomUUID().toString();
        case "java.lang.Double":
            return ThreadLocalRandom.current().nextDouble();

        default:
            return random(Class.forName(type));
    }
}

Was wondering if it would give me trouble during my tests.
Is it any good ? thanks.


texts: Converting tcpdump output to text2pcap acceptable input


texts:
This code takes a website and downloads all .jpg images in the webpage. It supports only websites that have the <img> element and src contains a .jpg link.

(Tested here)

import random
import urllib.request
import requests
from bs4 import BeautifulSoup

def Download_Image_from_Web(url):
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text, "html.parser")
    raw_text = r'links.txt'
    with open(raw_text, 'w') as fw:
        for link in soup.findAll('img'):
            image_links = link.get('src')
            if '.jpg' in image_links:
                for i in image_links.split("\\n"):
                    fw.write(i + '\n')
    num_lines = sum(1 for line in open('links.txt'))
    if num_lines == 0:
        print("There is 0 photo in this web page.")
    elif num_lines == 1:
        print("There is", num_lines, "photo in this web page:")
    else:
        print("There are", num_lines, "photos in this web page:")
    k = 0
    while k <= (num_lines-1):
        name = random.randrange(1, 1000)
        fullName = str(name) + ".jpg"
        with open('links.txt', 'r') as f:
            lines = f.readlines()[k]
            urllib.request.urlretrieve(lines, fullName)
            print(lines+fullName+'\n')
        k += 1

Download_Image_from_Web("https://pixabay.com")


texts:
Inspired by Reddit r/dailyprogrammer

  A vampire number v is a number v=xy with an even number n of digits formed by multiplying a pair of n/2-digit numbers (where the digits are taken from the original number in any order) x and y together. Pairs of trailing zeros are not allowed. If v is a vampire number, then x and y are called its "fangs."
  EDIT FOR CLARITY Vampire numbers were original 2 two-digit number (fangs) that multiplied to form a four digit number. We can extend this concept to an arbitrary number of two digit numbers. For this challenge we'll work with three two-digit numbers (the fangs) to create six digit numbers with the same property - we conserve the digits we have on both sides of the equation.

As always, looking for general feedback over code readability, structure and efficiency. But also I was looking to make the code a bit more flexible.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created on 6/29/2016.
 *
 * Inspired by r/dailyprogrammer
 * https://www.reddit.com/r/dailyprogrammer/comments/3moxid/20150928_challenge_234_easy_vampire_numbers/
 *
 */

public class VampireNumbers {

    /**
     * Calls generate function then displays return value.
     * @param args Not used in this application.
     */
    public static void main(String args[]){
        generate().forEach(System.out::println); // Generates vampires, displays them on screen.
    }

    /**
     * Generates list of vampire numbers. Currently only supports 3 fangs of length 2.
     * @return List of vampires generated along with their fangs.
     */
    private static List<String> generate(){
        ArrayList<String> vampires = new ArrayList<>();
        for (int i = 10; i < 100; i++) {
            String fangOne = String.valueOf(i);
            for (int j = i; j < 100; j++) {
                String fangTwo = String.valueOf(j);
                for (int k = j; k < 100; k++) {
                    String fangThree = String.valueOf(k);
                    String vampire = String.valueOf(i * j * k);
                    if (sortVampire(fangOne + fangTwo + fangThree).equals(sortVampire(vampire))){
                            vampires.add(String.format("%s * %s * %s = %s", fangOne, fangTwo, fangThree, vampire));
                    }
                }
            }
        }
        return vampires;
    }

    /**
     * Used to sort a string of numbers. Helpful when determining if all fangs
     * are within the generated vampire number.
     * @param vampire String of numbers
     * @return The sorted character list of the given string.
     */
    private static List<Character> sortVampire(String vampire){
        List<Character> list = new ArrayList<>();
        for (int i = 0; i < vampire.length(); i++){
            list.add(vampire.charAt(i));
        }
        Collections.sort(list);
        return list;
    }
}

It works as of now but can only generate 3 fangs(of length 2) creating vampire numbers of length 6. Was looking to expand the parameters of the generate function to something like:

private static List<String> generate(int fangLength, int vampireLength)

Also I had a question over this line specifically:

if (sortVampire(fangOne + fangTwo + fangThree).equals(sortVampire(vampire)))

Instead of concatenating all three fangs, would it be worth it to use a StringBuilder in this scenario?


texts: Vue + Vuex + Firebase serverless realtime chat

texts:
I am "discovering" Firebase and I'm trying create simple chat with Vue, Vuex and Firebase. But because I'm just starting out with Vue, I need code review or advices from more experienced programmers. I need to know whether this code is properly structured - if it is well written in "Vue way" - and how to make my components better - more universal / better separated from rest of the code.

jsFiddle

var uid = null

var firebaseConfig = {
  apiKey: "AIzaSyDGYiab8xoIXIgbFSmLSwXubNL2T3Rr6AQ",
  authDomain: "first-steps-6abb2.firebaseapp.com",
  databaseURL: "https://first-steps-6abb2.firebaseio.com"
}

var store = new Vuex.Store({
  state: {
    messages: []
  },
  mutations: {
    addMessage (state, message) {
      state.messages.push(message)
      if (state.messages.length > 10) {
        state.messages.shift()
      }
    }
  }
})

var listMessages = {
  template: `

        {{message.time}} {{ message.text }}

  `,
  data () {
    return {
      messages: this.$store.state.messages
    }
  }
}

var addMessage = {
  template: `

      Add new:
      <input id="message" @keyup.enter v-model="message">
      <button @click="sendMsg">Send</button>

  `,
  data () {
    return {
      message: ''
    }
  },
  methods: {
    sendMsg () {
      messages.push().set({
        uid: uid,
        content: this.message,
        timestamp: firebase.database.ServerValue.TIMESTAMP
      })
      this.message = ''
    }
  }
}

firebase.initializeApp(firebaseConfig)
firebase.auth().signInAnonymously()
firebase.auth().onAuthStateChanged(function (user) {
  if (user) { uid = user.uid }
})

new Vue({
  el: '#app',
  store,
  components: {
    listMessages,
    addMessage
  }
})

var db = firebase.database()
var messages = db.ref('messages')
var query = messages.orderByChild('timestamp').limitToLast(10)

query.on('child_added', function (data) {
  store.commit('addMessage', {
    uid: data.val().uid,
    text: data.val().content,
    time: moment(data.val().timestamp).format('hh:mm:ss')
  })
})
html, body {
  margin: 0;
  height: 100%;
}
.container {
  min-height: 100%;
  position: relative;
}
.list-messages {
  position: absolute;
  box-sizing: border-box;
  width: 100%;
  top: 10px;
  margin: 0;
  padding: 10px;
  list-style: none;
}
.list-messages span {
  color: lightblue;
}
.add-message {
  text-align: center;
  position: absolute;
  width: 100%;
  bottom: 10px;
}

  <list-messages></list-messages>
  <add-message></add-message>


texts:
For learning Rust I decided to make a 3D .obj viewer. I wrote a simplified OBJ parser without materials that only supports triangles.

Considering I'm completely new to Rust and don't really know anyone who's good at idiomatic Rust I figured I'd ask here :)

use std::fs;

use crate::geometry::*;
use crate::object::Object;

fn str_to_vec3(s: &str) -> Option<Vec3> {
    let bits: Vec<&str> = s.split(" ").collect();
    if bits.len() != 3 {
        return None;
    }

    Some(Vec3 {
        x: bits[0].parse().unwrap(),
        y: bits[1].parse().unwrap(),
        z: bits[2].parse().unwrap(),
    })
}

fn str_to_vec2(s: &str) -> Option<Vec2> {
    let bits: Vec<&str> = s.split(" ").collect();
    if bits.len() != 2 {
        return None;
    }

    Some(Vec2 {
        x: bits[0].parse().unwrap(),
        y: bits[1].parse().unwrap(),
    })
}

type VertexDescription = (usize, usize, usize);
type TriangleDescription = (VertexDescription, VertexDescription, VertexDescription);

fn str_to_vertex_description(s: &str) -> Option<VertexDescription> {
    let bits: Vec<&str> = s.split("/").collect();
    if bits.len() != 3 {
        return None;
    }

    Some((
        bits[0].parse::<usize>().unwrap() - 1,
        bits[1].parse::<usize>().unwrap() - 1,
        bits[2].parse::<usize>().unwrap() - 1,
    ))
}

fn str_to_triangle_description(s: &str) -> Option<TriangleDescription> {
    let bits: Vec<&str> = s.split(" ").collect();
    if bits.len() != 3 {
        return None;
    }

    Some((
        str_to_vertex_description(bits[0]).expect("Failed to parse vertex"),
        str_to_vertex_description(bits[1]).expect("Failed to parse vertex"),
        str_to_vertex_description(bits[2]).expect("Failed to parse vertex"),
    ))
}

pub fn parse(path: String) -> Object {
    let object_string = fs::read_to_string(path).expect("Cannot read .obj file!");
    let lines = object_string.lines();
    let mut positions: Vec<Vec3> = vec![];
    let mut normals: Vec<Vec3> = vec![];
    let mut uvs: Vec<Vec2> = vec![];
    let mut triangle_descriptions: Vec<TriangleDescription> = vec![];

    for line in lines {
        match &line[0..2] {
            "v " => match str_to_vec3(&line[2..]) {
                Some(vec3) => positions.push(vec3),
                None => panic!("Malformed 'v' value!"),
            },
            "vn" => match str_to_vec3(&line[3..]) {
                Some(vec3) => normals.push(vec3),
                None => panic!("Malformed 'vn' value!"),
            },
            "vt" => match str_to_vec2(&line[3..]) {
                Some(vec2) => uvs.push(vec2),
                None => panic!("Malformed 'vt' value!"),
            },
            "f " => match str_to_triangle_description(&line[2..]) {
                Some(td) => triangle_descriptions.push(td),
                None => panic!("Malformed 'f' value!"),
            },
            _ => {}
        }
    }

    let triangles: Vec<Triangle3> = triangle_descriptions
        .iter()
        .map(|&td| {
            let v1: Vertex3 = Vertex3 {
                pos: positions[(td.0).0],
                uv: uvs[(td.0).1],
                normal: normals[(td.0).2],
            };
            let v2: Vertex3 = Vertex3 {
                pos: positions[(td.1).0],
                uv: uvs[(td.1).1],
                normal: normals[(td.1).2],
            };
            let v3: Vertex3 = Vertex3 {
                pos: positions[(td.2).0],
                uv: uvs[(td.2).1],
                normal: normals[(td.2).2],
            };
            (v1, v2, v3)
        })
        .collect();

    let mut obj = Object::new();
    obj.triangles = triangles;
    obj
}

Is this a good approach? What can I improve on?

Any feedback is welcome!


texts:
I've written a function to parse configuration files. It doesn't handle file opening, but instead takes an array with the file contents and tries to find fields based on an array containing the fields' names. If found, it puts the content into its respective place.

The only rules it has so far are:

each field is delimited by a newline '\n'
case doesn't matter for the field's name
after a field's name has been found, leading spaces and tabs are irrelevant and discarded
lines containing unrecognized fields are ignored
the character separating the field's name and its respective content must be specified in the field's name

Example file:

FIELD 1: CONTENT 1
FIELD 2: CONTENT 2
FIELD 3: CONTENT 3
FIELD 4: CONTENT 4
FIELD 5: CONTENT 5

Here's an example call:

char *configuration = load_file(file_name);
char *field1;
char *field2;
char *field3;
char *field4;
char *field5;

static const char *fields[] = {
        "FIELD 1:",
        "FIELD 2:",
        "FIELD 3:",
        "FIELD 4:",
        "FIELD 5:",
        0
    };
    char **destinations[] = {
        &field1,
        &field2,
        &field3,
        &field4,
        &field5,
        0
    };

    //Parse and load fields
    parse(destinations, fields, configuration);

And the function:

//strings allocated must be freed by the caller
static void parse(char ***destinations, const char **fields, const char *source)
{
    char buffer[BUFFER_SIZE];
    int i, j, buffer_position;

    while(*source != '\0')
    {
        for(i = 0; fields[i] != 0; ++i)
        {
            //check if first character match, case insensitive
            if(*fields[i] == *source || inverse_case(*fields[i]) == *source)
            {
                //check if subsequent characters match
                for(j = 0; fields[i][j] != '\0'; ++j)
                {
                    if(fields[i][j] != source[j] && inverse_case(fields[i][j]) != source[j]) break;
                }

                //it's not the right field, look for another
                if(fields[i][j] != '\0') continue;

                //found, update pointer position
                source += j;

                //skip leading spaces and tabs
                while(*source == ' ' || *source == '\t') ++source;

                //collect content
                for(buffer_position = 0; *source != '\n' && buffer_position < BUFFER_SIZE - 1; ++buffer_position, ++source)
                {
                    buffer[buffer_position] = *source;
                }
                buffer[buffer_position] = '\0';

                //if it's an empty line, nothing to copy
                if(buffer_position > 0)
                {
                    //allocate memory for destination and copy
                    if((*destinations[i] = malloc(buffer_position + 1)) != 0)
                    {
                        COPY(*destinations[i], buffer);
                    }

                    //if there's an error on malloc(), we just skip the field and notify the user
                    else
                    {
                        printf("Error: malloc(%d)\n", buffer_position + 1);
                    }
                }

                //since we found a field that matches, no need to keep looking
                //break the for loop, skip the while and process next line
                goto next_iteration;
            }
        }
        //no matches for the current line just skip it entirely
        while(*++source && *source != '\n');

        next_iteration:
        ++source;
    }
}

My questions:

Would it be considered better if the line delimiter was defined by the caller?
By adding the options to not ignore spaces and tabs, and set case sensitivity on/off, would the parameter list be considered too big?


texts:
If one menu-item is clicked then the description with the same data-filter attribute should be shown.

I added a class to the description elements to associate each one with the affiliated menu item.

What do you think?

$(".button").click(function() {
  $(".button").removeClass("active-filter");
  $(this).addClass("active-filter");

  var button = $(this).attr("data-filter");
  var active_element = $('.descr[data-filter="' + button + '"]');

  $(".descr").removeClass("active-element");
  active_element.addClass("active-element");
});
.element {
  display: inline-block;
  background-color: lightgreen;
  width: 220px;
}

.filter {
  display: inline-block;
  margin: 10px;
  background-color: orange;
}

.button {
  width: 60px;
  height: 60px;
  padding: 10px;
  margin: 10px;
  background-color: lightgrey;
  float: left;
}

.descr {
  display: block;
  max-height: 0;
  visibility: hidden;
  background-color: lightgrey;
  padding: 10px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin: 10px;
}

.data-element {
  height: 60px;
  display: block;
  background-color: orange;
  margin: 10px;
  position: relative;
}

.active-filter {
  background-color: yellow;
  display: block;
}

.active-element {
  background-color: yellow;
  max-height: 100%;
  visibility: visible;
}

data-filter 1

data-filter 2

data-element 1

data-element 2


texts:
This is a function I just wrote that tries to condense a set of strings into grouped lines. It actually works, but looks ugly. Is there a better way to achieve the same thing?

Take 4 filtering empty strings first and dropping the if line on the final yield

def mergeToLines(strings, length=40, sep="    "):
    strs = (st for st in sorted(strings, key=len, reverse=True) if st)
    line = strs.next()
    for s in strs:
        if (len(line) + len(s) + len(sep)) >= length:
            yield line
            line = s
        else:
            line += sep + s
    yield line

The idea is that it takes a bunch of strings, and combines them into lines about as long as lineLength. Each line has one or more of the original strings in it, but how many isn't clear until I actually get to slotting them in. Also, note that if a single entry in the list is longer than lineLength, it's still added as its own line (dropping elements is not an option here).


texts:
How would I be able to improve the speed of this Monty Hall program?
 Interestingly, the same code written using BBC BASIC for Windows completes the task in half the time of the Python code.

Python:

import random

t = 10000001
j = 0
k = 0

for a in range(1, t):
    p = int(random.random() * 3) + 1
    g = int(random.random() * 3) + 1

    if p == g:
        r = int(random.random() * 2) + 1
        if p == 1:
            r += 1
        if p == 2 and r == 2:
            r = 3
    else:
        r = p ^ g
    s = g
    f = g ^ r
    if s == p:
        j = j + 1
    if f == p:
        k = k + 1

print(f"After a total of {t - 1} trials,")
print(f"The 'sticker' won {j} times ({int(j/t*100)}%)")
print(f"The 'swapper' won {k} times ({int(k/t*100)}%)")

BBC BASIC for Windows:

T% = 10000000

for A% = 1 to T%
  P% = rnd(3)
  G% = rnd(3)
  if P% = G% then

    R% = rnd(2)
    if P% = 1 then R% += 1
    if P% = 2 and R% = 2 then R% = 3
  else
    R% = P% eor G%
  endif
  S% = G%
  F% = G% eor R%
  if S% = P% then J% = J% + 1
  if F% = P% then K% = K% + 1
next

print "After a total of ";T%;" trials,"
print "The 'sticker' won ";J%;" times (";int(J%/T%*100);"%)"
print "The 'swapper' won ";K%;" times (";int(K%/T%*100);"%)"


texts:
I have implemented a binary heap in Go to get familiar with the language.

GitHub

package heap

import (
    "sync"
)

type Item interface {
    Less(than Item) bool
}

type Heap struct {
    sync.Mutex
    data []Item
    min  bool
}

func New() *Heap {
    return &Heap{
        data: make([]Item, 0),
    }
}

func NewMin() *Heap {
    return &Heap{
        data: make([]Item, 0),
        min:  true,
    }
}

func NewMax() *Heap {
    return &Heap{
        data: make([]Item, 0),
        min:  false,
    }
}

func (h *Heap) isEmpty() bool {
    return len(h.data) == 0
}

func (h *Heap) Len() int {
    return len(h.data)
}

func (h *Heap) Get(n int) Item {
    return h.data[n]
}

func (h *Heap) Insert(n Item) {
    h.Lock()
    defer h.Unlock()

    h.data = append(h.data, n)
    h.siftUp()

    return
}

func (h *Heap) Extract() (el Item) {
    h.Lock()
    defer h.Unlock()
    if h.Len() == 0 {
        return
    }

    el = h.data[0]
    last := h.data[h.Len()-1]
    if h.Len() == 1 {
        h.data = nil
        return
    }

    h.data = append([]Item{last}, h.data[1:h.Len()-1]...)
    h.siftDown()

    return
}

func (h *Heap) siftUp() {
    for i, parent := h.Len()-1, h.Len()-1; i > 0; i = parent {
        parent = i >> 1
        if h.Less(h.Get(i), h.Get(parent)) {
            h.data[parent], h.data[i] = h.data[i], h.data[parent]
        } else {
            break
        }
    }
}

func (h *Heap) siftDown() {
    for i, child := 0, 1; i < h.Len() && i<<1+1 < h.Len(); i = child {
        child = i<<1 + 1

        if child+1 <= h.Len()-1 && h.Less(h.Get(child+1), h.Get(child)) {
            child++
        }

        if h.Less(h.Get(i), h.Get(child)) {
            break
        }

        h.data[i], h.data[child] = h.data[child], h.data[i]
    }
}

func (h *Heap) Less(a, b Item) bool {
    if h.min {
        return a.Less(b)
    } else {
        return b.Less(a)
    }
}

It works fine and my tests pass just fine. I have implemented a heap sort based on this.

However, my implementation of heapsort give very very very bad performances, even when benchmark against \$O(n^2)\$algorithms such as insertion short.

Here are my results for both heap and insertion sort on the same data sets:

BenchmarkHeapSort100       20000         95676 ns/op
BenchmarkHeapSort1000        500       3613389 ns/op
BenchmarkHeapSort10000         5     287265292 ns/op
BenchmarkHeapSort100000        1    37184383822 ns/op
ok      github.com/arnauddri/algorithms/algorithms/sorting/heap-sort    43.738s
PASS

BenchmarkInsertionSort100   10000000           228 ns/op
BenchmarkInsertionSort1000   1000000          1857 ns/op
BenchmarkInsertionSort10000   100000         18822 ns/op
BenchmarkInsertionSort100000           1    3949000733 ns/op
ok      github.com/arnauddri/algorithms/algorithms/sorting/insertion-sort   12.348s
PASS

I have reviewed my code but I struggle to see what leads to bad performances. I'd really appreciate it if someone had a piece of advice on how I can improve my data structure.


texts:
I'm attempting this question on HackerRank, which states the follows:

  You are given a list of \$N\$ people who are attending ACM-ICPC World
  Finals. Each of them are either well versed in a topic or they are
  not. Find out the maximum number of topics a 2-person team can know.
  And also find out how many teams can know that maximum number of
  topics.

  Note Suppose \$a\$, \$b\$, and \$c\$ are three different people, then \$(a,b)\$ and
  \$(b,c)\$ are counted as two different teams.

  Input Format

  The first line contains two integers, \$N\$ and \$M\$, separated by a single
  space, where \$N\$ represents the number of people, and M represents the
  number of topics. \$N\$ lines follow. Each line contains a binary string
  of length \$M\$. If the ith line's jth character is \$1\$, then the ith person
  knows the jth topic; otherwise, he doesn't know the topic.

In my code below, I replaced \$N\$ with ppl and \$M\$ with topics.

ppl, topics = map(int, input().split())
knowledge = []

max_group = 0
max_topic = 0

for x in range(ppl):
    inp = input()
    x = [int(i) for i in inp]
    knowledge.append(x)

for x in range(ppl):
    for y in range(x+1, ppl):
        current_topic = 0

        for z in range(topics):
            if knowledge[x][z] | knowledge[y][z] == 1:
                current_topic += 1

        if current_topic == max_topic:
            max_group += 1
        elif current_topic > max_topic:
            max_topic = current_topic
            max_group = 1

print(max_topic)
print(max_group)

The solution above should return the correct outputs (passed three test cases), but there are simply way too many loops (5, if I am correct). What are some ways that I can reduce the amount of loops and bring the run-time down?


texts: Return nil after loop and also in unless block in Ruby

texts:
I have a working code as below. Is there any better way to return nil after the each loop and unless else in the below example?
def find_member(member_name)
  unless members.empty?
    members.each do |member|
      if member.name == member_name
        return member
      end
    end
    nil
  else
    nil
  end
end

I should pass nil in each case because there are different conditions in other methods where this method is called. That is the reason why I have written the code as above.


texts:
I am working on class for simple sharing values between threads without race-conditions, which can't be a std::atomic (this means, no POD and no trivially-copyable types).
The initial intention was to lock a std::function against writing while reading from an other thread.

The class itself is simple; just lock a mutex at every sensitive part of the class, but I am not totally sure if it's correct or not. I think about to lock the mutex in the dtor, but I don't know if it's good style or not.

#pragma once

template <class T>
class LockedValue
{
private:
    using Lock = std::scoped_lock<std::mutex>;

public:
    LockedValue() = default;

    LockedValue(const LockedValue& _other) :
        m_Value(_other.load())
    {}

    LockedValue(LockedValue& _other) :
        LockedValue(static_cast<const LockedValue&>(_other))
    {}

    LockedValue(LockedValue&& _other) :
        m_Value(_other._takeValue())
    {}

    template <class... Args>
    LockedValue(Args&&... _args) :
        m_Value(std::forward<Args>(_args)...)
    {}

    LockedValue& operator =(const LockedValue& _other)
    {
        auto value = _other.load();
        store(std::move(value));
        return *this;
    }

    LockedValue& operator =(LockedValue&& _other)
    {
        if (this != &_other)
            store(_other._takeValue());
        return *this;
    }

    template <class T_, typename = std::enable_if_t<std::is_convertible_v<T_, T>>>
    LockedValue& operator =(T_&& _value)
    {
        store(std::forward<T_>(_value));
        return *this;
    }

    T operator *() const
    {
        return load();
    }

    template <class T_>
    void store(T_&& _value)
    {
        Lock lock(m_Mutex);
        m_Value = std::forward<T_>(_value);
    }

    T load() const
    {
        Lock lock(m_Mutex);
        return m_Value;
    }

private:
    mutable std::mutex m_Mutex;
    T m_Value;

    T&& _takeValue()
    {
        Lock lock(m_Mutex);
        return std::move(m_Value);
    }
};

EDIT: Is it necessary to check for self-moving in move assign? I think it should be ok to remove the self check.

EDIT2: To the copy ctor related discussion. Delete the non-const& copy ctor from the class and try to use an object like this.

If you don't have c++17 change the Lock alias to std::lock_guard and change std::is_convertible_v to std::is_convertible::value

I pasted it at this online compiler with the ctor already deactivated
click me

// calls the variadic ctor
LockedValue<std::string> s("test");

// this is fine; calls the usual copty ctor
auto u(static_cast<const LockedValue<std::string>&>(s));

/* results in an error because type LockedValue<std::string>&
can not be converted to std::string; this means a second call
for the variadic ctor*/
auto t(s);


texts:
I tried to make a simple qsort() function in a functional way, it takes a vector and a bool pred()

Suggestions as to make it more functional, optimize it, and/or remove extra steps and intermediate variables are appreciated

template <typename T>
void operator+=(std::vector<T> &v1, const std::vector<T> &v2) {
    v1.insert(v1.end(), v2.begin(), v2.end());
}

template <typename T, typename Func>
std::vector<T> qsort(const std::vector<T>& in, const Func& pred) {
    std::vector<T> out;
    std::vector<T> less;
    std::vector<T> more;

    if (in.size() < 2)
        return in;
    auto p = in[0];
    for (auto i = 1; i < in.size(); i++) {
        if (pred(p, in[i]))
            less.push_back(in[i]);
        else
            more.push_back(in[i]);
    }
    out = qsort(less, pred);
    out.push_back(p);
    out += qsort(more, pred);

    return out;
}


texts:
I've written a php function and some helper functions that checks for cookies when somebody lands on a page but it's not so fast. I want to know is there any way to make it faster or improve it i know it's possible to check for cookies client side using javascript but what if it is disabled also so i need a pure server side solution.

<?php

function check_cookie(){
    if(is_cookie_disabled()){
        header("location:cookie_is_disabled.php");
        exit;
    }
}

function is_cookie_disabled(){
    $curr_url = $_SERVER['PHP_SELF'];
    if(isset($_COOKIE['testCookie']) && !(isset($_COOKIE['cookie']))){
        $original_url = original_url ($curr_url);
        header("location: ".$original_url);
        setcookie("cookie", 'enabled');
        exit;
    } elseif(!(isset($_COOKIE['testCookie']))) {
        if(isset($_GET['temp'])){
            return true;
        } else{
            if(if_parameters_exist_in_url($curr_url)){
                $url = $curr_url."&temp=temp";
            } else {
                $url = $curr_url."?temp=temp";
            }
            header("location: ".$url);
            setcookie("testCookie", 'test');
            exit;
        }
    }
    return false;
}

function original_url ($curr_url){
    if (!empty($_GET)){
        if (isset($_GET['temp'])) {
            if(count($_GET)>0){
                return removeqsvar($curr_url, 'temp');
            } else {
                return removeallvars($curr_url);
            }
        }
    }
    return $curr_url;
}

function removeqsvar($url, $varname) {
    return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}

function removeallvars($url){
    return $url = strtok($url, '?');
}

function if_parameters_exist_in_url($url){
    if (strpos($url, '=')) {
        return true;
    } else {
        return false;
    }
}

//at the top of your pages
check_cookie();

?>


texts: Generating random number inside a paralleled loop (openmp)

texts:
What is the most fast and safe way of generating random numbers inside a pararelled loop? I did as below but I'm not sure if it is correct or not:

using namespace std;
std::minstd_rand gen(std::random_device{}());
std::uniform_real_distribution<double> unirnd(0, 1);
int main(){
double eta=something;
double x[N];
//initializing x[]
for (i=0;i<N;i++)
{
double z= unirnd(gen) * eta;
x[i] = some function of x[i] and z
}
}

To compile the code, I use g++ -fopenmp -std=gnu++11 -Wall -Wextra -g code.cpp -o a.out


texts: Separate an email address into its username and domain name

texts:
This is my first ever Python program and I wanted to get everyone's opinions on it. The goal of the program is to separate an email address into its username and domain name.
import sys
import getopt

argv = sys.argv[1:]

# -------Error Handling-Start----------
try:
    opts, args = getopt.getopt(argv, "l:s:h", ["list ", "single ", "help "])
except getopt.GetoptError as err:
    print(f"{err}\n""\n"
          "Usage: <Options> <Input> \n"
          "-l, --list        Specify a list of emails to be sliced \n"
          "-s, --single      Specify a single email to be sliced \n"
          "-h, --help        Show options")
    opts = []
# -------Error Handling-End------------

for opt, file_arg in opts:
    if opt in ['-h', '--help']:
        sys.exit("Usage: <Options> <Input> \n"
                 "-l, --list        Specify a list of emails to be sliced \n"
                 "-s, --single      Specify a single email to be sliced \n"
                 "-h, --help        Show options")
# If option -h is present, display MAN page

for opt, email_arg in opts:
    if opt in ['-s', '--single']:
        email = email_arg
        username = email[:email.index('@')]
        domain = email[email.index('@') + 1:]
        print(f"Your username: {username}")
        print(f"Your domain name: {domain}\n")
# If option -s is present, split input email into username and domain then print the output

for opt, file_arg in opts:
    if opt in ['-l', '--list']:
        file = file_arg

        email_file = open(file, "r")

        for string in email_file:
            username = string[:string.index('@')]
            domain = string[string.index('@') + 1:]
            print(f"Your username: {username}")
            print(f"Your domain name: {domain}")
# If option -l is present read file specified then loop through each line while splitting each into username and domain

if len(sys.argv) == 1:
    sys.exit("Usage: <Options> <Input> \n"
             "-l, --list        Specify a list of emails to be sliced \n"
             "-s, --single      Specify a single email to be sliced \n"
             "-h, --help        Show options")
# If only one argument is supplied, print MAN page.


texts:
I implemented the well-known knapsack problem and now I would like to improve it using list comprehension or lambda. I don't want to use NumPy. Could you help me?

def get_optimal_value(capacity, weights, values):
    value = 0.
    numItems = len(values)
    valuePerWeight = sorted([[values[i] / weights[i], weights[i]] for i in range(numItems)], reverse=True)
    while capacity > 0 and numItems > 0:
        maxi = 0
        idx = None
        for i in range(numItems):
            if valuePerWeight[i][1] > 0 and maxi < valuePerWeight[i][0]:
                maxi = valuePerWeight[i][0]
                idx = i

        if idx is None:
            return 0.
        if valuePerWeight[idx][1] <= capacity:
            value += valuePerWeight[idx][0]*valuePerWeight[idx][1]
            capacity -= valuePerWeight[idx][1]
        else:
            if valuePerWeight[idx][1] > 0:
                value += (capacity / valuePerWeight[idx][1]) * valuePerWeight[idx][1] * valuePerWeight[idx][0]
                return value
        valuePerWeight.pop(idx)
        numItems -= 1
    return value

For completeness here is the client code to test the implementation with a simple example:

if __name__ == "__main__":
    n = 3
    capacity = 50
    values = [60, 100, 120]
    weights = [20, 50, 30]
    opt_value = get_optimal_value(capacity, weights, values)
    print("{:.10f}".format(opt_value)) # print 180.0000000000


texts: Clearing up property and field confusion in C#?

texts:
I understand that creating public properties that control private fields is good practice because of coupling and encapsulation, although lately I have seen it as such a waste of boilerplate code for a simple entity class like below.
Take this class for instance,
public class PersonEntity
{
    private string _firstName;
    private string _lastName;
    private int _age;

    public class PersonEntity(string firstName, string lastName, int age)
    {
        _firstName = firstName;
        _lastName = lastName;
        _age = age;
    }

    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }

    public int Age
    {
        get { return _age; }
        set { _age = value; }
    }
}

If all I am using is the property, is it okay to refactor the class to look something like this?
public class PersonEntity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public class PersonEntity(string firstName, stirng lastName, int age)
    {
        FirstName = firstName;
        LastName = lastName;
        Age = age;
    }
}

Or maybe even this is more simple (using object initialization to construct):
public class PersonEntity
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

Which one should I implement if all I want to use the entity for is to map data from a database, and use it as a model to write to the database at a later date than when it was created?
Which versions should I use, when should I use them, and for what reasons should I use each one?


texts: Two approaches to Logging when Unit Testing with Python

texts:
Python allows logging to be used in several ways.  Can you review the relative merits of these two approaches to Logging when Unit Testing with Python?  Is one approach appropriate to specific circumstances?  What are those circumstances and how might each approach be improved?

Directly addressing the logger.

#!/usr/bin/env python
import logging
import unittest

class LoggingTest(unittest.TestCase):

    logging.basicConfig(level=logging.INFO)

    def test_logger(self):
        logging.info("logging.info test_logger")
        pass

Getting a logger by name

#!/usr/bin/env python
import logging
import unittest

class GetLoggerTest(unittest.TestCase):
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    def test_logger(self):
        self.logger.info("self.logger.info test_logger")
        pass


texts: Calculating a total price by using switch statement and sentinel controlled loop

texts:
My homework is to make a program that calculates the total value of products sold.  It works, but I use the if statement because it was asking for the quantity on the output before ending the loop. And for the same reason, I couldn't make the program ask the user again to enter a number from 1 to 5.

import java.util.Scanner;

public class Sales {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        double sum = 0;
        int n = -1 ;
        while(n !=0 ) {

            System.out.println("Enter product number 1-5 (Enter  to stop)");
            n = input.nextInt();

            if (n==0)
                break;

            System.out.println("Enter quantity of product");
            int q = input.nextInt();

            switch (n) {
                case 1:
                    sum += 2.98*q;
                    break;
                case 2:
                    sum += 4.50*q;
                    break;
                case 3:
                    sum += 9.98*q;
                    break;
                case 4:
                    sum += 4.49*q;
                    break;
                case 5:
                    sum += 6.87*q;
                    break;
                default:
                    sum += 0;
                    break;
            }
        } System.out.printf("Total cost is $%.2f",sum);
    }
}


texts:
I have written this "Polyfill" for Chrome's Promise object and I have some concerns about the implementation;

Does it actually work as designed? It seems to work but I'm not sure if there are any "edge cases" I am not accounting for.
Is there a better way to do it? The inner function way seems a bit odd, as I don't like how I the promise[method] works.

Here is how the spread method works:

var resolvedArray = Promise.resolve([1, 2, 3]);

resolvedArray.spread(function(a, b, c) {
  console.log(a === 1); // true
  console.log(b === 2); // true
  console.log(c === 3); // true
});

var resolvedOther = Promise.resolve("Hello");

resolvedOther.spread(function(value) {
  console.log(value === "Hello"); // true
});

var rejectedArray = Promise.reject([1, 2, 3]);

rejectedArray.spread(undefined, function(a, b, c) {
  console.log(a === 1); // true
  console.log(b === 2); // true
  console.log(c === 3); // true
});

var rejectedObject = Promise.reject("Hello");

rejectedObject.spread(undefined, function(value) {
  console.log(value === "Hello"); // true
});

And here is my implementation:

Promise.prototype.spread = function() {
  var promise = this;

  var spread = function(promise, method, callback) {
    return promise[method](function(previousValue) {
      if (previousValue instanceof Array) {
        return callback.apply(undefined, previousValue);
      } else {
        return callback.call(undefined, previousValue);
      }
    });
  };

  if (arguments.length >= 1 && arguments[0] !== undefined) {
    promise = spread(promise, 'then', arguments[0]);
  }

  if (arguments.length >= 2 && arguments[1] !== undefined) {
    promise = spread(promise, 'catch', arguments[1]);
  }

  return promise;
};


texts: Multithreaded lock-free queue implementation

texts:
My partner and I are beginning to believe there could be a desync possibility in the lock free queue we have written, but we would like some fresh eyes on the subject. What are your thoughts on our design?

// nolockqueue.hpp:
#ifndef NOLOCKQUEUE_HPP
#define NOLOCKQUEUE_HPP

template<typename T>
class noLockQueue {
public:
    noLockQueue();
    ~noLockQueue();
    void push(const T dataVar);
    bool pop(T &dataVar);

private:
    struct node {
        node(T dataPassed) : dataVar(dataPassed), next(NULL) {};
        T dataVar;
        node* next;
    };

    node* topOfList;
    node* bottomOfList;
};

template<typename T>
noLockQueue<T>::noLockQueue() {
    topOfList = NULL;
    bottomOfList = NULL;
}

template<typename T>
noLockQueue<T>::~noLockQueue() {
    node* temp;

    while (topOfList != NULL) {
        temp = topOfList->next;
        delete topOfList;
        topOfList = temp;
    }

    if (bottomOfList != NULL)
        throw("Not All Nodes Deleted - nolockqueue/38/.cpp"); // TODO: Strange error to throw.
}

template<typename T>
void noLockQueue<T>::push(const T dataVar) {
    if (topOfList == NULL) {
        topOfList = bottomOfList = new node(dataVar);
        return;
    } else {
        bottomOfList->next = new node(dataVar);
        bottomOfList = bottomOfList->next;
    }
}

template<typename T>
bool noLockQueue<T>::pop(T &dataVar) {
    if (topOfList == NULL)
        return false;

    dataVar = topOfList->dataVar;
    node* temp = topOfList->next;
    delete topOfList;
    topOfList = temp;
    return true;
}

#endif

// main.cpp (purely a test unit):
#include <iostream>
#include <thread>

#include "nolockqueue.hpp"
#include <windows.h> // For Sleep().

noLockQueue<int> queue;

void threadFunc() {
    int var = 0;
    Sleep(10);
    while (queue.pop(var)) {
        std::cout << "\nPopped: " << var;
        Sleep(1);
    }
}

int main(int argc, char* argv[]) {
    std::thread myThread(threadFunc);

    for (int i = 0; i < 1000; ++i) {
        queue.push(i);
        std::cout << "\nPushed: " << i;
        Sleep(1);
    }

    myThread.join();

    std::cin >> argc;
    return 0;
}


texts:
Can this query be improved? I iterate over a couple of thousand times, and if I can improve it, it should decrease the run time.  Otherwise I might look into using a batch instead of doing one at a time. I'm using MS SQL 11.

job
****
id
name

job_stats
*************
id
job_id
median_runtime

select js.median_runtime from job_stats js
      join job j
      on j.id = js.job_id
      where j.name = '%s'


texts: Run python File With get request flask API

texts:
Code is Working Review and Recommend What Are Best Practice
What I am trying to achieve.

API with Flask that runs any python file from the current directory.

Run the file and get output in JSON

Below is the code for the app.py
from flask import Flask,jsonify
from flask_restful import Api,Resource
import os

app = Flask(__name__)
api = Api(app)

class callApi(Resource):
    def get(self,file_name):
        my_dir = os.path.dirname(__file__)
        file_path = os.path.join(my_dir, file_name)
        file = open(file_path)
        getvalues={}
        exec(file.read(),getvalues)
        return jsonify({'data':getvalues['total']})

api.add_resource(callApi,"/callApi/<string:file_name>")

if __name__ == '__main__':
   app.run(debug='true')

Below is the code for the main.py which sends a request to API.with Filename which to run.
The filename will be changed as per requirements.
import requests

BASE = 'https://127.0.0.1/callApi/runMe.py'

response = requests.get(BASE)
print(response.encoding)

Below is the File which runs by exec from API
API/app.py can access this file because both are in the same dir.
def fun():
    a = 10
    b = 10
    total = a+b
    print(total)
    return total

total = fun()

Is there any better way to write all this code please let me know.
here are refs which I used to make this
Eval function
Exec Function
Exec Docs
Running a python script saved in local machine from google sheets on a button press


texts:
A number chain is created by continuously adding the square of the
  digits in a number to form a new number until it has been seen before.

  For example,

  44 → 32 → 13 → 10 → 1 → 1
  85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89

  Therefore any chain that arrives at 1 or 89 will become stuck in an
  endless loop. What is most amazing is that EVERY starting number will
  eventually arrive at 1 or 89.

  How many starting numbers below ten million will arrive at 89?

To tackle this problem I used the following procedure.

set array[1] to 1
set array[89] to 89
loop through all starting numbers from 2 to 10,000,000
for each starting number, calculate sum of squares until a previously calculated number is found
mark off all numbers in the chain you have just created as either 89 or 1
count the number of starting numbers that now have 89 as their array value

However even after using this relative clever strategy, my code still takes half a minute to compute. Is there something wrong I have done in my logic, or are there any other obvious improvements? I also think this strategy uses a large chunk of memory.

def square_digits(num):
    # Squares the digits of a number, eg 44=4^2+4^2=32
    total = 0
    while num:
        total += (num % 10) ** 2
        num //= 10
    return total

def single_chain(num, square_dict):
    # Evaluates a single chain untill 1 or 89
    temp_nums = []
    while True:
        if num in [1, 89]:
            break
        try:
            # If we hit a previously calculated value, break
            num = square_dict[num]
            break
        except:
            temp_nums.append(num)
            num = square_digits(num)
    for i in temp_nums:
        # Backtrack through the chain saving each number
        square_dict[i] = num
    return num == 1, square_dict

def pre_calculation(limit):
    # Precalculates the first values
    square_dict = dict()
    for i in range(1,limit+1):
        num = i
        while num not in [1,89]:
            num = square_digits(num)
        if num == 1:
            square_dict[i] = 1
        else:
            square_dict[i] = 89
    return square_dict

def square_chains(limit, square_dict):
    # Finds the number of chains ending in 1 and 89
    count_1 = 0
    count_89 = 0
    for i in range(1, limit):
        boolean, square_dict = single_chain(i, square_dict)
        if boolean:
            count_1 += 1
        else:
            count_89 += 1
    print "Chains ending in 1: ", count_1
    print "Chains ending in 89: ", count_89

if __name__ == '__main__':
    square_dict = pre_calculation(9*9*7)
    square_chains(10**7,square_dict)


texts: Circular Queue Implementation Using Array in java

texts:
Here is my code of Array Implementation of Queue in java.

import java.util.Scanner;
class CircularQueue
{
int maxSize;
int rear;
int front;
int aQueue[];
{
    rear = -1;
    front = -1;
}
CircularQueue(int maxSize)
{
    this.maxSize = maxSize;
    this.aQueue = new int[maxSize];
}
void enQueue(int item)
{
    if(((rear+1) % maxSize) == front)
    {
        System.out.println("Queue is Full");
    }
    else
    {
        if (rear == front && front == -1)
        {
            front += 1;
        }
        rear = (rear+1) % maxSize;
        aQueue[rear] = item;
    }
}
void deQueue()
{
    if(rear == front && rear == -1)
    {
        System.out.println("Queue is Empty.");
    }
    else
    {
        int item = aQueue[front];
        if(rear == front)
        {
            rear = -1;
            front = -1;
        }
        else
        {
            front = (front + 1) % maxSize;
        }
        System.out.println(item + " is deQueued from the Queue");
    }
}

String elementOrElements()
{
    String send = (rear == front)? (" ") :("s ");
    return send;
}

void display()
{
    int tmpfront = front;
    if(rear == front && rear == -1)
            {
                    System.out.println("Queue is Empty.");
            }
            else
    {
        System.out.println("The element"+ elementOrElements() + "on the Queue are:- ");
        for(int i=0; i<maxSize ; i++)
        {
            if(tmpfront != rear)
            {
                System.out.println(aQueue[tmpfront]);
                tmpfront = (tmpfront + 1) % maxSize;
            }
            else
            {
                System.out.println(aQueue[rear]);
                break;
            }
        }
    }
}
public static void main(String []args)
{
    Scanner input = new Scanner(System.in);
    System.out.print("Enter total no of elements to be in the queue:- ");
    int maxSize = input.nextInt();
    CircularQueue queue = new CircularQueue(maxSize);
    int select;
    int term = 0;
    while (term == 0)
    {
        System.out.print("\nOption:\tTo Do:\n1\tTo push element.\n2\tTo POP element.\n3\tTo Display the Queue elements.\n4\tTo Exit the Program.\nEnter your option:- ");
                select = input.nextInt();
        switch(select)
        {
            case 1:
            {
                System.out.print("Enter element to insert in the Queue:- ");
                int ele = input.nextInt();
                queue.enQueue(ele);
                break;
            }
            case 2:
            {
                queue.deQueue();
                break;
            }
            case 3:
            {
                queue.display();
                break;
            }
            case 4:
            {
                term = 1;
                System.out.println("Thank you!");
                break;
            }
            default:
                System.out.println("Enter a valid options");
        }
    }
  }
}

Is there anything I can do to improve it? Code written for DSA class practical.