texts: Finding the bundle of the most similar strings in an array

texts:
I used the minimum edit distance algorithm to find the bundle of the most similar strings in an array. So, I have to travel double for loop to compare all elements.

If the data is large enough, this algorithm is Inefficient.

Values have rules:

value's length is 10
value is A-Z and can't be duplicated

Is there a way to optimize?

let data = [
  "10000", // count
  "asdfqwerty", "asdfzxcvgh", "asdfpoiuyt", // values
  ...
]

for i in 1..<data.count {
  let string = data[i]
  for j in (i + 1)..<data.count {
    let newMin = string.minimumEditDistance(other: data[j])

    if min >= newMin {
      // some logic
    }
  }
}

extension String {
  public func minimumEditDistance(other: String, `default`: Int = 10) -> Int {
    let m = self.count
    let n = other.count

    if m == 0 || n == 0 {
      return `default`
    }

    var matrix = [[Int]](repeating: [Int](repeating: 0, count: n + 1), count: m + 1)

    // initialize matrix
    for index in 1...m {
      // the distance of any first string to an empty second string
      matrix[index][0] = index
    }

    for index in 1...n {
      // the distance of any second string to an empty first string
      matrix[0][index] = index
    }

    // compute Levenshtein distance
    for (i, selfChar) in self.enumerated() {
      for (j, otherChar) in other.enumerated() {
        if otherChar == selfChar {
          // substitution of equal symbols with cost 0
          matrix[i + 1][j + 1] = matrix[i][j]
        } else {
          // minimum of the cost of insertion, deletion, or substitution
          // added to the already computed costs in the corresponding cells
          matrix[i + 1][j + 1] = Swift.min(matrix[i][j] + 1, matrix[i + 1][j] + 1, matrix[i][j + 1] + 1)
        }
      }
    }
    return matrix[m][n]
  }
}

```


texts: Improving script performance for looping unparalleled arrays

texts:
Ive written a script to loop through a couple of unparalleled arrays a loop within a loop, Now im trying to find out if using break is all that's needed to exit and then continue over again.

What eles can you see or know to improve this?

var arr_vals = ["74","f4e3","22","r31","17","hundernds"]; // could have 500+ items
var arr_items = ["r31","22","65","100"]; // could have 50 items

var c = arr_items.length;
var arr_vals_len = arr_vals.length;
 for ( var i = 0; i < c; i++ ) {
   var xid = arr_items[i];

     for (var j = 0; j < arr_vals_len; j++ ){
      if(arr_vals[j] === xid){
      // match !
      break;
}
 }


texts: Efficient String permutations calculation in Java

texts:
In trying to compute permutations of a given String, what can I do to further improve the code below for memory and/or time efficiency?

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

public class Main {

    public static void main(String[] args) {
        permutateString("ABC");
    }

    private static void permutateString(String str) {

        List<String> results = permutations(new StringBuilder(str), new ArrayList<>());
        System.out.println("Number of permutations: " + results.size()
                            + "\n" + "Permutations: \n" + results);
    }

    private static List<String> permutations(StringBuilder input, List<String> permutationsList) {

        if (input.length() == 0 || input.length() == 1) {
            permutationsList.add(input.toString());
        }
        else {
            char prefix;
            StringBuilder substring;

            for (int i=0; i<input.length(); i++) {
                prefix = input.charAt(i);
                substring = new StringBuilder(input).deleteCharAt(i);
                for (String str : permutations(substring, new ArrayList<>())) {
                    permutationsList.add(String.valueOf(prefix) + str);
                }
            }
        }
        return permutationsList;
    }
}


texts:
I want to build the markup below by iterating on an array of objects.  The structure of the object is also listed below.  I need some tips on how to make it clean.

Markup I want to build:

Crowne Plaza Hotel

                    <s>S$ 275</s>
                S$ 275

JavaScript:

//the object structure of each data
{
    name: "Hotel A",
    loc: "Prontera Rd",
    dist: 9,
    img: "img/rendezvous-hotel.jpg",
    price: 350,
    deal_price: 350,
    currency: "S$",
    star_rating: 4
}

function constructDOMFragment(data) {
    var fragment = document.createDocumentFragment();
    for (var i = data.length - 1; i >= 0; i--)(function(obj) {

        var div_container = document.createElement("div");
        div_container.className = "pull-left col-xs-4";

        var div_thumbnail = document.createElement("div");
        div_thumbnail.className = "thumbnail";

        div_container.appendChild(div_thumbnail);

        var div_caption_top = document.createElement("div");
        div_caption_top.className = "caption";

        var h5 = document.createElement("h5");
        h5["innerHTML" || "textContent"] = obj.name;
        div_caption_top.appendChild(h5);
        div_thumbnail.appendChild(div_caption_top);

        var img = document.createElement("img");
        img.className = "img-responsive";
        img.src = obj.img;
        img.alt = obj.name;

        div_thumbnail.appendChild(img);

        var div_caption_bottom = document.createElement("div");
        div_caption_bottom.className = "caption";

        var h3_deal_price = document.createElement("h3");
        h3_deal_price.className = "pull-right";
        if (obj.price !== undefined && obj.price && obj.price != obj.deal_price) {
            var price = document.createElement("small");
            var strikethrough = document.createElement("s");
            strikethrough["innerHTML" || "textContent"] = obj.currency + " " + obj.price;
            price.appendChild(strikethrough);
            h3_deal_price.appendChild(price);
        }
        h3_deal_price.appendChild(document.createTextNode("  " + obj.currency + " " + obj.price));

        div_caption_bottom.appendChild(h3_deal_price);

        var clearfix = document.createElement("div");
        clearfix.className = "clearfix";
        div_caption_bottom.appendChild(clearfix);

        div_thumbnail.appendChild(div_caption_bottom);
        fragment.appendChild(div_container);

    })(data[i]);

    var clearfix = document.createElement("div");
    clearfix.className = "clearfix";
    fragment.appendChild(clearfix);

    return fragment;
};


texts:
In my webpage, I have the following @media queries:

/* Smartphones (iPhone 3GS/4 and others; portrait and landscape) */
@media only screen and (min-width: 320px) and (max-width: 480px){
    html {
        font-size: 60%;
    }
}

/* iPhone 5 (portrait and landscape) */
@media only screen and (min-width: 320px) and (max-width: 568px){
    html {
        font-size: 60%;
    }
}

/* iPhone 6 (portrait and landscape) */
@media only screen and (min-width: 375px) and (max-width: 667px){
    html {
        font-size: 60%;
    }
}

/* iPhone 6 Plus (portrait) */
@media only screen and (min-width: 414px) and (max-width: 736px) and (orientation : portrait){
    html {
        font-size: 60%;
    }
}

/* Other smartphones with smaller screen (portrait and landscape) */
@media only screen and (max-width : 319px){
    html {
        font-size: 50%;
    }
}

/* iPads 1/2 iPad Mini (portrait and landscape) */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (-webkit-min-device-pixel-ratio : 1) {
    html {
        font-size: 90%;
    }
}

/* iPad 3/4 (portrait and landscape) */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (-webkit-min-device-pixel-ratio : 2) {
    html {
        font-size: 62.5%;
    }
}

/* Google Nexus 10 (portrait) */
@media only screen and (min-device-width : 800px) and (max-device-width : 1280px) and (orientation : portrait) {
    html {
        font-size: 100%;
    }
}

/* Google Nexus 7 (portrait) */
@media only screen and (min-device-width : 604px) and (max-device-width : 966px) and (orientation : portrait) {
    html {
        font-size: 100%;
    }
}

/* Google Nexus 7 2 (portrait and landscape) */
@media only screen and (min-device-width : 600px) and (max-device-width : 960px) {
    html {
        font-size: 100%;
    }
}

/* Desktops and laptops */
@media only screen  and (min-width : 1224px) {
    html {
        font-size: 100%;
    }
}

/* Large screens */
@media only screen  and (min-width : 1824px) {
    html {
        font-size: 150%;
    }
}

/* Motorola Nexus 6 (portrait and portrait) */
@media only screen and (min-device-width : 1440px) and (max-device-width : 2560px) and (-webkit-min-device-pixel-ratio : 3.5) {
    html {
        font-size: 200%;
    }
}

This works very well, but I am concerned because this is a lot of code and not a smart code.

What is the smarter way of writing these @media queries so that I dont have to write it for every device but it supports every device appropriately?


texts:
This program is eventually going to be a screen recorder, but right now I just want it to capture screen images.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Drawing;
using System.Windows.Forms;

namespace ScreenRecorder
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static bool recording = false;
        public static string saveAddress = @"C:\Users\UserName\Desktop\something.bmp";

        public MainWindow()
        {
            InitializeComponent();
        }

        private void onClick(object sender, RoutedEventArgs e)
        {
            System.Drawing.Image currentImage;
            if (recording == false)
            {
                currentImage =  this.CaptureScreen();
                recording = true;
                recorderButton.Content = "Stop Recording!";
                currentImage.Save(saveAddress);
            }
            else
            {
                recording = false;
                recorderButton.Content = "Start Recording!";
            }
        }

        private System.Drawing.Image CaptureScreen()
        {
            System.Drawing.Rectangle screenSize = Screen.PrimaryScreen.Bounds;
            Bitmap target = new Bitmap(screenSize.Width, screenSize.Height);
            using (Graphics g = Graphics.FromImage(target))
            {
                g.CopyFromScreen(0, 0, 0, 0, new System.Drawing.Size(screenSize.Width, screenSize.Height));
            }
            return target;
        }
    }
}


texts: My node app with valid syntax is failing silently, but not breaking. Infrastructure problem?

texts:
I built a simple Node app, and the code "works", with no failures, no syntax errors, and does not break, but one component doesn't work right. I showed a snippet on Stack Overflow, in this question, but viewers found no issue. So, I think the infrastructure, the method, in which I put this app together must be problematic, and I'd like to have it reviewed.

I put everything into a single source file to eliminate the headache of debugging whilst keeping track of modules.

Here is the code

Here's my relevant script:

var connection = createConnection();

connection.connect(function (err) {
    if (err) return callback(new Error('Failed to connect'), null);
    console.log('[Post]Connection with the officeball MySQL database opened...');

    connection.query(
        'INSERT INTO `officeball`.`sales_entries` SET category = ?, `group` = ?, date = ?, price = ?, customer = ?, seller = ?, commission = ?',
    salesData),

    function (err, rows, fields) {

        if (err) console.log(err);
        connection.destroy();
        console.log('[Post]...Connection with the officeball MySQL database closed.');

    }
});

And here's my console output:

Application initializing...
Application successfully initialized!
Server running at http://127.0.0.1:8080/
User username1 is attempting to validate for a hit...
Connection with the Officeball MySQL database openned...
...Connection with the Officeball MySQL database closed.
User username1 validated and is ready!
[Post] Connection with the officeball MySQL database opened...


texts:
The title says it all. This is yet another FizzBuzz implementation where you can specify the words you want to use, though it autoselects the divisors as the first n primes other than 2, rather than having you enter them.

I'm looking for tips on variable/function naming and that kind of thing; I couldn't think of good ones when I wrote this. I'd also like any performance improvements that can be put in.

def n_primes(count)
    primes = []
    number = 2
    until primes.length == count
        primes << number if primes.inject(true) { |memo, cur| memo and number % cur != 0 }
        number += 1
    end
    primes
end

puts 'Enter the words you would like to use'
word_array = gets.chomp.split
puts 'Enter the number to count up to'
up_to = gets.chomp.to_i

words = {}
primes = n_primes(word_array.length + 1)[1..-1]
primes.each_with_index { |prime, index| words[prime] = word_array[index] }

1.upto(up_to) do |number|
    to_print = words.reject { |n, _| number % n != 0 }.values
    to_print = [number] if to_print.length == 0
    puts to_print.join ''
end

Note: I extracted n_primes into a function because it means I don't have to use meaningless names like p or num to avoid naming conflicts. If there's a better solution, I'd like to know it.

Sample output:

Enter the words you would like to use
> Fizz Buzz Wolf Foo Bar
Enter the number to count up to
> 100
1
2
Fizz
4
Buzz
Fizz
Wolf
8
Fizz
Buzz
Foo
Fizz
Bar
Wolf
FizzBuzz
16
17
Fizz
19
Buzz
FizzWolf
Foo
23
Fizz
Buzz
Bar
Fizz
Wolf
29
FizzBuzz
31
32
FizzFoo
34
BuzzWolf
Fizz
37
38
FizzBar
Buzz
41
FizzWolf
43
Foo
FizzBuzz
46
47
Fizz
Wolf
Buzz
Fizz
Bar
53
Fizz
BuzzFoo
Wolf
Fizz
58
59
FizzBuzz
61
62
FizzWolf
64
BuzzBar
FizzFoo
67
68
Fizz
BuzzWolf
71
Fizz
73
74
FizzBuzz
76
WolfFoo
FizzBar
79
Buzz
Fizz
82
83
FizzWolf
Buzz
86
Fizz
Foo
89
FizzBuzz
WolfBar
92
Fizz
94
Buzz
Fizz
97
Wolf
FizzFoo
Buzz

(The user input is prefixed with >, though it doesn't show up when you actually run the code)


texts: Breaking a line segment into two where it encounters a rectangle

texts:
I have developed a function that takes a list of line segments and a rectangle that breaks the line segment into two where it encounters the rectangle. Here is a picture demonstration of what it does:

And here is a full demo code representation here:

var ctx = document.querySelector("canvas").getContext("2d");

function drawSegments(segments) {
  for (let seg of segments) {
    ctx.beginPath();
    ctx.moveTo(seg.x1, seg.y1);
    ctx.lineTo(seg.x2, seg.y2);
    ctx.stroke();
  }
}

function drawRectangles(rectangles) {
  for (let r of rectangles) {
    ctx.beginPath();
    ctx.rect(r.x, r.y, r.w, r.h);
    ctx.stroke();
  }
}

// Returns the point (x, y) where two line segments intersect
function getLineIntersection(p0_x, p0_y, p1_x, p1_y, p2_x, p2_y, p3_x, p3_y) {
  let s1_x = p1_x - p0_x;
  let s1_y = p1_y - p0_y;
  let s2_x = p3_x - p2_x;
  let s2_y = p3_y - p2_y;

  let s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);
  let t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);

  if (s >= 0 && s <= 1 && t >= 0 && t <= 1) {
    return { x: p0_x + (t * s1_x), y: p0_y + (t * s1_y) };
  }

  return false;
}

function breakSegments(segments, rect) {
  let rLeft = rect.x;
  let rTop = rect.y;
  let rRight = rect.x + rect.w;
  let rBot = rect.y + rect.h;

  for (let i = 0; i < segments.length; i++) {
    let s = segments[i];

    let nIntersection = getLineIntersection(s.x1, s.y1, s.x2, s.y2, rLeft, rTop, rRight, rTop);
    let wIntersection = getLineIntersection(s.x1, s.y1, s.x2, s.y2, rLeft, rTop, rLeft, rBot);
    let eIntersection = getLineIntersection(s.x1, s.y1, s.x2, s.y2, rRight, rTop, rRight, rBot);
    let sIntersection = getLineIntersection(s.x1, s.y1, s.x2, s.y2, rLeft, rBot, rRight, rBot);

    var closeIntersection, farIntersection;

    if (nIntersection && sIntersection) {
      let nXDelta = nIntersection.x - s.x1;
      let nYDelta = nIntersection.y - s.y1;

      let sXDelta = sIntersection.x - s.x1;
      let sYDelta = sIntersection.y - s.y1;

      if (nXDelta * nXDelta + nYDelta * nYDelta < sXDelta * sXDelta + sYDelta * sYDelta) {
        closeIntersection = nIntersection;
        farIntersection = sIntersection;
      } else {
        closeIntersection = sIntersection;
        farIntersection = nIntersection;
      }
    } else if (wIntersection && eIntersection) {
      let wXDelta = wIntersection.x - s.x1;
      let wYDelta = wIntersection.y - s.y1;

      let eXDelta = eIntersection.x - s.x1;
      let eYDelta = eIntersection.y - s.y1;

      if (wXDelta * wXDelta + wYDelta * wYDelta < eXDelta * eXDelta + eYDelta * eYDelta) {
        closeIntersection = wIntersection;
        farIntersection = eIntersection;
      } else {
        closeIntersection = eIntersection;
        farIntersection = wIntersection;
      }
    } else {
      continue;
    }

    segments.splice(i + 1, 0, { x1: farIntersection.x, y1: farIntersection.y, x2: s.x2, y2: s.y2 });

    s.x2 = closeIntersection.x;
    s.y2 = closeIntersection.y;

    break;
  }
}

let lineSegments = [
  { x1: 0, y1: 50, x2: 250, y2: 50 },
  { x1: 250, y1: 50, x2: 250, y2: 250 },
  { x1: 250, y1: 250, x2: 100, y2: 250 },
  { x1: 100, y1: 250, x2: 80, y2: 75 },
  { x1: 400, y1: 550, x2: 525, y2: 550 },
  { x1: 525, y1: 550, x2: 550, y2: 350 },
  { x1: 550, y1: 350, x2: 300, y2: 350 },
];

let rects = [
  { x: 200, y: 240, w: 16, h: 16 },
  { x: 500, y: 340, w: 16, h: 16 }
]

breakSegments(lineSegments, rects[0]);
breakSegments(lineSegments, rects[1]);

drawSegments(lineSegments);
drawRectangles(rects);
<canvas width="800" height="800">

As you can see it already works. What I don't like is how complex it is. I feel like this should be able to be accomplished with less code. Specifically, breakSegments is very verbose in how it determines which intersection is closer, as I use the distance formula to determine this. Is there no better way of accomplishing this?


texts: Loading data async with queue. Proper write only locking and scheduling

texts:
I have to store and return data on multitasking requests. If data is missing, I schedule loading and return null. I'm using some nubie scheduling by saving current jobs in a list. Also I need data request to be locked during writing. .NET 4.0

How can I schedule and lock properly?

private ConcurrentDictionary<string, IDataSet> data;
private List<string> loadingNow;

public IDataSet GetData(string dataId)
{
    if (loadingNow.Contains(dataId))
        return null; // Currently loading. Return null

    if (data.ContainsKey(dataId))
        return data[dataId]; // Return data

    // Schedule loading async. Return null.
    loadingNow.Add(dataId);
    dataIoAsync.LoadDataAsync(dataParams);
    return null;
}

private void DataIoAsync_DataFileLoaded(object sender, DataFileLoadedAsyncEventArgs e)
{
    loadingNow.Remove(e.DataId);
    data.TryAdd(e.DataId, e.DataSet);
    OnDataFileLoaded(e.DataId);
}

EDIT: Dictionary replaced with ConcurrentDictionary


texts:
I've created a system to generate tokens that could potentially be used in some sort of program:

# _gen.py is simply to generate the tokens, not to check them.

import string, secrets, random

# String is for getting all ascii letters and digits.
# Secrets is for a cryptographically secure function to choose chars.
# Random is providing a random number generator.

# Base functions used to generate a token

def _tknFrag(length: int=32):
    """Generates a tknFrag, or Token Fragment."""
    return ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(length))

def _tknFragLen():
    """Returns the tknFrag's tknFragLen, or Token Fragment Length, an int in between 30 and 34"""
    return int(random.randint(30, 34))

def _insDot(tknFrag: str):
    """Inserts a dot in the tknFrag at the end"""
    tknFrag += "."
    return tknFrag

def _insDash(tknFrag: str):
    """Inserts a dash in the tknFrag at the end"""
    tknFrag += "-"
    return tknFrag

def _ins(tknFrag: str):
    """Inserts a dash or a dot inside of the tknFrag"""
    return {
        "0" : lambda frag: _insDot(tknFrag=frag),
        "1" : lambda frag: _insDash(tknFrag=frag)
    }[str(random.randint(0, 1))](tknFrag)

# Now on to actually generating the tokens

# This is one last helper function, completely generating a fragment
def tokenFragment(repetition):
    """Generates a fragment with the random length, and the dot/dash. The repetition is to determine wether or not to actually put the dot/dash at the end of the token."""
    return _ins(_tknFrag(length=_tknFragLen())) if repetition != 2 else _tknFrag(length=_tknFragLen())

def token():
    """Generates a three-fragment-long token"""
    return "".join([tokenFragment(repetition) for repetition in range(3)])

# Gotta test it somehow

if __name__ == '__main__':
    print(token())

Here are five results from running the code:

2dD0ZYjV4AOGMzZ2lIg6wVPzwpB82Z.BsX34AaWpvJ7i6jtWzYI1zNRjz2pI0.GRW9Uhfl9P8Xu7pYzoSYutEwuhqjhQnN

AghhjknBMqgKLpD6rR90iXKj2yuT44B.CAyXZJtAE62L97SZUbadGBmXTTSflC9th.RbuKtUDWxQ9ROgwo2OkKYEozHc1ToRz8Q

5sFE1npNyEA7JCz9hHEJFwmP2aX4CY3p.RMiKkilzUp7kmJCigrB6HfOVPkWmsczJ-4DF3qLuQSgdwmRxiOMBLUw1ZLj1Al7n

6FCXlDGWjAKylt5rZFYxOfLecxyyL4Pj-0MGu0B2knedbR8HnFI16gHChWZ8uldQ.chCVuFycHPJXF2tj9wR3mi4W4yuRp3o

rEAi9Rn1lXNkMett8wHXLF0iJLQHbc6lI.ksViH35sOlIwFfvOjVHlyXfMS0Ye58diZB-jEX93wyHTRznkYUJvbADmOrdZZF2D0R0

Note that the dots and dashes are for looks only and serve no purpose.


texts:
I came across this excellent post on delegates and event and tried to adapt it to C# 5.0L

namespace Bla
{
    public delegate void WorkStarted();
    public delegate void WorkProgressing();
    public delegate Task<int> WorkCompleted();

    public class Worker
    {
        public event WorkStarted Started;
        public event WorkProgressing Progressing;
        public event WorkCompleted Completed;

        public void DoWork()
        {
            Console.WriteLine("Worker: work started");
            if (Started != null)
                Started();

            Console.WriteLine("Worker: work progressing");
            if (Progressing != null)
                Progressing();

            Console.WriteLine("Worker: work completed");
            if (Completed == null) return;
            foreach (var del in Completed.GetInvocationList())
            {
                var wc = (WorkCompleted) del;
                var wc2 = wc;
                wc.BeginInvoke(delegate(IAsyncResult result)
                {
                    var grade = wc2.EndInvoke(result);
                    Console.WriteLine("Worker grade = {0}", grade.Result);
                },
                    null);
            }
        }
    }

    public class Boss
    {
        public async Task<int> WorkCompleted()
        {
            await Task.Delay(TimeSpan.FromSeconds(3));
            Console.WriteLine("Better...");
            return 5; // out of 10
        }
    }

    public class Universe
    {
        public static void WorkerStartedWork()
        {
            Console.WriteLine("Universe notices worker starting work");
        }

        public static async Task<int> WorkerCompletedWork()
        {
            await Task.Delay(TimeSpan.FromSeconds(10));
            Console.WriteLine("Universe pleased with worker's work");
            return 7;
        }

        private static void Main()
        {
            var peter = new Worker();
            var boss = new Boss();
            peter.Completed += boss.WorkCompleted;
            peter.Started += WorkerStartedWork;
            peter.Completed += WorkerCompletedWork;
            peter.DoWork();

            Console.WriteLine("Main: worker completed work");
            Console.ReadLine();
        }
    }
}

Could this be further improved?


texts: Order a list of points by closest distance

texts:
I wrote a function that will take a list of points and then order them so they sort of... "chain together".

The function will start with point #1 in the list.

It will add point #1 to the list of ordered by distance points.

It will then search for the closest point to point #1. (We'll call this point, point #2)

It will then add point #2 to the list of ordered by distance points.

And then... it will search for the closest point to point #2. (Which would be point #3)

You get the point.

The main problem with my code is: it's incredibly slow when dealing with lists that contain tons of points.

I would like some help optimizing my function to make it operate as fast as possible.

private static double Distance(Point p1, Point p2)
{
    return Math.Sqrt(Math.Pow(p2.X - p1.X, 2) + Math.Pow(p2.Y - p1.Y, 2));
}

private List<Point> OrderByDistance(List<Point> pointList)
{
    var orderedList = new List<Point>();

    var currentPoint = pointList[0];

    while (pointList.Count > 1)
    {
        orderedList.Add(currentPoint);
        pointList.RemoveAt(pointList.IndexOf(currentPoint));

        var closestPointIndex = 0;
        var closestDistance = double.MaxValue;

        for (var i = 0; i < pointList.Count; i++)
        {
            var distance = Distance(currentPoint, pointList[i]);
            if (distance < closestDistance)
            {
                closestPointIndex = i;
                closestDistance = distance;
            }
        }

        currentPoint = pointList[closestPointIndex];
    }

    // Add the last point.
    orderedList.Add(currentPoint);

    return orderedList;
}


texts: Populate country-province-city dropdowns from Firebase query

texts:
I'm new to Firebase and am a recovering SQL developer, so I haven't quite wrapped my mind around all aspects of firebase querying. I have an app that has basic functionality in place, but some aspects run quite slowly.

For example, I have a function that gets cities for a dropdown based off two other dropdowns (country and province). If I query for Canada/Alberta, it will find 1155 cities, but takes 4-5 painful seconds to do so.

Does anyone have any refactoring advice to make this quicker? I use a once query because the data won't change, and I need to tag lat/lon into the value to be able to use it in a search based off what the user chooses.

Query:

function loadCity() {

//GET ID OF COUNTRY CURRENTLY SELECTED
var countryID = $("#inlineFormCountry option:selected").val();
//console.log("countryID:" +countryID);

//GET ID OF PROVINCE CURRENTLY SELECTED
var provinceID = $("#inlineFormProvinceState option:selected").val();
//console.log("provinceID:" + provinceID);

// GET A REFERENCE TO THE CITY NODE
var refCity = firebase.database().ref('baseData/mapping/countries/' + countryID + '/provinces/' + provinceID + '/cities').orderByChild('nameCity');

document.getElementById("inlineFormCity").innerHTML = "";

var itemCount = 0;

refCity.once('value', function(snapshot) {
    var recordCount = snapshot.numChildren();
    document.getElementById("rowCount").innerHTML = recordCount + " city records found.";
    snapshot.forEach(function(childSnapshot) {
        itemCount += 1;

        iKey = childSnapshot.key;
        //console.log(iKey);

        childData = childSnapshot.val();
        //console.log(childData);

        var nameCity = childData.nameCity;
        var textLatitude = childData.textLatitude;
        var textLongitude = childData.textLongitude;

        iKey = iKey + "," + textLatitude + "," + textLongitude

        if (itemCount == 1) {
            document.getElementById("inlineFormCity").innerHTML = "<option selected value='" + iKey + "'>" + nameCity + "</option>"
            document.getElementById("nameCity").value = nameCity;
            document.getElementById("textLatitude").value = textLatitude;
            document.getElementById("textLongitude").value = textLongitude;
        } else {
            document.getElementById("inlineFormCity").innerHTML = document.getElementById("inlineFormCity").innerHTML + "<option value='" + iKey + "'>" + nameCity + "</option>"
        };

        if (itemCount == recordCount) {};
    });
});

};

Relevant indexing from rules:

"baseData": {
  "mapping": {
    "countries": {
      "$countryID": {
      ".indexOn": "nameCountry",
      "provinces": {
      "$provinceID": {
        ".indexOn": "nameProvince",
        "cities": {
        "$cityID": {
          ".indexOn": "nameCity"
                    }
                }
            }
        }
        }


texts:
How can this be improved?

def quick_sort(temp_list):
#Check if the array is having one element or not
    if len(temp_list) == 1:
        return temp_list
    elif len(temp_list) >= 2:
        l_list = list()
        g_list = list()
#Choose a pivot
        if len(temp_list) % 2 == 0:
            pivot = temp_list[len(temp_list)/2 - 1]
        else:
            pivot = temp_list[len(temp_list)/2]
#Make two list greater and lesser than the pivot
        for e in temp_list:
            if e < pivot:
                l_list.append(e)
            elif e > pivot:
                g_list.append(e)
#Merge the two list with the pivot
        return merge(quick_sort(l_list),pivot,quick_sort(g_list))

def merge(list1,mid,list2):
    newlist = list()
    if not list1 and list2:
        newlist.append(mid)
        newlist.extend(list2)
    if not list2 and list1:
        newlist.extend(list1)
        newlist.append(mid)
    if list1 and list2 :
        newlist.extend(list1)
        newlist.append(mid)
        newlist.extend(list2)
    return newlist


texts: Improvement of a regular expression pattern

texts:
I created this script to take informations "at-the-moment" of this site:

Pictures of name channel
Name of channel
Pictures channel
Times
Title
Type

My script (Work):

<?php

$url="http://www.programme-tv.net/programme/toutes-les-chaines/en-ce-moment.html#Grandes%20cha%C3%AEnes";
$code_page = file_get_contents($url);

preg_match_all('/
(.*?)/is', $code_page, $chaines);
preg_match_all('/
(.*?)
(.*?)<\/div>/is', $code_page, $channels);

$i=0;
foreach ($channels as $channel) {
    if($i==3){
        for ($j=0; $j < 38; $j++) {
            preg_match_all('/<\/span>/', $channel[$j], $image[$j]);
        }
    }

if($i==4){
        for ($j=0; $j < 38; $j++) {
            preg_match_all('/
(.*?)<\/p>/', $channel[$j], $time[$j]);
            preg_match_all('/
(.*?)<\/p>/', $channel[$j], $title[$j]);
            preg_match_all('/
(.*?)<\/p>/', $channel[$j], $type[$j]);
        }
    }
    $i++;
}

for ($i=0; $i < 38; $i++) {
    $test = strpos($chaines[2][$i],'
');
    if($test != true){
        echo 'Chaines images:
';
        echo 'Chaines: '.$chaines[3][$i].'
';
        echo 'image :
';
        echo 'Temps : '.trim($time[$i][1][0]).'
';
        echo 'Titre : '.substr($title[$i][1][0], strpos($title[$i][1][0], '>') + 1, strrpos($title[$i][1][0], '<')).'
';
        echo 'Type : '.$type[$i][1][0].'
';
        echo '
';
    }
}
?>

I would like to improve and find a better regular expression pattern because I use 6 regular expression pattern.


texts:
I am reading Cracking the Code Interview and I am getting a bit confused at the bit using 'previous'. In this problem, the method deletes duplicate nodes in a Linked List.

My assumption is that head is used to scan through the linked list while previous is used to update the linked list head because previous points to the same linked list. Not sure if my assumption is correct. Could someone verify this please?

Perhaps someone could also provide a method of increasing the efficiency or space of this program? I would love your input!

public static void deleteDups1(LinkedListNode head) {
    Hashtable<Integer, Boolean> table = new Hashtable<Integer, Boolean>();
    LinkedListNode previous = null;
    while(head != null) {
        if (table.containsKey(head.value)) previous.next = head.next;
        else {
            table.put(head.value, true);
            previous = head;
        }
        head = head.next;
    }
}


texts:
This program calculates the \$n\$th fibonacci number, in \$O(\log n)\$ time. I'm looking for code review, optimizations, and best practices.

public final class Fibo {

    private Fibo() { }

    public static int getNthfibo(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("The fibo value cannot be negative");
        }

        if (n <= 1) return n;

        int[][] result = {{1, 0}, {0, 1}}; // identity matrix.
        int[][] fiboM = {{1, 1}, {1, 0}};

        while (n > 0) {
            if (n%2 == 1) {
                multMatrix(result, fiboM);
            }
            n = n / 2;
            multMatrix(fiboM, fiboM);
        }

        return result[1][0];
    }

    private static void multMatrix(int[][] m, int [][] n) {
        int a = m[0][0] * n[0][0] +  m[0][1] * n[1][0];
        int b = m[0][0] * n[0][1] +  m[0][1] * n[1][1];
        int c = m[1][0] * n[0][0] +  m[1][1] * n[0][1];
        int d = m[1][0] * n[0][1] +  m[1][1] * n[1][1];

        m[0][0] = a;
        m[0][1] = b;
        m[1][0] = c;
        m[1][1] = d;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println(getNthfibo(i));
        }
    }
}


texts:
I am very new to Python, and also this is my first time trying to parse XML.
I am interested in information within str elements. I can identify that information using the str@name attribute value.

def get_cg_resources(pref_label, count=10):
    r = request_that_has_the_xml

    ns = {'ns':"http://www.loc.gov/zing/srw/"}

    tree = ET.ElementTree(ET.fromstring(r.text))
    records =[]
    for elem in tree.iter(tag='{http://www.loc.gov/zing/srw/}record'):
        record = {
        'title':'',
        'source': '',
        'snippet': '',
        'link':'',
        'image':'',
        'adapter':'CG'
        }
        for value in elem.iter(tag='str'):
            attr = value.attrib['name']
            if(attr == 'dc.title'):
                record['title'] = value.text
            elif(attr == 'authority_name'):
                record['source'] = value.text
            elif(attr == 'dc.description'):
                record['snippet'] = value.text
            elif(attr == 'dc.related.link' ):
                record['link'] = value.text
            elif(attr == 'cached_thumbnail'):
                img_part = value.text
                record['image'] = "http://urlbase%s" % img_part
        records.append(record)

    return  records

Is this approach correct/efficient for extracting the information I need? Should I be searching for the str elements differently?

Any suggestions for improvements are welcome.


texts:
I am writing a JavaScript feature where by I need to make a call to a third-party library (pre-1.10 DataTables) depending upon whether or not the user provides an integer as an input to the function during initialization. I am pasting here the snippet. As you can see it has duplicate code in the if/else clauses, the only difference is the method signature for *.fnFilter.

How can I optimize this code further? Also I dont want to test the condition during each key-up.

/*
 * By default this is a global search box events. Global being searchable across all columns.
 * But if an int is provided as an input then it will apply the search only on that column.
 * */
_bindSearchEvents: function(onColumnIndex) {

    var self = this;

    if (Math.ceil(onColumnIndex) === Math.floor(onColumnIndex)) {
        self.settings.search.input.live('keyup', function() {
            self.widget.fnFilter($(this).val(), onColumnIndex);
        });

        self.settings.search.reset.live('click', function() {
            self.settings.search.input.val("");
            self.widget.fnFilter("", onColumnIndex);
        });

    } else {

        self.settings.search.input.live('keyup', function() {
            self.widget.fnFilter($(this).val());
        });

        self.settings.search.reset.live('click', function() {
            self.settings.search.input.val("");
            self.widget.fnFilter("");
        });
    }
},


texts:
I have this code to weave the split_input ['5,4 4,5 8,7', '6,3 3,2 9,6 4,3', '7,6', '9,8', '5,5 7,8 6,5 6,4'] together. However I feel like this can be done more efficient (especially the weave function) but I have no clue how to improve it without importing any modules.

class Class1:
    def __init__(self, row):
        self.row = row

    def append(self, coordinate):
        self.row += [coordinate]

    def extend(self, row):
        for coordinate in row:
            self.row += [coordinate]

    def weave(self, row2):
        result = Class1([])
        for i in range(len(self.row)):
            if i < len(self.row):
                result.append(self.row[i])
            if i < len(row2.row):
                result.append(row2.row[i])
        if len(row2.row) > len(self.row):
            result.extend(row2.row[len(self.row):])
        return result

def get_route(split_input):
    rows = []
    for i in range(len(split_input)):
        rows += [Class1(split_input[i].split())]
    previous_row = rows[0]

    for row in rows[1:]:
        previous_row = previous_row.weave(row)
    return previous_row

woven_rows = get_route(split_input)
print woven_rows

Do you have any good advice?

The output of the code is one list. First, the first and second list are weaved into one list. Then this list is weaved with the third list etc.


texts: Creating multiple observations from single observation depending on conditions

texts:
I have written a function in python with three loops which is time consuming. Is it possible to do the same operation in less time with some other way.
Here are my code and sample data you can run at your end

#Expand files to minute-level
def expand_b34(data):
    final_list = []
    df_columns = list(data.columns.tolist())
    for i in range(len(data)):
      #print i
      row_list = np.repeat(data.values[i][np.newaxis,:],     data['DURATION'].loc[i], axis=0).tolist()
      start_end_list = range(data['START'].loc[i], data['END_MINUTE'].loc[i])
      for j in range(len(row_list)):
        row_list[j].extend([start_end_list[j]])
      for k in row_list:
        final_list.append(k)

   data = pd.DataFrame(final_list)
   data.columns = df_columns + ['START_MINUTE']
   data = data.drop(['START','END_MINUTE'], axis=1)

   return data

df = expand_b34(test)

Sample data
date  Id     LD GOOD_AP_ORIG ap_station JULIAN_DAY START DURATION END_MINUTE PLDS PL PLT PLAY
16080 4012007 1 G            5000       16081       0       60       60      0    0   0
16080 4012007 1 G            5000       16081      60       60      120      0    0   0
16080 4012007 1 G            5000       16081     120       60      180      0    0   0
16080 4012007 1 G            5000       16080     180       60      240      0    0   0
16080 4012007 1 G            5000       16080     240      120      360      0    0   0

Code Work flow:

calculate difference between START and END_MINUTE
expand the observations for the difference

So if the difference is 10, ten more lines of observations will be generated for the observation which is having the same data except for the START_MINUTE variable. START_MINUTE starts at 0 (because for that particular observation START == 0) and ends at 9.

For a single observation the loop creates 10 duplicate observations except for the start minute variable, which varies from 0 to 9.

Can someone help me to do the same observation expansion by optimizing my code?


texts: Plotting points representing many events on a canvas

texts:
I have a web app which uses Node canvas to plot points on a graph. Each point is called an 'event'. An event is an array of usually 6 'parameters' represented as numbers. My app allows users to plot 2 different numbers from each event on an XY graph.

E.g. say one event is:

// Event 1 (e1) is
[69876, 7, 210089, 122000, 7676, 189909]

// Event 2 (e2) is
[78, 23782, 66976, 253990, 2310, 88213]

If the user chooses to plot the 3rd and 5th parameter then then e1 is represented as 210089, 7676 and e2 is 66976, 2310. A typical plot might look like:

Typically, a graph is 300 pixels. In this case above, the maximum values any parameter can be is 262144. So to figure out where to plot I just work out the ratio:

300 / 262144 = 0.001144409

Then multiple the ratio by the x, y numbers.

So e1 will be shown at 240, 9 (210089 * 0.001144409 = 240 etc) and e2 will be shown at the pixels 77, 3.

This all works fine when there are less than 100k events. However, when there are, say, 800k events, this becomes very slow.

Is there any way of doing this more efficiently by somehow preprocessing the data? So say there are 800k events and you know the maximum value of each one is 262144 and that the graph size will be 300px, could some sort of data binning be done?

For example, the numbers 400, 550, 650 will all appear in the first pixel (since anything from 0 to 873 (262144 / 300) will fall into the first pixel on a 300px graph). Is there a method I could use to condense all this data down so that I can loop through much quicker and plot?

The code is:

for (var i = 0; i < dataAsNumbers.length; i++) {

    x = dataAsNumbers[i][paramX];
    y = dataAsNumbers[i][paramY];

    pointX = getPointOnCanvas({
        value: x
        ratio: ratio
    });

    pointY = getPointOnCanvas({
        value: y,
        ratio: ratio
    });

    toPlotColors.push({
        pointX: pointX,
        pointY: pointY
    });
}

paintDotsAtOnce(toPlotColors);

var getPointOnCanvas = function(params) {

    var value = params.value;
    var ratio = params.ratio;

    return Math.floor(ratio * value);
};

var paintDotsAtOnce = function(plotColors) {

    plotColors.forEach(function(plotColor){

        if(plotColor.plotDot) {
           memoized(plotColor.pointX, plotColor.pointY, plotColor.color);
        }
    });
};

var paintDotS = function(pointX, pointY, color) {
        context.fillStyle = color;
        context.fillRect(pointX, pointY, 1, 1);
};

var memoized = memoize(paintDotS);

So if dataAsNumbers.length is 800k, it has to loop that many times. I'm worndering if data binning could reduce the need to do this.


texts:
I'm a Java beginner currently practising MVC pattern and came up with this. Could you please check if this is a proper implementation of MVC and if there are any best practices that I have broken?

public class Appka {

    public static void main(String[] args) {

        Model model = new Model();
        Controller controller = new Controller(model);
        View view = new View(model, controller);
        model.addListener(view);

    }
}

public class Model {

    String value;
    List<StateChangedListener> listeners = new ArrayList<>();

    public Model() {

        this.value = "";
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
        notifyListeners();
    }

    public void addListener(StateChangedListener l) {
        listeners.add(l);
    }

    public void removeListener(StateChangedListener l) {
        listeners.remove(l);
    }

    public void notifyListeners() {
        listeners.forEach(l -> l.stateChanged());
    }
}

public class View extends JFrame implements StateChangedListener {

    private Model model;
    private Controller controller;
    private JLabel label1;
    private JLabel label2;
    private JButton button1;
    private JButton button2;

    public View(Model model, Controller controller) {
        this.model = model;
        this.controller = controller;
        initComponents();
    }

    private void initComponents() {

        button1 = new JButton();
        button2 = new JButton();
        label1 = new JLabel();
        label2 = new JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        button1.setText("1");
        button1.addActionListener(controller);

        button2.setText("2");
        button2.addActionListener(controller);

        label1.setText("label1");

        label2.setText("label2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(button1)
                    .addComponent(label1))
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(label2)
                    .addComponent(button2))
                .addContainerGap(113, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(label1)
                    .addComponent(label2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(button1)
                    .addComponent(button2))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        pack();
        setVisible(true);

    }

    @Override
    public void stateChanged() {
        label1.setText(model.getValue());
        label2.setText(model.getValue());
    }

}

public class Controller implements ActionListener {

    private Model model;

    public Controller(Model model) {
        this.model = model;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton clicked = (JButton) e.getSource();
        model.setValue(clicked.getText());
    }

}

interface StateChangedListener {

    public void stateChanged();

}


texts: Bash script that searches for directories with files called package.json and install dependencies

texts:
I'm relatively familiar with the command line, but I've usually reached for other languages rather than bash for more full on scripts. It works, but I'm wondering if anything isn't really idiomatic. I've never used bash arrays before, and I've never had to write such an involved find command so I'm just wondering if I did all that fine. Also just overall is there a shorter way to do this?

.

#!/bin/bash

set -e

# The directories to search in
# Currently, lib + tools, and whatever command line args are provided
DIRS=(lib tools $@)
for i in "${!DIRS[@]}";
do
  DIRS[i]="$(pwd)/${DIRS[i]}"
done

# Get absolute path of directories with a package.json file and install dependencies
while IFS='' read -r line; do
  echo "Installing dependencies for $line"
  cd "$line" && yarn
done < <(
  find "${DIRS[@]}" -iname 'package.json' -not -path '*/node_modules/*' -exec dirname {} \;
)

# Do current directory
echo "Installing dependencies for current directory"
yarn


texts: Function to check that a Python list contains only True and then only False

texts:
I would like to only allow lists where the first n elements are True and then all of the remaining elements are False. I want lists like these examples to return True:

[]
[True]
[False]
[False, False]
[True, False]
[True, False, False]
[True, True, True, False]

And lists like these to return False:

[False, True]
[True, False, True]

That is, any list that can we written as [True] * n + [False] * m for n, m integers in the interval [0, infty).

I am currently using a function called check_true_then_false, but I feel like there is probably a neater way of doing this. The code doesn't need to be fast, as this will only be run once (not inside a loop) and the lists will short (single digit lengths).

def check_true_then_false(x):
    n_trues = sum(x)
    should_be_true = x[:n_trues]  # get the first n items
    should_be_false = x[n_trues:len(x)]  # get the remaining items
    # return True only if all of the first n elements are True and the remaining
    # elements are all False
    return all(should_be_true) and not any(should_be_false)

Testing shows that it produces the correct output:

test_cases = [[True],
              [False],
              [True, False],
              [True, False, False],
              [True, True, True, False],
              [False, True],
              [True, False, True]]
print([check_true_then_false(test_case) for test_case in test_cases])
# expected output: [True, True, True, True, True, False, False]


texts: Clojure function composition: logging results of an action performed by a "pure" function

texts:
I'm wondering how I could compose this program better allow it to grow more functionality without constant refactoring.

This is my code sample for Hacker School, so I'm less married to the results but instead am looking to further my understanding of Clojure and functional programming.

Basically, my battle simulator needs to update the state of the battle participants, while also making those actions known to the console where I represent the state of the battle. Every time I add a feature, I seem to be rewriting everything, so I know I'm structuring this wrong.

How would you arrange these functions (specifically, logfight and battleturn to work well together without being intrinsically tied? Right now I carry around the pertinent info (:lastswing) in the atom, but that feels wrong.

Feel free to mention anything else that bugs you in the code.

(ns rpg)

(def characters (atom
                 {:player {:name "Fred" :hp 100 :att 5 :dex 10 :alive? true :lastswing 0}
                  :creature1 {:name "Badman" :hp 99 :att 4 :dex 7 :alive? true :lastswing 0}}))

(defn hit? [dex]
  (> 5 (* dex (rand 1))))

(defn swing [att]
  (int (* att (+ 1 (rand 1)))))

(defn damage [hp swing]
  (- hp swing))

(defn attack [att dex hp]
  (if (hit? dex)
    (damage hp (swing att))
    hp))

(defn logfight [aname dname aswing dhp]
  (if (> aswing 0)
    (println (str aname " hits " dname " for " aswing ". " dname " has " dhp " hp left."))
    (println (str aname " missed!"))))

(defn battleturn [thechars a d]
  (let [attacker (a thechars)
        defender (d thechars)
        att (:att attacker)
        dex (:dex attacker)
        hp (:hp defender)
        result (attack att dex hp)
        lastswing (- hp result)]
    (if (:alive? defender)
      (if (<= result 0)
         (do
           (println (str (:name defender) " died!"))
           (-> thechars
           (assoc-in [d :alive?] false)))
         (do
           (logfight (:name attacker) (:name defender) lastswing hp)
           (-> thechars
           (assoc-in [d :hp] result)
           (assoc-in [a :lastswing] lastswing))))
      (do
        (println (str (:name defender) " is already dead!"))
        thechars))))

(defn fight [target]
  ((swap! characters battleturn :player target)
   (swap! characters battleturn target :player)))

;; The UI
(fight :creature1)


texts: Getting the individual digits of a number

texts:
Approach 1:

Repeated division-modulus operations:

long num = 123456789;
int count = 0;
while(num > 0)
{
 int digit = num % 10;
 if(digit == 1)
  count ++;
 num /= 10;
}

Approach 2:

Convert it into an String and get the characters at the position:

long num = 123456789;
int count = 0;
String s = String.valueOf(num);
for(int i = 0; i < s.length(); i++)
{
 char ch = s.charAt(i);
 if(ch == '1')
    count ++;
}

The second operation doesn't need to get the remainder and the quotient each time. A charAt() method can be enough.

Which approach is considered to be better and why?

Consider taking the input from the console.

1st Case:

long num = scanner.nextLong();

2nd Case:

String s = scanner.nextLine();

Here there would be no overhead on converting the number to string.

Also let us assume it is for positive numbers.


texts: Counting the number of points that have both a larger theta and a larger radius than a given point

texts:
I don't like the fact that I am selecting all the points, even though I only care about the count of them.

Which of the from parts should appear first, if it even matters?

var count = (from type in ValidTypes()
    from point in GetData(type)
    where point.Radius > referencePoint.Radius
        && point.Theta > referencePoint.Theta
    select point).Count()

ValidTypes() returns a few types, about 5.

GetData(type) may return many points, possibly 100,000.

This query is counting the number of points that have both a larger theta and a larger radius than a given point.

Is there a way to write this faster or more readable?


texts: Checking against user input and returns a response based on that input

texts:
How could I use enums in the following block of code to simplify it? The block is a program that has a command interpreter that returns different data based on user input. Is there a way I could easily apply enums and a match statement to the logic here?

use std::io;

fn main() {
    let version = String::from("0.0.1");
    let mut input = String::new();

    shell(&mut input, &version);
}

fn shell(input: &mut String, version: &String) {
    input.clear();
    match io::stdin().read_line(input) {
        Ok(b) => {
            if &input.trim() == &"ver" || &input.trim() == &"what are you" {
                println!("C ute R ust A mateur B eginner Shell ver: {}", version);
                shell(input, version);
            } else {
                println!("Command '{}' Not Recognized", input);
                shell(input, &version);
            }
        }
        Err(err) => panic!("incorrect"),
    }
}


texts:
I wanted to write a function findDeep that would perform a recursive, depth-first search on plain objects and arrays.

Comments and criticism welcome.

function findDeep(dict, test, index = 0, keys = Object.keys(dict)) {
    var item = dict[keys[index]];

    if(index > keys.length) {
        return null; // End of siblings. No match.
    }

    if(test(item)) {
        return item; // Match.
    }

    if(item !== null && typeof item === 'object') { // null is an object.
      var result = findDeep(item, test); // Children.
      if(result) {
        return result; // Short circuit, when item found.
      }
    }

    return findDeep(dict, test, ++index); // Siblings.
}

document.writeln('test1: ', findDeep(['foo', 'bar', 'bam'], i => i === 'bar') === 'bar', '
')
document.writeln('test2: ', findDeep([ ['foo'], [['bar']], [ ['baz', ['bat'] ] ] ], i => i === 'bat') === 'bat', '
');
document.writeln('test3: ', findDeep({ foo: 'foo', bar: 'bar', bam: { baz: 'baz' } }, i => i === 'baz') === 'baz', '
');


texts: Calculate regression coefficients for specific conditions in a data frame

texts:
I have a data set where leaf mass (MASS) was measured in 30 different tanks (TANK) on 3 dates (DATE). The tanks were also assigned to 5 different treatments.

I want to calculate the regression slope of the mass loss for each tank so I wrote the following function in R

 k.tank <- function() {
   k <- numeric(0)
   tank <- numeric(0)
   treat <- character(0)

   for(i in TANK)
     k <- c(coef(summary(lm(log(MASS)[TANK == i] ~ DATE[TANK == i])))[2, 1], k)

   for(i in TANK)
     tank <- c(i, tank)

   for(i in TANK)
     treat <- c(TREATMENT, treat)

   k.list <- data.frame(tank, treat, k)

   return(k.list)
}

This function is currently working (but see below) but I feel like I made some non-optimal choices.  Please provide feedback on how to improve this function.

NOTE: The code is working but it does return the list in reverse order 30 - 1 and it changes the treatment labels from letters ("A", "B", "C", etc...) to numbers ("1", "2", "3", etc...). Any thoughts on these idiosyncrasies would also be appreciated.


texts: Split a string and write the i-th element into a buffer with C

texts:
Question
Recently I've written the following splitv() function, without using strtok. Any way to make it shorter and more efficient?
Descrption
The function calculates the index-th element of the string str split by delim. The element is written into buff and 0 is returned. When an index error is occurred, any non 0 value is returned. This function was inspired by the python split function: buff = str.split(delim)[index], but I think it works too hard and can be improved.
int splitv(char buff[], char str[], char delim[], int index) {
    // returns 0 if an element is written. Else non 0.
    char *start = str, *end;
    int i = 0, buff_i = 0;
    // check if delim not in str
    if ((end = strstr(str, delim)) == NULL) {
        if (index == 0) strcpy(buff, str);
        return index;
    }
    // delim is in str
    for (i = 0; i < index; i++) {
        start = end + strlen(delim);
        end = strstr(start, delim);
        if (end == NULL) {
            // reached the last element
            if (i == index - 1) {
                end = str + strlen(str);
                break;
            }
            // index error: index >= elements_count
            return -1;
        }
    }
    // copy element to buffer
    while (start != end) {
        buff[buff_i] = *start;
        start++;
        buff_i++;
    }
    buff[buff_i] = '\0';
    return 0;
}

Thanks in advance!


texts:
I have links like foo that are supposed to open in Safari (from phonegap), so globally I did this:

$(document).on("a[target=_system]", function(e) {
  e.preventDefault();
  window.open($(this).attr("href"), '_system');
});

But it doesn't seem very ember-like to add global listeners.


texts:
I tried to refactor my code with entity framework configuration, splitting in multiple private methods, one per entity, each responsible for configuring things related to that entity and only that entity. But I feel like Version 2 can still be improved.

What do you think?

Version 1:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Country>()
        .Property(e => e.Code)
        .IsFixedLength()
        .IsUnicode(false);

    modelBuilder.Entity<Country>()
        .Property(e => e.PhoneCode)
        .IsFixedLength()
        .IsUnicode(false);

    modelBuilder.Entity<Country>()
        .HasMany(e => e.Locations)
        .WithRequired(e => e.Country)
        .WillCascadeOnDelete(false);
}

Version 2:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    Configure(modelBuilder.Entity<Country>());
}

Configure(EntityTypeConfiguration<Country> entity)
{
    entity
        .Property(e => e.Code)
        .IsFixedLength()
        .IsUnicode(false);

    entity
        .Property(e => e.PhoneCode)
        .IsFixedLength()
        .IsUnicode(false);

    entity
        .HasMany(e => e.Locations)
        .WithRequired(e => e.Country)
        .WillCascadeOnDelete(false);
}


texts: List of Ordered pairs from unordered Pair in Java

texts:
Problem statement is

  Write a method that can take an unordered list of airport pairs visited during a trip and return the list in order.

{"ITO", "KOA"}, {"SFO", "SEA"}, {"LGA", "CDG"}, {"KOA", "LGA"}, {"PDX", "ITO"}, {"SEA", "PDX"}

  should return:

(SFO,SEA)(SEA,PDX)(PDX,ITO)(ITO,KOA)(KOA,LGA)(LGA,CDG)

I have come up with this O(n^2) algorithm. I wanted to know if it can be done better than this:

private static void sortPairs(String[][] input)
    {

        for (int i = 0; i < input.length; i++) {
            int j = 1;
            for (; j < input.length; j++) {
                if (input[i][0].equals(input[j][1])) {
                    break;
                }
            }
            if (j == input.length) {
                swapPairs(i, 0, input);
                break;
            }
        }

        for (int i = 0; i < input.length; i++) {
            int j = 1;
            for (; j < input.length; j++) {
                if (input[i][1].equals(input[j][0])) {
                    break;
                }
            }
            if (j == input.length) {
                swapPairs(i, input.length - 1, input);
                break;
            }
        }

        for (int i = 2; i < input.length - 1; i++) {
            int j = i - 1;
            for (; j >= 0; j--) {
                if (input[j + 1][0].equals(input[j][1])) {
                    break;
                }
                swapPairs(j, j + 1, input);
                if (input[j + 1][0].equals(input[j][1])) {
                    break;
                }
            }

        }
    }

    private static void swapPairs(int i, int j, String[][] pairs)
    {
        String[] temp = pairs[i];
        pairs[i] = pairs[j];
        pairs[j] = temp;
    }


texts: Tax calculator using functional programming

texts:
class Program
{
    static void Main(string[] args)
    {
        var priceList = new List<int>() { 10, 20, 30, 40 };
        var totalAmount = InvoiceCalculator.CalculateTotalPriceWithTax(priceList, 5);
        Console.WriteLine(totalAmount);
    }
}

static class InvoiceCalculator
{
    private static int CalculatePrice(List<int> priceList)
    {
        return priceList.Sum();
    }
    private static int CalculateTax(int price, int taxRate)
    {
        return (price * taxRate / 100); // Ignore int datatype for simplicity. input values are immutable
    }
    public static int CalculateTotalPriceWithTax(List<int> priceList, int taxRate)
    {
        int totalPrice = CalculatePrice(priceList); // input values are immutable
        int tax = CalculateTax(totalPrice, taxRate); // input values are immutable
        return totalPrice + tax;
    }
}

Features of the program are

Inputs are immutable.
Functions are not altering the state
Use of pure functions
CalculateTotalPriceWithTax is calling CalculatePrice and CalculateTax but not altering the state

•   For simplicity I have used int datatype instead float, double for tax calculation.

Is it violating functional programming principle because CalculateTotalPriceWithTax() function is calling CalculateTax and CalculatePrice function?

Note: None of these calls are altering the state.
For simplicity exception handling and aspects are ignored. Just interested in knowing the functional aspects of the program


texts: Querying nearest city with a given shop using latitude and longitude is slow

texts:
I am using the following query to search for the nearest city to my location from the cities table using latitude and longitude. The query also checks whether the nearest cities to my location have more than 1 shops of a given category. Only then a city is selected.

The query works fine but it takes more than 5 seconds to execute. Is there any way this query can be optimised to consume less time.

SELECT id,city,city_url,
(SELECT count(shop) FROM shops JOIN
shop_categories ON shop_categories.shop_id = shops.id WHERE
city_id=cities.id && shop_categories.category_id = :catId LIMIT 1) as
totalshops,
(6371 * 2 * ASIN(SQRT( POWER(SIN(( :latitude - latitude) *
pi()/180 / 2), 2) +COS( :latitude * pi()/180) * COS( :latitude *
pi()/180) * POWER(SIN(( :longitude - longitude) * pi()/180 / 2), 2) )))
as distance
from cities
having totalshops > 1
order by distance ASC
LIMIT 1


texts: Printing bowTie pattern in efficient and pythonic way

texts:
I've posted  code/library to GitHub for first time over here.

The code is pretty simple. It generates a BowTie pattern of given size and characters.

I did attempt to implement DP by calculating only half of shape matrix and getting its mirror image from matrix itself.

The code works fine. I do need help with someone analyzing to see if certain logic/lines can be done in more pythonic  and efficient way [a.k.a. Code Review].

Any help is appreciated.

Source-Code

from __future__ import print_function

class BowTie(object):
    def __init__(self, size=5, fill_value = '*', empty_value = ' '):
        self.size = size
        self.fill_value = fill_value
        self.empty_value = empty_value

    def  create_shape(self):
        ''' creates shape as per input values and returns list of list of values'''
        star = self.fill_value
        dot = self.empty_value
        m = (self.size * 2) - 1 #Get center row

        #get  top half list
        th = []
        for idx,k in enumerate(xrange(1,self.size+1)): #run through 1 - size
            row = idx + 1
            tmplst = []
            if row % 2 != 0:
                tmplst.append(i for i in xrange(1,row + 1) if i % 2 != 0)
                tmplst.append(i for i in xrange(m, m-row, -1) if i % 2 != 0)
            else:
                tmplst.append(i for i in xrange(1,row + 1) if i % 2 == 0)
                tmplst.append(i for i in xrange(m, m-row, -1) if i % 2 == 0)

            #append each row value to  top half list.
            th.append(sorted(set([j for i in tmplst for j in i])))

        #create mirror-image of top half which is our bottom half
        th = th + th[len(th) -2::-1]

        def get_list(bound = self.size, alist = []):
            ''' expects upper bound and an integer list
            returns a list of fill_values '''
            tmp_list = []
            for i in xrange(1,bound + 1):
                tmp_list.append(star if i in alist else dot)
            return tmp_list

        #create list of * and blanks or as per fill and empty value
        row_values = [get_list(bound = m, alist = i) for i in th]
        return row_values

    def print_shape(self):
        ''' print given list of list of values'''
        for i in self.create_shape():
            print(' '.join(i))


texts:
I need to convert f32 arrays with a fix length to base64 representation and back.

My current code looks like this. It works, but it feels way too complicated.

How can I improve it?

main.rs:

extern crate base64;

fn read_float_vec_from_byte_vec(v: Vec<u8>) -> Result<Vec<f32>, String> {
    match v.len() % 4 {
        0 => {
            use std::ptr;
            let p = v.as_ptr();
            let dest_len = v.len() / 4;
            let mut result = Vec::<f32>::with_capacity(dest_len);
            for i in 0..dest_len as isize {
                unsafe {
                    let f_ptr = p.offset(4 * i) as *const f32;
                    result.push(ptr::read::<f32>(f_ptr));
                }
            }
            Ok(result)
        }
        _ => Err("Number of bytes not divisible by 4.".to_string())
    }
}

fn float_vec_as_byte_vec(values: &Vec<f32>) -> Vec<u8> {
    let dest_len = values.len() * 4;
    let mut result = Vec::<u8>::with_capacity(dest_len);
    result.resize(dest_len, 0);
    for (i, x) in values.iter().enumerate() {
        let bytes: [u8; 4] = unsafe { std::mem::transmute(*x) };
        result[i*4..i*4+4].copy_from_slice(&bytes[..]);
    }
    result
}

fn show_base64_decode_error(e: base64::DecodeError) -> String {
    use std::error::Error;
    format!("{:?}", e.description())
}

fn base64_to_f32_16_array(base64_str: &str) -> Result<[f32; 16], String>
{
    base64::decode(base64_str
        ).map_err(show_base64_decode_error
        ).and_then(read_float_vec_from_byte_vec
        ).map(
        |float_vec| {
            let mut result: [f32; 16] = [0.0; 16];
            result.copy_from_slice(&float_vec[..]);
            result
        }
    )
}

fn f32_16_array_to_base64(vals: &[f32; 16]) -> String
{
    base64::encode(&float_vec_as_byte_vec(&vals.to_vec()))
}

#[cfg(test)]
mod tests {
    static VALUES: [f32; 16] = [-0.35, -0.97, 0.05, 0.49, 1.35, 1.08, -0.71, 0.27, -0.44, 0.22, -1.34, -1.17, 0.68, 0.02, -0.52, 0.83];
    static BASE64_STR: &str = "MzOzvuxReL/NzEw9SOH6Ps3MrD9xPYo/j8I1v3E9ij6uR+G+rkdhPh+Fq7+PwpW/exQuPwrXozy4HgW/4XpUPw==";
    #[test]
    fn base64_to_f32_16_array_test() {
        assert_eq!(super::base64_to_f32_16_array(&BASE64_STR), Ok(VALUES));
        assert_eq!(
            super::base64_to_f32_16_array("foo"),
            Err("Number of bytes not divisible by 4.".to_string()));
    }
    #[test]
    fn f32_16_array_to_base64_test() {
        assert_eq!(super::f32_16_array_to_base64(&VALUES), BASE64_STR);
    }
}

cargo.toml (for completeness):

[package]
name = "base64_f32_test"
version = "0.1.0"

[dependencies]
base64 = "0.9.0"


texts: Find the starting indices of all occurrences of the pattern in the string

texts:
The task

  Given a string and a pattern, find the starting indices of all
  occurrences of the pattern in the string. For example, given the
  string "abracadabra" and the pattern "abr", you should return [0, 7].

My solution

function findStartingIndex(T, pattern) {
  let S = T;
  const res = [];
  while(true) {
    const i = S.indexOf(pattern);
    if (i === -1) { return res; }

    S = S.substring(i + 1);
    res.push(i ? i + 1 : i);
  }
  return res;
}


texts:
I wrote a AWS lambda function which buys €X worth of some currency on an exchange. For this I first have to find out the current price (getAskPrice), then calculate the amount to buy and post the order (buyLimitOrder). I've implemented both operations as promises, buyLimitOrder gets the result of getAskPrice as one of the arguments. The result of buyLimitOrder (if successful) should be returned as the result of the lambda function.

Here's the relevant code fragment:

const getAskPrice = new Promise(function(resolve, reject){

        got(TICKER_URL).then(response => {
            let result = JSON.parse(response.body);
            let ask = Number(result.ask);
            if (!isNaN(ask)) {
                resolve(ask);
            } else {
                throw new Error("Could not parse the ask price from [" + BTCEUR_TICKER_URL + "] response:\n" + response.body);
            }
        }).catch(reject);
});

const buyLimitOrder = function(customerId, key, secret, value, askPrice) {

    let amount = value / askPrice;

    let roundedAmount = Math.ceil(amount * Math.pow(10,5)) / Math.pow(10,5);

    let order = createAuthData(customerId, key, secret);
    order.amount = roundedAmount;
    order.price = askPrice;
    return new Promise(function(resolve, reject) {
        console.log("Buying " + roundedAmount + " of BTC for price " + askPrice + " for total value of " + (roundedAmount * askPrice) + ".");
        got.post(BUY_LIMIT_ORDER_URL, {
            body : order,
            form: true
        }).then(response => {
            let result = JSON.parse(response.body);
            resolve(result);
        }).catch(reject);
    });
};

const getAskPriceAndBuyLimitOrder = function(customerId, key, secret, value) {
    return new Promise(function(resolve, reject) {
        getAskPrice
            .then(askPrice => buyLimitOrder(customerId, key, secret, value, askPrice).then(resolve).catch(reject))
            .catch(reject);
    });
};

exports.handler = (event, context, callback) => {
    doWithBitstampProperties()
        .then(bitstampProperties =>
            getAskPriceAndBuyLimitOrder(bitstampProperties.customerId, bitstampProperties.key, bitstampProperties.secret, VALUE)
                .then(result => callback(null, result))
                .catch(error => callback(error)))
        .catch(error => callback(error));
};

Full code can be found here.

This works, but I was not sure this is how promises should be chained. For instance, calling .then(resolve).catch(reject) on buyLimitOrder(...) does not feel right:

    return new Promise(function(resolve, reject) {
        getAskPrice
            .then(askPrice => buyLimitOrder(customerId, key, secret, value, askPrice).then(resolve).catch(reject))
            .catch(reject);
    });

Generally, the code does not feel elegant.


texts:
I have the following function that works fine.  Is there a better way to do it and will this be efficient if I have 100+ rows returned from each table?

The database

Tables

wcx_articles
wcx_videos
wcx_apps
wcx_links

The corresponding _active column for each table

article_active
video_active
app_active
link_active

_active is a switch 1 or 0

This is my current function

public function findInactiveItems() {

    $query = "SELECT * FROM wcx_articles WHERE article_active = '0'
    UNION
    SELECT * FROM wcx_videos WHERE video_active = '0'
    UNION
    SELECT * FROM wcx_apps WHERE app_active = '0'
    UNION
    SELECT * FROM wcx_links WHERE link_active = '0'
    ";
        if( $this->num_rows( $query ) > 0 ) {
            $count = $this->num_rows($query);
            return $count;
        }
    }

 public function num_rows( $query ) {
    $query = $this->link->query( $query );
    if( mysqli_error( $this->link ) ) {
        $this->log_db_errors( mysqli_error( $this->link ), $query, 'Fatal' );
        return mysqli_error( $this->link );
    }
    else {
        return mysqli_num_rows( $query );
    }
    mysqli_free_result( $query );
}


texts:
This is a practice question:

  A happy number is a number defined by the following process:

  Starting with any positive integer, replace the number by the sum of
  the squares of its digits, and repeat the process until the number
  equals 1 (where it will stay), or it loops endlessly in a cycle which
  does not include 1. Those numbers for which this process ends in 1 are
  happy numbers.

Example: 19 is a happy number

\$1^2 + 9^2 = 82\$

\$8^2 + 2^2 = 68\$

\$6^2 + 8^2 = 100\$

\$1^2 + 0^2 + 0^2 = 1\$

Program below solves this problem:

public static boolean isHappy(int n) {
   int sum=0;
   Set<Integer> seenSet = new HashSet<Integer>();
    while (n > 0) {
        int x = n%10;
        sum+=x*x;
        n=n/10;

        if (n == 0 && sum != 1) {
            n=sum;
            sum=0;
            seenSet.add(n);
        } else if (n== 0 && sum == 1 ) {
            return true;
        }
            else if (seenSet.contains(n)) {
            return false;
        }
    }

    return true;
}

I'm looking for any comments on how to improve the code, but a specific focus on whether the way the method returns from multiple places would be appreciated - the multiple return statements concern me.


texts: Finding the closest data point in a sequential list

texts:
Given a List<double> and a double, it will find the closest value and return the index of the closest value in the list. The list will always be in order.

private int FindClosestPoint(double val, List<Double> list)
{
    int ret = new int();

    int max = list.Count;
    int min = 0;
    int index = max / 2;

    while (max - min > 1)
    {
        if (val < list[index])
            max = index;
        else if (val > list[index])
            min = index;
        else
            return index;

        index = (max - min) / 2 + min;
    }

    if (max != list.Count && min != 0)
    {
        if (Math.Abs(list[max] - val) < Math.Abs(list[min] - val))
            ret = max;
        else
            ret = min;
    }
    return ret;
}


texts:
I just started learning Go, and I wanted to created a project to learn more about concurrency in go. I heard about Go's lightweight threads, so I wanted to give them a try.

This program uses backtracking to brute-force a list of passwords loaded from a file. It tries from password of length 2 and go ahead until all passwords are been found.

It works well until password length doesn't come to 6: then my RAM will get full. I've already optimized my code in some ways e.g. in the first iteration of the program I used to create a chan for every thread, and every thread would wait for the spawned thread to terminate. Now it has a barrier.

I would need some suggestion about my code and spatial optimization tips.

package main

import (
"fmt"
"io/ioutil"
"strings"
"sync"
"log"
"time"
"crypto/md5"
)

var alfabeto = []rune {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'}

func compute(prefix int, n int, a string, wgFather *sync.WaitGroup){
    defer wgFather.Done()

    if prefix == n-1 {
        for _, d := range alfabeto {
            password := fmt.Sprintf("%s%c", a, d)

            if searchPassword(password) {
                if len(passwords) == 0{
                    return
                }
            }
        }
    }else {
        for i := range alfabeto{
            wgFather.Add(1)
            go compute(prefix+1, n, fmt.Sprintf("%s%c", a, alfabeto[i]), wgFather)
        }
    }
}

var passwords []string

func main(){

    if loadPasswords() {
        return
    }
    fmt.Println("File with passwords loaded. We're gonna crack", len(passwords),"passwords!")
    start := time.Now()
    cont := 2
    for len(passwords) > 0  {
            fmt.Println("Searching for passwords at length: ", cont)

            var wg sync.WaitGroup
            wg.Add(1)
            go compute(0, cont, "", &wg)
            wg.Wait()
            cont++
        }

    elapsed := time.Since(start)
    fmt.Println("Password's file cracked in:", elapsed)

}

func searchPassword(pass string) bool{
    hash := fmt.Sprintf("%x", md5.Sum([]byte(pass)))
    for i, value := range passwords{
        if strings.Compare(hash, value) == 0{
            // Password found!
            fmt.Println("Find Password:", pass, " with hash:", hash)
            passwords = append(passwords[:i], passwords[i+1:]...)
            return true
        }
    }
    return false
}

func loadPasswords() bool{
    stream, err := ioutil.ReadFile("file.txt")
    if err != nil{
        log.Fatal(err)
        return true
    }
    readstring := string(stream)

    passwords= strings.Split(readstring, "\n")
    return false
}

This is my password's file, file.txt:

56cc213a6303180cbab6a3da15108751
b1c9b44a9a0a65615f21834aee53594b
4b855fcca0a7140f60dd8259d1a0f1ad
14db43821fb74030ac6e8bdf662646d5
93eea5a9dfb14219e8e9d51ab1ae2b82
b0804ec967f48520697662a204f5fe72
ab6d50d5a9ecafd6fd429d38877837ca
168908dd3227b8358eababa07fcaf091
3cf4046014cbdfaa7ea8e6904ab04608
02c77002a0c646684b3325959fe147b2
f38fef4c0e4988792723c29a0bd3ca98
f3abb86bd34cf4d52698f14c0da1dc60
e842795b282293fd61bc294c49edb12b
c4fdb9019bcca7e82296952ba3e1895b
8dc01b0de0431cb7eced92277c1f04c7
bbebde933d57f88406bc530e5df0df3a
44fd79ea712293e5b5a7b51aceb6c0a7
56eb473ffd7429b00eb136c80664be30
875a8ec1acd2fa9f02ca152974dfd904
23ba6002aa3583a61db26e957b1fbe43
dcaa9fd4f23aaf0c29f540becf35b46f
98f740d68822f4209674ca9f23c20abe
a079350a0e30d9f293f6acaea80bb015
c44ab68f3a5ef32c8dfbbaa1daa86f98
6057b96acf9d41c1ca26a8923d970404
daa10b9d19015cf1cbf4bb53cf135b61
b29533fb6f81a9dbf8eae44b05ce8f49
22b35da29d5fa740fab4cb83ccb820aa
11cff46e84b6cae9951ea65eb5716d9e
9dd8ecec47e0c96bb189038fdb35bf16
e03a5f28b2349d6735adf6f528a7f18c
6057b96acf9d41c1ca26a8923d970404


texts: Profile with static and input modes (View and Update)

texts:
I'm a solo developer and a friend told me that my code is not very readable. I always write code trying to keep it DRY while not taking longer than it would take doing it in an "easier" way.
Here is the skeleton for My Profile feature which will initially have read-only values. When the user wants to update it, it turns into an input when clicking on edit.
Is there anything wrong with this way of going about it?
class MyProfileEdit extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            data: {},
            onEdit: ""
        }
        this.displayKey = {
            "first_name": "First name",
            "last_name": "Last name",
            "zipCode": "Zip"
        }
    }
    handleOnChange = key => e => e.persist() || this.setState(prevState => {
        prevState.data[key] = e.target.value;
        return prevState;
    })
    getInputValue = key => this.state.data[key] || this.props.currentUser[key]
    getKeyDisplay = key => this.displayKey[key] || key[0].toUpperCase() + key.slice(1)
    getStatic = key => (

            {this.getKeyDisplay(key)}: {this.getInputValue(key)}  &nbsp;&nbsp;&nbsp;

 this.setState({onEdit: key})}>Edit

    )
    getInput = key => (

            {this.getKeyDisplay(key)}:
            <input value={this.getInputValue(key)} onChange={this.handleOnChange(key)} />

 this.setState({ onEdit: "" })}>Done

    )
    getStaticOrInput = key => this.state.onEdit != key ? this.getStatic(key) : this.getInput(key);
    render(){
        return (
            <React.Fragment>
                My profile:

                { this.getStaticOrInput("first_name") }
                { this.getStaticOrInput("last_name") }

                    Notification option:
                    <select
                        value={this.getInputValue("notification_option")}
                        onChange={this.handleOnChange("notification_option")}
                    >
                        <option value="SMS">SMS</option>
                        <option value="EMAIL">Email</option>
                    </select>

                { this.getStaticOrInput("city") }
                { this.getStaticOrInput("address") }
                { this.getStaticOrInput("zipCode") }
            </React.Fragment>
        )
    }
}


texts: Regex for domain validation name validation

texts:
I created this regex in Javascript that returns a boolean for Domain validation that meets the criteria to allow IP addresses and ascii domain name. The assumption is that the TLD should be atleast two letters.

/^((([0-9]{1,3}\.){3}[0-9]{1,3})|(([a-zA-Z0-9]+(([\-]?[a-zA-Z0-9]+)*\.)+)*[a-zA-Z]{2,}))$/

I used the following Javascript to test the regex:

var func = function(val) { return /^((([0-9]{1,3}\.){3}[0-9]{1,3})|(([a-zA-Z0-9]+(([\-]?[a-zA-Z0-9]+)*\.)+)*[a-zA-Z]{2,}))$/.test(val);}

It works correctly:

   func('192.168.1.1') //return true;
   func('a-a.com')     //returns true;
   func('aa.com')      //returns true;
   func('aa.cc')       //returns true;
   func('aa.c')        //returns false;

I have basic knowledge of regex's and hence seeing if there anyway to optimize it.


texts:
I have a Map<String, List<Object>> multiFieldMap and I need to iterate over its value set and add the value to multiFieldsList:

public List<Object> fetchMultiFieldsList() {
    List<Object> multiFieldsList = new ArrayList<>();
    for (Entry<String, List<Object>> entry : multiFieldMap.entrySet()) {
        String entityName = entry.getKey();
        List<Object> ids = entry.getValue();
        for (Object id : ids) {
            Object entity = queryService.query(entityName, queryService.property("id").eq(id));
            multiFieldsList.add(entity);
        }
    }
    return multiFieldsList;
}

Can this method be simplified further?


texts:
Problem here.

It's not exactly the brute force approach but I'm not using any sort of pre-calculated primes table, and I'm definitely not using the coprimality trick shown in the PE pdf. I'm finding the divisor count for each triangle number via its representation as a product of primes. More on it here.

I've written a bunch of similarly sized programs in Chicken Scheme before, and this is my 2nd Racket program.

Is there anything that I'm doing that isn't something a Racketeer would do? Am I reinventing anything that's already implemented?

#lang racket

(define (prime? n)
  (if (<= n 1)
      #f
      (not (ormap (lambda (x) (= (modulo n x) 0))
                  (stream->list (in-range 2 (add1 (truncate (sqrt n)))))))))

(define (next-prime start)
  (define (search candidate)
    (if (prime? candidate)
        candidate
        (search (add1 candidate))))
  (search (add1 start)))

(define (prime-factors n)
  (define (decompose num prime factors)
    (cond
      ([prime? num] (append factors (list num)))
      ([not (= 0 (modulo num prime))] (decompose num (next-prime prime) factors))
      (else (decompose (quotient num prime) prime (append factors (list prime))))))
  (if (= n 1)
      empty
      (decompose n (next-prime 1) empty)))

(define (remove-duplicates numbers)
  (define (remove numbers result)
    (cond
      ([empty? numbers] result)
      ([not (member (first numbers) result)]
       (remove (rest numbers) (append result (list (first numbers)))))
      (else
       (remove (rest numbers) result))))
  (remove numbers empty))

(define (divisor-count n)
  (let* ([factors (prime-factors n)]
         [no-duplicates-factors (remove-duplicates factors)])
    (apply * (map add1 (map (lambda (x)
                              (count (lambda (y) (= x y)) factors))
                            no-duplicates-factors)))))

(define (number->triangle-number n)
  (quotient (* n (add1 n))
            2))

(define (first-triangle-num-with property)
  (define (search candidate)
    (let ([triangle-candidate (number->triangle-number candidate)])
      (if (property triangle-candidate)
          triangle-candidate
          (search (add1 candidate)))))
  (search 1))

An answer is obtained via a call like:

(first-triangle-num-with (lambda (x) (>= (divisor-count x) 10)))


texts: Slow bash script for getting audio/video duration

texts:
I have created a bash script to generate a HTML file, which will have the duration of the audio/video files in the current folder. The script uses ffprobe to fetch the duration in the quiet mode and file to get the mime-type. Although, the script works as intended, it feels a bit slow. I was wondering if it is possible to speed it up.
However, I don't have any experience in scripting and don't know about any time profiling tools. I did come across a stackoverflow answer on that topic, but time profiling can't suggest new libs or methods.

I did come across a suggestion on the SO from the python world using opencv and the benchmarks looked promising, but I am wary of installing such a huge library, and its big or small dependencies, just for this.

#!/bin/bash

today=$(date +"%Y-%m-%d-%H-%M-%S")
file=$(printf "duration-${today}.html")
tot_dur=0
echo "<!DOCTYPE html>

" >> "${file}"
echo "
" >> "${file}"
echo "

        File
        Duration

" >> "${file}"
while read filename
do
    mime=$(file -b --mime-type "${filename}")
    IFS='/' read -r -a mime <<< "$mime"
    if [[ $mime == "video" || $mime == "audio" ]]; then
        duration=$(ffprobe -v quiet -of default=noprint_wrappers=1:nokey=1 -show_entries format=duration "${filename}")
        tot_dur=$(echo $tot_dur + $duration | bc -l)
        duration=$(printf '%02d:%02d:%02f\n' $(echo -e "$duration/3600\n$duration%3600/60\n$duration%60"| bc | xargs echo))
        echo "
"${filename}"	"${duration}"
" >> "${file}"
    fi
done < <(ls)
# (find . -type f)
tot_dur=$(printf '%02d:%02d:%02f\n' $(echo -e "$tot_dur/3600\n$tot_dur%3600/60\n$tot_dur%60"| bc | xargs echo))
echo "

        Total
        ${tot_dur}

" >> "${file}"
echo "
" >> "${file}"
echo " " >> "${file}"


texts: Single Linked List JavaScript implementation

texts:
How can I improve my singly linked list implementation?

"use strict";

var LinkedList = function(){
  this.head = null;
  this.tail = null;
  this.count = null;
}
var Node = function(value){
  this.value = value;
  this.next = null;
}

LinkedList.prototype.addToHead = function(value){
  var newNode = new Node(value);
  if(this.head) {
    this.next = this.head;
    this.head = newNode
    this.count++;
  }
  else this.tail = newNode
}
LinkedList.prototype.addToTail = function(value){
  var newNode = new Node(value);
  if(this.tail) {
    this.tail.next = newNode
  }
  else this.tail = newNode;
}
var ll = new LinkedList();
ll.addToHead(3);
ll.addToHead(4);
ll.addToHead(2);
ll.addToTail(6);
console.log(JSON.stringify(ll))


texts: Parking Charges exercise from Deitel's C book

texts:
I'm learning to code with Deitel's C: How to program book, 6th edition. Here's Exercise 5.9 (Parking Charges):

  A parking garage charges a $2.00 minimum fee to park for up to three
  hours and an additional $0.50 per hour for each hour or part thereof
  over three hours. The maximum charge for any given 24-hour period is
  $10.00. Assume that no car parks for longer than 24 hours at a time.
  Write a program that will calculate and print the parking charges for
  each of three customers who parked their cars in this garage
  yesterday. You should enter the hours parked for each customer. Your program should print the results in a neat tabular
  format, and should calculate and print the total of yesterday's
  receipts. The program should use the function calculateCharges to
  determine the charge for each customer.

My solution is below. These exercises have no answers so I don't know how can I improve this code, in which I want to know if it is possible to dispense with variables "one", "two" and "three", and also automate the printing process (after the for loop in main) inside a loop.

#include <stdio.h>

float calculateCharges( float hours );

float charge;

int main()
{
    int customer;
    float one;
    float two;
    float three = 0;
    float hours;

    for( customer = 1; customer <= 3; customer++ ) {
        printf( "Enter customer #%d parking hours: ", customer );
        scanf( "%f", &hours );

        if( customer == 1 )
            one = hours;
        else if( customer == 2 )
            two = hours;
        else
            three = hours;
    }
    printf( "%s%10s%12s", "Car", "Hours", "Cost" );
    printf( "\n%d%12.1f%12.1f", 1, one, calculateCharges( one ) );
    printf( "\n%d%12.1f%12.1f", 2, two, calculateCharges( two ) );
    printf( "\n%d%12.1f%12.1f", 3, three, calculateCharges( three ) );
    printf( "\n%s%8.1f%12.1f", "TOTAL", one + two + three, calculateCharges( one ) + calculateCharges( two ) + calculateCharges( three ) );
}

float calculateCharges( float hours )
{
    int h = hours;
    charge = 2.0;

    if( hours > 0 ) {
        if( hours <= 3 )
            return charge;

        else if( hours <= 24 ) {
            while( h > 3 ) {
                charge += .5;
                h--;
                if( charge >= 10 )
                    charge = 10;
            }
            return charge;
        }
    }
    else
        printf( "\nThe amount of time entered is not supported." );
}


texts: Python list dictionary items round robin mixing

texts:
I have a list of dictionaries, which I want to make round robin mixing.

sample = [
    {'source': 'G', '"serial"': '0'},
    {'source': 'G', '"serial"': '1'},
    {'source': 'G', '"serial"': '2'},
    {'source': 'P', '"serial"': '30'},
    {'source': 'P', '"serial"': '0'},
    {'source': 'P', '"serial"': '1'},
    {'source': 'P', '"serial"': '2'},
    {'source': 'P', '"serial"': '3'},
    {'source': 'T', '"serial"': '2'},
    {'source': 'T', '"serial"': '3'}
]

I want result as below:

sample_solved = [
    {'source': 'G', '"serial"': '0'},
    {'source': 'P', '"serial"': '30'},
    {'source': 'T', '"serial"': '2'},
    {'source': 'G', '"serial"': '1'},
    {'source': 'P', '"serial"': '1'},
    {'source': 'T', '"serial"': '3'},
    {'source': 'G', '"serial"': '2'},
    {'source': 'P', '"serial"': '0'},
    {'source': 'P', '"serial"': '2'},
    {'source': 'P', '"serial"': '3'}
]

The way I solved it as follows:

def roundrobin(*iterables):
    # took from here https://docs.python.org/3/library/itertools.html#itertools-recipes

    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis

    pending = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

def solve():
    items_by_sources = collections.defaultdict(list)

    for item in sample:
         items_by_sources[item["source"]].append(item)

    t, p, g = items_by_sources.values()

    print(list(roundrobin(t, p, g)))

Using python default dict to separate the items by source and then using roundrobin solution which I got from python docs.

How can make the solution more pythonic or improved?


texts:
I'm trying to create a generic Makefile that will work with the following directory structure:

Project Directory

Makefile
main.c source file
source directory

Source files

include directory

Header files for each source file

depend directory

GCC generated depend (.d) files for each source/header pair

object directory

all compiled object (.o) files

It should automatically generate depend files and include them to build the executable. Currently this works for my basic C projects that are all from source but I'm planning on also using this (or some slightly modified version of this) for an OpenGL project using glfw and GLAD. I would like this Makefile to remain cross-platform between MSYS2 on Windows and Linux. Any thoughts?

TARGET      = hashtest # executable name
SOURCE_DIR  = source
OBJECT_DIR  = objects
DEPENDS_DIR = depends
MAIN        = main.c

NAMES   := $(shell find $(SOURCE_DIR) -name "*.c" -printf "%f\n")
SOURCES := $(addprefix $(SOURCE_DIR)/, $(NAMES))
OBJECTS := $(addprefix $(OBJECT_DIR)/, $(NAMES:.c=.o))
DEPS    := $(addprefix $(DEPENDS_DIR)/, $(NAMES:.c=.d))

DEPS += $(DEPENDS_DIR)/$(TARGET).d

INCL_DIRS := $(shell find . -type d -name "include*")
INCL_FLAG := $(addprefix -I , $(INCL_DIRS))

CC            = gcc
OBJ_CFLAGS    = -g -Wall $(INCL_FLAG) -MMD -MP -MF $(DEPENDS_DIR)/$*.Td -c
TARGET_CFLAGS = -g -Wall $(INCL_FLAG) -MMD -MP -MF $(DEPENDS_DIR)/$@.Td
#Add -mwindows to disable console window opening on launch (stdout can only be piped afterwards)

$(TARGET): $(OBJECTS) | $(DEPENDS_DIR)
    $(CC) $(TARGET_CFLAGS) -o $@ $(OBJECTS) $(MAIN)
    @mv -f $(DEPENDS_DIR)/$@.Td $(DEPENDS_DIR)/$@.d && touch $@
    @echo "Build successful."

$(OBJECT_DIR)/%.o: $(SOURCE_DIR)/%.c $(DEPDIR)/%.d | $(OBJECT_DIR) $(DEPENDS_DIR)
    $(CC) $(OBJ_CFLAGS) -o $@ $<
    @mv -f $(DEPENDS_DIR)/$*.Td $(DEPENDS_DIR)/$*.d && touch $@

$(OBJECT_DIR):
    mkdir -p $(OBJECT_DIR)

$(DEPENDS_DIR):
    mkdir -p $(DEPENDS_DIR)

.PHONY: clean

$(DEPDIR)/%.d: ;

.PRECIOUS: $(DEPDIR)/%.d

clean:
    rm -f $(OBJECT_DIR)/*.o
    rm -f $(DEPENDS_DIR)/*.d
    rm -f $(TARGET)
    @echo "Clean successful."

-include $(DEPS)
```


texts:
I'm giving myself programming challenges in various languages so that I can become a better problem solver i.e. focusing on problem abstraction and algorithm design, using various programming paradigms. This includes re-writing code from one type of language to another. Yesterday I posted a Python script using TKinter that converts Celsius <-> Fahrenheit and received very helpful feedback from a contributor here. I've written the same thing in Racket (layout is a little different) with some help from the documentation here. A big difference with this code is that I've not defined the GUI as a single class made from widget objects. Is this good practice in Racket?

The script makes use of the Racket GUI library (module?) and binds the GUI widgets to global variables using 'define'. The type of conversion is decided using the checkbox e.g. ticked does a Fahrenheit conversion. I've put the conversion function within the button object callback. Should I include a function call here to make it more readable? Also, I feel that my use of define within the callback is a bad thing - I should use let. I defined the checkbox further down the script as I wanted it to appear below the button.

I'd appreciate your feedback about this e.g. code layout, what am I doing wrong or what could be done better?

#lang racket
(require racket/gui/base)
; Create a dialog
(define dialog (instantiate dialog% ("Celsius <-> Farenheit")))

; Add a text field to the dialog
(define textField (new text-field% [parent dialog] [label "Enter value"]))

;add label that shows the converted vales
(define output (new message% [parent dialog] [label "output"]))

; Add a horizontal panel to the dialog
(define panel (new horizontal-panel% [parent dialog]
                                     [alignment '(center center)]))

(new button% [parent panel]
     [label "calculate"]
     [callback (lambda (button event)
                 (let ([value (send textField get-value )])
                   (define b (send check get-value))
                   (if (eq? b #f)
                       (send output set-label value)
                       (send output set-label (number->string (+ (/ (* 9 (string->number value)) 5.0) 32)))
                    )
                   ))]
)

(define check (new check-box% [parent panel] [label "farenheit"]))

; Show the dialog
(send dialog show #t)


texts: Convert a matrix ("DataFrame") to printable string

texts:
While I understand that "V is a simple language," I find myself repeating a lot of stuff. For instance the whole first block, "measure column widths," could beautifully be accomplished by two simple list comprehension lines in Python. Is there some way to simplify the allocate array, initialize the index pointer, loop-assign, increase index pointer code? Any equivalent to Python's enumerate() would go a long way...
What do I do about the pad thing? Sure, it will work in 99.9% instances, but would be nice with an arbitrary length solution (such as ' '*n in Python).
Performance-wise I'm not concerned for this function in particular, but I'm curious if there are any obvious blunders? It looks close to C to me, and it's probably only cache handling that could be a problem? I'm assuming the three mutable arrays end up on the heap? If so: anything I can do about that?
I'm left with the sense that "simple language" in this case is equivalent to "hard-to-read implementation." With just a few more features it could be both simple and easy to read? What is your impression?
pub fn (df DataFrame) str() string {
    // measure column widths
    mut width := []int{len: 1 + df.cols.len}
    mut str_sers := []Series{len: 1 + df.cols.len}
    mut sers := [df.index]
    sers << df.cols
    mut i := 0
    for ser in sers {
        str_sers[i] = ser.as_str()
        mut row_strs := str_sers[i].get_str().clone()
        row_strs << [ser.name]
        width[i] = maxlen(row_strs)
        i++
    }

    // columns
    pad := '                                        '
    mut row_strs := []string{len: sers.len}
    i = 0
    for ser in sers {
        w := width[i]
        row_strs[i] = pad[0..(w - ser.name.len)] + ser.name
        i++
    }
    mut s := row_strs.join('  ')

    // cell data
    l := df.len()
    if l == 0 {
        s += '\n[empty DataFrame]'
    }
    for r in 0 .. l {
        i = 0
        for ser in str_sers {
            w := width[i]
            row_strs[i] = pad[0..(w - ser.get_str()[r].len)] + ser.get_str()[r]
            i++
        }
        s += '\n' + row_strs.join('  ')
    }
    return s
}