texts:
I've create a simple interface for viewing a time-series as it changes over time in matplotlib. You can pause, reset or click/drag on the time-line to change the view. Have I used the matplotlib API as effectively as possible?

import numpy as np
from collections import deque

import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Button, Slider

class AnalogPlot:

    def __init__(self, data, display_len):
        self.buff = deque(np.zeros(display_len))
        self.display_len = display_len
        self.data = data

        # set up the plot
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111, xlim=(0, t_max), ylim=(-1, 1))
        self.ax.set_xticks((0, t_max))
        self.lines = self.ax.plot([], [])

        # setup the animation
        self.cur_frame = 0
        self.anim = animation.FuncAnimation(self.fig, self._update,
                                            interval=1.0)

        # setup the animation control
        self.anim_running = True

    def _add_to_buff(self, buf, val):
        if len(buf) < self.display_len:
            buf.appendLeft(val)
        else:
            buf.popleft()
            buf.append(val)

    def _update(self, frame):
        frame = self.cur_frame
        self._add_to_buff(self.buff, self.data[frame:frame+1])
        self.lines[0].set_data(range(self.display_len), self.buff)

        self.ax.set_xticklabels((str(frame), str(frame+self.display_len)))

        self.time_slider.eventson = False
        self.time_slider.set_val(frame)
        self.time_slider.eventson = True

        self.cur_frame += 1

        return self.lines

    def _pause(self, event):
        if self.anim_running:
            self.anim.event_source.stop()
            self.anim_running = False
        else:
            self.anim.event_source.start()
            self.anim_running = True

    def _reset(self, event):
        self._set_val(0)

    def _set_val(self, frame=0):
        frame = int(frame)
        self.cur_frame = frame
        new_start = frame - self.display_len
        if new_start >= 0:
            self.buff = deque(self.data[new_start:frame])
        else:
            self.buff = deque(np.concatenate((np.zeros(np.abs(new_start)),
                                              self.data[:frame])))

        self.anim.event_source.stop()
        self.anim = animation.FuncAnimation(self.fig, self._update,
                                            interval=1.0)
        self.anim_running = True

    def animate(self):
        pause_ax = self.fig.add_axes((0.7, 0.025, 0.1, 0.04))
        pause_button = Button(pause_ax, 'pause', hovercolor='0.975')
        pause_button.on_clicked(self._pause)

        reset_ax = self.fig.add_axes((0.8, 0.025, 0.1, 0.04))
        reset_button = Button(reset_ax, 'reset', hovercolor='0.975')
        reset_button.on_clicked(self._reset)

        slider_ax = self.fig.add_axes((0.1, 0.025, 0.5, 0.04))
        self.time_slider = Slider(slider_ax, label='Time',
                                  valmin=0, valmax=self.data.shape[0],
                                  valinit=0.0)

        self.time_slider.on_changed(self._set_val)

        plt.show()

t_max = 100
lin_sig = np.linspace(0, 1, 1000)
analog_plot = AnalogPlot(lin_sig, t_max)
analog_plot.animate()


texts:
Here is my code to find the details of the domain. The domain can be feed as following:

bash script.sh domain1.com domain2.com
bash script.sh domains.txt <-- not completed

The output should be in following format:

IP Address: 192.168.101.2
Server Name: servername.com
NS1: ns1.ournameserver.com
NS2: ns2.ournameserver.com
NS3: ns3.ournameserver.com
Datacenter: datacenter-name
Region: datacenter-13
Server Role: cPanel Web Server
Env: Production
Owner: xxxxxxxxxxx
Status: Active

IP Address: 192.168.101.2
Server Name: servername
NS1: ns1.ournameserver.com
NS2: ns2.ournameserver.com
NS3: ns3.ournameserver.com
Datacenter: datacenter-name
Region: datacenter-13
Server Role: cPanel Web Server
Env: Production
Owner: xxxxxxxxxxx
Status: Suspended

If it is in cloudflare:

Domain name: test.com
IP Address: 192.168.101.1
Server ID: N/A
Server Name: N/A
NS1: LYNDA.CLOUDFLARE.COM
NS2: DYN.CLOUDFLARE.COM
Datacenter: OVH
Region: HETZ-C3
Server Role: cPanel Web Server
Env: Production
Owner: xxxxxxxxxxx

Now it is only giving result in normal format, it also needs to be in JSON format

script.sh

#!bin/bash
HIP="$@"
check ()
{
    regexp="^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$"
    nameserver=('@ns1.ournameserver.com' '@ns2.ournameserver.com' '@ns3.ournameserver.com')

    for j in ${nameserver[@]}
       do
          IPADD=`dig $j $i +noall +answer | grep "A" | awk '{print $5}'`
          if [[ $IPADD =~ $regexp ]]
            then
                echo "IP Address = " $IPADD
                ServerName=`nslookup $IPADD | grep -o -P '(?<=\=).*(?=.)'`
                echo "ServerName = " $ServerName
                DATA=`whois $IPADD | egrep 'org-name|OrgName' | awk '{print $2.$3}'`
                echo "Data Center = " $DATA
                break
          fi
       done
}

check2 ()
{
    Pinging=`ping $i -c 1 | grep 'from' | cut -d$' ' -f4-5| tr '\(|\)' ' '`
    IPADD=`awk '{print $2}' <<< $Pinging`
    echo "IP Address = " $IPADD
    ServerName=`awk '{print $1}' <<< $Pinging`
    echo "Server Name = " $ServerName
}

for i in ${HIP[@]}
do
    echo "Domain Name = " $i;
    nsserver=`nslookup -type=ns $i | grep 'nameserver' |  grep -o -P '(?<=ns.).*(?=.)' | head -n 1`
    if [[ $nsserver == 'cloudflare.com' ]]
    then
            check
        if ! [[ $IPADD =~ $regexp ]]
        then
                echo "This Domain does not belong to this server."
        fi
    else
        check2
    fi

    whois $i | grep "Registrant Name"
    nslookup -type=ns $i | grep nameserver | awk '{print $2,$3,$4}'
    var=`curl -sL $i | grep '<title>' | tr -d ' ' | grep -o -P '(?<=Account).*(?=ed)'`
    if [[ $var == 'Suspend' ]]
        then
        echo "Status = Account Suspended"
        else
        var=`curl -I $i 2>/dev/null | head -n 1 | cut -d$' ' -f2-3`
        echo "Status = " $var
    fi
    printf '%*s' 100 | tr ' ' '#'
    echo ''

done


texts: Polling AJAX client for P2P file sharing website

texts:
I have this function:

function Filer() {
    setTimeout(function () {
        $.ajax({
            url: '/Pages/Handlers/filecheckerhandler.ashx',
            data: { id: GetMyId(), sid: GetSessionId() },
            success: function (data) {
                if (data == "true") {
                    window.open('/Pages/Handlers/livesharehandler.ashx?id=' + GetMyId() + '&sid=' + GetSessionId(), '_self');
                }
            },
            global: false
        });
        Filer();
    }, 2000)
}
Filer();

Basically, my website allows for peer to peer file sharing online. What this does is checks for files and if it is present the file will be downloaded and the file will be deleted from the server.

The function is recursive as you can see. This is making a lot of requests.

But my function is making a lot of requests which is making the site slow. What can be done?


texts: Find and print all numbers in a comma-delimited string using sscanf

texts:
I want to find all of the whole numbers in a string that starts with { and ends with }, and uses , to separate each number.

I use sscanf to find and match each item in the string—for example:

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

int main(void)
{

    const char *str =  "{0,1,22,333,4,55,6,77777,8}";
    int tmp, tmp2, tmp3, number;

    printf("filtered number:");

    tmp = 0;
    while(1)
    {
        if( *str == '{' )
        {
            /* begin of current str */
            tmp2 = 0;
            tmp3 = 0;
        }

        if( *str == ',' || *str == '}' )
        {
            /* found a number now */
            tmp++;

            /* get how far the ptr move */
            //printf("ptr moved step: %d\n", tmp2);

            /* get the digit len */
            tmp3 = tmp2 - tmp3 - 1;

            /* get the number */
            sscanf(str-tmp3, "%d", &number);
            printf("%d ", number);

            /* record current ptr possition */
            tmp3 = tmp2;
        }

        if ( *str == '}' ) break;

        str++;
        tmp2++;
    }
    printf("\n");
    printf("howm any number found: %d\n", tmp);

    return 0;
}

Questions:

Any risk in my code?
Is there a smarter way to do this? Can my code be optimized?


texts:
I have a function written in Python 2.7 that I call several times in a program. This function is rather slow, and I'd like to rewrite it in NumPy. However, I don't know how to do it.

I basically have a canvas of width * height pixels, and I'm making something rather complicated inside. I'd like to know how to replace all the parts with:

for i in range(x):
    do x[i]
    ...

by NumPy-style operations.

I know that I can start by making an array of zeros with np.zeros, but how can I implement the equations / operations in NumPy?

def Circular_cumsum_spot(width,height,centre,radius,spectrum,red_or_violet):
    """makes a "light spot" by cumsums
    from the center to the periphery

    width, height = size of canvas
    x, y = center of the spot
    radius = magnitude of the spot in pixels
    spectrum = light source
    red = to red, violet = to violet

    returns a numpy array"""

    x,y = centre[0], centre[1]

    data = []
    X = Y = Z = 0

    for i in range(height):
        for j in range(width):

            distance = radius - np.sqrt((i-x)**2+(j-y)**2)

            if distance >= radius:
                cumsum = 0
                X = Y = Z = 0
            else:
                cumsum = round((distance/radius) * (len(spectrum)))

                if red_or_violet == "red":

                    for k in range(cumsum):

                        X += spectrum[k][0]
                        Y += spectrum[k][1]
                        Z += spectrum[k][2]

                else:

                    for k in range(cumsum):

                        l = len(spectrum)-k-1

                        X += spectrum[l][0]
                        Y += spectrum[l][1]
                        Z += spectrum[l][2]

            data += [(X,Y,Z)]
            X = Y = Z = 0
    data = np.array(data)

    divisor = np.max(data[:,1])

    if divisor == 0:
        data = data
    else:
        data = np.divide(data, divisor)

    return data
    print "spot created is", red_or_violet


texts:
I was trying to explain the mediator pattern to a new developer, and ended up writing a simple event mediator. Thoughts?

EventMediator

class EventMediator {
    private $events = array();

    public function attach($event, Closure $callback) {
        if(!is_string($event)) throw new \InvalidArgumentException();

        $event = strtolower(trim($event));
        if(!isset($this->events[$event])) $this->events[$event] = array();

        $this->events[$event][] = $callback;

        return $this;
    }

    public function trigger($event, $data = null) {
        if(!is_string($event)) throw new \InvalidArgumentException();

        $event = strtolower(trim($event));
        if(!isset($this->events[$event])) return false;

        foreach($this->events[$event] as $callback) $callback($event, $data);

        return true;
    }

    public function getEvents() { return $this->events; }
}

EventfulTrait

trait EventfulTrait {

    private $eventMediator;

    public function attachEventMediator(EventMediator $eventMediator) {
        $this->eventMediator = $eventMediator;
        return $this;
    }

    public function detachEventMediator() {
        $this->eventMediator = null;
        return $this;
    }

    public function getEventMediator() {
        return $this->eventMediator;
    }

    public function attachEvent($name, $callback) {
        if(!is_null($this->eventMediator)) $this->eventMediator->attach($name, $callback);
        return $this;
    }

    public function triggerEvent($name, $data = null) {
        if(!is_null($this->eventMediator)) return $this->eventMediator->trigger($name, $data);
        return false;
    }
}

Example

require "EventMediator.php";
require "EventfulTrait.php";

class Log {
    public function write($message) {
        echo "{$message}\n";
    }
}

class Eventful {
    use EventfulTrait;

    private $log;

    public function __construct() { $this->log = new Log(); }

    public function attachLoadEvent() {
        $self = $this;
        $log  = $this->log;
        $this->attachEvent(
            "load", function() use($self, $log) {
                $self->runOutOfNames();
                $log->write("log message");
            }
        );
    }

    public function doSomething() {
        $this->triggerEvent("load");
        $this->triggerEvent("event1");
    }

    public function doSomethingElse() {
        $this->triggerEvent("load");
        $this->triggerEvent("event1");
        $this->triggerEvent("event2");
    }

    public function runOutOfNames() { echo "load\n"; }
}

$eventMediator = new EventMediator();
$eventMediator->attach("event1", function() { echo "event1\n"; });
$eventMediator->attach("event2", function() { echo "event2\n"; });
$eventMediator->attach("done", function() { echo "done\n"; });

$eventful = new Eventful();
$eventful->attachEventMediator($eventMediator);
$eventful->attachLoadEvent();
$eventful->doSomething();
$eventful->doSomethingElse();

$eventMediator->trigger("load");
$eventMediator->trigger("done");

This will echo:

load
log message
event1
load
log message
event1
event2
load
log message
done


texts:
This relates to Round to specified int but I'm separating these methods out since they're technically different.

Is there a method that already performs a custom floor and ceiling to a specified integer?

// If the interval is 5, 9 --> 5.
public static int FloorTo(this int value, int interval)
{
    var remainder = value % interval;
    return remainder > 0 ? value - remainder : value;
}

// If the interval is 5, 6 --> 10.
public static int CeilingTo(this int value, int interval)
{
    var remainder = value % interval;
    return remainder > 0 ? value + (interval - remainder) : value;
}


texts: Large-scale pairwise similarity calculations of vectors

texts:
I am a C++ beginner and am working on a bit of code which calculates the pairwise cosine similarities between vectors. The vectors are TF-IDF vectors and the similarities are used to determine similarity between texts (documents).

My code and approach outlined below work as expected, but runs into performance issues when datasets get larger. The number of vectors often runs into the thousands and the vectors can be quite large themselves (thousands of elements).

I have done the following to try and optimize the code:

In the nested loop, set j equal to i to only calculate similarities one way, i.e. only return results for one side of the diagonal of the similarity matrix;
Passing the vectors as const references to cosine_similarity to avoid the overhead of copying the vectors;
Defined v1i and v2i outside of the loop in cosine_similarity to only look them up once inside the loop (as opposed to using v1[i] and v2[i] in the dot product and sum of squares calculations);
Check for dot_product == 0 in cosine_similarity to avoid magnitude calculation when it is not necessary.

Here's what I have:

// Vector containing all the vectors to compare (populated somewhere else)
std::vector< std::vector<double> > vector_of_vectors;

// Get the number of vectors
int number_of_vectors = vector_of_vectors.size();

// Get the size of a vector (all vectors have the same size)
int vector_size = vector_of_vectors[0].size();

// Vector to store the results
std::vector<double> similarities;

// Nested loop for similarity calculation
for (int i=0; i<number_of_vectors; ++i) {
    for (int j=i; j<number_of_vectors; ++j) {
        if (i == j) {
            similarities.push_back(1);
        } else {
            similarities.push_back(cosine_similarity(vector_of_vectors[i], vector_of_vectors[j], vector_size));
        }
    }
}

double cosine_similarity(const std::vector<double>& v1, const std::vector<double>& v2, const int& vector_size) {
    // Cross-vector dot product
    double dot_product = 0;

    // Sum of squares of first vector
    double ss1 = 0;

    // Sum of squares of second vector
    double ss2 = 0;

    double v1i;
    double v2i;
    for (int i=0; i<vector_size; ++i) {
        v1i = v1[i];
        v2i = v2[i];

        dot_product += (v1i * v2i);
        ss1 += (v1i * v1i);
        ss2 += (v2i * v2i);
    }

    if (dot_product == 0) {
        return 0;
    } else {
        double magnitude = sqrt(ss1 * ss2);
        return dot_product / magnitude;
    }
}

I'm quite happy about how it works, but have the feeling there are some things I could do to make this much faster. Any ideas?


texts: String extension method that truncates at sentence punctuation

texts:
I've received a request at work and the senior developer is away on vacation so I can't ask him. The request was to truncate lengthy article titles while maintaining readability. In other words, don't simply chop a word in half and add an ellipsis.

I wrote an extension method that looks for punctuation and establishes length requirements.

Bullet Points:

truncate at sentence endings ('.','!','?')
allow for variable maxLength
make sure title is at least 30 chars long (for the case where a title starts like "wow!")
when all else fails truncate at last space and add an ellipsis

Anyway, the method works the way I intended, however, the programming feels gross.

What is a more succinct way of writing this string extension method?

I've reproduced the code in a fiddle:
.NET Fiddle

Extension method

public static class StringExtensions
{

    public static string TruncateAtFirstSentence(this string value, int maxLength)
    {

        char[] punc = new char[3];
        punc[0] = '.';
        punc[1] = '!';
        punc[2] = '?';

        // not the best programming, basically falls though when requirements
        // arent met.
        foreach (char c in value) {

            if (c == punc[2]) {

                var str = value.Substring(0, value.IndexOf("?") + 1);

                if (str.Length <= 30)
                    continue;
                else
                {
                    if (str.Length > maxLength)
                    {
                        continue;
                    }
                    else
                    {
                        return str;
                    }
                }
            }
            else if (c == punc[1]) {

                var str = value.Substring(0, value.IndexOf("!") + 1);

                if (str.Length <= 30)
                    continue;
                else
                {
                    if (str.Length > maxLength)
                    {
                        continue;
                    }
                    else
                    {
                        return str;
                    }
                }
            }
            else if (c == punc[0]) {

                var str = value.Substring(0, value.IndexOf(".") + 1);

                if (str.Length <= 30)
                    continue;
                else
                {
                    if (str.Length > maxLength)
                    {
                        continue;
                    }
                    else
                    {
                        return str;
                    }
                }
            }
        }

        var output = value.Length <= maxLength ? value : value.Substring(0, maxLength);
        output = output.Substring(0, output.LastIndexOf(' '));

        return output + "...";

    }

}

Main program

public class Program
{

    public static void Main()
    {

        string sentence = "This is a simple! question that ends with! a question mark. This is nearly the same. sentence that also ends with a period.";
        string longSentence = "This is a simple question that does not end with a question mark This is nearly the same sentence that ends with a period.";

        var output = StringExtensions.TruncateAtFirstSentence(sentence, 100);
        var output2 = StringExtensions.TruncateAtFirstSentence(longSentence, 100);

        Console.WriteLine("output 1: \n{0}\n", output);
        Console.WriteLine("output 2: \n{0}\n", output2);
    }
}


texts:
I'd like to have neater URLs, no more and no less — I'd like to be able to write /page/subpage instead of something like ?p=page&s=subpage.

I've looked at various PHP frameworks and routing classes to see how they did it. Since most of them come with features I don't need, I wanted to try making my own system using only what's absolutely necessary — indeed, I think this is about as basic as routing can get.

Above all, I'd like to know if I've missed something. The code works, but I'm sure there are edge cases I didn't account for (or security issues; this is PHP after all).
On a side note, is there a difference betwen "routing" and "URL rewriting"? The terminology isn't all that clear to me.

.htaccess

RewriteEngine on

RewriteBase /routing_test/

RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php [QSA,L]

inc/functions/routing.php

<?php

    define('DEFAULT_PAGE_NAME', 'default');

    function getPageName($level)
    {
        $requestParams = explode('/', $_SERVER['REQUEST_URI']);
        $scriptPath = explode('/', $_SERVER['SCRIPT_NAME']);

        // remove the base path
        while ($requestParams[0] === $scriptPath[0])
        {
            array_shift($requestParams);
            array_shift($scriptPath);
        }

        if ($level === 0)
        {
            return $requestParams[0] ?: DEFAULT_PAGE_NAME;
        }

        return isset($requestParams[$level]) ? $requestParams[$level] : '';
    }

As you can see, it's really only one function that does the work: getPageName($level) gives the name of the "directory" at the specified level.

What you do with those is up to you — in this case, I'm simply including a file with that name.

index.php

<?php

    define('BASE_PATH', '/routing_test');

    require_once 'inc/functions/routing.php';

?>

        <title>Routing Test</title>

            <?php

                $pageName = getPageName(0);
                $subpageName = getPageName(1);

                if (file_exists($file = 'inc/content/' . $pageName . '.php'))
                {
                    include $file;
                }
                else
                {
                    echo 'not found';
                }

            ?>

inc/content/default.php

This is the default page

inc/content/users.php

<?php

    if ($subpageName === '')
    {
        echo 'Displaying all users.' . '
';
    }
    else
    {
        $userId = $subpageName;
        echo 'Displaying user #' . $userId . '.
';
    }

?>

<a href="<?php echo BASE_PATH . '/' . DEFAULT_PAGE_NAME; ?>">go back

In this example, opening /routing_test/users would show Displaying all users., while /routing_test/users/123 would show Displaying user #123..

As I said, I'm mainly looking for advice on best practices, security issues and correctness (pretty much exactly the points on the tour page), though general feedback is always welcome.


texts:
I've been playing around with functional programming for a while now and just started learning Clojure. So the problem I'm trying to solve is the following:

I have a tree-like hashmap of tasks where each task can include a number of tasks and each of those can include other tasks. The toy one I'm using for starters looks like this:

(def master-list
  {:name "Master List"
   :details "One List to Rule them all"
   :list
   [{:name "Writing"
     :details "Writing things is fun"
     :list
     [{:name "Write A Best-Seller"
       :details "Making money is also fun"
       :list
       [{:name "Come up with the plot"
         :details "What do I want to talk about?"}]}
      {:name "Write for the New York Times"
       :details "People need to hear this"}]}
    {:name "Reading"
     :details "I have a long list of books to read"
     :list
     [{:name "The Catcher in the Rye"
       :details "Who is Holden Caulfield and Why should I care?"}]}
    {:name "Profit"
     :details "All Done"}]})

Where :list contain the subtask list of a given task. Ok, cool, so far so good.

But in order to work with a given task I need to be able to get to it within that hashmap. And because that hashmap sits within an atom and to keep every representation of the tasks consistent I can't just copy it into a new map. What I figured is that I'd keep a vector of keys that can be used to access each item individually with the function get-in.

For example to refer to the task named "Come up with the plot" I can just store the vector [:list 0 :list 0 :list 0]. Since

(get-in master-list [:list 0 :list 0 :list 0])

Will return me the task I need. Cool.

So now I can access a task within the hashmap and if that changes the changes will be reflected everywhere. Now I need to have a way to find that vector given any of my tasks. Something that will always pass the test (called find-in in the code below):

(= list-i-have (get-in master-list (helper/find-in master-list list-i-have)))
;;Should always be true

After a while, I came up with the code:

(defn- inner-func [index item]
  (cond
   (= item '()) nil
   (seq? item) (conj item index)
   (== item true) (conj '() index)
   true nil))

(defn- is-in [task subtask]
  (cond
   (= task subtask) true
   (:list task)  (flatten (keep-indexed inner-func (keep #(is-in % subtask) (:list task))))
   true  nil))

(defn find-in [task subtask]
  (let [result (is-in task subtask)]
    (cond
     (== result true)  []
     (= result '())   nil
     true (interleave (cycle [:list]) result))))

That seems to solve my problem which brings me to my (many) questions:

What do you think about the design choices?
Have I missed any other ways to represent the list and the selected part of the list? Can you find any major flaws with my choice?
What about the code itself? Is it functional? As I was writing it, I felt like I kept falling back to imperative-like solutions.
Any other problems with it I might have missed?


texts:
I am learning C++ and currently playing with variadic template functions and formatting string, So here is my small attempt to write a formatting function and provide a simple iostream-like interface for std::FILE, I am using '%' as a format specifier
f.e

  format("const CharT *str") == "const CharT *str" format("HelloWorld -
  %", 10) == "HelloWorld - 10"

here is the code:

#include <cstdlib>
#include <string>

namespace gupta {
using string_t = std::string;
using CharT = string_t::value_type;

inline string_t format(const CharT *str) { return str; }
template <typename T> inline string_t to_string(const T &f) { return std::to_string(f); }
inline string_t to_string(const char *str) { return std::string{str}; }
inline string_t to_string(string_t s) { return (s); }

template <typename T, typename... Ts>
string_t format(const CharT *str, const T &arg, const Ts &... args) {
  string_t res;
  for(; *str; str++) {
    if(*str == '%') {
      if(*(str + 1) == '%') {
        str++;
      }
      else {
        res += to_string(arg);
        return res += format(str + 1, args...);
      }
    }
    res += *str;
  }
  return res;
}

template <typename... Ts> auto fprint(std::FILE *f, const char *str, Ts &&... args) {
  auto s = std::move(format(str, std::forward<Ts>(args)...));
  return fwrite(s.data(), 1, s.size(), f);
}

template <typename... Ts> inline auto print(const char *str, Ts &&... args) {
  return fprint(stdout, str, std::forward<Ts>(args)...);
}

template <typename... Ts> inline auto debug(const char *str, Ts &&... args) {
  return fprint(stderr, str, std::forward<Ts>(args)...);
}

namespace detail {
  class _stdout_object {};
  class _stderr_object {};
} // namespace detail

namespace printing_shortcuts {

  template <typename T> detail::_stdout_object operator<<(detail::_stdout_object f, const T &arg) {
    auto s = to_string(arg);
    fwrite(s.data(), 1, s.size(), stdout);
    return f;
  }

  template <typename T> detail::_stderr_object operator<<(detail::_stderr_object f, const T &arg) {
    auto s = to_string(arg);
    fwrite(s.data(), 1, s.size(), stderr);
    return f;
  }

  detail::_stdout_object print() { return {}; }
  detail::_stderr_object debug() { return {}; }

} // namespace printing_shortcuts

using namespace printing_shortcuts;

} // namespace gupta

using namespace gupta::printing_shortcuts;

class test {};

std::string to_string(const test &) { return "test"; }

#include <assert.h>
int main() {
  using namespace gupta;
  assert(format("const CharT *str") == "const CharT *str");
  assert(format("HelloWorld - %", 10) == "HelloWorld - 10");
  print("%s\n", format("HelloWorld - %,%", 10, test{}));
  assert(format("HelloWorld - %,%", 10, test{}) == "HelloWorld - 10,test");
}

also, does it make sense to replace class _stdout_object while their pointers with something like

namespace detail {
  class _stdout_object;
  class _stderr_object;
} // namespace detail

namespace printing_shortcuts {

  template <typename T> detail::_stdout_object *operator<<(detail::_stdout_object *, const T &arg) {
    auto s = to_string(arg);
    fwrite(s.data(), 1, s.size(), stdout);
    return nullptr;
  }

  template <typename T> detail::_stderr_object *operator<<(detail::_stderr_object *, const T &arg) {
    auto s = to_string(arg);
    fwrite(s.data(), 1, s.size(), stderr);
    return nullptr;
  }

  detail::_stdout_object *print() { return nullptr; }
  detail::_stderr_object *debug() { return nullptr; }

} // namespace printing_shortcuts


texts:
This page (full source & demo) displays a 2-channel horizontal d3.js Streamgraph that takes realtime mouse coordinates as data inputs for the graph.

However, it tends to gradually use up an increasing amount of memory until there's none left, both on Chrome and Firefox (on Ubuntu 12.04 x64).  Data is being collected but not released, yet the arrays that hold the incoming mouse coord data are being popped for every push, and I'm missing where the problem is occuring.

I'm working on profiling it, but wondering if any JS experts can eyeball it and see it.  The only dependencies are JQuery and D3.js v3.


texts:
Can someone please critique my Elevator problem - I wanted to use OOP principles and coding standards.
Also, does logic make sense?

Once elevator starts going up it needs to finish all requests for above floors, same for down.

So I imagine that if the elevator is moving up and the request is floor below it will need to finish all up/above requests etc.

internal class Program
{
    private const string _quit = "q";

    private static void Main(string[] args)
    {
        var manager = new Manager();
        var input = string.Empty;

        while (input != _quit) {
            Console.Write("Enter floor: ");
            input = Console.ReadLine();
            int floor;
            if (int.TryParse(input, out floor))
                manager.ButtonPressed(floor);
            else if (input == _quit)
                Console.WriteLine("GoodBye!");
            else
                Console.WriteLine("You have pressed an incorrect floor, Please try again");
        }
    }
}

internal enum Status
{
    GoingUp,
    GoingDown,
    Stopped
}

internal class Elevator
{
    public int TopFloor;

    public Elevator(int topFloor)
    {
        TopFloor = topFloor;
    }

    public int CurrentFloor { get; set; } = 1;
    public Status Status { get; set; } = Status.Stopped;

    public void MoveUp(int floor)
    {
        Status = Status.GoingUp;
        Console.WriteLine("Going up to: {0}", floor);
        CurrentFloor = floor;
        OpenDoor();
        CloseDoor();
    }

    public void MoveDown(int floor)
    {
        Status = Status.GoingDown;
        Console.WriteLine("Going down to: {0}", floor);
        CurrentFloor = floor;
        OpenDoor();
        CloseDoor();
    }

    private void OpenDoor()
    {
        Console.WriteLine("Door opening");
    }

    private void CloseDoor()
    {
        Console.WriteLine("Door closing, at floor: {0}", this.CurrentFloor);
    }
}

internal class Request
{
    public Request(int floor)
    {
        Floor = floor;
    }

    public int Floor { get; set; }
}

internal class Manager
{
    private readonly Queue<Request> _downRequests = new Queue<Request>();
    private readonly Elevator _elevator = new Elevator(10);
    private readonly Queue<Request> _upRequests = new Queue<Request>();

    public void ButtonPressed(int floor)
    {
        if (floor > _elevator.TopFloor) {
            Console.WriteLine("Only have {0} floors", _elevator.TopFloor);
            return;
        }

        if (floor > _elevator.CurrentFloor)
            _upRequests.Enqueue(new Request(floor));
        else
            _downRequests.Enqueue(new Request(floor));

        Move(floor);
    }

    private void Move(int floor)
    {
        switch (_elevator.Status) {
            case Status.GoingDown:
                while(_downRequests.Count > 0)
                    _elevator.MoveDown(_downRequests.Dequeue().Floor);

                _elevator.Status = Status.Stopped;
                break;

            case Status.GoingUp:
                while(_upRequests.Count > 0)
                    _elevator.MoveUp(_upRequests.Dequeue().Floor);

                _elevator.Status = Status.Stopped;
                break;

            case Status.Stopped:
                if (floor > _elevator.CurrentFloor)
                    _elevator.Status = Status.GoingUp;
                else if (floor <= _elevator.CurrentFloor) {
                    _elevator.Status = Status.GoingDown;
                }
                Move(floor);

                break;
            default:
                break;
        }
    }
}

Revised code based on feedback: Elevator Interview Problem OOP - Revised


texts: Sort array of hashes with nil values last

texts:
I wrote a method which sorts an array of hashes by given hash keys. The method should put nil values at the end.

def sort(records, *attrs)
  records.sort do |a,b|
    result = 0
    attrs.each do |attr|
      unless a[attr] == b[attr]
        result = if a[attr].nil?
                   1
                 elsif b[attr].nil?
                   -1
                 else
                  a[attr] <=> b[attr]
                 end
        break
      end
    end
    result
  end
end

p sort([{:a => 1},{:a => nil},{:a => 2}], :a)
#=> [{:a=>1}, {:a=>2}, {:a=>nil}]
p sort([{:a => nil},{:a => 'x'},{:a => 'a'}], :a)
#=> [{:a=>"a"}, {:a=>"x"}, {:a=>nil}]

My solution looks quite complex. Is there a better way to achieve the ordering in Ruby?


texts:
I wrote this program to remove comments from a C source file, accepting a file name from the command prompt. Let me know if I missed anything or if there are any improvements that can be made in the program.

#include<stdio.h>
#include<stdbool.h>

void m_cmnt( FILE *fp )
{
    int prev=0 , ch ;

    while ((ch=getc(fp))!=EOF)
    {
        if ( prev== '*' && ch == '/')
            return ;
        else
        prev=ch ;
    }
}

void s_cmnt( FILE *fp )
{
    int ch ;
    while ( (ch=getc(fp))!='\n' && ch!=EOF )
        ;
}

int main ( int c , char **arr )
{
        FILE *fp , *np ;
        int ch , prev=0 ;
        bool String=0 ;

        fp = fopen(arr[1] , "r") ;
        np = fopen("temp.txt" , "w") ;

        if (fp==NULL )
        {
            printf ("Invalid/No Filename given as Argument ! \n") ;
            return 1 ;
        }
        while ((ch=getc(fp))!=EOF )
        {
            /* file pointer currently not inside a string */
            if ( !String )
            {
                if ( ch=='/' )
                {
                    prev=ch ;
                    ch= getc(fp) ;
                    switch(ch)
                    {
                        case '*'  : m_cmnt( fp) ;
                                     break ;
                        case '/'  : s_cmnt( fp) ;
                                     break ;
                        default   :  putc(prev , np) ;
                                     putc(ch , np) ;
                                     break ;
                    }
                }
                else putc( ch ,np ) ;
            }
            else  putc(ch , np) ;

            if ( ch=='\"')
                String = !String ;
            prev = ch ;
        }

    fclose(fp) ;
    fclose(np) ;
    remove(arr[1]) ;
    rename( "temp.txt" , arr[1] ) ;
    return 0 ;
}


texts: Bash script to symlink configuration files from git repo into home directory

texts:
My goals are to:

Do it automatically (without adding a line to my script every time I add or change the location of a config file)
The files in the git repo folder should not be hidden, but the symlinks in my home directory should
Existing files of the same name should be overwritten, but not directories. For example if I have config/conf.txt in my dotfiles repo, it shouldn't overwrite the entire ~/.config folder, but simply add a link to conf.txt inside ~/.config.

My current solution does these, but it could probably be done better:

DOTFILES_DIR="$HOME/dotfiles"

echo -n Creating symlinks...

shopt -s extglob nocaseglob

# Create hidden symlinks, hard link them to $HOME, rm old symlinks
for dotfile in $DOTFILES_DIR/!(readme*|${0##*/}); do
    hidden="$DOTFILES_DIR/.${dotfile##*/}"
    cp -asf "$dotfile" "$hidden"
    cp -alf "$hidden" "$HOME"
    rm -r "$hidden"
done

echo done

I think I should be able to copy the files directly to the home directory, but I had some trouble getting that to work right if a destination folder already existed.

Edit: I was able to eliminate the second for loop. Much better. There may still be a better way, though.


texts: Is there a way to avoid calling the document with jQuery on click?

texts:
I have taken a look at several answered questions on Stack Overflow about jQuery's new (since 1.9.1 upgrade)

.on('click','',function(){}

and that you need to delegate. However, in each one, it just provides the solution to fix the issue, but I need a bit more finest or an explanation to why it must be done like that.

Here is my code segment which I have already made it working.  My question will follow after the code.

jQuery(document).ready(function($){

    /* Shopping Cart Items */
    $(".header-shopping-cart div .toggle-items").on('click', function(){ // Show/Hide Shopping Cart Items
        if ($(".header-shopping-cart-items").css("display") == "none" && $("#items-amount").html() > 0) {
            $(".header-shopping-cart-items").fadeIn();
            $(this).find("i").removeClass("icon-angle-right").addClass("icon-angle-down");
        }
        else {
            $(".header-shopping-cart-items").fadeOut();
            $(this).find("i").removeClass("icon-angle-down").addClass("icon-angle-right");
        }
        return false;
    });

    $(document).on('click','.header-shopping-cart-items .item a', function(){
        var amount = $("#items-amount").html();
        if (amount > 0) {
            $("#items-amount").html(amount - 1); // Dicrease the amount of SC items
            $(this).parent().slideUp(); // Hide this item
            if (amount - 1 == 0) {
                $(".header-shopping-cart-items").fadeOut(); // When there's no any items in the cart, hide the items block
                $(".header-shopping-cart div .toggle-items i").fadeOut();
            }
        }
        return false;
    });
});

The short end of the code basically have two purpose: one the toggle makes it so that when press a drop down opens up.

The second one (which is where I have confusion on) enables a way to remove (or delete) a row from the drop down.

My questions:

When the HTML used to be static, I can do both the operation of toggling the HTML and the deletion of the row without issues. However when I now append the row, I could no longer remove the row by hitting the second on('click'). So I had to modify it with $(document) and then shift the .header-shopping-cart-items .item a into the delegation position. I don't know why it is that.
Must I use the document as the starting point of the delegation? Is it because these rows are not statically there at first and were actually generated later via an event.
If I want to omit

jQuery(document).ready(function($){
//code
});

I should have done IIFE instead - however is there a "trap" in doing so. Trap as in must I start changing the code structure around in order to achieve the same effect.

Please note that I read this in order to fix my JavaScript up to achieve the current code which works.


texts:
I written my own calculator script in javascript! It is a basic one, but works really well. I am just wondering if there is any way to make this script more efficient & clean. On first look, I feel like I did some redundant stuff in it, however I am a beginner and in no right to judge the code on my own.

window.onload = () => {
  const calculator = document.querySelector('form[name = "calculator"]')
  const btns = document.querySelectorAll(`form[name = "calculator"] table tr input[type = "button"]`)
  btns.forEach((button) => {
    if(button.value != 'c' && button.value != '='){
      button.addEventListener('click', () => {
        calculator.display.value += button.value
      })
    } else {
      if (button.value == 'c') {
        button.addEventListener('click', () => {
          calculator.display.value = '';
        })
      } else if (button.value == '=') {
        button.addEventListener('click', () => {
          calculator.display.value = eval(calculator.display.value);
        })
      }
    }
  })
}
<!DOCTYPE html>

      <form name = "calculator">

            <input type = "text" name = "display" id = "display" disabled>

            <input type = "button" name = "one" value = "1">
            <input type = "button" name = "two" value = "2">
            <input type = "button" name = "three" value = "3">
            <input type = "button" name = "plus" value = "+">

            <input type = "button" name = "four" value = "4">
            <input type = "button" name = "five" value = "5">
            <input type = "button" name = "six" value = "6">
            <input type = "button" name = "minus" value = "-">

            <input type = "button" name = "seven" value = "7">
            <input type = "button" name = "eight" value = "8">
            <input type = "button" name = "nine" value = "9">
            <input type = "button" name = "multiplicatio" value = "*">

            <input type = "button" name = "clear" value = "c">
            <input type = "button" name = "0" value = "0">
            <input type = "button" name = "equal" value = "=">
            <input type = "button" name = "division" value = "/">

      </form>

Are there any ways to make this script "better"? Thanks for the help.


texts:
I need some help with my register and log in functions. I'm not sure if I have understood bcrypt correctly either. I'm doubting the security of it, what do you think?

Is this good, or are there any changes I should make? Have I missed anything?

For the database table users, I created (ID, username and password[char:60]):

function loginAccount() {
    global $connect;

    $username = mysqli_real_escape_string($connect, $_POST['username']);
    $password = mysqli_real_escape_string($connect, $_POST['password']);

    $existingHashFromDb = "";
    if(!isset($existingHashFromDb)) {
        // existing password from database is not set
    } else {

        $login_sql = "SELECT password FROM users WHERE username = '".$username."'";
        $login_result = mysqli_query($connect, $login_sql);

        if($login_result) {
            while($row = mysqli_fetch_assoc($login_result)) {
                $existingHashFromDb = $row['password'];
            }

            # Check if the hash of the entered login password, matches the stored hash.
            # The salt and the cost factor will be extracted from $existingHashFromDb.
            $isPasswordCorrect = password_verify($password, $existingHashFromDb);

            if($isPasswordCorrect) {
                // you are logged in
                echo "
Welcome " . ucfirst($username) . "
";

                // logout?
                echo "
Logout
";
            } else {
                echo "
Password did not match.
";
            }
        } else {
            // query failed
            mysqli_free_result($login_result);
            mysqli_close($connect);
        }

    }

}

function registerAccount() {
    global $connect;

    $username       = mysqli_real_escape_string($connect, $_POST['username']);
    $password       = mysqli_real_escape_string($connect, $_POST['password']);
    $password_again = mysqli_real_escape_string($connect, $_POST['password_again']);

    # This way you can define a cost factor (by default 10). Increasing the
    # cost factor by 1, doubles the needed time to calculate the hash value.
    $hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT, array("cost" => 11));

    # See if the username already exists in the database
    $userexist_query = "SELECT username FROM users WHERE username = '".$username."'";
    $userexist_result = mysqli_query($connect, $userexist_query);

    if($userexist_result) {
        if(mysqli_num_rows($userexist_result) >= 1) {
            echo "
Username already exists!
";
        } else {
            # See if the password and password_again is matching.
            if($password == $password_again) {
                $register_query  = "INSERT INTO users (username, password) VALUES ('$username', '$hashToStoreInDb')";
                $register_result = mysqli_query($connect, $register_query);

                if($register_result) {
                    echo "
" . ucfirst($username) . " has been created!
 Password: {$hashToStoreInDb}
";
                } else {
                    // query failed
                    mysqli_free_result($register_result);
                    mysqli_close($connect);
                }
            } else {
                echo "
Password does not match!
";
            }
        }
    } else {
        // query failed
        mysqli_free_result($userexist_result);
        mysqli_close($connect);
    }

}


texts:
I use the following code to add tree item to vscode extension, Im getting the data and build the tree according to the entries I got, the code works.
As I new to typescript I appreciate your feedback's, if the code looks good let me know either :) thanks

export class TaskTreeDataProvider implements vscode.TreeDataProvider<TreeItem> {

private _onDidChangeTreeData: vscode.EventEmitter<TreeItem | null> = new vscode.EventEmitter<TreeItem | null>();
  readonly onDidChangeTreeData: vscode.Event<TreeItem | null> = this
    ._onDidChangeTreeData.event;

  private eeake: Promise<TreeItem[]> | undefined = undefined;
  private autoRefresh: boolean = true;

  constructor(private context: vscode.ExtensionContext) {
    this.autoRefresh = vscode.workspace
      .getConfiguration(“sView")
      .get("autorefresh");

    let filePath = this.fileName;
    let fileWatcher = vscode.workspace.createFileSystemWatcher(filePath);
    fileWatcher.onDidChange(() => (this.eeake = this.getChildren()), this.refresh());
  }

  refresh(): void {
    this._onDidChangeTreeData.fire();
  }

  public async getChildren(task?: TreeItem): Promise<TreeItem[]> {
    let tasks = await vscode.tasks
      .fetchTasks({ type: “run” })
      .then(function (value) {
        return value;
      });

    let entry: TreeItem[] = [];
    if (tasks.length !== 0) {
      for (var i = 0; i < tasks.length; i++) {
        entry[i] = new TreeItem(
          tasks[i].definition.type,
          tasks[i].name,
          {
            command: “sView.executeTask",
            title: "Execute",
            arguments: [tasks[i]]
          }
        );
      }
    }
    return entry;
  }

  getTreeItem(task: TreeItem): vscode.TreeItem {
    return task;
  }
}

class TreeItem extends vscode.TreeItem {
  type: string;
  constructor(
    type: string,
    label: string,
    collapsibleState: vscode.TreeItemCollapsibleState,
    command?: vscode.Command
  ) {
    super(label, collapsibleState);
    this.type = type;
    this.command = command;
    this.iconPath = getIcon();
  }
```


texts:
I have a simple quantity display function that runs for every product displayed in our catalog.  The MaxQtyDisplay value is set in our web.config file.  Part of me thinks the function is as streamlined as possible and part of me thinks it can be improved upon somewhere.  Because this function is called many, many times in our web application I would like it be optimized as best it could.

What could be done to improve it?

Private Shared Function CalculateQtyDisplay(ByVal x As Double, ByVal y As Double) As Double
    Dim q As Double = x - y
    If q > 0 And q <= My.Settings.MaxQtyDisplay Then
        Return q
    ElseIf q > My.Settings.MaxQtyDisplay Then
        Return My.Settings.MaxQtyDisplay
    Else
        Return 0
    End If
End Function


texts: jenkins deployment making the build very slow

texts:
I am new to Jenkins. I am doing a build through Jenkins, but the build is very slow. Is there any way I can speed it up?

#!/usr/bin/env groovy
@Library('cplib') _

import com.sports.paas.cplib.helpers.Build
import com.sports.paas.cplib.helpers.Workspace
import com.sports.paas.cplib.utils.Openshift

def bld = new Build()
def wspace = new Workspace()
def osh = new Openshift()
def appReleaseTag = ""

def NODE_HOME = "${JENKINS_HOME_SLAVE}/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/Node_6.11.1"
def projectName = "player"
def appName = "ball"
def appOcpConfigBranch = "master"

// ########################################################################################
// PIPELINE WORKFLOW
// ########################################################################################
pipeline {

    agent { node('nodejs')}
    tools {
        nodejs 'nodejs-8.11.2'
    }

    options {
        disableConcurrentBuilds()
        buildDiscarder(logRotator(numToKeepStr: '30', daysToKeepStr: '15'))
        skipDefaultCheckout(true)
        timestamps()
        skipStagesAfterUnstable()
    }

    parameters {
        choice (
            name : 'DEPLOY_ENVIRONMENT',
            choices: ' \nunit\ntest\nstage',
            description: '[Required] Select the location to deploy.'
        )
    }

    stages {

        stage('Prepare') {
            steps {
                script {
                    log.info "Explicit scm checkout ..."
                    checkout scm
                    wspace.init()
                // wspace.checkoutAppOcpConfig(appName, appOcpConfigBranch)
                    appReleaseTag = wspace.getBuildProperty("version") + "." + env.BUILD_NUMBER
                }
            }
        }

        stage('Build Artifacts') {
            steps {
                script {
                    sh """
                        echo "Building artifacts ..."
                        export PATH=$PATH:$NODE_HOME/bin;
                        echo "Running node build ..."
                        # Please build your application using npm or yarn. Application build
                        #       using yarn has been tested for a 35% faster execution when compared to yarn.
                        #npm install --no-optional --production --silent
                        npm install

                        echo "@@@ NPM RUN PROD ( BUILD )"
                        npm run build
                        #yarn
                    """
                }
                prepareForBuildImage()
            }
        }

        stage('Build Image') {
            steps {
                script {
                    if(!wspace.releaseVersionExists()) {
                        appReleaseTag = osh.buildAppImage(appName, appReleaseTag)
                    } else {
                        appReleaseTag = env.RELEASE_VERSION
                    }
                }
            }
        }

        stage('Deploy Unit') {
            steps {
                script {
                    envName=env.DEPLOY_ENVIRONMENT
                    osh.deploy(projectName+"-"+envName, appName, envName,appReleaseTag)
                }
            }
        }

    } //stages
} // pipeline

def prepareForBuildImage() {
    sh '''
        echo "Preparing Image contents ..."
        rm -rf tmp
        mkdir -p tmp
        chmod -R 777 tmp
        echo "Compressing files ..."
        tar cvzf tmp.tar.gz client server *.json node_modules index.js build.properties README.md
        cp -pr tmp.tar.gz tmp/
        echo "Decompressing files ..."
        cd tmp
        tar xvzf tmp.tar.gz
        rm -fr tmp.tar.gz
        cd ..
        echo "Displaying deployment artifacts ..."
        ls -Rlt tmp/ --ignore=node_modules
    '''
}


texts:
Addressed both issues in this codereview post.

Fixed the indexing issue and the call mechanism of the function expression.

Looking for perfect code.  Hope this is the last rev.

    /***************************************************************************************************
    **ALGORITHMS
    ***************************************************************************************************/

    // self used to hold client or server side global
    (function () {

        "use strict";

        // holds (Pub)lic properties
        var Pub = {},

            // holds (Priv)ate properties
            Priv = {},

            // holds "imported" library properties
            $A;

        (function manageGlobal() {

            // Priv.g holds the single global variable, used to hold all packages
            Priv.g = '$A';

            if (this[Priv.g] && this[Priv.g].pack && this[Priv.g].pack.utility) {
                this[Priv.g].pack.algo = true;
                $A = this[Priv.g];
            } else {
                throw new Error("algo requires utility module");
            }
        }());

        Pub.swap = function (arr, i, j) {
            var temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        };

        // checks to see if sorted
        Pub.isSorted = function (arr) {
            var i,
                length = arr.length;
            for (i = 1; i < length; i++) {
                if (arr[i] < arr[i - 1]) {
                    return false;
                }
            }
            return true;
        };

        // repeatedly orders two items ( a bubble ) at a time
        Pub.bubbleSort = function (arr) {
            var index_outer,
                index_inner,
                swapped = false,
                length = arr.length;
            for (index_outer = 0; index_outer < length; index_outer++) {
                swapped = false;
                for (index_inner = 0; index_inner < length - index_outer; index_inner++) {
                    if (arr[index_inner] > arr[index_inner + 1]) {
                        Pub.swap(arr, index_inner, index_inner + 1);
                        swapped = true;
                    }
                }
                if (!swapped) {
                    break;
                }
            }
            return arr;
        };

        // repeatedly finds minimum and places it the next index
        Pub.selectionSort = function (arr) {
            var index_outer,
                index_inner,
                index_min,
                length = arr.length;
            for (index_outer = 0; index_outer < length; index_outer++) {
                index_min = index_outer;
                for (index_inner = index_outer + 1; index_inner < length; index_inner++) {
                    if (arr[index_inner] < arr[index_min]) {
                        index_min = index_inner;
                    }
                }
                if (index_outer !== index_min) {
                    Pub.swap(arr, index_outer, index_min);
                }
            }
            return arr;
        };

        // repeatedly places next item in correct spot using a "shift"
        Pub.insertionSort = function (arr) {
            var index_outer,
                index_inner,
                value,
                length = arr.length;
            for (index_outer = 1; index_outer < length; index_outer++) {
                value = arr[index_outer];

                // JavaScript optimization - index_inner >=0 is removed
                // as the array index will return undefined for a negative index
                for (index_inner = index_outer - 1; (arr[index_inner] > value);
                        index_inner--) {
                    arr[index_inner + 1] = arr[index_inner];
                }
                arr[index_inner + 1] = value;
            }
            return arr;
        };

        // module complete, release to outer scope
        this[Priv.g] = $A.extendSafe(this[Priv.g], Pub);
    }).call(this);


texts: Rails controller action methods corresponding to static web pages

texts:
One of my rails controllers is horribly overcrowded with a bunch of methods that link to static web pages.

Controller

def adventure
end

def cooking
end

def dancing
end

def programming
end

def reading
end

def running
end

def sports
end

def writing
end

For each of the above actions I have seperate view files and routes defined for them.

View Files

adventure.html.erb
cooking.html.erb
dancing.html.erb
programming.html.erb
reading.html.erb
running.html.erb
sports.html.erb
writing.html.erb

Routes

match '/adventure', to: 'pages#adventure', via: 'get'
match '/cooking', to: 'pages#fighting', via: 'get'
match '/dancing', to: 'pages#first_person_shooter', via: 'get'

match '/programming', to: 'pages#programming', via: 'get'
match '/reading', to: 'pages#reading', via: 'get'
match '/running', to: 'pages#running', via: 'get'
match '/sports', to: 'pages#sports', via: 'get'
match '/writing', to: 'pages#writing', via: 'get'

It is quite embarrassing to have code that horrible. Is there any way I can optimize that?


texts: PowerShell script to read line by line large CSV files

texts:
I am managing large CSV files (files ranging from 750 Mb to 10+ Gb), parsing their data into PSObjects, then processing each of those objects based on what is required.

I wrote the following script to churn through these files line by line, filter based on one of the data fields, then close the file.  The script works but I feel that it could be faster.  For instance, it took 4.5 hours to parse a 389k line csv file. Taking that filesize and timeline, it would take over two and a half days to work through just the sorting and filtering of the data!

Before anyone suggests "use a database!", I'm 100% with you and have started the RFC for adding a database server to our network.  Unfortunately our CAB only meets quarterly and this wasn't deemed an emergency.  So, I'm left without a database solution for at least 2-3 months.

Anyhow, here is the code:

[void][reflection.assembly]::LoadWithPartialName("Microsoft.VisualBasic")

$source = Get-FileName "C:\users\$env.username\Downloads"

$reader = New-Object Microsoft.VisualBasic.FileIO.TextFieldParser $source

$reader.SetDelimiters(",")

While(!$reader.EndOfData)
{
    $line = $reader.ReadFields()

    $details = [ordered]@{
                            "Plugin ID" = $line[0]
                            CVSS = $line[2]
                            Risk = $line[3]
                            Host = $line[4]
                            Protocol = $line[5]
                            Port = $line[6]
                            Name = $line[7]
                            Description = $line[9]
                            Solution = $line[10]
                            "Plugin Output" = $line[12]
                         }

    $pluginID = $line[0]
    $risk = $line[3]

    if ($risk -eq "Critical" -or $risk -eq "High" -or $risk -eq "Medium" -or $risk -eq "Low")
    {
        $allVulns += New-Object PSObject -Property $details
    }
    else
    {
        # Filters data into objects based on their plugin ID
        Switch ($pluginID)
        {
            11936 # OS Identification
            {
                $11936 += New-Object PSObject -Property $details
                break
            }
            14272 # Open Ports
            {
                $14272 += New-Object PSObject -Property $details
                break
            }
            20811 # Software Inventory
            {
                $20811 += New-Object PSObject -Property $details
                break
            }
            54615 # Device Type
            {
                $54615 += New-Object PSObject -Property $details
                break
            }
            66334 # Missing OS Patches
            {
                $66334 += New-Object PSObject -Property $details
                break
            }
        }
    }
}

# Close the read file
$reader.Close()

Is there a faster, more efficient way for this code to execute?

Thanks!

EDIT: Some sample data by request! This is two of the plugins I'm parsing that don't have endless amounts of Plugin Output data.

Plugin ID,CVE,CVSS,Risk,Host,Protocol,Port,Name,Synopsis,Description,Solution,See Also,Plugin Output
11936,,,None,GCAB-L7-449096R,tcp,0,OS Identification,It is possible to guess the remote operating system.,"Using a combination of remote probes (e.g., TCP/IP, SMB, HTTP, NTP,
SNMP, etc.), it is possible to guess the name of the remote operating
system in use. It is also possible sometimes to guess the version of
the operating system.",n/a,,"
Remote operating system : Microsoft Windows 7 Enterprise Service Pack 1
Confidence level : 100
Method : SMB

The remote host is running Microsoft Windows 7 Enterprise Service Pack 1"
14272,,,None,GCAB-L7-449096R,udp,53125,netstat portscanner (SSH),Remote open ports are enumerated via SSH.,"This plugin runs 'netstat' on the remote machine to enumerate open
ports.

See the section 'plugins options' about configuring this plugin.",n/a,https://en.wikipedia.org/wiki/Netstat,Port 53125/udp was found to be open


texts: Computing the relative magnitude of the values in one double array to another

texts:
An interview question I received:

  You are given two unsorted lists of positive doubles

  x contains the results from experiment 1
  y which contains the results from experiment 2.

  All results from the second experiment y are improvements over x
  by i percent, where i is an integer. That is to say that given a
  result from x, the corresponding result from y will be an i
  percent improvement.

  However, the lists are not parallel; that  is to say x[0] does not
  necessarily correspond to y[0]. Find the value of i.

  Note: must be written in Java 7

  Some examples

  Inputs:

y = [1.0]
x = [1.0]

  Output:

0

  Inputs:

y = [2.2999999999999998, 15.0, 102.40000000000001, 3486.8000000000002]
x = [23.0, 150.0, 1024.0, 34868.0]

  Output:

90

  Inputs:

y = [23, 11.1, 50.4]
x = [22.2, 46, 100.8]

  Output:

50

  Note in the last case where 46 -> 23 and 22.2 -> 11.1 but the
  index of 46 is not the index of 23, etc.

My Solution

import java.util.Arrays;

//Time complexity: O(n)
//Space complexity: O(1)
public class Solution{
    public static int solution(double[] secondRun, double[] firstRun) {

        Double firstRunMax = findMax(firstRun),
               secondRunMax = findMax(secondRun);

        return (int)((1.0-secondRunMax/firstRunMax)*100);
    }

    private static double findMax(double[] array){
        double max = -Double.MAX_VALUE;

        for(double d : array){
            if(d > max){
                max = d;
            }
        }

        return max;
    }
}

Strengths: Very simple, as efficient as possible (I think?), ignores most of the data

Weakness: the return line is a little convoluted. Perhaps there is a better way to simplify it also. Also I thought I would be able to find a simple Arrays.Max method or something in Java, but I didnt see any during a quick glance.


texts: Simple wrapper to use IEnumerable as a producer in a producer-consumer pattern

texts:
I have a relatively simple problem: I have an IEnumerable<T>, which takes considerable time to yield each term. This is then used by another piece of code, which takes considerable (but not identical) time to process each term.

As I understand it, this is a classic producer-consumer scenario, so I'm choosing to use a BlockingCollection<T> so that I can produce and consume concurrently.

To support this, I have a simple wrapper:

class EnumerableProducer<T>
{
    public readonly BlockingCollection<T> ProducerCollection;

    public EnumerableProducer(IEnumerable<T> source)
    {
        ProducerCollection = new BlockingCollection<T>();
        AddItemsToBlockingCollection(ProducerCollection, source).Start();
    }

    private static Task AddItemsToBlockingCollection(BlockingCollection<T> collection, IEnumerable<T> source)
    {
        return new Task(() =>
        {
            foreach (var item in source)
            {
                collection.Add(item);
            }
            collection.CompleteAdding();
        });
    }
}

Any code having an IEnumerable<T> and wanting to use it as a producer passes it to the constructor, then accesses it through the ProducerCollection.

Interested in a general review, but in particular:

Is this the simplest/most idiomatic way to do achieve the overall goal?
Any comments/suggestions on naming.
Extensibility (e.g. adding cancellation or parallelizing the enumeration of the source) probably fall under YAGNI for me at the moment, but if there are alternative designs which would make this kind of extension in general easier to implement, I would be interested.


texts:
Is this example the correct way of writing an Async controller end point in Scala using Play 2.3?

def submitResponse(qkey:String) = CorsAction.async(parse.json){
    req =>
      val json = req.body
      val channel = json.\("section").as[String]

      val currentQuestionKey = Cache.getAs[String](channel).getOrElse("N_A")
       if(!currentQuestionKey.equals(qkey)){
        scala.concurrent.Future{BadRequest("Inactive or Invalid Key")}
      }
      else {

        val futureResponse = scala.concurrent.Future {
          responseService.create(qkey,channel)
        }
        futureResponse.map{response =>
          response match {
            case Failure(x) => { BadRequest("Duplicate " + qkey)}
            case Success(storedResponse) => { Ok(storedResponse)}
          }
        }

      }

  }


texts: Getting JSON and putting it in a table using jQuery and PHP

texts:
How can I improve this code?

jQuery:

$.ajax({
   url: "get_attributes.php",
   type: "post",
   datatype: "json",
   data: {
       wtype: red_type
   },
   success: function (data) {
       var toAppend = '';
       if (typeof data === "object") {
           toAppend += "
";
           toAppend += "
	Type:	" + data['type'] + "
";
           toAppend += "
Health:	" + data['health'] + "
";
           toAppend += "
Attack:	" + data['attack'] + "
";
           toAppend += "
Defense:	" + data['defense'] + "
";
           toAppend += "
Speed:	" + data['speed'] + "
";
           toAppend += "
Evade:	" + data['evade'] + "
";
           toAppend += "
Special:	" + data['special'] + "
";
           toAppend += "
";
           $("tbody").remove();
           $("#red_form table").append(toAppend);
       }
   }
   });

PHP:

    <?php
header("Content-Type: application/json");

$wtype = $_POST['wtype'];

$attributes = array();

if($wtype == 'Ninja'){
    $attributes['type'] = 'Ninja';
    $attributes['health'] = '40-60';
    $attributes['attack'] = '60-70';
    $attributes['defense'] = '20-30';
    $attributes['speed'] = '90-100';
    $attributes['evade'] = '0.3-0.5';
    $attributes['special'] = 'There is a 5% chance of 2x attack';
}
else if($wtype == 'Samurai'){
    $attributes['type'] = 'Samurai';
    $attributes['health'] = '60-100';
    $attributes['attack'] = '75-80';
    $attributes['defense'] = '35-40';
    $attributes['speed'] = '60-80';
    $attributes['evade'] = '0.3-0.4';
    $attributes['special'] = '10% chance of restoring +10 health when evade is successful';
}
else if($wtype == 'Brawler'){
    $attributes['type'] = 'Brawler';
    $attributes['health'] = '90-100';
    $attributes['attack'] = '65-75';
    $attributes['defense'] = '40-50';
    $attributes['speed'] = '40-65';
    $attributes['evade'] = '0.3-0.35';
    $attributes['special'] = 'increased +10 defense when health is below 20%';
}

echo json_encode($attributes);
?>


texts: Checking if two strings are anagrams in Python

texts:
The code written in Python 3.6 mostly using Python's built in functions sorted and len. First I'm checking for the edge case that the two given strings are not of the same length obviously. Then I'm sorting the strings and comparing if their sorted value are equal to each other with a boolean expression. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Just for the sake of practising Big-O this function runs in \$O(1)\$ constant complexity time because regardless of the strings given the function will always return a Boolean value. Is this correct? I realized my assumption was not correct since the function will run in the time complexity of the sorted built-in function which is \$nlog(n)\$.
If you were an interviewer would you prefer the candidate to not use Python's built in functions and to resort to a more manual way of solving the problem?

def is_anagram(string1, string2):

    while len(string1) == len(string2):

    # Testing sorted values equality
        if sorted(string1) == sorted(string2):
            return True
        return False

    return 'The strings are not anagrams they have differing lengths'

print(is_anagram('cat', 'cra'))


texts: To send the email on some given date and time

texts:
I am making a PHP script which fetches the data of the emails whose sending date and time has been reached and then send emails to those records. I am following the steps below and integrating it in an API, that is.

GitHub code

Steps:

Get the communication records whose time has reached.
Run the loop of above and get the email addresses.
Run the loop of email addresses and send emails.

This is my PHP code:

<?php
include('iSDK/src/isdk.php');
$myApp = new iSDK();
// Test Connnection
if ($myApp->cfgCon("connectionName")) {
    echo "Connected...";
} else {
    echo "Not Connected...";
}
$query = mysql_query('SELECT * FROM `emails` WHERE `senddate` <= NOW()');
while ($row = mysql_fetch_assoc($query)) {
    $conDat = array('Email' => $row['email']);
    $conID = $myApp->addCon($conDat);
    $clist = array($conID);
    $email = $myApp->sendEmail($clist, 'kamranasadi431@gmail.com', '~Contact.Email~',
        'ccAddresses', 'bccAddresses', 'contentType', 'JK', 'htmlBody', 'txtBody');
}
?>

What changes should be made in it?


texts: Naive php web hook endpoint for use in a production environment

texts:
Below is the WebHook endpoint in its entirety.  I have five seconds to acknowledge if the payload is correctly formed.  After that, the payload is inserted into a queue for processing.
Importantly, it works, but it feels naive outside a Class and without any exception handling or error checking beyond the signature match. It does however, achieve exactly what I need.
Should for example, $rawPayload = file_get_contents("php://input"); and $authKey = $_SERVER['HTTP_SIGNATURE']; be inside a try catch block?
Alternatively, should it be threaded in case the endpoint is flooded?
<?php

namespace NJIS\Helpers;

use NJIS\Helpers\XeroWebHookHandler;

$key = $_ENV['XERO_WEBHOOK_KEY'];
$rawPayload = file_get_contents("php://input");
$signature = base64_encode(hash_hmac('sha256', $rawPayload, $key, true));
$authKey = $_SERVER['HTTP_SIGNATURE'];

if($signature === $authKey)
{
    http_response_code(200);
    XeroWebHookHandler::insertPayloadIntoDatabase($rawPayload);
}
else
{
    http_response_code(401);
}


texts: Append to compressed tar file with performance

texts:
As you might know, Python's tarfile does not have the ability to append to the files that compressed with e.g. gz or bz2. I tried to implement this functionality which works fine but operates slowly. The following function accepts a string or bytes object and appends it as a file to an existing tarfile. I'm not sure if this code has the best performance, and it may have issues. I also tried writing files to memory instead of to a temporary directory, but this didn't impact performance.
import os
import tarfile
import tempfile
import time
from pathlib import Path

def append_tar_file(buffer, file_name, output_path, replace=True):
    """
    append a buffer to an existing tar file
    """
    # extract files
    # check for existing file and overwrite if need to
    # compress files
    if not os.path.isfile(output_path):
        return
    buffer = buffer.encode("utf-8") if isinstance(buffer, str) else buffer

    with tempfile.TemporaryDirectory() as tempdir:
        tempdirp = Path(tempdir)
        with tarfile.open(output_path, "r:bz2") as tar:
            try:
                tar.extractall(os.path.abspath(tempdirp))
            except Exception as err:   #tar file is empty
                print(err)
        buffer_path = os.path.join(tempdir, os.path.basename(file_name))
        if replace or (buffer_path not in list(os.path.abspath(f) for f in tempdirp.iterdir())):
            with open(buffer_path, "wb") as f:
                f.write(buffer)

        with tarfile.open(output_path, "w:bz2") as tar:
            for file in tempdirp.iterdir():
                try:
                    tar.add(file, arcname=os.path.basename(os.path.normpath(file)))
                except Exception as err:
                    print(err)

if __name__ == "__main__":
    path = "./test.tar.gz"
    buffer = "Test String"
    filename = "somefile"
    for i in range(1, 100):
        print(time.time())
        append_tar_file(buffer, filename+str(i), path)


texts:
I'm a clean guy when I code and I don't like typing the same thing over and over again, so I will try to be simple.

In my Laravel project I have two routes for every major page on the website, for example:

Route::get('/artigos','GlobalController@gestorArtigos');
Route::get('/artigos/{id}','GlobalController@gestorArtigos');

When it receives an ID in the controller:

 public function gestorArtigos(Request $request , $id = '') {
    $MyOutput = view('artigos.art_gestor_base');
    if($id){
        return $MyOutput->with('id',$id);
    }
    return $MyOutput->with('request',$request);
}

This is completely fine and I have no intention of changing this. What does bother me is the fact that I have to repeat the same function every single time I create a new page. The only differences are the function name and the value of $MyOutput, because the views change.

I need help to compact the function to a 'global' one so I don't have to repeat the code, just call it.


texts: Getting path array for given value in nested Object

texts:
I'm wondering how I can improve my getPath function (I found it on SO and adjusted it to my needs - biggest change was returning an array, used to be a string).

It takes an object and a value as inputs and returns an array of object keys for the first matching value they find, otherwise false.

My focus isn't primarily the speed.
Focus is: As short but at the same time as easy to understand as possible without having to write many comments.

I'm using JS before ECMAScript 6

var nestedObj = {
  "rrr": {
    "ddd": {
      "aa    bbbb": {
        1: 30009463
      },
      "cc    dddd.": {
        1: 30010338
      },
      "e     fff": {
        1: 30007744
      },
      "d-Pool": {
        1: 30018363,
        2: 30017133,
        3: 30013107
      },
      "e   e g": {
        1: 30011707,
        2: 30017137
      },
      "f   f.-f. (f)": {
        1: 30012329
      },
      "g": {
        1: 30011894
      }
    }
  }
};

var result = getPath(nestedObj, 30017137);
document.getElementById("result").innerHTML = result;

function getPath(obj, value, path) {
  if (typeof obj !== 'object') {
    return false;
  }
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      var t = path;
      var v = obj[key];
      //SLICE is super important, otherwise newPath will reference path
      var newPath = path ? path.slice() : [];
      newPath.push(key);
      if (v === value) {
        return newPath;
      } else if (typeof v !== 'object') {
        newPath = t;
      }
      var res = getPath(v, value, newPath);
      if (res) {
        return res;
      }
    }
  }
  return false;
}

I wrote that one comment as a reminder to myself because I spent too much time wondering why the function didn't work before figuring this out.


texts:
I have been working through the Cryptopals challenges in Ocaml. My interest in Ocaml is to better learn functional programming techniques and effective usage of the type system.

Set 1 Challenge 4 says 'One of the 60-character strings in this file has been encrypted by single-character XOR. Find it.'

My code finds the correct string. I tried using user-defined types (e.g. xor_input, xor_output) to avoid passing around lots of string types that could easily be muddled. However, I am not sure of what is an appropriate level of type annotation. For example:

is there any merit in make_ranking specifying a return type of score if it ends in |> Score? My understanding of Haskell is that I could use the function's type annotation to specify that it returns a Score and the int returned from the fold would automatically be wrapped in a score type - is there something similar in Ocaml? |> Score seems a cumbersome way to specify the return type.
I was also unsure how to convert to and from a user-defined type and its unwrapped value (e.g. score and int). My approach in sort_results and output (destructuring) seems inelegant to me.
in sort_results I destructure the arguments to get the scores. Does this not mean that any type with a score field will be accepted?

(Note that Hexx is a module I wrote to convert a base64 encoded string to a hex string. Assume the input is a file containing a list of strings.)

open Core

let english = "etaoin srhldcumfpgwybvkxjqzETAOINSRHLDCUMFPGWYBVKXJQZ0123456789.?!"

type score = Score of int
type xor_input = Xor_input of string
type xor_output = Xor_output of string
type result =
  {
    test_char : char;
    score : score;
    xor_input : xor_input;
    xor_output : xor_output;
  }

let xor c (Xor_input input) : xor_output =
  String.map input ~f:(fun l -> int_of_char l |> (lxor) c |> char_of_int) |> Xor_output

let make_ranking (Xor_output str) : score =
  String.fold str ~init:0 ~f:(fun total c ->
      total + match String.index english c with
              | Some v -> v
              | None -> 100 (* arbitary value for non-letters *)
    ) |> Score

let make_result (input : xor_input) c : result =
  let output = xor c input in
  { test_char = char_of_int c; score = make_ranking output; xor_input = input; xor_output = output }

let sort_results { score = first; _ } { score = second; _ } =
  let (Score first_val) = first in
  let (Score second_val) = second in
  first_val - second_val

let find_best_match results : result =
  let best = List.sort ~cmp:sort_results results |> List.hd in
  match best with
  | Some x -> x
  | None -> failwith "No best result found"

let xor_line line =
  let decoded = Hexx.decode line in
  List.range 0 255
  |> List.map ~f:(make_result (Xor_input decoded))
  |> find_best_match

let output {test_char; score; xor_input; xor_output} =
  let (Score s) = score in
  let (Xor_input input) = xor_input in
  let (Xor_output out) = xor_output in
  fprintf stdout "Char: %c, Score: %d, Original: %s, Output: %s\n" test_char s input out

let () =
  In_channel.read_lines "4.txt"
  |> List.map ~f:xor_line
  |> find_best_match
  |> output


texts:
I want to determine the number of distinct subarrays that can form having at most a given number of odd elements. Two subarrays are distinct if they differ at even one position. The subarray is a contiguous position of an array. Please give some suggestions to improve the time and space complexity.
Exp1:
Input: nums = [1, 2, 3, 4], k = 1
Output: 8
Explanation: [1], [2], [3], [4], [1, 2], [2, 3], [3, 4], [2, 3, 4]

Exp2:
Input: nums = [3, 2, 3, 4], k = 1
Output: 7
Explanation: [3], [2], [4], [3, 2], [2, 3], [3, 4], [2, 3, 4]
Note we did not count [3, 2, 3] since it has more than k odd elements.

Exp3:
Input: nums = [3, 2, 3, 2], k = 1
Output: 5
Explanation: [3], [2], [3, 2], [2, 3], [2, 3, 2]
[3], [2], [3, 2] - duplicates
[3, 2, 3], [3, 2, 3, 2] - more than k odd elements

class result {

    static int numberOfSubarrays(int[] numbers, int k) {
        if(k == 0) return 0;

        boolean [] IsOdd = new boolean [numbers.length];

        for(int i = 0; i < numbers.length; i++){
            IsOdd[i] = numbers[i] %2 != 0;
        }

        HashSet<String> subs = new HashSet<String>();

        for(int i = 0; i < numbers.length; i++){
            StringBuilder sb = new StringBuilder();
            int oddCount = 0;

            for(int j = i; j < numbers.length; j++){
                if(IsOdd[j]){
                    oddCount++;
                    if(oddCount > k){
                        break;
                    }
                }
                sb.append(numbers[j] + " ");
                subs.add(sb.toString());
            }
        }
        return subs.size();
    }

}


texts:
I have a program that creates 100,000 objects of class Client, puts them into array and then goes through that array 100 times, each time assigning each Client a different random number through Rnd() function:

Main sub:

Sub start()
    Dim i As Long
    Dim j As Long

    Dim clientsColl() As Client
    ReDim clientsColl(1 To 100000) As Client

    For j = 1 To 100000
        Set clientsColl(j) = New Client
        clientsColl(j).setClientName = "Client_" & j

        Application.StatusBar = "Getting client " & j

        DoEvents
    Next

    Dim tempCount As Long
    Dim clientCopy As Variant
    For i = 1 To 100
        tempCount = 0
        For Each clientCopy In clientsColl
            tempCount = tempCount + 1

            clientCopy.generateRandom

            'Application.StatusBar = "Calculating " & i & ": " & tempCount & "/" & 100000  '(1)

            'DoEvents
        Next

        Application.StatusBar = "Calculating " & i

        DoEvents
    Next

    MsgBox ("done")
End Sub

Client class:

Option Explicit

Dim clientName As String
Dim randomNumber As Double

Public Sub generateRandom()
    randomNumber = Rnd()
End Sub

Public Property Get getClientName()
    getClientName = clientName
End Property

Public Property Let setClientName(value As String)
    clientName = value
End Property

The problem is, the execution time depends on whether or not line (1) is commented out. If it's executed, the status bar gets renewed, but the execution time is very slow. If it's not executed, the program gets done really fast. Why does this happen?


texts:
So I have a query like this:

SELECT  data.Id,
        mr.mri AS Mri
FROM    ( SELECT    e.Id ,
                    dbo.GetLatestEntryId(e.Id, 2) AS G02
          FROM      dbo.Estimations AS e
        ) AS data

        LEFT JOIN
                ( SELECT  Id,
                            d.value('mri[1]', 'decimal(18,6)') AS mri
                    FROM    [dbo].[Entries]
                    CROSS APPLY [SerializedDataSet].nodes('/MechanicalRiskManager') AS DA(d)
                ) AS mr ON data.G02 = mr.Id

Xml columns that I am querying looks something like this:

<MechanicalRiskManager xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <EstimationDataEntryId>63dbfd37-41a6-48a1-b1f2-0480327408e1</EstimationDataEntryId>
  <mudWeight>0</mudWeight>
  <kdf>0</kdf>
  <mri>0</mri>
</MechanicalRiskManager>

Problem is that, it takes 4 seconds to generate 2000 rows using this exact query. Xml string besides mudWeight, kdf and mri has another 15 properties. I have another 2 left joins on xml columns (which are more or less the same complexity) and 5 left joins on other tables. [dbo].[Entries] has about 30000 rows. dbo.GetLatestEntryId returns guid of most recent record based on arguments.
In total, this query takes about 15 secs to finish, and as far as I'he read this is a bit to long. If I strip querying to xml column, then it takes no time at all.

I am pretty new to querying xml, and I would appreciate any suggestion how to optimize querying.


texts:
I've been working in C# for a while, but I'm just recently starting to force myself to use better abstracted and generic code. I recently encountered a situation where I was juggling a lot of session values on a page, so I made a wrapper class for the session to enable easy and safe get/sets of session values.

I'm not entirely sure if this is the best way to go about accomplishing what I want, but I would love some feedback on ways this code can be improved. I'm aware that it can currently only be used for string values, but I'm just using it right now for storing form values between multiple postbacks in a very complex page, so that's not a huge concern for me at the moment.

Base class

abstract public class SessionManager
{
    public List<string> PossibleKeys;

    public string GetValue(HttpSessionState pSession, string pKey)
    {
        if (this.PossibleKeys.Contains(pKey))
            return ((SessionManager)pSession[this.SessionKey]).Values[pKey].ToString();
        else
            return "";
    }

    public bool SetValue(HttpSessionState pSession, string pKey, string pValue)
    {
        if (this.PossibleKeys.Contains(pKey))
        {
            var tParameters = (SessionManager)pSession[this.SessionKey];
            tParameters.Values[pKey] = pValue.Trim();
            pSession[this.SessionKey] = tParameters;
            return true;
        }
        return false;
    }

    abstract class Keys { }

    private Dictionary<string, string> Values { get; set; }
    private string SessionKey { get; set; }
    private static string DefaultKey = "parameters";

    protected void Construct(HttpSessionState pSession, string pSessionKey = null)
    {
        if (pSessionKey.IsNullOrWhitespace())
            this.SessionKey = SessionManager.DefaultKey;
        else
            this.SessionKey = pSessionKey.Trim();

        this.Values = new Dictionary<string, string>();
        foreach (var tKey in this.PossibleKeys)
        {
            this.Values.Add(tKey, "");
        }

        SessionManager.Save(pSession, this, this.SessionKey);
    }

    private static void Save(HttpSessionState pSession, SessionManager pSelf, string pSessionKey)
    {
        pSession[pSessionKey] = pSelf;
    }
}

Implemented class on the page codebehind

public class DataManager : SessionManager
{
    public class Keys
    {
        public static string MemberID = "MemberID";
        public static string ProviderID = "ProviderID";
        public static string ReferredToID = "ReferredToID";
        public static string SpecialtyID = "SpecialtyID";
        public static string DiagnosisID = "DiagnosisID";
        public static string CPTServiceID = "CPTServiceID";
        public static string FromDate = "FromDate";
        public static string ToDate = "ToDate";
    }

    public DataManager(HttpSessionState pSession, string pSessionKey = null)
    {
        this.PossibleKeys = new List<string>()
        {
              DataManager.Keys.MemberID
            , DataManager.Keys.ProviderID
            , DataManager.Keys.ReferredToID
            , DataManager.Keys.SpecialtyID
            , DataManager.Keys.DiagnosisID
            , DataManager.Keys.CPTServiceID
            , DataManager.Keys.FromDate
            , DataManager.Keys.ToDate
        };

        base.Construct(pSession, pSessionKey);
    }
}

Actual use in the page codebehind

    public DataManager Parameters { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            this.Parameters = new DataManager(this.Session);
        }

        this.Parameters.SetValue(this.Session, DataManager.Keys.DiagnosisID, "Blah blah, your value goes here");

        string test = this.Parameters.GetValue(this.Session, DataManager.Keys.DiagnosisID);
    }


texts: Java application processing GUI input when "Done" is clicked

texts:
Right now, I've got this really ugly loop in my code that waits for a boolean to be true before the method can return. It's triggered when "Done" is clicked. I'm wondering, what is the proper way for me to delay this method's return until the button is pressed? How should I refactor this code so that it follows common practices for this?

Here is the relevant code. It is part of a much bigger application. This is the only place this happens because it is the only custom dialog box in the application. Everything else is done with JOptionPane, so it doesn't have this problem.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        PrintWriter out = new PrintWriter("textfile.txt");
        out.println(GUI.getUserInput());
        out.close();
    }
}

class GUI implements ActionListener {

    private static boolean pressed;

    public static String getUserInput() {
        pressed = false;

        JFrame frame = new JFrame();
        frame.setSize(400, 250);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Diary");
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout(4, 2));
        JLabel instructionLabel = new JLabel("What's on your mind?");
        panel.add(instructionLabel, BorderLayout.NORTH);
        JTextArea inputField = new JTextArea("", 7, 30);
        inputField.setLineWrap(true);
        inputField.setWrapStyleWord(true);
        panel.add(new JScrollPane(inputField), BorderLayout.CENTER);
        JButton done = new JButton("Done");
        done.addActionListener(new GUI());
        panel.add(done, BorderLayout.SOUTH);
        frame.add(panel);
        frame.setVisible(true);
        inputField.setCaretPosition(inputField.getText().length());

        while (!pressed) { // Wait for the "Done" button to be pressed
            // For some reason, there has to be something in this loop for it to work
            System.out.println();
        }

        frame.dispose();
        return inputField.getText();
    }

    public void actionPerformed(ActionEvent e) {
        pressed = true;
    }
}


texts:
I'm learning Ruby and I would like to know if I have used the good syntax.
My script works, but can I simplify it and make it more elegant.

puts "Hello, what is youre name?"
name = gets.chomp

puts "Are you a boy? (yes/no)"
genre = gets.chomp

if genre == ("yes")
    puts "Do you like soccer #{name}? (yes/no)"
    foot = gets.chomp

        if foot == ("yes")
            puts "And beer? (yes/no)"
            biere = gets.chomp

                if biere == ("yes")
                    puts "Nice buddy!"
                else
                    puts "Too bad #{name}! But you like soccer!"
                end
        else
            puts "You're complicated #{name}!!!"
        end
else
    puts "Do you like romantics movies?"
    film = gets.chomp
end


texts: Optimize/Refactor Javascript Unique Array function

texts:
This is one idea of implementation:

 Array.prototype.unique = function () {
  unique_array = [];
  for (var i = 0, l = this.length; i < l; i++) {
    if(unique_array.indexOf(this[i]) == -1){
      unique_array.push(this[i]);
    }
  }
  return unique_array;
 }

This version uses Object.keys which is a ECMAScript 5 only feature, as you can see on this website http://kangax.github.com/es5-compat-table/

Array.prototype.unique_e5 = function () {
  unique_object = {};
  for (var i = 0, l = this.length; i < l; i++) {
    unique_object[this[i]] = 1;
  }
  return Object.keys(unique_object);
}

And this is how is done in prototype.js
https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/array.js

 /**
   *  Array#uniq([sorted = false]) -> Array
   *  - sorted (Boolean): Whether the array has already been sorted. If `true`,
   *    a less-costly algorithm will be used.
   *
   *  Produces a duplicate-free version of an array. If no duplicates are
   *  found, the original array is returned.
   *
   *  On large arrays when `sorted` is `false`, this method has a potentially
   *  large performance cost.
   *
   *  ##### Examples
   *
   *      [1, 3, 2, 1].uniq();
   *      // -> [1, 2, 3]
   *
   *      ['A', 'a'].uniq();
   *      // -> ['A', 'a'] (because String comparison is case-sensitive)
  **/
  function uniq(sorted) {
    return this.inject([], function(array, value, index) {
      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
        array.push(value);
      return array;
    });
  }

Also not that the prototype version uses the Prototype enumerable method include, which is:

 /**
   *  Enumerable#include(object) -> Boolean
   *  - object (?): The object to look for.
   *
   *  Determines whether a given object is in the enumerable or not,
   *  based on the `==` comparison operator (equality with implicit type
   *  conversion).
   *
   *  ##### Examples
   *
   *      $R(1, 15).include(10);
   *      // -> true
   *
   *      ['hello', 'world'].include('HELLO');
   *      // -> false ('hello' != 'HELLO')
   *
   *      [1, 2, '3', '4', '5'].include(3);
   *      // -> true ('3' == 3)
  **/
  function include(object) {
    if (Object.isFunction(this.indexOf))
      if (this.indexOf(object) != -1) return true;

    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  }

Is there a better way to do it? faster or "better" cross browser compatible?


texts:
Is it considered bad practice to pass string literals as char*, when an array and not a c-string is expected by the function? From my code:

char ConsoleIO::GetNextChar(string prompt, char* choices, int numChoices) {
    // Loop until valid input, or 10 times.
    for (int i = 0; i < 10; i++) {
        Write(prompt);

        char* buffer = new char[200];
        cin.getline(buffer, 200);
        char choice = tolower(buffer[0]);

        if (in(choice, choices, numChoices)) {
            return choice;
        }

        WriteLine("Invalid choice.");
    }
    // Just return the first choice as the default.
    return choices[0];
}

// In main:
char userChoice = ConsoleIO::GetNextChar("Make a selection: ", "234", 3);

It compiles, but is it bad practice?


texts: Optimization of AngularJS function to load images on the page

texts:
I have two AngularJS function in my dataContext object that receive data from a WebAPI:

(function () {
'use strict';

var serviceId = 'datacontext';
angular.module('app').factory(serviceId,
    ['common', datacontext]);

function datacontext(common) {
    var service = {

        getAllTagsByHttp: getAllTagsByHttp,
        getBlogPostsByHttp: getBlogPostsByHttp,
        getAllUserPicByHttp: getAllUserPicByHttp

    };
    return service;

    function getAllTagsByHttp() {
       return common.$http.get('/api/TagApi/alltags');
    }

    function getBlogPostsByHttp() {
        return common.$http.get('/api/BlogPostApi/AllBlogPosts');
    }

    function getAllUserPicByHttp() {
        return common.$http.get('/api/BlogPostApi/AllUserPic');
    }
}})();

I have an AngularJS controller that calls these API functions from the datacontext to receive information to display back to the user. The getblogPost function is called first because the next function needs the data from this to operate on.  The second function does a comparison on the first function's data to display back the img source to the user.

The problem I am having is that it takes quite a few seconds for the second function to receive the data and complete its operation. The amount of data being send back is a few  records.  Is there any improvements that can be made to the controller or dataContext object to reduce the time or improve the code?

(function () {
'use strict';
var controllerId = 'search';
angular
    .module('app')
    .controller(controllerId, ['common','datacontext', search]);

function search(common, datacontext) {
    var getLogFn = common.logger.getLogFn;
    var log = getLogFn(controllerId);

    var vm = this;
    vm.title = 'search';
    vm.picData = [];

    activate();

    function activate() {
        var promises = [getBlogPosts(), getUserPicData(), getUserPicUrl()];
        common.activateController(promises, controllerId)
            .then(function () { log('Search View'); });
    }

    function getBlogPosts() {
        datacontext.getBlogPostsByHttp().then(function (response) {
            vm.data = response.data;
        });
    }
    function getUserPicData() {
        datacontext.getAllUserPicByHttp().then(function (response) {
            vm.picData = response.data;

            for (var i = 0; vm.data.length > i; i++) {
                for (var x = 0; vm.picData.length > x; x++) {
                    if (vm.data[i].UserName == vm.picData[x].UserName) {
                        vm.data[i].PictureUrl = vm.picData[x].PictureUrl;
                       // console.log(vm.data[i].PictureUrl);
                        break;
                    }

                }
           }
        });
    }

   function getUserPicUrl(username) {
        getUserPicData();
        for (var i = 0; vm.picData.length < i; i++) {
            if (vm.picData[i].UserName === username) {
                return vm.picData[i].PictureUrl;
                }
            }
            return "not found";
    }
}})();