text:
Q: Angular theme: how to use Material theme color within a custom component style? Despite hours spent looking for this info, I don't know how to use the Material pre-built theme colors I choose from Angular Material, with my own components.
I was expecting something like that, my-component.component.scss
a {
  color: $primary-color;
}

a .active {
  color: $active-link
}

However, it seems it does not work that way as I cannot find any list of "colors" to be used.
The closer thing I found was to do the following:
@use '~@angular/material' as mat;
$my-palette: mat.define-palette(mat.$indigo-palette);

a {
  color: mat.get-color-from-palette($my-palette, '100-contrast');
}

The catch is I don't want to specify a palette, but I would like to use the default one. Plus I doubt this is the best way to import theme colors...
Any help with dummy example would be really appreciated!


text:
Q: BindTransportException when trying to start elasticsearch I am trying to start my elasticsearch server by running bin/elasticsearch from my ES directory but I keep getting a bindtransport exception. What should I do?
 idea!
[2016-08-11 04:57:45,143][INFO ][node                     ] [anish-elk1] version[2.3.3], pid[30342], build[218bdf1/2016-05-17T15:40:04Z]
[2016-08-11 04:57:45,143][INFO ][node                     ] [anish-elk1] initializing ...
[2016-08-11 04:57:45,683][INFO ][plugins                  ] [anish-elk1] modules [lang-groovy, reindex, lang-expression], plugins [], sites []
[2016-08-11 04:57:45,707][INFO ][env                      ] [anish-elk1] using [1] data paths, mounts [[/ (/dev/xvda1)]], net usable_space [16.1gb], net total_space [49gb], spins? [no], types [ext4]
[2016-08-11 04:57:45,707][INFO ][env                      ] [anish-elk1] heap size [990.7mb], compressed ordinary object pointers [true]
[2016-08-11 04:57:47,647][INFO ][node                     ] [anish-elk1] initialized
[2016-08-11 04:57:47,648][INFO ][node                     ] [anish-elk1] starting ...
Exception in thread "main" BindTransportException[Failed to bind to [9300-9400]]; nested: ChannelException[Failed to bind to: /192.168.0.1:9400]; nested: BindException[Cannot assign requested address];
Likely root cause: java.net.BindException: Cannot assign requested address
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:444)
    at sun.nio.ch.Net.bind(Net.java:436)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:214)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at org.jboss.netty.channel.socket.nio.NioServerBoss$RegisterTask.run(NioServerBoss.java:193)
    at org.jboss.netty.channel.socket.nio.AbstractNioSelector.processTaskQueue(AbstractNioSelector.java:391)
    at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:315)
    at org.jboss.netty.channel.socket.nio.NioServerBoss.run(NioServerBoss.java:42)
    at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108)
    at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

elasticsearch.yml
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
# name that es uses to find other clusters to join
# when you turn on a node, it will find other nodes on the network to talk to
# if found, it will cluster. name determines if node will join or not.
cluster.name: elk1
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
# everytime you turn on a node, it will choose a marvel comic character
# node.name is just a name
node.name: anish-elk1
#
# Add custom attributes to the node:
#
# node.rack: r1
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
# path.data: /path/to/data
#
# Path to log files:
#
# path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
# allows jvm to lock memory on startup to avoid swapping
bootstrap.mlockall: true
#
# Make sure that the `ES_HEAP_SIZE` environment variable is set to about half the memory
# available on the system and that the owner of the process is allowed to use this limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
# setting to control network traffic. only allows traffic from :<> so that
# external processes cannot access elasticsearch server
# network.host: 192.168.0.1
#
# Set a custom port for HTTP:
#
# http.port: 9200
#
# For more information, see the documentation at:
# <http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-network.html>
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when new node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
# discovery.zen.ping.unicast.hosts: ["host1", "host2"]
#
# Prevent the "split brain" by configuring the majority of nodes (total number of nodes / 2 \
+ 1):
#
# discovery.zen.minimum_master_nodes: 3
#
# For more information, see the documentation at:
# <http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery.html>
...(everthing commenteed)

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery sum of each new created row Im trying to calculate input val() on each row, currently it calculates only 1st row please help, Thanks!
HTML
new

JS
$('.new').click(function(){
    $("ul").append('
<input type="text" class="inputA"/><input type="text" class="inputB"/>
total:

');
});

$('.container').on('keyup', 'input', function(){

  var a = 0;
  var b = 0;
  var c = 0;
  var d = 0;

  $('ul li').each(function(){
    $(this).parent().find('li input').each(function(){
      a = parseInt($('.inputA').val());
      b = parseInt($('.inputB').val());
      c = a+b;
        $(this).parent().find('p span').html(c);
    });
    d += c;
  });

  $('.all').html(d);

});

FIDDLE

A: Use
$('.new').click(function () {
    $("ul").append('
<input type="text" class="inputA"/><input type="text" class="inputB"/>
total:

');
});

$('.container').on('keyup', 'input', function () {

    var d = 0;
    $('.container li').each(function () {
        var $this = $(this),
            a = parseFloat($this.find('.inputA').val()) || 0,
            b = parseFloat($this.find('.inputB').val()) || 0
        var subTotal = a + b;
        $this.find('span').text(subTotal);
        d += subTotal;
    })

    $('.all').html(d);

});

Demo: Fiddle

A: $('.new').click(function () {
    $("ul").append('
<input type="text" class="inputA"/><input type="text" class="inputB"/>
total:

');
});

$('.container').on('keyup', 'input', function () {
    var total = 0;
    $('ul li').each(function () {
        var a = parseInt($(this).find('.inputA').val(), 10) || 0;
        var b = parseInt($(this).find('.inputB').val(), 10) || 0;
        $(this).find('p span').html(a + b);
        total += (a + b);
    });
    $('.all').html(total);
});

jsFiddle example

A: Here is what I came up with:
$('.new').click(function () {
    $("ul").append($('
', {
        html: [
            $('<input>', {class: 'inputA'}),
            $('<input>', {class: 'inputB'}),
            $('', {class: 'total'})
        ]
    }).data('total', 0)); //set list item total to ZERO
});

$('.container').on('keyup', 'input', function () {
    var other_input = $(this).siblings('input');
    var totalEl = $(this).siblings('.total');
    var total = parseInt(this.value);
    var list_item = $(this).parents('li');
    total += parseInt(other_input.val());
    totalEl.text(total); //show new total
    list_item.data('total', total); //set list item's total

    var real_total = 0;
    var allEl = $('.all');
    list_item.parent().find('li').each(function(){
        var t = $(this).data('total');
        real_total += t;
    }); //tally up all list item totals
    allEl.text(real_total); //display the total total
});

Fiddle: http://jsfiddle.net/maniator/Wn2cs/11/

A: A concise version. Includes a bit of code to handle new lines automatically as a bonus.
$('.new').click(function () {
    $("ul").append('
<input type="text" class="inputA"/><input type="text" class="inputB"/>
total:

');
});

$(document).on("blur","input.inputB",function () {
    $('.new').click();
});

$('.container').on('keyup', 'input', function (e) {

    //var code = e.keyCode || e.which;

    var d = 0;

    $('ul li').each(function () {
        a = parseInt($(this).find('input.inputA').val());
        b = parseInt($(this).find('input.inputB').val());
        c = a + b;
        $(this).find('p span').html(c);
        d += c;
    });

    $('#all').html(d);

});

[jsFiddle]


text:
Q: How to populate Twitter Typeahead based on select box value? I have an input text that is correctly populate with Twitter Typeahead. In this case i would like to select a value from select box and populate the input text with values that are related with selected dropdownlist value. I found similar questions about my doubt but unfortunatly i didnt get the correct way to solve this:

*

*Dynamically populating Twitter Bootstrap Typeahead

*Twitter bootstrap Typeahead to populate hrefs

*jQuery Autocomplete / Twitter Typeahead Populate Multiple Fields
Below is the code that display a select box that is populate with php code and an input text that is populated with Twitter TypeAhead script:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

DYNAMIC TWITTER TYPEAHEAD

<?php
    // Include the database config file
    include_once 'dbConfig.php';

    // Fetch all the category data
    $query = "SELECT * FROM categories ORDER BY category ASC";
    $result = $db->query($query);
?>

<select id="categoryFK" name="categoryFK" class="form-control">
    <option value="">Select category</option>
    <?php
    if($result->num_rows > 0){
        while($row = $result->fetch_assoc()){
            echo '<option value="'.$row['categoryID'].'">'.$row['category'].'</option>';
        }
    }else{
        echo '<option value="">Category not available</option>';
    }
    ?>
</select>

<input type="text" name="products" id="products" class="form-control input-lg" autocomplete="off" placeholder="" />

Below is the script that call php script via Ajax:

And below is the php script (fetch.php) that populate values according to categoryID:

<?php
//fetch.php
include 'dbConfig.php';
if(!empty($_POST["query"])){
$request = mysqli_real_escape_string($db, $_POST["query"]);
$query = "
 SELECT * FROM products WHERE productName LIKE '%".$request."%' AND categoryFK = ".$_POST["query"]."
";

$result = $db->query($query);
$data = array();

if(mysqli_num_rows($result) > 0)
{
 while($row = mysqli_fetch_assoc($result))
 {
  $data[] = $row["productName"];
 }
 echo json_encode($data);
}
}
?>

As i showed the code above, when i type something into input text after i selected any option into select box, the input text with Twitter TypeAhead just populate one register.
In this case, how can i improve php code above to populate input text with values related with select box value correctly? Thanks.

A: I managed to solve the problem. Below are the scripts that i modified to adapt on my project:
AJAX

And PHP script (fetch.php)
<?php
include 'dbConfig.php';

if ( isset ( $_POST [ 'category' ] ) ) {
    $request = $db->real_escape_string($_POST["category"]);

    $query = "
        SELECT * FROM products WHERE categoryFK = ".$request."
    ";

    $result = $db->query($query);
    $data = array ();

    if ( $result->num_rows > 0 )
    {
        while($row = $result->fetch_assoc ())
        {
            $data[]=$row["productName"];
        }

        echo json_encode($data);
    }
}
?>

Now, with these modifications, i can select an option into "category" select box and after, type into input text where all valus related with selected option will be load :)


text:
Q: Typescript let used outside of block-scope causing ReferenceError in apps We have multiple web apps already in production working properly. During recent updates (which includes tree shaking i think), our apps crashes with the ReferenceError: Cannot access 'variable' before initialization.
We found some typescript source code that uses the 'let' declaration inside a block scope, and then accessing that variable outside of the block. This used to work before (not my code, but i know it is wrong).
example:
    let batman: number = 1;
    switch(batman)
    {
        case 0:
            let superman: boolean = false;
            break;

        case 1:
            superman = true;
            break;
    }

Before: No errors.
Now: ReferenceError: Cannot access 'superman' before initialization
Question:
How can I automate or catch all instances of this issue without manually going through all code?


text:
Q: JavaScript function that returns all permutations I've been trying to make a function that generates all the permutations of the numbers from 0 to num and stores them in a multidimensional array. I want to store in the combinations variable something like:
 [ [ 1, 2, 3 ],
    [ 1, 3, 2 ],
    [ 2, 1, 3 ],
    [ 3, 1, 2 ],
wrongly     [ 2, 3, 1 ],
    [ 3, 2, 1 ] ]

but instead I get:
[ [ 3, 2, 1 ],
  [ 3, 2, 1 ],
  [ 3, 2, 1 ],
  [ 3, 2, 1 ],
  [ 3, 2, 1 ],
  [ 3, 2, 1 ] ]

My function is:
var combinations = [];

function comb(num, index, list, used) {
  if (num == index)
    combinations.push(list);
  else {
    for (var i = 0; i < num; ++i) {
      if (!used[i]) {
        list[i] = index + 1;
        used[i] = true;
        comb(num, index + 1, list, used);
        used[i] = false;
      }
    }
  }
}

I usually program with C++, so I think that I am using the arrays wrongly.

A: Your issue is that the list array you pass into your recursive call is going to be changed as it is essentially passed by reference, so list will lose its previous combinations. Instead, you can make a copy of the array before you pass it into your recursive call using the spread syntax (...).
See working example below:

var combinations = [];

function comb(num, index, list, used) {
  if (num == index)
    combinations.push(list);
  else {
    for (var i = 0; i < num; ++i) {
      if (!used[i]) {
        list[i] = index + 1;
        used[i] = true;
        comb(num, index + 1, [...list], used);
        used[i] = false;
      }
    }
  }
}

comb(3, 0, [], []);
console.log(combinations); // [[1,2,3],[1,3,2],[2,1,3],[3,1,2],[2,3,1],[3,2,1]]
.as-console-wrapper { max-height: 100% !important; top: 0;}


text:
Q: Extracting the maximum of several subsets and join all maximums in a new table I have a big table:

What I need is to obtain the maximum value for each testname, with different entry and get a new table such as:

And then I want to compute the maximum, the minimum and the average value for this new table.
Can you help me?

A: First step:
SELECT testname, entry, MAX(`value`) as max_value
FROM your_table
GROUP BY testname, entry

Second step:
SELECT MAX(max_value), MIN(max_value), AVG(max_value)
FROM ( /*here we insert the query from the first step*/
    SELECT testname, entry, MAX(`value`) as max_value /*rename the column so we can conveniently access it from the outer query*/
    FROM your_table
    GROUP BY testname, entry
) sq /*sq is an alias for the subquery, it's needed*/


text:
Q: Problems with merge function I'm trying to create a us map with the total cases of Covid-19 by state. In order to do that task I have this following code:
library(readxl)
library(maptools)
library(spdep)
library(RColorBrewer)

library(sp)
library(sf)

hp_usa_states <- readShapeSpatial("USA_States.shp")
names(shp_usa_states)
shp_usa_states@data

infected <- read_excel("C:/Users/BP2646/Desktop/databaseinfUS/US.xlsx")
names(infected)

I have problems with this part of the code "(Error in fix.by(by.x, x) : 'by' must specify a uniquely valid column)"
infected_bystate <- shp_usa_states
    infected_bystate@data <- merge(shp_usa_states@data,infected,by.x= "Cases",by.y="Cases",all.x = TRUE,sort  = FALSE)
    summary(infected_bystate)

I have this problem:
Error in fix.by(by.x, x) : 'by' must specify a uniquely valid column
I don't know why.
This is my dataset:
structure(list(State = c("Arizona", "California", "Colorado",
"Connecticut", "District of Columbia", "Florida", "Georgia",
"Hawaii", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky[384][385]",
"Lousiana", "Maryland", "Massachusetts", "Michigan", "Minnesota",
"Missouri", "Nebraska", "Nevada", "New Hampshire", "New Jersey",
"New York", "North Carolina", "Ohio", "Oklahoma", "Oregon", "Pennsylvania",
"Rhode Island", "South Carolina", "Soth Dakota", "Tennessee",
"Texas", "Utah", "Vermont", "Virginia", "Washington", "Wisconsin",
"Total"), Cases = c(6, 157, 18, 2, 4, 28, 22, 2, 19, 6, 13, 1,
8, 6, 9, 92, 2, 3, 1, 5, 4, 5, 15, 176, 7, 3, 2, 15, 14, 5, 9,
5, 7, 21, 2, 1, 9, 275, 3, 976), Recovered = c(1, 6, 0, 0, 0,
0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 12), Deceased = c(0, 3,
0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 24, 0, 31), Remaining = c(5,
148, 18, 2, 4, 26, 22, 2, 17, 6, 13, 1, 8, 6, 9, 91, 2, 3, 1,
5, 4, 5, 14, 176, 7, 3, 2, 15, 14, 5, 9, 4, 7, 21, 2, 1, 9, 250,
2, 933)), row.names = c(NA, -40L), class = c("tbl_df", "tbl",
"data.frame"))

This is the second data frame:
structure(list(STATE_NAME = structure(c(48L, 27L, 20L, 35L, 42L,
51L, 50L, 13L, 46L, 24L, 38L, 30L, 16L, 22L, 28L, 33L, 39L, 7L,
40L, 31L, 15L, 29L, 45L, 5L, 36L, 14L, 9L, 8L, 49L, 21L, 6L,
18L, 17L, 47L, 26L, 3L, 37L, 34L, 43L, 44L, 32L, 1L, 25L, 11L,
41L, 4L, 19L, 10L, 23L, 12L, 2L), .Label = c("Alabama", "Alaska",
"Arizona", "Arkansas", "California", "Colorado", "Connecticut",
"Delaware", "District of Columbia", "Florida", "Georgia", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky",
"Louisiana", "Maine", "Maryland", "Massachusetts", "Michigan",
"Minnesota", "Mississippi", "Missouri", "Montana", "Nebraska",
"Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York",
"North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon",
"Pennsylvania", "Rhode Island", "South Carolina", "South Dakota",
"Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington",
"West Virginia", "Wisconsin", "Wyoming"), class = "factor"),
    STATE_FIPS = structure(c(48L, 27L, 20L, 35L, 42L, 51L, 50L,
    13L, 46L, 24L, 38L, 30L, 16L, 22L, 28L, 33L, 39L, 7L, 40L,
    31L, 15L, 29L, 45L, 5L, 36L, 14L, 9L, 8L, 49L, 21L, 6L, 18L,
    17L, 47L, 26L, 3L, 37L, 34L, 43L, 44L, 32L, 1L, 25L, 11L,
    41L, 4L, 19L, 10L, 23L, 12L, 2L), .Label = c("01", "02",
    "04", "05", "06", "08", "09", "10", "11", "12", "13", "15",
    "16", "17", "18", "19", "20", "21", "22", "23", "24", "25",
    "26", "27", "28", "29", "30", "31", "32", "33", "34", "35",
    "36", "37", "38", "39", "40", "41", "42", "44", "45", "46",
    "47", "48", "49", "50", "51", "53", "54", "55", "56"), class = "factor"),
    STATE_ABBR = structure(c(48L, 27L, 22L, 29L, 42L, 51L, 49L,
    14L, 47L, 24L, 38L, 31L, 13L, 20L, 30L, 35L, 39L, 7L, 40L,
    32L, 16L, 34L, 45L, 5L, 36L, 15L, 8L, 9L, 50L, 21L, 6L, 18L,
    17L, 46L, 25L, 4L, 37L, 28L, 43L, 44L, 33L, 2L, 26L, 11L,
    41L, 3L, 19L, 10L, 23L, 12L, 1L), .Label = c("AK", "AL",
    "AR", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "HI",
    "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME",
    "MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ",
    "NM", "NV", "NY", "OH", "OK", "OR", "PA", "RI", "SC", "SD",
    "TN", "TX", "UT", "VA", "VT", "WA", "WI", "WV", "WY"), class = "factor")), class = "data.frame", row.names = c("0",
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
"13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23",
"24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34",
"35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45",
"46", "47", "48", "49", "50"), data_types = c("C", "C", "C"))


text:
Q: JAVA aop @AfterThrowing couldn't catch Exception I want to do some action when this method has an exception.
Therefore I made aop function like AfterReturning, AfterThrowing...
I changed the method raising exception on purpose.
But the request arrives AfterReturning, not AfterThrowing even if exception is occured.
How can I make this request reach to AfterThrowing method?
    @EventListener
    @GetHost
    public void getHost(ContextRefreshedEvent event) throws Exception {

        try {
            prHostName = InetAddress.getLocalHost().getHostName();
            prIpAddr = InetAddress.getLocalHost().getHostAddress();

            //making exception on purpose
            String[] tmp = new String[0];
            prIpAddr = tmp[1];

        } catch (Exception exception) {
            prHostName = "unknown";
            prIpAddr = "unknown";
            System.out.println("unknown");
            exception.printStackTrace();

        }
    }

There are aop methods
    @Pointcut("@annotation(com.etc.web.annotation.GetHost)")
    public void componentMethod() {}

    @Before("componentMethod()")
    public void beforeComponent(JoinPoint point) {
        System.out.println("beforeComponent");

    }

    @Around("componentMethod()")
    public Object aroundComponent(ProceedingJoinPoint point) throws Throwable {

        System.out.println("aroundComponent");
        Object retVal = point.proceed();

        return retVal;
    }
    @AfterReturning(pointcut = "componentMethod()", returning = "result")
    public void afterComponent(JoinPoint point, Object result) {
        System.out.println("afterReturnComponent");

    }

    @AfterThrowing(pointcut = "componentMethod()", throwing = "exception")
    public void afterThrowingComponent(JoinPoint point, Throwable exception) throws Exception {
        System.out.println("afterThrowingComponent");

    }

Please help me.
Thanks!

A: The method does not exit with an exception, because the exception is caught and the method exits normally. So of course, @AfterThrowing is not triggered. That should not surprise you.


text:
Q: css border-image gradient solution I've had a search around but cannot find a solution to the way I wish to use it.
My gradient will be border-top/bottom with a white center with a reflected 0% opacity. Giving the effect that you see a lot like this.
border-image: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(255,255,255,0)), color-stop(49%,rgba(255,255,255,1)), color-stop(100%,rgba(255,255,255,0)));
But I cannot seem to get it to work, any ideas? I can't think of a way apart from adding manual images above and below the divs, which seems like a terrible way of doing it.

A: I think that what you want to do is this
.test {
    position: absolute;
    left: 20px;
    top: 20px;
    width: 200px;
    height: 200px;
    border-style: solid;
    border-width: 20px 0px;
    border-image-source: linear-gradient(90deg, rgba(255,255,255,0), rgba(255,255,255,1), rgba(255,255,255,0));
    border-image-slice: 20;
    border-image-repeat: stretch;
    box-shadow: 0px 0px 10px black;
}

body {
    background-color: lightblue;
}

I have used only the unprefixed syntax; it will work as is in Chrome. You can use the shorthand notation, but I think that this way is more easy to understand how it works.
I have also set a background on body (if not, it's difficult to tell the difference between white and transparent) and shadow on the div so that you can see the real diemnsions.
fiddle


text:
Q: Signed zero linux vs windows i am running a program in c++ on windows and on linux.
the output is meant to be identical.
i am trying to make sure that the only differences are real differences oppose to working inviorment differences.
so far i have taken care of all the differences that can be caused by \r\n differences
but there is one thing that i can't seem to figure out.
in the windows out put there is a 0.000 and in linux it is -0.000
does any one know what can it be that is making the difference?
thanx

A: Probably it comes from differences in how the optimizer optimizes some FP calculations (that can be configurable - see e.g. here); in one case you get a value slightly less than 0, in the other slightly more. Both in output are rounded to a 0.000, but they keep their "real" sign.

A: Since in the IEEE floating point format the sign bit is separate from the value, you have two different values of 0, a positive and a negative one. In most cases it doesn't make a difference; both zeros will compare equal, and they indeed describe the same mathematical value (mathematically, 0 and -0 are the same). Where the difference can be significant is when you have underflow and need to know whether the underflow occurred from a positive or from a negative value. Also if you divide by 0, the sign of the infinity you get depends on the sign of the 0 (i.e. 1/+0.0 give +Inf, but 1/-0.0 gives -Inf). In other words, most probably it won't make a difference for you.
Note however that the different output does not necessarily mean that the number itself is different. It could well be that the value in Windows is also -0.0, but the output routine on Windows doesn't distinguish between +0.0 and -0.0 (they compare equal, after all).

A: Unless using (unsafe) flags like -ffast-math, the compiler is limited in the assumptions it can make when 'optimizing' IEEE-754 arithmetic. First check that both platforms are using the same rounding.
Also, if possible, check they are using the same floating-point unit. i.e., SSE vs FPU on x86. The latter might be an issue with math library function implementations - especially trigonometric / transcendental functions.


text:
Q: Using knockout.js with custom template engine I'm trying to get the timeline component of vis.js work together with knockout.js.
The timeline has a templates option which allows you to write custom HTML for each event on the timeline. In my case, it looks like this:
var options = {
    ... // other options
    template: function(item) {
        var html = '' + item.subject + ''+
                '
' + item.owner.username + ' (' + item.format.name + ' for ' + item.channel.name + ')
' +
                '
<input type="checkbox"';
        if (item.done !== null) {
            html += "checked"
        };
        html += '>
';
        html += '

';  // http://www.knockmeout.net/2013/06/knockout-debugging-strategies-plugin.html
        return html;
    }
}

All data bindings are tested and OK, but I cannot think of a way to attach knockout behaviour to the template generated by the vis.js timeline library. As you see, even trying to print out the $root data doesn't do a thing.
How can I attach observables to this template?

A: The template property of the options for the timeline component allows you to provide an HTML element instead of an HTML string if you so wish. This could be one way to achieve what you are after. This way you could create the element, use knockout to apply bindings on the element (and its children) using the provided item as context and return that element to vis.js.
An example of doing this could use code similar to the following:
var templateHtml = '

'
//Set the template to a custom template which lets knokcout bind the items
options.template = function(item){
    //Create a div wrapper element to easily create elements from the template HTML
    var element = document.createElement('div');
    element.innerHTML = templateHtml;
    //Let knockout apply bindings on the element with the template, using the item as data context
    ko.applyBindings(item, element);
    //Return the bound element to vis.js, for adding in the component
    return element;
};

In a knockout world, it would of course be better to create a custom bindingHandler for the vis.js timeline component.
Therefore, here you also have a sample of doing similar using a custom bindingHandler for knockout (which is a very simple sample bindingHandler, not really supporting observable options or observableArray for data, but it does support observable values in the items).

ko.bindingHandlers.visTimeline = {
    init: function(element, valueAccessor){
        var unwrappedValue = ko.unwrap(valueAccessor());
        var data = ko.unwrap(unwrappedValue.data);
        var options = ko.unwrap(unwrappedValue.options);

        if (options.templateId){
            var templateId = ko.unwrap(options.templateId);
            var templateHtml = document.getElementById(templateId).innerHTML;
            //Set the template to a custom template which lets knokcout bind the items
            options.template = function(item){
                //Create a div wrapper element to easily create elements from the template HTML
                var element = document.createElement('div');
                element.innerHTML = templateHtml;
                //Let knockout apply bindings on the element with the template, using the item as data context
                ko.applyBindings(item, element);
                //Return the bound element to vis.js, for adding in the component
                return element;
            };
        }

        //Apply the vis.js timeline component
        new vis.Timeline(element, data, options);
        //Let knockout know that we want to handle bindings for child items manually
        return { controlsDescendantBindings: true };
    }
};

var items = [
    { id: 1, content: 'item 1', counter: ko.observable(0), start: '2014-04-20'},
    { id: 2, content: 'item 2', counter: ko.observable(0), start: '2014-04-14'},
    { id: 3, content: 'item 3', counter: ko.observable(0), start: '2014-04-18'},
    { id: 4, content: 'item 4', counter: ko.observable(0), start: '2014-04-16', end: '2014-04-19'}
];

var viewModel = {
    items: items
};

//Randomly increment the counters of the items, to see that the data is bound
setInterval(function(){
    var randomItem = items[Math.floor(Math.random() * items.length)];
    randomItem.counter(randomItem.counter() + 1);
}, 500);

ko.applyBindings(viewModel);

<link href="https://cdnjs.cloudflare.com/ajax/libs/vis/3.12.0/vis.css" rel="stylesheet" />

You can also see this snippet at http://jsbin.com/lecidaxobo/1/edit?html,js,output


text:
Q: Logs en nginx, en blanco se crean pero no se actualizan Me estoy volviendo loco, me ha dejado de funcionar los logs, los he creado de nuevo, tengo los subdominios con los logs activados, he revisado la configuración de arriba abajo de nginx y no funciona, solo funciona un log que se a creado que pone error.log en /var/log/nginx y ese si se va actualizando cuando inicias nginx, el resto de logs se crean segun como los tengo configurados en site-avalibles, pero están en blanco
Un ejemplo de los logs creados:

-rw-r----- 1 www-data adm       0 May 26 10:42 blog_access.log
-rw-r----- 1 www-data adm       0 May 26 10:42 blog_error.log

Este es el único que funciona:

-rw-r----- 1 www-data adm   14591 May 26 12:40 error.log

No entiendo, porque he revisado como he dicho nginx.conf y he buscado por todo el equipo y no encuentro donde nginx le dice que cree ese log y tampoco entiendo, teniendo el resto de logs los mismos permisos y dueños, porque no funcionan.

A: Ya lo encontré:

--http-log-path=/var/log/nginx/access.log
--error-log-path=/var/log/nginx/error.log

Se compila cuando se instala nginx, pero esto no responde a porque me han dejado de funcionar el resto de logs


text:
Q: Output is fetched from the first input provided in the textbox 3, but the output should be change dynamically based textbox 3 input We have to provide input to three textbox. In two of the textbox, the value is static but the value is changed in the third one. Based on this input provided in the textbox, we click the Search button and the result is generated .E.g. Textbox1: 2, Textbox2: 3, Textbox3:91, Click on Search button. The page is refreshed for few seconds & output is generated. Total count: 13. Now againTextbox1: 2, Textbox2: 3, Textbox3:92,Click on Search button. The page is refreshed for few seconds & output is generated.Total count: 17.
But As per the below code, the output is 13.
please let me know issue in the code. I am not able to rectify it.
if (myFixedNumbers[0]==91){
 driver.findElement(By.id("txtPortal")).sendKeys(Integer.toString(myFixedNumbers[0]));
 driver.findElement(By.id("btnSearch")).click();
 // use it just before the sendkeys code like this
 wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@id='dvCount']/span[2]")));
 String text1 = driver.findElement(By.xpath("//*[@id='dvCount']/span[2]")).getText();
 System.out.println(text1);

 }

if (myFixedNumbers[1]==92){
 driver.findElement(By.id("txtPortal")).clear();
 driver.findElement(By.id("txtPortal")).sendKeys(Integer.toString(myFixedNumbers[1]));
 driver.findElement(By.id("btnSearch")).click();
 // use it just before the sendkeys code like this
 //wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[@id='dvCount']/span[2]")));
 String text2 = driver.findElement(By.xpath("//*[@id='dvCount']/span[2]")).getText();
 System.out.println(text2);

 }

A: In the second if block the wait code is commented. Because of this the code will try to retrieve the value from the box without being wait till the page is loaded. So try to uncomment the wait statement and retrieve the value.

A: Hi try this it will work
if (myFixedNumbers[0] == 91) {
            driver.findElement(By.id("txtPortal")).sendKeys(Integer.toString(myFixedNumbers[0]));
            driver.findElement(By.id("btnSearch")).click();
            // use it just before the sendkeys code like this
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='dvCount']/span[2]")));
            String text1 = driver.findElement(By.xpath("//*[@id='dvCount']/span[2]")).getText();
            System.out.println("Output 1 : " + text1);
        }
        if (myFixedNumbers[1] == 92) {
            Thread.sleep(1000);
            driver.findElement(By.id("txtPortal")).clear();
            driver.findElement(By.id("txtPortal")).sendKeys(Integer.toString(myFixedNumbers[1]));
            driver.findElement(By.id("btnSearch")).click();
            // use it just before the sendkeys code like this
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id='dvCount']/span[2]")));
            String text2 = driver.findElement(By.xpath("//*[@id='dvCount']/span[2]")).getText();
            System.out.println("Output 2 : " + text2);
        }

A: I have inserted Thread.Sleep and removed wait code .it is working fine now.


text:
Q: Is there a maximum sample size for a Kruskal Wallis test? I am performing a Kruskal Wallis test for very big sample sizes (100 000+ numbers). While the distributions seem similar on the figures, the test says there is a significant difference between the two distributions. This is making me think that the Kruskal Wallis test can become less reliable when using too large sample sizes. Is this the case?

A: Ideally, sample size for a test would be just a little larger than is necessary to detect an effect of a size that is of practical importance. When the sample size is huge the test may have enough power to find that differences of no practical significance are declared statistically significant.
Consider three samples of size $n=100$ from similar gamma populations: $\mathsf{Gamma}(5, .100)$ (with mean $\mu=50,$ median $\eta=46.709)$ and $\mathsf{Gamma}(5, .101)$ (with mean $\mu = 49.505,$ median $\eta=46.207).$
set.seed(901)
x1 = rgamma(100, 5, .1)
x2 = rgamma(100, 5, .101)
x3 = rgamma(100, 5, .101)

x = c(x1,x2,x3);  g = rep(1:3, each=100)
boxplot(x ~ g, horizontal=T, col="skyblue2", notch=T)

Boxplots do not show noticeable differences in locations. Notches in the sides of the boxes are nonparametric confidence intervals, calibrated so that overlapping of two intervals often indicates no true
difference in location.

A K-W test does not reject the null hypothesis that
all three samples are from populations with the same location.
kruskal.test(x ~ g)

        Kruskal-Wallis rank sum test

data:  x by g
Kruskal-Wallis chi-squared = 1.4712, df = 2, p-value = 0.4792

By contrast, if we repeat the above except for sample size $n=10\,000,$ the K-W tests finds
highly statistically significant differences among the populations.
set.seed(2021)
x1 = rgamma(10000, 5, .1)
x2 = rgamma(10000, 5, .101)
x3 = rgamma(10000, 5, .101)
x = c(x1,x2,x3);  g = rep(1:3, each=10000)
kruskal.test(x ~ g)

        Kruskal-Wallis rank sum test

data:  x by g
Kruskal-Wallis chi-squared = 16.363, df = 2, p-value = 0.0002798

Neither scenario of wrong. However, the second uses more data than necessary---unless it is of practical importance to detect a difference in location of size about $0.5$ units.


text: Q: Gdb prints no stack So my program compiles and prints the right values, but then when I use gdb it prints inferrior 1 process(...) exited normally. And then upon writing bt it prints back "no stack". Is this an error or an indication that everything works?


text:
Q: Check certain URL in JavaScript? How can I add something in JavaScript that will check the website URL of someone on a web site and then redirect to a certain page on the website, if a match is found? for example...
the string we want to check for, will be mydirectory, so if someone went to mysite.com/mydirectory/anyfile.php or even mysite.com/mydirectory/index.php JavaScript would then redirect their page / url to mysite.com/index.php because it has mydirectory in the URL, how can I do that using JavaScript?

A: Check out window.location, particularly it's properties and methods. You would be interested in (part of the) pathname property (you can split it on /) and the href property to change the page.
This is all assuming the javascript is being served in the first place; so I'm assuming anyfile.php and index.php would all result in the JS being served and not some 'generic 404' message.

A: If I have understood the question correctly, then it is fairly simple and can be achieved using document.URL
var search = 'mydirectory'; // The string to search for in the URL.
var redirect = 'http://mysite.com/index.php' // Where we will direct users if it's found
if(document.URL.substr(search) !== -1) { // If the location of
    // the current URL string is any other than -1 (doesn't exist)
    document.location = redirect // Redirect the user to the redirect URL.
}

Using document.URL you can check anything in the URL, however you might want to look into using something like Apache's mod_rewrite for redirecting the user before they even load the page.


text:
Q: Cannot add Secure InstallDir in Wix 1.10 Environment: Windows 7 x86 SP1, Wix Toolset 3.10
Below is the installer wxs ignoring the INSTALLDIR.

Here is the WiX XML:
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Product Id="*" Name="HelloWix Sample 1.0" Language="1041" Version="1.0.0"
           Manufacturer="CM" UpgradeCode="PUT-GUID-HERE" Codepage="932">
    <Package Description="Simple Message to standard output"
             Comments="This installer database contains the logic and data required
     to install HelloWix Sample." InstallerVersion="200" Compressed="yes"
     SummaryCodepage="932" />
    <Media Id="1" Cabinet="simple.cab" EmbedCab="yes" />
    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="ProgramFilesFolder" Name="PFiles">
        <Directory Id="hellowix" Name="hellowix">
          <Component Id="HelloWix.cmd" Guid="*">
            <File Id="HELLOWIX.CMD" Name="HelloWix.cmd" Source="HelloWix.cmd" />
          </Component>
        </Directory>
      </Directory>
    </Directory>
    <Feature Id="DefaultFeature" Title="Main Feature" Level="1">
      <ComponentRef Id="HelloWix.cmd" />
    </Feature>
    <UI />
    <UIRef Id="WixUI_InstallDir" />
    <Property Id="WIXUI_INSTALLDIR" Value="hellowix" />

    <!--Added the following line:-->
    <Property Id="INSTALLFOLDER" Secure="yes" />

  </Product>
</Wix>

I think it is a related topic of http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/Installer-ignores-InstallDir-directory-change-td6677782.html.
So I added only one line;  to the next line of Property Id="WIXUI_INSTALLDIR" as shown above:
    <!--Added the following line:-->
    <Property Id="INSTALLFOLDER" Secure="yes" />

Then my installer got Error Code 2343...What's wrong?

A: You can look up Windows Installer Error Messages on MSDN.
Error 2343 means "Specified path is empty". See link above, or get hold of
msi.chm from your Windows SDK installation (search under ProgramFiles). It is very practical to have that help file available for quick retrieval of other information and MSI SDK information. I believe there is a copy of it included with WiX as well in its installation folder.

As written in the comment, please try to set the dialog set to use <UIRef Id="WixUI_Mondo" /> instead of your current setting of <UIRef Id="WixUI_InstallDir" />. I believe there may be some bugs in some of these dialog sets. I was told to use Mondo back in the day, and I remember the problem I experienced disappeared. I can not recall what the problem was though.
Please give that a go first, and I will "evolve" this answer if you add new information to your question with the test results.
Perhaps also see this answer I wrote for a different question. It is very similar in that it is a minimal WiX file used to compile a test MSI and it uses the Mondo GUI: WiX installer msi not installing the Winform app created with Visual Studio 2017.

It is possible that your problem is related to the Japanese system you are on. If so, it is crucially important that you help the WiX creators resolve the problems reliably for all users.

A: If you have another system (or virtual machine) on which you can test this, then do so. Using the WiX source, this issue is not reproducible on my Windows 10 x64 English system. Also ICE validation reports no errors.
If it works on another system then your test system is most likely damaged in some way, and the most likely cause is that the Shell Folders entries are incorrect or damaged somewhere. The only directory this really being used is the 32-bit ProgramFilesFolder, so that's perhaps broken somewhere. I've seen this problem before where the values of the standard directory locations are broken in some way, and when Windows Installer evaluates them they become empty, hence the 2343 error.


text:
Q: Solr - multifaceting syntax I'm having a hard time constructing the URL for a query that has more than one multifacet. I'm following the sample here:
http://www.craftyfella.com/2010/01/faceting-and-multifaceting-syntax-in.html
For instance, take a look at the eBay screendump, how would the URL look like if you select 'Sony' and 'LG' in the 'Brand' section and then select 'LCD' in the 'Type' section?
Assume BRAND and TYPE are defined in schema.xml.
This URL would work if you select 'Sony' and 'LG' in the 'Brand' section:
...&facet=on&facet.field={!ex=BRAND}BRAND&fq={!tag=BRAND}BRAND:Sony%20OR%20LG

But what if you need to have selections from both 'Brand' and 'Type'? I tried this but it does not give me what I want:
...&facet=on&facet.field={!ex=BRAND}BRAND&fq={!tag=BRAND}BRAND:Sony%20OR%20LG&facet.field={!ex=TYPE}TYPE&fq={!tag=TYPE}TYPE:LCD

Any help is appreciated.

A: When you specify fq twice, only documents matching both filters will be kept. It is like having one fq with AND for the conditions. Maybe it is not what you want. If you want to keep documents having one or the other filter, you will have to use only one fq and combined the condition with OR.
UPDATE
After re-thinking, it makes probably more sense to have an AND between the BRAND and the TYPE filters.
Also, do not forget to specify again in which field you apply the second condition of the Brand fq:
fq=BRAND:Sony+OR+BRAND:LG

Finally, you can specify the same exclusion for both facet.field, given:
...&facet=on&facet.field={!ex=bt}BRAND&facet.field={!ex=bt}TYPE&fq={!tag=bt}BRAND:Sony+OR+BRAND:LG+OR+TYPE:LCD


text:
Q: Different ExpressJS Error for API vs Page Request? What is the best way to detect if a request is for an API call versus a page request?  I'd like to render a view for page requests and send JSON for API requests.  For example:
Common error for page requests:
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('500', {
            message: err.message,
            error: err
        });
    });
}

Common error for API requests:
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.send({
            message: err.message,
            error: err
        });
    });
}

Thinking about using this but wanted other opinions:
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        if (req.url.startsWith('/api')){
            res.send({
                msg: err.message,
                err: err
            });
        } else {
            res.render('500', {
                message: err.message,
                error: err
            });
        }
    });
}

A: There is not fundamental difference between API calls and page requests except their headers. It could also depend on how you architecture your app/routes.
I would suggest the following:
Solution one:
Use a unique middleware that checks the content-type of the request headers:
app.use(function(err, req, res, next) {
    if (req.get('Content-Type') === 'application/json') {
        // API Stuff
    } else {
        // Page Stuff
    }
});

NB: I assumed here that your API was of the JSON kind.
Solution two:

*

*Create a router on which you map all your APIs.

*Mount this router and your special API middleware on a common route like

Ex:
app.use('/api', apiRouter, apiMiddleware)


text:
Q: Mapping data from array in child component and parent component I have data stored in data.js file in array. I am showing that data in Child component (only the first object in array). I want to map through same array in parent component (by rendering <ChildComponent>). How can I do that?
data.js
export default {
  accordionItems: [
    {
      id: 1,
      title: 'Why is my car not green?',
      answer: 'We ran out of green color',
    },
    {
      id: 2,
      title: 'Where have all the drivers gone?',
      answer: 'It\'s lunch time',
    },
    {
      id: 3,
      title: 'Do you have a book of complains',
      answer: 'You can write at info@mail.eu',
    },
  ],
};

child component
import Data from './data';

class AccordionItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      question: Data.accordionItems[0], //if I remove [0], no data is rendered
    };
  }

 return (

{question.title}

        <button>toggle</button>

{question.answer}

 );

Parent Component
import AccordionItem from './AccordionItem';
import Data from './data';

class Accordion extends Component {
  constructor(props) {
    super(props);
    this.state = {
      accordionItems: Data.accordionItems,
    };
  }
render() {
    const { accordionItems } = this.state;
    return accordionItems.map(accordionItem => (
      <AccordionItem key={accordionItem.id} />

I want to get all 3 objects from 'data' array in Parent component, now I am getting 3 same components with just first object.

A: Pass the item down as props:
 <AccordionItem question={accordionItem} ... />

The  you can access it in the render() method:
render() {
 const { question } = this.props;

 return (

{question.title}

       <button>toggle</button>

{question.answer}

 );
}

You shouldn't use the state at all (yet).

A: You can simply pass data from map function itself like:
accordionItems.map(accordionItem => (
      <AccordionItem
        key={accordionItem.id}
        open={[`isOpen-${accordionItems.id}`]}
        data={accordionItem}
      />
));

And in the Child:
class AccordionItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      question: props.data, //data from map function in parent
    };
  }

A: Maybe you should read a bit more about components and passing props in React.
What you could do to make this work is instead of importing Data in your AccordionItem component, you pass it down to the AccordionItem via props.
This would look something like this:
import AccordionItem from './AccordionItem';
import Data from './data';

class Accordion extends Component {
  constructor(props) {
    super(props);
    this.state = {
      accordionItems: Data.accordionItems,
    };
  }

  render() {
    const { accordionItems } = this.state;
    return accordionItems.map(accordionItem => (
        <AccordionItem
          key={accordionItem.id}
          item={accordionItem}
          open={[`isOpen-${accordionItems.id}`]}
        />
    ))
  }

Now the item should become accessible via props in the child component:
 class AccordionItem extends Component {

   render(){
     const { question } = this.props
     return (

{question.title}

           <button>toggle</button>

{question.answer}

     );
   }


text:
Q: Open Graph Beta: Aggregation's "Group By" Field The documentation for the Open Graph beta says:

Group by - Option is only available if your Aggregation is displaying
  Objects. This option allows the aggregation to group by a property of
  the object. For example, you can group by Movie object's type, to show
  how many times you've watched a certain type of movie.

How do you select this?
I have Egg objects with that have a Collection property and want to aggregate based on that.
For example, one aggregate story would include Egg objects with Collection set to "Easter" and another would include Egg objects with Collection set to "Christmas".
Group By always seems to default select the object type I choose for Data to Display and I don't see an option to manually set this. Nor do I see a way to set the Aggregation Title to be the name of the group.

A: You can't group by a String, only an Object. Try making an Object Type called Collection and make urls for each collection. Then Collection will show up in Data to Display and you can group by it.


text:
Q: I cannot access to user points pages: myuserpoints/ID I'm using the "User Points" module in Drupal to assign points to the users given the rating on some of their nodes.
I visited the menu: admin/user/userpoints from which I can see users scores.
However when I click on one of them, I get "Access Denied" (and I'm the admin id=1).
For example, this link is forbidden for me:
myuserpoints/6

I can only visit my own:
myuserpoints/1

But if the module does provide a list with all user points, I guess i'm supposed to see them.. or not ?
thanks

A: Check out this issue, it seems there is a patch for the problem. Try if that fixes it for you.
User 1 should never see an access denied message, that is definitely a bug.


text:
Q: ufw delete allow 'Nginx HTTP': Could not delete non-existent rule, but it does exist I have successfully set up nginx using these instructions, but one part has never worked for me, and that bothers me even though it does not seem to cause an problems.
root@devtest:/home/dev-admin# ufw app list
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH
root@devtest:/home/dev-admin# sudo ufw delete allow 'Nginx HTTP'
Could not delete non-existent rule
Could not delete non-existent rule (v6)
root@devtest:/home/dev-admin# ufw app list
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH

What am I missing here?
Is this not the correct syntax to delete the rule?
This is on Ubuntu 20.04, but I get the same result on 18.04.

A: From man ufw, the command ufw app list

list[s] the names of application profiles known to ufw

(these are all the profiles stored in the /etc/ufw/applications.d/ directory). The output does not imply that rules for those profiles have been added to the running firewall - to see that information, use
ufw status verbose


text:
Q: Pull Image from Gitlab Registry in Docker Compose File I want to deploy a docker stack on my own server. I've written a .gitlab-ci.yml file that currently builds the images in my stack and pushes them to my gitlab registry:
build:
  stage: build
  image: docker:stable
  services:
    - docker:dind
  before_script:
    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
    - docker info
  script:
    - docker build -t $DOCKER_IMAGE1_TAG -f dir1/Dockerfile ./dir1
    - docker push $DOCKER_IMAGE1_TAG
    - docker build -t $DOCKER_IMAGE2_TAG -f dir2/Dockerfile ./dir2
    - docker push $DOCKER_IMAGE2_TAG

I'm struggling for a way to run the docker deploy command on my own server with the docker-compose.yml file I've written, that successfully pulls the images from my gitlab registry. I figure I could use sshpass to ssh into my server and then copy the docker-compose.yml file across and run docker deploy from there, but I'm not sure what's the best way to allow my server to access the images now located in my gitlab registry:
# Need to ssh into the server, transfer over docker-stack file and run docker swarm deploy
deploy:
  stage: deploy
  environment:
    name: production
  image: trion/ng-cli-karma
  before_script:
    - apt-get update -qq && apt-get install -y -qq sshpass
    - eval $(ssh-agent -s)

This is a section of my docker-compse file:
version: "3.2"
services:
  octeditor:
    image: image # how to set this to the image in my container registry?
    ports:
      - "3000:3000"
    networks:
      - front-tier
    deploy:
      replicas: 1
      update_config:
        parallelism: 1
      failure_action: rollback
      placement:
        constraints:
          - 'node.role == manager'
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
        window: 120s

How can I pull the images from my gitlab registry? Is this the preferred way of creating a docker deployment on a remote server, via gitlab ci?

A: I equally had this difficulty recently, finally I found out that the solution is just to insert the link to the image in the private registry as is the case for me with gitlab.
version: "3.2"
services:
  octeditor:
    image: registry.gitlab.com/project-or-group/project-name/image-name:tag
    ports:
      - "3000:3000"
    networks:
      - front-tier


text:
Q: How can I automatically generate minified css from scss? I'm making edits to a project that uses scss. As I work locally the changes I make to the scss are reflected on my local server. However, there are minified css files that are part of the project and I feel like I should update those as well. Is there something I should be doing to generate those minified files as I go, or maybe an additional step I should take to regenerate those minified files?

A: An automated task runner would be perfect for this, here's an example in Gulp.
$ npm install -g gulp && npm install gulp gulp-sass

In the root directory of your project, add a file named gulpfile.js, and place the following code into the file:
var sass = require('gulp-sass');

// Compile all the .scss files from
// ./scss to ./css
gulp.task('scss', function () {
  gulp.src('./scss/**/*.scss')
    .pipe(sass())
    .pipe(gulp.dest('./css'));
});

// Watches for file changes
gulp.task('watch', function(){
  gulp.watch('./scss/**/*.scss', ['scss']);
});

gulp.task('develop', ['scss', 'watch']);

In the terminal, run:
$ gulp develop

and try to make changes to your scss files. They are now automatically compiled on every save!


text:
Q: Install pep 518 build system requirements only (to build sdist) PEP 518 introduced the pyproject.toml file, as well as a section describing the tools needed to build:
[build-system]
requires = ["setuptools", "wheel", "numpy>=1.13"]

Here, I'm telling the build system (implicitly setuptools) that I need these three requirements installed before I can run the build.  (And yes, I actually do need numpy as part of the build process.)
When I run pip wheel, it knows to look for this section in this file, install the requirements, and then build the wheel.  But pip has no way to create an sdist distribution (and its maintainers seem reluctant to add one), so I need to run python setup.py sdist.  And that's where the problem comes in: setup.py doesn't know it needs numpy, and the build fails.
Is there a standard way to just install the requirements, and then build an sdist?  In particular, pip has moved toward build isolation, so can this be done with isolation?  Failing that, I could create my own environment for some isolation; then, what's the best way to install the requirements in some environment?

A: One way is with the pypa project pep517 (though the module is marked "experimental")
here's a sample dist with a special dependency that I tried:
# setup.py
from setuptools import setup
import astpretty
setup(name='wat', version='1')

# pyproject.toml
[build-system]
requires = ["setuptools", "wheel", "astpretty"]
build-backend = "setuptools.build_meta"

$ python -m pep517.build --source .
WARNING: You are using pip version 20.2.1; however, version 20.2.2 is available.
You should consider upgrading via the '/tmp/x/venv/bin/python -m pip install --upgrade pip' command.
running egg_info
creating wat.egg-info
writing wat.egg-info/PKG-INFO
writing dependency_links to wat.egg-info/dependency_links.txt
writing top-level names to wat.egg-info/top_level.txt
writing manifest file 'wat.egg-info/SOURCES.txt'
reading manifest file 'wat.egg-info/SOURCES.txt'
writing manifest file 'wat.egg-info/SOURCES.txt'
running sdist
running egg_info
writing wat.egg-info/PKG-INFO
writing dependency_links to wat.egg-info/dependency_links.txt
writing top-level names to wat.egg-info/top_level.txt
reading manifest file 'wat.egg-info/SOURCES.txt'
writing manifest file 'wat.egg-info/SOURCES.txt'
warning: sdist: standard file not found: should have one of README, README.rst, README.txt, README.md

running check
warning: check: missing required meta-data: url

warning: check: missing meta-data: either (author and author_email) or (maintainer and maintainer_email) must be supplied

creating wat-1
creating wat-1/wat.egg-info
copying files to wat-1...
copying pyproject.toml -> wat-1
copying setup.py -> wat-1
copying wat.egg-info/PKG-INFO -> wat-1/wat.egg-info
copying wat.egg-info/SOURCES.txt -> wat-1/wat.egg-info
copying wat.egg-info/dependency_links.txt -> wat-1/wat.egg-info
copying wat.egg-info/top_level.txt -> wat-1/wat.egg-info
Writing wat-1/setup.cfg
Creating tar archive
removing 'wat-1' (and everything under it)
$ ls dist/
wat-1.tar.gz


text:
Q: xna zoom using mouse scroll wheel How do i zoom using the mouse scroll wheel, i got try this
        if (currentMouseState.ScrollWheelValue < originalMouseState.ScrollWheelValue)
        {
            cameraPosition += new Vector3(0, -1, 0);
            UpdateViewMatrix();
            currentMouseState.ScrollWheelValue.Equals(0);
        }
        if (currentMouseState.ScrollWheelValue > originalMouseState.ScrollWheelValue)
        {
            cameraPosition += new Vector3(0, 1, 0);
            UpdateViewMatrix();
            currentMouseState.ScrollWheelValue.Equals(0);
        }

But i keep zooming in even if i scroll once and i am kinda new to XNA. Please help.

A: ScrollWheelValue gets the cumulative mouse scroll wheel value since the game was started, so every time you get it you need to copy that value in a variable, in order to compare it the next cycle.
Moreover, you can't set ScrollWheelValue, and this line is wrong:
currentMouseState.ScrollWheelValue.Equals(0);

I think your idea was to set its value as 0, but that instruction compares its value with 0 and gives you a boolean.
EDIT:
You should do something like this:
Declare a global variable
private int previousScrollValue;
And set it in the Initialize method as:
previousScrollValue = originalMouseState.ScrollWheelValue;
Then edit your code as this:
if (currentMouseState.ScrollWheelValue < previousScrollValue)
{
    cameraPosition += new Vector3(0, -1, 0);
    UpdateViewMatrix();
}
else if (currentMouseState.ScrollWheelValue > previousScrollValue)
{
    cameraPosition += new Vector3(0, 1, 0);
    UpdateViewMatrix();
}
previousScrollValue = currentMouseState.ScrollWheelValue;

It should work.


text:
Q: ios11 toolbar last icon is spaced out I have upgrade my ios app to ios11 and xcode 9. When running the app in the xcode 9 ios 11 simulator i get my toolbar last icon spaced out like this.
Any idea how to fix this?

A: I Solved it by adding flexiblespace uibarbuttonitem at the end.
Thanks


text:
Q: In SystemVerilog, Is Virtual Class same as Abstract Class? Please help me to understand the need of Virtual Class in SystemVerilog.

*

*For an abstract class, we can use Interface in SystemVerilog.  What are differences between these two?

A: Yes, an abstract class in SystemVerilog is the same as a virtual class. Java uses the keyword 'abstract', but other languages like C++ do not have a specific keyword. SystemVerilog re-used the keyword virtual so as not to reserve another keyword. An abstract class is simply one where the constructor is protected and you cannot construct it directly, you must extend the class first and you can construct a derived object.
Abstract classes allow another concept with is a pure virtual method. These are methods that must be overridden in in the extended class. Base class libraries like the UVM are full of abstract classes and have methods that you must override, like a copy or print method.
An abstract class that only contains pure virtual methods is called an interface class and you can define an interface class that implements multiple interface classes. This years DVCon had many papers on this topic.


text:
Q: Values not inserted in SQL Server database I have a really interesting case: in two views during my shopping process I have a partial view for displaying the total price of the order and delivery prices.
This partial view is rendered by the ShowCartDiscountsPrices action. At the end I have to insert using Entity Framework in the database MinDeliveryPrice, MinDeliveryPriceDDS, DeliveryPrice, DeliveryPriceDDS.
The strange problem is that in two cases last week in my SQL Server database, I have value only for DeliveryPrice AND SOMEHOW THE OTHER THREE COLUMNS ARE null in my SQL Server database.
And when I look at the problem and make an order with the same articles for example an hour after that everything is fine and the four columns are populated and during this period of time nobody has made any changes in the database.
I am wondering what can be the problem can I write some script for logging to see if some kind of mistakes occurs either in SQL Server or IIS maybe?
public ActionResult ShowCartDiscountsPrices(OrderDiscountPriceModel model, bool? ischange, int? deliverypreference)
{
    var cart = ShoppingCart.GetCart(WebsiteContext.CurrentUser != null ? (int?)WebsiteContext.CurrentUser.UserID : null);

    decimal mindeliveryprice = 0;
    decimal mindeliverypricedds = 0;

    if (deliverypreference != null || Session["DeliveryPreference"] != null)
    {
        var parsedelprice = deliverypreference.HasValue ? deliverypreference.Value == 1 ? Decimal.TryParse(Settings.GetSettingByName("Eshop_SpeedyMinDeliveryPrice"), out mindeliveryprice) :Decimal.TryParse(Settings.GetSettingByName("Eshop_HomeMinDeliveryPrice"), out mindeliveryprice) : Decimal.TryParse(Session["MinDeliveryPrice"].ToString(), out mindeliveryprice );

        var parsedelpricedds = deliverypreference.HasValue ? deliverypreference.Value == 1 ? Decimal.TryParse(Settings.GetSettingByName("Eshop_SpeedyMinDeliveryPriceDDS"), out mindeliverypricedds) : Decimal.TryParse(Settings.GetSettingByName("Eshop_HomeMinDeliveryPriceDDS"), out mindeliverypricedds) : Decimal.TryParse(Session["MinDeliveryPriceDDS"].ToString(), out mindeliverypricedds );

        decimal deliveryprice;
        decimal deliverypricedds;

        ShoppingCartHelper.CalculateArticlesDeliveryPrice(mindeliveryprice, mindeliverypricedds, cart.ComputeTotalTransport(), cart.ComputeTotalTransportDDS(), out deliveryprice, out deliverypricedds);

        model.DeliveryPrice = deliveryprice;
        model.DeliveryPriceDDS = deliverypricedds;
        model.DeliveryPreference = deliverypreference.HasValue ? deliverypreference.Value : (int)Session["DeliveryPreference"];
        model.MinDeliveryPrice = mindeliveryprice;
        model.MinDeliveryPriceDDS = mindeliverypricedds;
        model.FinalSum += deliverypricedds;
    }
    else
    {
        if (isFromLastStep != null && bool.Parse(isFromLastStep.ToString()) == true)
            ViewBag.IncludeDelivery = true;
    }

    if (deliverypreference != null)
    {
            Session["DeliveryPreference"] = deliverypreference;
            Session["MinDeliveryPrice"] = mindeliveryprice;
            Session["MinDeliveryPriceDDS"] = mindeliverypricedds;
    }

    ViewData.TemplateInfo.HtmlFieldPrefix = "OrderDiscoutPrice";
    return PartialView("_CartDiscountsPrices", model);
}

And here are my helper functions that only iterate through a collection with articles and calculate the Total Delivery Prices.
 public decimal ComputeTotalTransport()
        {
            decimal totalarticletransport = 0;
            decimal articletransport;
            foreach (var article in lineCollection)
            {
                if (decimal.TryParse(article.Article.Transport.ToString(), out articletransport))
                {
                    totalarticletransport += article.Article.Quantity * articletransport;
                    articletransport = 0;
                }
            }
            return totalarticletransport;
        }
public decimal ComputeTotalTransportDDS()
        {
            decimal totaltransportdds = 0;
            decimal articletransportdds;
            foreach (var article in lineCollection)
            {
                if (decimal.TryParse(article.Article.TransportDDS.ToString(), out articletransportdds))
                {
                    totaltransportdds += article.Article.Quantity * articletransportdds;
                    articletransportdds = 0;
                }
            }
            return totaltransportdds;
        }

A: I want to suggest you to extend your if expression one step further as shown below to check whether the session value is greater than 0 as shown below.
if (Convert.ToString(deliverypreference) != "" && Convert.ToString(Session["DeliveryPreference"]) != "" && Convert.ToDecimal(deliverypreference) > 0 && Convert.ToDecimal(Session["DeliveryPreference"]) > 0)
{
    //Your insert logic as you have written.
}

As you might be aware sometime when your session variable might not be blank or null string but the value in session is equal to the 0. In that case your code will execute but the data will not inserted properly.
The second workaround I want to suggest you to disable allow null value in SQL Server column by modifying table in design mode.

A: Hello I promise I will add code to my answer but actually the problem turned out to be restarting of IIS server.


text:
Q: Rearranging RGB values to GRB, GBR, BRG, BGR, and RBG through an entire directory I have a directory of images for a CNN. I would like to be able to rearrange each band in a different order to help better train my model to allow it to recognize my objects. I so far have some code working with cv2. It is separating the bands, but I am having trouble rearranging the bands.
import cv2
import numpy

img = cv2.imread("IMG_4540.jpg")
g,b,r = cv2.split(img)
cv2.imwrite('green_channel.jpg', g)

I would like to have 6 separate images all with different band combinations from one singular image if possible.

A: You can just form all reorderings with numpy's indexing capabilities.
import numpy as np
from itertools import permutations
# first generate all sets of rearrangements you'd like to make..
orderings = [p for p in permutations(np.arange(3)) if p!=(0,1,2)]
# [(0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
# rbg, brg, and so on.

# then reorder along axis=-1 using these. (0,1,2) --> (0,2,1) and so on.
for order in orderings:
    reordered = im[...,order]
    # then save each an appropriate filename
    cv2.imsave('filename.jpg', reordered)
del reordered, order


text:
Q: Can use aggregate functions with join?
*

*table projects : pid(pk), name ...

*table categories : pid(pk), project(project's pid), parent(other category's pid) ...

*table counts : project(project's pid), category(category's pid), count ...

I used this query before
SELECT
categories.*, projects.pid, projects.name, parent_category.*
FROM categories
INNER JOIN projects ON projects.pid = categories.project
LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent

and it worked well
This time we need SUM, COUNT data. So i added "counts" table and made this query.
SELECT
categories.*, projects.pid, projects.name, SUM(counts.count), COUNT(counts.count),
parent_category.*, SUM(parent_category_count.count), COUNT(parent_category_count.count)
FROM categories
INNER JOIN projects ON projects.pid = categories.project
LEFT JOIN counts ON counts.category = categories.pid
LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent
LEFT JOIN counts AS parent_category_count ON parent_category_count.category = categories.pid

Then I get

ERROR:  aggregate function calls cannot be nested

What can I do? Does this query basically make sense? Or should I split it?

A: You should add  a proper GROUP BY clause  (in your case should be categories.pid  )
    SELECT
    categories.*
    , projects.pid
    , projects.name
    , SUM(counts.count)
    , COUNT(counts.count)
    , parent_category.*
    , SUM(parent_category_count.count)
    , COUNT(parent_category_count.count)
    FROM categories
    INNER JOIN projects ON projects.pid = categories.project
    LEFT JOIN counts ON counts.category = categories.pid
    LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent
    LEFT JOIN counts AS parent_category_count ON parent_category_count.category = categories.pid
    GROUP BY categories.pid

or as in your comment
    SELECT
    categories.*
    , projects.pid
    , projects.name
    , SUM(counts.count)
    , COUNT(counts.count)
    , parent_category.*
    , SUM(parent_category_count.count)
    , COUNT(parent_category_count.count)
    FROM categories
    INNER JOIN projects ON projects.pid = categories.project
    LEFT JOIN counts ON counts.category = categories.pid
    LEFT JOIN categories AS parent_category ON parent_category.pid = categories.parent
    LEFT JOIN counts AS parent_category_count ON parent_category_count.category = categories.pid
    GROUP BY categories.pid, projects.pid, parent_category.pid


text:
Q: C# determine if one of child elements has specific value in XElement Please consider this XML:
<MyRoot>
    <c1>0</c1>
    <c2>0</c2>
    <c3>0</c3>
    <c4>0</c4>
    <c5>1</c5>
    <c6>0</c6>
    <c7>0</c7>
    <c8>0</c8>
</MyRoot>

How can I write a lambda expression to find if one of child of MyRoot has 1 for it's value?
Thanks

A: This is pretty trivial using XDocument class and some linq which would be :
string xml=@"<MyRoot>
    <c1>0</c1>
    <c2>0</c2>
    <c3>0</c3>
    <c4>0</c4>
    <c5>1</c5>
    <c6>0</c6>
    <c7>0</c7>
    <c8>0</c8>
</MyRoot>";

     XDocument Doc = XDocument.Parse(xml);
     var nodes = from response in Doc.Descendants()
                 where response.Value == "1"
                 select new {Name = response.Name, Value = response.Value };

    foreach(var node in nodes)
          Console.WriteLine(node.Name + ":  " + node.Value);

See the working DEMO Fiddle as example
with lambda:
var nodes = Doc.Descendants().Where(x=> x.Value == "1")
                           .Select(x=> {Name = x.Name, Value = x.Value });

Now you can iterate it:
foreach(var node in nodes)
      Console.WriteLine(node.Name + ":  " + node.Value);

A: string x = @"<MyRoot>
                <c1>0</c1>
                <c2>0</c2>
                <c3>0</c3>
                <c4>0</c4>
                <c5>1</c5>
                <c6>0</c6>
                <c7>0</c7>
                <c8>0</c8>
            </MyRoot>";
XElement xml = XElement.Parse(x);
bool has_one = xml.Elements().Any(z => z.Value == "1");

A: For VB'ers wanting an answer
    Dim xe As XElement
    'xe = XElement.Load("URI here")

    'for testing use literals
    xe = <MyRoot>
             <c1>0</c1>
             <c2>0</c2>
             <c3>0</c3>
             <c4>0</c4>
             <c5>1</c5>
             <c6>0</c6>
             <c7>0</c7>
             <c8>0</c8>
         </MyRoot>

    'any child = 1
    Dim ie As IEnumerable(Of XElement) = From el In xe.Elements Where el.Value = "1" Select el

    'check c4 for 1
    ie = From el In xe.<c4> Where el.Value = "1" Select el
    'or
    If xe.<c4>.Value = "1" Then
        '
    End If


text:
Q: How can I show a UIDatePicker inside a Popover on iPad using StoryBoard? I have achieved to show the datepicker inside the popover, doing it programmatically as it is shown in UIDatePicker in UIPopover.
But I have been trying to do it in interface Builder, I already made a View Controller named DatePickerViewController.m with a DatePicker in it and its corresponding IBoulet
#import <UIKit/UIKit.h>

@interface DatePickerViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIDatePicker *birthdayDatePicker;

@end

Then I need this to be shown in a popover when the Birthday text field is being edited. so I use the following code
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    //Assign DatePicker to Birthday TextField
    //build our custom popover view
    DatePickerViewController* popoverContent = [[DatePickerViewController alloc] init];
    //resize the popover view shown
    //in the current view to the view's size
    popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 216);

    // dismiss existing popover
    if (self.popoverControllerBirthday)
    {
        [self.popoverControllerBirthday dismissPopoverAnimated:NO];
        self.popoverControllerBirthday = nil;
    }

    //create a popover controller with my DatePickerViewController in it
    UIPopoverController *popoverControllerForDate = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
    //Set the delegate to self to receive the data of the Datepicker in the popover
    popoverControllerForDate.delegate = self;
    //Adjust the popover Frame to appear where I want
    CGRect myFrame =textField.frame;
    myFrame.origin.x = 260;
    myFrame.origin.y = 320;

    //Present the popover
    [popoverControllerForDate presentPopoverFromRect:myFrame
                                          inView:self.view
                        permittedArrowDirections:UIPopoverArrowDirectionDown
                                        animated:YES];
    self.popoverControllerBirthday = popoverControllerForDate;
    return NO; // tells the textfield not to start its own editing process (ie show the keyboard)

}

And I also import the custom DatePickerViewController in my current ViewController
#import "DatePickerViewController.h"

But it is not showing the datepicker inside the popover.

Does anybody know what could be happening?

A: Solved
All I have to do is instantiate the StoryBoard Date Picker View Controller like :
...
DatePickerViewController* popoverContent = [[DatePickerViewController alloc] init];

popoverContent =[[UIStoryboard storyboardWithName:@"MainStoryboard"
                                         bundle:nil]
               instantiateViewControllerWithIdentifier:@"DatePickerVC"];
//resize the popover view shown
//in the current view to the view's size
popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 216);
...

where the identifier is set in StoryBoard Attributes Inspector

and now it is shown

A: You might want to avoid all the work in the storyboard by creating the ViewController and the DatePicker programmatically:
//build our custom popover view
UIView *v = [[UIView alloc] init];
CGRect pickerFrame = CGRectMake(0, 0, 320, 216);
UIDatePicker *pView=[[UIDatePicker alloc] initWithFrame:pickerFrame];
pView.datePickerMode = UIDatePickerModeDate;

self.datePicker = pView;
[v addSubview:self.datePicker];

UIViewController *popoverContent = [[UIViewController alloc]init];
popoverContent.view = v;

//resize the popover view shown
//in the current view to the view's size
popoverContent.contentSizeForViewInPopover = CGSizeMake(320, 216);

// dismiss existing popover
if (self.pcDatePicker)
{
    [self.pcDatePicker dismissPopoverAnimated:NO];
    self.pcDatePicker = nil;
}

//create a popover controller with my DatePickerViewController in it
UIPopoverController *popoverControllerForDate = [[UIPopoverController alloc] initWithContentViewController:popoverContent];

//Set the delegate to self to receive the data of the Datepicker in the popover
popoverControllerForDate.delegate = self;

//Adjust the popover Frame to appear where I want
CGRect myFrame = sender.frame;//CGRectMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, 320,     200);
myFrame.origin.x = 260;
myFrame.origin.y = 320;

//Present the popover
[popoverControllerForDate presentPopoverFromRect:myFrame
                                          inView:self.view
                        permittedArrowDirections:UIPopoverArrowDirectionAny
                                        animated:YES];

self.pcDatePicker = popoverControllerForDate;

And then use the delegate Method to get the date:
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    self.startDate = self.datePicker.date;
}


text:
Q: Using Cookies across Activities when using HttpClient I'm trying a simple app to read in the HTML of a website, and tranform it to create an easily readable UI in Android (This is an exersize in learning android, not to make a useable app). The problem I'm having is persisting a users session across Activities and then using the session in a HttpClient once recalled.
I would like to do this "Correctly", the recommended approach seem to be to use CookieManager. I've had problems with this however - I cannot seem to find the "Correct" way to take a Cookie from the CookieManager and use it in a later instantiation of HttpClient in a seperate Activities.
When using a CookieManager I can save the Cookie and the Cookie is then in scope in other Activities (See code snippet 2). I haven't found how to use this later (See code snippet 3) when requesting a page.
Enough talking, here is some code. First my login action and Cookie storage:
private OnClickListener loginActionListener = new OnClickListener()
{
    public void onClick(View v)
    {
        EditText usernameTextView = (EditText) findViewById(R.id.Username);
        EditText passwordTextView = (EditText) findViewById(R.id.Password);
        String username = usernameTextView.getText().toString();
        String password = passwordTextView.getText().toString();

        try {
            HttpPost postMethod = new HttpPost(URI);
            HttpParams params   = new BasicHttpParams();

            params.setParameter("mode", "login");
            params.setParameter("autologin", true);
            params.setParameter("username", username);
            params.setParameter("password", password);
            postMethod.setParams(params);

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpResponse response        = httpClient.execute(postMethod);
            List<Cookie> cookies = httpClient.getCookieStore().getCookies();

            if(cookies != null)
            {
                for(Cookie cookie : cookies)
                {
                    String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();
                    CookieManager.getInstance().setCookie(cookie.getDomain(), cookieString);
                }
            }
            CookieSyncManager.getInstance().sync();

            Intent intent = new Intent(v.getContext(), IndexAction.class);
            startActivity(intent);
    } catch (Exception e) {...}
}

The startup Activity which decides wether to make the user login or go to the index is below. You can see from this code that the cookie is in scope and can be read:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    CookieSyncManager.createInstance(this);

    if(CookieManager.getInstance().getCookie(URI) == null)
    {
        Intent intent = new Intent(this, LoginAction.class);
        startActivity(intent);
    }
    else
    {
        Intent intent = new Intent(this, IndexAction.class);
        startActivity(intent);
    }
}

But from my code to read the Index page I'm hoping you can suggest what i'm missing:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    CookieSyncManager.createInstance(this);

    try
    {
            HttpGet getMethod = new HttpGet(URI_INDEX);

            HttpParams params   = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, 30000);
            HttpConnectionParams.setSoTimeout(params, 30000);

            // This code results in a ClassCastException, I'm assuming i've found a red herring with this solution.
            // HttpContext localContext = new BasicHttpContext();
            // localContext.setAttribute(ClientContext.COOKIE_STORE, CookieManager.getInstance().getCookie(URI));

            DefaultHttpClient httpClient = new DefaultHttpClient(params);
            HttpResponse response        = httpClient.execute(getMethod);

            if(response.getStatusLine().getStatusCode() > 299 && response.getStatusLine().getStatusCode() < 400)
            {
                // Not logged in doesn't give a redirect response. Very annoying.
            }

            final char[] buffer = new char[0x10000];
            StringBuilder out = new StringBuilder();
            Reader in = new InputStreamReader(response.getEntity().getContent(), "UTF-8");
            int read = 0;
            while (read>=0)
            {
              read = in.read(buffer, 0, buffer.length);
              if (read>0) {
                out.append(buffer, 0, read);
              }
            }

            String returnString = out.toString();
    } catch (ClientProtocolException e) {...}
}

The HttpClient on execute(getMethod) isn't using the Cookie (double checked this in debug) to pull back the page. It would be great if someone could fill this hole in my knowledge.
Thanks in advance.
EDIT
When commented code is added back in (with the httpClient.execute(getMethod) method change to httpClient.execute(getMethod, localContext)) this strack trace is produced - Assumedly because i'm filling the attribute ClientContext.COOKIE_STORE with a Cookie String rather than a CookieStore:
*org.apache.http.client.protocol.RequestAddCookies.process(RequestAddCookies.java:88), org.apache.http.protocol.BasicHttpProcessor.process(BasicHttpProcessor.java:290), org.apache.http.protocol.HttpRequestExecutor.preProcess(HttpRequestExecutor.java:160), org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:401)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555), org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487),
com.testapp.site.name.IndexAction.onCreate(IndexAction.java:47),
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047),
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611),
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663),
android.app.ActivityThread.access$1500(ActivityThread.java:117),
android.app.ActivityThread$H.handleMessage(ActivityThread.java:931),
android.os.Handler.dispatchMessage(Handler.java:99),
android.os.Looper.loop(Looper.java:123),
android.app.ActivityThread.main(ActivityThread.java:3683),
java.lang.reflect.Method.invokeNative(Native Method),
java.lang.reflect.Method.invoke(Method.java:507),
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839),
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597),
dalvik.system.NativeStart.main(Native Method)*

A: In my application server wants to use same session with same cookies...
After few hours of "googling" and painful headache I just saved cookies to SharedPreference or just put in some object and set DefaultHttpClient with same cookies again ... onDestroy just remove SharedPreferences ... that's all:

*

*First copy SerializableCookie class to your package:
SerializableCookie
Look the following example:
public class NodeServerTask extends AsyncTask<Void, Void, String> {
private DefaultHttpClient client;

protected String doInBackground(Void... params) {
  HttpPost httpPost = new HttpPost(url);
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(nameValuePair);
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
        List<Cookie> cookies = loadSharedPreferencesCookie();
        if (cookies!=null){
            CookieStore cookieStore = new BasicCookieStore();
            for (int i=0; i<cookies.size(); i++)
                cookieStore.addCookie(cookies.get(i));
            client.setCookieStore(cookieStore);
        }
        HttpResponse response = client.execute(httpPost);
        cookies = client.getCookieStore().getCookies();

        saveSharedPreferencesCookies(cookies);

// two methods to save and load cookies ...
 private void saveSharedPreferencesCookies(List<Cookie> cookies) {
    SerializableCookie[] serializableCookies = new SerializableCookie[cookies.size()];
    for (int i=0;i<cookies.size();i++){
        SerializableCookie serializableCookie = new SerializableCookie(cookies.get(i));
        serializableCookies[i] = serializableCookie;
    }
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = preferences.edit();
    ObjectOutputStream objectOutput;
    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
    try {
        objectOutput = new ObjectOutputStream(arrayOutputStream);

        objectOutput.writeObject(serializableCookies);
        byte[] data = arrayOutputStream.toByteArray();
        objectOutput.close();
        arrayOutputStream.close();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT);
        b64.write(data);
        b64.close();
        out.close();

        editor.putString("cookies", new String(out.toByteArray()));
        editor.apply();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private List<Cookie> loadSharedPreferencesCookie() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    byte[] bytes = preferences.getString("cookies", "{}").getBytes();
    if (bytes.length == 0 || bytes.length==2)
        return null;
    ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
    Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT);
    ObjectInputStream in;
    List<Cookie> cookies = new ArrayList<Cookie>();
    SerializableCookie[] serializableCookies;
    try {
        in = new ObjectInputStream(base64InputStream);
        serializableCookies = (SerializableCookie[]) in.readObject();
        for (int i=0;i<serializableCookies.length; i++){
            Cookie cookie = serializableCookies[i].getCookie();
            cookies.add(cookie);
        }
        return cookies;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

Google Luck

A: CookieManager is used by the Java's internal HTTP client. It has nothing to do with Apache HttpClient.
In your code you always create for each request a new instance of HttpClient and therefore a new CookieStore instance, which obviously gets garbage collected along with all cookies stored in as soon as that HttpClient instance goes out of scope.
You should either
(1) Re-use the same instance of HttpClient for all logically related HTTP requests and share it between all logically related threads (which is the recommended way of using Apache HttpClient)
(2) or, at the very least, share the same instance of CookieStore between logically related threads
(3) or, if you insist on using CookieManager to store all your cookies, create a custom CookieStore implementation backed by CookieManager

A: (As promised a solution to this. I still don't like it and feel like I'm missing out on the "Correct" way of doing this but, it works.)
You can use the CookieManager to register your cookies (and therefore make these cookies available between apps) with the following code:
Saving cookies into the CookieManager:
List<Cookie> cookies = httpClient.getCookieStore().getCookies();

if(cookies != null)
{
    for(Cookie cookie : cookies)
    {
        String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();
        CookieManager.getInstance().setCookie(cookie.getDomain(), cookieString);
    }
}
CookieSyncManager.getInstance().sync();

Checking for cookies on specified domain:
if(CookieManager.getInstance().getCookie(URI_FOR_DOMAIN)
To reconstruct values for HttpClient:
DefaultHttpClient httpClient = new DefaultHttpClient(params);
String[] keyValueSets = CookieManager.getInstance().getCookie(URI_FOR_DOMAIN).split(";");
for(String cookie : keyValueSets)
{
    String[] keyValue = cookie.split("=");
    String key = keyValue[0];
    String value = "";
    if(keyValue.length>1) value = keyValue[1];
    httpClient.getCookieStore().addCookie(new BasicClientCookie(key, value));
}

A: I had the same problem. Since I am using Volley and not HTTPClient directly the Singleton for HTTPClient didn't seem like the correct solution. But using that same idea I simply saved the CookieManager in my application singleton.
So if app is my application singleton then in the onCreate() of each activity I add this:
    if (app.cookieManager == null) {
        app.cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
    }
    CookieHandler.setDefault(app.cookieManager);

To make this even better, all of my activities are subclasses of MyAppActivity so all I have to do is put it in the onCreate for MyAppActivity and then all of my activities inherit this functionality. Now all my activities are using the same cookie manager and my web service session is shared by all the activities. Simple and it works great.

A: I suppose one of best thing is apply Singleton Pattern to your HTTPClient so you just have only one instance!
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

public class myHttpClient {
    private static HttpClient mClient;
    private myHttpClient() {};
    public static HttpClient getInstance() {
        if(mClient==null)
            mClient = new DefaultHttpClient();
        return mClient;
    }
}

A: A good solution for the cookie storage would be to follow the ThreadLocal pattern in order to avoid storing cookies randomly.
This will help keeping a one and only CookieStore. For more explanation of this pattern, you can follow this useful link.
http://veerasundar.com/blog/2010/11/java-thread-local-how-to-use-and-code-sample/
Cheers


text:
Q: how to get list of all users with role equal None I use code below and it return 0 result
$args = array(
    'role'    => 'None',
    'orderby' => 'last_name',
    'order'   => 'ASC'
);
$users = get_users( $args );

and if I change role to '' or NULL it return all user
$args = array(
    'role'    => '',
    'orderby' => 'last_name',
    'order'   => 'ASC'
);
$users = get_users( $args );

A: In standard vanilla WordPress there is no role by the name of "none".
So you need to get it using pass '' NULL.
Thanks


text:
Q: Check if user exists to e-mail in bash I'm trying to create a script that prompts a user for a username to send an email to (on the same UNIX server) and checks to see if that username exists, and displays an error if it doesn't.
This is what I have so far:
#!/bin/bash
echo "Please enter the email address of the recipient and press <enter>: "
read recipient
echo "Please enter a subject for your message and press <enter>: "
read subject
mail -s "$subject" "$recipient"

I've been told I can use the grep command for this, and I know how to make grep display a list of usernames, but I don't know how to simply make the script check to see if the name is valid.
*EDIT:
Nevermind, I found something that worked:
echo "Please enter the email address of the recipient and press <enter>: "
read recipient
while [ -z "$(getent passwd $recipient)" ]
    do
        echo "invalid recipient"
        echo "Please enter the email address of the recipient and press <enter>: "
        read recipient
    done
        echo "Please enter a subject for your message and press <enter>: "
        read subject
        mail -s "$subject" "$recipient"
exit 0


text:
Q: rational number solutions to $\frac{a}{a^2+1} + \frac{b}{b^2+1} = \frac{c}{c^2+1}$ with $abc\ne 0$ This question concerns the equation
$$\frac{a}{a^2+1} + \frac{b}{b^2+1} = \frac{c}{c^2+1}$$
and the possibility of rational number solutions with $abc \ne 0$.
In comments arising from: Using Modularity Theorem and Ribet's Theorem to disprove existence of rational solutions
It is mentioned that this equation has an infinite number of such solutions.
How can we determine that there are an infinite number of such solutions?
And is there a way to generate these solutions (or at least find a few of them)?

A: Let $C$ be the curve defined by the equation
$$3(a^2 + 1)(b^2 + 1) = 10( a(b^2 + 1) + b(a^2 + 1)),$$
so rational points on $C$ correspond to solutions of your original equation with $c = 3$. Let $E$ be the elliptic curve with equation
$$y^2 = x^3 + x^2 + 65x + 3458.$$
The point is that $E$ and $C$ are "birationally equivalent" over the rational numbers $\mathbf{Q}$ -- there are maps given by ratios of polynomials with $\mathbf{Q}$-coefficients from $E$ to $C$ and back again, which are well-defined away from a finite set of bad points. (I won't write down the polynomials explicitly; I got the computer program Magma to compute them for me).
Now, elliptic curves over $\mathbf{Q}$ are very well-studied objects, and we can do (or, rather, ask Magma to do) a "descent" computation to find that $E$ has infinitely many rational points and enumerate the first few. Then we just feed them into the map from $E$ to $C$ to get rational points on $C$. This gives the following solutions:
$$ (a, b) = (-627/119, 160/123), (-1287933/7579360, 20097649/13679883), (176228877641067/9078545489689, 14356927982089/53923856957760), \dots $$
If $(a, b)$ is any such solution then clearly $(a, b, 3)$ is a solution to your original problem. So your equation has infinitely many rational solutions.
(I got to this by a little trial and error: I spotted that for a fixed $c$ the equation in $a, b$ gave an elliptic curve, and I tried a few small values of $c$ until I found an elliptic curve with nontrivial rational points. Here is the Magma session:
Magma V2.21-4     Thu Oct  8 2015 10:14:42 on fermat   [Seed = 3701259969]
Type ? for help.  Type <Ctrl>-D to quit.
> A<x, y> := AffineSpace(Rationals(), 2);
> S := Curve(A, 3/(3^2 + 1)*(x^2 + 1)*(y^2 + 1) - (x*(y^2 + 1) + y*(x^2 + 1)));
> Sp := ProjectiveClosure(S);
> E, phi := EllipticCurve(Sp, Sp ! [3, 0, 1]);
> Rank(E);
1 true
> _, nu := IsInvertible(phi);
> nu(2*Generators(E)[2]);
> (-627/119 : 123/160 : 1)
> nu(3*Generators(E)[2]);
(-1287933/7579360 : 13679883/20097649 : 1)

Try it yourself at the online Magma calculator.
)
PS. One can even write down infinitely many parametric families of solutions: for instance, for any rational $c$ we can take
$$ a = \frac{-c^6 + 3c^4 + c^2 + 1}{c^7 + c^5 + 3c^3 - c}, b = \frac{c^6 - c^4 - c^2 + 1}{2(c^5 + c)}. $$

A: -b/(bb+1)=a/(aa+1)-c/(cc+1). Put a=0. Then b/(bb+1)=c/(cc+1). Then b=c. Infinity number of rational solutions. We can replace the problem with -f(b)/f(b)f(b)+1=f(a)/(f(a)f(a)+1)-f(c)/(f(c)f(c)+1) such that f(0)=0 and f is 1:1.