text:
Q: Content not being Posted properly? I am using simpleTest WebBrowser for DataScraping on this URL http://www.magicbricks.com/bricks/agentSearch.html.  But though everything seems right I always get the error City Field is required. I guess the problem might be with the fact that values in city field changes dynamically when value of State changes. Any solutions?  Here is my code.
<?php
require_once('simpletest/browser.php');

$browser = &new SimpleBrowser();
$browser->addHeader('User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0.2) Gecko/20100101 Firefox/6.0.2');
$browser->get('http://www.magicbricks.com/bricks/agentSearch.html');
$browser->setField('source','agentSearch');
$browser->setField('_transactionType','1');
$browser->setField('_propertyType','1');
$browser->setField('resultPerPage','50');
$browser->setField('agentSearchType','B');
$browser->setField('state','520');
$browser->setField('city','4320');
$browser->setField('keyword','');
$browser->setField('country','50');

print $browser->submitFormById('searchFormBean');
print $browser->getResponseCode()

?>

A: Here are some errors i noticed
Field Missing

*

*Missing agentSearchType field

*Missing transactionType  ( There is Both transactionType & _transactionType)

*missing propertyType ( There is both propertyType & _propertyType)

There are some header information you need to add such as

*

*Referer

*Cookie

A typical post test should come this format if you view the headers
        POST http://www.magicbricks.com/bricks/agentSearch.html HTTP/1.1
        Host: www.magicbricks.com
        Connection: keep-alive
        Content-Length: 173
        Cache-Control: max-age=0
        Origin: http://www.magicbricks.com
        User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
        Content-Type: application/x-www-form-urlencoded
        Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
        Referer: http://www.magicbricks.com/bricks/agentSearch.html
        Accept-Encoding: gzip,deflate,sdch
        Accept-Language: en-US,en;q=0.8
        Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
        Cookie: JSESSIONID=nF1UqV3DM2tZC42zByYm6Q**.MBAPP09; __utma=163479907.1423216630.1331970312.1331970312.1331970312.1; __utmb=163479907.1.10.1331970312; __utmc=163479907; __utmz=163479907.1331970312.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _mbRunstats=3k0ilrpcgprh4tea

        source=agentSearch&agentSearchType=B&country=51&state=601&city=8417&transactionType=11951&_transactionType=1&propertyType=10001&_propertyType=1&keyword=tesy&resultPerPage=50

I hope this helps
:D


text:
Q: Unable to pass a parameter from a closure to a function in Swift I recently started learning Swift and got a question about closure.
I tried to pass the parameter of driving to func travel and got an error message: Cannot convert value of type '()' to expected argument type '() -> String'
Can anyone kindly advise? Appreciate!
import UIKit

let driving = { (place: String) in
    print ("I'm going to \(place).")
}

func travel(action: () -> String) {
    print("I'm getting ready to go.")
    action()
    print("I arrived!")
}

travel(action: driving("London"))

A: driving is a closure of type (String) -> Void
driving("London") is a function call expression, calling that closure, passing it the argument "London". The result of this expression is the result of the closure, which is Void (a.k.a. the empty tuple, ()).
That () argument value isn't compatible with the parameter, which is expected to be () -> String.

A: driving is a closure, but driving("London") is a closure invocation that returns ().
If you need the closure to have the variable that holds the value "London", i.e. if you want closure to capture ("close") it, you can do it with a function:
func makeAction(place: String) -> () -> String {
   { "I'm going to \(place)." }
}

let drivingToLondon = makeAction(place: "London")

// drivingToLondon() will return "I'm going to London"

travel(action: drivingToLondon)

You might also want to update travel to print the return value of the closure, since it returns String:
func travel(action: () -> String) {
    print("I'm getting ready to go.")
    print(action())
    print("I arrived!")
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Arrange List with Total I created a list
t = Array[Subscript[a, ##] &, {2, 3, 4}]

whose result is

I would like to do a sum operation as follows

I used Total option, but I could not get it the way I wanted it.
Can you help me?

A: You need to use Map with Total to the correct level.  To find the level you can use TreeForm:
TreeForm[t]

From this you can see the levels of the expressions.  You are trying to total the second level down (the third row in the diagram, as the top expression is at level 0), which makes the level spec in the map Map[function, list, {2}].  Alternatively you can count upwards to the third level up - Map[function, list, {-3}].
So to get the correct result:
Map[function, list, {-3}]


text:
Q: node.js' express middleware does not return error on nodester My node app uses the express framework. I developed a middleware to check parameters but when an error is sent by the middleware it is not sent back in the response.
I only have this problem on nodester, on localhost it works as expected.
Here is an example of the controller action:
/*
 * Create a new user
 *
 */
app.post('/user/create', md.checkParams(["nickname", "email", "password"]), function(req, res){
  var email    = req.query.email;
  var nickname = req.query.nickname;
  var password = req.query.password;
  jsonObj = { "nickname" : nickname, "email" : email, "password" : password };

  // Save user in DB
  db.hmset("user:" +nickname, jsonObj, function(err1){
    if(!err1) {
      db.sadd("users","user:" + nickname, function(err2){
        if(err2){
          jsonObj = {"error" : "database error", "message" : "error adding object to set" };
        }
        h.respond(res, jsonObj);
      });
    } else {
      jsonObj = {"error" : "database error", "message" : "error creating hash for object" };
      h.respond(res, jsonObj);
    }
  });
});

The checkParams middleware is:
function checkParams(arr){
  return function(req, res, next) {
    // Make sure each param listed in arr is present in req.query
    var missing_params = [];
    for(var i=0;i<arr.length;i++){
      if(! eval("req.query." + arr[i])){
        missing_params.push(arr[i]);
      }
    }
    if(missing_params.length == 0){
      next();
    } else {
      next(JSON.stringify({ "error" : "query error", "message" : "Parameter(s) missing: " + missing_params.join(",") }));
    }
  }
}

For instance, if I use a
curl -XPOST 'http://HOST/users/create'

on localhost I get:
{"error":"query error","message":"Parameter(s) missing: nickname,email,password"}
on NODESTER I only got:
Internal Server Error

({"error":"query error","message":"Parameter(s) missing: nickname,email,password"} appears in the app log but not in the response)
Any idea what could be wrong ?
UPDATE
I found a workaround by issuing the following in the middleware when an error is supposed to be thrown:
res.writeHead(200, {'content-type': 'application/json'});
res.write("my error message");
res.end();

instead of
next("my error message);

it's working this way even if I'm not 100% sure this is best solution.

A: Look at your express configuration settings.
by default under "development" the server returns error details whereas under "deployment" it hides them.
Update
With regards to your proposed solution. I would recommend you call next with multiple non standard parameters i.e.
next("error", data)
And then have a global middleware in connect that acts as a global error handling mechanism where you write error data to the response in your own personal manner.
You may have some edge cases where the middlewares behave strangely. You'll have to look into how next works in detail.


text:
Q: An electrified comb can attract bits of paper but not a sheet of paper. Why? An electrified comb can attract bits of paper but not a sheet of paper. Why?
Does this indicate that electrostatic force is related to mass like Electrostatic force=ma?


text:
Q: Is it possible to mix in a trait to an already existing object?
Possible Duplicate:
scala and traits on object instances

Is it possible to mix in a trait to an already existing object ?
Something like:
val s = new MyClass
val sWithTrait = s with myTrait

The code above does not work, but maybe the syntax is wrong or it is not possible at all ?

A: Dynamic mixins are not possible in regular Scala, but I seem to remember that there was an attempt at a compiler plugin called Autoproxy that allowed something along these lines. Not sure about the state of it though.


text:
Q: Anyway to shorten this Python Caesar Cipher code into fewer lines? def encrypt(text, key, direction):
    if direction == 1: #The direction is either -1, or 1. If it is 1, it goes right. Otherwise, it will go left.
        emptys=''
        for x in text:
            b = ord(x) #b is the individual characters after the ord() function
            b+=key
            if b<=122:
                n = chr(b) #n is the converted letter of the encrypted ASCII number
                emptys+=n
            else:
                o=b-90
                q=chr(o)
                emptys+=q
        return emptys
    else:
        emptys=''
        for x in text:
            b = ord(x) #b is the individual characters after the ord() function
            b=b-key
            if b>=32:
                n = chr(b) #n is the converted letter of the encrypted ASCII number
                emptys+=n
            else:
                o=b+90
                q=chr(o)
                emptys+=q
        return emptys

A: Your code as written blithely translates alphabetic characters to non-alphabetic and vice versa (e.g. encrypt('abc', 25, 1) gets 'z!"'). So it's wrong by most definitions of the traditional Caesar cipher, which should only modify alphabetic characters, and should rotate them within the alphabet.
That said, getting it right is easier than you're making it. The best approach is to avoiding rolling your own rotation code. Python already provides a really nice way to do one-to-one character mappings, str.translate. For example:
from string import ascii_letters, ascii_uppercase, ascii_lowercase

def encrypt(text, key, direction):
    # direction == -1 is trivially converted to direction == 1 case
    if direction == -1:
        key = 26 - key

    # On Py2, you'd use the string module's string.maketrans instead of
    # str.maketrans
    trans = str.maketrans(ascii_letters, ascii_lowercase[key:] + ascii_lowercase[:key] + ascii_uppercase[key:] + ascii_uppercase[:key])

    return text.translate(trans)


text:
Q: Date order in bokeh plot with pandas dataframe I have a pandas dataframe with 4 different scores per day:
import pandas as pd
df = pd.DataFrame( {u'Date' : ['2014-08-15', '2014-08-16', '2014-08-17', '2014-08-18', '2014-08-19', '2014-08-20',
                               '2014-08-15', '2014-08-16', '2014-08-17', '2014-08-18', '2014-08-19', '2014-08-20',
                               '2014-08-15', '2014-08-16', '2014-08-17', '2014-08-18', '2014-08-19', '2014-08-20',
                               '2014-08-15', '2014-08-16', '2014-08-17', '2014-08-18', '2014-08-19', '2014-08-20'],
                    u'Score': [-0.13, -0.25, 0.1, -0.3, -0.1, 0.1,
                               -0.1, 0.1, -0.05, 0.2, -0.13, -0.25,
                               0.2, 0.5, 0.4, -0.2, -0.25, 0.1,
                               -0.3, 0.1, 0.25, 0.05, -0.05, 0.2]})
    df.Date = pd.to_datetime(df.Date,format='%Y-%m-%d')

I would like to plot the daily average of the score. I'm trying with:
from numpy import *
from bokeh.plotting import *
output_file('question.html')
figure(x_axis_type="datetime", plot_width=800, plot_height=500)
grouped = df.groupby("Date")
score = grouped["Score"]
avg = score.mean()
print dates
dates = asarray(grouped.groups.keys())
hold(True)
line(dates, avg, line_color="grey", line_width=8, line_join="round")
asterisk(dates, avg, line_color="black", size=15)
hold(False)

However, this code leads to a disordered dates array:
print dates
['2014-08-15T02:00:00.000000000+0200' '2014-08-16T02:00:00.000000000+0200'
 '2014-08-18T02:00:00.000000000+0200' '2014-08-19T02:00:00.000000000+0200'
 '2014-08-17T02:00:00.000000000+0200' '2014-08-20T02:00:00.000000000+0200']

and the line in the plot I obtain (see the image in this link) is accordingly wrong.
Sortering by date with:
df = df.sort(['Date'])

does not helps.
On the other hand, if I try to plot the same dataframe but of 4 days instead of 6:
df = pd.DataFrame( {u'Date' : ['2014-08-15', '2014-08-16', '2014-08-17', '2014-08-18',
                               '2014-08-15', '2014-08-16', '2014-08-17', '2014-08-18',
                               '2014-08-15', '2014-08-16', '2014-08-17', '2014-08-18',
                               '2014-08-15', '2014-08-16', '2014-08-17', '2014-08-18'],
                    u'Score': [-0.13, -0.25, 0.1, -0.3,
                               -0.1, 0.1, -0.05, 0.2,
                               0.2, 0.5, 0.4, -0.2,
                               -0.3, 0.1, 0.25, 0.05]})

then the dates array is in order and the plot is correct. I don't understand why, but anyway what I want is the plot with 6 or more dates.
I would appreciate if you could please help me. It is clear that I am doing something wrong but I am a beginner in these languages and I have already tried hundreths of solutions, unsuccesfully. Thank you!

A: If you check the types:
>>> type(df.groupby('Date').groups)
<class 'dict'>

therefore, as a dictionary, df.groupby('Date').groups does not provide any order guarantee when you access items or keys; in your example grouped.groups.keys(); So you will lose consistency and correspondence between dates and avg when you pull them out of groupby separately.
If you want to work with datetime objects and simple numpy arrays (as opposed to the pandas series), you may do as below, in order to have the orders consistent:
>>> ts = df.groupby('Date')['Score'].mean()
>>> avg, dates = ts.values, ts.index.map(pd.Timestamp.date)

so you will have:
>>> avg
array([-0.0825,  0.1125,  0.175 , -0.0625, -0.1325,  0.0375])
>>> dates
array([datetime.date(2014, 8, 15), datetime.date(2014, 8, 16), datetime.date(2014, 8, 17), datetime.date(2014, 8, 18),
       datetime.date(2014, 8, 19), datetime.date(2014, 8, 20)], dtype=object)

Note that groupby has a default parameter sort=True, so the output is already sorted by index:
>>> df.groupby('Date')['Score'].mean()
Date
2014-08-15   -0.082
2014-08-16    0.112
2014-08-17    0.175
2014-08-18   -0.062
2014-08-19   -0.133
2014-08-20    0.038
Name: Score, dtype: float64

A: The avg series will have the timestamps in the right order as the index, and can be passed directly to the bokeh plotting functions, like this.
line(avg.index, avg, line_color="grey", line_width=8, line_join="round")
asterisk(avg.index, avg, line_color="black", size=15)


text:
Q: Elm union subsets Say I have a union type like this:
type Route
  = Home
  | License
  | UserProfile { username : String }
  | Search { query : String }
  | SomeOtherPage

In practice I frequently need to work with subsets of this union. For example:
type StaticRoute = Home | License

I would like to be able to define functions which accept subsets like the above, instead of the wider Route.
I don't want to nest StaticRoute inside of Route, like so:
type Route
  = Static StaticRoute
  | UserProfile { username : String }
  | Search { query : String }
  | SomeOtherPage

This is because I want to be able to define many different subsets of Route, some of which could overlap:
type StaticRoute = Home | License
type RouteWithServerRendering = Home | Search { query : String }
type LoggedInRoute = SomeOtherPage
-- and so on…

How then can I define subsets of Route without repeating definitions?

A: Jasper Woudenberg recently posted Conversion functions, five stars
, which advocates for having similar types and using conversion functions to translate between one type to another.
In your case, it might look like this:
module Route exposing (fromStaticRoute, toStaticRoute)

fromStaticRoute : StaticRoute -> Route
fromStaticRoute staticRoute =
    case staticRoute of
        Static.Home ->
            Home
        Static.License ->
            License

toStaticRoute : Route -> Maybe StaticRoute
toStaticRoute route =
    case route of
        Home ->
            Just Static.Home
        License ->
            Just Static.License
        _ ->
            Nothing


text:
Q: SVG element from an array I am trying to load images into a svg canvas from an array and I am not able to make this code work.
I am trying to debug it with Chrome and I am not able to. The image is blank and I don't know how to proceed.
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
<style type="text/css">
body {
                background-image:url('BG.png')
     }
</style>
<title>Drag And Drop</title>
</head>
<body>
<script type="text/javascript">

    window.onload = function(){
    var NumImages = [
                { 'x' :200, 'y':90, 'width': 450, 'height':200, 'href' : 'numbers.jpeg'  },
];
var circleData = [
   { "cx": 20, "cy": 20, "radius": 20, "color" : "green" },
   { "cx": 70, "cy": 70, "radius": 20, "color" : "purple" }];

 var rectangleData = [
   { "rx": 110, "ry": 110, "height": 30, "width": 30, "color" : "blue" },
   { "rx": 160, "ry": 160, "height": 30, "width": 30, "color" : "red" }];

    var svgContainer = d3.select("body").append("svg")
                                                .attr("width",700)
                                                .attr("height",700)
                                                .attr("margin-top", 100);

    var images = svgContainer.selectAll("image")
        .data(NumImages)
        .enter()
        .append("image");

    svgContainer.append("image")
        .attr('x',200)
        .attr('y',90)
        .attr('width', 50)
        .attr('height', 200)
        .attr("xlink:href", "2-image.jpg");
    };

</script>

</body>
</html>

A: You've done all the hard work, you just need to adjust the last couple of lines.  You need to use the data that you've bound to the images variable so try this;
images
    .attr('x', function (d,i) { return d.x; })
    .attr('y', function (d,i) { return d.y; })
    .attr('width', function (d,i) { return d.width; })
    .attr('height', function (d,i) { return d.height; })
    .attr("xlink:href", function (d,i) { return d.href; });


text:
Q: Turn on the GPS on automatically like OLA cabs app I am trying to turn on the gps automatically. But I can not find the solution for this. Now I am using like navigate to the settings page to turn on the GPS. In OLA cabs app gps is automatically on. I want to turn on the GPS location automatically like OLA cabs. I am using following code for switch on the GPS.
public void MessageNoGps(final Activity mActivity) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setMessage(mActivity.getString(R.string.gps_enable))
                .setCancelable(false)
                .setPositiveButton(mActivity.getString(R.string.yes),
                        new DialogInterface.OnClickListener() {
                            public void onClick(final DialogInterface dialog,
                                    final int id) {
                                mActivity
                                        .startActivity(new Intent(
                                                android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                        })
                .setNegativeButton(mActivity.getString(R.string.no),
                        new DialogInterface.OnClickListener() {
                            public void onClick(final DialogInterface dialog,
                                    final int id) {
                                dialog.cancel();
                                mActivity.finish();
                            }
                        });
        final AlertDialog alert = builder.create();
        alert.show();
    }

Please let me know how to turn on the GPS automatically.


text:
Q: C# Multiply fields of Array elements using lambda Let's say I have an array of MyClass objects (not just a IEnumerable<int>).
MyClass has a string field (e.g. name) and int filed (e.g. size).
I need to have multiplied sizes of all elements in array as result (int result = array[0].size*array[1].size*...array[n].size).
It is easy to implement using iteration of array, but I wonder how to implement it using lambda.
Thanks.

A: Use Aggregate:
  int result = array
    .Select(item => item.size)
    .Aggregate((x, y) => x * y);


text:
Q: @react-google-maps/api / Feature click event resets state I am using @react-google-maps/api and I'm trying to set click event on gmap features which appends its area to React state.
enter image description here
but every time I click the feature, it seems the state has been set to empty array(initial state). and the event append one string to it. so the state doesn't get longer.
in this component i put one button that fires the same click event and that works fine. I don't know why this happens.
const MapComponent = ({area, setArea}) => {

    const { isLoaded, loadError } = useLoadScript({
        googleMapsApiKey: "APIKEY"
    })

    const onClickFeature = e => {
        let tgt = e.feature.getProperty("S_NAME")
        if(tgt){
            addArea(tgt)
        }
    }

    const addArea = tgt => {
        let copy = [...area]
        copy.push(tgt)
        setArea(copy)
    }

    const renderMap = () => {

        const onLoad = async map => {
            await getGeoJson().then(res => {
                initPolygon(map,res) //draw polygons with feature collection
                map.data.addListener("click", e => {
                 onClickFeature(e)
                })
            })
        }

        return <><GoogleMap
            mapContainerStyle={containerStyle}
            center={center}
            zoom={14}
            onLoad={onLoad}
            onClick={onClickFeature}
            >

            </GoogleMap>
            <button onClick={() => addArea('someplace')}>CLICK</button> {/* This works fine */}

Selected: {area}

    </>}

    if (loadError) {
        return
Map cannot be loaded right now, sorry.

      }

    return isLoaded ? renderMap() : null
}

A: I can see that your use case should have an area state which should be an array and everytime the geoJsondata feature is clicked, it will get the value of "S_NAME" property. Then it will add it to the area state array.
As you have not provided your whole code, I created your use case using the Google Maps sample geojson data. Everytime the feature is clicked, it will get the "title" property and add it to the "area" state.
Here's the sample code (Note: please use your API key in the index.js for the code to work) and code snippet below:
import React, { useState } from 'react';
import { GoogleMap } from '@react-google-maps/api';

const defaultLocation = { lat: -28, lng: 137 };

function Map() {
  const [area, setArea] = useState([]);

  const handleOnLoad = map => {
    map.data.loadGeoJson(
      'https://storage.googleapis.com/mapsdevsite/json/google.json'
    );
    map.data.addListener('click', onClickFeature);
  };

  const onClickFeature = event => {
    console.log(event.feature.getProperty('letter'));
    let letter = event.feature.getProperty('letter');
    if (letter) {
      addArea(letter);
    }
  };

  const addArea = letter => {
    let copy = area;
    copy.push(letter);
    setArea(copy);
//you will see here that the value of area array is being updated
    console.log(area);
  };

  return (
    <GoogleMap
      center={defaultLocation}
      zoom={5}
      onLoad={handleOnLoad}
      mapContainerStyle={{ width: '100%', height: '88vh' }}
    />
  );
}

export default Map;


text:
Q: How to create a screen like when delete a photo on photo library it displays a splash screen with 2 options: Delete Photo or Cancel? How to create a screen like when delete a photo on photo library it displays a splash screen with 2 options: Delete Photo or Cancel?
I don't know what component to do that. Any advice is appreciated.

A: That's called a UIActionSheet. It's used very much like a UIAlertView.


text:
Q: How to display correct local time on view ticket page in fossil I see the ticket view page display like
username added on 2015-10-29 08:51:00:

In fact, it should be 2015-10-29 16:51:00:
My time zone is GMT+8, so I changed the view ticket from
...
query {SELECT datetime(tkt_mtime) AS xdate, login AS xlogin,
...
html " added on $xdate:\n"
...

To
...
query {SELECT datetime(tkt_mtime+8/24) AS xdate, login AS xlogin,
...
html " added on $xdate:\n"
...

But, it won't work.

A: Tip: "it won't work" is not a good description of your problem. You're much more likely to get (effective) help if you describe what exactly goes wrong; what you expected to happen, what did happen, and what message appeared.
That said...
Use SELECT datetime(tkt_mtime, 'localtime') as xdate to convert utc to your local time zone.
Check out SQLite's documentation on date functions for more info.


text:
Q: Should i use Role based Authentification? I am planning to build a website where users can sell and buy stuff.
My question is if i should use role based authentification for my API or if i should create two complete different types of users. The sellers and the buyers.
The user should be able to decide if he/she wants to sign up as a seller or buyer.
What is the common way to achieve this?
Jakob

A: Role based authentication will be more dynamic. Because, if your project be more complex in future, then your user type solution won't be enough. Also, you can easily give multiple roles for one user by role based authentication.


text:
Q: Weird speed measurement of ZFS over AFP file copy I've been checking how fast is my ZFS storage server. I have some big files (>30 GB) and I've been using dd piped to /dev/null to check read speed.
When running dd for a specific file for a first time, I'm getting a consistent result of about 95 MB/s. I've used both signals and pv to monitor progress and they gave equal results.
However, when running dd for a second time, unusual thing happens:
407+0 records in
406+0 records out
425721856 bytes (426 MB, 406 MiB) copied, 4.61932 s, 92.2 MB/s
911+0 records in
910+0 records out
954204160 bytes (954 MB, 910 MiB) copied, 9.66672 s, 98.7 MB/s
1412+0 records in
1411+0 records out
1479540736 bytes (1.5 GB, 1.4 GiB) copied, 14.7018 s, 101 MB/s
12374+0 records in
12373+0 records out
12974030848 bytes (13 GB, 12 GiB) copied, 19.7579 s, 657 MB/s
12854+0 records in
12853+0 records out
13477347328 bytes (13 GB, 13 GiB) copied, 24.7491 s, 545 MB/s

What causes the sudden spike from 1.5 to 13 GB? I would think that ZFS cache is responsible (server has 64 GB RAM so it could be possible), however the server (FreeBSD) is connected to my client (OSX) over a single 1Gbps link which definitely couldn't handle 657 MB/s speed. Compression is also unlikely as the file contains nearly random data.

Edit: Sorry, perhaps I asked my question in a confusing way.
I have a FreeBSD server with ZFS filesystem. This server shares file using AFP protocol.
I connect to it using desktop PC running OSX 10.10. And of course I run dd on the client.
dd if=/Volumes/NetworkShare/testfile.dat of=/dev/null bs=1048576
When running directly on the server, dd shows over 625 MB/s (which seems OK as the zpool has data striped over 8 drives).

A: First of all, please include the dd command that you used to run the test. As pointed out in the comment, the file written is growing so it's likely something is not right (unless each test was copying a different file). Also to this point it matters how big chunks of data you are writing, i.e. bs option should be big enough. See this Test ZFS speed thread for an example.
Secondly, you can use the diskinfo tool to get the maximum theoretical speed of your disk, e.g.:
diskinfo -tv /dev/ada0

Thirdly, I would recommend trying different tools to get a wider picture, e.g. iozone, mentioned in the thread I posted.
Lastly, when you copy a file to /dev/null then the data never leaves your server. So you are right, the speed difference is most likely due to ZFS caching. Try to copy the file over the network and you won't be able to get more than 100Mb/s (theoretical speed of a 1Gbit link is 125Mb/s).


text:
Q: Ionic data storing like sharedpreferences? Hello everyone I am kinda new for ionic framework.I need your help.
What do you suggest me to store user's data(username , password or loginkey....).
Does it help me to use html5 local storage? I want user to use the application after login till he logout even turn off the mobile device.
thanks in advance :)

A: The best way you can use localstorage , localstorage will be cleared only if the app is uninstalled ...


text:
Q: Shiny: subset a reactive dataframe based on a reactive column name I have a reactive dataframe df(), and reactive column names from this dataframe, slectedName(). I would like to subset this df() based on the reactive column name.
I have tried with the following approaches, but none of them worked. How should I do it?
Thanks a lot.
1. df()$selectedName()

2. df() %>% dplyr::select(selectedName())


text:
Q: Checkbox not checking inside div in Firefox Weird problem.  I don't know if anyone can shed some light on this? I have a checkbox inside a div.  It works fine in IE but not Firefox. I have to click the space around the checkbox that is occupied by the div (sort of like a label) for the checkbox to tick on and off.  Directly clicking the checkbox does not show it as ticked on or off, even though in firebug it is showing that it is in a checked state and an unchecked state.
Only in FF does this happen.....

A: I think this is a bug in firebug.  Disabling firebug will stop this behaviour happening.
I had a similar strange thing happening with radio buttons.  Disabling firebug fixed it.


text:
Q: how to program the STM32 flash using openOCD and gdb I'm using an Olimex ARM-USB-OCD dongle with openOCD and GDB to program and debug an stm32f103 micro. The IDE I'm using came from the Olimex dev-kit CD and makes use of eclipse ganymede.
I can load a small program into the RAM and step through the code without any problems.
I now have a much larger program which doesn't fit into RAM (which is only 20K) and so I'd like to run it from flash (which is 128K).
I've modified the linker script indicating the program code should go in the flash section (address 0x8000000), but gdb fails to load the program.
(gdb)
20 load main.out
&"load main.out\n"
load main.out
~"Loading section .text, size 0xb0e6 lma 0x8000000\n"
Loading section .text, size 0xb0e6 lma 0x8000000
&"Load failed\n"
Load failed

What should I do to get gdb to load the program into flash?

A: Have you considered flashing directly with openocd? I am doing this in a similar setup, but with an ARM7 microcontroller.
 openocd -f flash.cfg

Here is my flash.cfg
set CHIPNAME at91sam7x512

source [find interface/olimex-arm-usb-ocd.cfg]
source [find target/at91sam7sx.cfg]

init
halt

flash probe 0
flash probe 1

flash erase_sector 0 0 15
flash erase_sector 1 0 15

flash write_image my-image.elf

at91sam7 gpnvm 0 set
at91sam7 gpnvm 1 set
at91sam7 gpnvm 2 set
shutdown

The GPNVM stuff is Atmel SAM7 specific, but I think this script should give you a good starting point for making a STM32 version. Openocd can be a bit confusing in the beginning, but the documentation is good and worth reading (http://openocd.berlios.de/). The current stable version (0.4.0) is quite old, so if you have problems, download the latest source code and compile your own.


text:
Q: IndexError on Raspberry pi 3b+ but not in pc Python I am writing a program that sends me a specific number from a website to my phone. When I run the Python file on my laptop it runs smoothly but when I run it on my Raspberry Pi I get this error
Pillen_ant = self.driver.find_elements_by_class_name("bg_periode.vandaag")[1].text
IndexError: list index out of range

But it is not, I use the same line of code on my laptop and then it works fine.

A: The call
self.driver.find_elements_by_class_name("bg_periode.vandaag")

is not returning a list with 2 elements when you run it on the Pi. When you try to index into it at element [1] it is failing because the list doesn't have that many elements. Try adding a breakpoint in your code right before that line and then inspect it by hand to see what is being returned.


text:
Q: Partition map issues external WD SSD exfat drive, how can I re-add EFI partition? Partition map issues external WD SSD exfat drive, how can I re-add EFI partition?
this week , partial data disappeared on this external drive . Mac's first aid showed that the partition map had issues . error said :
Couldn't modify partition map (-69874)
basically the partitions are healthy (i've used four softwares to analyze this hard drive, all three softwares except Mac First Aid act like the drive is perfect and unharmed) but the parent device wont successfully run first aid and thats the error . Mac First Aid treats the two partitions 1 and 2 as if they're healthy , but the parent device is triggering an alert ...
so ive been trying to repair it and haven't been able to . its a MBR EXFAT .
so , i converted it to GPT EXFAT to better suit my mac .
now im getting this error :
Problems were found with the partition map which might prevent booting
This disk doesn't contain an EFI system partition. If you want to start up your computer with this disk or include it in a RAID set, back up your data and partition this disk. :(-69767)
Operation failed...
??? what on earth ... ?
so i guess the external drive doesn't have an EFI and that's been the problem all along ?
what i have is a very healthy drive , no hardware damage , no possible indicator it could've been damaged ... yet data is missing as of this week when my computer froze and the external drive had trouble mounting .
its a really high quality drive that i use on nice computers , new cables , even power surge protector , and my data is basic day-to day stuff .
how can i place an EFI partition on this external hard drive again ? thanks


text:
Q: How to always show submenu in vertical menu with this js file? My question is if anybody knows what to change in the following js file to always show submenu on the vertical menu , meaning to show the submenu on page load and stay shown whether i hover on it or not, in clear make it part of the vertical menu and not an hidden sub menu that you have to hover on the parent category to access.
What do i need to change in the following code to acomplish that, :
Thanks in advance guys !
     * DC Vertical Mega Menu - jQuery vertical mega menu
     * Copyright (c) 2011 Design Chemical

 *
 * Dual licensed under the MIT and GPL licenses:
 *  http://www.opensource.org/licenses/mit-license.php
 *  http://www.gnu.org/licenses/gpl.html
 *
 */
(function($){

    //define the new for the plugin ans how to call it
    $.fn.dcVerticalMegaMenu = function(options){
        //set default options
        var defaults = {
            classParent: 'dc-mega',
            arrow: true,
            classArrow: 'dc-mega-icon',
            classContainer: 'sub-container',
            classSubMenu: 'sub',
            classMega: 'mega',
            classSubParent: 'mega-hdr',
            classSubLink: 'mega-hdr',
            classRow: 'row',
            rowItems: 3,
            speed: 'fast',
            effect: 'show',
            direction: 'right',
            menubg: '0',
            menufixwidth: '0',
            menufixheight: '0'
        };

        //call in the default otions
        var options = $.extend(defaults, options);
        var $dcVerticalMegaMenuObj = this;

        //act upon the element that is passed into the design
        return $dcVerticalMegaMenuObj.each(function(options){

            $mega = $(this);
            if(defaults.direction == 'left'){
                $mega.addClass('left');
            } else {
                $mega.addClass('right');
            }
            // Get Menu Width
            var megaWidth = $mega.width();

            // Set up menu
            $('> li',$mega).each(function(){

                var $parent = $(this);
                var $megaSub = $('> ul',$parent);

                if($megaSub.length > 0){

                $('> a',$parent).addClass(defaults.classParent).append('');
                    $megaSub.addClass(defaults.classSubMenu).wrap('
');
                    var $container = $('.'+defaults.classContainer,$parent);
                    if($('ul',$megaSub).length > 0){

                        $parent.addClass(defaults.classParent+'-li');
                        $container.addClass(defaults.classMega);

                        // Set sub headers
                        $('> li',$megaSub).each(function(){
                            $(this).addClass('mega-unit');
                            if($('> ul',this).length){
                                $(this).addClass(defaults.classSubParent);
                                $('> a',this).addClass(defaults.classSubParent+'-a');
                            } else {
                                $(this).addClass(defaults.classSubLink);
                                $('> a',this).addClass(defaults.classSubLink+'-a');
                            }
                        });

                            $('> li li',$megaSub).each(function(){
                            if($('> ul',this).length){
                              $(this).addClass('mega-sub3'); //rajib
                               $('.mega-sub3 ul').addClass("show3div");
                            }
                        });

                    } else {
                        $container.addClass('non-'+defaults.classMega);
                        if(defaults.menubg==1){
                            var catimages =$('.non-'+defaults.classMega).closest("li").attr('id');
                            catimages = catimages.replace(/\s+/g, '-').toLowerCase();
                            $('.non-'+defaults.classMega).css('background','#333 url(modules/leftmegamenu/bgimages/'+catimages+'.gif) no-repeat right bottom');
                        }
                    }
                }

                var $container = $('.'+defaults.classContainer,$parent);
                var subWidth = $megaSub.outerWidth(true);
                var subHeight = $container.height();

                    if(defaults.menufixwidth>0){
                            var subWidth = defaults.menufixwidth;
                            }
                    if(defaults.menufixheight>0){
                            var subHeight = defaults.menufixheight;
                        }

                var itemHeight = $parent.outerHeight(true);
                // Set position to top of parent
                $container.css({
                    height: subHeight+'px',
                    width: subWidth+'px',
                    zIndex: '1000'
                }).hide();
            });

            // HoverIntent Configuration
            var config = {
                sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
                interval: 10, // number = milliseconds for onMouseOver polling interval
                over: megaOver, // function = onMouseOver callback (REQUIRED)
                timeout: 0, // number = milliseconds delay before onMouseOut
                out: megaOut // function = onMouseOut callback (REQUIRED)
            };

            $('li',$dcVerticalMegaMenuObj).hoverIntent(config);

            function megaOver(){
                $(this).addClass('mega-hover');
                var $link = $('> a',this);
                var $subNav = $('.sub',this);
                var $container = $('.sub-container',this);
                var width = defaults.menufixwidth;
                var outerHeight = $container.outerHeight();
                var height = defaults.menufixheight;
                var itemHeight = $(this).outerHeight(true);
                var offset = $link.offset();
                var scrollTop = $(window).scrollTop();
                var offset = offset.top - scrollTop
                var bodyHeight = $(window).height();
                var maxHeight = bodyHeight - offset;
                var xsHeight = maxHeight - outerHeight;

                if(defaults.menubg==1){
                            var catimages =$(this).closest("li").attr('id');
                            catimages = catimages.replace(/\s+/g, '-').toLowerCase();

                $container.css({
                            background: '#333 url(modules/leftmegamenu/bgimages/'+catimages+'.gif) no-repeat right bottom'
                        });
                }

            if(xsHeight < 0){
                    var containerMargin = xsHeight - itemHeight;
                    $container.css({marginTop: containerMargin+'px'});
                }

                var containerPosition = {right: megaWidth};
                if(defaults.direction == 'right'){
                    containerPosition = {left: megaWidth};
                }

                if(defaults.effect == 'fade'){
                    $container.css(containerPosition).fadeIn(defaults.speed);
                }
                if(defaults.effect == 'show'){
                    $container.css(containerPosition).show();
                }
                if(defaults.effect == 'slide'){
                    $container.css({
                        width: 0,
                        height: 0,
                        opacity: 0});

                    if(defaults.direction == 'right'){

                        $container.show().css({
                            left: megaWidth
                        });
                    } else {

                        $container.show().css({
                            right: megaWidth
                        });
                    }
                    $container.animate({
                            width: width,
                            height: height,
                            opacity: 1
                        }, defaults.speed);
                }
            }

            function megaOut(){
                $(this).removeClass('mega-hover');
                var $container = $('.sub-container',this);
                $container.hide();
            }
        });
    };

})(jQuery);

$(document).ready(function($){
// menu slide hoverIntend
$('#rajbrowsecat').hoverIntent({
     over: startHover,
     out: endHover,
     timeout: 1000
    });

    function startHover(e){
    $('#rajdropdownmenu').slideDown(200)
 }

 function endHover(){
     $('#rajdropdownmenu').slideUp(600)
 }
// menu slide hoverIntend

$('#rajmegamenu').dcVerticalMegaMenu({
        rowItems: '5',
        speed: 'fast',
        effect: 'slide',
        direction: 'right',
        menubg: '1',
        menufixwidth: '236',
        menufixheight: '155'
    });

});

A: UPDATE:
  So i managed to do it by diabling all the code (with /*) related to hover effect from the line    "// HoverIntent Configuration" to "// menu slide hoverIntend" and by twicking the css a bit for presentation , seemed to do the trick to always showing submenus but for those who are interested i also found a way by adding to the css the line "height:auto", that also seemed to work fairly nicely.
Anyway thanks guys for yor answers anyway , it's always nice to to know that we have a place you can turn to when we are stuck !


text:
Q: SQL select rows with a missing value I have a table like this :
id      group_id    meta
1       A           last_activity
2       A           post_id
3       B           last_activity
4       C           last_activity
5       C           post_id

I would like to return only the group_id where there is not the value 'post_id' in column meta
I've tried different solutions with NOT IN, <>, etc. but i can't get the correct result.
Something like :
$sql_group_id = ("SELECT group_id FROM `table` WHERE meta <> 'post_id'");

The result would be : group_id = B
How can i do this ?

A: Try this:
SELECT group_id
FROM mytable
GROUP BY group_id
HAVING SUM(meta='post_id') = 0

The query uses a conditional aggregate in its HAVING clause, in order to filter out groups of records having at least one related record with meta='post_id'.

A: SELECT group_id
FROM `table`
WHERE group_id NOT IN (SELECT group_id
                       FROM `table`
                       WHERE meta like '%post_id%'
                       GROUP BY group_id);

Or could try with:
SELECT group_id
FROM `table`
WHERE group_id NOT IN (SELECT DISTINCT group_id
                       FROM `table`
                       WHERE TRIM(BOTH ' ' FROM meta like) = 'post_id');

A: Your query returns the group_ids that have any other meta value. Instead, you should use the not exists operator to query those that don't have the meta value of post_id:
SELECT DISTINCT group_id
FROM   mytable a
WHERE  NOT EXISTS (SELECT *
                   FROM   mytable b
                   WHERE  a.group_id = b.group_id and b.meta = 'post_id')

A: Use a CASE expression.
Query
select t.`group_id` from(
    select `group_id`,
    sum(case `meta` when 'post_id' then 1 else 0 end) as `new_col`
    from `table`
    group by `group_id`
)t
where t.`new_col` = 0;

A: Use following
$sql_group_id = ("SELECT group_id FROM `table` WHERE meta not in ('post_id')");


text:
Q: Calling an injected button from the content script to the background.js I'm writing a chrome extension that injects a button into a youtube page. The button is created in my content script and injected into the page. My problem is that I have no idea how to build a click function for it, either in the content script or the background script.
my content script(the injected button):
 $("watch7-user-header").innerHTML+=
 '

        <button id="download">
            '+x+'
        </button>
        <button id="menu" class=" yt-uix-button  yt-uix-button-default" onclick="";return false;"> //this is the dropdown menu

'+o+S+"

        </button>

"

How would i call a click an event in the background script?

A: You can't "click" a button from the background page. If you wish to do it, you'll have to send a message to the content script to do it for you.
From the content script, you can do it like this:
var evt = new MouseEvent('click', {
    view: window,
    bubbles: true,
    cancelable: true
});
document.querySelector('<yourElementSelector>').dispatchEvent(evt);

UPDATE:
If you are tryong to click a <button> element, you can simply do:
document.querySelector('<yourButtonSelector>').click();


text:
Q: Handling Keil C51 keywords in the Eclipse indexer According to Keil C51, the following is valid:
static void kernel(void) small interrupt 1 using 2
{
    /* do stuff */
}

According to the Eclipse indexer, however, it isn't.
We can make the following definitions to help the case:
#define small /*small*/
#define interrupt /*interrupt*/

But unfortunately, we can't redefine the reserved keyword 'using' and it would be silly to redefine the numbers 1 or 2.
Is there a way to get the Eclipse indexer to parse ancient 8051 code in order to reap the benefits of a modern IDE?
Is there an alternative to Eclipse that can offer an efficient way to navigate through such a C project? Something with an equivalent "Open Call Hierarchy" function?

A: In fact I created an Eclipse plugin exactly for this purpose a few years ago. I've uploaded the code to github. You may find a binary build of the plugin here:
https://github.com/andersesbensen/eclipse-c51-plugin/blob/master/deployment/eclipse-c51-plugin.zip
You need to activate to plugin under "Language Mappings" in your C project.
The plugin may not be perfect, but its a good start. Feel free to contribute to the code if you find anything not working.
Best regards
Anders

A: You can redefine the problematic keywords for the CDT indexer only. When the indexer is running, the symbol __CDT_PARSER__ is defined. When compillation is running this symbol won't be defined. So you can do something like:
#ifdef __CDT_PARSER__
#undef small
#define small
//....etc
#endif

Or you can have a macro replacing the function definition:
#ifndef __CDT_PARSER__
#define KEIL_SPECIFIC_STUFF(param1, param2) small interrupt param1 using param2
#else
#define KEIL_SPECIFIC_STUFF(param1, param2)
#endif

and then
static void kernel(void) KEIL_SPECIFIC_STUFF(1,2)
{
    /* do stuff */
}


text:
Q: Which one of the following are true?[CSIR-June 2017] Let $\{a_n\}$ be a sequence of real numbers satisfying $\sum _{n=1}^{\infty }\left|a_n-a_{n-1}\right|<\infty $, then the series $\sum_{n=1}^\infty a_nx^n,x\in \mathbb R$ is convergent.
(a)nowhere on $\mathbb R$
(b)Everywhere on $\mathbb R$
(c) On some set containing $(-1,1)$
(d)Only on $(-1,1)$
My Try
(a) False, $a_n=1/n$, $\sum_{n=1}^\infty x^n/n,x\in \mathbb (-1,1)$ is convergent
(b) False,  $a_n=1/n$, $\sum_{n=1}^\infty x^n/n,x\in \mathbb (-1,1)$ is convergent. Not converges everywhere.
(c) I think (c) is also false, $a_n=1/2^n$ $\sum_{n=1}^\infty x^n/2^n,x\in \mathbb (-1/2,1/2)$. which is not an interval containing (-1,1)
(d)False, $a_n=2^n$ $\sum_{n=1}^\infty 2^nx^n,x\in \mathbb (-2,2)$

A: Your argument for (d) is not valid because $a_n=2^{n}$ does not satisfy the hypothesis. Note that $|a_n-a_m| \leq |a_n-a_{n+1}|+...+|a_{m-1}-a_m|$ for $n >m$. Conclude that $(a_n)$ Ia Cauchy sequence, hence bounded. It follows that the series $\sum a_n x^{n}$ converges in $(-1,1)$. Being a  power series it converges in some interval containing $(-1,1)$. Other parts of your answer are correct.

A: You can solve this problem using the root criterion as follows.
First note that the sequence (a_n) is convergent:

*

*$a_n = a_1 + \sum_{k=1}^{n-1}(a_{k+1}-a_k)\stackrel{\sum_{k=1}^{\infty}|a_{k+1}-a_k|<\infty}{\Longrightarrow} \exists \lim_{n\to \infty }|a_n| =L\geq 0$
Now, there are two cases for the radius of convergence $\rho$ of $\sum_{k=1}^{\infty}a_nx^n$:
$$L>0 \stackrel{\forall n>N_{\epsilon:\;}0<\sqrt[n]{L-\epsilon} < \sqrt[n]{|a_n|} < \sqrt[n]{L+\epsilon}}{\Rightarrow} \lim_{n\to\infty}\sqrt[n]{|a_n|}=1\Rightarrow \rho = 1$$
$$L=0 \stackrel{\forall n>N_{\epsilon:\;}0\leq \sqrt[n]{|a_n|} < 1}{\Rightarrow} \limsup_{n\to\infty}\sqrt[n]{|a_n|}\leq 1\Rightarrow \rho \geq 1$$
So, the radius of convergence is at least $1$, hence the series converges on some set containing $(-1,1)$.


text:
Q: Is there a way to "reuse" a PHP DocBlock? I currently have code like this:
/**
 * blah blah blah thing1
 *
 * @return string a thing1
 */
function thing1() {
    //
}

/**
 * blah blah blah thing2
 *
 * @return string a thing2
 */
function thing2() {
    //
}

//dozens more with the same format

Is there a more concise way to do that?

A: Assuming the docblocks are actually identical, often the case when you're overriding an inherited method but maintaining the same signature, you can use @see....
abstract class MyBaseModel
    /**
     * @param Boolean $excludeDeleted Should soft-deleted records be excluded
     */
    public function newQuery($excludeDeleted = true)
    {
        ....
    }
}

class MyExtendedModel extends MyBaseModel
    /**
     * Overload the base newQuery() method so that we can inject any security filters into the query
     *
     * @see MyBaseModel::newQuery
     */
    public function newQuery($excludeDeleted = true)
    {
        ....
    }
}

but the sample docblocks for your thing1() and thing2() aren't identical, so there's no concise (lazy) way of doing so in that case

A: You can use a @see if it is truly the same.
Documentation relating to this
/**
 * blah blah blah thing1
 *
 * @return string a thing1
 */
function thing1() {
    //
}

/**
 * @see thing1
 */
function thing2() {
    //
}


text:
Q: Difference among explicit indexing and implicit indexing? I am learning Database and currently I am using mysql. While practicing it I got a doubt regarding the indexing and wanted to know what exactly is the difference between implicit and explicit indexing? Which is better? Considering that i will be using more of the update, insert and delete commands over the database, which is better suited that time and why?
thank you

A: The term "implicit index" is sometimes used to refer to indexes that are created by operations other than create index.  This occurs in two particular cases:

*

*Primary key definitions in tables

*Unique constraints

And, I am not sure if the use of the key/index keyword in create table is considered implicit or explicit.
There is no difference between the these indexes per se.  There is a difference between primary key and non-primary key indexes -- primary key indexes may result in the table being physically ordered by the index (see here).
Neither is better.  "Implicit" indexes have the advantage that they are part of the table definition.  "Explicit" indexes have the advantage that they are created explicitly.  Other than the definition, the use of the index in queries should be the same.


text:
Q: Limits and sandwich rule with non continuous functions For the following function, find L ∈ ℝ such that g(x) tents to L as x tends to infinity. Prove that lim g(x) -> L by using the sandwich rule.
g: (0,∞) -> ℝ, x->g(x): = (1/x if x ∈ ℕ), (0 otherwise)
I'm pretty sure the limit of this is 0, but the fact that it's not continuous and is 1/x only in the natural numbers is throwing me off.
The sandwich rule basically says if f,g,h are functions from X to ℝ, f(x)≤g(x)≤h(x) and f(x) and h(x) tend to L as x tends to infinity, then g(x) also tends to L as x tends to infinity.
So basically I need to find a function less than g for f(x) and a function greater than g for h(x) that both have the limit 0 (if this is the correct limit) but I am unsure of what function to choose as g is not continuous.

A: We have
$$\forall x\in(0,+\infty)$$
$ f(x)=0$ or $f(x)=\frac{1}{x}\implies$
$$\forall x\in(0,+\infty)\;\; 0\leq f(x)\leq \frac 1x$$
$$\implies 0\leq \lim_{x\to+\infty}f(x)\leq \lim_{x\to+\infty}\frac 1x =0$$
$$\implies \lim_{x\to +\infty}f(x)=0$$


text:
Q: AIX - rename oldest file in a directory I have a situation where several files may accumulate a folder for some processing and the processing routine can only handle one file at a time, and it must have a specific filename.
I need to be able to find the oldest file in this directory and rename it to the required input filename.  Once processed this file gets deleted so I'd have the procedure keep renaming the oldest between processing until all files were exhausted.
e.g.:
In a folder I have:
file1 created 1 Mar
file2 created 2 Mar
file3 created 3 Mar
…

The script would have to rename the file created March 1st to 'input.dat'. On the next occurrence it would rename the one from March 2nd, etc...
How would I go about doing this?

A: mv `ls -ct file* | tail -n 1` input.dat

will rename the oldes file that matches the pattern file* to the name input.dat.


text:
Q: Using either isVisible ember logic or move this logic at the CSS level could anybody point in which specific use cases are using becameVisible and becameHidden events?
I have a case where i want to hide/show views depending on a specific state, and wondering if i should either move this logic at the CSS level via classNames or using isVisible Ember Logic.
The example below tried to show the current scenario.
Em.ContainerView.extend({

  childViews: ['image','spinner'],
  isLoading: true,

  image: Em.View.extend({
    classNames: ['product_image'],
    classNameBindings: ['isLoading'],
    isLoadingBinding: Em.Binding.oneWay('parentView.isLoading')

  }),

  spinner: Em.View.extend({
    classNames: ['spinner'],
    classNameBindings: ['isLoading'],
    isLoadingBinding: Em.Binding.oneWay('parentView.isLoading')
  })

})

CSS would be something like:
    > .product_image {
      display:block;
    }

    > .product_image.is-loading {
      display:none;
    }

    > .spinner {
      display:none;
    }

    > .spinner.is-loading {
      display:block;
    }

Any suggestions/comments on advantages/drawbacks of both scenarios would be really appreciated.

A: I would do it this way in the view template:
{{#unless content.isLoaded }}

....

{{/unless }}
{{#if content.isLoaded }}

...

{{/if }}


text:
Q: Как с помощью команды bat узнать место расположение exe'шника конкретного процесса? Мне необходимо с помощью команды в bat получить местоположение уже запущенного процесса, чтобы далее использовать полученную с этого действия переменную.
Подробнее:
Мне нужно получить весь путь расположения процесса steam.exe (пробовал через tasklist /fi "IMAGENAME eq Steam.exe", но пути к файлу там не указывается), чтобы в последствии запустить этот процесс с дополнительным параметром. Я знаю, что можно указать фиксированный путь, но вопрос именно в том, каким образом этот путь можно получить из самого процесса.

A: 2 способа, через утилиты wmic и where:
@for /f "tokens=1* delims==" %%i in ('@wmic process where "name='steam.exe' and not executablepath=null" get ExecutablePath /format:list^|find/i"="') do @echo %%j

и
where steam

2-ой способ не требует проверки на то, запущен ли процесс, а ищет исходя из параметров среды.


text:
Q: sharing jsonbuilder files for index and show Let's say I have a model called Customer. My index.json.jbuilder looks something like this
eg
json.array!(@customers) do |customer|
  json.extract! customer, :id, :name, :phone_number, :email
  # some more nested fields of customer
end

and my show.json.jbuilder also has similar duplicate code
json.extract! customer, :id, :name, :phone_number, :email
# some more nested fields of customer

is there a better way, say to include the show.json.jbuilder inside the index.json.jbuilder. I don't want duplicate the logic of rendering the json in two places.

A: Use partials (partial!) as described in jbuilder documentation.


text:
Q: Custom REST API returns duplicate "response" tag I am struggling because I get an invalid response from my custom API module for Magento 2 (2.2.5). When I send a request to my endpoint via GET with the header "Accept application/xml" (which is totally valid for Magento 2) I get my XML reponse. However, the surrounding <response> tag pops up twice and I can't get rid of the second one. Here is a sample result:
<response>
    <test>value</test>
    <response/>
</response>

Problem here is the <response/> in line 3. Where does this come from/how can I get rid of this?
I'll only point out the most important files since the rest is just bare standard. For testing purposes I set the resource to anonymous (it's local so no worries here).
webapi.xml:
<?xml version="1.0"?>
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Webapi:etc/webapi.xsd">
    <route url="/V1/xmlorderexport/get" method="GET">
        <service class="Vendor\XmlOrderExportApi\Api\XmlInterface" method="get"/>
        <resources>
            <resource ref="anonymous"/>
        </resources>
    </route>
</routes>

Api/XmlInterface.php:
<?php

namespace Vendor\XmlOrderExportApi\Api;

interface XmlInterface
{

    /**
     * Returns order data as XML.
     *
     * @api
     * @return string Returns the order as XML based on the given template.
     */
    public function get();
}

Model/Xml.php:
<?php

namespace Vendor\XmlOrderExportApi\Model;

use \Vendor\XmlOrderExportApi\Api\XmlInterface;
use \Vendor\XmlOrderExport\Model\WebapiInterface;
use \Magento\Framework\Webapi\Rest\Response\Renderer\Xml as Renderer;

class Xml implements XmlInterface
{

    private $webapi;

    private $renderer;

    function __construct(
        WebapiInterface $webapi,
        Renderer $renderer
    )
    {
        $this->renderer = $renderer;
        $this->webapi   = $webapi;
    }

    /**
     * Returns order data as XML.
     *
     * @api
     * @return string Returns the order as XML based on the given template.
     */
    public function get()
    {
        /**
         * Only for testing purposes!
         */
        //$order_id = 194;

        //$result = $this->webapi->getXml($order_id);
        //$xml    = simplexml_load_string($result);

        $this->renderer->render(['test' => 'value']);
    }
}

Can anybody help me out and point me in the right direction please?
Thanks in advance ...


text:
Q: How to get id of just-executed sql query (in php) In php I have an INSERT query to database. This query add some issue to database. I want to check if issue was added fine (there are some cases when issue doesn't added - without any mistake reporting). How to check this?
I have an idea, that after i make INSERT query i should make a query, for example: SELECT ..... WHERE id=last_id. But how to get the last_id - how to get id of last INSERT query? (id is autoincrementing sql field)
Thank you

A: mysql_insert_id();

A: mysql_insert_id()

More info at http://php.net/manual/en/function.mysql-insert-id.php and http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

A: You may find the answer to this StackOverflow question useful:
SQL - INSERT and catch the id auto-increment value

A: mysql_insert_id function returns id of previously inserted record.
I assume you're working with MySQL


text: Q: Запретить изменение HTML структуры CKEditor Зачастую редакторы статей могут испортить структуру статьи: убрать заголовок, или изменить жирность шрифта и так далее. Появилось желание отгородить простых редакторов от HTML вообще, чтобы они изменяли только текст внутри тэгов, а все тэги оставались на своем месте. Возможно ли такое реализовать? Может есть какой-то другой редактор по мимо ckeditor, который даёт подобные возможности?


text:
Q: Copy subset of files keeping folder structure using Powershell Looking for some Powershell help with a copying challenge.
I need to copy all MS Office files from a fairly large NAS (over 4 million of them and a little over 5tb) to another drive, retaining the existing folder structure where a file is copied.
I have a text file of all the common Office file types (about 40 of them) - extns.txt
At this stage, being a good StackExchanger, I'd post the script I've got so far, but I've spent best part of a day on this and, not only is what I've got embarrassingly awful, I suspect that even the basic algorithm is wrong.
I started to gci the entire tree on the old NAS, once for each file type
Then I thought it would be better to traverse once and compare every file to the list of valid types.
Then I got into a complete mess about rebuilding the folder structure. I started by splitting on '\' and iterating through the path then wasted an hour of searching because I thought I remembered reading about a  simple way to duplicate a path if it doesn't exist.
Another alternative is that I dump out a 4 million line text file of all the files (with full path) I want to copy (this is easy as I imported the entire structure into SQL Server to analyse what was there) and use that as a list of sources
I'm not expecting a 'please write the codez for me' answer but some pointers/thoughts on the best way to approach this would be appreciated.

A: I'm not sure if this is the best approach, but the below script is a passable solution to the least.
$sourceRootPath = "D:\Source"
$DestFolderPath = "E:\Dest"

$extensions = Get-Content "D:\extns.txt"

# Prefix "*." to items in $extensions if it doesn't already have it
$extensions = $extensions -replace "^\*.|^","*."

$copiedItemsList = New-Object System.Collections.ArrayList

foreach ( $ext in $extensions ) {
    $copiedItems = Copy-Item -Path $sourceRootPath -Filter $ext -Destination $DestFolderPath -Container -Recurse -PassThru
    $copiedItems | % { $copiedItemsList.Add($_) | Out-Null }
}

$copiedItemsList = $copiedItemsList | select -Unique

# Remove Empty 'Deletable' folders that get created while maintaining the folder structure with Copy-Item cmdlet's Container switch
While ( $DeletableFolders = $copiedItemsList | ? { ((Test-Path $_) -and $_.PSIsContainer -eq $true -and ((gci $_ | select -first 1).Count -eq 0)) } ) {
    $DeletableFolders | Remove-Item -Confirm:$false
}

The Copy-Item's -Container switch is going to preserve the folder structure for us. However, we may encounter empty folders with this approach.
So, I'm using an arraylist named $copiedItemsList to add the copied objects into, which I will later use to determine empty 'Deletable' folders which are then removed at the end of the script.
Hope this helps!


text:
Q: angularUI ui-select2 directive not working I've been banging my head against the wall with this, so I've reduced it to the bare minimum:
index.html:
<html lang="en" ng-app="myApp">
    <body ng-controller="main">

        <select ui-select2>
            <option>12451</option>
            <option>23435</option>
            <option>3456</option>
        </select>

        <!-- Scripts loaded here. See the plunker -->

    </body>
</html>

app.js:
angular
    .module('myApp', ['ui'])
    .controller('main', function (){});

Here's the link to the Plunker: http://plnkr.co/edit/kXnHPzBt7apRc7EivLp8?p=preview
I think I'm doing it all right, but it just refuses to initialize the select2.
Here's the error I get:

Object [[object HTMLSelectElement]] has no method 'is'

Here's a screenshot of the error:

What am I doing wrong here?

A: You need to load jQuery before AngularJS and apparently select2.js before Angular-ui
The following order works fine
<script src="jquery.min.js"></script>
<script src="select2.js"></script>
<script src="angular.js"></script>
<script src="angular-ui.js"></script>

Check the plunker: http://plnkr.co/edit/sAGfzmNdykEnqlH40gNf?p=preview

Check this other answer: Angular UI Select2 in the Bootstrap Navigation Bar


text:
Q: Python pandas- Remove all elements of one dataframe that aren't included in another I'm working with two dataframes in pandas:
DF1: Product_ID, Num_Reviews
DF2: Product_ID, Reviewer_ID, Review_Score
I want to remove or filter DF2 to only contain entries with a Product_ID that exists in DF1. I'm not very familiar with pandas or even python for that matter, and couldn't find a clear way to check if a dataframe includes a key and filter based on that.
Thanks!

A: Here's on way to do it.
df2[df2['Product_ID'].isin(df1['Product_ID'].unique())]

Get unique Product_ID from df1 and filter those values in df2['Product_ID'] using isin()

A: The most efficient way to calculate the intersection of Product_ID's would be using numpy's in1d. That gives you a mask.
Then, you simply slice your DF2 using the mask to get the new dataframe you want.
import numpy as np
mask = ~np.in1d(DF2.Product_ID, DF1.Product_ID)
DF2 = DF2[mask]


text:
Q: How to parse array JSON with XE2 dbxJSON Following on my previous question: How to parse JSON with XE2 dbxJSON
Where I had a clear answer on how to get a value out of a JSON string. I am now requiring to get the value from an array.
The full JSON string:
{"ATTITUDE":{"message_information":{"counter":45942,"frequency":10.07058334350586,"time":{"first_message":"2021-06-02T04:17:19.713053488+00:00","last_message":"2021-06-02T05:33:21.925390505+00:00"}},"pitch":0.39779675006866455,"pitchspeed":0.04370392858982086,"roll":-3.1154606342315674,"rollspeed":0.29034918546676636,"time_boot_ms":4587189,"type":"ATTITUDE","yaw":2.762258768081665,"yawspeed":0.39911729097366333},"AUTOPILOT_VERSION":{"board_version":0,"capabilities":{"bits":10695},"flight_custom_version":[48,53,102,101,100,52,57,98],"flight_sw_version":50660607,"message_information":{"counter":1,"frequency":null,"time":{"first_message":"2021-06-02T05:03:34.953044355+00:00","last_message":"2021-06-02T05:03:34.953068261+00:00"}},"middleware_custom_version":[56,100,53,48,53,97,48,50],"middleware_sw_version":0,"os_custom_version":[49,97,57,57,98,97,53,56],"os_sw_version":0,"product_id":0,"type":"AUTOPILOT_VERSION","uid":0,"uid2":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"vendor_id":0},"BATTERY_STATUS":{"battery_function":{"type":"MAV_BATTERY_FUNCTION_UNKNOWN"},"battery_remaining":99,"charge_state":{"type":"MAV_BATTERY_CHARGE_STATE_UNDEFINED"},"current_battery":4,"current_consumed":51,"energy_consumed":-1,"id":0,"mavtype":{"type":"MAV_BATTERY_TYPE_UNKNOWN"},"message_information":{"counter":45443,"frequency":9.961201667785645,"time":{"first_message":"2021-06-02T04:17:19.729121346+00:00","last_message":"2021-06-02T05:33:21.936851877+00:00"}},"temperature":32767,"time_remaining":0,"type":"BATTERY_STATUS","voltages":[65535,65535,65535,65535,65535,65535,65535,65535,65535,65535]},"COMMAND_ACK":{"command":{"type":"MAV_CMD_REQUEST_PROTOCOL_VERSION"},"message_information":{"counter":2,"frequency":null,"time":{"first_message":"2021-06-02T05:03:34.954980156+00:00","last_message":"2021-06-02T05:03:35.688089082+00:00"}},"progress":0,"result":{"type":"MAV_RESULT_UNSUPPORTED"},"result_param2":0,"target_component":0,"target_system":0,"type":"COMMAND_ACK"},"GLOBAL_POSITION_INT":{"alt":0,"hdg":15816,"lat":0,"lon":0,"message_information":{"counter":45452,"frequency":9.963173866271973,"time":{"first_message":"2021-06-02T04:17:19.707524674+00:00","last_message":"2021-06-02T05:33:21.943859157+00:00"}},"relative_alt":0,"time_boot_ms":4587209,"type":"GLOBAL_POSITION_INT","vx":-10,"vy":11,"vz":0},"GPS_RAW_INT":{"alt":0,"alt_ellipsoid":0,"cog":0,"eph":9999,"epv":0,"fix_type":{"type":"GPS_FIX_TYPE_NO_GPS"},"h_acc":0,"hdg_acc":0,"lat":0,"lon":0,"message_information":{"counter":4532,"frequency":0.99364173412323,"time":{"first_message":"2021-06-02T04:17:20.312445519+00:00","last_message":"2021-06-02T05:33:21.692667024+00:00"}},"satellites_visible":0,"time_usec":0,"type":"GPS_RAW_INT","v_acc":0,"vel":0,"vel_acc":0},"HEARTBEAT":{"autopilot":{"type":"MAV_AUTOPILOT_ARDUPILOTMEGA"},"base_mode":{"bits":81},"custom_mode":19,"mavlink_version":3,"mavtype":{"type":"MAV_TYPE_SUBMARINE"},"message_information":{"counter":4563,"frequency":1.0,"time":{"first_message":"2021-06-02T04:17:17.848160794+00:00","last_message":"2021-06-02T05:33:21.539669615+00:00"}},"system_status":{"type":"MAV_STATE_ACTIVE"},"type":"HEARTBEAT"},"MISSION_COUNT":{"count":0,"message_information":{"counter":1,"frequency":null,"time":{"first_message":"2021-06-02T05:03:37.486328037+00:00","last_message":"2021-06-02T05:03:37.486349756+00:00"}},"mission_type":{"type":"MAV_MISSION_TYPE_MISSION"},"target_component":190,"target_system":255,"type":"MISSION_COUNT"},"MISSION_CURRENT":{"message_information":{"counter":45414,"frequency":9.95484447479248,"time":{"first_message":"2021-06-02T04:17:19.702201949+00:00","last_message":"2021-06-02T05:33:21.889268605+00:00"}},"seq":0,"type":"MISSION_CURRENT"},"NAMED_VALUE_FLOAT":{"message_information":{"counter":399816,"frequency":87.60210418701172,"time":{"first_message":"2021-06-02T04:17:17.857721885+00:00","last_message":"2021-06-02T05:33:21.912362180+00:00"}},"name":["S","t","i","c","k","M","o","d","e","\u0000"],"time_boot_ms":4587170,"type":"NAMED_VALUE_FLOAT","value":0.0},"NAV_CONTROLLER_OUTPUT":{"alt_error":8.696813583374023,"aspd_error":0.0,"message_information":{"counter":45414,"frequency":9.95484447479248,"time":{"first_message":"2021-06-02T04:17:19.702460695+00:00","last_message":"2021-06-02T05:33:21.892910002+00:00"}},"nav_bearing":158,"nav_pitch":22.816354751586914,"nav_roll":-178.67893981933594,"target_bearing":90,"type":"NAV_CONTROLLER_OUTPUT","wp_dist":0,"xtrack_error":0.0},"PARAM_VALUE":{"message_information":{"counter":1379,"frequency":0.496221661567688,"time":{"first_message":"2021-06-02T04:17:17.382040509+00:00","last_message":"2021-06-02T05:03:36.411921703+00:00"}},"param_count":689,"param_id":["R","C","1","6","_","D","Z","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000"],"param_index":688,"param_type":{"type":"MAV_PARAM_TYPE_INT16"},"param_value":0.0,"type":"PARAM_VALUE"},"POWER_STATUS":{"Vcc":4798,"Vservo":4826,"flags":{"bits":6},"message_information":{"counter":45414,"frequency":9.95484447479248,"time":{"first_message":"2021-06-02T04:17:19.682529932+00:00","last_message":"2021-06-02T05:33:21.886051991+00:00"}},"type":"POWER_STATUS"},"RAW_IMU":{"id":0,"message_information":{"counter":45397,"frequency":9.951117515563965,"time":{"first_message":"2021-06-02T04:17:19.734752711+00:00","last_message":"2021-06-02T05:33:21.877993635+00:00"}},"temperature":0,"time_usec":292202468,"type":"RAW_IMU","xacc":317,"xgyro":175,"xmag":-491,"yacc":167,"ygyro":-9,"ymag":266,"zacc":957,"zgyro":456,"zmag":-115},"RC_CHANNELS":{"chan10_raw":1100,"chan11_raw":1100,"chan12_raw":0,"chan13_raw":0,"chan14_raw":0,"chan15_raw":0,"chan16_raw":0,"chan17_raw":0,"chan18_raw":0,"chan1_raw":1500,"chan2_raw":1500,"chan3_raw":1500,"chan4_raw":1500,"chan5_raw":1300,"chan6_raw":1500,"chan7_raw":1500,"chan8_raw":1500,"chan9_raw":1100,"chancount":0,"message_information":{"counter":45418,"frequency":9.955720901489258,"time":{"first_message":"2021-06-02T04:17:19.711293621+00:00","last_message":"2021-06-02T05:33:21.917371628+00:00"}},"rssi":0,"time_boot_ms":4587170,"type":"RC_CHANNELS"},"SCALED_IMU2":{"message_information":{"counter":45397,"frequency":9.951117515563965,"time":{"first_message":"2021-06-02T04:17:19.736843145+00:00","last_message":"2021-06-02T05:33:21.879795741+00:00"}},"temperature":0,"time_boot_ms":4587169,"type":"SCALED_IMU2","xacc":350,"xgyro":168,"xmag":0,"yacc":23,"ygyro":-16,"ymag":0,"zacc":947,"zgyro":417,"zmag":0},"SCALED_PRESSURE":{"message_information":{"counter":45397,"frequency":9.951117515563965,"time":{"first_message":"2021-06-02T04:17:19.738746395+00:00","last_message":"2021-06-02T05:33:21.881683105+00:00"}},"press_abs":985.9927978515625,"press_diff":0.9619531035423279,"temperature":3839,"time_boot_ms":4587169,"type":"SCALED_PRESSURE"},"SERVO_OUTPUT_RAW":{"message_information":{"counter":45418,"frequency":9.955720901489258,"time":{"first_message":"2021-06-02T04:17:19.709378809+00:00","last_message":"2021-06-02T05:33:21.914680318+00:00"}},"port":0,"servo10_raw":0,"servo11_raw":0,"servo12_raw":0,"servo13_raw":0,"servo14_raw":0,"servo15_raw":0,"servo16_raw":0,"servo1_raw":1500,"servo2_raw":1500,"servo3_raw":1500,"servo4_raw":1500,"servo5_raw":1500,"servo6_raw":1500,"servo7_raw":1100,"servo8_raw":1500,"servo9_raw":0,"time_usec":292203152,"type":"SERVO_OUTPUT_RAW"},"STATUSTEXT":{"message_information":{"counter":6,"frequency":0.0021606050431728363,"time":{"first_message":"2021-06-02T04:17:17.906866746+00:00","last_message":"2021-06-02T05:03:34.950209089+00:00"}},"severity":{"type":"MAV_SEVERITY_INFO"},"text":["P","X","4","v","2"," ","0","0","2","6","0","0","3","8"," ","3","4","4","E","5","0","1","4"," ","2","0","3","9","3","8","4","E","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000","\u0000"],"type":"STATUSTEXT"},"SYSTEM_TIME":{"message_information":{"counter":90857,"frequency":19.916046142578125,"time":{"first_message":"2021-06-02T04:17:19.702351114+00:00","last_message":"2021-06-02T05:33:21.934951232+00:00"}},"time_boot_ms":4587189,"time_unix_usec":1622669680316000,"type":"SYSTEM_TIME"},"SYS_STATUS":{"battery_remaining":-1,"current_battery":4,"drop_rate_comm":0,"errors_comm":0,"errors_count1":0,"errors_count2":0,"errors_count3":0,"errors_count4":0,"load":320,"message_information":{"counter":45413,"frequency":9.954625129699707,"time":{"first_message":"2021-06-02T04:17:19.740726362+00:00","last_message":"2021-06-02T05:33:21.884494257+00:00"}},"onboard_control_sensors_enabled":{"bits":2137095},"onboard_control_sensors_health":{"bits":2161671},"onboard_control_sensors_present":{"bits":2161671},"type":"SYS_STATUS","voltage_battery":28},"VFR_HUD":{"airspeed":0.0,"alt":-8.6899995803833,"climb":0.0,"groundspeed":0.0,"heading":158,"message_information":{"counter":45610,"frequency":9.997807502746582,"time":{"first_message":"2021-06-02T04:17:19.718803757+00:00","last_message":"2021-06-02T05:33:21.919499092+00:00"}},"throttle":0,"type":"VFR_HUD"},"VIBRATION":{"clipping_0":0,"clipping_1":1,"clipping_2":0,"message_information":{"counter":45443,"frequency":9.961201667785645,"time":{"first_message":"2021-06-02T04:17:19.732746078+00:00","last_message":"2021-06-02T05:33:21.941986844+00:00"}},"time_usec":4587189930,"type":"VIBRATION","vibration_x":0.743248462677002,"vibration_y":1.1571483612060547,"vibration_z":1.0443675518035889}}

This is extracted from the NAMED_VALUE_FLOAT part of the JSON string.
  "message_information": {
    "counter": 302846,
    "frequency": 87.47718048095703,
    "time": {
      "first_message": "2021-06-02T04:17:17.857721885+00:00",
      "last_message": "2021-06-02T05:15:00.035238554+00:00"
    }
  },
  "name": [
    "P",
    "i",
    "l",
    "o",
    "t",
    "G",
    "a",
    "i",
    "n",
    "\u0000"
  ],
  "time_boot_ms": 3485250,
  "type": "NAMED_VALUE_FLOAT",
  "value": 0.5
}

This is the working code provided by Remi Lebeau to get the value out.
function TForm_OV_REC.ParseJSON(sJSON, sITEM, sVALUE : String) : String;
var
  LJsonVal : TJSONValue;
  LJPair : TJSONPair;
begin
  Result := '';
  LJsonVal := TJSONObject.ParseJSONValue(sJSON);
  if LJsonVal = nil then Exit;
  try
    LJPair := (LJsonVal as TJSONObject).Get(sITEM);
    if LJPair = nil then Exit;
    LJPair := (LJPair.JsonValue as TJSONObject).Get(sVALUE);
    if LJPair = nil then Exit;
    Result := LJPair.JsonValue.Value;
  finally
    LJsonVal.Free;
  end;
end;

procedure TForm_OV_REC.timerRESTAPITimer(Sender: TObject);
var
  MyString, sJSON : String;
  IdHTTP: TIdHTTP;
begin
  IdHTTP := TIdHTTP.Create(nil);
  try
    IdHTTP.ConnectTimeout := 100;
    sJSON := IdHTTP.Get('http://192.168.2.2:4777/mavlink');
  finally
    IdHTTP.Free;
  end;
  MyString := ParseJSON(sJSON, 'NAMED_VALUE_FLOAT', 'value');
  ...
end;

The "name" array changes from PilotGain to Tethertrn etc etc and I need to retrieve it to associate the right value. My knowledge of JSON is very limited. I honestly have no clue how to proceed.
Cheers,
E.
=================================================
Clarifications:
The robot sends a JSON to URL http://192.168.2.2:4777/mavlink about 20 time per second. For some reason I don't understand they use item NAMED_VALUE_FLOAT to pass values for either PilotGain,Stickmode, TetherTrn,etc,etc And for further reason I don't understand, instead of just using a string for "name", they use an array...
NAMED_VALUE_FLOAT is the item like ATTITUDE in the previous question.
I can get the "value" from NAMED_VALUE_FLOAT but this value means nothing unless I can tie it in with its identifier. Is the value for PilotGain? for TetherTrn? etc.
The part I am trying to retrieve is:
"name": [
    "P",
    "i",
    "l",
    "o",
    "t",
    "G",
    "a",
    "i",
    "n",
    "\u0000"
  ],

Where the "name" array contains "P","i","l","o","t","G","a","i","n","\u0000"
So I need to retrieve: PilotGain
This name array changes to other characters such as:
"S","t","i","c","k","M","o","d", "e","\u0000"
So I need to retrieve: StickMode
"T","e","t","h","e","r","T","r","n","\u0000"

So I need to retrieve: TetherTrn
So on...
If I try to retrieve the value of "name" I get an empty string. So I am guessing I have to retrieve the array in Name and then put that into a string.
I am sorry, I cannot change what the robot puts out as JSON.
I hope this is more clear.
Thank you.

A: Following Remy Lebeau's instructions, I came up with this code which outputs the string I was trying to retrieve.
All credit goes to him.
I hope this helps someone else who is still using Delphi XE2.
function TForm_OV_REC.ParseJSONArray(sJSON, sITEM, sArray : String) : String;
var
  LJsonVal : TJSONValue;
  LJPair : TJSONPair;
  LJsonArray : TJSONArray;
  LIndex    : Integer;
  LSize     : Integer;
begin
  Result := '';
  LJsonVal := TJSONObject.ParseJSONValue(sJSON);
  if LJsonVal = nil then Exit;
  try
    LJPair := (LJsonVal as TJSONObject).Get(sITEM);
    if LJPair = nil then Exit;
    LJPair := (LJPair.JsonValue as TJSONObject).Get(sArray);
    if LJPair = nil then Exit;

    LJsonArray := TJSONArray(LJPair.JsonValue);
    LSize := LJsonArray.Size;
    if LSize < 1 then Exit;

    for LIndex := 0 to LSize-1 do
      begin
        Result := Result +  LJsonArray.Get(LIndex).Value;
      end;
  finally
    LJsonVal.Free;
  end;
end;


text:
Q: Puzzle about convict who chooses length of his imprisonment This is the puzzle I deal with for few days right now and I can't figure it out. I translated it from other language if I can improve post please comment.
In the end of a trial judge sentenced a convict for some years of prison, but he let the convict to choose how many years he will spend there.
Judge placed 12 boxes in the circle. In clockwise order the numbers on the boxes were: 7, 10, 1, 3, 6, 11, 8, 4, 5, 9, 0, 2.
Judge said that in every box there is a certain number of coins. In clockwise order amount of coins in boxes were:  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11.
Convict had to choose a box. The number of coins determined years of his/her imprisonment.
Convict asked judge how many boxes have number equal to number of coins inside. Judge said he won't say because then convict could determine empty box. Convict selected empty box.
How he found out which box was empty?

A: I found the answer by writing down the numbers
0 1 2 3 4 5 6 7 8 9 10 11 0 1 2 3 4 5 6 7 8 9 10
on a piece of paper and writing down the numbers
7 10 1 3 6 11 8 4 5 9 0 2
on another piece of paper and sliding one against the other and counting the number of matches.
5 positions have 0 matches.
3 positions have 1 match.
3 positions have 2 matches.
1 position has 3 matches. That is the one that saves the convict from prison.

A: Call a box "accurately labeled" if it has the same number of coins in it as its label. There are several ways in which none of the boxes could be accurately labeled, so at least one of them must be accurately labeled. The sets of boxes that could be accurately labeled are $\{0,6,8\},\{1\},\{2\},\{3,9\},\{4,5,10\},\{7\},\{11\}$.  The only one of these sets with a unique cardinality is $\{3,9\}$, so those must be the accurately labeled ones. This means the box labeled 7 has no coins in it.


text:
Q: WP7 XNA ContentLoadException only for specifc types of models Recently, I ported over a desktop XNA application to WP7. However, I get ContentLoadExceptions when trying to load specific types of models.
I get the following error:
Cannot find type Microsoft.Xna.Framework.Content.Pipeline.Graphics.NodeContent, Microsoft.Xna.Framework.Content.Pipeline, Version=4.0.0.0, Culture=neutral, PublicKeyToken=842cf8be1de50553.

It attempts to load a class which is only available on the desktop version of XNA even when I use the default content pipeline. I have several types of models: terrain, buildings, and a couple other types. Building tiles refuse to load because of this error. I've tried several file formats (Collada, FBX, X, and OBJ and always get the same error).
Anyone have ideas as to why this might happen?


text:
Q: What is the format that date? I need to know what format this date, the format is this 1394567523572-0300 here, this is a timestamp ?
Format:
1394567523572-0300

A: It appears to be a non-standard format consisting of the number of milliseconds since the epoch (1394567523572) and a time zone offset (0300). If I had to guess this "format" is intended to mean 2014-03-11T19:52:03.572Z, with some time zone that has a UTC+03:00 offset.

A: It's the number of milliseconds since Unix epoch (1-Jan-1970) with the addition of a timezone (-0300).
See this online epoch converter.

A: It looks like the number of milliseconds from Jan 1 1970 (otherwise known as Unix time * 1000) along with a timezone offset of -3 hours.
The Unix timestamp of 1394567523 is the equivalent of Tue, 11 Mar 2014 19:52:03


text:
Q: Firebase intellisense / autocompletion on JavaScript React project in VSCode I'm working on a React and Firebase project and I'm having trouble setting up the autocompletion on my code (I'm using VScode).
Here's what I've got so far:

HOW I'M PROVIDING FIREBASE TO MY APP COMPONENTS (VIA CONTEXT)

FirebaseContext.js
import React from 'react';

const FirebaseContext = React.createContext(null);

export default FirebaseContext;

firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';

// .env file in root folder
const config = {
  apiKey: process.env.FIREBASE_APP_API_KEY,
  authDomain: process.env.FIREBASE_APP_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_APP_DATABASE_URL,
  projectId: process.env.FIREBASE_APP_PROJECT_ID,
  storageBucket: process.env.FIREBASE_APP_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_APP_MESSAGING_SENDER_ID
};

firebase.initializeApp(config);
firebase.functions().useFunctionsEmulator('http://localhost:5000');

export default firebase;

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import firebase from './helpers/firebase/firebase';
import FirebaseContext from './helpers/firebase/FirebaseContext';
import { BrowserRouter as Router} from "react-router-dom";

...

ReactDOM.render(

  // HERE'S HOW I'M PROVIDING FIREBASE FOR MY APP
  <FirebaseContext.Provider value={firebase}>
    <Router>
      <App/>
    </Router>
  </FirebaseContext.Provider>

,document.getElementById('root')
);

HOW I'M CONSUMING FIREBASE IN MY COMPONENTS

AddProductContainer.js
import React, { useEffect, useState, useCallback, useContext } from 'react';
import FirebaseContext from '../../../helpers/firebase/FirebaseContext';

function AddProductContainer() {

  const firebase = useContext(FirebaseContext);

  function saveToFirestore() {
    // I DON'T HAVE ANY AUTOCOMPLETION FROM 'FIREBASE...'
    firebase.firestore().collection('products').add({
      title: productDetails.title.newTitle,
      description: productDetails.description,
      categories: productDetails.categories
    });
  }

}

QUESTION
How can I get autocompletion from Firebase inside a JavaScript project?
Note: All of my component files are .js. I'm not using Typescript.
Is there a way to use JSDoc annotations to get access to autocompletion in this case?
Something like:
/** @type {firebase} */
const firebase = useContext(FirebaseContext);

A: It would definitely be pretty tricky to do it the way you're doing it without Typescript or something, but can I suggest another option?
I don't think it's necessary to put the firebase object itself in context.  Putting app in context might make sense (the object returned from firebase.initializeApp) if you were going to use more than one app or just wanted to be explicit, but it seems like firebase itself would make more sense being a direct import (import firebase from 'firebase/app') in any file that's using it.  It won't create a second instance of firebase or anything if that's what you're concerned about, it's just a handle for the firebase library.  It'll pick up the default app you initialized with firebase.initializeApp() as long as initializeApp() ran first.  initializeApp() creates a global default firebase app that any invocation of Firebase methods will pick up.
If you're uncomfortable with globals, you can be explicit about the specific app you're working with by assigning const app = firebase.initializeApp(...), then passing app down through props or context, then always calling firebase packages with app as an argument, such as firebase.firestore(app).collection('products').etc... .
But there should be no cost to importing the firebase package directly at the top of any file you're using it in (and want autocomplete in).


text:
Q: Visual Studio Online - operations failed getUser List We are trialing a test migration of a project on TFS 2010 (on prem) to #visual-studio-online using #OpsHub  . During the migration phase at the user mapping window we are getting the below error message.

2015-07-08 15:10:49,916 [4] ERROR Error : The operation has timed out
  at System.Net.HttpWebRequest.GetResponse()    at
  Microsoft.TeamFoundation.Client.Channels.TfsHttpWebRequest.SendRequestAndGetResponse(HttpWebRequest
  webRequest, WebException& webException)

I am not able to find much information on-line about this error. I tried doing the migration as a TFS administrator and as a domain user who has project admin access to the project but still get these time out errors.
I saw online a user upgraded to #OpsHub 1.3 from 1.2 to overcome this issue which I tried but still doesn't help. Do we need to open any other ports for this to work apart from 80 and 443? Any suggestion as to how to over come this issue?

A: From the logs we find out that error is about time out from your local tfs server.
Server Error : TF400324: Team Foundation services are not available from server tfs.nextdigital.com\Next Digital.
Technical information (for administrator):
  The operation has timed out
Here you need to work with your tfs admin to increase timeout parameter of your tfs.
Following thread might help you in this.
http://blogs.msdn.com/b/ablock/archive/2008/09/16/increasing-the-time-out-time.aspx
Thanks & Regards,OpsHub Support


text:
Q: C - choose interface for UDP/multicast socket I am trying to modify a multicast listener / sender example to bind the UDP / multicast socket to a specific interface and not using the INADDR_ANY macro.
I possess the IPv4 address of the interface.
I tried the following, but the socket does not receive any UDP (unicast, broadcast, multicast) packets.
struct sockaddr_in addr;
int fd, nbytes;
socklen_t  addrlen;
struct ip_mreq mreq;

// my_ipv4Addr equals current IP as String, e.g. "89.89.89.89"

// create what looks like an ordinary UDP socket */
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
    perror("socket");
    exit(1);
}

// set up addresses
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
// [-]    addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_addr.s_addr = inet_addr(my_ipv4Addr);
addr.sin_port = htons(port);

// bind socket
if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
    perror("bind");
    exit(1);
}

// use setsockopt() to request that the kernel join a multicast group
mreq.imr_multiaddr.s_addr = inet_addr(group);
// [-]    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
mreq.imr_interface.s_addr = inet_addr(my_ipv4Addr);
if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))< 0) {
    perror("setsockopt");
    exit(1);
}

Edit:
Let me explain the purpose of my program. I am writing a little tool, which will check, if a network supports broadcast/multicast. Therefore I own a system with two interfaces and send via Interface1 a multicast Packet and try to receive it with Interface2. But: The packet shall go through the network, not the loopack device.
The idea is to block multicast-loopback on thread1/interface1 with:
u_char loop = 0;
setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));

And to listen on thread2/interface 2 interface-specific. Tcpdump shows, that the packets are arriving, but are dropped with my config above.

A: When binding a socket for receiving multicast traffic, if you bind to a local address, this prevents multicast packets from being received on non-Windows systems.
I first discovered this when I released version 3.6 of UFTP with the feature of binding to a specific address.  Windows handles it just fine, but on Linux systems the multicast packets weren't received by the app.  I had to remove the feature in the next release.
Note that you are allowed to bind directly to the multicast address:
addr.sin_addr.s_addr = inet_addr(group);

In this case, you'll receive traffic only for that multicast address on that socket.  You still need to join the multicast group on a specific interface to receive however.
If you plan on receiving data from more than one multicast address on the same socket, then you need to bind to INADDR_ANY.

A: bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
//addr.sin_addr.s_addr = inet_addr(my_ipv4Addr);
addr.sin_port = htons(port);

mreq.imr_multiaddr.s_addr = inet_addr(group);
// [-]    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
mreq.imr_interface.s_addr = inet_addr(my_ipv4Addr);

You just need to edit your code like mine.

A: with
addr.sin_addr.s_addr=inet_addr(my_ipv4Addr);
bind(sockfd,(SA*)&addr,sizeof(addr));
you can only send out packets to the multicast group,
but you can't recv any packets, even those send out from `my_ipv4Addr'.
so addr.sin_addr.s_addr must be htonl(INADDR_ANY).
with
mreq.imr_interface.s_addr=inet_addr(my_ipv4Addr);
you can recv all packets from the multicast group,
but it send out packets with the default interface (maybe eth0),
not the one you specified (like eth1).
So this is no effect.
with
setsockopt(sockfd,SOL_SOCKET,SO_BINDTODEVICE,ETH1,strlen(ETH1));
you can send out packets through the interface ETH1,
but you can only recv packets send out from the ip associated with ETH1,
you can't recv any packets from other clients.
with
mreq.imr_interface.s_addr=inet_addr(my_ipv4Addr);
setsockopt(sockfd,IPPROTO_IP,IP_MULTICAST_IF,&mreq.imr_interface,sizeof(struct in_addr);
you can send out packets through the interface associated with my_ipv4addr,
also you can recv any packets from any clients in the multicast group.

A: Either you simplified your code for the sake of understanding or i have missed something,
This is the struct
struct ip_mreqn {
    struct in_addr imr_multiaddr; /* IP multicast group
                                     address */
    struct in_addr imr_address;   /* IP address of local
                                     interface */
    int            imr_ifindex;   /* interface index */
};

ip man page - IP_ADD_MEMBERSHIP
But you are referring
mreq.imr_interface.s_addr = inet_addr(my_ipv4Addr);

What is imr_interface? Does it compile?
In case you just wrote the name above for better readibility, have you tried filling the interface index i.e. imr_ifindex to the specific interface you want to attach to.
My guess is, if you leave the imrr_address and assign the interface index only, it should bind to that interface and receive packets. See if that helps.


text:
Q: Linking from a column value in jqGrid to a new page using GET I have created a jqGrid that contains some fields such as:
job_id, name, etc
What I am trying to do is make so that when the click on the value in the job_id column, it will redirect them to:
job.php?job_id=(value that they clicked on)
I started by trying to use the following as my colModel:
{ name:'job_id', index:'job_id', edittype:'select', formatter:'showlink',
  formatoptions:{baseLinkUrl:'job.php'}, width:50, align:'center' }

But what this results in is a redirection to:
job.php?job_id=(row_id)
I did some searching, and found a post by the developer of the open source version of this software who suggested using the following colModel and additional JS:
{ name:'job_id', index:'job_id', edittype:'select', formatter:'showlink',
  formatoptions:{baseLinkUrl:'#'}, width:50, align:'center' }

loadComplete: function() {
    var myGrid = $("#home_list");
    var ids = myGrid.getDataIDs();
    for (var i = 0, idCount = ids.length; i < idCount; i++) {
        $("#"+ids[i]+" a",myGrid[0]).click(function(e) {
            var hash=e.currentTarget.hash;// string like "#?id=0"
            if (hash.substring(0,5) === '#?id=') {
                var id = hash.substring(5,hash.length);
                var text = this.textContent;
                location.href="job.php?id="+text;
            }
            e.preventDefault();
        });
    }
}

But this is not compatible with IE.  In addition to this, when displaying a large number of rows in the jqGrid, it takes a extremely long time to load, say 5 seconds + for 500 rows.
I'm going to keep working on this, but is this something that anyone else has done?

A: You used code example from my old answer so I decide I should answer on you question.
I agree with the critic about performance of the code of the loadComplete. So +1 from me for your question. The construct $("#"+ids[i]+" a", myGrid[0]) inside of long loop can work very slowly. One can easy fix the problem if one will use the following
var getColumnIndexByName = function (columnName) {
    var cm = $(this).jqGrid("getGridParam", "colModel"), l = cm.length, i;
    for (i = 0; i < l; i++) {
        if (cm[i].name === columnName) {
            return i; // return the index
        }
    }
    return -1;
};

var myGrid = $("#list");
myGrid.jqGrid({
    ...
    loadComplete: function () {
        var i = getColumnIndexByName.call(this, 'Subcategory');
        // nth-child need 1-based index so we use (i+1) below
        $("tbody>tr.jqgrow>td:nth-child(" + (i+1) + ")>a", this).click(function (e) {
            var hash=e.currentTarget.hash;// string like "#?id=0"
            if (hash.substring(0,5) === '#?id=') {
                var id = hash.substring(5, hash.length);
                var text = this.textContent || this.innerText;
                alert("clicked the row with id='"+id+"'. Link contain '"+text+"'");
                location.href = "http://en.wikipedia.org/wiki/" + text;
            }
            e.preventDefault();
        });
    }
});

You can see that the improved version of the demo works exactly as the original demo. To show the performance of the method on 1000 rows I created one more demo. One can see that the new method works quickly.
Now back to your main problem. The best performance we will receive if you write your custom formatter and unformatter instead of the usage of the predefined formatter showlink. The code can be about following:
formatter: function (cellvalue, options, rowObject) {
    return "" + cellvalue + "";
},
unformat: function (cellvalue, options, cellobject) {
   return cellobject.job_id;
}

The exact code depend on which datatype you use, whether you use loadonce:true or not and which jsonReader you use. It can be for example, that rowObject is array in your case and you have to use
array index of the corresponding data field (like rowObject[4]) instead of rowObject.job_id.
UPDATED: I think the best implementation way will be the usage of onCellSelect or beforeSelectRow instead of binding click event to every  element in the column. I recommend to read the following answers for details: this one, another one and one more old answer.


text:
Q: Is there a limit on the current carrying capacity of a wire? Obviously, for continuous current there is - the melting point. If it is superconducting, the field strength at which it quenches. OTOH if we specify a pulse of arbitrarily short timescale in order to avoid melting we introduce high frequency components that create a skin effect, which in turn feeds back into any current limitation.
However - is there any other physical limit on the current carrying capacity? For example, at some point the field is going to liquify the metal due to sheer pressure. What else?