text:
Q: cordova android install error on mac I am trying to create a phonegap app, but each time I try to add a platform I get this error:
Creating a new cordova project with name "HelloWorld" and id "com.mc2now.hello" at location "/Users/tony/Desktop/eclipse/eclipse"
imac-6:eclipse tony$ cd eclipse
imac-6:eclipse tony$ cordova platform add android
Creating android project...

/Users/tony/.cordova/lib/android/cordova/3.4.0/bin/node_modules/q/q.js:126
                    throw e;
                          ^
Error: The command "android" failed. Make sure you have the latest Android SDK installed, and the "android" command (inside the tools/ folder) is added to your path.
    at /Users/tony/.cordova/lib/android/cordova/3.4.0/bin/lib/check_reqs.js:85:29
    at _rejected (/Users/tony/.cordova/lib/android/cordova/3.4.0/bin/node_modules/q/q.js:808:24)
    at /Users/tony/.cordova/lib/android/cordova/3.4.0/bin/node_modules/q/q.js:834:30
    at Promise.when (/Users/tony/.cordova/lib/android/cordova/3.4.0/bin/node_modules/q/q.js:1079:31)
    at Promise.promise.promiseDispatch (/Users/tony/.cordova/lib/android/cordova/3.4.0/bin/node_modules/q/q.js:752:41)
    at /Users/tony/.cordova/lib/android/cordova/3.4.0/bin/node_modules/q/q.js:574:44
    at flush (/Users/tony/.cordova/lib/android/cordova/3.4.0/bin/node_modules/q/q.js:108:17)
    at process._tickCallback (node.js:415:13)
Error: /Users/tony/.cordova/lib/android/cordova/3.4.0/bin/create: Command failed with exit code 8
    at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/src/superspawn.js:112:23)
    at ChildProcess.EventEmitter.emit (events.js:98:17)
    at maybeClose (child_process.js:743:16)
    at Process.ChildProcess._handle.onexit (child_process.js:810:5)

so, my question is how to add android to my path? I have tried this:
imac-6:eclipse tony$ export PATH=${PATH}:adt-bundle/sdk/platform-tools:/adt-bundle/sdk/tools

can someone please explain what I am doing wrong? Any help is much appreciated!

A: I had the same problem and it appeared to be permission problems in the installed adt-bundle.
the following fixed it for me:
$ sudo chown -R $(whoami) /Development/adt-bundle

A: Try going to your user directory cd ~/ and edit .bash_profile then add export PATH=${PATH}:adt-bundle/sdk/platform-tools:/adt-bundle/sdk/tools to that file.
Save, close the terminal and start it up again.

A: I had the same error on my linux box.
I fixed putting android sdk "tools" subdir in my system PATH env variable.
For example:
export PATH="/opt/android/adt-bundle-linux-x86_64-20140321/sdk/tools:$PATH"

You should also include "platform-tools" subdir.


text:
Q: Disable hidden form input I have a form kinda like this:
<form action="#" method="post">
 <select name="phase">
   <option>1</option>
   <option>2</option>
   <option>3</option>
 </select>

  <input type="text" name="info" />

  <input type="text" name="info" />

  <input type="text" name="info" />

</form>

By using JQuery, at any time, only one of the DIVs is displayed, corresponding to the value in the select box.
The issue is that the value POSTed is overridden by the last text input, since they all have the same name. Is there away around this WITHOUT renaming the inputs?

A: Yes -- before submission, dynamically remove the unwanted div sections.  You could do this by hooking in using jQuery's submit() function callback.
To remove the elements, you could use jQuery's remove() function, for example.  It would be easier with div ids, but you could also use indexes to do it.

A: You can dynamically rename the inputs with javascript before submitting the form. Or you could even remove the disabled inputs from the DOM just before submission.
For example, something like this may work:
$(input[name="info"]).filter(function() {
    return $(this).css('display') == "none";
}).remove();

So, select all the inputs named "info" that have display: none and remove them.

A: I so sorry to say this: you'll have to rename the name of each div. something like this
name="info1" name="info2" name="info3"
you only use the same name for the name attribute when you dealing with radio input type.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get parent with more than 2 child Table structure:
| id | parent |
   1     0
   2     1
   3     1
   4     2
   5     2
   6     2

How can I get the id of the parent row that have more than 2 childs ?
(in the above case should return only the id=2 row)

A: Try this query
SELECT *
FROM tablename
WHERE id IN
(
    SELECT parent
    FROM tablename
    GROUP BY parent
    HAVING COUNT(parent) > 2
)

A: I believe this is enough to find the parent id
SELECT parent
FROM   tablename
GROUP  BY parent
HAVING Count(parent) > 2


text:
Q: Split strings in array to form three-element subarrays I am practising with the AdventureWorks database for now and I will be receiving strings like the following:   SalesOrderNumber=SOH123 and  CustomerID=1.  The strings may not always contain =, as they may be >, <, >=, <=, !=, <>.
Ideally, I would like to split each string into 3 fields - the database column to query, the comparison (e.g. =, >, !=, etc) and the value to search for.
I can achieve what I want with lots of code, comparing character by character, but I am hoping someone can suggest a really simple way to do this, as I am sure this must be a fairly common task for websites.
I don't want to just use the strings as they come through, as I need to sanitise them first. I also don't want to send bad queries to the database that may generate SQL errors.

A: This is my aproach using foreach, explode and array functions:
$strings = [
    'SalesOrderNumber=SOH123',
    'CustomerID=1',
    'BigOrEqual>=44',
    'SmallOrEqual<=67',
    'NotEqual!=123',
    'NotEqual<>2000',
    'Smaller<21',
    'Bigger>12',
];
function explodeOperators(array $strings) : array
{
    $operators = ['>=','<=','!=','<>','<','>','=']; // do not change this order
    $result = [];
    foreach ($strings as $expression) {
        $found = false;
        foreach ($operators as $operator) {
            $exploded = explode($operator, $expression);
            if (count($exploded) > 1 and $found === false) {
                $found = true;
                array_splice($exploded, 1, 0, $operator);
                $result[] = $exploded;
            }
        }
    }
    return $result;
}
$result = explodeOperators($strings);
print_r($result);

That will result:
Array
(
    [0] => Array
        (
            [0] => SalesOrderNumber
            [1] => =
            [2] => SOH123
        )

    [1] => Array
        (
            [0] => CustomerID
            [1] => =
            [2] => 1
        )

    [2] => Array
        (
            [0] => BigOrEqual
            [1] => >=
            [2] => 44
        )

    [3] => Array
        (
            [0] => SmallOrEqual
            [1] => <=
            [2] => 67
        )

    [4] => Array
        (
            [0] => NotEqual
            [1] => !=
            [2] => 123
        )

    [5] => Array
        (
            [0] => NotEqual
            [1] => <>
            [2] => 2000
        )

    [6] => Array
        (
            [0] => Smaller
            [1] => <
            [2] => 21
        )

    [7] => Array
        (
            [0] => Bigger
            [1] => >
            [2] => 12
        )

)

A: It is indirect and feasibly inefficient to make calls of explode() within nested loops with break condition.
I recommend preg_split() as the right tool for the job.  Create a capture group containing a character class of whitelisted symbols.  Allow a maximum of 3 elements as its return value.  Use the PREG_SPLIT_DELIM_CAPTURE flag to inform the function to preserve the delimiting comparison operators when exploding the string into three parts.
Code: (Demo)
var_export(
    array_map(
        fn($v) => preg_split(
            '/([!<=>]+)/',
            $v,
            3,
            PREG_SPLIT_DELIM_CAPTURE
        ),
        $array
    )
);

Output:
array (
  0 =>
  array (
    0 => 'SalesOrderNumber',
    1 => '=',
    2 => 'SOH123',
  ),
  1 =>
  array (
    0 => 'CustomerID',
    1 => '=',
    2 => '1',
  ),
  2 =>
  array (
    0 => 'BigOrEqual',
    1 => '>=',
    2 => '44',
  ),
  3 =>
  array (
    0 => 'SmallOrEqual',
    1 => '<=',
    2 => '67',
  ),
  4 =>
  array (
    0 => 'NotEqual',
    1 => '!=',
    2 => '123',
  ),
  5 =>
  array (
    0 => 'NotEqual',
    1 => '<>',
    2 => '2000',
  ),
  6 =>
  array (
    0 => 'Smaller',
    1 => '<',
    2 => '21',
  ),
  7 =>
  array (
    0 => 'Bigger',
    1 => '>',
    2 => '12',
  ),
)


text:
Q: Applying stream sequence on a slice in go using ghemawat/stream Assume that you have a slice items and you want to apply a sequence of stream operations on this slice using stream package: ghemawat/stream. how one can do this? to my knowledge the only way to give a stream sequence string input is to use stream.items(items ...string) which can't be used on slices.

A: The solution I found is to use the trick below:
we start by using stream.Numbers(1, len(items)) and adding a map filter stream.Map(fn func(string) string) like this:
package main

import("strconv")

func main() {
    sliceStreamExample()
}

func sliceStreamExample() {
    items := []string{"foo", "bar"} // define a sample slice

    stream.Run { // using Map to and Numbers to emit the slice content
        stream.Numbers(1, len(items)),
        stream.Map(func(num string) string {
            return items[strconv.Atoi(num)]
        }),
        stream.WriteLines(os.Stdout)
    }
}

output:
foo
bar

I don't know if its the optimal way or not. please share your solution if you found an easier one! thanks.


text:
Q: Clojure Update Atom PersistentQueue I am trying to maintain a queue of orders and "cook" them using the FIFO process. Using the atom I am able to update the queue but the last two line are not working. What I need is to remove the first element and update the atom(queue) with the remaining list.
Thanks,
R.
(ns example.atomqueue
  (:use clojure.pprint))

(def orders-queue (atom clojure.lang.PersistentQueue/EMPTY))

(defrecord Order [fplate splate])

(defn add-order [order]
  (swap! orders-queue conj order))

(add-order (->Order "Soup" "Fish&Chips"))
(pprint orders-queue)

(add-order (->Order "Salad" "Hamburger"))
(pprint orders-queue)

(add-order (->Order "Rice" "Steak"))
(pprint orders-queue)

;;NOT SURE IF CORRECT
(defn cook-order [orders]
  (swap! orders-queue (pop orders)))

;;EXCEPTION
(cook-order orders-queue)

A: Thanks to Mr. leetwinski this is the right solution:
(ns chaptertwo.atom
  (:use clojure.pprint))

(def orders-queue (atom clojure.lang.PersistentQueue/EMPTY))

(defrecord Order [fplate splate])

(defn add-order [order]
  (swap! orders-queue conj order))

(defn cook-order [] (swap! orders-queue pop))

(add-order (->Order "Soup" "Fish&Chips"))
(pprint orders-queue)

(add-order (->Order "Salad" "Hamburger"))
(pprint orders-queue)

(add-order (->Order "Rice" "Steak"))
(pprint orders-queue)

(cook-order )
(pprint orders-queue)


text:
Q: How to partition a problem into smaller understandable portions? I'm not sure if it's possible to give general advice on this topic, but please try. It's hard to explain my case because it's too complex to explain. And that's exactly the problem.
I seem to constantly stumble on a situation where I try to design some part of my project, but it has so many things to take into consideration that I'm unable to get a grasp of it.
Are there any general tips or advice on how to look at my system in smaller pieces at a time? How to find smaller portions that could be designed separately on their own?

A: Create a glossary.
In other words, identify the terms that are meaningful to the project domain — not from the programmer's point of view, but from a user's, who is familiar with the subject matter.
Then define the terms as precisely and discretely as you can.  A good definition in this form can serve as a kind of pseudocode.
Since you have not identified even the domain of your problem, I'll choose a random example.  In a civilian personnel system, you might have terms like:

*

*billet: a term of service (from start date to end date) at a particular grade and step

*employee: a series of billets associated with a particular SSN

*grade and step: row and column in the federal general schedule

And so on.  This isn't to identify functional units, as it sounds like you are trying to do, but it's a good preparatory step before doing so, so that you can express your functional steps in well-defined terms.

A: It's useful to approach problem decomposition both top-down and bottom-up.
If you're having trouble splitting a big problem into two or more smaller problems, try to think of the smallest possible problems that will need to be solved.  Once those are handled, you may start to see ways to combine them into larger problems as you approach your original large problem.

A: Your key goals are:

*

*High cohesion: Code (methods, fields, classes) within one piece/module/partition should interact intensively; it should make sense for these elements to know about each other. If you find that some of them don't interact much with the rest, they probably belong somwhere else or should form their own partition. If you find code outside interacting intensively with the partition and knowing too much about its inner workings, it probably belongs inside. The typical example is found in OO code written in procedural style, with "dumb" data objects and "manager" code that operates on them but should really be part of the data objects.

*Loose coupling: Interaction between pieces/modules/partitions should only happen through narrow, well-defined, well-documented APIs. Try to identify such APIs and see what code is needed to implement them and what code will use them.

A: When I find myself copying and pasting chunks of code with minimal adjustments I realize that's a "partition" and then create a class, method, function, or whatever.
Actually, the whole object oriented approach is what it's all about.  Try thinking of your application as tangible things that do stuff.  Write pseudo code describing what the things are and what they do, I find lots of "partitions" this way.

A: Here's a try, kind of wild guess.
People usually underestimate how long it will take them to do the work. If your project is large, then most likely you'll need several people to work on it, so you can try planning with that in mind. Now a person can be expected to hold just one area in the head, so you'll need to explain to him exactly what kind of task he's supposed to do.
So I'd say you should try to write a job description that should encompass as much as possible for one person to seriously concentrate on. Repeat, until you have broken your project into parts you wanted to. As a benefit, you're ready to assemble your team. But if you find out the parts are small, maybe you'll still be able to do it yourself.


text:
Q: How to fix jQuery Promise .then() from being called before the AJAX function is executed completely? I am using Promise to execute my AJAX function, and am using `.then()' when calling the function to imply that anything in the .then() scope is executed once the AJAX function is executed. However, the .then() still executes before the AJAX function is fully done retrieving data from the server. I have been stuck on this for really long, and am unable to figure out what exactly is causing the issue. Is my code wrong? Below is my code. Any help will be deeply appreciated!
Calling the AJAX Function
userLayer = this.addUserLayerTreemail(
            $loadingContent,
            $loadingDiv,
            treeLayers,
            map,
            heritage_cluster_layer_view_18,
            flowering_cluster_layer_view_18,
            IMP_FIELDS,
            suggestion,
            userPlottedLayerView18Options,
            userLayer,
            $speciesError
          ).then( function(response){
            //this gets executed before the function retrieves all the data from the server - it should return true, but returns false
            console.log(map.hasLayer(userLayer), "check if layer exists")
            setSearchState(true);
            $mapSearch.blur();
          }).catch(function(err){
            console.log("error caught", err)
          });

Defining the AJAX Function
addUserLayerTreemail(
  $loadingContent,
  $loadingDiv,
  treeLayers,
  map,
  heritage_cluster_layer_view_18,
  flowering_cluster_layer_view_18,
  IMP_FIELDS,
  suggestion,
  userPlottedLayerView18Options,
  userLayer,
  $speciesError
) {

  // let checked = this.getCurrentFilter(),
  const featureType = 'USERTREE';

  let queryString = '';

  suggestion = suggestion.toLowerCase();

  let $selectedOptionSearch = $('.mapFilterBtns.is-active').data('value');
  let all_trees="";

  let searchText= $('#mapSearch').val();

  let configData = {"searchText": searchText, "searchType" : $selectedOptionSearch};

    console.log("config", configData)

    // this function is called in the resolve() function below
    function retrieveTrees(response) {

    let conditionalVal = " or ";
          let treeID = "";

          for(let i=0; i<response.length; i++) {
            treeID = response[i]['MYTreeID']
            if(i==0) {
                all_trees = `${IMP_FIELDS.TREEMAIL_SEARCH} like '%${treeID}%'`;
            } else {
                all_trees += conditionalVal + `${IMP_FIELDS.TREEMAIL_SEARCH} like '%${treeID}%'`;
            }
          }

          console.log("all trees here",all_trees);

          queryString = all_trees + ` and Actual_Tree_Type like '%${featureType}%'`;

          let isSearch = true;

          let layerOptions = $.extend(
            {
              where: queryString
            },
            userPlottedLayerView18Options
          );

          layerOptions.url = mapLayers.userPlantedLayer;

          userLayer = L.esri.featureLayer(layerOptions);

          userLayer
            .query()
            .where(queryString)
            .run((err, featureCollection, response) => {

              if (featureCollection.features.length > 0) {

                removeClass($loadingDiv, 'show');
                //adding the userLayer to the map
                userLayer.addTo(map);
                //this returns true after the .then() chunk is executed in the call above
                console.log(map.hasLayer(userLayer), "checking in ajax")

            });
            console.log(map.hasLayer(userLayer), "checking in ajax ")

          return userLayer;
    }

    return new Promise(function(resolve, reject){

      $.ajax({
        url: "../apis/treemailSearch",
        method: 'GET',
        dataType: 'json',
        data : configData,
        contentType: 'application/json',
        success: response => {
          return resolve(retrieveTrees(response));

              },
              error : function(err){
                reject(err, "printing error here");
              }
      });

    })
}


text:
Q: Поиск по table и вставка новой tr после найденной Сам пхпшник.С фронтом почти не работал. Задача: пишу расширение для Хрома. Со всем справился, кроме одного. В Storage у меня хранится JSON мне нужно найти совпадение ключа с path от урла, который внутри таблицы в href.   И после того как я нашел, я должен нарисовать  еще один ...... после найденного tr.

blabla">	 ... 	  ... много

blabla">	 ... 	  ... много

Получить ссылки получилось. Но не пойму как получить родителя tr чтобы после него сделать вставку. Без jQuery, ибо с ним я умею.
var links = document.getElementsByTagName('a');

for(var i = 0; i< links.length; i++){
  //alert(links[i].href);

  let parent = links[i].closest('td');

  //как узнать тут родительскую tr ?
   console.log(parent);
}

A: Можно так:

var links = document.getElementsByTagName('a');

for(const link of links){
  let parent = link.closest('tr');
  const newTr = document.createElement('tr');
  parent.after(newTr);
  const newTd = document.createElement('td');
  newTr.appendChild(newTd);
  newTd.textContent = 'New content.';
}

blabla

blabla


text:
Q: Which match takes precedence when exporting an NFS share? Say you're exporting an NFS share using IP addresses and netmasks to give different machines different permissions:
[/etc/exports]
/media/shared 192.168.0.64/26(rw,[...]) 192.168.0.0/24(ro,[...])

In case the ranges overlap and a machine will match both expressions, which one will take precedence? Is this allowed? What permissions will this client get?

A: In that case first match wins since the two expressions are of the same type.  (A single host expression would win even if it came after the IP subnet expression because it has precedence.)  See exports(5) for details.


text:
Q: Some information about how to correctly extract DateTime from an XML document in C#? I have the following situation.
In a C# program I initialize some object fields using the content of an XML file.
In the XML file I have the 2 followings date time fielnds:
<x:Published>May 21 2014</x:Published>
<x:LastUpdated>2014-05-21T17:00:38</x:LastUpdated>

As you can see these fields have different format.
To initialize the related object field in my code I found:
currentDeepSightVuln.Published = n_alertdocument.SelectSingleNode("./x:Published", nsmgr) == null ? DateTime.MinValue : DateTime.ParseExact(n_alertdocument.SelectSingleNode("./x:Published", nsmgr).InnerText, "MMM dd yyyy", System.Globalization.CultureInfo.InvariantCulture);

currentDeepSightVuln.LastUpdated = n_alertdocument.SelectSingleNode("./x:LastUpdated", nsmgr) == null ? DateTime.MinValue : XmlConvert.ToDateTime(n_alertdocument.SelectSingleNode("./x:LastUpdated", nsmgr).InnerText);

Is it right? Can I use the XmlConver.ToDateTime() method also for the firs XML data field? Why they used the ParseExact() and not XmlConvert.ToDateTime()
Tnx

A: Yes, you should be able to use XmlConvert.ToDateTime by specifying the format string, as you're doing with DateTime.ParseExact:
XmlConvert.ToDateTime("May 21 2014", "MMM dd yyyy")

This method will end up calling DateTime.ParseExact, so it doesn't really matter which option you choose, as long as you're consistent.
For reference, here's the implementation of XmlConvert.ToDateTime(string, string[]):
public static DateTime ToDateTime(string s, string[] formats)
{
    return DateTime.ParseExact(s, formats, (IFormatProvider) DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
}

A: The XML Schema specification defines the representation expected for dates and times stored in an XML document. The XmlConvert.ToDateTime overloads which only take a single string are expecting to use this format. By using that method, rather than a variant of DateTime.Parse, you're saying you expect the interoperable format.
XmlConvert.ToDateTime does have overloads which take one or more format parameters to try, but those overloads are still a subset of the full string.
The Published date in your file does not conform to the XML Schema date data type, so it must be parsed with a method that can handle that format. DateTime.Parse can, XmlConvert.ToDateTime will reject it as an invalid format.


text:
Q: Calling only date from datagridview to a textbox  private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0)
        {
            DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
            textBox3.Text = row.Cells["StartDate"].Value.ToString();

I am trying to pass the date data (Appear as 8/24/2017 in database) from datagridview to a textbox to display the start date given in the picture below. However the time (12:00:00AM) kept appearing even when the data type is Date and not datetime. May I know what is the solution to the problem here?

A: You can parse value from the "StartDate" cell into DateTime and then use ToShortDateString() method to get desired output:
var startDate = DateTime.Parse(row.Cells["StartDate"].Value);
var startDateDisplay = startDate.ToShortDateString();

Note: Keep in mind that Parse method uses Date format from the current culture, so if you have different date format, consider using TryParse method instead or one of the Parse method overloads in which you'll provide specific format.

A: Check if your cell contains value, and if it does, cast it to DateTime (since it came from database, there's no need to use parsing).
Take a look at this example
if (e.RowIndex >= 0)
{
    DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
    if (row.Cells["StartDate"].Value != null)
    {
        DateTime date = (DateTime) row.Cells["StartDate"].Value;
        //now convert DateTime fo any text format you want to use
        textBox3.Text = date.ToShortDateString();
        //or, you can use some custom format
        //textBox3.Text = date.ToString("MM/dd/yyyy");
        //textBox3.Text = date.ToString("ddd MM/dd/yyyy");
        //etc

    }
}

also, take a look at msdn custom date and time formats


text:
Q: Google Maps InfoBox and ajax call causing multiple to render Having an issue with how I have implemented the InfoBox and am wondering if anyone has insight about possible solutions.
Currently I have ~1000 client side markers which are all being dynamically added to the page. They are being generated using the following .
 var cir = new google.maps.Marker({
            position: new google.maps.LatLng(l.lat, l.lng),
            map: map,
            icon: icons[l.type].simple
        });
        addClickHandlerAjax(cir, l);
        l.m = cir;

The method addClickHandlerAjax is what is invoked when the marker is clicked on. Here is the basics of this method .
function addClickHandlerAjax(marker, l) {

    google.maps.event.addListener(marker, "click", function () {

        if(theInfoWindow){
        theInfoWindow.close();
       // InfoWindow = null;
        }
        //get content via ajax
        $.ajax({
            url: 'map/getInfo',
            type: 'get',
            data: {
                'ID': l.f
            },
            success: function (data, status) {
                if (status == "success") {
                    //create infowindow here..
                           theInfoWindow= new InfoBox({
                            content: document.getElementById("infobox-wrapper-hotel"),
                            disableAutoPan: true,
                            enableEventPropagation: true,
                            closeBoxURL: '../assets/images/info-close.png',
                        });
                        theInfoWindow.open(map, marker);
                        touchScroll('rab-scroll');

                });
                }
            },
            error: function (xhr, desc, err) {
                console.log(xhr);
                console.log("Details: " + desc + "\nError:" + err);
            }
        }); // end ajax call
    });
}

The issue is when users click on multiple markers very quickly. The infoboxfor a previous marker could remain opened. But it may contain nothing in it.
Does anyone know how to properly handle multiple infobox by safely closing all instances of the infobox?
I do not see this behavior in this implementation Jsfiddle

A: The simplest fix: if you only want one InfoBox open at a time, create one in the global scope, and use that for all the markers.  The fiddle you reference does that (var ib = new InfoBox(); is the single global InfoBox).
To address the lengthy response time, change your ajax processing to take that into account (only close the existing infowindow when the callback function succeeds):
function addClickHandlerAjax(marker, l) {

    google.maps.event.addListener(marker, "click", function () {

        //get content via ajax
        $.ajax({
            url: 'map/getInfo',
            type: 'get',
            data: {
                'ID': l.f
            },
            success: function (data, status) {
              if (status == "success") {
                // close the existing infowindow only if the AJAX response succeeds
                if(theInfoWindow){
                  theInfoWindow.close();
                }
                // remove the existing infowindow from the map if the AJAX response succeeds
                if (theInfoWindow.setMap) theInfoWindow.setMap(null);
                //create a new infowindow here, with the returned content..
                theInfoWindow= new InfoBox({
                   content: document.getElementById("infobox-wrapper-hotel"),
                   disableAutoPan: true,
                   enableEventPropagation: true,
                   closeBoxURL: '../assets/images/info-close.png',
                });
                theInfoWindow.open(map, marker);
                touchScroll('rab-scroll');
              });
            }
          },
          error: function (xhr, desc, err) {
              console.log(xhr);
              console.log("Details: " + desc + "\nError:" + err);
          }
        }); // end ajax call
    });
}


text:
Q: libgit2sharp remove remote branch I want to delete a branch locally and remote.
My code:
using (var repository = new Repository(path))
{
    var remote = repository.Network.Remotes["origin"];
    var options = new PushOptions();
    var credentials = options.CredentialsProvider = GetUserCredentialsProvider();
    options.CredentialsProvider = credentials;
    string pushRefSpec = @"refs/heads/:{0}".FormatWith(branch);
    repository.Network.Push(remote, pushRefSpec);
    repository.Branches.Remove(repository.Branches[branch]);
}

But I get the 401 error ("Unauthorized").
And it's because of the presence of the ":" in the name of the branch.
But I read that they are necessary, because of they are like "--delete" in native git.
Thanks for any helps!

A: This is failing with a 401 Unauthorized error because it is unauthorized.  To fix this error, you just need to pass the options containing your credentials to the Push() method:
repository.Network.Push(remote, pushRefSpec, options)

That fixed this problem for me.

A: I just figured out the solution from the libgit2 sourcecode.
repository.Network.Push(origin, "+:/refs/heads/to-remove-branch")

The part +:/refs/heads/to-remove-branch of the refspec specifies that the remove command is forced, else just use :/refs/heads/to-remove-branch
Source: https://github.com/libgit2/libgit2/blob/master/tests/online/push.c


text:
Q: Trouble with Array within Object pasting as props I am not sure if this is a react issue or a javascript issue.
I have data setup in my state that are objects that contain arrays of objects.
These arrays of objects don't come down properly.
I am attempting to pass the whole array of objects into a sub component as a prop and then iterate over that array to render out each object.  No matter what I do I can't seem to access the array properly.
I hope this is the best way to give you all of my details.
Here is a portion of my state (I only opened one of the groups)
    context.js:72
    (3) [{…}, {…}, {…}]
    0: {id: "5c0fd8da9af84012ee8b5edf", title: "Test", groups: Array(1)}
    1:
    groups: Array(4)
    0: {id: "5c2fdff78b3f6295dce3f63d", title: "Group #1", commands: Array(0)}
    1: {id: "5c2fdffc8b3f6295dce3f63e", title: "Group #2", commands: Array(0)}
    2: {id: "5c2fdfff8b3f6295dce3f63f", title: "Group #3", commands: Array(0)}
    3: {id: "5c2fe0028b3f6295dce3f640", title: "Group #4", commands: Array(0)}
    length: 4
    __proto__: Array(0)
    id: "5c10307e0ba810224f988e4c"
    title: "Test 2"
    __proto__: Object
    2: {id: "5c2fb6930fb58e8ce67977cc", title: "Next Silo Test", groups: Array(3)}
    length: 3
    __proto__: Array(0)

Now I want to access the groups array of the silo.  I have backed all the way to the root of my app and still have this problem so it's beyond the prop not passing right.
if I console log the silo and the group items this is the results
    silo
    {id: "5c10307e0ba810224f988e4c", title:
    "Test 2", groups:                 Array(0)}groups: (4) [{…}, {…}, {…}, {…}]0: {id: "5c2fdff78b3f6295dce3f63d",
    title: "Group #1", commands: Array(0)}1: {id: "5c2fdffc8b3f6295dce3f63e", title: "Group #2", commands: Array(0)}
    2: {id: "5c2fdfff8b3f6295dce3f63f", title: "Group #3", commands: Array(0)}
    3: {id: "5c2fe0028b3f6295dce3f640", title: "Group #4", commands: Array(0)}length:
    4__proto__: Array(0)id: "5c10307e0ba810224f988e4c"title: "Test 2"
    __proto__: Object
    17:05:57.127 Main.js:17 silo.groups []0: {id: "5c2fdff78b3f6295dce3f63d",
    title: "Group #1", commands: Array(0)}1: {id: "5c2fdffc8b3f6295dce3f63e", title: "Group #2", commands: Array(0)}
    2: {id: "5c2fdfff8b3f6295dce3f63f", title: "Group #3", commands: Array(0)}
    3: {id: "5c2fe0028b3f6295dce3f640", title: "Group #4", commands: Array(0)}
    length: 4
    __proto__: Array(0)
    17:05:57.128 Main.js:18 silo.groups[0] undefined

From here what I see is that silo is an object and silo.groups is an array.  I can't access any of the elements inside of that array.  even though it shows length of 4 if I do silo.groups.length I get 0 back instead of 4.
I am iterating over the root array with silos.forEach(silo => { and expected the same to work for the each silo.groups.
Here is the code that creates the output before.  the first console.log is from just dumping the value of silos when it's loaded into state in the context script.  Before that completes this component would never render.
const { silos, user } = value
      if (Object.keys(user).length > 0) {
          const siloList = []
          silos.forEach(silo => {
            console.log("silo",silo)
            console.log("silo.groups",silo.groups)
            console.log("silo.groups[0]",silo.groups[0])

I can't figure out what I am missing or what I am getting wrong here.
I can do this by itself if I create a JSON object with this structure I can use these same code to drill into it and get the items back out of each array within each object.  Something is changing when this is done within this app somewhere.  I can't see where though.
--Edit: Adding repo for project --
If it helps anyone here is a github repo of the project as it is right now
https://github.com/jeremyhawkins1/robin.git


text:
Q: How to implement nested live data? How to implement nested live data in android : I need to pass the serverMovies to second level of Live data
Is this possible ?
   activityViewModel.getAllMovies().observe(this, new Observer<List<Movie>>() {
                @Override
                public void onChanged(List<Movie> serverMovies) {
                    Log.d("",serverMovies+"");

                    activityViewModel.insertMoviesIntoLocalDatabase(serverMovies).observe(this, new Observer<List<Movie>>() {
                        @Override
                        public void onChanged(@Nullable List<Movie> movies) {
                            Log.d("",movies+"");
                            /*contactArrayList.clear();
                            contactArrayList.addAll(contacts);
                            contactsAdapter.notifyDataSetChanged();*/

                        }
                    });
                }

     });

A: I could also achieve using switchmap:
Transformations.switchMap(
      activityViewModel.getAllMovies(), (x) ->
      activityViewModel.insertMoviesIntoLocalDatabase(x))
      .observe(this, movies ->
       movieAdapter.setData(new ArrayList<>(movies))
 );

A: You need to add a Mediator Live Data that reacts to changes in the movies live data.
Something like this,
LiveData<List<Movies>> moviesLiveData = getAllMovies();
MediatorLiveData mediatorLiveData = new MediatorLiveData<>();
mediatorLiveData.addSource(moviesLiveData, value -> mediatorLiveData.setValue(value));

So when the value of the original live data changed the value of the mediator live data changes too, then you can observe it anyway you want.


text:
Q: Using an ENV variable with the url in a link_to in rails I have the URL for the ISSUES in an environment variable. I have an image, that when clicked is supposed to direct one to that URL. I've read the documentation on the link_to tag and have tried several variations to no avail.  Here is what I have:
<%= link_to "{<%= ENV["ISSUES_SERVER"] %>}" do %>
   <%= image_tag("/assets/bug.gif", :size => "27x25" %>
<% end %>

How do I get the ENV["ISSUES_SERVER"] as the URL for the link_to?

A: Tried the most obvious, which I had overlooked as it looked too easy.  It looked like it need something surrounding it at first.
<%= link_to ENV["ISSUES_SERVER"],  :target => "_blank" do %>
   <%= image_tag("/assets/bug.gif", :size => "27x25") %>
<% end %>

This worked quite well.  I have noticed that I can no longer have the image change its' highlighting as I mouse over it after these changes.  I can live with that, I suppose.


text:
Q: What namespace holds information on the SQL Server TinyInt datatype? I have this code:
DataTable answers = new DataTable();
answers.Columns.Add("Response", typeof(TinyInt));
foreach (AnswerRow a in answer.AnswerRows)
{
    answers.Rows.Add(a.Response);
}

However it is giving me an error with TinyInt saying the "type or namespace cannot be found"
Does anyone know what I need to include to make it so that I can use this?
Here's my current includes?
using Entities.Models.Core;
using Microsoft.AspNet.Identity;
using Models.Http;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using WebRole1.Helpers;
using System.Data.SqlClient;
using WebRole1.Filters;
using System.Data.Entity.Infrastructure;
using System.Data;

A: TinyInt of SQL Server would map to Byte in C#.
See: Mapping CLR Parameter Data
So for your code you need:
answers.Columns.Add("Response", typeof(byte));


text:
Q: Confuse about css float I have a div and an image inside it

img {
    float: left;
}

I can see the div have collapsed, the height have become to 0,
my first question is, but the image is inside the, cuz the div's height is 0,why the image still can be see?
I know the solution like give the div a overflow property, even to auto. But why it can solve the problem?

A: Floating elements doesn't affect the size of the parent element. As the div only contains floating elements, there is nothing that gives it height.
By setting the overflow style on the parent element (to anything but visible), you force it to contain its elements, so that they can be scrolled.
By not setting a specific size on the parent element, it will get the size from its children, and you don't get scrollbars. As the children are now contained, the floating elements will affect the size of the parent.
An alternative to using overflow on the parent element, is to add a non-floating child after the other, and use clear: both; on it so that it's below the floating children. That way the parent will contain the children because of that last non-floating child.

A: By default, a parent element will not wrap around floated content. (It would be annoying in many situations if it did.) So if you want it to do so, you need to force the container to enclose the floated element. overflow: hidden; is one way of doing it, though it's not always a viable solution. There are quite a few other ways of doing it, too, such as the "clearfix" method.
The overflow property works to contain floats because, to obey the rule, the containing element has to 'look and see' what's inside it. Normally, floated content is taken outside the document flow and mostly ignored by other elements.
Here are some other containment options for that div:
The "clearfix" method:
div:after {
    content:"";
    display:table;
    clear:both;
}

Floating the container:
div.contain {
    float: left;
    width: 100%;
}

Using display: table:
div {
    display: table;
    width: 100%;
}

Using display: inline-block:
div {
    display: inline-block;
    width: 100%;
}

Using position: absolute;:
div {
    position: absolute;
    width: 100%;
}

Some of these are more useful than others, and context will determine which is and isn't appropriate in any particular layout. Generally, I stick with overflow: hidden unless some content needs to hang out of the containing element (such as in a drop down menu), in which case I'll normally use the "clearfix" option.


text:
Q: block disappeared at the end of the animation - CSS 3 I want to make a simple effet: slide a div from right to the center of a div (300x300).
I success to do that by using animation:

/* Place your styles here */
*, input, button{
 font-family:"Roboto Slab";
}

.ad{
 width:300px;
 height:250px;
 overflow:hidden; /* elements won't spill outside of the ad */
 position:relative; /* make it easier to position elements */
 background-color:#efefef;
 color:#3A3A3A;
  text-align: center
}

.h1-background{
 color:white;
 background-color:#003967; /* #4285F4;*/
 padding-top:20px;
 padding-bottom:20px;
 padding-left:10px;
 padding-right:10px;
 text-align:center;
  height: 100px;
}

h1#text-1{
 position:relative;
  font-size: 26px;
}

h1#text-2 {
  font-size: 20px;
  position: relative;
  left: 0px;

  -moz-animation-name: dropHeader;
  -moz-animation-iteration-count: 1;
  -moz-animation-timing-function: ease-out;
  -moz-animation-duration: 0.5s;

  -webkit-animation-name: dropHeader;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-timing-function: ease-out;
  -webkit-animation-duration: 0.5s;
  -webkit-transition-delay: 5s;

  animation-name: dropHeader;
  animation-iteration-count: 1;
  animation-timing-function: ease-out;
  animation-duration: 0.5s;
}

@-moz-keyframes dropHeader {
    from {left: 0px;}
    to {left: 200px;}
}
@-webkit-keyframes dropHeader {
   from {left: 300px;}
    to {left: 0;}
}
@keyframes dropHeader {
    from {left: 300px;}
    to {
      left: 0px;
    }

}

.company-logo
{
  width:80%;
  height: auto
}
button{
 padding:5px 20px; /* give the button some padding */
 font-size:20px; /* expand the font size */
 background-color:  #95c11a; /*#4285F4;*/
 border:none; /* Remove the default border */
 color:white;
 margin:auto; /* Centers the button */
 margin-top:7px;
 display:block;
 position:relative; /* Position relatively for animation */
 cursor:pointer;
 border-radius:50px; /* Give the button a rounded look */
 cursor:pointer;

 -moz-animation-name: raiseButton;
  -moz-animation-iteration-count: 1;
  -moz-animation-timing-function: linear;
  -moz-animation-duration: .7s;

  -webkit-animation-name: raiseButton;
  -webkit-animation-iteration-count: 1;
  -webkit-animation-timing-function: linear;
  -webkit-animation-duration: .7s;

  animation-name: raiseButton;
  animation-iteration-count: 1;
  animation-timing-function: linear;
  animation-duration: .7s;

}
@-moz-keyframes raiseButton {
    0% {
      -moz-transform: translateY(100px);
      opacity :0;
    }
    50%{
     -moz-transform: translateY(100px);
     opacity :0;
    }
    100% {
      -moz-transform: translateY(0);
      opacity:1;
    }
}
@-webkit-keyframes raiseButton {
    0% {
        -webkit-transform: translateY(100px);
        opacity :0;
    }
    50%{
     -webkit-transform: translateY(100px);
     opacity :0;
    }
    100% {
        -webkit-transform: translateY(0);
        opacity:1;
    }
}
@keyframes raiseButton {
    0% {
        transform: translateY(100px);
        opacity :0;
    }
    50%{
     transform: translateY(100px);
     opacity :0;
    }
    100% {
        transform: translateY(0);
        opacity :1;
    }
}

test test

    <button id="cta">
    azerty
    </button>

But I want a 2s delay before the animation stats. If I add animation-delay: 2s;, the text of the div is shown during 2s, after the animation starts and the text disappears, the text slides, but at the end, it disappears again.
How can I do not to have it at the before the animation, but that it stays visible after the animation ?
I tried with opacity, visibility in the animation, but nothing works.
Thanks for the answers

A: You don't have consistency here
@-moz-keyframes dropHeader {
  from {left: 0px;}
  to {left: 200px;}
}
@-webkit-keyframes dropHeader {
  from {left: 300px;}
  to {left: 0;}
}

and If you use:
transform: translateY(100px);

why you don't use
    transform: translateX in dropHeader too?
fix that and try again
If you want apply the property values for the time the animation ended use.
animation-fill-mode: forwards;

You can check this codepen if you want
  http://codepen.io/tarod_spj/pen/vKBVaK
I hope that hepl you.


text:
Q: How to detect if your app was "side-loaded" with a different certificate? Is there a way to detect if your app was sideloaded with a different (free) dev certificate on iOS via code?

A: An app can check the certificate it was signed with, the certificate details should be enough for you to determine it was load-loaded. E.g. if you normally sign your apps with a particular certificate and that isn't the one app finds then you have been side-loaded.
The code to do the checking is not long but you do need to understand what you are doing and write the appropriate custom checks for your app. Try starting with Apple's Code Signing Guide.
HTH


text:
Q: About interfaces
Possible Duplicate:
Interfaces: Why cant I seem to grasp them?

What is the purpose of interfaces in C#?
How would they enable extendable,modular design in c#,Java?
As far as my experience with the interfaces is concerned ,we used in a gridview scenario where columns values are brought from disparate objects.
(e.g:
List<IPub> list = new List<IPub>();
gridview.DataSource = list;
gridview.DataBind();

IPub has 4 methods which is implemented by 4 or 5 disparate classes.
)
What are the cases they come in handy compared to their class counterparts,apart from above?
I heard Java creator despised of interfaces or saying like "If i were a given a chance to design java again;I would never make interfaces into the language".
Does this applies to C# as well?
What implications made him to say that ?
I am feeling like i never understood interfaces completely.
Please somebody take pains to explain.
EDIT: Here is the Goslings quote, see the Java section

A: Interfaces can be considered as "can-do", whilst abstract/base classes can be considered as "is-a".
So a dog is-a animal, so you'd used a base class.
A dog can-do a poo, so poo would be a method on an interface which other animals might implement.. (crap example)
Reading my OO book the other day it posited that concrete instances should be avoided and good OO coders always program to an interface or base-class.
With that in mind it might be worth picking up a copy of a good OO / patterns book, such as head first design patterns

A: you should see the answers here or here or here or here
An interface provides a way to use something without having to worry about how that thing is implemented.
If you have an interface ITextGetter  with a method GetText(string textKey) which you are using, you don't know if where the text comes from, all you know is that when you ask for the text with a particular key, you get the text. If you write you app using this interface then you can use different classes which all implement the interface to get the text without having to change your app.  This makes it easy to switch from file based text getting to database based or webservice based text getting without having to change any of the code that uses the interface

A: Interfaces are a sort of contract: if some class implements some interface, then that class guarantees to have certain methods. You could have the same when you inherit from some baseclass, but you can't always do that. In that case an interface is handy to implement a sort of multiple inheritance.

A: Interfaces are there so that you don't need to specify a whole lot of functional code about something. You just need to know what it does. It's kinda like if you need to hire a family car.
You need to know
A) its a car that drives and
B) it has a family sized boot.
You don't need to know about how the car works, how the engine works. You just need to do know it can do A) and B). That's the purpose of an interface.
Within C# we don't allow multiple inheritance, (i.e. having more than 1 base class), so if you want to define the behaviour of more than 1 interface you can't do it with classes. If multiple inheritance existed there would be the option of using multiple base classes to do this.

A: Well, back when java was being developed there was a thing called "Multiple inheritance" where classes could be derived from two (or more) different classes.
So for example, you had a "Vehicle" class and a "Animal" class you could have a "Horse" class that derived from both.
The problem was, what if you wanted to derive a class from two classes that had a function name in common?  You couldn't really, there would be two underlying implementations of the function.
So for example the Vehicle and Animal classes might have a "move()" function. Well, if you don't override that yourself, then what happens when you call horse.move()? It's undefined! Either one could get called!
So, in Java, you can only derive from one class.  But what if you really need a class that is compatible with more then one type?  Like if you have, for example a database connection that needs to derive a base class to work with the DB but also needs to be able to be managed like a resource with a close() function.
Okay, so they created 'Interfaces'.  When you implement an interface, you don't have to worry about competing code underneath because you have to implement them yourself.

It's generally agreed that multiple inheritance is a "considered harmful" (like GOTO), and interfaces are a way of getting the benefits without the downsides. But, nowadays there are other ways to do that. Such as "DuckTyping" where as long as classes implement the feature name, they are good to go.
Also, java now can do nested classes, so if you need your class to be derived from two classes, you can make an inner class that derives from the second class.
Different methods have their pluses and minuses, but interfaces are not the only want to get around the problems of multiple inheritance today.

A: Interfaces give you a way to effectively have some sort of multiple inheritance (you can't inherit from more than one abstract base class). If you ask yourself the question why would you prohibit multiple class inheritance, just read relevant chapter from one of Bjarne Stroustroup's books (on C++), where you will how overcomplicated it gets.
On the other note, when you are using unit testing, pretty much every interface you create will have at least 2 implementations - the real one and a mocked one for the tests.


text:
Q: How can I implement a simple web server using Python without using any libraries? I need to implement a very simple web-server-like app in Python which would perform basic HTTP requests and responses and display very basic output on the web page. I am not too concerned about actually coding it in Python, but I am not sure where to start? How to set this up? One file? Multiple files? I guess I have no idea how to approach the fact that this is a "server" - so I am unfamiliar with how to approach dealing with HTTP requests/sockets/processing requests, etc. Any advice? Resources?

A: You can use socket programming for this purpose. The following snippet creates a tcp socket and listens on port 9000 for http requests:
from socket import *

def createServer():
    serversocket = socket(AF_INET, SOCK_STREAM)
    serversocket.bind(('localhost',9000))
    serversocket.listen(5)
    while(1):
        (clientsocket, address) = serversocket.accept()
        clientsocket.send("HTTP/1.1 200 OK\n"
         +"Content-Type: text/html\n"
         +"\n" # Important!
         +"Hello World\n")
        clientsocket.shutdown(SHUT_WR)
        clientsocket.close()

    serversocket.close()

createServer()

Start the server, $ python server.py.
Open http://localhost:9000/ in your web-browser (which acts as client). Then in the browser window, you can see the text "Hello World" (http response).
EDIT**
The previous code was only tested on chrome, and as you guys suggested about other browsers, the code was modified as:

*

*To make the response http-alike you can send in plain header with http version 1.1, status code 200 OK and content-type text/html.

*The client socket needs to be closed once response is submitted as it's a TCP socket.

*To properly close the client socket, shutdown() needs to be called socket.shutdown vs socket.close
Then the code was tested on chrome, firefox (http://localhost:9000/) and simple curl in terminal (curl http://localhost:9000).

A: I decided to make this work in Python 3 and make it work for Chrome to use as an example for an online course I am developing.  Python 3 of course needs encode() and decode() in the right places.  Chrome - really wants to send its GET request before it gets data. I also added some error checking so it cleans up its socket if you abort the server or it blows up:
def createServer():
    serversocket = socket(AF_INET, SOCK_STREAM)
    try :
        serversocket.bind(('localhost',9000))
        serversocket.listen(5)
        while(1):
            (clientsocket, address) = serversocket.accept()

            rd = clientsocket.recv(5000).decode()
            pieces = rd.split("\n")
            if ( len(pieces) > 0 ) : print(pieces[0])

            data = "HTTP/1.1 200 OK\r\n"
            data += "Content-Type: text/html; charset=utf-8\r\n"
            data += "\r\n"
            data += "Hello World\r\n\r\n"
            clientsocket.sendall(data.encode())
            clientsocket.shutdown(SHUT_WR)

    except KeyboardInterrupt :
        print("\nShutting down...\n");
    except Exception as exc :
        print("Error:\n");
        print(exc)

    serversocket.close()

print('Access http://localhost:9000')
createServer()

The server also prints out the incoming HTTP request.  The code of course only sends text/html regardless of the request - even if the browser is asking for the favicon:
$ python3 server.py
Access http://localhost:9000
GET / HTTP/1.1
GET /favicon.ico HTTP/1.1
^C
Shutting down...

But it is a pretty good example that mostly shows why you want to use a framework like Flask or DJango instead of writing your own. Thanks for the initial code.

A: You should look at the SimpleHttpServer (py3: http.server) module.
Depending on what you're trying to do, you can either just use it, or check out the module's source (py2, py3) for ideas.
If you want to get more low-level, SimpleHttpServer extends BaseHttpServer (source) to make it just work.
If you want to get even more low-level, take a look at SocketServer (source: py2, py3).
People will often run python like python -m SimpleHttpServer (or python3 -m http.server) if they just want to share a directory: it's a fully functional and... simple server.

A: There is a very simple solution mentioned above, but the solution above doesn't work. This solution is tested on chrome and it works. This is python 3 although it may work on python 2 since I never tested it.
from socket import *

def createServer():
    serversocket = socket(AF_INET, SOCK_STREAM)
    serversocket.bind(('localhost',9000))
    serversocket.listen(5)
    while(1):
        (clientsocket, address) = serversocket.accept()
        clientsocket.send(bytes("HTTP/1.1 200 OK\n"
         +"Content-Type: text/html\n"
         +"\n" # Important!
         +"Hello World\n",'utf-8'))
        clientsocket.shutdown(SHUT_WR)
        clientsocket.close()

    serversocket.close()

createServer()

This is improved from the answer that was accepted, but I will post this so future users can use it easily.


text:
Q: Decode String in an unknown format I have a string returned in this format:
\n\bbcn_test\u0012\u00041.14\u001a\u0004escc\"\u0004vscc*(\u0012\f\u0012\n\b\u0001\u0012\u0002\b\u0000\u0012\u0002\b\u0001\u001a\u000b\u0012\t\n\u0007Org1MSP\u001a\u000b\u0012\t\n\u0007Org2MSP2D\n \ufffd\ufffda\ufffd\ufffd\ufffd3RU4\ufffd\ufffdR\ufffd\ufffd\ufffd\ufffd@\ufffd\ufffds\b\ufffd\u0014\ufffd\ufffd.\ufffd!\ufffd\u0012 s\ufffd\ufffdc\ufffd6\ufffd\ufffd@\ufffd\u001eF\ufffdƳ\ufffdi\ufffd$\ufffd\ufffd4\ufffdgP\ufffd:\ufffdt\u000e: 6ђ\ufffd\ufffd3\u007fJ\ufffdHt\u0004\ufffd\ufffd\ufffd\ufffd^{\\\ufffd\u001d\ufffd\ufffd\ufffd\ufffd\ufffd3\ufffdb?@\ufffdB,\u0012\f\u0012\n\b\u0001\u0012\u0002\b\u0000\u0012\u0002\b\u0001\u001a\r\u0012\u000b\n\u0007Org1MSP\u0010\u0001\u001a\r\u0012\u000b\n\u0007Org2MSP\u0010\u0001

\n\u0004mycc\u0012\u00031.0\u001a\u0004escc\"\u0004vscc*,\u0012\f\u0012\n\b\u0002\u0012\u0002\b\u0000\u0012\u0002\b\u0001\u001a\r\u0012\u000b\n\u0007Org1MSP\u0010\u0003\u001a\r\u0012\u000b\n\u0007Org2MSP\u0010\u00032D\n \ufffd\u0011}\ufffdT\ufffdV \u0010l\ufffdNT\ufffd\ufffdz\ufffd\ufffd\ufffdv+\ufffd˹5;\ufffd@q\ufffd\ufffd\u000e\u0012 \u0007\u001f\u0014)\u001e\u0015+\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdt\ufffd\u0013ak\ufffd\u0015J\ufffd\ufffd\ufffd\ufffdZ\u0017_c&: y\ufffd\ufffdw\ufffdnN\ufffd<\ufffd3^v\ufffdbIB`M\ufffd\ufffd\ufffd)&\u0007x\ufffd;(u\ufffdLB,\u0012\f\u0012\n\b\u0001\u0012\u0002\b\u0000\u0012\u0002\b\u0001\u001a\r\u0012\u000b\n\u0007Org1MSP\u0010\u0001\u001a\r\u0012\u000b\n\u0007Org2MSP\u0010\u0001

I am trying to decode it in order to obtain a valid string but I don't understand which format it's written in and what is a good decoder for it.
How can I determine what the format is and how to decode it?

A: What you have is binary data that has been stringified into a human readable format.
So, you need to first parse the string converting its characters into bytes.
Substrings that are encoded in an escape sequence format (preceded by the '\' character followed by 1-4 characters) are decoded to specific bytes like this:

*

*\b -> 0x08

*\t -> 0x09

*\n -> 0x0A

*\f -> 0x0C

*\r -> 0x0D

*\" -> 0x22

*\' -> 0x27

*\\ -> 0x5C

*\u00## + \uff## -> 0x## (the ff is due to sign-extension for bytes >= 0x80)

Any un-escaped characters in the string are to be converted as-is (ie, simply cast from 16-bit Char to 8-bit Byte ignoring the high 8 bits).
Let's look at the first string you provided:

\n\bbcn_test\u0012\u00041.14\u001a\u0004escc\"\u0004vscc*(\u0012\f\u0012\n\b\u0001\u0012\u0002\b\u0000\u0012\u0002\b\u0001\u001a\u000b\u0012\t\n\u0007Org1MSP\u001a\u000b\u0012\t\n\u0007Org2MSP2D\n \ufffd\ufffda\ufffd\ufffd\ufffd3RU4\ufffd\ufffdR\ufffd\ufffd\ufffd\ufffd@\ufffd\ufffds\b\ufffd\u0014\ufffd\ufffd.\ufffd!\ufffd\u0012 s\ufffd\ufffdc\ufffd6\ufffd\ufffd@\ufffd\u001eF\ufffdƳ\ufffdi\ufffd$\ufffd\ufffd4\ufffdgP\ufffd:\ufffdt\u000e: 6ђ\ufffd\ufffd3\u007fJ\ufffdHt\u0004\ufffd\ufffd\ufffd\ufffd^{\\ufffd\u001d\ufffd\ufffd\ufffd\ufffd\ufffd3\ufffdb?@\ufffdB,\u0012\f\u0012\n\b\u0001\u0012\u0002\b\u0000\u0012\u0002\b\u0001\u001a\r\u0012\u000b\n\u0007Org1MSP\u0010\u0001\u001a\r\u0012\u000b\n\u0007Org2MSP\u0010\u0001

Break up the individual sequences for decoding:
\n \b b c n _ t e s t \u0012 \u0004 1 . 1 4 \u001a \u0004 e s c c \" \u0004 v s c c * ( \u0012 \f \u0012 \n \b \u0001 \u0012 \u0002 \b \u0000 \u0012 \u0002 \b \u0001 \u001a \u000b \u0012 \t \n \u0007 O r g 1 M S P \u001a \u000b \u0012 \t \n \u0007 O r g 2 M S P 2 D \n  \ufffd \ufffd a \ufffd \ufffd \ufffd 3 R U 4 \ufffd \ufffd R \ufffd \ufffd \ufffd \ufffd @ \ufffd \ufffd s \b \ufffd \u0014 \ufffd \ufffd . \ufffd ! \ufffd \u0012  s \ufffd \ufffd c \ufffd 6 \ufffd \ufffd @ \ufffd \u001e F \ufffd Ƴ \ufffd i \ufffd $ \ufffd \ufffd 4 \ufffd g P \ufffd : \ufffd t \u000e :  6 ђ1 \ufffd \ufffd 3 \u007f J \ufffd H t \u0004 \ufffd \ufffd \ufffd \ufffd ^ { \\ \ufffd \u001d \ufffd \ufffd \ufffd \ufffd \ufffd 3 \ufffd b ? @ \ufffd B , \u0012 \f \u0012 \n \b \u0001 \u0012 \u0002 \b \u0000 \u0012 \u0002 \b \u0001 \u001a \r \u0012 \u000b \n \u0007 O r g 1 M S P \u0010 \u0001 \u001a \r \u0012 \u000b \n \u0007 O r g 2 M S P \u0010 \u0001
And convert them to bytes:
0x0A 0x08 0x62 0x63 0x6E 0x5F 0x74 0x65 0x73 0x74 0x12 0x04 0x31 0x2E 0x31 0x34 0x1A 0x04 0x65 0x73 0x63 0x63 0x22 0x04 0x76 0x73 0x63 0x63 0x2A 0x28 0x12 0x0C 0x12 0x0A 0x08 0x01 0x12 0x02 0x08 0x00 0x12 0x02 0x08 0x01 0x1A 0x0B 0x12 0x09 0x0A 0x07 0x4F 0x72 0x67 0x31 0x4D 0x53 0x50 0x1A 0x0B 0x12 0x09 0x0A 0x07 0x4F 0x72 0x67 0x32 0x4D 0x53 0x50 0x32 0x44 0x0A 0x20 0xFD 0xFD 0x61 0xFD 0xFD 0xFD 0x33 0x52 0x55 0x34 0xFD 0xFD 0x52 0xFD 0xFD 0xFD 0xFD 0x40 0xFD 0xFD 0x73 0x08 0xFD 0x14 0xFD 0xFD 0x2E 0xFD 0x21 0xFD 0x12 0x20 0x73 0xFD 0xFD 0x63 0xFD 0x36 0xFD 0xFD 0x40 0xFD 0x1E 0x46 0xFD 0x59 0xFD 0x69 0xFD 0x24 0xFD 0xFD 0x34 0xFD 0x67 0x50 0xFD 0x3A 0xFD 0x74 0x0E 0x3A 0x20 0x36 ђ1 0xFD 0xFD 0x33 0x7F 0x4A 0xFD 0x48 0x74 0x04 0xFD 0xFD 0xFD 0xFD 0x5E 0x7B 0x5C 0xFD 0x1D 0xFD 0xFD 0xFD 0xFD 0xFD 0x33 0xFD 0x62 0x3F 0x40 0xFD 0x42 0x2C 0x12 0x0C 0x12 0x0A 0x08 0x01 0x12 0x02 0x08 0x00 0x12 0x02 0x08 0x01 0x1A 0x0D 0x12 0x0b 0x0A 0x07 0x4F 0x72 0x67 0x31 0x4D 0x53 0x50 0x10 0x01 0x1A 0x0D 0x12 0x0B 0x0A 0x07 0x4F 0x72 0x67 0x32 0x4D 0x53 0x50 0x10 0x01
Once you have decoded the bytes, you can interpret binary data as needed.  It appears to be in a kind of Type-Length-Value format, like @RobNapier suggested in a comment to your question:

BTW, this looks exactly like a TLV (Type-Length-Value) format. The first byte is a type 0x0a, followed by a length 0x08, followed by eight bytes of data ("bcn_test"), followed by a type (0x12), followed by a length (0x04), followed by 4 bytes of data ("1.14"), etc.

0x0A (Type 10), 0x08 (Len 8)
0x62 0x63 0x6E 0x5F 0x74 0x65 0x73 0x74 (bcn_test)
0x12 (Type 18) 0x04 (Len 4)
0x31 0x2E 0x31 0x34 (1.14)
0x1A (Type 26) 0x04 (Len 4)
0x65 0x73 0x63 0x63 (escc)
0x22 (Type 34) 0x04 (Len 4)
0x76 0x73 0x63 0x63 (vscc)
and so on ...
1: however, I'm not sure how to correctly decode the ђ in the original string.  It is Unicode codepoint U+0452 CYRILLIC SMALL LETTER DJE, which in a Java Char is bytes 0x04 0x52.  Truncated to 0x04 or 0x52, or interpreted in a Cyrillic charset like Windows-1251 where it would be byte 0x90, it doesn't match up with the rest of the TLV format.


text:
Q: unique_ptr as class member and move semantics fail to compile with clang I can't get clang (Apple LLVM version 4.2 (clang-425.0.28)) to compile these classes:
struct A {
    int f(){return 2;}
};
class Cl{
     std::unique_ptr<A> ptr;

public:
     Cl(){ptr = std::unique_ptr<A>(new A);}

     Cl(const Cl& x) : ptr(new A(*x.ptr)) { }
     Cl(Cl&& x) : ptr(std::move(x.ptr)) { }
     Cl(std::unique_ptr<A> p) : ptr(std::move(p))  { }

    void m_ptr(std::unique_ptr<A> p){
        ptr = std::unique_ptr<A>(std::move(p));
    }
    double run(){return ptr->f();}
};

I would like to run the constructor as follows:
std::unique_ptr<A> ptrB (new A);
Cl C = Cl(ptrB);

but if I do this I get the following compiler error:
    ../src/C++11-2.cpp:66:10: error: call to implicitly-deleted copy constructor of 'std::unique_ptr'
        C.m_ptr(ptrB);
I can solve the compiler problem by running Cl(std::move(ptrB)) but this doesn't actually move the ownership of A away from ptrB: I can still run ptrB->f() without causing a run-time crash... Secondly, the constructor is not very satisfying, since I want to hide the implementation of std::move in the class interface.
Thanks in advance.

A: Since ptrB is passed by value to Cl's copy constructor, a call to Cl(ptrB) tries to create a copy of ptrB which in turn calls a (obviously disabled) copy constructor of unique_ptr.  In order to avoid creating an extra copy of ptrB, do the following:
Cl C = Cl(std::unique_ptr<A>(new A)); //A temporary is created on initialization, no extra copy steps performed

Or:
std::unique_ptr<A> ptrB (new A);
Cl C = Cl(std::move(ptrB)); //Move semantics used. Again, no extra copy steps

Or, use pass by reference (rvalue or lvalue) in your copy constructor:
class Cl{

//...
public:
//...
     Cl(std::unique_ptr<A> &p) : ptr(std::move(p))  { }

//...

};

std::unique_ptr<A> ptrB (new A);
Cl C = Cl(ptrB);

P.S Oh and by the way: the objects stay in unspecified, but valid state after std::move(). I believe that means you can still call ptrB->f(), and it is guaranteed
to return 2 :)


text:
Q: Subset vector based on table of logical values R I am trying to subset a vector based on a number of inputs. file.list will be a vector of filenames that I want to subset, and species will be the species names I want to search for within the files.
file.list <- c("blah_cod", "blah_had", "blah_ggu", "blah_cod")
species <- c("cod", "had")
a<-sapply(species, grepl, file.list, ignore.case=TRUE)

       cod   had
[1,]  TRUE FALSE
[2,] FALSE  TRUE
[3,] FALSE FALSE
[4,]  TRUE FALSE

file.list[a[,1]]
file.list[a[,2]]

With the code I have currently I am able to get what I need, but I need to be able to automate it such that the number of columns will depend on the number of species input by the user. I tried looping like this:
for (i in (1:ncol(a))){b<-file.list[a[,i]]}

I have also tried a number of combinations along these lines, but either get only part of the information I need or errors. Any ideas?

A: grep can be used to actually return the matches instead of logical values:
lapply(species, grep, file.list, ignore.case=TRUE, value=TRUE)
#[[1]]
#[1] "blah_cod" "blah_cod"
#
#[[2]]
#[1] "blah_had"


text:
Q: How is virtual base classes stored? So I understand that if you have the diamond inheritance problem and you do virtual inheritance it creates only one of the base class however how exactly is this represented?
In the vtable is there a pointer to the base class and when one of the derived classes is constructed it looks to see if that pointer exists already and if not it creates it and makes it point to the base class?

A: You start out right. Although implementation details can vary, in effect yes there's information in the vtable (or anyway in class metadata) sufficient to find the base class.
To your second part, AFAIK there's no "see if the pointer exists already" in any implementation. C++ makes the most-derived class responsible for constructing all virtual bases. So with a normal diamond inheritance involving Root, Middle1, Middle2 and MostDerived, the code emitted to construct instances of MostDerived will:

*

*construct Root and set a vptr to point to a vtable for MostDerived

*construct Middle1 and Middle2

*construct data members of MostDerived

*execute the body of the constructor of MostDerived
I say "a vptr" rather than "the vptr", because during the construction of Middle1 the Root base class is available but any virtual functions of Middle1 don't yet refer to overrides defined in MostDerived. It's up to the implementation to sort this out, you can experiment for yourself by looking at object sizes how many hidden pointers are used to do it and whether the number depends on whether Middle1 has virtual functions.
Note that the usual code emitted to construct instances of Middle1 will:

*

*construct Root and set a vptr to point to a vtable for Middle1

*construct data members of Middle1

*execute the body of the constructor of Middle1.

When we're constructing the Middle1 base class subobject of MostDerived, we only want to do two of those steps, not all three. For this reason, you will probably find that the emitted code for a class with more than one constructor contains multiple constructors -- one for objects whose most-derived type is the class, and a separate one for base class subobjects whose type is the class.


text:
Q: iOS: Retaining connectivity with band I have 2 apps on the app store with Tiles on the MS Band- (Band Time Tracker and Band List).  Both of these suffer from the same issue: over time the connection to the band is lost, events generated in the Band do not trigger code execution on the app.
What types of mitigating strategies can I use to ensure that events always trigger code execution on the phone?
Right now the only thing I have included is haptic feedback to notify the user that the event was accepted.


text:
Q: I cannot access Thunderbird ppa I tried the suggestion given to this question:
Thunderbird won't send email
but apt gave the following error:
Cannot access PPA (https://launchpad.net/api/1.0/~mozillateam/+archive/thunderbird-stable) to get PPA information, please check your internet connection.
Of course, because I can post this, my internet connection is fine. Any suggestions?
Ubuntu 12.04 LTS.
Thanks.

A: That PPA seems to no longer exist, see here.
That other answer you linked to basically suggested installing the newest stable version of Thunderbird, which may have been more up-to-date than the latest stable version in the official repos at that time. But apparently, now the thunderbird package is updated often enough in the official repos.
Along the lines of the idea suggested in that other thread, if you have a similar problem and want try upgrading Thunderbird to solve it, you may try the Thunderbird Beta PPA:
sudo add-apt-repository ppa:mozillateam/thunderbird-next
sudo apt-get update
sudo apt-get install thunderbird

Be aware that this will install a beta version of thunderbird, with a higher potential for bugs.


text:
Q: centos 8 - sssd configuration not fetching shadow contents for ldap user I have configured sssd on centos 8 and ldap on centos 7. I am able to get details about a testuser using getent passwd and getent group , but while testing it for getent shadow I am not getting any details for the testuser. This is causing login failures for testuser. I am not sure what is configured wrong.

# cat /etc/sssd/sssd.conf
[sssd]
debug_level=7
config_file_version = 2
reconnection_retries = 3
enable_files_domain = False
services = nss, pam, ssh
domains = ldap.corp.com

[nss]
debug_level=7
reconnection_retries = 3
pwfield = x
homedir_substring = /home

[pam]
debug_level=7
reconnection_retries = 3

[ssh]
debug_level=7
debug_timestamps = True

[domain/ldap.corp.com]
debug_level=7
debug_timestamps = True
description = LDAP Client Login

enumeration = true
id_provider = ldap
auth_provider = ldap
access_provider = ldap
chpass_provider = ldap

ldap_access_order = filter
ldap_access_filter = (&(objectclass=posixAccount))
ldap_id_use_start_tls = True
ldap_tls_cacertdir = /etc/openldap/cacerts
ldap_tls_reqcert = allow
ldap_uri = ldap://ldap01.corp.com
ldap_search_base = dc=corp,dc=com
ldap_default_bind_dn = cn=ldapadm,dc=corp,dc=com
ldap_default_authtok_type = password
ldap_default_authtok = xxxxxxxxx
cache_credentials = true

ldap_group_search_base = ou=Group,dc=corp,dc=com
ldap_user_search_base = ou=Users,dc=corp,dc=com
#ldap_sudo_search_base = ou=sudoers,dc=corp,dc=com
ldap_user_object_class = posixAccount
ldap_group_object_class = posixGroup
ldap_group_member = memberUid
ldap_pwd_policy = shadow

# cat /etc/authselect/password-auth
auth        required                                     pam_env.so
auth        required                                     pam_faildelay.so delay=2000000
auth        [default=1 ignore=ignore success=ok]         pam_succeed_if.so uid >= 1000 quiet
auth        [default=1 ignore=ignore success=ok]         pam_localuser.so
auth        sufficient                                   pam_unix.so nullok try_first_pass
auth        requisite                                    pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient                                   pam_sss.so forward_pass
auth        required                                     pam_deny.so

account     required                                     pam_unix.so
account     sufficient                                   pam_localuser.so
account     sufficient                                   pam_succeed_if.so uid

# getent passwd testuser1
testuser1:x:1005:1005:testuser1:/home/testuser1:/bin/bash
# getent group testuser1
testuser1:x:1005:
# getent shadow testuser1
#

# ssh testuser1@rhel01
testuser1@rhel01's password:
Connection closed by 192.168.10.11 port 22
#

# tail /var/log/secure
Jul 23 13:23:14 rhel01 sshd[2074]: pam_sss(sshd:auth): authentication success; logname= uid=0 euid=0 tty=ssh ruser= rhost=192.168.10.11 user=testuser1
Jul 23 13:23:14 rhel01 sshd[2074]: Failed password for testuser1 from 192.168.10.11 port 49462 ssh2
Jul 23 13:23:14 rhel01 sshd[2074]: fatal: Access denied for user testuser1 by PAM account configuration [preauth]

# cat /etc/authselect/password-auth
auth        required                                     pam_env.so
auth        required                                     pam_faildelay.so delay=2000000
auth        [default=1 ignore=ignore success=ok]         pam_succeed_if.so uid >= 1000 quiet
auth        [default=1 ignore=ignore success=ok]         pam_localuser.so
auth        sufficient                                   pam_unix.so nullok try_first_pass
auth        requisite                                    pam_succeed_if.so uid >= 1000 quiet_success
auth        sufficient                                   pam_sss.so forward_pass
auth        required                                     pam_deny.so

account     required                                     pam_unix.so
account     sufficient                                   pam_localuser.so
account     sufficient                                   pam_succeed_if.so uid

password    requisite                                    pam_pwquality.so try_first_pass local_users_only
password    sufficient                                   pam_unix.so sha512 shadow nullok try_first_pass use_authtok
password    sufficient                                   pam_sss.so use_authtok
password    required                                     pam_deny.so

session     optional                                     pam_keyinit.so revoke
session     required                                     pam_limits.so
-session    optional                                     pam_systemd.so
session     [success=1 default=ignore]                   pam_succeed_if.so service in crond quiet use_uid
session     required                                     pam_unix.so
session     optional                                     pam_sss.so

Below is the Debug log from /var/log/secure:

Jul 23 15:08:24 rhel01 sshd[3024]: pam_sss(sshd:auth): authentication success; logname= uid=0 euid=0 tty=ssh ruser= rhost=192.168.10.11 user=testuser1
Jul 23 15:08:24 rhel01 sshd[3024]: debug1: PAM: password authentication accepted for testuser1
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_answer_authpassword: sending result 1
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_request_send entering: type 13
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_request_receive_expect entering: type 102
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_request_receive entering
Jul 23 15:08:24 rhel01 sshd[3024]: debug1: do_pam_account: called
Jul 23 15:08:24 rhel01 sshd[3024]: debug2: do_pam_account: auth information in SSH_AUTH_INFO_0
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: PAM: do_pam_account pam_acct_mgmt = 9 (Authentication service cannot retrieve authentication info)
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_request_send entering: type 103
Jul 23 15:08:24 rhel01 sshd[3024]: Failed password for testuser1 from 192.168.10.11 port 49554 ssh2
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_auth_password: user authenticated [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: user_specific_delay: user specific delay 0.000ms [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: ensure_minimum_time_since: elapsed 107.666ms, delaying 14.497ms (requested 7.635ms) [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_do_pam_account entering [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_request_send entering: type 102 [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_request_receive_expect entering: type 103 [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_request_receive entering [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_do_pam_account returning 0 [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: fatal: Access denied for user testuser1 by PAM account configuration [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: debug1: do_cleanup [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: PAM: sshpam_thread_cleanup entering [preauth]
Jul 23 15:08:24 rhel01 sshd[3024]: debug3: mm_request_send entering: type 124 [preauth]

A: You don't need the shadow map when using sssd with LDAP backend. And for security reasons you definitely should not try to implement it.
That's because password checks going through PAM are done by sssd with sending an LDAP simple bind request to the LDAP server. Thus no need to expose password hashes in a shadow map.


text:
Q: Plotting facetgrid plots in seaborn with smoothing I have a pandas dataframe a snippet of which is shown below:-

I wish to recreate the graphs shown below in Seaborn. These graphs were created in R using ggplot, but I am working with pandas/matplotlib/seaborn.

Essentially the graphs summarize the variables(mi,steps,st...) grouped by sensor id, with hours to the event on the x-axis. Additionally and most importantly, there is smoothing performed by stat_smooth() within ggplot. I have included a snippet of my ggplot code.
 step.plot <- ggplot(data=cdays, aes(x=dfc, y=steps, col=legid)) +
  ggtitle('time to event' +
  labs(x="Days from event", y='Number of steps') +
  stat_smooth(method='loess', span=0.2, formula=y~x) +
  geom_vline(mapping=aes(xintercept=0), color='blue') +
  theme(legend.position="none")

A: here is how I would do it. Bear in mind that I had to make assumptions about the structure of your data, so please review what I did before applying it.
Creating some simulated data
subject = np.repeat(np.repeat([1, 2, 3, 4, 5], 4), 31)
time = np.tile(np.repeat(np.arange(-15, 16, 1), 4), 5)
sensor = np.tile([1, 2, 3, 4], 31*5)
measure1 = subject*20 + time*(5-sensor) - time**2*(sensor-2)*0.1 + (time >= 0)*np.random.normal(100*(sensor-2), 10, 620) + np.random.normal(0, 10, 620)
measure2 = subject*10 + time*(2-sensor) - time**2*(sensor-4)*0.1 + (time >= 0)*np.random.normal(50*(sensor-1), 10, 620) + np.random.normal(0, 8, 620)
measure3 = time**2*(sensor-1)*0.1 + (time >= 0)*np.random.normal(50*(sensor-3), 10, 620) + np.random.normal(0, 8, 620)
measure4 = time**2*(sensor-1)*0.1  + np.random.normal(0, 8, 620)

Putting it in a long form dataset for plotting
df = pd.DataFrame(dict(subject=subject, time=time, sensor=sensor, measure1=measure1,
                      measure2=measure2, measure3=measure3, measure4=measure4))

df = pd.melt(df, id_vars=["sensor", "subject", "time"],
             value_vars=["measure1", "measure2","measure3", "measure4"],
             var_name="measure")

Creating the plot, without smoothing
g = sns.FacetGrid(data=df, col="measure", col_wrap=2)
g.map_dataframe(sns.tsplot, time="time", value="value", condition="sensor", unit="subject", color="deep")
g.add_legend(title="Sensor Number")
g.set_xlabels("Days from Event")
g.set_titles("{col_name}")
plt.show()

Plotted data, before smoothing
Now let's use statsmodels to smooth the data.
Please review this part, this is where I made assumptions about the sampling unit (I assume that the sampling unit is the subject, and therefore treat sensors and measure types as conditions).
from statsmodels.nonparametric.smoothers_lowess import lowess
dfs = []
for sens in df.sensor.unique():
    for meas in df.measure.unique():
        # One independent smoothing per Sensor/Measure condition.
        df_filt = df.loc[(df.sensor == sens) & (df.measure == meas)]
        # Frac is equivalent to span in R
        filtered = lowess(df_filt.value, df_filt.time, frac=0.2)
        df_filt["filteredvalue"] = filtered[:,1]
        dfs.append(df_filt)
df = pd.concat(dfs)

Plotted data, after smoothing
From there you can tweak your plot however you like. Tell me if you have any question.


text:
Q: Extended information for nodes in Jenkins I want to add more information to node/computer/agent entries in Jenkins (listed under <JenkinsUrl>/computer).
minimum for me would be:

*

*URL to a wiki page (clickable)

and optimal would be in addition:

*

*more configurable columns / fields with different types possible

*

*URL

*HTML

*Text

*above fields should be displayed in node/computer overview

Is this configurable in jenkins or are there plugins for that?
Motivation:
We have multiple teams sharing the same Jenkins instance and want to describe some maintenance details accessible from the jenkins node overview (e.g.: who is responsible for maintenance? Where is it hosted? How to get access?).


text:
Q: Why does GetVolumeInformation return an int for a serial number? How can I positively identify the physical drive AND the partition in a computer?  I've tried using VOLUME serial number from GetVolumeInformation and was shocked to see it returns a NUMBER and NOT an alpha numeric value?
[DllImport("Kernel32.dll", SetLastError = true)]
extern static bool GetVolumeInformation(string vol, StringBuilder name, int nameSize, out uint serialNum, out uint maxNameLen, out uint flags, StringBuilder fileSysName, int fileSysNameSize);

I need to know that a USB thumb drive or CD or DVD or hard drive is the same physical device when it is attached to a different computer.  I also need to know that the partition or volume is the same even after a user renames it or changes the drive letter.

A: What else should it return? Its just a 32 bit number that the file system assigned when it is formatted.
If you want to have it formatted like what dir returns, just use
serialNumber.ToString("X8");

A: You're confusing two different things.  The documentation says:

lpVolumeSerialNumber [out, optional]
This function returns the volume serial number that the operating system assigns when a hard disk is formatted.

So, this is the OS assigned serial number. It assigned it, I'm sure it knows the correct format to return it in.
It goes on to say:

To programmatically obtain the hard disk's serial number that the manufacturer assigns, use the Windows Management Instrumentation (WMI) Win32_PhysicalMedia property SerialNumber.


text:
Q: Why precision is reduced when I print the QgsGeometry points? I was trying to extract latitudes and longitudes from QgsGeomtery. But I noticed that no all digits we being printed.
Can anybody identify why and how can I resolve this problem?
For example is this was the actual point 231233.22123413317891095, then output is 231233.2212341331.
This is the code used.
for part in geom.parts():
    for vertices in part.vertices():
        print(vertices.x(), vertices.y())


text:
Q: Enable alternative FTP port on Windows Server 2008 R2 I have Windows Server 2008 R2 installed and using XLight FTP Server. I need to use 2221 port as FTP. I've created rules in FireWall, also run commands:
netsh advfirewall firewall add rule name="FTP (non-SSL)" action=allow protocol=TCP dir=in localport=2221

netsh advfirewall set global StatefulFtp enable

FTP clients connect, but hangs on getting list of files and directories.
How to resolve that problem. Thank you!

A: By default active FTP uses port 21 for control messages and 20 for data transfer and passive uses 21 for control and > 1023 for data transfer. The easiest way to resolve this in Windows is to use a program or service based rule instead of a port-based one.


text:
Q: Python - Garbage collection very slow, can't disable gc I am developing a program that uses pandas dataframes and large dictionaries. The dataframe is read from a CSV that is approx. 700MB.
I am using Python 3.7.3 on Windows
I noticed that the program I am running is extremely slow, and slows down after each loop of the algorithm.
The program reads every line of the dataframe, checks some conditions on every item of every line of the df, and if those conditions are met, it stores the item and his state in a dictionary. This dictionary can get pretty big.
I have tried profiling my code with CProfile and I have found that the garbage-collector is the function that uses up about 90% of the execution time.
I have seen similar problems resolved by calling gc.disable() but this did nothing for me.
Weirdly (I have no idea if this is normal) but if I print(len(gc.get_objects())) as the first line of the code I get 51053 which seems a lot considering no function has been called yet.
My CProfile attempt : (on a small chunk of the CSV, as it would take hours to complete the attempt on the full CSV)
cProfile.run('get_pfs_errors("Logs/L5/L5_2000.csv")', 'restats.txt')

import pstats
from pstats import SortKey
p = pstats.Stats('restats.txt')
p.sort_stats(SortKey.CUMULATIVE).print_stats(10)
p.sort_stats(SortKey.TIME).print_stats(10)

Here are the stats from CProfile :
Tue Jun 18 15:40:19 2019    restats.txt

         1719320 function calls (1459451 primitive calls) in 7.569 seconds

   Ordered by: cumulative time
   List reduced from 819 to 10 due to restriction <10>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    7.569    7.569 {built-in method builtins.exec}
        1    0.001    0.001    7.569    7.569 <string>:1(<module>)
        1    0.000    0.000    7.568    7.568 C:/Users/BC744818/Documents/OPTISS_L1_5/test_profile.py:6(get_pfs_errors)
        1    0.006    0.006    7.503    7.503 C:\Users\BC744818\Documents\OPTISS_L1_5\utils\compute_pfs_rules.py:416(compute_pfs_rules)
        1    0.197    0.197    7.498    7.498 C:\Users\BC744818\Documents\OPTISS_L1_5\utils\compute_pfs_rules.py:323(test_logs)
      264    0.001    0.000    6.532    0.025 C:\Users\BC744818\Documents\OPTISS_L1_5\venv\lib\site-packages\pandas\core\series.py:982(__setitem__)
      529    0.010    0.000    6.158    0.012 C:\Users\BC744818\Documents\OPTISS_L1_5\venv\lib\site-packages\pandas\core\generic.py:3205(_check_setitem_copy)
      528    6.125    0.012    6.125    0.012 {built-in method gc.collect}
      264    0.004    0.000    3.430    0.013 C:\Users\BC744818\Documents\OPTISS_L1_5\venv\lib\site-packages\pandas\core\series.py:985(setitem)
      264    0.004    0.000    3.413    0.013 C:\Users\BC744818\Documents\OPTISS_L1_5\venv\lib\site-packages\pandas\core\indexing.py:183(__setitem__)

Tue Jun 18 15:40:19 2019    restats.txt

         1719320 function calls (1459451 primitive calls) in 7.569 seconds

   Ordered by: internal time
   List reduced from 819 to 10 due to restriction <10>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      528    6.125    0.012    6.125    0.012 {built-in method gc.collect}
      264    0.405    0.002    0.405    0.002 {built-in method gc.get_objects}
        1    0.197    0.197    7.498    7.498 C:\Users\BC744818\Documents\OPTISS_L1_5\utils\compute_pfs_rules.py:323(test_logs)
 71280/33    0.048    0.000    0.091    0.003 C:\Users\BC744818\AppData\Local\Programs\Python\Python37\lib\copy.py:132(deepcopy)
   159671    0.033    0.000    0.056    0.000 {built-in method builtins.isinstance}
      289    0.026    0.000    0.026    0.000 {built-in method nt.stat}
167191/83791    0.024    0.000    0.040    0.000 C:\Users\BC744818\AppData\Local\Programs\Python\Python37\lib\json\encoder.py:333(_iterencode_dict)
  8118/33    0.019    0.000    0.090    0.003 C:\Users\BC744818\AppData\Local\Programs\Python\Python37\lib\copy.py:236(_deepcopy_dict)
167263/83794    0.017    0.000    0.048    0.000 C:\Users\BC744818\AppData\Local\Programs\Python\Python37\lib\json\encoder.py:277(_iterencode_list)
 1067/800    0.017    0.000    0.111    0.000 C:\Users\BC744818\Documents\OPTISS_L1_5\venv\lib\site-packages\pandas\core\indexes\base.py:253(__new__)

A: Thank you @user9993950, I solved it thanks to you.
When I tested this program, I had a SettingWithCopyWarning but I wanted to fix the speed of the program before fixing this warning.
Yet it so happens that by fixing the warning I also greatly increased the speed of the program and gc is no longer taking up all of the running time
I don't know what caused this though, if someone knows and wants to share the knowledge please do.


text:
Q: TypeORM Synchronize issue with UUID (MySQL) I am running into issues with synchronize setting on TypeORM with UUID PrimaryGeneratedColumns on MySQL driver. It seems each time application loads it tries to re-index, so it drops the id column and tries to add it again. Issue is that since it's UUID, for MySQL the column type is varchar(36) NOT NULL PRIMARY KEY. So we run into duplicate entry '' for key 'PRIMARY' because UUID is not set.
To recreate issue, you can do it like this:
typeorm init --name MyProject --database mysql

Edit your User.ts entity to change primary key to UUID.
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class User {

    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    age: number;

}

Ensure synchronize is set to true in ormconfig.json.
Start the app and it will insert sample User. Restart app and synchronize will run and try and drop and re-add the column and give error.
  message: 'ER_DUP_ENTRY: Duplicate entry \'\' for key \'PRIMARY\'',
  code: 'ER_DUP_ENTRY',
  errno: 1062,
  sqlMessage: 'Duplicate entry \'\' for key \'PRIMARY\'',
  sqlState: '23000',
  index: 0,
  sql:
   'ALTER TABLE `user` ADD `id` varchar(36) NOT NULL PRIMARY KEY',
  name: 'QueryFailedError',
  query:
   'ALTER TABLE `user` ADD `id` varchar(36) NOT NULL PRIMARY KEY',
  parameters: []


text:
Q: R Package Plumber: Binary POST Body does not work correct I tested to attach an STL file as body on a POST request. Configuration: Windows 10, Postman (POST->binary), R 3.4.2. The R code for the POST request looks like:
#' @post /endpointname
function(req) {
    rawstl = req$postBody  # STL file is attached as Binary in Postman.
    rawData1 = as.raw(unlist(lapply(rawstl, charToRaw)))
    ## E.g. 43 4f 4c 4f 52 3d ...
    ...
}

The output of this is the same as a direct binary read on the STL file using:
 con = file(fileName, "rb")
 rawData2 = readBin(con, "raw", n=100, size=1, endian="little")

however there are some parts missing if the Plumber version (above) is used. I think the reason could be the way line endings are handled or introduced, or Plumber's default filters.
The missing values occur between the elements of req$postBody: e.g. while rawData2 holds [a, b, c, d, e, f, g], rawData1 holds [a, b, e, f]. The R object rawstl in the function above has length > 1 and the missing values occur between the sub-lists there.
I played around for some time but I cannot figure out what is broken.


text:
Q: Get description item from XML with PHP and ignore br tags I have this XML file:
http://www.dailymotion.com/rss/tag/house

I need obtain first title and description items content. Than I use this code:
$xml = simplexml_load_file('http://www.dailymotion.com/rss/tag/house/', 'SimpleXMLElement', LIBXML_NOCDATA);

$dom = new DOMDocument();
echo $xml->channel->item->title . "
";
@$dom->loadHtml($xml->channel->item->description);

$xpath = new DOMXPath($dom);
echo $description = $xpath->evaluate("string(//p[1]/text())");

This is OUTPUT
Fabio Lenzi - Beautiful Sorrow (Ivan Scratchin Funky Mix)
Download:

But if I read xml, in description item I find this content within p tag:

Download:
https://itunes.apple.com/it/album/beautiful-sorrow/id661901853

©
Copyright protected work. ℗ Frutilla Records - All rights reserved. Only for watching,
listening and streaming. Downloading, copying, sharing and making available is strictly
prohibited.

frutillarecords@gmail.com
alex.voghi@dancetool.net
info@dancetool.net -
YourDancefloorTV – (Re)Discover your Dance greatest hits - YourDancefloorTV is your
channel for all the best Dance music. Find your favorite tracks and artists and
experience the best of Dance music. Subscribe for free to stay connected to our channel
and easily access our video updates! - YourDancefloorTV:
http://www.dailymotion.com/yourdancefloortv

Than I noticed that parsing is interrupted from
 tags. How can I ignore br tags and others any tags included in paragraph?
Any helps its really appreciated.

A: Use strip_tags to remove html tags !
Example:
$stripped_string = strip_tags($unstripped_string, $allowable_tags);

A: This may be ,
$x = // Your Result;

echo strip_tags($x,'
');


text:
Q: database isn't connecting without internet connection I am facing this problem while using Xampp mysql database with SailsJS.my application is running locally and connection code is as follows:
someMysqlServer: {
adapter: 'sails-mysql',
host: "localhost",
user:"root",
port     : '3306',
database: 'school'
}

when i start Xamp control panel without internet connection it's working well even request to http://localhost is also connecting to phpmyadmin,but my sails console says
error: A hook (`orm`) failed to load!
error: Error (E_UNKNOWN) :: Encountered an unexpected error
: Could not connect to MySQL:
Error: getaddrinfo ENOENT
at afterwards (D:\SchoolProject\node_modules\sails-    mysql\lib\connections\spawn.js:72:13)
at D:\SchoolProject\node_modules\sails-mysql\lib\connections\spawn.js:40:7
at Handshake.onConnect (D:\SchoolProject\node_modules\sails-mysql\node_modules\mysql\lib\Pool.js:54:9)
at Handshake.Sequence.end (D:\SchoolProject\node_modules\sails-mysql\node_modules\mysql\lib\protocol\sequences\Sequence.js:96:24)
at Protocol.handleNetworkError (D:\SchoolProject\node_modules\sails-mysql\node_modules\mysql\lib\protocol\Protocol.js:355:14)
at PoolConnection.Connection._handleNetworkError     (D:\SchoolProject\node_modules\sails-mysql\node_modules\mysql\lib\Connection.js:367:18)
at Socket.emit (events.js:107:17)
at net.js:950:16
at process._tickDomainCallback (node.js:381:11)

while same application works with internet connection.I Cant figure this out any idea please?????

A: Replace host: "localhost" by host: "127.0.0.1"
I think it will work.


text:
Q: Display calculate total from the separate column I work with CRM. Now I create some report from SSRS.
I need create some table like this:

I can not create last column of the table. This column must contains sum of all rows previous column from groupping. How to do it? I work with crm online. Reports to CRM online can not use SQL - only fetch. And even I would can calculate value of this column from query I can not place it in last column - only second column because we are using grouping.


text:
Q: Finding all subsets $B \subseteq U$ such that $A \cap B \neq \emptyset$ $A$ is a specific set with $k$ elements, $A \subseteq U$, $U$ has $n$ elements. I would like to count all ways to choose subset $B \subseteq U$ where $A \cap B \neq \emptyset$.
I know that $B$ must have either one of $A$'s elements (and then it has another $2^{n-1}$ subsets of $U$, or two (and then we have $2^{n-2}$ of the rest), etc. until $k$. But I just don't see how to count all these possibilities for $B$s.

A: Edit: The question was entirely changed while I was typing the answer below. We answer the new question in the "Added" part at the end.
Old answer: The expression $3^n-2^n$ that you give counts the number of ordered pairs $(A,B)$ such that $A\cap B\ne \emptyset$.  An adjustment of the type you are familiar with from the previous question takes care of unordered pairs.
We first count the ordered pairs with no restriction on $A\cap B$.  For any such ordered pair, let $f:U\to \{0,1,2\}$ be defined by $f(x)=0$ if $x\in A\setminus B$, $f(x)=1$ if $x\in \setminus A$, and $f(x)=2$ if $x\in A\cap B$.
The number of functions is the number of ordered pairs $(A,B)$ of subsets of $U$. So there are $3^n$ ordered pairs.  The ordered pairs $(A,B)$ with $A\cap B\ne \emptyset$ correspond to the functions $f$ that never take the value $2$. There are $2^n$ functions from $U$ to $\{0,1\}$.
So by simple Inclusion/Exclusion, our count is $3^n-2^n$.
Added: Suppose now that $A$ is a fixed $k$-element set, and we want to count the sets $B$ such that $A\cap B\ne \emptyset$. Such a $B$ is uniquely determined by the ordered pair $(A\cap B, U\setminus A)$.
We can chose $A\cap B$ in $2^k-1$ ways, since $A$ has $2^k-1$ non-empty subsets. For each such choice the part $B\setminus A$ can be any subset of $U\setminus A$. There are $2^{n-k}$ of these, for a total of $(2^k-1)(2^{n-k})$.
More simply, $U$ has $2^n$ subsets. The only "bad" $B$ are the subsets of $U\setminus A$, and there are $2^{n-k}$ of these, for a total of $2^n-2^{n-k}$.


text:
Q: What is the difference between using a "<=" sign instead of a "<" sign in the compare function of an STL in C++? I have to implement the 3rd parameter, cmp, in the sort() function for sorting an array of integers in descending order.
The problem is that this definition doesn't work properly,
bool cmp (int a, int b)
{
    if(a<b)
        return false;
    else
        return true;
}

However, this does
bool cmp (int a, int b)
{
    if(a<=b)
        return false;
    else
        return true;
}

In the main() function, I use
sort(Arr,Arr+n,cmp);

Please note that I claim that the first code doesn't work properly because my solution to a problem on Codechef is accepted when I use the 2nd, but not with the 1st.

A: An STL compare function must return false if both values are equal.

A: In sort,
Last argument:

comp  -   comparison function object (i.e. an object that satisfies the requirements of Compare)
  ....

Compare

comp(a, b)
Establishes strict weak ordering relation with the following properties:
For all a, comp(a,a)==false
....

That's why
if(a<=b)
    return false;

works, while
if(a<b)
    return false;

doesn't.

A: std::sort's compare function returns a value that indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.
Here is the definition of strict weak ordering from sgi

A Strict Weak Ordering is a binary predicate that compares two
objects, returning true if the first precedes the second. This
predicate must satisfy the standard mathematical definition of a
strict weak ordering. The precise requirements are stated below, but what
they roughly mean is that a Strict Weak Ordering has to behave the way
that "less than" behaves:

*

*if a is less than b then b is not less than a,

*if a is less than b and b is less than c then a is less than c,
and so on.

A: According to documentation of Compare functions:

Establishes strict weak ordering relation

So, the function comp must define a strict weak ordering. By definition, it must satisfy three conditions:
1) comp(x, x) is false for all x (irreflexivity condition)
2) If comp(x, y) then !comp(x, y) (asymmetry condition)
3) If comp(x, y) and comp(y, z) then comp(x, z) (transitivity condition)
It is easy to see that first example of cmp function does not satisfy the irreflexivity condition, therefore it cannot be used to be passed as comp argument of std::sort. It is also clear that second cmp example in case of x, y are numbers satisfies all of three conditions, so it can be passed as comp argument to std::sort.

A: The compare function provided to std::sort must return true if its first argument lies before its second argument in the ordering required and false otherwise.
Hence, for descending ordering you should use the > operator>, which for ints returns the complement of what the <= operator returns (which you used to implement your comparison with). Better use std::greater<int> to avoid such pitfalls.