text:
Q: calculating shortest grid distance
Consider a city where the streets are perfectly laid out to form an infinite square grid. In this city finding the shortest path between two given points (an origin and a destination) is much easier than in other more complex cities. As a new Uber developer, you are tasked to create an algorithm that does this calculation.
Given user's departure and destination coordinates, each of them located on some street, find the length of the shortest route between them assuming that cars can only move along the streets. You are guaranteed that at least one of the coordinates is an integer.

I am struggling a little to figure out the logic here. There are many cases and I don't know how to accommodate them all. This is what I have so far
double perfectCity(double[] departure, double[] destination) {
    double yDist = Math.abs(destination[1]-departure[1]);
    double xDist = Math.abs(departure[1] - departure[0] + departure[1]-destination[0]);
    return xDist + yDist;
}

A: The algorithm is very simple if the inputs are integers, just find the absolute value between the x and y coordinates and then add them together. This is called the Manhattan distance.
int distance = Math.abs(x1 - x2) + Math.abs(y1 - y2);

With doubles, it is almost exactly the same, except for one situation. Here are some possibilities:

*

*Both points have integer coordinates

*One point has integer coordinates, and the other point has only one integer coordinate

*Both points have only one integer coordinate, but they are on different axes.

*Both points have only one integer coordinate, and they are on the same axis.

Possibilities 1-3 all work fine using the same algorithm as for finding distance with integers, except #4 has the possibility of the axis in common being on the same block.
For example, if the inputs were: {x: 0.5, y: 2} and {x: 0.5, y: 3} you would have to travel horizontally, vertically, and then backwards horizontally again in order to reach the destination. This is different from inputs of {x: 0.5, y: 2} and {x: 1.5, y: 3} because there is no need to travel backwards on the same axis.
So you can use the normal algorithm in all cases except for the case of when both of the Xs or Ys have floating-point values and have the same floor-ed value.
Your code should look something like this.
import static java.lang.Math.*;

public static double perfectCity(double x1, double y1, double x2, double y2) {
    double xDist = abs(x1 - x2);
    double yDist = abs(y1 - y2);
    if (floor(x1) != x1 && floor(x2) != x2 &&        // both Xs are doubles
        floor(x1) == floor(x2) &&                    // on the same block
        y1 != y2) {                                  // not on the same street
        xDist = min(abs(x1 - floor(x1) + x2 - floor(x2)),
                    abs(x1 - ceil(x1)  + x2 - ceil(x2)));
    } else if (floor(y1) != y1 && floor(y2) != y2 && // both Ys are doubles
               floor(y1) == floor(y2) &&             // on the same block
               x1 != x2) {                           // not on the same street
        yDist = min(abs(y1 - floor(y1) + y2 - floor(y2)),
                    abs(y1 - ceil(y1)  + y2 - ceil(y2)));
    }
    return xDist + yDist;
}

This can be much further simplified by using a helper function to calculate each axis separately.
public static double perfectCity(double x1, double y1, double x2, double y2) {
    return travelOnAxis(x1, x2, y1 == y2) + travelOnAxis(y1, y2, x1 == x2);
}

private static double travelOnAxis(double from, double to, boolean travelIsStraight) {
    if (Math.floor(from) == Math.floor(to) && !travelIsStraight) {
        double dist = Math.abs((from % 1) + (to % 1));
        return Math.min(dist, 2 - dist);
    } else {
        return Math.abs(from - to);
    }
}

I used the trick with 2 - dist here because it's the same as calculating
Math.abs((1 - (from % 1)) + (1 - (to % 1)))

which is the same as
Math.abs(from - Math.ceil(from) + to - Math.ceil(to))

A: If this is a square grid, you can consider the x and y coordinates separately; the minimum distance is the sum of the minumum distances in the two directions.
In the p-direction (either x or y), you have to move from p1 to p2. From p1, you can either move to floor(p1) or ceil(p1) to get to a road (which may be equal, if p1 is an integer); from there, you can move to either floor(p2) or ceil(p2), the road on which p2 is located; from there, you can move to p2.
So, the minimum distance in the p-direction is
min(abs(p1 - ceil(p1) ) + abs(ceil(p1)  - floor(p2)) + abs(floor(p2) - p2),  # (1)
    abs(p1 - floor(p1)) + abs(floor(p1) - ceil(p2) ) + abs(ceil(p2)  - p2),  # (2)
    abs(p1 - floor(p1)) + abs(floor(p1) - floor(p2)) + abs(floor(p2) - p2),  # (3)
    abs(p1 - ceil(p1) ) + abs(ceil(p1)  - ceil(p2) ) + abs(ceil(p2)  - p2))  # (4)

So you can just calculate this independently for the x and y directions, and add.

To illustrate this (abbreviating floor and ceil as f and p respectively):
f(p1) p1  c(p1)
  +---O>>>>+>>>>>>>>+
                    .
                    .
                    +>>>O----+
                  f(p2) p2  c(p2)

--------------------------------> p axis

The shortest route is indicated here with >. The .s are on the shortest route, but since that part of the route is orthogonal to the p direction, it "doesn't count" towards the minimum distance in that direction.
The minimum route shown here, p1 -> c(p1) -> f(p2) -> p2, is Case 1 above.
It should not be hard to visualize swapping p1 and p2, in which case the minimum route is to go from p1 ->f(p1) -> c(p2) -> p2 (Case 2).
The case of pN == f(pN) == c(pN) is not very different; then, the part of the expression abs(pN - f(pN)) or abs(pN - c(pN)) is just zero.
The slightly different case is where f(p1) == f(p2):
f(p1) p1  c(p1)          f(p1) p1  c(p1)
  +---O>>>>+               +<<<O----+
           .               .
           .               .
  +-----O<<+               +>>>>>O--+
 f(p2) p2  c(p2)          f(p2) p2  c(p2)

--------------------------------> p axis

In this case, the minimum route can either be p1 -> f(p1) -> f(p2) -> p2 or p1 -> c(p1) -> c(p2) -> p2 (which are Cases 3 and 4, respectively).

A: As mentioned by 4castle, the problem is trivial if only integers are considered for input. You would never have to "move back" after having "moved forward" in that case since you would always reach your destinaton in a single move.
But since, at most one floating point number needs to be considered for each of departure/destination, we need to consider 3 cases, (warning: lengthy explanation). Below is a python2 implementation with explanations.

*

*x co-ordinates of both departure and destination are the same and are not floating point numbers. In this case, the shortest distance is simply the absolute difference between y co-ordinates. The same logic applies vice-versa.
import math
class Location():
    def __init__(self, cord):
        self.x = cord[0]
        self.y = cord[1]

def perfectCity(departure, destination):
    l1 = Location(departure)
    l2 = Location(destination)

    if l1.x == l2.x and float(l1.x).is_integer() and float(l2.x).is_integer():
        return abs(l1.y-l2.y)
    if l1.y == l2.y and float(l1.y).is_integer() and float(l2.y).is_integer():
        return abs(l1.x-l2.x)

*When one of the co-ordinates in the departure is a floating point, then:

*

*If x co-ordinate is floating point, we can move backwards(round down) or move front(round up).

*If y co-ordinate is floating point, we can either move down (round down) or move up (round up).

*The above logic should work even when there is no floating point co-ordinate since we move in either direction by zero  units.

*Once we calculate these, we just choose the minimum among those like below,

return min(calc_round_up_dist(l1, l2), cal_round_down_dist(l1, l2))
Lets take an example of (0.4, 1) and (0.9, 3) for below calculations.

*While calculating the round_up we need to calculate 3 distances:

*

*round_up_distance: difference between the rounded up value of the floating point co-ordinate and the original floating point co-ordinate. We return zero if there is no floating point co-ordinate. 1 - 0.4 = 0.6 in the above example

*non_floating_point difference: difference between the non floating point co-ordinate of departure and the corresponding co-ordinate of destination ( note that this might be floating point or not a floating point abs(3-1) = 2 in the above example

*Difference between departure's floating point counterpart in the destination co-ordinate 0.9 in the above case and the new value of departure's floating point after rounding up, 0.4 + 0.6(this is the round_up distance) = 1.0, i.e. abs(0.9 - 1.0) = 0.1

*Adding all the 3 above we get 0.6 + 2 + .1 = 2.7 which is the shortest distance.

*Corresponding calculation needs to be done for rounding down. And we pick the minimum among both. The code for round_up and round_down is as below,
import math
class Location():
    def __init__(self, cord):
        self.x = cord[0]
        self.y = cord[1]

    def floating_point_round_up(self):
        if not float(self.x).is_integer():
            return math.ceil(self.x) - self.x
        if not float(self.y).is_integer():
            return math.ceil(self.y) - self.y
        return 0

    def floating_point_round_down(self):
        if not float(self.x).is_integer():
            return self.x - math.floor(self.x)
        if not float(self.y).is_integer():
            return self.y - math.floor(self.y)
        return 0

    def non_floating_point_diff(self, obj):
        if not float(self.x).is_integer():
            return abs(self.y - obj.y)
        if not float(self.y).is_integer():
            return abs(self.x - obj.x)
        return abs(self.y - obj.y)

    def floating_point_counterpart(self, obj):
        if not float(self.x).is_integer():
            return obj.x
        if not float(self.y).is_integer():
            return obj.y
        return obj.x

    def floating_point(self):
        if not float(self.x).is_integer():
            return self.x
        if not float(self.y).is_integer():
            return self.y
        return self.x

*Round up and down functions are as below,
def calc_round_up_dist(l1, l2):
    dist = l1.floating_point_round_up()
    diff = l1.non_floating_point_diff(l2)
    floating_point_counterpart = l1.floating_point_counterpart(l2)
    new_val = dist + l1.floating_point()
    return dist + diff + abs(new_val - floating_point_counterpart)

def cal_round_down_dist(l1, l2):
    dist = l1.floating_point_round_down()
    diff = l1.non_floating_point_diff(l2)
    floating_point_counterpart = l1.floating_point_counterpart(l2)
    new_val = l1.floating_point() - dist
    return dist + diff + abs(floating_point_counterpart - new_val)

*Finally the main function that calls the above methods,
def perfectCity(departure, destination):
    l1 = Location(departure)
    l2 = Location(destination)

    if l1.x == l2.x and float(l1.x).is_integer() and float(l2.x).is_integer():
        return abs(l1.y-l2.y)
    if l1.y == l2.y and float(l1.y).is_integer() and float(l2.y).is_integer():
        return abs(l1.x-l2.x)

    return min(calc_round_up_dist(l1, l2), cal_round_down_dist(l1, l2))

A: This is a practice question on CodeSignal:
https://app.codesignal.com/company-challenges/uber/gsjPcfsuNavxhsQQ7
def solution(departure, destination):
    # go to the closest integer
    # I can only travel the path of an integer
    # if the number is a float I need to travel to an integer first
    # then travel to the destination

    x1, y1 = departure
    x2, y2 = destination
    res = 0

    # check if the coordinations are integers
    a = list(map(isInteger, departure))
    b = list(map(isInteger, destination))

    # if all are integers or if the corresponding elements are different
    if a[0] ^ b[0] or (a[0] and a[1] and b[0] and b[1]):
        return abs(x1-x2) + abs(y1-y2)

    if a[0]:
        res += abs(x2-x1)
        # cloest distance from y1 to y2
        res += getClosest(y1, y2)
    else:
        res += abs(y2-y1)
        # closes distance from x1 to x2
        res += getClosest(x1, x2)

    return res

def getClosest(y1, y2):
    cand1 = math.floor(y1)
    cand2 = math.ceil(y1)
    # find the integer closer to y1 to move to
    res1 = abs(y1-cand1) + abs(cand1-y2)
    res2 = abs(y1-cand2) + abs(cand2-y2)
    return min(res1, res2)

def isInteger(n):
    return n == round(n)


text:
Q: PHP - Character Encoding Issue - Must be Missing Something In my PHP page, product descriptions are showing up with the infamous £ issue.
Aha! I thought - I must remember to move the entire website over to UTF-8. So I:

*

*Specified in both the mysql_set_charset('utf8'); and the array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") command. I'm migrating the website over to PDO - so still in a transitional process. The actual part of the website where the product description is saved and read both use the new PDO method.

*Specified ini_set('default_charset', 'utf-8'); at the start of my header.php page.

*Specified <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> in the head tag of the HTML page. I verified that there were no caching issues by checking that it appears.

*Changed the collation of the products table to utf8_general_ci.

But the error still occurs. It even occurs on new products and when I edit the product to remove and re-add the pound sign. Is there anything I'm missing?

A: I found the problem. I was throwing htmlentities() onto the strings for security when I was echoing them to the browser. I should have thrown:
htmlentities($string, ENT_COMPAT | ENT_HTML401, "UTF-8"); to rectify this.

A: There are 2 more things

*

*set header("Content-Type: text/html; charset=utf-8");

*make sure your file encoding is UTF-8 (eg: open file with notepad and save it as UTF-8 ENCODING)

redpajama_set_name: RedPajamaStackExchange


text:
Q: WordPress - Sum meta value by post_parent I am trying to run a WPDB query for counting value of post meta:
Sum meta Value by post_id which have post_parent = xx

I have a WPDB code but I dont know how to get by post_parent:
$wpdb->get_results("SELECT SUM($wpdb->postmeta.meta_value)
      FROM $wpdb->postmeta WHERE `post_id` = get_the_ID()");

A: $wpdb->get_results("SELECT SUM( wp_postmeta.meta_value )
FROM wp_postmeta
WHERE wp_postmeta.post_id =".get_the_ID());


text:
Q: web page with python server and sqlite i am new to python

and i want to do simple web server using python,i see some videos on YouTube how to create web server ,but i didn't found how to use the button click as an example .
  and after i do that i will connect it with tkinter to desktop  GUI
i don't know if there is something like that ,so i am just asking ,and hope to post any useful links ,thanks

from http.server import HTTPServer, BaseHTTPRequestHandler

class Serv(BaseHTTPRequestHandler):

def do_GET(self):
    if self.path == '/':
        self.path = '/index.html'
    if self.path == '/test':
        self.path = '/test.html'
    try:
        file_to_open = open(self.path[1:]).read()
        self.send_response(200)
    except:
        file_to_open = "sorry this page isn't found"
        self.send_response(404)
    self.end_headers()
    self.wfile.write(bytes(file_to_open, 'utf-8'))

httpd = HTTPServer(('localhost', 8080), Serv)
httpd.serve_forever()


text:
Q: Why is Spring State Machine PersistStateChangeListener component sometimes not executing during same thread? Long story short:
We have a Spring State Machine implementation that will persist with a different request (on same thread from thread pool), causing a state error within our code. Why does it not run synchronously as part of same request?
Much longer story:
Our state machine is set up such that when an event is triggered and the state transition is successful/valid and it persisted, then work is done. If it fails either, we throw an exception. Persistence ironically is not enforced in Spring State Machine, so we had to do our own thing to enforce it.
We have a config class:
@Slf4j
@Configuration
@EnableStateMachine(name = "myStateMachine")
public class StatemachineConfiguration extends StateMachineConfigurerAdapter<String, String> {

    @Override
    public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception {
     transitions
            .withExternal().source(States.INITIAL.name()).target(States.IN_PROGRESS.name())
            .event(Events.START.name())
            .and()
            ...more transitions
    }

    @Override
    public void configure(StateMachineStateConfigurer<String, String> states) throws Exception {
        states
            .withStates()
            .initial(States.INITIAL.name())
            .state(States.IN_PROGRESS.name())
            ...more states;
    }

    @Override
    public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception {
        config.withConfiguration()
            .taskExecutor(new SyncTaskExecutor()) // This should be default, but I added it anyways
            .autoStartup(false);
    }
}

To trigger events we are using a wrapper to enforce persistence prior to continuing on. Without the wrapper, we were continuing without actually having successfully saved the state entity. This was causing us to run into state transition errors when we later tried to trigger events, but the database had the old state.
StateEntityWrapper wrapper = new StateEntityWrapper(stateEntity);
boolean success = persistStateMachineHandler.handleEventWithState(
    MessageBuilder.withPayload(event.name()).setHeader(Constants.PERSIST_ENTITY_WRAPPER_HEADER, wrapper).build(),
    stateEntity.getState().name()
        );

if (!(success && wrapper.isPersisted()) {
    throw new StateTransitionException();
}

// Transition saved and successful - begin work
// Trigger other events depending on what happens during work

Our PersistStateChangeListener:
@Slf4j
@Component
@RequiredArgsConstructor
public class MyPersistStateChangeListener implements PersistStateChangeListener {

    private final MyStateRepository repository;

    @Override
    public void onPersist(State<String, String> state,
                          Message<String> message,
                          Transition<String, String> transition,
                          StateMachine<String, String> stateMachine) {
        StateEntityWrapper wrapper = message.getHeaders().get(Constants.PERSIST_ENTITY_WRAPPER_HEADER, StateEntityWrapper.class);
        if (wrapper != null) {
            StateEntity entity = wrapper.getStateEntity();
            entity.setState(States.valueOf(state.getId()));
            this.persist(entity);
            wrapper.setPersisted(true);
        } else {
            String msg = "StateEntityWrapper is null. Could not retrieve " + Constants.PERSIST_ENTITY_WRAPPER_HEADER + ".";
            log.warn("{}", msg);
            throw new MyPersistRuntimeException(msg);
        }
    }

    private void persist(FulfillmentState entity) {
        try {
            repository.save(entity);
        } catch (Exception e) {
            throw new MyPersistRuntimeException("Persistence failed: " + e.getMessage(), e);
        }
    }
}

I found that exceptions thrown by the persist listener are caught by Spring State Machine in AbstractStateMachine::callPreStateChangeInterceptors and will skip the state change. However, the call to PersistStateMachineHandler::handleEventWithState will return true regardless of not being able to save. This is because the state machine interceptors (persist listener is one of these) can be set up to be asynchronous. However, according to documentation, the default is supposed to be synchronous.
If the default is synchronous, then why does it sometimes execute after the PersistStateMachineHandler returns? We use Sleuth in our logging and I noticed that usually it has the same trace id during persistence. But occassionally, I see it execute with another request and its trace id. Lastly, I found DefaultStateMachineExecutor manages a TaskExecutor and should run synchronously based on default configurations, but sometimes does not. Any ideas?


text:
Q: name is not defined python I defined prefixcmd in CONFING class, but when I call prefixcmd.get() it returns a NameError:
line 10, in
client = commands.Bot(command_prefix=prefixcmd.get())
NameError: name 'prefixcmd' is not defined
Here is the code:
from tkinter import *
import discord
from discord.ext import commands
from discord.ext import tasks
import os
import re
#==========BOT CONFING==========
class CONFING:
    PREFIX = '$'
client = commands.Bot(command_prefix=prefixcmd.get())
client.remove_command('help')

@client.event
async def on_ready():
    client.statuses = cycle([playingBox.get(),'✨Robitco.ir'])
    change_status.start()
    print("Gangz Iz Herez")

@tasks.loop(seconds=5)
async def change_status():
    await client.wait_until_ready()
    await client.change_presence(activity=discord.Game(name=next(client.statuses)))

#==================BOT RUN==========================
def StartBot():
 client.run(TokenBox.get())
 #================== TKINTER ========================
root = Tk()
root.title('Free Discord Bot maker ! [Beta] ')
root.geometry("400x400")

prefixLabel = Label(root, text="Prefix (NEEDED) Example: $ ")
prefixLabel.pack()

prefixcmd = Entry(root, width=30)
prefixcmd.pack()

spaceLabel = Label(root, text="---------------Token--------------")
spaceLabel.pack()

yourTokenLabel = Label(root, text="Enter Your Bot Token!")
yourTokenLabel.pack()

TokenBox = Entry(root, width=30)
TokenBox.pack()

RunButton = Button(root, text="Start Bot", command=StartBot)
RunButton.pack()

root.mainloop()

It works when I use client = commands.Bot(command_prefix=CONFING.PREFIX) instead of calling prefixcmd.get()

A:
NameError: name 'prefixcmd' is not defined

prefixcmd isn't defined when you first call it here: client = commands.Bot(command_prefix=prefixcmd.get()).
CONFING.PREFIX works because its defined before.


text:
Q: Angular2 button not disabled when the form is initialized on IE11 I am using Angular2 and PrimeNg to create a form.. There is a button that needs to be disabled when the form is not dirty or when it is invalid. All the things work well on Chrome but not on IE11. Here is the code ... the Modify button is not disabled as expected.
<button pButton type="submit" icon="fa-pencil" (click)="modify()"
[disabled]="!form.dirty || form.invalid ||
disableModifyButton" disabled="true" label="Modify"></button>

Any ideas on how to solve this?

A: disabled only have one attribute value is disabled, so try this
[disabled]="(!form.dirty || form.invalid || disableModifyButton) ? 'disabled' : null"


text:
Q: How to use __local variables in OpenCL? I'm trying to implement a convolution algorithm in OpenCL (using Vivado HLS). I'm trying to load part of the image into the local memory before executing the workgroup (for example, if the workgroup is 128*128 and the convolution filter is 5*5, I would load 132*132 pixels). How do I write the kernel so that the local memory is only loaded once when the workgroup starts?
Pseudocode:
#define WKGRP_W 128
#define WKGRP_H 128

#define FILTER_SIZE 5

#define BUFFER_W WKGRP_W+FILTER_SIZE-1
#define BUFFER_H WKGRP_H+FILTER_SIZE-1

__kernel void  __attribute__ ((reqd_work_group_size(WKGRP_W, WKGRP_H, 1)))
convolve(
    const __global data_t* input,
    __global data_t* output,
    __constant data_t* filter_params
){
    __local data_t img_buffer[BUFFER_H][BUFFER_W];
    __local data_t output_buffer[WKGRP_H][WKGRP_W];

    /**
     * if (the workgroup is starting) {
     *     load data from input into img_buffer
     * }
     */

    filter(img_buffer, filter_params, get_local_id(0), get_local_id(1), output_buffer);

    /**
     * if (the workgroup is finished) {
     *     load data from output_buffer into output
     * }
     */
}

A: Assuming you have a single work-item per input pixel, you can have each thread load one pixel from global memory into local memory.
int x = get_local_id(0);
int y = get_local_id(1);
img_buffer[x][y] = input[...];
barrier(CLK_LOCAL_MEM_FENCE);

// filter here or whatever computation you need to perform

If your data is aligned, you could make that faster by casting to larger data types. See this link for more details.
Edit: have each thread grab 2 values until you reach your 132. Of course, some work items might end up doing nothing in the process
int x = get_local_id(0);
int y = get_local_id(1);

if (2*x < 132 && 2*y < 132) {
    img_buffer[2*x][2*y] = input[...];
    img_buffer[2*x][2*y + 1] = input[...];
    img_buffer[2*x + 1][2*y] = input[...];
    img_buffer[2*x + 1][2*y + 1] = input[...];
}
barrier(CLK_LOCAL_MEM_FENCE);

// filter here...

A: You can use async_work_group_copy to perform a copy to local. It will return you an event object that you can wait on it immediately with wait_group_events.
Or do some other processing in the meantime that does not need the data being copied. (ie: Computing some factors for the filter). To keep the work-group busy.
//Copy input from global to local
event_t global2local = async_work_group_copy(img_buffer, input, size, 0);
wait_group_events(1, &global2local);

//Copy the buffer from local to global
event_t local2global = async_work_group_copy(output_buffer, output, size2, 0);
wait_group_events(1, &local2global);


text:
Q: Youtube-DL: Is there an output wildcard for which site the video is being downloaded from? Youtube-dl supports several sites; in my case I'm using youtube & vimeo. I want to have my '-o' string differentiate between the two when setting an output directory, so that matching users don't clobber each other, and cross-site user's content can be kept separate by site.
I've looked in this list of supported wildcards:
https://github.com/ytdl-org/youtube-dl/blob/master/README.md#output-template
and didn't see one for "site". Are there more wildcards than just the ones in this list? or is that it?
If not, I have some programming experience, how difficult would it be to add the new wildcard myself? I am not familiar with the code at all. Would it be worth investigating? or is there a simpler solution that I'm overlooking?
thanks,
-Yurelle

A: You can probably use the extractor name as a proxy for site, especially if it's limited to Youtube and Vimeo.

extractor (string): Name of the extractor

Thus
youtube-dl -o '%(extractor)s'

with a youtube URL will output to a file named youtube.mkv by default. Add other identifiers from the list as you see fit.
Here's a complete list of extractors, and as you see, major sites have their own specific extractor which will give you information about which site it was downloaded for. The Vimeo extractor is named vimeo.


text:
Q: Show Google maps based on the address in MVC/jquery I need to show the google map based on the address of a contact in my asp.net (MVC) c# application.
I have a list of contacts in my application. When the user views a particular contact, i need to show the google map of the contact's address, to the side of contact view page.
How can i implement this functionality using jquery in MVC?

A: First thing you'll probably want to do is get the latitude and longitude of the contact's address. You can either access the geoCode api and do that real time or get it and save it in the database when you first create the new contact. I highly recommend the later and you'll save a bunch on headaches if you don't need to do a geoCode look up for every page request.
Then attach your latitude and longitude to the ViewModel so you can work with those values in your view. Set the latitude and longitude to a couple of javascript variables and you're good to go.
Take a look at the "hello world" for google maps api and you should have all the info you need there. Just set the options to what you want and use your latitude and longitude.
There's not much you can do with jQuery here since you'll mainly be using Google's api. The only real advantage would be to maybe put things in the $(funcion() {... so you don't have to do a function on the body onload=...

A: You could use the jQuery Google Maps plugin for this, however it doesn't have support yet for converting an address to a location as it requires the latitude and longitude up front.

A: Maybe MVCMaps could be useful to you. It can used for both the Bing Maps and Google Maps.
Visit http://mvcmaps.codeplex.com/.


text:
Q: Jquery: Add fieldset element between form How to insert fieldset inform using jquery now I have this
<form action="" method="post">

all dynamic field generated with db and array

</form>

I want to add fieldset between form tag so code become
<form action="" method="post">
<fieldset>

all dynamic field generated with db and array

</fieldset>
</form>

A: I'd recommend doing this server-side, but if you really need to use jQuery for this:
$('form').wrapInner('<fieldset />');

Fiddle
.wrapInner docs

A: or you can do it like this:
    var newForm = "<fieldset>"+$('form').html()+"</fieldset>";
    $('form').html(newForm);


text:
Q: I want to simulate and obtain best ARIMA ith number of time in R I want to simulate ARIMA(1,0,0) with arima.sim() 100 times and find the best model with auto.arima() function for each time the simulation is done. I want the program to print the order of ARIMA obtain each time.
reslt = c()
num <- 60
epselon = rnorm(num, mean=0, sd=1^2)
for(i in 1:10){
reslt[i]<-auto.arima(arima.sim(n = num, model=list(ar=0.8, order = c(1, 0, 0)), n.start=1, innov=c(0,epselon[-1])))
}

The above is what I tried but no result.
What I want is to print a series of ARIMA(p, d, q) into 10 times

A: This will do it:
library(forecast)
nsim <- 10
result <- matrix(NA_integer_, nrow = nsim, ncol = 3)
colnames(result) <- c("p","d","q")
num <- 60
for (i in seq(nsim)) {
  result[i, ] <- arima.sim(n=num, model=list(ar=0.8, order=c(1,0,0)), sd=1) %>%
    auto.arima() %>%
    arimaorder()
}
result
#>       p d q
#>  [1,] 0 1 0
#>  [2,] 0 1 0
#>  [3,] 0 1 0
#>  [4,] 1 0 0
#>  [5,] 1 0 0
#>  [6,] 0 1 0
#>  [7,] 0 1 0
#>  [8,] 1 0 0
#>  [9,] 1 0 0
#> [10,] 1 0 0

Created on 2020-06-24 by the reprex package (v0.3.0)
A few comments:

*

*Your code will produce the same series every time because epselon is generated outside the loop. As you are just using random normal innovations, it is simpler to let arima.sim() handle it as in the code above.

*If you wanted to keep the whole model object that is returned by auto.arima() rather than just the orders as in my code, you could modify it like this:

library(forecast)
nsim <- 10
result <- list()
num <- 60
for (i in seq(nsim)) {
  result[[i]] <- arima.sim(n=num, model=list(ar=0.8, order=c(1,0,0)), sd=1) %>%
    auto.arima()
}
result
#> [[1]]
#> Series: .
#> ARIMA(0,1,0)
#>
#> sigma^2 estimated as 1.145:  log likelihood=-87.72
#> AIC=177.44   AICc=177.51   BIC=179.52
#>
#> [[2]]
#> Series: .
#> ARIMA(1,0,2) with zero mean
#>
#> Coefficients:
#>          ar1     ma1     ma2
#>       0.5200  0.4086  0.4574
#> s.e.  0.1695  0.1889  0.1446
#>
#> sigma^2 estimated as 0.877:  log likelihood=-80.38
#> AIC=168.77   AICc=169.5   BIC=177.15
#>
#> [[3]]
#> Series: .
#> ARIMA(0,1,0)
#>
#> sigma^2 estimated as 0.9284:  log likelihood=-81.53
#> AIC=165.05   AICc=165.12   BIC=167.13
#>
#> [[4]]
#> Series: .
#> ARIMA(1,0,0) with zero mean
#>
#> Coefficients:
#>         ar1
#>       0.615
#> s.e.  0.099
#>
#> sigma^2 estimated as 1.123:  log likelihood=-88.35
#> AIC=180.7   AICc=180.91   BIC=184.89
#>
#> [[5]]
#> Series: .
#> ARIMA(0,0,3) with zero mean
#>
#> Coefficients:
#>          ma1     ma2      ma3
#>       0.5527  0.2726  -0.3297
#> s.e.  0.1301  0.1425   0.1202
#>
#> sigma^2 estimated as 0.6194:  log likelihood=-69.83
#> AIC=147.66   AICc=148.39   BIC=156.04
#>
#> [[6]]
#> Series: .
#> ARIMA(1,0,0) with non-zero mean
#>
#> Coefficients:
#>          ar1    mean
#>       0.7108  0.9147
#> s.e.  0.0892  0.4871
#>
#> sigma^2 estimated as 1.332:  log likelihood=-93.08
#> AIC=192.15   AICc=192.58   BIC=198.43
#>
#> [[7]]
#> Series: .
#> ARIMA(1,0,1) with non-zero mean
#>
#> Coefficients:
#>          ar1     ma1     mean
#>       0.6116  0.3781  -1.0024
#> s.e.  0.1264  0.1559   0.4671
#>
#> sigma^2 estimated as 1.161:  log likelihood=-88.6
#> AIC=185.2   AICc=185.92   BIC=193.57
#>
#> [[8]]
#> Series: .
#> ARIMA(1,0,0) with zero mean
#>
#> Coefficients:
#>          ar1
#>       0.6412
#> s.e.  0.0969
#>
#> sigma^2 estimated as 0.8666:  log likelihood=-80.6
#> AIC=165.2   AICc=165.41   BIC=169.39
#>
#> [[9]]
#> Series: .
#> ARIMA(0,1,0)
#>
#> sigma^2 estimated as 1.314:  log likelihood=-91.78
#> AIC=185.57   AICc=185.64   BIC=187.64
#>
#> [[10]]
#> Series: .
#> ARIMA(1,0,0) with non-zero mean
#>
#> Coefficients:
#>          ar1    mean
#>       0.6714  1.3449
#> s.e.  0.0985  0.4428
#>
#> sigma^2 estimated as 1.397:  log likelihood=-94.44
#> AIC=194.89   AICc=195.32   BIC=201.17

Created on 2020-06-24 by the reprex package (v0.3.0)


text:
Q: How to modify directives isolated scope variable in controller, while still keeping it isolated? I have a directive with isolated scope. I am modifying one of the variables passed from the parent controller in the controller of the directive. The issue I'm running into is that when I use multiple instances of this directive (with different options and model) on the same view, the options object does not remain unique to each instance of the directive. Instead, it becomes a shared variable and all the instances of the directive use the same options object.
So if I had used them in my view like below, with optionsA.isFlagOn = true and optionsB.isFlagOn = false
<my-directive model="modelA" options="optionsA">
<my-directive model="modelB" options="optionsB">

Directive with modelB loads with the optionsA.
How do I keep options unique while modifying it for each specific instance?
angular.module('myModule', [])
.directive('myDirective', function($compile) {
  template = '

';
  return {
    restrict: 'AE',
    scope: {
       model: "=",
       options: "=?" //A JSON object
    },
    controller: function($scope) {
      $scope.options = $scope.options || {};
      //A function that sets default values if no options object passed
      ensureDefaultOptions($scope);

      //now based on some of the options passed in, I modify a property in the options object
      if ($scope.options.isFlagOn)
        $scope.options.thisProp = true;
    },
    link: function(scope, element, attr) {
      let content = $compile(template)(scope);
      element.append(content);
    }
  };
}

Edit: I solved my issue. My solution is posted in the answer below.

A: Can you change it to you one-way bindings with:
scope: {
       model: "=",
       options: "<?" //A JSON object
    }

A: Your directive should make a copy of passed in options combined with defaults, so each directive instance have its own option object.
You can achieve that easily by using extend
var defaultOptions = { a:1, b:2, c:3 };
var options = angular.extend(defaultOption, $scope.options);
// then use options everywhere

Note that this will only be done once during init, so if your options come from controller asynchronously, you'll need extra handling.

A: I solved it using the bindToController property of Angular directive available in 1.4x or higher.
angular.module('myModule', [])
  .directive('myDirective', function($compile) {
    template = '

';
    return {
      restrict: 'AE',
      bindToController: {
        model: "=",
        options: "=?" //A JSON object
      },
      scope: {},
      controller: function() {
        var vm = this;

        //a function that handles modifying options
        vm.setOptions = function(options){
          let newOptions = {};
          angular.copy(options, newOptions);

          // modify newOptions here

          return newOptions;
        }

      },
      controllerAs: 'vm',
      link: function(scope, element, attr) {

         ensureDefaultOptions(scope.vm);

         scope.myOptions = scope.vm.setOptions(scope.vm.options);

         let content = $compile(template)(scope);
         element.append(content);
      }
    };
  });


text:
Q: android.view.InflateException: Binary XML file line #158: Error inflating class Button I want to use color.xml file for my button, but it show this error and app crash. It says, it cannot find the color.xml file.
Caused by: android.content.res.Resources$NotFoundException: File res/color/color.xml from drawable resource ID #0x7f0e00dd
  at android.content.res.Resources.loadDrawableForCookie(Resources.java:3783)
  at android.content.res.Resources.loadDrawable(Resources.java:3651)
  at android.content.res.TypedArray.getDrawable(TypedArray.java:762)
  at android.view.View.<init>(View.java:3983)
  at android.widget.TextView.<init>(TextView.java:1021)
  at android.widget.Button.<init>(Button.java:115)
  at android.widget.Button.<init>(Button.java:108)
  at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:62)
  at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:5

Here is my button xml:
<Button
    android:id="@+id/btn_buy"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@color/color"
    android:textColor="@color/mdtp_white"
    android:text="@string/buy"/>

This is my color.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@color/grey" />
    <item android:color="@color/myRedColor"/>
</selector>

A: Create color.xml file in Drawable folder.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@color/grey" />
<item android:state_pressed="true"  android:drawable="@color/myRedColor" />
</selector>

Use color.xml as background in button
<Button
    android:id="@+id/btn_buy"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    // here
    android:background="@drawable/color"
    android:textColor="@color/mdtp_white"
    android:text="@string/buy"/>

A: android:background attribute requires a drawable resource. All you need to do is moving your color.xml file to drawable folder.

A: Paste your color.xml file in drawble folder and add color.xml as backgrouned to your button like this
<Button
    android:id="@+id/btn_buy"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@drawable/color"
    android:textColor="@color/mdtp_white"
    android:text="@string/buy"/>

A: put your color.xml file in drawable
make changes in drawable\color.xml file
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@color/grey" />
    <item android:drawable="@color/myRedColor"/>
</selector>

button xml
<Button
    android:id="@+id/btn_buy"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="@drawable/color"
    android:textColor="@color/mdtp_white"
    android:text="@string/buy"/>

A: Finally, I fixed the error. I look strange but it work. First, move the color.xml to drawable folder. Then update the color.xml like following:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false">
        <color android:color="@color/grey"/>
    </item>
    <item>
        <color android:color="@color/myRedColor"/>
    </item>
</selector>


text:
Q: Changing line color below specific value in Chart.js I am trying to color the line below a specific value a certain color. I am using Chart.js v3.7.1
I have implemented the solution found in this answer with partial success...

 let posColour= 'rgb(86,188,77)';
 let negColour= 'rgb(229,66,66)';
 let config = {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: tempData.sensorName,
                        data: data,
                        backgroundColor: 'rgba(60,141,188,0.9)',
                        borderColor: posColour,
                        pointRadius: false,
                        pointColor: '#3b8bba',
                        pointStrokeColor: posColour,
                        pointHighlightFill: '#fff',
                        pointHighlightStroke: posColour,
                        segment: {
                            borderColor: (ctx2) => (ctx2.chart.data.datasets[0].data[ctx2.p0DataIndex] < 40 ? negColour : posColour)
                        }

                    }]
                }
                 /*  items below here are not necessary to reproduce the issue  */
                 ,
                options: {
                    reponsive: true,
                    scales: {
                        x: {
                            type: 'time',
                            time: {
                                displayFormats: timeFormat,
                                format: 'day'
                            },
                            ticks: {
                                major: {
                                    enabled: true
                                },
                                maxTicksLimit: 15
                            },
                            title: {
                                display: true,
                                text: 'Date'
                            }
                        },
                        y: {
                            title: {
                                display: true,
                                text: 'Temp (\u00b0C)'
                            }
                        }
                    }
                }
                 /*  items above here are not necessary to reproduce the issue  */
            }

I am aware that I can do it very simply with a fill, but the visible impact of the inversed area chart is not the visual effect I am seeking.
I am looking for something like this answer, but I cannot get the last two lines to work (I am not familiar enough with ChartJS).
let posColour= 'rgb(86,188,77)';
let negColour= 'rgb(229,66,66)';

plugins: [{
  beforeRender: (x, options) => {
    const c = x.chartArea; //tweaked for chart.js3
    const dataset = x.data.datasets[0];
    const yScale = x.scales.y; //tweaked for chart.js3
    const yPos = yScale.getPixelForValue(40); //I want everything under 40 red, not 0 as the original answer...

    const gradientFill = c.ctx.createLinearGradient(0, 0, 0, c.height);
    gradientFill.addColorStop(0, posColour);
    gradientFill.addColorStop(yPos / c.height, posColour);
    gradientFill.addColorStop(yPos / c.height, negColour);
    gradientFill.addColorStop(1, negColour);

    //these two lines are the ones i can't figure out how to convert to chart.js3...
    const model = x.data.datasets[0]._meta[Object.keys(dataset._meta)[0]].dataset._model;
    model.borderColor = gradientFill;
  },
}];

A: The solution provided by this answer can easily be adapted to also work with Chart.js v3.7.1.
Please take a look at below runnable code and see how it works.

const threshold = 25;

new Chart('myChart', {
  type: 'line',
  plugins: [{
    afterLayout: chart => {
      let ctx = chart.ctx;
      ctx.save();
      let yAxis = chart.scales.y;
      let yThreshold = yAxis.getPixelForValue(threshold);
      let gradient = ctx.createLinearGradient(0, yAxis.top, 0, yAxis.bottom);
      gradient.addColorStop(0, 'green');
      let offset = 1 / yAxis.bottom * yThreshold;
      gradient.addColorStop(offset, 'green');
      gradient.addColorStop(offset, 'red');
      gradient.addColorStop(1, 'red');
      chart.data.datasets[0].borderColor = gradient;
      ctx.restore();
    }
  }],
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
    datasets: [{
      label: 'My Dataset',
      data: [32, 44, 29, 33, 18, 15, 30],
      fill: false,
      lineTension: 0.2
    }]
  },
  options: {
    plugins: {
      legend: {
        display: false
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>

A: I have made a detailed response here that can help you.
Here is the code:
var myLineChart = new Chart(ctx, {
  type: 'line',
  plugins: [{
    afterLayout: chart => {
      let ctx = chart.chart.ctx;
      ctx.save();
      let yAxis = chart.scales["y-axis-0"];
      let yThresholdMax = yAxis.getPixelForValue(data.limits.max);
      let yThresholdMin = yAxis.getPixelForValue(data.limits.min);

      let offsetMax = 1 / yAxis.bottom * yThresholdMax;
      let offsetMin= 1 / yAxis.bottom * yThresholdMin;

      let gradient = ctx.createLinearGradient(0, yAxis.top, 0, yAxis.bottom);

      gradient.addColorStop(0, 'red');
      gradient.addColorStop(offsetMax, 'darkred');
      gradient.addColorStop(offsetMax, 'blue');
      gradient.addColorStop(offsetMin, 'blue');
      gradient.addColorStop(offsetMin,'darkred');
      gradient.addColorStop(1,"red");
      chart.data.datasets[0].borderColor = gradient;
      ctx.restore();
    }
  }],
  // The data for our dataset
  data: {
      ......
  },
    options: {
    ........
   }
});


text:
Q: What is the probability that if n =39 a randomly chosen array element is in A[$\lfloor n/2 \rfloor$], A[$\lfloor n/2 \rfloor$ + 1], . . . , A[n]?
"A sample space is the set of all possible outcomes of a random process or experiment. An event is a subset of a sample space"
   For any finite set A, N(A) denotes the number of elements in A.

Suppose $A[1], A[2], A[3], . . . , A[n]$ is a one-dimensional
array and $n ≥ 50$.
a. How many elements are in the array?
b. How many elements are in the subarray
$A[4], A[5], . . . , A[39]$?
c. If $3 ≤ m ≤ n$, what is the probability that a randomly
chosen array element is in the subarray
$A[3], A[4], . . . , A[m]$?
d. What is the probability that a randomly chosen array element
is in the subarray shown below if n = 39?
$A[\lfloor \frac n2 \rfloor], A[\lfloor \frac n2 \rfloor + 1], . . . , A[n]$
Source: Discrete Mathematics with Applications Susanna S. Epp
I'm not sure about my answer for d. Can you show how to solve the question d?
My answer
a. $n$
b. $36 $
c. $\frac {m-2}n$
d(edited).
$A[\lfloor \frac {39}{2} \rfloor]=A[19], A[\lfloor \frac {39}{2} \rfloor + 1]=A[20], . . . , A[39]$ has 39-18=21 elements
So $\frac {21}{39}$

A: I too think you might have made a mistake. Firstly, there is no $m$ or infact, no variable in the question.. unless the question was -
What is the probability that a randomly chosen array element is in the subarray shown below if $m = 39$?
$A[\lfloor \frac m2], A[⌊\frac m2⌋ + 1], . . . , A[m]$
If so, then the answer would be-
$⌊\frac m2⌋= 19$ and so, there are $21$ elements.
The probability would then be $\frac {21}n$
If the original question is right though, then the answer would be -
$\frac {21}{39}$  putting $n=39$ above.


text:
Q: Sorting ArrayList With Firebase I have an array list called myfoods. In a for loop , I retrieve data from firebase and place it into the array list. Then i display everything it in a recyclerview.
for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {

    String name = ing.child("productName").getValue(String.class);
    String quantity = ing.child("quantity").getValue(String.class);
    String productId = ing.child("productId").getValue(String.class);

    AllOrders order = new AllOrders(productId, name, quantity);

    myfoods.add(order);

}

This is my recycler view.

What I want to achieve is , group the quantity of the foods which have the same productId. Take an example for the 1st and 2nd item in the recyclerview.They have the same productId and I want to merge them into one and adding their quantity all along. Any help on how to do that ? I tried some if else statement but in vain.

A: You can create a HashMp<String, AllOrders> containing productId as key and AllOrders as value so use
Map<String,AllOrder> map = new HashMap<>();
for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {

    String name = ing.child("productName").getValue(String.class);
    String quantity = ing.child("quantity").getValue(String.class);
    String productId = ing.child("productId").getValue(String.class);

    AllOrders order = map.get(productId);
    if(order == null){
        // add new item, no order exists with productId
        order = new AllOrders(productId, name, quantity);
        map.put(productId,order);
    }else{ // change the value of already existing item
        String oldQ = order.getQuantity();
        int newQ = Integer.parseInt(order.getQuantity()) + Integer.parseInt(quantity);
        oder.setQuantity(String.valueOf(newQ));
    }

}

// whenever you need a list
myfoods = new ArrayList<>(map.values());

I believe you can simply get your AllOrder object directly as
Map<String,AllOrder> map = new HashMap<>();
for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {

    // String name = ing.child("productName").getValue(String.class);
    // String quantity = ing.child("quantity").getValue(String.class);
    // String productId = ing.child("productId").getValue(String.class);
    AllOrder entry = ing.getValue(AllOrder.class);
    AllOrders order = map.get(entry.gerProductId());
    if(order == null){
        // add new item, no order exists with productId
        map.put(productId,entry);
    }else{ // change the value of already existing item
        String oldQ = order.getQuantity();
        int newQ = Integer.parseInt(order.getQuantity()) + Integer.parseInt(quantity);
        oder.setQuantity(String.valueOf(newQ));
    }

}

// whenever you need a list
myfoods = new ArrayList<>(map.values());

A: Try this:
 mDatabase.orderByKey().equalTo("value", "key")

you could change orderByKey() to orderByChild("child")
I haven't tried, but I think it will work for you.
Give it a try :))
Goodluck !
Update:
 String lastChild = "";
 mDatabase.orderByChild("productId").addChildEventListener(){

 @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot,
          @Nullable String s) {
         Object yourObject = dataSnapshot.getValue(Object.class);
         if(!TextUtils.equal(yourObject.productId(), lastChild )) {
           lastChild = yourObject.productId();
         } else {
            // Merge here
         }
    }

A: query ordered by productId ...and then sort into an ArrayList (in order to group):
final ArrayList<Product> orderItems = new ArrayList<Product>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.child("foods").orderByChild("productId");

query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            for (DataSnapshot product : dataSnapshot.getChildren()) {

                String name = product.child("productName").getValue(String.class);
                Integer quantity = product.child("quantity").getValue(Integer.class);
                Integer productId = product.child("productId").getValue(Integer.class);

                /* room for improvement here, just to provide an idea */
                if(orderItems.get(productId) == null) {
                    /* add the product */
                    orderItems.set((int) productId), product.getValue(Product.class))
                } else {
                    /* increment the product's quantity */
                    orderItems.get(productId)).incrementQuantityBy(quantity);
                }
            }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

... while it might be rather practical, to already group items with the same productId, before even adding or updating them into Firebase - because noSQL features no SUM() & GROUP BY domain aggregate functions, which just leads to some more records and the calculation per order item.


text:
Q: Wrong behavior with big files and nanoHTTPD and WebView on Android I'm using nanohttpd on Android to serve content to my WebView (The ContentProvider approach was broken in KitKat version, THANKS SO MUCH GOOGLE !!!), my issue comes when I try to send a MP4 file as response, when the fisrt request comes a return the following as response :
byte[] loData = [VIDEO_BYTES_IN MEMORY];
ByteArrayInputStream loBAIS = new ByteArrayInputStream(loData);
loResponse = new Response(Response.Status.OK, loMIME, loBAIS);
loResponse.addHeader("Content-Type", loMIME); // "video/mp4"
loResponse.addHeader("Content-Length", "" + loLength); // 21784780 bytes in total <-- NOTICE THIS !!!
loResponse.addHeader("Accept-Ranges", "bytes");
loResponse.addHeader("ETag", loETag);

When the second request comes, the header looks like this :
Host: 127.0.0.1:8080
Connection: keep-alive
User-Agent: stagefright/1.2 (Linux;Android 4.4.4)
Accept-Encoding: gzip,deflate
Range: bytes=21389346-

Now here the issue is that the range from the second request from the client is invalid as far as I can tell. Why I'm not receiving a range like :
Range: bytes=0-4999

After this, I received one more request as the second one, but I never get the "Starter" one with the range starting at 0. Anybody have a clue, comment, fix, path, workaround about this behavior?
More info :
First request, when page is loading :
Host: 127.0.0.1:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Linux; Android 4.4.4; GT-N5110 Build/KTU84Q) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Safari/537.36
Accept: */*
Referer: http://127.0.0.1:8080/html/index.html
Accept-Encoding: gzip,deflate
Accept-Language: es-US,en-US;q=0.8
X-Requested-With: com.myapp.browser

Second request, page is still loading :
Host: 127.0.0.1:8080
Connection: keep-alive
User-Agent: stagefright/1.2 (Linux;Android 4.4.4)
Accept-Encoding: gzip,deflate

Third request, page is still loading, the Range header appears :
Host: 127.0.0.1:8080
Connection: keep-alive
User-Agent: stagefright/1.2 (Linux;Android 4.4.4)
Accept-Encoding: gzip,deflate
Range: bytes=21389346-

Once the page is loaded, if I try to play the video, the following request are get.
First request :
Host: 127.0.0.1:8080
Connection: keep-alive
User-Agent: stagefright/1.2 (Linux;Android 4.4.4)
Accept-Encoding: gzip,deflate

Second request :
Host: 127.0.0.1:8080
Connection: keep-alive
User-Agent: stagefright/1.2 (Linux;Android 4.4.4)
Accept-Encoding: gzip,deflate

Third request :
Host: 127.0.0.1:8080
Connection: keep-alive
User-Agent: stagefright/1.2 (Linux;Android 4.4.4)
Accept-Encoding: gzip,deflate
Range: bytes=21389346-

Fourth (and last) request :
Host: 127.0.0.1:8080
Connection: keep-alive
User-Agent: stagefright/1.2 (Linux;Android 4.4.4)
Accept-Encoding: gzip,deflate
Range: bytes=21389346-

After this, the audio can be heard but not video, logcat shows the following errors :
09-16 13:34:41.565    2036-2702/com.myapp.browser W/System.err﹕ java.net.SocketException: sendto failed: ECONNRESET (Connection reset by peer)
09-16 13:34:41.570    2036-2702/com.myapp.browser W/System.err﹕ at libcore.io.IoBridge.maybeThrowAfterSendto(IoBridge.java:499)
09-16 13:34:41.575    2036-2702/com.myapp.browser W/System.err﹕ at libcore.io.IoBridge.sendto(IoBridge.java:468)
09-16 13:34:41.575    2036-2702/com.myapp.browser W/System.err﹕ at java.net.PlainSocketImpl.write(PlainSocketImpl.java:508)
09-16 13:34:41.575    2036-2702/com.myapp.browser W/System.err﹕ at java.net.PlainSocketImpl.access$100(PlainSocketImpl.java:46)
09-16 13:34:41.580    2036-2702/com.myapp.browser W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketOutputStream.write(PlainSocketImpl.java:270)
09-16 13:34:41.580    2036-2702/com.myapp.browser W/System.err﹕ at org.apache.http.impl.io.AbstractSessionOutputBuffer.write(AbstractSessionOutputBuffer.java:109)
09-16 13:34:41.585    2036-2702/com.myapp.browser W/System.err﹕ at org.apache.http.impl.io.IdentityOutputStream.write(IdentityOutputStream.java:86)
09-16 13:34:41.585    2036-2702/com.myapp.browser W/System.err﹕ at java.io.BufferedOutputStream.write(BufferedOutputStream.java:131)
09-16 13:34:41.590    2036-2702/com.myapp.browser W/System.err﹕ at com.myapp.browser.ContentServer.ContentHandler$3.writeTo(ContentHandler.java:165)
09-16 13:34:41.590    2036-2702/com.myapp.browser W/System.err﹕ at org.apache.http.entity.EntityTemplate.writeTo(EntityTemplate.java:76)
09-16 13:34:41.595    2036-2702/com.myapp.browser W/System.err﹕ at org.apache.http.impl.entity.EntitySerializer.serialize(EntitySerializer.java:97)
09-16 13:34:41.595    2036-2702/com.myapp.browser W/System.err﹕ at org.apache.http.impl.AbstractHttpServerConnection.sendResponseEntity(AbstractHttpServerConnection.java:182)
09-16 13:34:41.600    2036-2702/com.myapp.browser W/System.err﹕ at org.apache.http.protocol.HttpService.handleRequest(HttpService.java:209)
09-16 13:34:41.600    2036-2702/com.myapp.browser W/System.err﹕ at com.myapp.browser.ContentServer.ContentServer.run(ContentServer.java:89)
09-16 13:34:41.605    2036-2702/com.myapp.browser W/System.err﹕ Caused by: libcore.io.ErrnoException: sendto failed: ECONNRESET (Connection reset by peer)
09-16 13:34:41.610    2036-2702/com.myapp.browser W/System.err﹕ at libcore.io.Posix.sendtoBytes(Native Method)
09-16 13:34:41.615    2036-2702/com.myapp.browser W/System.err﹕ at libcore.io.Posix.sendto(Posix.java:156)
09-16 13:34:41.615    2036-2702/com.myapp.browser W/System.err﹕ at libcore.io.BlockGuardOs.sendto(BlockGuardOs.java:177)
09-16 13:34:41.620    2036-2702/com.myapp.browser W/System.err﹕ at libcore.io.IoBridge.sendto(IoBridge.java:466)
09-16 13:34:41.620    2036-2702/com.myapp.browser W/System.err﹕ ... 12 more
09-16 13:34:41.635    2036-2702/com.myapp.browser D/ContentHandler﹕ Handling content request. video/shared-culture.mp4
09-16 13:34:41.890    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5942)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUseProgram: program not linked
09-16 13:34:41.890    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type
09-16 13:34:41.890    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniform1iv: wrong uniform function for type
09-16 13:34:45.760    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5942)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUseProgram: program not linked
09-16 13:34:45.760    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type
09-16 13:34:45.760    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniform1iv: wrong uniform function for type
09-16 13:34:45.795    2036-2036/com.myapp.browser I/Choreographer﹕ Skipped 60 frames!  The application may be doing too much work on its main thread.
09-16 13:34:46.020    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5942)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUseProgram: program not linked
09-16 13:34:46.020    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type
09-16 13:34:46.020    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniform1iv: wrong uniform function for type
09-16 13:34:46.105    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5942)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUseProgram: program not linked
09-16 13:34:46.105    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type
09-16 13:34:46.105    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniform1iv: wrong uniform function for type
09-16 13:34:46.200    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5942)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUseProgram: program not linked
09-16 13:34:46.200    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type
09-16 13:34:46.200    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniform1iv: wrong uniform function for type
09-16 13:34:46.380    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5942)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUseProgram: program not linked
09-16 13:34:46.380    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type
09-16 13:34:46.380    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniform1iv: wrong uniform function for type
09-16 13:34:46.630    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5942)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUseProgram: program not linked
09-16 13:34:46.630    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type
09-16 13:34:46.630    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniform1iv: wrong uniform function for type
09-16 13:34:46.900    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5942)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUseProgram: program not linked
09-16 13:34:46.900    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type
09-16 13:34:46.900    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniform1iv: wrong uniform function for type
09-16 13:34:47.155    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5942)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUseProgram: program not linked
09-16 13:34:47.155    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniformMatrix4fv: wrong uniform function for type
09-16 13:34:47.155    2036-2036/com.myapp.browser E/chromium﹕ [ERROR:gles2_cmd_decoder.cc(5718)] [.Compositor-Onscreen-0x45422790]GL ERROR :GL_INVALID_OPERATION : glUniform1iv: wrong uniform function for type
09-16 13:34:47.215    2036-2036/com.myapp.browser E/MediaPlayer﹕ Should have subtitle controller already set


text: Q: Javascript self-invoking function and ajax callback I am a bit confused by the following. I am working on the asp.net mvc. I have an ajax call to return to refresh a partial view which contains a self-executing js function. I also have a callback function on the ajax done event. I was intrigued by the fact that the self-executing js function is only fired on the first time when the partial view is loaded. However, when the ajax call complete, the callback function would be triggered but the self-executing function was not. My concept make me believe that the self-executing function should be parsed by the DOM and executed immediately when the partial view has rendered. Does anyone encounter this situation? What is the cause of the problem? Thanks.


text:
Q: How to force virtualenv to install latest setuptools and pip from pypi? Is it possible to force virtualenv to use the latest setuptools and pip available from pypi?  Essentially, I'm looking for the opposite of the --never-download flag.
Currently, when I make a new virtualenv, it uses the local (old) versions that come bundled with virtualenv.
$ v.mk testvenv
New python executable in testvenv/bin/python
Installing setuptools............done.
Installing pip...............done.
$ pip show setuptools
---
Name: setuptools
Version: 0.6c11
Location: /Users/cwilson/.virtualenvs/testvenv/lib/python2.7/site-packages/setuptools-0.6c11-py2.7.egg
Requires:
$ pip search setuptools
[...]
setuptools                - Easily download, build, install, upgrade, and
                            uninstall Python packages
INSTALLED: 0.6c11
LATEST:    0.7.2
[...]

A: You can upgrade pip after installing your virtualenv by using pip install -U pip.
I'm sure you could write a bootstrap-script to automate this step.

A: I needed the latest setuptools library, and the --extra-search-dir flag wasn't working for me (even though it's been fixed apparently).
However, making a virtualenv without setuptools and then installing directly from PyPi worked great.
E.g. to set up a virtualenv called test:
virtualenv --no-setuptools test
source test/bin/activate
wget https://bootstrap.pypa.io/ez_setup.py -O - | python
easy_install pip

Testing with
python -c 'import setuptools; print setuptools.__version__'

shows the right version.

A: I ran into the same problem, and I fixed it by upgrading setuptools.
If env is your virtual env, run the following:
$ env/bin/pip install --upgrade setuptools

A: It's not supported for security reasons.

Using virtualenv.py as an isolated script (i.e. without an associated
  virtualenv_support directory) is no longer supported for security
  reasons and will fail with an error. Along with this, --never-download
  is now always pinned to True, and is only being maintained in the
  short term for backward compatibility (Pull #412).

I can't use the --extra-search-dir option either because it's currently broken https://github.com/pypa/virtualenv/issues/327
Looks like the only option is to simply wait for the virtualenv maintainers to update the bundled packages?

A: Building on ematsen's excellent answer I made a bash script that works with virtualenvwrapper
#!/bin/bash
source `which virtualenvwrapper.sh`
mkvirtualenv --no-setuptools $1
wget https://bootstrap.pypa.io/ez_setup.py -O - | python
rm setuptools-*.zip
easy_install pip

# for python version < 2.7.9
# https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
pip install urllib3[secure]


text:
Q: MVVM Windows Phone 8 - adding a collection of pushpins to a map Here is the XAML code:
<maps:Map x:Name="NearbyMap"
                  Center="{Binding MapCenter, Mode=TwoWay}"
                  ZoomLevel="{Binding ZoomLevel, Mode=TwoWay}"
              >
        <maptk:MapExtensions.Children>
            <maptk:MapItemsControl Name="StoresMapItemsControl" ItemsSource="{Binding Treks}">
                <maptk:MapItemsControl.ItemTemplate>
                    <DataTemplate>
                        <maptk:Pushpin x:Name="RouteDirectionsPushPin" GeoCoordinate="{Binding Location}" Visibility="Visible" Content="test"/>
                    </DataTemplate>
                </maptk:MapItemsControl.ItemTemplate>
            </maptk:MapItemsControl>
            <maptk:UserLocationMarker x:Name="UserLocationMarker" Visibility="Visible" GeoCoordinate="{Binding MyLocation}"/>
        </maptk:MapExtensions.Children>
    </maps:Map>

xmlns:maps="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps"
xmlns:maptk="clr-namespace:Microsoft.Phone.Maps.Toolkit;assembly=Microsoft.Phone.Controls.Toolkit"

PushPinModel has an attribute Location which is a GeoCoordinate. Treks is an ObservableCollection<PushPinModel>. I run this code and only the UserLocationMarker is displayed, which is my current location.

A: The MapItemsControl is currently not yet MVVM bindable ( what I am aware off ).
So best way is to set it's ItemsSource in the code behind of your view.
You can still use the collection defined in your ViewModel though!
Options are:

*

*through mvvm messaging pass along the collection from the viewmodel to the code behind of the view

*use the datacontext of the view to access the collection, something like this: this.StoresMapItemsControl.ItemsSource = ServiceLocator.Current.GetInstance<MainViewModel>().Locations;

A: I finally make it work by using dependency property. I added a new class:
public static class MapPushPinDependency
{
    public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.RegisterAttached(
             "ItemsSource", typeof(IEnumerable), typeof(MapPushPinDependency),
             new PropertyMetadata(OnPushPinPropertyChanged));

    private static void OnPushPinPropertyChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
    {
        UIElement uie = (UIElement)d;
        var pushpin = MapExtensions.GetChildren((Map)uie).OfType<MapItemsControl>().FirstOrDefault();
        pushpin.ItemsSource = (IEnumerable)e.NewValue;
    }

    #region Getters and Setters

    public static IEnumerable GetItemsSource(DependencyObject obj)
    {
        return (IEnumerable)obj.GetValue(ItemsSourceProperty);
    }

    public static void SetItemsSource(DependencyObject obj, IEnumerable value)
    {
        obj.SetValue(ItemsSourceProperty, value);
    }

    #endregion
}

And in the .xaml file I have added
xmlns:dp="clr-namespace:Treks.App.Util.DependencyProperties"

and now the .xaml file looks like this:
<maps:Map x:Name="NearbyMap"
                  Center="{Binding MapCenter, Mode=TwoWay}"
                  ZoomLevel="{Binding ZoomLevel, Mode=TwoWay}"
                  dp:MapPushPinDependency.ItemsSource="{Binding Path=Treks}"
              >
        <maptk:MapExtensions.Children>
            <maptk:MapItemsControl Name="StoresMapItemsControl">
                <maptk:MapItemsControl.ItemTemplate>
                    <DataTemplate>
                        <maptk:Pushpin x:Name="PushPins" GeoCoordinate="{Binding Location}" Visibility="Visible" Content="test"/>
                    </DataTemplate>
                </maptk:MapItemsControl.ItemTemplate>
            </maptk:MapItemsControl>
            <maptk:UserLocationMarker x:Name="UserLocationMarker" Visibility="Visible" GeoCoordinate="{Binding MyLocation}"/>
        </maptk:MapExtensions.Children>
    </maps:Map>

Now all the pushpins are correctly rendered.


text:
Q: PowerShell and MySQL - Leave connection open for multiple queries? I am using the MySQL connector with PowerShell and I have the need to do a query, then scrub the data a little bit and then dump the remainder to another table on the same MySQL DB.  How could I leave the connection open to make this all run a bit faster?
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
      $Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
      $Connection.ConnectionString = $ConnectionString
      $Connection.Open()

      $Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
      $DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
      $DataSet = New-Object System.Data.DataSet
      $RecordCount = $dataAdapter.Fill($dataSet, "data")
      return $DataSet.Tables[0]

A: Create the connection object in the function that calls this function.  The called function will inherit whatever objects the calling function is maintaining, so $Connection will be valid in the called function.
function RunMe(){
    [void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
    $Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
    $Connection.ConnectionString = $ConnectionString
    $Connection.Open()

    # Call the function that executes the MySQL code
    ExecuteMySQL

    # If needed, call another function that executes the MySQL code
    ExecuteSomeOtherMySQL

    # Close the connection after all MySQL operations are complete
    $Connection.Close()
}

function ExecuteMySQL(){
    $Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
    $DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
    $DataSet = New-Object System.Data.DataSet
    $RecordCount = $dataAdapter.Fill($dataSet, "data")
    return $DataSet.Tables[0]
}


text:
Q: Modify security.enterprise_roots.enabled (or other about:config) in nodejs with selenium-webdriver using geckodriver For my automation testing in NodeJS, I have the following script that creates a new instance of firefox and runs my script there
 const firefox = require('selenium-webdriver/firefox');

 let options = new firefox.Options().setBinary(os.homedir() + '/AppData/Local/Mozilla Firefox/firefox.exe');

 let driver = new webDr.Builder()
      .forBrowser('firefox').setFirefoxOptions(options).build();

However, the page I am automating needs an additional requirement... I need to set security.enterprise_roots.enabled to "true" (located in about:config)

I have changed the setting on my non-automated firefox browser. However, it seems that whenever I run the code above the driver reverts it back to "false".
How can I change this programmatically?
I saw this answer but it is in Python. How do you write the same code in NodeJS with selenium-webdriver?

A: The answer for me was that I had to use a different profile instead.
Before building the automation, I set .Options().setProfile() as follows:
let options = new firefox.Options().setBinary(os.homedir() +
 '/AppData/Local/Mozilla Firefox/firefox.exe').setProfile(os.homedir() +
 '/AppData/Roaming/Mozilla/Firefox/Profiles/(your profile.. it's a folder)');

 let driver = new webDr.Builder().forBrowser('firefox').setFirefoxOptions(options).build();

This would run my firefox with the current settings I have with the profile, which includes security.enterprise_roots.enabled = true
 (or other about:config settings)


text:
Q: Java Spring - Show or list all properties in application.yml Is there a way to list all of the parameters that exist in an application.yml properties file?
If I have these properties, can I list them similar to the display below?
application.yml
parentProp1:
  childProp1: childProp1Value1
  childProp2: childProp1Value2
  childProp3: childProp1Value3

parentProp2:
  childProp1: childProp1Value1
  childProp2: childProp1Value2
  childProp3: childProp1Value3

Display like this:
parentProp1:childProp1:childProp1Value1
parentProp1:childProp2:childProp1Value2
parentProp1:childProp3:childProp1Value3

parentProp2:childProp1:childProp1Value1
parentProp2:childProp2:childProp1Value2
parentProp2:childProp3:childProp1Value3

Note: I can access the properties using @Value or environment.GetProperty, that part works fine, but is there a way, in Java, to iterate over all of the porperties in the application.yml file?


text:
Q: Scoket.IO v1.0.x Token based auth -- can't pass token? I am using this tutorial to get the basics of a token-based auth system in place. Here is the code I'm using:
In app.html:
var socket = io('', {
  // originally I thought the $.param might've been a problem, so I hard coded a token instead
  // query: $.param({token: 'i271az2Z0PMjhd6w0rX019g0iS7c2q4R'})
  query: "token=i271az2Z0PMjhd6w0rX019g0iS7c2q4R"
});

In index.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var tokens = [
  'i271az2Z0PMjhd6w0rX019g0iS7c2q4R',
  'oWD4sh1eU2Yhn95C05t2YKrKMVWoAFAk'
];

io.set('authorization', function(handshakeData, callback) {

    console.log(handshakeData.query);

    // Some basic validation to make sure a token was passed
    if ( handshakeData.query.token === undefined || handshakeData.query.token.length === 0 ) {
        console.log('No token')
        return false;
    }

    // Loop through the valid tokens, to validate the token passed
    var validated = false;
    for ( var key in tokens ) {
        if ( key == handshakeData.query.token ) {
            validated = true;
            break;
        }
    }

    // If valid, continue to callback the next function
    if ( validated ) {
        console.log('Good token');
        return callback(null, true);
    } else {
        console.log('Bad token');
        return false;
    }
});

io.on('connection', function(socket){
    console.log('connection ' + socket.id);
});

But, when I navigate to my server, I'm getting console errors:
if ( handshakeData.query.token === undefined || handshakeData.query.token.
                            ^
TypeError: Cannot read property 'token' of undefined
....

And the console.log(handshakeData.query); returns undefined.
Any ideas on what I'm missing?

A: For v1.0.x
After some tinkering and reading through the tangled web that is socket.io documentation, I came up with the following solution:
app.html:
// in version 1.0 the first param is the options object
var socket = io({
    query: $.param({token: 'i271az2Z0PMjhd6w0rX019g0iS7c2q4R'})
});

Index.js:
// io.use instead of io.set
io.use(function(socket, next) {
    var handshakeData = socket.request;

    // "query" lives in _query
    var query = handshakeData._query

    if ( query.token === undefined || query.token.length === 0 ) {
        console.log('No token')
        return false;
    }

    // the for loop was returning the array key and was
    // comparing that to the token val, so I fixed that
    var validated = false;
    for ( var key in tokens ) {
        console.log(tokens[key]);
        if ( tokens[key] == query.token ) {
            validated = true;
            break;
        }
    }

    // This now returns next() if true and nothing if false
    if (validated) {
        next();
    }
});

A: I am assuming you are using the new socket.io v 1.0 which is not what the tutorial was written for.
I followed the same tutorial and my code was identical to yours and ran without error.
You can print out the entire handshake data to the console and it should look something like this:
    { headers:
   { host: '_yourip/_yourPort',
     connection: 'keep-alive',
     'cache-control': 'max-age=0',
     origin: 'http://localhost:8080',
     accept: '*/*',
     referer: 'http://localhost:8080/',
     'accept-encoding': 'gzip,deflate,sdch',
     'accept-language': 'en-US,en;q=0.8' },
  address: { address: '_ipAdress', port: _yourPort },
  time: 'Thu May 29 2014 16:13:51 GMT-0600 (MDT)',
  query: { token: 'i271az2Z0PMjhd6w0rX019g0iS7c2q4R', t: '1401401631469' },
  url: '/socket.io/1/?token= i271az2Z0PMjhd6w0rX019g0iS7c2q4R&t=1401401631469',
  xdomain: true,
  secure: undefined,
  issued: 1401401631471 }

If the query is not set it will appear there as query:{} (in the previous socket.io)
Edit: It seems you have figured it out. If you wish to follow the tutorial in the version it was written for you can add
socket.io : 0.9.*

to the dependencies in your package.json, but socket.io's website is overhauled for the new version.


text:
Q: Excel Copy Paste Way in Python I have a data frame as below
df = pd.DataFrame([[3,2,1],[4,5,6],[10,20,30]], columns = ['A','B','C'])

    A   B   C
0   3   2   1
1   4   5   6
2  10  20  30

Is there any way in python to mimic copy and paste function in excel? For example I want to copy paste row 0 column A and B and paste them into row 0 column B and C, such that it will become
    A   B   C
0   3   3   2
1   4   5   6
2  10  20  30

In a small data frame, I can use:
df.loc[0,'C'] = df.loc[0,'B']
df.loc[0,'B'] = df.loc[0,'A']

But my original data frame is sizable and I prefer not to do this one element by one element.
I was also trying to do:
df.loc[0,['A','B']] = df.loc[0,['B','C']]

But my data in row 0 column A becomes NaN.
So is there a way of doing things similar like doing copy paste in excel in python (simply block a range of data, copy them and paste them on top of another existing data)? Thanks

A: anky_91's answer
df.loc[0, ['B', 'C']] = df.loc[0, ['A', 'B']].to_numpy()

shift
There are many ways you can use shift. This is just one.
df.update(df.shift(axis=1)[['B', 'C']])

For reasons that I'm not happy about, you can provide a fill_value to shift to preserve the integer dtype
df.update(df.shift(axis=1, fill_value=0)[['B', 'C']])

A: This mostly feels like a bad idea, but if it's what you really want to do, you can use .iloc to address columns by number and just shift them:
In [56]: df.iloc[0, 1:] = df.iloc[0, :-1].values

In [57]: df
Out[57]:
    A   B   C
0   3   3   2
1   4   5   6
2  10  20  30


text:
Q: Make popup have smart positioning I am working on a piece of legacy code for a table. In certain cells, I'm adding a notice icon. When you hover over the icon a  is made visible displaying some information. I would like to be able to make this  smart about its positioning but can't figure out a good method. I can statically position it but depending on which cell in the table it is in it gets lost against the edge of the page. I have done a JsFiddle here demonstrating the issue. Unfortunately, I am not allowed to use anything but HTML, CSS and vanilla JS.
The title attribute to most tags is pretty smart about its position. I have added a title to one of the cells in the table in the jsFiddle (cell containing "Hello"). Is there any way to make my span exhibit the same smart behaviour?

A: A pop-up can be added before any element by putting the popup html code inside a 'div' with 'position:absolute; overflow:visible; width:0; height:0'.
When these events: 'onmouseenter', 'onmouseleave' are fired on the element, just toggle the popup css attribute 'display' between 'none' and 'block' of the element.
Example on jsfiddle:
https://jsfiddle.net/johnlowvale/mfLhw266/
HTML and JS:

Some content

Some link

CSS:
.popup-holder {
  position: absolute;
  overflow: visible;
  width: 0;
  height: 0;
}

.popup {
  background-color: white;
  border: 1px solid black;
  padding: 10px;
  border-radius: 10px;
  position: relative;
  top: 20px;
  width: 300px;
  display: none;
}


text:
Q: Skin Detection and Background Subtraction in Python cv2 For the past couple of days, I've been working on a gesture recognition program using OpenCV Python.  Ideally, I'd like to have a system like the one shown in this video.  I've read through the algorithm described in the video description, and I understand just about all of it.  However, I have been having trouble replicating his success in background subtraction and skin tone detection.  All of my attempts have ended up very noisy and/or very lighting-dependent, both of which render my code useless for the time being.
I have tried the following:

*

*BackgroundSubtractorMOG and BackgroundSubtractorMOG2 applied to color frame

*Split image into Y Cr Cb, applied MOG or MOG2 to each before recombining into a single image

*Filter range to remove colors that aren't skin tones (applied to color image)

So far, I have not had success.  I have been able to pick out some contours, but these have been noisy and unstable (come and go depending on the frame).  Is their another approach I should be using?

A: I have written a fingerspelling interpreter application, so I've encountered many of the robustness issues you're facing.  After several weeks of experimentation, I settled on a solution that incorporated a few different approaches, but the most important approach employed was color-based segmentation.
Color-based (skin tone) segmentation can be very powerful, but a simplistic implementation is bound to lack the robustness you're looking for.  First of all, everyone's skin color is different.  So it's important to identify the baseline skin color through some other mechanism.  One approach is to use a face detector (such as a cascade classifier) to find the subject's face, and then "tune" the filter ranges accordingly.
I personally used a cascade classifier to first find the closed fist shape, and then I normalized and differenced the HSV histograms between 1) a tight bounding box only including the fist and 2) the entire image.  Then I set up a lookup table (LUT) mapping each value for each channel to a value between 0 and 255 representing the probability that the pixel represents skin.
In my experience, the most important factor that improved the performance of my hand tracking logic was when I struck on the idea of not throwing away information.  You will be tempted to simply threshold using some optimal ranges in order to generate a binary image, but there is value in knowing that one pixel has a 40% chance of being skin and another has a 60% chance.  Once you threshold, all you have is a 1 and a 0.
Of course, if you intend to use contour-based classification of poses, it may be necessary to threshold at some point.  But if you really want to build robust gesture recognition software, you may want to investigate using a Convolutional Neural Net (CNN) to perform the classification.  Prediction can be done very quickly, and it's very robust to background noise, translation, etc...  Hope this helps!
EDIT: Let me clarify my comments about "normalizing and differencing the HSV histograms".  First of all, the rationale for doing this is to be able to make use of OpenCV's LUT (lookup table) rather than using range-based thresholding.  LUT is very efficient, and is more flexible than range-based thresholding.  For example, suppose the hue that you want includes values in two separate ranges (e.g.: 0-30 and 150-180).  A LUT-based approach easily deals with that since each individual value can be mapped independently.
So once you establish the LUT, you only need to run LUT on the HSV image for each frame.  It's a very efficient solution.
In my case, to build the LUT, I took the following steps:

*

*Convert to HSV color space.

*Get the ROI of the tight bounding box around the fist.

*Build histograms for each channel for both the ROI and the entire image.

*Scale down (normalize) the full image channel histograms so that scale matches that of the ROI histograms (i.e.: multiply each full image histogram by ROI_area/full_image_area).

*Subtract (difference) the full image histograms from the ROI histograms.  (Entries with large positive values will correspond to channel values commonly found in the ROI, but not the full image.)

*I then smooth the difference histograms to reduce noise and "overfitting".

*Finally, I normalize the difference histograms to values between 0.0 and 1.0 using OpenCV's normalize function with NORM_MINMAX.

*The difference histograms can then just be merged together to produce a 3-channel LUT.

I personally don't threshold the values after using the LUT.  Instead, I just use the resulting data to compute a "center of color mass" of sorts which I use to keep a ROI centered on the hand.  Then, I can send the same LUT-based values to a CNN for classification.
Note that while this approach works well for my purposes, if you do perform thresholding, it's still not going to be perfect; there will be some foreground detected as background and vice versa.  I incorporated some edge detection-based logic to help reduce false positives resulting from beige walls (a common failure mode in my house), but the reality is that if there's a truly robust way to cleanly segment a hand from the background that's truly robust to changing backgrounds and lighting conditions, I haven't found it.  So my recommendation is to take a cue from the visual cortex and allow information from higher levels of abstraction to help filter out the noise.  (In other words, investigate CNNs - they're truly remarkable.)

A: Background subtraction tends to leave a lot of ghost images.You should start with HSV based skin detection, to rule out the non skin regions. This will eliminate the need for background subtraction.
Then you can apply face detection to mask out your face, following which, when you're left with only the hand contours, you can use approxPolyDP() to get a simplified polygon. Computing the moments and convexity of this polygon will give you a base for gesture recognition


text:
Q: How to redirect ending URLS? I'm not quite sure what the terminology is but all I want to do is redirect URL's after mydomain.com like mydomain.com/todays-news.
How would I point this "todays-news" url to lets say a file within a directory like a portfolio?
Also what do you call this ending url? A sub domain?

A: SEF URL
Add this to your web_root/.htaccess
 RewriteEngine on
 RewriteBase /
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^todays-news/?$ /portfolio/some_file.php [NC,L]

rewriteRule will internally redirect  example.com/today-news  to example.com/portfolio/somefile


text:
Q: Can I stream music from my laptop to my iPod Touch over wifi? Rather than running a long cable from my Laptop to my stereo, I've been thinking for a while about getting one of those wireless devices that lets you transmit audio from your PC to a receiver plugged into the stereo.
Then I realised I already have hardware that can potentially do this - I have an iPod Touch, and a Wi-Fi network in the house.
So, is there some iPod Touch App that will let the iPod act as a Wi-Fi music receiver? And presumably, a corresponding piece of broadcast software for my (Windows Vista) Laptop?
edit: Bonus points for a solution that lets me stream all audio from the laptop, rather than just streaming music tracks.

A: You can use the Windows version of Airfoil to send any audio to an Airport Express connected to a stereo.  The page above claims it can do the same via an iPod Touch as well.  And you can try it for free.

A: You can also share your iTunes library on your Mac of PC and then stream your music from your computer to your iPod touch by selecting that shared iTunes library in the Music app on your iPod touch.
This solution doesn't require any extra software or app.

A: On the road I use the Simplify Media application to do this. It requires an application to be installed on both the computer and the iPod touch/iPhone. Once installed I can play almost any track from my desktop to my iPod touch.
However at my house the simplest solution I have found is to use an Airport Express. I use iTunes to manage my music and then choose to play it on the Airport Express which is connected to my stereo in the living room. I can then use my iPod touch as a remote for iTunes to control what plays.

A: You can use the wifi2hifi app to stream any audio from your Mac but not on your PC to your iOS device.


text:
Q: Allowing `sudo su` without password over Ubuntu This question is answered a number of times in the net, but none of those answer resulted useful in my case.
The problem
Accessing a remote machine using private key, I usually require root permissions, which imply writing a long password and is annoying.
For the purpose of having sudo su, I tried following steps:

*

*Ensure the line <user> ALL=(ALL) NOPASSWD: ALL is in /etc/sudoers

*Ensure the user is in sudo user group: $groups <user> ->  sudo

But trying sudo su will just prompt me for my own password: [sudo] password for <user>:
The question
How to have password-less sudo su?

A: I often place it below the line
# User privilege specification
root    ALL=(ALL:ALL) ALL
+++ myuser ALL=(ALL) NOPASSWD: ALL

The better way is to use an own file in /etc/sudoers.d with the line above.
If you would like to use the group policy, you need to modify the line for your group
# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) NOPASSWD: ALL

Otherwise the group policy will overwrite your user policy and you will be asked for the password.
And an other hint:
Please don't use "sudo su". Instead use sudo su - or sudo -i. This will unload your env and load the one of root, avoiding to use bad env variable from your account with root.

A: Your sudoers file has something that already grants you the ability to run sudo su (or possibly any commands), but does not include the NOPASSWD: option.
Ordering within the sudoers file is important: last match wins.
You can use sudo -l to list all the sudo Defaults options and all the allowed commands for your user account.


text:
Q: Почему после ввода числа, все остальное перестает работать? Появилась такая проблема, что после ввода числа все что идет после перестает работать. И никаких ошибок. Вот код и на скрине видно где ошибка
#include <stdio.h>
#include <string.h>

const int countWorkers = 1;
const int countProducts = 1;
const int countMagazin = 1;
const int countAllProducts = countProducts*countMagazin;

struct listWorkers{
    char surname[20];
    char name[20];
    char address[20];
    char date[20];
};

struct listProducts{
    int id;
    char name[20];
    int price;
    int count;
};

struct st_products{
    listProducts list[countProducts];
};

struct stMagazin{
    int id;
    char name[20];
    char type[20];
    char address[20];
    st_products products;
    listWorkers workers[countWorkers];
};

void output(struct stMagazin magazin);
void findChar(char [20], char [255]);
void findInt(int,int);
void hr(){
    printf("\n----------------------------------------------------------------------------------------\n");
}

int main()
{
    struct stMagazin magazin[countMagazin];
    for(int j=0;j<countMagazin;j++){

        printf("Products: \n");
        for(int i=0;i<countProducts;i++){
            magazin[j].products.list[i].id = i;
            printf("%d)",i+1);
            printf("name: ");scanf("%s",magazin[j].products.list[i].name);
            printf("price: ");scanf("%d",&magazin[j].products.list[i].price);
            printf("count: ");scanf("%d",&magazin[j].products.list[i].count);
        }

        output(magazin[j]);
    }

    hr();

    printf("Опции: \n");
    printf("1) Поиск по-символьному\n");
    printf("2) Поиск по-числовому\n");
    printf("3) Сортировать элементы структуры в возрастающем порядке\n");
    printf("4) Сортировать элементы структуры в убывающем порядке\n");
    printf("5) Вывести символьные поля в алфавитном порядке\n");
    hr();

    while(true){
        int n;
        scanf("%d",&n);
        switch(n){
            case 1:{
                char symbols[255]; char *str_p;
                printf("Ищем символ(ы): "); scanf("%s",symbols);
                for(int i=0;i<countMagazin;i++){
                  findChar(magazin[i].name,symbols);
                  findChar(magazin[i].type,symbols);
                  findChar(magazin[i].address,symbols);
                  for(int j=0;j<countProducts;j++){
                    findChar(magazin[i].products.list[j].name,symbols);
                  }
                  for(int j=0;j<countWorkers;j++){
                    findChar(magazin[i].workers[j].surname,symbols);
                    findChar(magazin[i].workers[j].name,symbols);
                    findChar(magazin[i].workers[j].address,symbols);
                    findChar(magazin[i].workers[j].date,symbols);
                  }
                }
              break;
            }
            case 2:{
                int k;
                printf("Ввести искомое число: ");
                scanf("%i",&k);
                printf("Цикл");
                for(int i=0;i<countMagazin;i++){
                    //printf("Hello\n");
                  for(int j=0;j<countProducts;j++){
                      printf("Hello");
                    findInt(magazin[i].products.list[j].price,k);
                    findInt(magazin[i].products.list[j].count,k);
                  }
                }
              break;
            }
            case 3:{

              break;
            }
            case 4:{

              break;
            }
            case 5:{

              break;
            }
        }
    }
    return 0;
}

void output(struct stMagazin magazin){
    printf("Products: \n");
    for(int i=0;i<countProducts;i++){
        printf("%d)",i+1);
        printf("Name: %s, ",magazin.products.list[i].name);
        printf("Price: %d, ",magazin.products.list[i].price);
        printf("Count: %d",magazin.products.list[i].count);
        printf("\n");
    }
}
void findChar(char myStr[20], char symbols[255]){
  char *str_p;
  str_p = strstr(myStr,symbols);
  if(str_p != NULL){
    printf("Совпадение найдено, %s\n",myStr);
  }
}
void findInt(int myInt, int k){
  printf("%d, %d",myInt,k);
  int intNumber, edNumber;
  while(myInt!=0){
    intNumber = myInt/10;
    edNumber = myInt%10;
  }
  if(intNumber == k || edNumber == k){
      printf("Совпадение найдено, %d",myInt);
    }

}

Скрин

A: У вас бесконечный цикл в функции findInt
  while (myInt != 0) {
    intNumber = myInt / 10;
    edNumber = myInt % 10;
  }

PS научитесь пользоваться дебаггером
PSS вывода не происходит из-за буферизации: для моментального вывода допишите \n


text:
Q: Execute specific test scenarios in a suite using Web driver I have a suite with more than 500 test scenarios written in Web driver. I am using TestNG framework to execute the test cases.
Could you please suggest me how to execute specific test cases from the suite like 31, 45, 68 etc?
Thank you

A: If you have prefaced all of your tests with @Test, then in Eclipse with TestNG plugin, you can right click on the method name, and run it as a TestNG Test.  You can also click on a class file, and only run that class.  However, if you want to run test X and test Y that are in different tests, you can press Run Configurations... and add which methods you want run.
If you don't have the TestNG plugin, you can write an XML file that has the classes, methods, groups, or suites you want to run.  It is described here


text:
Q: What this is parameter in the geo block in Nginx? In nginx, in geo module it has the following example
http://nginx.org/en/docs/http/ngx_http_geo_module.html
I am wondering what is this 0,2,1,1 numbers etc.. stated after the main addresses (values). what are the usage of them?
> geo $geo {
>     default        0;
>
>     127.0.0.1      2;
>     192.168.1.0/24 1;
>     10.1.0.0/16    1;
>
>     ::1            2;
>     2001:0db8::/32 1;
>}

A: 0, 1 and 2 are the values that the variable $geo takes when in use for that specific IP. Later in the documentation is't clearer
geo $country {
default        ZZ;
include        conf/geo.conf;
delete         127.0.0.0/16;
proxy          192.168.100.0/24;
proxy          2001:0db8::/32;

127.0.0.0/24   US;
127.0.0.1/32   RU;
10.1.0.0/16    RU;
192.168.1.0/24 UK;
}

Then you can use it as you wish, ie (devil if used only as example)
if ( $geo = 1 ) {
    return 403;
}