text:
Q: Add data to JSON for dates which are not there I use fullcalendar.io and I need to put prices on all dates beetween. Some prices I get from database but some fixed which are not in database I need to create at frontend so with javascript (I think that will be faster and I dont fill database with stupid fixed data, becouse just dates will be different)
First I have start and end date:
var period_start = new Date('2016-02-04 15:18:46');
var period_end = new Date('2016-11-04 15:18:46');

Also I get from database this JSON:
[
  {
    "id": 5,
    "user_id": 1,
    "article_id": 5,
    "price": 78,
    "comment": "",
    "created_at": "2016-02-04 18:33:41",
    "updated_at": "2016-02-04 18:33:41",
    "key": "xLetirBT8wfrTNoQgqkeBUu8ebmZld",
    "title": "",
    "start": "2016-03-25 15:18:46"
  },
  {
    "id": 4,
    "user_id": 1,
    "article_id": 5,
    "price": 55,
    "comment": "",
    "created_at": "2016-02-04 18:33:33",
    "updated_at": "2016-02-04 18:33:33",
    "key": "xLetirBT8wfrTNoQgqkeBUu8ebmZld",
    "title": "",
    "start": "2016-03-15 15:18:46"
  },
  {
    "id": 3,
    "user_id": 1,
    "article_id": 5,
    "price": 35,
    "comment": "",
    "created_at": "2016-02-04 18:33:25",
    "updated_at": "2016-02-04 18:33:25",
    "key": "xLetirBT8wfrTNoQgqkeBUu8ebmZld",
    "title": "",
    "start": "2016-03-07 15:18:46"
  },
  {
    "id": 2,
    "user_id": 1,
    "article_id": 5,
    "price": 22,
    "comment": "dd",
    "created_at": "2016-03-04 15:20:36",
    "updated_at": "2016-02-04 15:20:36",
    "key": "xLetirBT8wfrTNoQgqkeBUu8ebmZld",
    "title": "drugi",
    "start": "2016-03-05 15:18:46"
  },
  {
    "id": 1,
    "user_id": 1,
    "article_id": 5,
    "price": 44,
    "comment": "gg",
    "created_at": "2016-05-04 15:18:46",
    "updated_at": "2016-02-04 15:18:46",
    "key": "xLetirBT8wfrTNoQgqkeBUu8ebmZld",
    "title": "prvi",
    "start": "2016-02-04 15:18:46"
  }
]

Now I want to fill this JSON with dates which are not in JSON file so all dates between period_start and period_end who missing...
so etc. I have in JSON - start: 2016-02-05 but missing other dates...
How to put empty dates into JSON and just change the date - start ?
Also if you have some better solution please tell me, I think that the best is to fill empty dates at frontend with javascript-jquery...

A: You should be able to add a day to the start date until you get to the end date to populate an array, then replace the dates for the data you have. You could also check if you have a date in the db data as you populate, but this was quick and dirty and I wanted to show map and filter...
// declare variables
var period_start = new Date('2016-02-04 15:18:46'),
    period_end = new Date('2016-11-04 15:18:46'),
    current_date = period_start,
    array_of_all_dates = [];

// Create a populated array of dates
while (current_day.getTime() <= period_end.getTime()) {
    array_of_all_dates.push(current_date);
    current_date = new Date(+current_date);
    current_date.setDate(current_date.getDate() + 1);
}

// Now loop over the array of populated dates and mutate, so something like
array_of_all_dates = array_of_all_dates.map(function (date) {
    var found_in_db = db_data.filter(function (db_data) {
        return new Date(db_data.start).getTime() === date.getTime(); // You need to do this comparison better!
    });
    if (found_in_db.length > 0) {
        return found_in_db[0];
    }
    var new_object = {
        a_property: 'some_default_value',
        start: date
    };
    return new_object;

});

I'm sure this could be done better, but technique is ok if you ignore the time parts and significantly improve the date comparison.
You should probably look into array operations if you don't recognise filter and map.
I've added some extra into the snippet for the purposes of looking at the objects.

var addToList = function (text) {
  var node = document.createElement("LI");
  var textnode = document.createTextNode(text);
  node.appendChild(textnode);
  document.getElementById("myList").appendChild(node);
};

//var db_data = [{"start": "2016-05-04T15:18:46", "title": "FOUND"}, {"start": "2016-06-04T15:18:46", "title": "FOUND ME TOO"}];
var db_data = [
  {
    "id": 5,
    "user_id": 1,
    "article_id": 5,
    "price": 78,
    "comment": "",
    "created_at": "2016-02-04 18:33:41",
    "updated_at": "2016-02-04 18:33:41",
    "key": "xLetirBT8wfrTNoQgqkeBUu8ebmZld",
    "title": "",
    "start": "2016-03-25 15:18:46"
  },
  {
    "id": 4,
    "user_id": 1,
    "article_id": 5,
    "price": 55,
    "comment": "",
    "created_at": "2016-02-04 18:33:33",
    "updated_at": "2016-02-04 18:33:33",
    "key": "xLetirBT8wfrTNoQgqkeBUu8ebmZld",
    "title": "",
    "start": "2016-03-15 15:18:46"
  },
  {
    "id": 3,
    "user_id": 1,
    "article_id": 5,
    "price": 35,
    "comment": "",
    "created_at": "2016-02-04 18:33:25",
    "updated_at": "2016-02-04 18:33:25",
    "key": "xLetirBT8wfrTNoQgqkeBUu8ebmZld",
    "title": "",
    "start": "2016-03-07 15:18:46"
  },
  {
    "id": 2,
    "user_id": 1,
    "article_id": 5,
    "price": 22,
    "comment": "dd",
    "created_at": "2016-03-04 15:20:36",
    "updated_at": "2016-02-04 15:20:36",
    "key": "xLetirBT8wfrTNoQgqkeBUu8ebmZld",
    "title": "drugi",
    "start": "2016-03-05 15:18:46"
  },
  {
    "id": 1,
    "user_id": 1,
    "article_id": 5,
    "price": 44,
    "comment": "gg",
    "created_at": "2016-05-04 15:18:46",
    "updated_at": "2016-02-04 15:18:46",
    "key": "xLetirBT8wfrTNoQgqkeBUu8ebmZld",
    "title": "prvi",
    "start": "2016-02-04 15:18:46"
  }
];

// declare variables
var period_start = new Date('2016-02-04T15:18:46'),
    period_end = new Date('2016-11-04T15:18:46'),
    current_date = period_start,
    array_of_all_dates = [];

// Create a populated array of dates
while (current_date.getTime() <= period_end.getTime()) {
  array_of_all_dates.push(current_date);
  current_date = new Date(+current_date);
  current_date.setDate(current_date.getDate() + 1);
}

// Now loop over the array of populated dates and mutate, so something like
array_of_all_dates = array_of_all_dates.map(function (date) {
  var found_in_db = db_data.filter(function (db_data) {
    return new Date(db_data.start.replace(" ", "T")).getTime() === date.getTime(); // You need to do this comparison better!
  });
  if (found_in_db.length > 0) {
    return found_in_db[0];
  }
  var new_object = {
    a_property: 'some_default_value',
    start: date
  };
  console.log(new_object);
  return new_object;

});

// Display something
array_of_all_dates.forEach(function (date_object) {
  addToList(JSON.stringify(date_object));
});
<ul id="myList">
</ul>


text:
Q: Invalid JSON but validates on JSONLint I have the following JSON which validates on JSONLint.com but when I pass it to JSON.parse() I get the error
SyntaxError: JSON.parse: unexpected character
...0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,...

This is apparently the last "correct": line
        var theJSON = JSON.parse({
    "data": [
        {
            "wrong": "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
            "correct": "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
        },
        {
            "wrong": "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
            "correct": "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
        },
        {
            "wrong": "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
            "correct": "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
        },
        {
            "wrong": "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
            "correct": "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
        }
    ]
});

A: You, like many, have confused JavaScript's literal syntax with JSON. This happens a lot as JSON uses a subset of JavaScript's literal syntax so it looks a lot alike. JSON, however, is always a string. It is a serialized data scheme for porting data structures between langs/platforms.
Also confusing is that a string of JSON which has been output by any platform can be copied and pasted right into JavaScript and used. Again, this is because of the shared syntax. Having pasted such output right into JavaScript, however, one is no longer using JSON--they are now writing JavaScript in literal syntax. That is, unless, you pasted it between quotes and properly escaped the resulting string. But there's no sense in doing so as then it needs to be parsed in order to end up with what you already had.
JSON.parse() is a method for unserializing data which had been serialized into JSON. It expects a string because, well, JSON is a string. You're passing an object (in literal syntax). It does not need parsing...it is already the thing you want.
Wrapping your object literal in single quotes would make the code work, but it would be pointless to do so as the parse would simply result in what you already have.
Your code would be better written if you replaced the variable named theJSON with one named theObject and made it look as such:
var theObject = {
    data: [
        {
            wrong: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
            correct: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
        },
        {
            wrong: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
            correct: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
        },
        {
            wrong: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
            correct: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
        },
        {
            wrong: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0",
            correct: "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"
        }
    ]
};

Whatever code wanted to use the parse result should be fine once you've done it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Writing a Script to Delete JMS Queus in Websphere suppose I have the following JMS queues "doc/queue1","home/queue2" and "someOtherQueue" added in a websphere process server, how can I write a script to delete them? looking around the web i haven't found a solution to my problem yet unfortunately, thanks in advance for the help guys

A: Take a look at the deleteWMQQueue command (for WMQ queues) and the deleteSIBJMSQueue command (for other types of queues).


text:
Q: couchbase merge array to sub-document I have to merge an arry to couchbase key-value array ,I have read the document, that is only this:
from couchbase.cluster import Cluster,PasswordAuthenticator
import couchbase.subdocument as SD
#other thing
bucket.upsert("all_goods",[])
bucket.mutate_in("all_goods",SD.array_append("",["a","b","c"])
bucket.mutate_in("all_goods",SD.array_append("",["1","2","3"])

I hope get that
all_goods => [a,b,c,1,2,3]

but ,I got this:
all_goods => [[a,b,c],[1,2,3]]

I hope to merge the array in to the document

A: As per documentation this is the expected behaviour:
bucket.mutate_in('my_array', SD.array_append('', ['elem1', 'elem2', 'elem3'])
# the document my_array is now ["some_element", ["elem1", "elem2", "elem3"]]

As a workaround I will suggest to create an array and extend it and later do the array_append:
from couchbase.cluster import Cluster,PasswordAuthenticator
import couchbase.subdocument as SD
#other thing
bucket.upsert("all_goods",[])
my_array = ["a","b","c"]
my_array.extend(["1","2","3"])
bucket.mutate_in("all_goods",SD.array_append("",my_array)

Or you can append the elements individually:
from couchbase.cluster import Cluster,PasswordAuthenticator
import couchbase.subdocument as SD
#other thing
bucket.upsert("all_goods",[])
bucket.mutate_in("all_goods",SD.array_append("","a","b","c")
bucket.mutate_in("all_goods",SD.array_append("","1","2","3")


text:
Q: Is there a way to split a line plot into branches, with the branches forking off the main line in ggplot2? I have a data set as follows:
data <- data.frame(
ID = c(rep(1:4, each = 16)),
time = c(rep(1:4, each = 4, times = 4)),
drug1 = c(rep(1:2, each = 2, times = 16)),
drug2 = rep(c(1,2,2,3), times = 16),
value = c(sample(1:100, 64, replace = FALSE)))

In this study ID took drug1 (1 or 2) for time points 1 and 2, then for time 3 and 4, ID may have stayed on the same drug (1 or 2), or had a switch (1-->2, or 2-->3)
I have two issues.

*

*I would like to make a line plot, plotting the means for the drug condition where for time 1 and 2 the grouping in ggplot follows variable "drug" but for time 3 and 4 it follows "drug 2".

An example might be something like (https://ibb.co/6gLP0Hv)

*I also want to ignore any NA that are in the drug2 column if it's week 3 and 4, but keep the data in for week 1 and 2.

I have used filter from an answer below and it was close, but not quite what I visualized what look right.
Thank you for your help.

A: I'm not convinced a line plot is the best way to go as you have multiple measures per drug/time so it will look odd/misleading... perhaps a jitter/scatterplot is better (just change to geom_line if you want - the bit you are after here really is the filter):
ggplot() +
  geom_jitter(data %>% filter(time == 1| time == 2),
    mapping = aes(x = time, y = mean, shape = drug), width = 0.1) +
  geom_jitter(data %>% filter(time == 3| time == 4),
    mapping = aes(x = time, y = mean, shape = drug2), width = 0.1, color = 'red')


text:
Q: given a word forming a meaningful word by adding spaces in between them You are given a string example "Iamastudent" without any spaces. You will be provided with a predefined dictionary function which verifies whether a given word is present in the dictionary or not. Using this function you have to insert the spaces in the string a print it as "I am a student".
its my interview question and told me too solve in c++, i solved it using dynamic programming but he was not satisfied
the solution i gave is
 same as in the below question
Given a phrase without spaces add spaces to make proper sentence
he asked me to do it using trie or suffix array but i couldnt able to figure the solution can any one help me

A: Find words and put spaces after them
The answer is to use Trie data structure. Create Trie with possible words and keep traversing. with Trie you can generate many different possible words.
now here "iamastudent" with Trie you could generate these words.
i, a, am, a, as, student

now you have to make a proper sentence out of these words. Here the possible solution is markov chain. A markov chain is data structure where it holds probability for next word after a word. so markov chain will be.
"i" : [ "am", "did", "went" ...],
"a" : [ "tree", "dog" ..]
"am" : [ "a" ...]

Now you these many data in sequence
[i], [a, am], [a, as], [student]

Note: I grouped all elements which starts with same character in one
  list.

start with "i"
next word is "a". but in markov chain "a" is not there. so go for next word. like this you can continue.
from here onwards it is a dfs search for a valid sentence. well, it was a nice and tricky question.

A: If there is a unique solution of splitting the sentence then doing it with a trie is simple:

*

*if there are characters in the input string start walking down from the root consuming characters from the string. otherwise terminate.

*if it is a compressed trie you will find a mark whenever a prefix is a complete word otherwise if you reach a leaf that's when you output a space

*go back to 1 (walking down from the root) starting from the current position in the string

You are done when there are no more characters in the string (you may want to check that at this point you are not traversing the tree).
If the solution is not unique, then whenever you reach the end of the string and you are not at a mark or a leaf in the tree you need to backtrack to the previous space you emitted. You need a stack for positions in the input string.


text:
Q: Getting exsl:node-set to work in PHP I have the following PHP code, but it's not working. I don't see any errors, but maybe I'm just blind. I'm running this on PHP 5.3.1.
<?php
$xsl_string = <<<HEREDOC
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
                xmlns="http://www.w3.org/1999/xhtml"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:exsl="http://exslt.org/common"
                extension-element-prefixes="exsl">
  <xsl:template match="/">

Hello world

    <xsl:variable name="person">
      <firstname>Foo</firstname>
      <lastname>Bar</lastname>
      <email>test@example.com</email>
    </xsl:variable>
    <xsl:value-of select="exsl:node-set(\$person)/email"/>
  </xsl:template>
</xsl:stylesheet>
HEREDOC;

$xml_dom = new DOMDocument("1.0", "utf-8");
$xml_dom->appendChild($xml_dom->createElement("dummy"));

$xsl_dom = new DOMDocument();
$xsl_dom->loadXML($xsl_string);

$xsl_processor = new XSLTProcessor();
$xsl_processor->importStyleSheet($xsl_dom);
echo $xsl_processor->transformToXML($xml_dom);
?>

This code should output "Hello world" followed by "test@example.com", but the e-mail portion doesn't appear. Any idea what's wrong?
-Geoffrey Lee

A: The problem is that the provided XSLT code has a default namespace.
Therefore, the <firstname> , <lastname> and <email> elements are in the xhtml namespace. But email is referenced without any prefix in:

exsl:node-set($person)/email

XPath considers all unprefixed names to be in "no namespace". It tries to find a child of exsl:node-set($person) called email that is in "no namespace" and this is unsuccessful, because its email child is in the xhtml namespace. Thus no email node is selected and output.
Solution:
This transformation:
<xsl:stylesheet version="1.0"
  xmlns="http://www.w3.org/1999/xhtml"
  xmlns:x="http://www.w3.org/1999/xhtml"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:exsl="http://exslt.org/common"
  exclude-result-prefixes="exsl x">
  <xsl:output omit-xml-declaration="yes" indent="yes"/>

  <xsl:template match="/">

Hello world

     <xsl:variable name="person">
      <firstname>Foo</firstname>
      <lastname>Bar</lastname>
      <email>test@example.com</email>
     </xsl:variable>
     <xsl:text>
</xsl:text>
     <xsl:value-of select="exsl:node-set($person)/x:email"/>
     <xsl:text>
</xsl:text>

  </xsl:template>
</xsl:stylesheet>

when applied on any XML document (not used), produces the wanted result:

Hello world

test@example.com

Do note:

*

*The added namespace definition with prefix x

*The changed select attribute of <xsl:value-of>:
exsl:node-set($person)/x:email


text:
Q: Updating Google line chart I am using Google line chart and I set event to put data in chart. When I use this event for first time it worked fine but, when I use it for second time the new data over write with the previous data but I don't want that. I want to keep the data together not over writing when I think about this problem I realized that I can solve this problem with saving data each time and put them in for loop but I think it's not proper way to do that is there any other way to solve this problem
Here is my JS code :
function drawChart() {
    var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'example1'); // Implicit domain label col.
    data.addColumn('number', 'example2'); // Implicit series 1 data col.
    $("#Sample").click(function () {
        var test1 = $("#sample1").val();
        var test2 = $("#sample2").val();
        var test3 = $("#sample3").val();
        data.addRows([
            [test3, test1],
            [test3, test2]
        ]);
        chart.draw(data, {
            pointSize: 5
        });
    }
}

A: Your main problem is that you didn't separate add.columns part form your event and every time you call event make another columns and your data over write.
Your solution:
function drawChart() {
var chart = new google.visualization.LineChart(document.querySelector('#chart_div'));
var data = new google.visualization.DataTable();
data.addColumn('number', 'example1'); // Implicit domain label col.
data.addColumn('number', 'example2'); // Implicit series 1 data col.
$("#Sample").click(function () {
    var test1 = new Number($("#sample1").val()).valueOf();
    var test2 = new Number($("#sample2").val()).valueOf();
    var test3 = new Number($("#sample3").val()).valueOf();
    data.addRows([
    [test3, test1],
    [test3, test2]
    ]);
    chart.draw(data, {
    pointSize: 5
    });
});
}
google.load('visualization', '1', {packages: ['corechart'], callback: drawChart});


text:
Q: mysql not starting in xampp even after changing mysql port and restarting the server I have changed port number and restarted the service but still I am not able to start MySQL in Xampp.
Content of my.ini file:

and config.inc.php:


text:
Q: Работа NavigationDrawer Activity и Fragments Здравствуйте! В Андроиде новичок. Я хотел бы написать приложение для различных расписаний, в первую очередь для школьников и студентов. Приложение, по моей задумке состоит из NavigationDrawer с такими вкладками: Расписание, Оценки, Экзамены (и зачеты) и Задания. Во вкладке с расписанием должен быть TabLayout с днями недели. Суть вопроса заключается в следующем, по своей реализации NavigationDrawer должен работать с фрагментами (это как я понял задумка гугла), чтобы он (NavigationDrawer) был доступен по всему приложению, с Активностями NavigationDrawer пропадает. Дак вот, Как можно реализовать структуру, описанную выше? Я пробовал создавать фрагмент с табами, при нажатии на день недели появляется фрагмент с днем недели, но данный подход кажется мне некорректным, т.к. при запуске приложения фрагменты работают нормально, но если в NavigationDrawer перейти, например, в Оценки и затем вернуться в Расписание, то после этого фрагменты ничего не отображают и табы не переключаются корректно, т.е. на какое расстояние провел пальцем, на столько таба и сдвинулась, при этом информации на ней ноль. Если вручную нажать на последнюю или предпоследнюю табу, то там появляется информация и затем табы нормально начинают работать.
Что делать в данной ситуации, не знаю. Гугление особо ничего не дало. Практически везде TabLayout реализуют внутри Активности, а не во фрагменте. Да и в таком случае, табы будут во всех фрагментах. Или все же есть какой то способ совместить табы, активность и NavigationDrawer?
и можно как нибудь при вызове фрагмента, убрать табы, если они организованны на уровне активности ?

A: Можно задать контейнер для главной активности
   <FrameLayout
                android:id="@+id/frame_container"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
        </RelativeLayout>

И вызывать фрагменты по необходимости с помощью
 getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new Fragment()).addToBackStack("tag").commit();

также в oncreate указать старт фрагмент


text:
Q: Making CASE statement from previous CASE statement for SQL Query I currently am working with SQL Server 2012 and trying to figure out how to get results from a CASE statement.
So currently I have a CASE statement to calculate an AgeBusiness field that I currently am using to find the Business Age of requests. This is the code I have for it:
CASE    WHEN A.[End_Date] > A.[Start_Date] THEN C2.[BUS_DY_OF_CAL_NUM] - C1.[BUS_DY_OF_CAL_NUM]
        WHEN A.[End_Date] IS NULL and A.[Start_Date] IS NOT NULL THEN C3.[BUS_DY_OF_CAL_NUM] - C1.[BUS_DY_OF_CAL_NUM]
        WHEN A.[End_Date] = A.[Start_Date] THEN 1
END AS AgeBusiness

Basically, if End Date is greater than Start Date, use End Date - Start Date to calculate.
If no End Date, use GETDATE() - Start Date to calculate.
If they're equal, then 1 business day.
Anyways, I have this AgeBusiness field and am trying to either use this field or data from this field to calculate a new Case When statement to calculate requirements.
In a perfect world my CASE statement would go something like this:
CASE WHEN AgeBusiness >= 0 AND AgeBusiness <11 AND Name = "RequirementA" Then 1
     WHEN AgeBusiness >= 0 AND AgeBusiness <8 AND Name = "RequirementB" Then 1
     WHEN AgeBusiness >= 0 AND AgeBusiness <181 AND Name = "RequirementC" Then 1
     WHEN AgeBusiness >= 0 AND AgeBusiness <8 AND Name = "RequirementD" Then 1
     WHEN AgeBusiness >= 0 AND AgeBusiness <11 AND Name = "RequirementE" Then 1
     WHEN AgeBusiness >= 0 AND AgeBusiness <16 AND Name = "RequirementF" Then 1
End AS WithinRequirements

Basically I want to make a new case statement called Within Requirements where if it fell within a certain amount of days and had a particular name, then it would be yes or in this case 1. The name field already exists from a table that I can pull in. Though one of the requirements for making WithinRequirements requires the AgeBusiness to exist, which the fields would be created in query at same time...so that's not possible.
Is there a way to use the info from AgeBusiness that I put above to create WithinRequirements somehow? The goal is to figure this out in a query...even if it means a long winded query.

A: Use CROSS APPLY for intermediate variables
SELECT
CASE WHEN AgeBusiness >= 0 AND AgeBusiness <11 AND Name = "RequirementA" Then 1
     WHEN AgeBusiness >= 0 AND AgeBusiness <8 AND Name = "RequirementB" Then 1
     WHEN AgeBusiness >= 0 AND AgeBusiness <181 AND Name = "RequirementC" Then 1
     WHEN AgeBusiness >= 0 AND AgeBusiness <8 AND Name = "RequirementD" Then 1
     WHEN AgeBusiness >= 0 AND AgeBusiness <11 AND Name = "RequirementE" Then 1
     WHEN AgeBusiness >= 0 AND AgeBusiness <16 AND Name = "RequirementF" Then 1
End AS WithinRequirements
FROM  A
CROSS APPLY (
   SELECT CASE WHEN A.[End_Date] > A.[Start_Date] THEN C2.[BUS_DY_OF_CAL_NUM] - C1.[BUS_DY_OF_CAL_NUM]
           WHEN A.[End_Date] IS NULL and A.[Start_Date] IS NOT NULL THEN C3.[BUS_DY_OF_CAL_NUM] - C1.[BUS_DY_OF_CAL_NUM]
           WHEN A.[End_Date] = A.[Start_Date] THEN 1
        END AS AgeBusiness
) vars

A: If when A.[End_Date] is null will C2.[BUS_DY_OF_CAL_NUM] also be null you can rewrite the first case statement like this:
 ABS(COALESCE(COALESCE(C2.[BUS_DY_OF_CAL_NUM],C3.[BUS_DY_OF_CAL_NUM])-C1.[BUS_DY_OF_CAL_NUM],1))

You also use BETWEEN in a case statement and operate on a single value so rewrite the 2nd one like this:
CASE ABS(COALESCE(COALESCE(C2.[BUS_DY_OF_CAL_NUM],C3.[BUS_DY_OF_CAL_NUM])-C1.[BUS_DY_OF_CAL_NUM],1))
     WHEN AgeBusiness >= 0 AND AgeBusiness <11 AND Name = "RequirementA" Then 1
     WHEN BETWEEN 0 AND 11  AND Name = "RequirementB" Then 1
     WHEN BETWEEN 0 AND 181 AND Name = "RequirementC" Then 1
     WHEN BETWEEN 0 AND 8   AND Name = "RequirementD" Then 1
     WHEN BETWEEN 0 AND 11  AND Name = "RequirementE" Then 1
     WHEN BETWEEN 0 AND 16  AND Name = "RequirementF" Then 1
End AS WithinRequirements

I believe this query is less "long winded" than your original.


text:
Q: Call child iframe method from Parent aspx page I've created one aspx page Default.aspx. It contains iframe with child.aspx. File Child.cs contains web methods which should be called by parent page.
As I understand I need to receive the instance of Child class so then I'll be able to them call. How can I make this?
I will be really appreciated for constructive solution,
Default.aspx (Parent page)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Parent_Child_Iframe._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:Button ID="btGetDataFromChild" runat="server" Text="Get Data from Child" />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>

            </ContentTemplate>
        </asp:UpdatePanel>

    </form>

Child.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Child.aspx.cs" Inherits="Parent_Child_Iframe.Child" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

    </form>

Child.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Parent_Child_Iframe
{
    public partial class Child : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        public string getResultData ()
        {
            return TextBox1.Text + TextBox2.Text;
        }
    }
}

So How I can call getResultData () from Child.aspx.cs by clicking Button on the parent page.
The main difficulty is that I can't use Javascript to collect the information from TextBoxes because the task is more complicated and I can use only server methods.
Thank you in advance,
Best wishes,
Greg.

A: Thats not really the way iframes work. Remember, HTTP is a stateless protocol, which means that each request for a page is an independent request, and won't have any context of the previous request. What I think you would need to do, is either request the Child.aspx page with specific form or request variables, and the Child page should output the correct page accordingly.
Could you explain what it is you want to achieve?


text:
Q: Keystone returning is_admin = 0 in every case Did a search on this and found:
Keystone returning token with metadata is_admin = 0
which doesn't really answer the question, and it's a year old, so I thought I'd open a new one.
I am running a VM instance of Ubuntu 14.04 running the latest build of devstack (as in less than a few weeks old) and am seeing strange behavior from keystone, I think.
I understand the admin role is supposed to be tenant specific, but my observations contradict that.
1) Keystone NEVER returns is_admin=1.  Authenticating to the admin tenant, with the admin user, who has the admin role for the admin tenant STILL returns "is_admin 0". Is there a guarantee that the admin role will always be named "admin"? If so, could you just use .user.roles.name = admin to check?
2) If that's true, I still need to provide a tenant when authenticating in order for that array to be populated in the response.  Why does this matter? Well I would like to authenticate without a tenant, get a list of tenants and roles, and then re-authenticate to a particular tenant to do something useful.  Why?  Because I don't want to have to know my list of tenants and roles ahead of time. I want to write an automated process that allows a login and upon authenticating, displays a list of tenants and additional functionality, IF and only IF the user is an admin.
3) Frustratingly, and this is a continuation of #2.  If the admin role is truly tenant specific, then  logging in using tenant A shouldn't allow me to do admin things on tenant B when I'm not even a member of tenant B, and it most certainly does.  This would lead me to believe the admin role is global, period.  It would make more sense to me, I would think to have tenant specific admins, admins that have access to a set of tenants, and global admins, but either this is not the case and they're lying or I am just completely bafffled by Openstack identity.
Since all internet searches have come up nada, or seem to assume that the reader already knows the context and answer to the question they are trying to address, can someone explain to me:
A) What IS the official prupose/limitations of the admin role?
B) Why on Earth doesn't my first point work?
C) Why does the admin role seem to be global?
D) Where is there documentation on this that doesn't assume you already know the intimate details of keystone?  E.g., The admin role is blah blah blah.  You configure its access here in blah blah blah.  It operates exactly this way: blah blah blah.  Not referencing or assuming any prior exposure to Openstack and all in one place?
E) Am I asking too much?  :)
Thanks.


text:
Q: Get inner most values in the Map as a List in `Map>>>` Java I need to get the values in the inner most map as a list in Map<String, List<Map<String,Map<String,String>>>>.
Other than for each, Can we implement it using streams?

A: Stream#flatMap returns a Stream of all values of all elements:
List<String> converted = yourComplexStructure.values().stream()
    .flatMap(List::stream)
    .map(Map::values)
    .flatMap(Collection::stream())
    .map(Map::values)
    .flatMap(Collection::stream()))
    .collect(Collectors.toList());

It takes the values of your structure as a Stream, maps it to a Stream with all elements of each List, maps it to a Stream with all values of the Maps, creates a Stream with all values of the most inner maps and collects it.

Note that it is basically the same as the other answer (we wrote it at the same time) but I changed this answer so that it doesn't require lambdas but uses method references.

A: Perhaps
    List<String> keys = map.values().stream() // get the first list
            .flatMap(List::stream) //flatten the list
            .flatMap(mapOfMap -> mapOfMap.values().stream()) //get the list of all values
            .flatMap(mapOfMap -> mapOfMap.keySet().stream()) //get the keys
            .collect(Collectors.toList());

As @dan1st pointed out, flatMap is key to success here.
To get the values you simply change the innermost flatMap:
    List<String> values = map.values().stream() // get the first list
            .flatMap(List::stream) //flatten the list
            .flatMap(mapOfMap -> mapOfMap.values().stream()) //get the list of all values
            .flatMap(mapOfMap -> mapOfMap.values().stream()) //get the values
            .collect(Collectors.toList());

To filter for a key:
List<String> values = map.values().stream() // get the first list
                .flatMap(List::stream) //flatten the list
                .flatMap(mapOfMap -> mapOfMap.values().stream()) //get the list of all values
                .flatMap(mapOfMap -> mapOfMap.entrySet().stream()) //get the entries (key -> value)
                .filter(entry -> entry.getKey().equals("somekey")) //filter here
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());


text:
Q: winhttp WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR I am using Casablanka Rest SDK with Visual C++ 2015. The Casablanka SDK is based on winhttp. Whenever a request is sent over SSL, an exception is received.  The exception is:
"SSL error: WINHTTP_CALLBACK_STATUS_FLAG_SECURITY_CHANNEL_ERROR internal error."
The problem is only with Windows 2008 R2 server. My laptop running Windows 10 and Windows 2012 server are OK.
There are no problems browsing the SSL enabled websites from the Windows 2008. However, my application just don't work and fails with the above errors.
Any help is appreciated :)
Just adding the winhttp trace:
"23:24:31.228 ::usr-req 003B2A60 received OnTcpConnected callback
23:24:31.244 ::   an async I/O operation completes (overlapped = 00397790, #bytes/info = 0, error = SEC_E_INVALID_TOKEN (-2146893048))
23:24:31.244 ::sys-sender processing HttpSendHttpRequest completion (error-cdoe = SEC_E_INVALID_TOKEN (0x80090308), #bytes = 0, overlapped = 00397790)
23:24:31.244 ::sys-sender failed to a request; error = SEC_E_INVALID_TOKEN (-2146893048)
23:24:31.244 ::ERROR_WINHTTP_FROM_WIN32 mapped (SEC_E_INVALID_TOKEN) -2146893048 to (ERROR_WINHTTP_SECURE_FAILURE) 12175"

A: Windows 2008 couldn't negotiate TLS 1.2. So, I downgraded the protocols in Rest SDK (cpprestsdk\Release\src\http\client\http_client_winhttp.cpp).
changes:
DWORD secure_protocols = WINHTTP_FLAG_SECURE_PROTOCOL_SSL3 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1;
    if (IsWindowsVersionOrGreater(6, 3, 0)) {
        secure_protocols += WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2;
    }
    win32_result = ::WinHttpSetOption(m_hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, &secure_protocols, sizeof(secure_protocols));

I hope this helps some facing the same issue.


text:
Q: Trying to make simple timer to shutdown windows in python Trying to make simple timer to shutdown windows in python (just for fun) but i'm having a small problem that can't find the answer, the script just ask if the user wants to use minutes or seconds to shut down using an if, the part of using seconds works fine, the problem is with minutes, the script get the time in minutes and convert to seconds, than runs: subprocess.call(["shutdown" "-s", "-t", ntime])
But it's not working, if i double click on the file.py and try this part, the script just close, but if a execute in the IDLE i recieve an this error:
Traceback (most recent call last):
  File "C:\Users\User\Desktop\shutdown.py", line 17, in <module>
    subprocess.call(["shutdown" "-s", "-t", ntime])
  File "F:\Programs\python\lib\subprocess.py", line 267, in call
    with Popen(*popenargs, **kwargs) as p:
  File "F:\Programs\python\lib\subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "F:\Programs\python\lib\subprocess.py", line 997, in  _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
>>>

Code:
import subprocess
print('0:Seconds')
print('1:Minutes')
minorsec = input('Want to use minutes or seconds? ')
if minorsec == '0':
    time = input('Type the time to shutdown in seconds: ')
    subprocess.call(["shutdown", "-s", "-t", time])
elif minorsec == '1':
    time = input('Type the time to shutdown in minutes: ')
    ntime = int(time) * 60
    subprocess.call(["c:\\windows\\system32\\shutdown.exe" "-s", "-t", str(ntime)])
else:
    print('Error, Press just 0 or 1')
input('Press Enter to close: ')

A: Issue #1:   This line
ntime = time * 60

Doesn't do what you think it does. time, the value returned from the previous input call is a string, not an integer. So if the user types "15" as his input, ntime becomes something insane like: "1515151515151515151515.....15". That's probably your core problem:
Convert the user's input from string back to integer:
 ntime = int(time) * 60

Issue #2, which is a side effect of fixing #1: All the values in the argument list to subprocess.call must be strings:
time = input('Type the time to shutdown in minutes: ')
ntime = int(time) * 60
subprocess.call(["shutdown" "-s", "-t", str(ntime)])

Issue #3: Don't use an argument list:
subprocess.call("shutdown.exe -s -t " + str(ntime))


text:
Q: Java Object->String[] to String[] I have an Object variable that contains a String[] array, and I am trying to do the following
String[] arr = ((String[])packet.getObject());

I however recieve the dreaded ClassCastException. What information do you guys need? My packet class looks as the following:
public class Packet implements Serializable {
private static final long serialVersionUID = 1L;
private int type;
private Object object;

public Packet(int type, Object object) {
    this.type = type;
    this.object = object;
}

public int getType() {
    return type;
}

public void setType(int type) {
    this.type = type;
}

public Object getObject() {
    return object;
}

public void setObject(Object object) {
    this.object = object;
}
}

Any ideas? I'm trying to convert the Object into a String[].

A: If you get a ClassCastException, it means that the packet does NOT hold a String[].
Execute the following code to see what it actually holds, then debug to see why and where the object is stored in the packet:
System.out.println(packet.getObject());
System.out.println(packet.getObject().getClass());

A debugger would give you this information without needing to modify the code.


text:
Q: svn local obstruction, incoming add upon merge I have read quite a few SO threads on this and also the following blogg but still don't understand my particular issue so I hope someone can help...
Doing a merge from mainline into dev line to catch up again and I get the following tree conflict.
M      incubator
     C incubator/UtilityScripts
     >   local dir obstruction, incoming dir add upon merge

Okay, so I understand that this should be that this directory was independently added to both the trunk and dev branch independently such that there is no common ancestor...
..Buuuut (there's always a but right?!) there IS a common ancestor. This directory entered my dev branch because of a previous merge from truck.
dev$ svn mergeinfo {^/trunk/src/,}incubator/UtilityScripts/
     youngest common ancestor
     |         last full merge
     |         |        tip of branch
     |         |        |         repository path

     23788              23838
     |                  |
   -------| |------------         trunk/src/incubator/UtilityScripts
      \
       \
       --| |------------          branches/dev/src/incubator/UtilityScripts

                        |
                        23838

So, as I understand this SVN does believe that the dev branch is ancestrally related to trunk with a common ancestor at revision 23788.
branch$ svn log --stop-on-copy incubator/UtilityScripts/
------------------------------------------------------------------------
r23790 | me | 2015-05-12 16:08:25 +0100 (Tue, 12 May 2015) | 1 line

So I got this file in revision 23790 and I am now at revision 23838
Trunk$ svn log --stop-on-copy incubator/UtilityScripts/
------------------------------------------------------------------------
r23639 | someone | 2015-03-06 10:59:10 +0000 (Fri, 06 Mar 2015) | 1 line

So, common ancestor is 23788. The only revision at which this entered my dev branch as 23790 which is after this anyway.The most recent trunk change is 23639 which is before any of these.
So given this, how on earth can there be an incoming add conflict?!


text:
Q: JOIN two tables and GROUP by the common column I'm new to MYSQL and struggling to form a query that joins two tables and returns a unique product row.
TABLE product:
╔══════════════════════════════╦══════════╦════════════╦════════════════════╗
║             ref              ║  brand   ║    mpn     ║        sku         ║
╠══════════════════════════════╬══════════╬════════════╬════════════════════╣
║ 0001___DOGICLON___912-101242 ║ DOGICLON ║ 912-101242 ║ 000000000001082649 ║
║ 0002___DOGICLON___912-101242 ║ DOGICLON ║ 912-101242 ║ 912-101242         ║
║ 0003___Dogiclon___912-101242 ║ Dogiclon ║ 912-101242 ║ 912-101242(R400)   ║
║ 0005___Dogiclon___912-101242 ║ Dogiclon ║ 912-101242 ║ MILT-R400          ║
╚══════════════════════════════╩══════════╩════════════╩════════════════════╝

TABLE inventory:
╔══════════════════════════════╦═══════╦═════════╦══════════╗
║             ref              ║ scost ║ instock ║ location ║
╠══════════════════════════════╬═══════╬═════════╬══════════╣
║ 0001___DOGICLON___912-101242 ║ 53.68 ║      24 ║ WA       ║
║ 0001___DOGICLON___912-101242 ║ 53.68 ║       0 ║ CA       ║
║ 0002___DOGICLON___912-101242 ║ 61.00 ║     121 ║ WA       ║
║ 0003___Dogiclon___912-101242 ║ 53.53 ║     100 ║ WA       ║
║ 0003___Dogiclon___912-101242 ║ 53.53 ║       0 ║ NY       ║
║ 0003___Dogiclon___912-101242 ║ 53.53 ║      20 ║ MA       ║
║ 0003___Dogiclon___912-101242 ║ 53.53 ║       2 ║ CA       ║
║ 0005___Dogiclon___912-101242 ║ 56.00 ║       5 ║ IN       ║
║ 0005___Dogiclon___912-101242 ║ 56.00 ║       5 ║ MA       ║
║ 0005___Dogiclon___912-101242 ║ 56.00 ║       5 ║ WA       ║
║ 0005___Dogiclon___912-101242 ║ 56.00 ║       5 ║ NY       ║
║ 0005___Dogiclon___912-101242 ║ 56.00 ║       2 ║ CA       ║
╚══════════════════════════════╩═══════╩═════════╩══════════╝

I guess pseduo code would be:
SHOW all products
WHERE
    instock (any location) > 0 AND
    (cost > 10 AND cost < 2000)
ORDER BY
    cost asc

Notes:

*

*refs are unique per supplier

*brand and mpn lookup needs to be
case insensitive

Expected Result:
╔══════════╦══════════╦════════════╦══════════════╦══════════════╦═══════════════════════════╗
║   ref    ║  brand   ║    mpn     ║     sku      ║    scost     ║          instock          ║
╠══════════╬══════════╬════════════╬══════════════╬══════════════╬═══════════════════════════╣
║ whatever ║ Dogiclon ║ 912-101242 ║ based on ref ║ based on ref ║ based on ref and location ║
╚══════════╩══════════╩════════════╩══════════════╩══════════════╩═══════════════════════════╝

This is what I'm trying:
SELECT DISTINCT
    product.ref,
    product.brand,
    inventory.scost,
    inventory.instock
FROM
    product
    JOIN inventory ON inventory.ref = product.ref
WHERE
    inventory.instock > 1
    AND ( app.inventory.scost >= 10 AND app.inventory.scost <= 2000 )
GROUP BY
    product.ref

A: If you are grouping by unique column within product which seems to be ref, distinct won't do what you wish it would. DISTINCT takes care of uniqueness per returned row (all values being returned). In this case to get one row in result per product ref you'd need to drop the distinct part, add product.mfr to group by and aggregate non-grouped columns like below:
SELECT
    product.ref,
    product.mfr,
    group_concat(inventory.scost) as scost,
    group_concat(inventory.instock) as instock,
FROM
    product
    JOIN inventory ON inventory.ref = product.ref
WHERE
    inventory.instock > 1
    AND ( app.inventory.scost >= 10 AND app.inventory.scost <= 2000 )
GROUP BY
    product.ref, product.mfr

If you want to ensure proper ordering for scost and instock just include ordering clause within the group_concat itself ie:
group_concat(column order by column1, [...])


text:
Q: I have a problem with this function "Uncaught ReferenceError: sync is not defined at HTMLInputElement.onkeyup" The function doesn't work, the console show me this message: Uncaught ReferenceError: sync is not defined at HTMLInputElement.onkeyup
`https://jsfiddle.net/sfzc68w0/`

I expect the textarea will include the text from input

A: That because you have a function of the html event onkeyup

  Adresa de email
  <input type="text" id="i1" name="i1" value="" class="form-control input-sm"

  [HERE===>]onkeyup="sync()">

  Numarul de telefon
  <input type="text" id="i2" name="i2" value="" class="form-control input-sm"

  [HERE===>]onkeyup="sync()">

  Județ
  <input type="text" id="i3" name="i3" value="" class="form-control input-sm"

  [HERE===>]onkeyup="sync()">

  Descriere - date de contact, adresă, stare etc.
  <textarea name="body" class="form-control" rows="6"></textarea>

You have to remove it from there or just create the "sync()" function on the window object (on the window scope).


text:
Q: Can't install supervisor in docker container I have a Dockerfile
FROM python:3.10.4

RUN apt-get update
RUN apt-get install -y supervisor

WORKDIR /app

COPY requirements.txt .
COPY ./docker/api/conf.d/supervisor.conf /etc/supervisor/conf.d/supervisord.conf

RUN pip3 install -r requirements.txt

EXPOSE 8010
CMD ["uvicorn", "v1.api:app", "--host=0.0.0.0", "--port", "8010", "--reload"]

When I build this Dockerfile on my local machine (Ubuntu), everything works fine
However, when I build it on a CentOS 7 virtual machine, i got this error:

=> ERROR [3/7] RUN apt-get install -y supervisor
0.6s

[3/7] RUN apt-get install -y supervisor:
#0 0.473 Reading package lists...
#0 0.501 Building dependency tree...
#0 0.503 Reading state information...
#0 0.508 E: Unable to locate package supervisor
failed to solve: executor failed running [/bin/sh -c apt-get install -y supervisor]: exit code: 100

Please help me.
How do I install supervisor in the container


text:
Q: Easiest way to reset Backbone's model to initial defaults? My models already have a defaults hash. When parts of the view/page are reset, I wish to reset the models back to their original defaults.
Currently, I explicitly set each attribute to its default value. Is there anything built in or a JavaScript/Underscore.js/Backbone.js/jQuery function that I could use to do this in a single statement?

A: I came up with the following approach:
reset: function () {
    this.clear({silent: true});
    this.set(this.defaults);
}

Having {silent: true} in the clear() call ensures that the change event is not fired; it will be fire only on set() call.

A: I do this when the model has non-null initial object properties.
first, define defaults as a function
var MyModel = Backbone.Model.extends({

    defaults:function(){

        return {
            AnArrayTypeProp:[]
        };
    }

});

second, when needed to reset model to default
model.clear().set(model.defaults());

A: Based on saabeilin's answer and Backbone's annotated source, I came with an optimal function to fill the need for resetting a model.
Reusable reset
/**
 * Clears the model's attributes and sets the default attributes.
 * @param  {Object} attrs to overwrite defaults
 * @param  {Object} options  to pass with the "set" call.
 * @return {Backbone.Model}  this object, to chain function calls.
 */
reset: function(attrs, options) {
    // adds default option reset to true
    options = _.extend({ reset: true }, options);

    // ensure default params
    var defaults = _.result(this, 'defaults');
    attrs = _.defaults(_.extend({}, defaults, attrs), defaults);

    // apply
    this.clear({ silent: true }).set(attrs, options);

    // triggers a custom event, namespaced to model in order
    // to avoid collision with collection's native reset event
    // when listening to a collection.
    if (!options.silent) this.trigger('model:reset', this, options);

    return this;
},

The following line ensures that even if an attribute is passed as undefined { test: undefined }, it'll still have its default value.
attrs = _.defaults(_.extend({}, defaults, attrs), defaults);

Here's an example:
var defaults = { test: 1 },
    attrs = { test: undefined };

_.extend({}, defaults, attrs);                       // {test: undefined}
_.defaults(_.extend({}, defaults, attrs), defaults); // {test: 1}

Extending Backbone
And if you want it with all Backbone models, you can extend Backbone itself:
_.extend(Backbone.Model.prototype, {
    reset: function(attributes, options){
        /* ... */
    }
});

Disclaimer: Don't do this if you're writing a JavaScript lib or Backbone plugin, as it could collide with another lib or it could cause a different behavior than the one expected by the person using your code.

A: I also thought about using model.clear() and model.set() in conjunction. Then I ran across the problem, that I trigger the change event twice now.
Using the silent option when calling model.clear() is not an option, because I also want to have a change event fired, when a property gets unset.
I ended up with adding a model.reset() method. It takes a new attributes hash and fills this hash with undefined values for old attributes keys not being present in the new attribute hash.
Model.prototype.reset = function(attrs, options) {
    for (var key in this.attributes) {
        if (key in attrs) continue;
        attrs[key] = void 0;
    }

    return this.set(attrs, options);
};

This way you reset the models old attributes and get a valid change event for every old and new attribute.

A: myModel.clear().set(myModel.defaults);

A: What about overriding the value of current model with a new empty model :
myModel = new model(); // default values will be considered

A: My solutions is:
model.clear({silent: true}).set(model.defaults);


text: Q: How to replace existing Curl version with an updated one using Cygwin? I already have curl 7.40.0 installed on my windows. I downloaded the latest curl package from https://curl.haxx.se/download.html and I unziped it into my Downloads directory. Now I have a usr directory in my Downloads. Location of curl.exe is Downloads/usr/bin/curl.exe. I want to replace my existing curl (/cygdrive/c/Program Files/cURL/bin/curl this I got by typing "which curl" on terminal) on my system with this new version which is in the Downloads. How do I do it?


text:
Q: Symfony ManyToOne relationship getter returns empty object I'll simplifly my code, I have te next:
Doctor entity:
    use ...\...\Entity\Paciente;

    class Doctor extends Usuario {

        public function __construct() {
            ...
            $this->pacientes = new ArrayCollection();
            ...

        }

        /**
         * Número de colegiado - numColegiado
         *
         * @var string
         *
         * @ORM\Column(name="numColegiado", type="string", length=255, unique=true)
         */
        protected $numColegiado;

        /**
         * @ORM\OneToMany(targetEntity="Paciente", mappedBy="doctor")
         * @var \Doctrine\Common\Collections\ArrayCollection
         */
        private $pacientes;

       ...

    }

Paciente entity:
use \...\...\Entity\Doctor;

...

class Paciente extends Usuario {

    }

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Doctor", inversedBy="pacientes")
     * @ORM\JoinColumn(name="doctorNum", referencedColumnName="numColegiado", nullable=TRUE)
     *
     * @var type
     */
    protected $doctor;

    ...

    /**
     * Set doctor
     *
     * @param Doctor $doctor
     * @return Paciente
     */
    public function setDoctor(Doctor $doctor = null)
    {
        $this->doctor = $doctor;

        return $this;
    }

    /**
     * Get doctor
     *
     * @return Doctor
     */
    public function getDoctor()
    {
        return $this->doctor;
    }
}

Ok, the matter is, when I execute that code (of course there is a relationship created and this object exists in the database):
\Doctrine\Common\Util\Debug::dump($paciente->getDoctor());

It prints that follows:
object(stdClass)#804 (28) { ["__CLASS__"]=> string(34) "Knoid\CorcheckBundle\Entity\Doctor" ["__IS_PROXY__"]=> bool(true) ["__PROXY_INITIALIZED__"]=> bool(false) ["id"]=> NULL ["numColegiado"]=> NULL ["pacientes"]=> NULL ["nombre"]=> NULL ["apellidos"]=> NULL ["dni"]=> NULL ["tipo"]=> NULL ["username"]=> NULL ["usernameCanonical"]=> NULL ["email"]=> NULL ["emailCanonical"]=> NULL ["enabled"]=> NULL ["salt"]=> NULL ["password"]=> NULL ["plainPassword"]=> NULL ["lastLogin"]=> NULL ["confirmationToken"]=> NULL ["passwordRequestedAt"]=> NULL ["groups"]=> NULL ["locked"]=> NULL ["expired"]=> NULL ["expiresAt"]=> NULL ["roles"]=> NULL ["credentialsExpired"]=> NULL ["credentialsExpireAt"]=> NULL }

As you can see, all the atributes of the "doctor" object are null, the object exists but it's empty, in my DB this object exists and it isn't empty.
Any idea of what's happening ?

A: This is because the proxy object is not initialised yet. One way to initialise it, is by querying the object e.g. $doctor->getId(). If you dump the object after that, you'll see that all the attributes are 'visible'

A: The answer of Thomas K worked for me in my own Bundle. If I translate what I did :
$myPaciente = $em->getRepository('MyBundle:Paciente')->findOneBy(array('numColegiado' => $value));

I add $myPaciente->getDoctor()->getName();
Then the initialisation was done and I could dump $myPaciente with all the information about the doctor related to it.


text:
Q: Why do nodes in force layout jump from origin on update Why do my circles jump from (0,0) when I update my data each iteration?
I want to make a force layout with circles that change radius when the data updates. I can't figure out how to use d3 forces inside a loop. All I can get is circles that jumping from the origin while they change their sizes. I suppose that problem lies in the way how d3 stores and sets the coordinates to objects.
Here is my code:

var tickDuration = 1000;
var margin = {top: 80, right: 60, bottom: 60, left: 60}
const width = 960 - margin.left - margin.right,
    height = 600 - margin.top - margin.bottom;
let step = 0;

data = [
    {
        "name": "A",
        "value": 99,
        "step": 9
    },
    {
        "name": "A",
        "value": 28,
        "step": 8
    },
    {
        "name": "A",
        "value": 27,
        "step": 7
    },
    {
        "name": "A",
        "value": 26,
        "step": 6
    },
    {
        "name": "A",
        "value": 25,
        "step": 5
    },
    {
        "name": "A",
        "value": 24,
        "step": 4
    },
    {
        "name": "A",
        "value": 23,
        "step": 3
    },
    {
        "name": "A",
        "value": 22,
        "step": 2
    },
    {
        "name": "A",
        "value": 21,
        "step": 1
    },
    {
        "name": "A",
        "value": 20,
        "step": 0
    },
    {
        "name": "B",
        "value": 19,
        "step": 9
    },
    {
        "name": "B",
        "value": 18,
        "step": 8
    },
    {
        "name": "B",
        "value": 17,
        "step": 7
    },
    {
        "name": "B",
        "value": 16,
        "step": 6
    },
    {
        "name": "B",
        "value": 150,
        "step": 5
    },
    {
        "name": "B",
        "value": 14,
        "step": 4
    },
    {
        "name": "B",
        "value": 13,
        "step": 3
    },
    {
        "name": "B",
        "value": 12,
        "step": 2
    },
    {
        "name": "B",
        "value": 11,
        "step": 1
    },
    {
        "name": "B",
        "value": 10,
        "step": 0
    },
    {
        "name": "С",
        "value": 39,
        "step": 9
    },
    {
        "name": "С",
        "value": 38,
        "step": 8
    },
    {
        "name": "С",
        "value": 37,
        "step": 7
    },
    {
        "name": "С",
        "value": 36,
        "step": 6
    },
    {
        "name": "С",
        "value": 35,
        "step": 5
    },
    {
        "name": "С",
        "value": 34,
        "step": 4
    },
    {
        "name": "С",
        "value": 33,
        "step": 3
    },
    {
        "name": "С",
        "value": 32,
        "step": 2
    },
    {
        "name": "С",
        "value": 31,
        "step": 1
    },
    {
        "name": "С",
        "value": 30,
        "step": 0
    }
];

const halo = function (text, strokeWidth) {
    text.select(function () {
        return this.parentNode.insertBefore(this.cloneNode(true), this);
    })
        .style('fill', '#ffffff')
        .style('stroke', '#ffffff')
        .style('stroke-width', strokeWidth)
        .style('stroke-linejoin', 'round')
        .style('opacity', 1);

}

var svg = d3.select('body').append('svg')
    .attr('width', width + margin.left + margin.right)
    .attr('height', height + margin.top + margin.bottom)
    .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

let rad = d3.scaleSqrt()
    .domain([0, 100])
    .range([0, 200]);

var fCollide = d3.forceCollide().radius(function (d) {
    return rad(d.value) + 2
});
    fcharge = d3.forceManyBody().strength(0.05)
    fcenter = d3.forceCenter(width / 2, height / 2)

var Startsimulation = d3.forceSimulation()
    .force('charge', fcharge)
    //.force('center', fcenter)
    // .force("forceX", d3.forceX(width/2).strength(.2))
    // .force("forceY", d3.forceY(height/2).strength(.2))
    .force("collide", fCollide)

function ticked() {
    d3.selectAll('.circ')
        .attr('r', d => rad(d.value))
        .attr("cx", function (d) {
            return d.x = Math.max(rad(d.value), Math.min(width - rad(d.value), d.x));
        })

        .attr("cy", function (d) {
            return d.y = Math.max(rad(d.value), Math.min(height - rad(d.value), d.y));
        })

    d3.selectAll('.label')
        .attr("cx", function (d) {
            return d.x = Math.max(rad(d.value), Math.min(width - rad(d.value), d.x));
        })
        .attr("cy", function (d) {
            return d.y = Math.max(rad(d.value), Math.min(height - rad(d.value), d.y));
        });

}

data.forEach(d => {
    d.value = +d.value
    d.value = isNaN(d.value) ? 0 : d.value,
        d.step = +d.step,
        d.colour = d3.hsl(Math.random() * 360, 0.6, 0.6)
});

let stepSlice = data.filter(d => d.step == step && !isNaN(d.value))
    .sort((a, b) => b.value - a.value)

let stepText = svg.append('text')
    .attr('class', 'stepText')
    .attr('x', width - margin.right)
    .attr('y', height - 25)
    .style('text-anchor', 'end')
    .html(~~step)
    .call(halo, 10);

svg.selectAll('circle.circ')
    .data(stepSlice, d => d.name)
    .enter()
    .append('circle')
    .attr('class', 'circ')
    .attr('r', d => rad(d.value))
    .style('fill', d => d.colour)
    .style("fill-opacity", 0.8)
    .attr("stroke", "black")
    .style("stroke-width", 1)

Startsimulation.nodes(stepSlice).on('tick', ticked)

let ticker = d3.interval(e => {

    stepSlice = data.filter(d => d.step == step && !isNaN(d.value))
        .sort((a, b) => b.value - a.value)

    // rad.domain([0, d3.max(stepSlice, d => d.value)]);
    let circles = d3.selectAll('.circ').data(stepSlice, d => d.name)

    circles

        .transition()
        .duration(tickDuration)
        .ease(d3.easeLinear)
        .attr('r', d => rad(d.value))

    Startsimulation
        .nodes(stepSlice)
        .alpha(1)
        .alphaTarget(0.3)

    stepText.html(~~step);
    if (step == 9) ticker.stop();
    step = d3.format('.1f')((+step) + 1);
}, tickDuration);
<!DOCTYPE html>

    <meta charset="utf-8">

A: The ultimate issue lies with d3-force given your code, but I'm going to propose an alternative method of creating this visualization (if I understand it correctly). This proposed alternative will be more consistent with the patterns D3 was designed for.
The proposed solution will address the issue with d3-force but also make the data binding easier too. I'll attempt to explain why a different approach might be preferrable on both points below:
D3 and Data Binding
D3 places a considerable focus on data binding. Items in a data array are bound to elements in the DOM.
Generally speaking the best data source for use in D3 is one where the data is an array and every item in that data array is represented by an element in the DOM. This way we can enter, update, exit easily.
Your data is an array of 30 items, of which you show only 3. The elements have new data bound to them every step/interval. This requires filtering the data array, using a key function, and rebinding new data each step/interval. This newly bound data is used to update the circles and the force layout.
A more straight forward method with D3 would be to structure your data differently. You have three circles so your data array should have three objects in it. These objects should have properties to hold the step data. Then we can update the circles based on what step we're on. No reselection, rebinding, filtering, etc neccesarry. The downside is this often requires restructuring your data prior to even getting to the visualization code - but the returns are worth it when you start making the visualization.
D3 Force Simulation
The nodes method of a D3 force simulation takes an array of objects. If these objects don't have x, y, vx, vy properties, the force simulation modifies these objects to give them these properties (it does not clone these objects to do so). This is the initialization of nodes. If you replace the original nodes with new ones, the simulation will initialize the new nodes. There is no reference to the previous nodes - the nodes are the objects themselves (you aren't replacing a data portion of the node, you're replacing the entire node).
To address this in your current approach we'd need to take the x,y,vx,vy properties of each node of the current step and assign those properties to the nodes of the next step at the beginning of each step.
Instead, let's have the force simulation keep the same nodes the whole time. As above, we have three nodes, so we have a data array of three objects, each with all the step data contained within it. Now we don't need to filter nodes, transfer properties, etc.
Alternative Approach
We'll use a data array that contains one object for each thing we want to represent:
let data = [
  {
    "name": "A",
    "steps": [20,21,22,23,24,25,26,27,28,99],
    "colour": "steelblue"
  },
  {
    "name": "B",
    "steps": [10,11,12,13,14,150,16,17,18,19],
    "colour":"crimson"
  },
  {
    "name": "С",
    "steps": [30,31,32,33,34,35,36,37,38,39],
    "colour":"orange"
  }
];

Now when we want to advance to the nth step, we can get the current radius with someScale(d.steps[n]). This lets us set the drawn radius and the collision radius without rebinding data to the DOM elements and without providing new nodes to the force.
Now we can set up everything that isn't dependent on step:

*

*SVG

*Scales

*Tick function

*Data

*Most of simulation set up

*Enter SVG elements

However, you don't need to set the initial radius to the first step's value when you add the circles because we'll do that each time we move a step. We just need the static properties of each SVG element (That said, I've set the initial radii to zero below so we can transition in nicely).
Then we can place all the code that is changes with each step within the interval function. This code will do only a few things:

*

*Increment to the next step

*Set a new collide force with new radii

*Transition the radii of the circles

*Apply the new collide force and reheat the simulation.

*Update the text that shows what step we're on.

Notes
I've heavily modified your code to show a simplified example of the alternative. The largest change not part of the above explanation is the removal of labels for simplicity.
One thing to note about transitions and force layouts. If you transition a radius and set the radius in the tick function, the tick function and the transition will constantly over-ride one another. Transitions should modify attributes that are not modified in the tick and vice versa. In your code you modify each circles r in both tick and transition.
I've changed the transition time to be less than the duration between each interval: this way I can insure that the transition is complete prior to beginning the next step and its corresponding transition. I've exaggerated this change cause I liked the pause.
I have a function below (radius) that uses the current step and datum to return a radius. Because I wanted to use just this where I need a circle's radius, I start at step -1. The reason is because I need to increment step at the beginning of the nextStep function. If I increment at the end of this function then the ticked function - which runs continuously - will use a different step than the rest of the nextStep function. The radius function has been written so that if the step is -1, it'll use the zeroth step to avoid issues on initialization. There may be nicer ways of handling this, I felt this was the simplest.
I can add more comments if necessary, but I hope that the above explanation and my limited comments are sufficient:

const tickDuration = 1000,
      margin = {top: 80, right: 60, bottom: 60, left: 60},
      width = 960 - margin.left - margin.right,
      height = 600 - margin.top - margin.bottom;

let data = [
  {
    "name": "A",
    "steps": [20,21,22,23,24,25,26,27,28,99],
    "colour": "steelblue"
  },
  {
    "name": "B",
    "steps": [10,11,12,13,14,150,16,17,18,19],
    "colour":"crimson"
  },
  {
    "name": "С",
    "steps": [30,31,32,33,34,35,36,37,38,39],
    "colour":"orange"
  }
];

let step = -1;
let svg = d3.select('body').append('svg')
    .attr('width', width + margin.left + margin.right)
    .attr('height', height + margin.top + margin.bottom)
    .append('g')
    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')

// No need to set the text value yet: we'll do that in the interval.
let stepText = svg.append('text')
    .attr('x',10) // repositioned for snippet view.
    .attr('y', 10)

// Scale as before.
let scale = d3.scaleSqrt()
    .domain([0, 100])
    .range([0,  100]);

// Get the right value for the scale:
let radius = function(d) {
  return scale(d.steps[Math.max(step,0)]);
}

// Only initial or static properties - no data driven properties:
let circles = svg.selectAll('circle.circ')
    .data(data, d => d.name)
    .enter()
    .append('circle')
    .attr("r", 0) // transition from zero.
    .style('fill', d => d.colour)

// Set up forcesimulation basics:
let simulation = d3.forceSimulation()
    .force('charge', d3.forceManyBody().strength(100))
    .nodes(data)
    .on('tick', ticked)

// Set up the ticked function for the force simulation:
function ticked() {
  circles
    .attr("cx", function (d) {
      return d.x = Math.max(radius(d), Math.min(width - radius(d), d.x));
    })
    .attr("cy", function (d) {
      return d.y = Math.max(radius(d), Math.min(height - radius(d), d.y));
    })
}

// Advance through the steps:
let ticker = d3.interval(nextStep, tickDuration);

function nextStep() {
  step++;

  // Update circles
  circles.transition()
    .duration(tickDuration*0.5)
    .ease(d3.easeLinear)
    .attr('r', radius)

  // Set collision force:
  var collide = d3.forceCollide()
    .radius(function (d) {  return radius(d) + 2 })

  // Update force
  simulation
    .force("collide", collide)
    .alpha(1)
    .restart();

  // Update text
  stepText.text(step);
  // Check to see if we stop.
  if (step == 9) ticker.stop();
};
nextStep(); // Start first step without delay.
text {
  font-size: 64px;
  font-weight: 700;
  opacity: 0.25;
}

circle {
  fill-opacity: 0.8;
  stroke: black;
  stroke-width: 1px;
}


text:
Q: Inlining a conditional type in typescript? Sorry for what might be a simple question to people more familiar with typesystems. Why does inlining a conditional in typescript give different results?
For example, if I'm using the Extract conditional, I get different behavior if I inline it vs if I use it as a generic:
// setup
type TUnion = ['foo', 1] | ['baz', 2];
type TDiscriminator = ['foo', any];

// using the conditional generic
type Extract<T, U> = T extends U ? T : never;
type TExtracted = Extract<TUnion, TDiscriminator>; // ["foo", 1]

// inlining the conditional
type TInlined = TUnion extends TDiscriminator ? TUnion : never; // never

When I push on this further, it seems that the value of T needs to be passed in:
type ExtractWithU<T> = T extends TDiscriminator ? T : never;
type TExtractedWithU = ExtractWithU<TUnion>; // ["foo", 1]

type ExtractWithT<U> = TUnion extends U ? TUnion : never;
type TExtractedWithT = ExtractWithT<TDiscriminator>; // never

Am I missing something really simple?

A: From the comment chain above with jcalz and Titian, the problem is that the generic is being distributed while the inlined one is not.
Concretely
// setup
type TA = ['foo', 1];
type TB = ['baz', 2];
type TUnion = TA | TB;
type TDiscriminator = ['foo', any];

// using the conditional generic
type Extract<T, U> = T extends U ? T : never;
type TExtracted = Extract<TUnion, TDiscriminator>; // ["foo", 1]
//              = Extract<TA | TB, TDiscriminator>
//              = Extract<TA, TDiscriminator> | Extract<TB, TDiscriminator>
//              = TA | never
//              = TA

// inlining the conditional
type TInlined = TUnion extends TDiscriminator ? TUnion : never; // never
//            = never, because the union isn't a subtype of the discriminator


text:
Q: CSS Sprite-Sheet resize with var calc in row col for adapt sprite I have no way of knowing the actual values of these variables.

Also I'm not sure my code is correct.

I want resize the sprite sheet 1536x128 to 384x32 and adapt this size to sprites.

Using var, calc, parseInt with system of Col > X > Width, and Row > Y > Height.

But not work, all explain in code:

:root {
    /* image sprite sheet */
    --sheet_width: 1536px;
    --sheet_height: 128px;
    /* one sprite in this sheet */
    --sprite_width: 128px;
    --sprite_height: 128px;
    /*
        Sprite sheet can contain 12 sprits on width 128x12=1536
        Debug css value before cal are not possible for me ! (i work on notepad++)
        normaly nb_col =  12 > (1536px / 128px) > 12px ? > parseint > 12 ?
        normaly nb_row =  0 > (128px / 128px) > 1px ? > parseint > 1 ?
    */
    --nb_col: parseInt(calc(var(--sheet_width) / var(--sprite_width)));
    --nb_row: parseInt(calc(var(--sheet_height) / var(--sprite_height)));
    /*
        I want transform sprite sheet for 32x32 sprites
        So i defined it with variables
    */
    --content_width: 32px;
    --content_height: 32px;
    /*
        And i calculate the new size of my sprite sheet
        new width 32 * 12 = 384px ?
        new height 32 * 1 = 32px ?
    */
    --sheetcontent_width: calc(var(--content_width) * var(--nb_col));
    --sheetcontent_height: calc(var(--content_height) * var(--nb_row));
    /*
        for finish what i want, i use variable for store
        the value to define my background-size
        --content_resolution = background-size: 384px 32px ?
    */
    --content_resolution: var(--sheetcontent_width) var(--sheetcontent_height);
}
.spritebox {
    background: url("buttons.png");
    display: block;
    width: var(--content_width);
    height: var(--content_height);
    background-repeat: no-repeat;
    background-size: var(--content_resolution);

}
.spritebox.spriteblock_00 {
    background-position: calc(-1 * var(--content_width) * 0) top;
}
.spritebox.spriteblock_01 {
    background-position: calc(-1 * var(--content_width) * 1) top;
}
.spritebox.spriteblock_02 {
    background-position: calc(-1 * var(--content_width) * 2) top;
}

00

01

02


text:
Q: Insert mysql usando ajax estou tentando inserir registro no BD via ajax mas estou tendo problemas, eu estava usando o format: 'json' mas tava dando erro de permissão e talz, agora estou usando type: "POST", dataType: "jsonp". Enfim, esses dados para eu inserir o registro vem de um form, segue o codigo abaixo:
JS
if(!document.getElementById('formulario')) return;
                var f = document.getElementById( 'formulario' );

                var nome = f.elements[1].value;
                var email = f.elements[2].value;
                var senha = f.elements[3].value;
                var telefone = f.elements[4].value;
                var endereco = f.elements[5].value;
                var estado = f.elements[6].value;
                var cidade = f.elements[7].value;

                var url = 'http://www.petfy.com.br/android/addUsuario.php?nome='+nome+'&email='+email+'&senha='+senha+'&telefone='+telefone+'&endereco='+endereco+'&estado='+estado+'&cidade='+cidade+'&imagem='+imagem+'';
                $.ajax({
                    url: url,
                    type: "POST",
                    dataType: "jsonp",
                    success: function(rows){
                        rows = $.parseJSON(rows);
                        for (var i in rows){
                            var row = rows[i],
                                id = row[0],
                                nome = row[1];
                                alert(nome);
                        }
                    },
                    error: function(rows){
                        alert('erro');
                    }
                });

agora o PHP no servidor:
header("Access-Control-Allow-Origin: *");

include '../banco.php';

$nome     = $_POST['nome'];
$email    = $_POST['email'];
$senha    = $_POST['senha'];
$telefone = $_POST['telefone'];
$endereco = $_POST['endereco'];
$estado   = $_POST['estado'];
$cidade   = $_POST['cidade'];
$imagem   = $_POST['imagem'];

$sql = mysql_query(" INSERT INTO usuarios VALUES ('','$nome','$email','$telefone','$endereco','$cidade','$estado','$senha','$imagem') ");

$usuario = array();
$sql2 = mysql_query("SELECT * FROM usuarios ORDER BY id DESC LIMIT 1");
while ($result = mysql_fetch_array($sql2)) {
    $usuario[] = $result;
}

echo json_encode($usuario);

o erro que ele me retorna é esse:
GET http://www.petfy.com.br/android/addUsuario.php?nome=Felipe%20Furlan&email=f…ype=large&callback=jQuery1707645740224979818_1407864204964&_=1407864215433 403 (Forbidden)

A: Olá amigo reveja as alterações que eu fiz, no data você pode passa o serialize do form completo, em vez de setar variaveis ... e outra coisa já que está usando jquery use por completo em vez de document.getElementById = $('#id')
faça os devidos a justes conforme suas necessidades
jQuery('#formulario').submit(function(e){
   e.preventDefault();
  var nome = $('input[name="nome"]').val();
  var url = 'http://www.petfy.com.br/android/addUsuario.php';
                    $.ajax({
                        url: url,
                        type: "POST",
                        data: jQuery(this).serialize().
                        dataType: "json",
                        success: function(rows){
                            rows = $.parseJSON(rows);
                            for (var i in rows){
                                var row = rows[i],
                                    id = row[0],
                                    nome = row[1];
                                    alert(nome);
                            }
                        },
                        error: function(){
                            alert('erro');
                        }
                    });
});

A: SOLUCAO
             var url = 'http://www.petfy.com.br/android/addUsuario.php';
            $.ajax({
                url: url,
                type: "POST",
                data:{
                    nome: nome, email: email, senha: senha, telefone: telefone, endereco: endereco, estado: estado, cidade: cidade
                },
                success: function(rows){
                    rows = $.parseJSON(rows);
                    for (var i in rows){
                        var row = rows[i],
                            id = row[0],
                            nome = row[1];
                            alert(nome);
                    }
                },
                error: function(rows){
                    alert('erro');
                }
            });
        });


text:
Q: How to apply WHERE clause to a RECORD REPEATED I have a table composed like that:
-header
-data
-----createdAt
-----attributes
---------------key
---------------value

where data is a type RECORD in mode NULLABLE and attributes is a type RECORD in mode REPEATED.
I would like to make a query:
SELECT *
FROM `tablename`
WHERE data.createdAt >= "2021-08-13 10:44:00.000 UTC"
AND data.attributes.key = "key name"
AND data.attributes.value IS null

That clearly I can't.
How can I achieve this?

A: For the records, this should work:
    SELECT *
    FROM `table`
    CROSS JOIN UNNEST (data.attributes) as attributes
    WHERE EXISTS (
        SELECT *
        FROM UNNEST(data.attributes) AS attributes
        WHERE attributes.attributeKey = "key name"
        AND attributes.attributeValue IS NULL
    )
    AND data.createdAt >= "2021-08-13 10:44:00.000 UTC"

or also
   SELECT *
   FROM `table`
   CROSS JOIN UNNEST (data.attributes) as attributes
   WHERE attributes.attributeKey = "key name"
   AND attributes.attributeValue IS NULL
   AND data.createDateTime >= "2021-08-13 10:44:00.000 UTC"


text:
Q: How to create a folder named "1" (If not exists) then create a folder named "2" (if not exist in the same directory)and so on I need to create folders named like "1", "2" , "3"  and so on ...
Everytime script should check if it exists already or not. If not it should create or otherwise simply continue and create folder with next numeric value.
e.g. If folder "1" is there is shouldn't create folder, instead script should create folder "2" and exit. Everytime script should check for the folder and it should create the next one if its already there, or else it should create the same it was checking for.
Please let me know if anybody know the answer.
Regards,
Eshant Garg


text:
Q: How to extract exact matches with list from one dataframe column to another one? I have a large dataframe with text that I want to use to find matches from a list of words (around 1k words in there).
I have managed to get the absence/presence of the word from the list in the dataframe, but it is also important to me to know which word matched.
Sometimes there is exact match with more than one word from the list, I would like to have them all.
I tried to use the code below, but it gives me partial matches - syllables instead of full words.
#this is an example of what I want

import pandas as pd

df_data= [['orange','0','0'],
  ['apple and lemon','1','apple, lemon'],
  ['lemon and orange','1', 'lemon'],
 ]

df= pd.DataFrame(df_data,columns=['text','match','exact word(s)'])

#this is the list of words I need to match
exactmatch = ['apple', 'lemon']

#this is what I've tried, for some rows it gives me words I want, and for some it gives me parts of the word

pattern1 = '|'.join(exactmatch)
df['contains'] = df['text'].str.extract("(" + "|".join(exactmatch) +")", expand=False)

Unlike similar questions, here I'm interested in using patterns from a list, and not just one regex.
The question was marked as duplicate, however, the solution from the linked post does not work:
df['contains'] = df['text'].str.extractall
("(" + "|".join(exactmatch) +")").unstack().apply(','.join, 1)

This is what I get:
TypeError: ('sequence item 1: expected str instance, float found', 'occurred at index 2')

A: An applymap(str) was missing so that ",".join could work properly for this case.
import pandas as pd

df_data= [['orange','0','0'],
  ['apple and lemon','1','apple, lemon'],
  ['lemon and orange','1', 'lemon'],
 ]

df= pd.DataFrame(df_data,columns=['text','match','exact word(s)'])

exactmatch = ['apple', 'lemon']

df_tmp = df['text'].str.extractall("(" + "|".join(exactmatch) + ")")
df_tmp = df_tmp.unstack().fillna("").applymap(str).apply(",".join, 1)

# fix when empty column is used with join
df["Word(s)"] = df_tmp.replace(",$","", regex=True)
df.fillna(0, inplace=True)
print(df)

               text match exact word(s)      Word(s)
0            orange     0             0            0
1   apple and lemon     1  apple, lemon  apple,lemon
2  lemon and orange     1         lemon        lemon


text:
Q: Modern fantasy novel with yellow cover about girl who discovers she is a witch It was written by a young, female (possibly Australian, I can't really remember) author and probably came out somewhere between 2008-2013. It begins with the protagonist going about her day to day life (I think she was being bullied at school) until certain strange events cause her to discover she has magical powers (it might have been water magic?). She meets some sassy flying creature who goes on to become her companion. I think it ended on a cliffhanger but a sequel never came out. The story had lots of humorous moments and didn't take itself too seriously.
The bright yellow cover also had the silhouette of a girl in a shirt and jeans on it. It looked something like this:

Unfortunately, that is all I can remember. Please help if you can!


text:
Q: Difference between declaring Routes in React Router v6 and v6.4+ I've tried searching that, however, couldn't really find whether using React Fragments is okay to achieve the same behavior as pre-v6.4?
const Routes6 = (
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="posts" element={<Posts />}>
      <Route path="/posts/new" element={<NewPost />} />
    </Route>
  </Routes>
);

const routes64 = createBrowserRouter(
  createRoutesFromElements(
    <>
      <Route path="/" element={<Home />} />
      <Route path="/posts" element={<Posts />}>
        <Route path="/posts/new" element={<NewPost />} />
      </Route>
    </>,
  ),
);

A: I see no reason why using React.Fragements wouldn't work to implement the routes using the new RRDv6.4+ data router. A more conventional method that avoids the React.Fragment may be to use a root route on "/" and render the Home component on an index route.
Example:
const routes64 = createBrowserRouter(
  createRoutesFromElements(
    <Route path="/">
      <Route index element={<Home />} />
      <Route path="/posts" element={<Posts />}>
        <Route path="new" element={<NewPost />} />
      </Route>
    </Route>,
  ),
);


text:
Q: How to deliver fonts from a non-standard directory using Asset Pipeline I'm trying to include Fontawesome with a Rails 4 app however the assets aren't making it into the asset pipeline. However, the fonts aren't making it out in production and I can't figure out why.
File structure organisation
All my assets are stored in /assets/components
so that Fontawesome appears in: /assets/components/font-awesome (they're in a different directory because I'm using Bower).
CSS manifest file:
# application.css.scss
/* ...
*= require bootstrap/dist/css/bootstrap
*= require font-awesome/css/font-awesome
*= require_self
*= require_tree .
*/

Asset pipeline is set to precompile fonts
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.paths << Rails.root.join('vendor', 'assets', 'components')

# Adding Webfonts to the Asset Pipeline
config.assets.precompile << Proc.new { |path|
  if path =~ /\.(eot|svg|ttf|woff|otf)\z/
    true
  end
}

I added the precompile instructions so that the fonts would all be precompiled as per this question
Heroku 12 Factor gem is included
#gemfile
group :production do
  gem "rails_12factor"
end

So what's the problem?
When I push to Heroku, it shows that the application is requesting the files but that they're not loading:

And looking at the logs it seems to be a routing issue - I would have expected the font to be served from /assets/fonts but it is apparently looking in /fonts
   app[web.1]: Started GET "/fonts/fontawesome-webfont.ttf?v=4.0.1" for 86.161.231.181 at 2013-10-29 15:53:01 +0000
   app[web.1]: Started GET "/fonts/fontawesome-webfont.ttf?v=4.0.1" for 86.161.231.181 at 2013-10-29 15:53:01 +0000
   app[web.1]:
   app[web.1]: ActionController::RoutingError (No route matches [GET] "/fonts/fontawesome-webfont.ttf"):

Why aren't the assets getting served
I'm a bit confused with all of this. Why aren't these fonts being served?

A: This problem maybe caused by a reason that Rails assets can't precompile url() function in CSS file.
Because your fonts files are precompiled by assets, all urls point to these files must be rewritten to MD5-digested file name. Unfortunately Rails can't precompile url() automatically, at least I think so because I tested some cases and got this conclusion :) In Rails guide, Rails provides these functions using ERB and Sass. see here .
I think there are two ways to solve your problem.
The first, set directory in .bowerrc to public/components and use them manually, don't require them in your assets.
The second, I suggest to use font-url() instead of url() in Font-Awesome, so your application.css.scss will be looked like:
   /* ...
    *= require bootstrap/dist/css/bootstrap
    *= require font-awesome/css/font-awesome
    *= require_self
    *= require_tree .
    */

    @font-face {
      font-family: 'FontAwesome';
      src: font-url('font-awesome/fonts/fontawesome-webfont.eot?v=4.0.3');
      src: font-url('font-awesome/fonts/fontawesome-webfont.eot?#iefix&v=4.0.3') format('embedded-opentype'),
      font-url('font-awesome/fonts/fontawesome-webfont.woff?v=4.0.3') format('woff'),
      font-url('font-awesome/fonts/fontawesome-webfont.ttf?v=4.0.3') format('truetype'),
      font-url('font-awesome/fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular') format('svg');
      font-weight: normal;
      font-style: normal;
    }

Redefine the font-path with your actual font path and font-face with font-url() , this function is provided by sass-rails. After precompile, you will see your url has been rewritten to /assets/font-awesome/fonts/fontawesome-webfont-50b448f878a6489819d7dbc0f7dbfba0.eot?v=4.0.3 or something like in public/assets/application-xxxxxx.css.
You can find the same approach in various gems which include assets for example bootstrap-sass, it's a very popular gem. read this file: _glyphicons.scss. You will see:
@font-face {
  font-family: 'Glyphicons Halflings';
  src: font-url('#{$icon-font-path}#{$icon-font-name}.eot');
  src: font-url('#{$icon-font-path}#{$icon-font-name}.eot?#iefix') format('embedded-opentype'),
       font-url('#{$icon-font-path}#{$icon-font-name}.woff') format('woff'),
       font-url('#{$icon-font-path}#{$icon-font-name}.ttf') format('truetype'),
       font-url('#{$icon-font-path}#{$icon-font-name}.svg#glyphicons_halflingsregular') format('svg');
}

url() has been replaced. So I think rewrite @font-face in application.css.scss is the simplest way :)
By the way, bootstrap and font-awesome both have @font-face. I don't know whether font-awesome is necessary.
When you access the page, it shows the correct log. So you don't need change any code in bower repositories. Hope it helps.


text:
Q: Is it possible to integrate the mapping capabilities of QGIS with Stata? I was wondering  of the possibility of integrating the mapping capabilities of Q-GIS with Stata, by using the programming aspect of Stata as opposed to using R or python.
Is this possible?


text:
Q: Correct procedure to call multiple asynchronous functions in node.js I have a requirement where I need to get the records from table 1 and store in redis cache and once redis cache is finished storing, get table 2 records and store in redis cache. So there are 4 asynchronous functions.
Steps:

*

*Get table 1 records

*Store in redis cache

*Get table 2 records

*Store in redis cache

What is the correct procedure to handle it.
Below is the code which I have written to handle it. Please confirm whether its the right procedure or any other ways to handle it as per node.js
var redis = require("redis");
var client = redis.createClient(6379, 'path', {
    auth_pass: 'key'
});

var mysqlConnection = // get the connection from MySQL database

get_Sections1()

function get_Sections1() {
    var sql = "select *from employee";

    mysqlConnection.query(sql, function (error, results) {
        if (error) {
            console.log("Error while Sections 1 : " + error);
        } else {
            client.set("settings1", JSON.stringify(summaryResult), function (err, reply){
                if (err) {
                    console.log("Error during Update of Election : " + err);
                } else {
                    get_Sections2();
                }
            });
        }
    });
}

function get_Sections2()
{
    var sql = "select *from student";

    mysqlConnection.query(sql, function (error, results)
    {
        if (error)
        {
            console.log("Error while Sections 2 : " + error);
        }
        else
        {
            client.set("settings2", JSON.stringify(summaryResult), function (err, reply)
            {
                if (err)
                {
                    console.log("Error during Update of Election : " + err);
                }
                else
                {
                    console.log("Finished the task...");
                }
            });
        }
    });
}

A: Create two parameterised functions. One for retrieval, one for storing.
Then promisify them both.
Then write:
return getTableRecords(1)
  .then(storeInRedisCache)
  .then(getTableRecords.bind(null,2))
  .then(storeInRedisCache)
  .then(done);

To promisify a function, something like this might work:
var getEmployees = new Promise(function(resolve, reject) {
  var sql = "select *from employee";

  mysqlConnection.query(sql, function (error, results) {
    if (error) {
      return reject();
    } else {
      return resolve(results);
    }
  });
});

If you are using an old version of NodeJS you will need a polyfill for Promise.

A: Here is an alternative to Ben Aston's solution using Promise.coroutine assuming promises:
const doStuff = Promise.coroutine(function*(){
     const records = yield getTableRecords(1);
     yield storeRecordsInCache(records);
     const otherRecords = yield getTableRecords(2);
     yield storeRecordsInCache(otherRecords); // you can use loops here too, and try/cath
});

doStuff(); // do all the above, assumes promisification

Alternatively, if you want to use syntax not yet supposed in Node (and use Babel to get support) you can do:
async function doStuff(){
     const records = await getTableRecords(1);
     await storeRecordsInCache(records);
     const otherRecords = await getTableRecords(2);
     await storeRecordsInCache(otherRecords); // you can use loops here too, and try/cath
})


text:
Q: deliveries quote 404 Not Found deliveries quote 404 Not Found
     we call deliveries quote API, we getting following 404 errors
     https://api.uber.com/v1/deliveries/quote
Fatal error: Uncaught exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: `POST https://api.uber.com/v1/deliveries/quote` resulted in a `404 Not Found` response: 404 page not found ' in /home/mealhi5/domains/mealhi5.com/public_html/libraries/uber/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113 Stack trace: #0 /home/mealhi5/domains/mealhi5.com/public_html/libraries/uber/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response)) #1 /home/mealhi5/domains/mealhi5.com/public_html/libraries/uber/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response)) #2 /home/mealhi5/domains/mealhi5.com/public_html/libraries/uber/vendor/guzzlehttp/promises/src/Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array) #3 /home/mealhi5/domains/mealhi5.com/public_html/libraries/uber/vendor/gu in /home/mealhi5/domains/mealhi5.com/public_html/libraries/uber/src/Client.php on line 173

We are using following sample code to work out, let me know what could be issue.
require_once('vendor/autoload.php');

$client = new Stevenmaguire\Uber\Client(array(

'access_token' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',

'server_token' => 'xxxxxxx',

'use_sandbox'  => false, // optional, default false

'version'      => 'v1', // optional, default 'v1.2'

'locale'       => 'en_US', // optional, default 'en_US'

));

$data['items'][0]['title'] = 'Chocolate bar';
$data['items'][0]['quantity'] = 1;
$data['items'][0]['price'] = 10;
$data['items'][0]['currency_code'] = 'USD';

$data['pickup']['contact']['first_name'] = 'xxxxx';
$data['pickup']['contact']['last_name'] = 'xxxxxx';
$data['pickup']['contact']['phone']['number'] = 'xxxxxx';
$data['pickup']['contact']['contact'] = 'Sri Surati Thali';
$data['pickup']['location']['address'] = '138 S Main St';
$data['pickup']['location']['city'] = 'Milpitas';
$data['pickup']['location']['state'] = 'CA';
$data['pickup']['location']['postal_code'] = '95035';
$data['pickup']['location']['country'] = 'US';

$data['dropoff']['contact']['first_name'] = 'xxxx';
$data['dropoff']['contact']['last_name'] = 'xxxx';
$data['dropoff']['contact']['phone']['number'] = 'xxxxxxx';
$data['dropoff']['location']['address'] = '399 Silicon Valley Blvd';
$data['dropoff']['location']['city'] = 'San Jose';
$data['dropoff']['location']['state'] = 'CA';
$data['dropoff']['location']['postal_code'] = '95138';
$data['dropoff']['location']['country'] = 'US';

$products = $client->deliveriesquote($data);

A: I don't think that endpoint is adding new people, see this article for example: http://fortune.com/2018/03/31/uber-ending-uberrush-delivery-service/
In addition, in the scope list for delivery it mentions: "Including access to your route information for any delivery in progress. Your Uber account will be charged for any deliveries processed. Selecting this scope will only provide access to the sandbox. For full access, apply here."
So it does not seem like you should move forward with delivery testing. Hope that helps.


text:
Q: svn update does not load all files from server From time to time I've this problem and still no clue why this happens.
Sometimes svn won't load all files with svn up.
Example:
$ svn up
Aktualisiere ».«:
Revision 18.
$ ls -alh externalFiles/
insgesamt 8,0K
drwxr-xr-x  2 me mygroup 4,0K Dez  8 10:24 .
drwxr-xr-x 10 me mygroup 4,0K Dez  8 10:24 ..
$ svn list http://svn.my-server.local/spielwiese/trunk/externalFiles/
file1.xlsx
Fahrzeugangaben-Dateien/
Fahrzeugangaben.htm
file2.docx
file3.dotx

As you can see there are several files inside "externalFiles" which I am missing local. I can do svn up as often as I want and it still won't download the missing files. I even can delete the whole directory (local of course) - svn up just recreates it but without files.
What happens here?
Deleting the whole repository and do a fresh new checkout can't be a real solution.


text:
Q: CSS div wrapper works with everything except these div tags. Why? I have used a wrapper to center div tags and it works for everything except the css in the link
Please check out:
http://jsfiddle.net/T5rBU/3/
As you can see the pink box with text is in the center but the black box isn't.
I have put
float: left;

but that is only because if I don't the black box doesn't show!?

A: try this:
.center div {
     display:inline-block;
     text-align:center;
}

it seams to work:
http://jsfiddle.net/u3ggV/

A: add a with to .center
.center {width:400px;}
or another width you cant center div with text-align

A: I don't quite follow what you mean but I think it could be down to not having a wrapping element to hold both divs - http://jsfiddle.net/djsbaker/T5rBU/4/
Did you want the black box beside or above/below the navigation?