text:
Q: Meaning of "absolute zero" in set theory With great pleasure I am reading "Believing the axioms" by Penelope Maddy after someone linked to it here on MSE. (https://www.jstor.org/stable/2274520). However on page 495 there is a sentence I don't understand:

For example, a subset of the unit interval is called "absolute zero" if it can be covered by any countable collection of intervals.

(The 'for example' refers to 'strong smallness properties', of which being absolute zero is an example)
I don't understand this definition and due to the overwhelming number of articles on the more famous "absolute zero" from physics it is impossible to google. I think my problem is with the interpretation of the word 'any'.
It seems to me that for every point $x$ in the unit interval it is easy to construct a countable collection of intervals not covering $x$, hence showing that no non-empty set can be absolute zero. But clearly that is not what is meant. But then, what is?
The next sentence from the article does not make it any clearer:

If covering is only required when the intervals are of equal length, then the set would have Lebesgue measure zero, but would not necessarily be absolute zero.

I was hoping I could think of some criterion that sounds vaguely like 'can be covered by any countable collection of intervals of the same length' that would imply being measure zero but I failed. The next sentence from the article elaborates on the distinction between measure zero and absolute zero:

Thus Cantor's discontinuum has Lebesgue measure zero, but is not absolute zero, because it cannot be covered by countable manby intervals of length $(1/3)^n$.

'Ok', I thought, 'this gives some hint of what might be meant'. Perhaps they meant 'A set $Z$ is absolute zero if for each sequence $a_1, a_2 ,\ldots$ of numbers in $(0, 1]$ there is a collection of intervals $I_1, I_2, \ldots$ such that $I_n$ has length $a_n$ and together the intervals cover $Z$.' At least this sounds like a well defined property. EDITED IN: Due to Asaf Karagila' comment below I now know that this property actually has name and a Wikipedia page, increasing the likelihood that this indeed is what is meant. END OF EDIT
But then I thought what the analogue with 'intervals of equal length' would be and everything collapses: obviously the property 'for each number $a \in (0, 1]$ there is a countable collection of intervals, each of length $a$, that together cover $X$' is true for every subset of $[0,1]$, not just those of measure zero.
So I am back to square one. Can anyone tell me what the definition of 'absolute zero' is and what property implying 'ordinary' measure zero is intended in the second sentence?
UPDATE: after reading the wikipedia page on 'strong measure zero' I actually believe that indeed (as Asaf wrote) strong measure zero and absolute zero are the same thing. The relations of both properties to the continuum hypothesis and conjectures by Borel discussed in both articles are just too similar for them not to be the same property.
But I am still mystified what property of a given set involving collections of intervals of the same length and implying the set to have measure zero is alluded to in the second of the quoted sentences. Does anyone know?

A: Unfortunately, Maddy is being imprecise in her use of terminology and the surrounding explanation. The mention of Borel in page 496 is a good hint that the notion she is discussing is that of being strong measure zero, as suggested in the comments.
A set of reals is (or has) measure zero if and only if for any $\epsilon>0$ it can be covered by countably many open intervals whose lengths add up to less than $\epsilon$. Cantor's set is a good example.
A set is strong measure zero if and only if, for any sequence of numbers $\epsilon_n>0$, it can be covered by a sequence of open intervals $I_n$ with the length of $I_n$ being at most $\epsilon_n$. The notion is due to Borel, in 1919.
Clearly any set satisfying this latter notion is measure 0, as for any $\epsilon>0$ we can take $\epsilon_n=\epsilon/2^{n+1}$. What the new notion brings to the table is that we can control very strongly how the set is covered by intervals, essentially ensuring that it cannot have many accumulation points. Easily, any countable set is strong measure 0, but one can show that no perfect set is (Maddy also mentions this).
One can prove this as follows: First, given any perfect set $P\subseteq \mathbb R$, there are continuous maps $f:\mathbb R\to\mathbb R$ that send $P$ onto the unit interval: when $P$ is the Cantor set, a famous example of such a function $f$ is the Cantor function; in general, any perfect set contains a set homeomorphic to the Cantor set, and from this the claim easily follows. Second, if $X\subseteq \mathbb R$ is strong measure 0, then its image under any continuous map $f:\mathbb R\to\mathbb R$ is again strong measure 0, this is an easy consequence of continuity. It follows that no perfect set is strong measure 0.
Borel conjectured that every strong measure 0 set is countable. This fails under CH and it is a famous result of Laver from 1976 that it is consistent (in fact, later work by Laver, Shelah and Woodin shows that it is consistent with $\mathbb R$ being arbitrarily large).
[Note that, as pointed out in the comments, only the empty set can be covered by any countable collection of intervals. Also, we do not recover the notion of measure zero if instead we require that the set can be covered by a countable collection of intervals of equal length, even if we insist that this length be less than any given $\epsilon>0$. Indeed, any set can be covered by such a collection. I suspect what Maddy meant to say was that the set can be covered by a countable collection of intervals of any given length, meaning that the whole collection has the given length, rather than the individual intervals.]


text:
Q: Serializing a compressed xml buffer I'm using libxml2-2.7.8 compiled on Windows with zlib support. I'm trying to get a buffer in memory with compressed XML document. I'm using xmlSetDocCompressMode(doc, 9); function.
If I save the doc to a file using xmlSaveFormatFile(), it saves the compressed file fine. However when I'm trying to use xmlDocDump...() functions, the buffer is not compressed. I can see that there is xmlSaveFileTo() function, however I can't find any related documentation on this matter. All my attempts cause crashes. A code example would be much appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cakephp can't change database on-the-fly I am trying to connect from multiples databases from a loop, but seens CakePHP can't change database, only others infos (like user/pass/host).
app/Config/database.php
<?php
class DATABASE_CONFIG {
    [...]

    public $default = array(
        [..] // Where I have the companies
    );
    public $client = array(
        [...] // Fakke settings, because I will change it on-the-fly
    );
}

app/Controller/CronController.php
$companies = $this->Company->find('all');
foreach($companies as $company) {
    $settings = array(
        'datasource' => 'Database/Mysql',
        'host' => $company['Company']['host'],
        'login' => $company['Company']['username'],
        'password' => $company['Company']['password'],
        'database' => $company['Company']['database'],
    );

    ConnectionManager::drop('client');
    $db = ConnectionManager::create('client', $settings);

    try {
        debug($this->MyModel->find('first'));
    } catch (Exception $e) {
        echo '<pre>';
        echo "Exception: ",  $e->getMessage(), "\n";

        /*
        debug($this->MyModel->getDataSource());

        Outputs:

        [...]
        [config] => Array
            (
                [persistent] =>
                [host] => 0.0.0.0 // CORRECT HOST
                [login] => root // CORRECT LOGIN
                [password] => pass // CORRECT PASSWORD
                [database] => database1
                [port] => 3306
                [datasource] => Database/Mysql
                [prefix] =>
                [encoding] => utf8
            )
        [...]
        */
    }
}

It return the first connection and all others I can select nothing from MyModel, because it is wrong. It seens connection from user/password/host is ok, but, database are not changed, so, because user haven't permission to select on cdatabase, I get the error.
Array
(
    // First connection, connection ok, MyModel return nothing
)

// Second connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_2'@'localhost' for table 'my_model'

// Third connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_3'@'localhost' for table 'my_model'

// Fourth connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_4'@'localhost' for table 'my_model'

// Fifth connection
Exception: SQLSTATE[42000]: Syntax error or access violation: 1142 SELECT command denied to user 'database_user_5'@'localhost' for table 'my_model'

Thanks!

A: Try not to drop config, just alter the things you need.
For this task I successfully use
$dataSource = ConnectionManager::getDataSource('company_data');
$dataSource->config['schema'] = 'company_'.$id;

I don't know if database switching and mysql as engine is good pair. I use postgresql schemas for this purpose.

A: You can use the model method setSource() to change the table or setDataSource() to change the db config.


text:
Q: Order dataframe by row Suppose I have the following dataframe
      C1  C2
John  4   3
Bob   5   7
Mary  6   5
Carl  5   6
James 4   3

How can I order my dataframe to have:
Carl, Mary, Bob, John, James
in an efficient way?
It is an arbitrary ordering and I might have the names stored in a variable orderedNames

A: define your ordering
arbitrary_ordering = ['Carl', 'Mary', 'Bob', 'John', 'James']

option 1
loc
df.loc[arbitrary_ordering]

option 2
reindex
df.reindex(arbitrary_ordering)

option 3
reindex_axis
df.reindex_axis(arbitrary_ordering)

All yield
       C1  C2
Carl    5   6
Mary    6   5
Bob     5   7
John    4   3
James   4   3

alternative 1
df.iloc[df.index.to_series().map(arbitrary_ordering.index)]

alternative 2
pd.Categorical
df.index = pd.Categorical(df.index, categories=arbitrary_ordering)
df.sort_index()

Time Test

A: You can order them arbirtrarly using loc (suppose your data are in df)
df.loc[['Carl', 'Mary', 'Bob', 'John', 'James'], :]

However, if you want to order them by subset of columns use sort_values
df.sort_values(by='C1')

Or even more advanced would be sorting by custom key function. See this question: pandas sort lambda function


text:
Q: How to add nodes from another xml using xmlbeans I am using xmlbeans to generate the xml document, while I need to extract all the children  from another xml file and insert them to my current document.
The to_be_add.xml:
<root>
    <style>
        .....
    </style>
    <atlas img="styles/jmap.png">
        ....
    </atlas>
    .....
</root>

And this xml file does not have a schema so I do not create related java class to map it. You think it as a plain xml file.
I want the style atlas node added. I use the following codes:
        XmlObject pointRoot = XmlObject.Factory.parse(Main.class.getResourceAsStream("to_be_added.xml"));
        NodeList nodeList = pointRoot.getDomNode().getChildNodes();

        Node themeNode = renderthemeDoc.getDomNode();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            themeNode.appendChild(node);
        }

Then I got error:

Exception in thread "main"
  org.apache.xmlbeans.impl.store.DomImpl$WrongDocumentErr: Child to add
  is from another document

And I found this post by searching "child to .... another document": how to add a xml document to another xml document in java which said that the connection between the element and the document has to be broken between the element can be add to other document.
So I try to build the Document object(that is why the variable pointDoc and themeDoc exist):
        XmlObject pointRoot = XmlObject.Factory.parse(Main.class.getResourceAsStream("to_be_added.xml"));
        Document pointDoc = pointRoot.getDomNode().getOwnerDocument();
        System.out.println(pointDoc);
        Element element = pointDoc.getDocumentElement();
        NodeList nodeList = element.getChildNodes();

        Document themeDoc = myCurrentDoc.getDomNode().getOwnerDocument();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            node = themeDoc.importNode(node, true);
            themeDoc.appendChild(node);
        }

Then I got NullPointerException which said that the pointDoc is null.
That is the whole process how I try to solve this problem. If it is unclear, please tell me, I will update accordingly.
Is it possible to fix it?

A: Since your other XML file is not mapped to a class, you can use a regular DOM parser to read it and extract its nodes. But using a generic object factory you can still get the nodes:
    XmlObject pointRoot = XmlObject.Factory.parse(  "<root>\n" +
                                                    "    <style>\n" +
                                                    "    </style>\n" +
                                                    "    <atlas img=\"styles/jmap.png\">\n" +
                                                    "    </atlas>\n" +
                                                    "</root>");

    Node pointDoc = pointRoot.getDomNode().getFirstChild();
    NodeList nodeList = pointDoc.getChildNodes();

    for(int i = 0; i < nodeList.getLength(); i++) {
        System.out.println("Node: " + nodeList.item(i).getNodeName());
    }

This will print:
Node: #text
Node: style
Node: #text
Node: atlas
Node: #text


text:
Q: how to update user table in node js mycode is--
 updateUser: function(req, res) {
    var data = req.body;
    var option = {
        name: data.name,
        mobile: data.mobile,
        domain: data.domain,
    }
    userModel.update(option, function (error, rows) {
        console.log('###############',error || rows);
        if(!res){
            //TODO: Error handling
            console.log("ERROR", res);
            res.status(200).send({"status_code": 0, 'message': 'Some error occured'});
            return;
        }
        res.status(200).send({"status_code": 1, 'message': 'Succesfully Updated'});
    })
},

the problem is updated all user coloumn.
in the code how to give id of the particular update data.

A: If you are not writing some very low level driver, I would recommend to use ORM like https://github.com/sequelize/sequelize. The very first example on their homepage shows:
var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password');

var User = sequelize.define('user', {
  username: Sequelize.STRING,
  birthday: Sequelize.DATE
});

sequelize.sync().then(function() {
  return User.create({
    username: 'janedoe',
    birthday: new Date(1980, 6, 20)
  });
}).then(function(jane) {
  console.log(jane.get());
  jane.update({
       username: 'a very different username now'
  }).then(function() {
       console.log(jane.get());
  })
});

A: You should use Bookshelf.js, good ORM, easy to use


text:
Q: PHP - Unable to change memory_limit on php-fpm It might seem a stupid question, but I'm already trying since one hour to figure it out without success.
As stated in title, I'm actually unable to change memory_limit directive in PHP 7.1.15 but only for php-fpm. In fact if I execute php -i | grep memory_limit in terminal I can see the correct value memory_limit => -1 => -1.
What I tried so far:

*

*Setting memory_limit in php.ini

*Using ini_set('memory_limit', -1); directly in PHP script

I also tried to disable all loaded extensions cause I thought maybe one of them is overwriting that setting, but didn't work.
Also consider that edited php.ini file is the correct one since I was able to change max_execution_time without any problem.
So how this code
ini_set('memory_limit', -1);
echo ini_get('memory_limit');
exit;

can return 128M as output?

A: To change the memory limit for PHP-FPM, add the following line to your php-fpm.conf file:
php_admin_value[memory_limit] = -1

A: from fpm-config
;   php_value/php_flag             - you can set classic ini defines which can
;                                    be overwritten from PHP call 'ini_set'.
;   php_admin_value/php_admin_flag - these directives won't be overwritten by
;                                     PHP call 'ini_set'

You must chose better solution for you. I'm prefer set lower memory limit in global config, and in places (wo I can't rewrite better) I'm add ini_set('memory_limit', xxx);


text:
Q: Choosing a Server for CSV import of 400k Products I am in need of some help in understanding and selecting a server to use for a website.  If somebody has a CSV file of 400,000 products that they need to import into a website, what would be the best server to handle the load and minimize timeouts when uploading?
I'm assuming it would be possible to utilize Wordpress (with MySQL), WooCommerce and WP All Imports to import the CSV file of products.  To help with the upload process, I figured it would be best to create 40 batches of 10,000, products and upload them batch by batch.
Does this sound possible? Any thoughts? Thanks!


text:
Q: Problems with Docker swarm manager on Google Cloud and Oracle Cloud VPC My scenario has 7 nodes, 4 running in AWS (each one in a different account), 1 running in LINODE, 1 running in Google Cloud and 1 running in Oracle Cloud. Every node is using external IP, and I checked firewall ports into the provider and ensure that is disabled on the VM. I also edited the hosts files in each node to ensure that they will be reachable, all they are pinging ok.
All machines running in AWS and Linode can join the SWARM both as a worker or as a manager, but the machines running in the Google Cloud and Oracle, just can join as a worker.
Using one AWS node as Leader, I got the following error messages...
docker node ls on leader
trying join node from Oracle
trying join node from Google Cloud
At last, I tried to make the Google Cloud node as a leader into a new SWARM, and tried to join the Linode and Oracle Nodes into it and got the following error message
trying to join o a new swarm
In this last attempt, the node that I tried to add says that he is into a swarm but when I run a docker node ls into the Leader, no new nodes are added...
Anyone already used Google Cloud or Oracle to run dockers and swarm can help me to figure out what more I need configure or what port or protocol more I need to allow. I already tried to permit all traffic from the nodes IP... in theory, everything would be allowed...
My best regards,
Leonardo Lima

A: Google Cloud Platform handles implied Firewall rules and also have default Ingress rules added once a new VPC is created. If you don't explicitly allow the Ingress traffic to specific ports in the node/nodes within the VPC, connection will timeout. Therefore, you need to allow the traffic to the node through the manager port (2377) from 0.0.0.0/0 (any source). So, these are the networking configurations that we need to review before understand why you can't connect to your node as Manager.


text:
Q: Content-Length returned in headers for chunked transfer encoding with nginx, uwsgi and flask If I use chunked transfer encoding with nginx, uwsgi and flask I always get Content-Length in headers together with Transfer-Encoding: chunked. However, HTTP 1.1 prohibits this behaviour. I have tried to configure nginx and uwsgi to achieve desired behaviour (no Content-Length in headers when Transfer-Encoding: chunked) but without success. Firstly, there is my server and client code:
Server code (server.py):
from flask import Flask
from flask import request

application = Flask(__name__)

@application.route('/', methods=['PUT'])
def hello():
    print(request.headers)
    print(request.environ.get('SERVER_PROTOCOL'))
    return "Hello World!"

if __name__ == "__main__":
    application.run(host='0.0.0.0')

Client code (client.py):
import requests

def get_data():
    yield b'This is test file.'
    yield b'This is test file.'

r = requests.request(
    method='PUT',
    url='http://127.0.0.1:5000/',
    data=get_data(),
    headers={
        'Content-type': 'text/plain',
        'X-Accel-Buffering': 'no',
    }
)
print('Response: ', r.text)

If I run server and try to connect to server with client I get the following output. Server output:
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
Host: 127.0.0.1:5000
User-Agent: python-requests/2.18.4
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
Content-Type: text/plain
X-Accel-Buffering: no
Transfer-Encoding: chunked

HTTP/1.1
[pid: 18455|app: 0|req: 1/1] 127.0.0.1 () {34 vars in 412 bytes} [Wed Jan 17 08:24:53 2018] PUT / => generated 12 bytes in 0 msecs (HTTP/1.1 200) 2 headers in 79 bytes (1 switches on core 0)

Client output:
Response:  Hello World!

For now, everything seems alright. In headers, we have Transfer-Encoding without Content-Length. Now, I try to incorporate uwsgi (uwsgi.py):
from server import application

if __name__ == "__main__":
    application.run()

I run the following command:
$ uwsgi --http-socket localhost:5000 -w wsgi

The output is the same as in the previous attempt. Therefore, still as expected. Now, I will try to deploy nginx. My uwsgi configuration (uwsgi.ini):
[uwsgi]
module = wsgi

master = true
processes = 5

socket = /tmp/flask.sock
chmod-socket = 777
vacuum = true

die-on-term = true

My nginx configuration (/etc/nginx/nginx.conf):
worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen 5000;
        server_name 127.0.0.1;

        location / {
            include uwsgi_params;
            uwsgi_pass unix:/tmp/flask.sock;
            proxy_request_buffering off;
            proxy_buffering off;
            proxy_http_version 1.1;
            chunked_transfer_encoding on;
        }
        proxy_request_buffering off;
        proxy_buffering off;
        proxy_http_version 1.1;
        chunked_transfer_encoding on;
    }
}

I start nginx and then I run:
$ uwsgi --ini uwsgi.ini --wsgi-manage-chunked-input --http-raw-body --http-auto-chunked --http-chunked-input

Now, the output contains Content-Length:
Content-Type: text/plain
Content-Length: 36
Host: 127.0.0.1:5000
User-Agent: python-requests/2.18.4
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive
X-Accel-Buffering: no
Transfer-Encoding: chunked

HTTP/1.1
[pid: 20220|app: 0|req: 1/1] 127.0.0.1 () {42 vars in 525 bytes} [Wed Jan 17 08:31:39 2018] PUT / => generated 12 bytes in 1 msecs (HTTP/1.1 200) 2 headers in 79 bytes (1 switches on core 0)

I try different settings for nginx: proxy_request_buffering, proxy_buffering, proxy_http_version and chunked_transfer_encoding in the server and location context without success. I added X-Accel-Buffering: no to headers but it did not solve the problem. Also, I tried different options for uwsgi: wsgi-manage-chunked-input, http-raw-body, http-auto-chunked, http-chunked-input without achieving desired behaviour (Content-Length is still present in headers with Transfer-Encoding: chunked).
I use the following versions of flask, uwsgi and nginx:
Flask==0.12.2
uWSGI===2.1-dev-f74553db
nginx 1.12.2-2

Any idea what can be wrong? Thanks.

A: I suffered same problem. My environment was uWSGI 2.0.17, with Nginx and Flask 1.0. When the client sent a request with Transfer-Encoding: chunked, the nginx added the Content-Length. (Though this is prohibited by HTTP/1.1 protocol.)
My conclusion was uWSGI does not support request with chunked Tranfer-Encoding. My flask app didn't get the request body of POST method when the request header have Transfer-Encoding only and also have both Transfer-Encoding and Content-Length.
Waitress, the wsgi server for python 2 and 3, solved this problem. If waitress receives the request with Transfer-Encoding header, he ignores it and set the right Content-Length. (refer to https://github.com/Pylons/waitress/blob/c18aa5e24e8d96bb64c9454a626147f37a23f0f0/waitress/parser.py#L154)
The flask official document also recommends the waitree to run a production flask server. (http://flask.pocoo.org/docs/1.0/tutorial/deploy/)


text:
Q: Looping a multidimensional array to update values in PHP in these troubling times I've been trying to keep my social contact up and that includes my board game club.
I figured we could still play "King of Tokyo" as it involves no "secret cards" (ie, nothing in your hands only you can see, everything is on the table). So I set up about five webcams (well, two webcams, two mobile phones and a tablet all running IP Webcam), one for my pretty face, one for the board, one for the dice, one for the player stat cards and a roaming one if needs be. OBS studio worked a charm linking everything together and switching where needs be plus the PIP so you could see board, dice rolls and stat cards all on one screen.
However, that's all a tad complex and I spent focusing so much on managing the cameras I fluffed my role as a GM up a few times so decided to simplify things, I've written a small PHP script that does the dice rolls and player stats so I can link that in as an overlay on OBS and drop two cameras, merging that next to the game board.
So, long intro, apologies, here's the problem - TL;DR join in here:
I have the following array:
$monsters = array(
    array("Alienoid",0,10),
    array("Space Penguin",0,10),
    array("Meka Dragon",0,10),
    array("Cyber Kitty",0,10),
    array("The King",0,10),
    array("Gigazaur",0,10)
    );

Which is basically for the first load (name, points, health), I randomise it to randomise players turns on first load and so from then on I re-read it back in from $_POST data to maintain order:
//names from last round
if (isset($_POST['mon0'])){
    $monsters[0][0] = $_POST['mon0'];
}
if (isset($_POST['mon1'])){
    $monsters[1][0] = $_POST['mon1'];
}
if (isset($_POST['mon2'])){
    $monsters[2][0] = $_POST['mon2'];
}
if (isset($_POST['mon3'])){
    $monsters[3][0] = $_POST['mon3'];
}
if (isset($_POST['mon4'])){
    $monsters[4][0] = $_POST['mon4'];
}
if (isset($_POST['mon5'])){
    $monsters[5][0] = $_POST['mon5'];
}

And that all works perfectly fine. However, I'm getting a bit carried away and want to adjust it from this rather static 6 monsters list to N monsters for N players (game limit is 6, so N can at most be 6, but could be as little as 2).
So I thought I'd just do a for loop like this:
//get names from last round
for ($x = 0; $x < count($monsters); $x++) {
    if (isset($_POST['mon'+$x])){
        $monsters[$x][0] = $_POST['mon'+$x];
    }
}

Now, as I'm still using my static $monsters list from above count($monsters) is 6 but this doesn't seem to work at all and all my player stats and names disappear. I've seen a lot of for loop tutorials and questions on here and they're all about displaying data, I'm happy with that, but I'm not sure how I dynamically update my array - I'm not a coder, just poke about a bit with PHP in the past and thought it could help solve my problem and keep us all playing and chatting during what is a pretty dull period.
Thanks for reading, big thanks if you can help.
BTW, happy to share the full dodgy code (as in it works, but, could probably be better by someone who knows what they're doing) if anyone else would like to take this online with their friends, using OBS Studio and Virtual Cam plugin you can basically stream the game to any webex you use, we used Google Hangouts which worked averagely (lost one guy at the start, another couldn't work out how to log in) but it does allow you to click on a person and keep their screen as the focus rather than jump around to who's talking. So my plan for the next game is just this window down the side and a webcam pointed at the gameboard as the main pic with a tiny me in the corner.

A: Need to use . instead of +
for ($x = 0; $x < count($monsters); $x++) {
    if (isset($_POST['mon'.$x])){
        $monsters[$x][0] = $_POST['mon'.$x];
    }
}


text:
Q: Winston createLogger() is not a function In a TypeScript, Node project I am trying to make some Jest unit tests, the problem is ever since I installed Jest with ts-node the main code is broken, when I try to us npm test or npm start I get this error:
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node src/server.ts`
TypeError: winston_1.default.createLogger is not a function

I'm using Winston 3.6.0 but can someone help me?

A: This worked for me,
import * as winston from "winston";

const loggerInstance = winston.createLogger({});

loggerInstance.log('info', 'Hello distributed log files!');
loggerInstance.info('Hello again distributed logs');


text:
Q: Running windows message Constantly I'am using Getx but build Runing Constantly
Running Constantly Error
I/chatty  ( 1828): uid=10153(com.remax.app) 1.ui identical 82 lines
I/flutter ( 1828): View List Value Market statics=======> 6
I/flutter ( 1828): build running
I/flutter ( 1828): View List Value Market statics=======> 6


text:
Q: do rust type annotations affect speed, or are used just for readability's sake I'm learning rust and I have this question.
Is this
let x: i32 = 1;

Faster than
let x = 1;

Or is it just for readability?

A: You can investigate a compiled Rust program (that is, what the Rust compiler produces from Rust source code) easily using a tool such as Godbolt.
See the following example: https://godbolt.org/z/54x3Gd9oo

As you can see, the compiled output is identical (as far as the arithmetic is concerned, the fact that the two functions are named differently introduces some minor differences). From this, you can infer that there is no speed advantage, and that the Rust compiler erases these details at compile time. It cannot have any effect on the wall time of the program being run, but as @Christina Sørensen says, it may affect compile time.

A: We can test this by printing the type, inspired by this answer:
How do I print in Rust the type of a variable?
fn print_type_of<T>(_: &T) {
    println!("{}", std::any::type_name::<T>())
}

fn main() {
    let x: i32 = 1;
    let y = 1;
    print_type_of(&x);
    print_type_of(&y);
}

Which will print out:
i32
i32

What happens when we don't explicitly tell rust what type to use is that rust will try to infer it.
As we can see here, the compiler on my computer made the variables the same type, but it's important to know that this is not a guarantee.
As to whether or not it's faster, usually, being explicit about what type you want the variable to be means that the compiler has to do less thinking, making the program faster to compile. The same holds for interpreted languages, where the program will have a faster runtime, because again it does not need to think about what kind of type to give the variable.
However, it's not a very large difference, and when it has been decided it's unlikely to have an impact on runtime.


text:
Q: PDO insert statement and comma separator I have:
INSERT INTO post(title,message) VALUES (:title,:message)

where :message value has some random text with symbols (including comma).
As the comma symbol is the separator between components of the statement:
How can i escape :message value to keep its included commas in the string context and not be interpreted as the separator?

A: You don't need to. The whole point of using prepared statements, as you are with PDO, is that the structure of the query is sent separately from the data. This means that characters in the data are never confused for parts of the structure of the query.
You've done all you need to do to make the query safe in this regard.

A: Prepared statements my friend.
This is what php.net has to say;

The query only needs to be parsed (or prepared) once, but can be executed multiple time with the same or different parameters. When
the query is prepared, the database will analyze, compile and optimize
its plan for executing the query. For complex queries this process can
take up enough time that it will noticeably slow down an application
if there is a need to repeat the same query many times with different
parameters. By using a prepared statement the application avoids
repeating the analyze/compile/optimize cycle. This means that prepared
statements use fewer resources and thus run faster.
The parameters to prepared statements don't need to be quoted; the driver automatically handles this. If an application exclusively uses
prepared statements, the developer can be sure that no SQL injection
will occur (however, if other portions of the query are being built up
with unescaped input, SQL injection is still possible).


text:
Q: How to activate a cell in tree view for editing I have a simple tree view with text-based cells. I would like to be able to open the currently selected cell for editing by pressing the F2 key. In other words, the F2 key should behave exactly the same way as the Enter key does now, when a cell is selected. (It opens a little box in which I can edit the contents of the cell.)
I could not figure out what to call in order to activate that little box.
I include a minimum working example:
#include <gtkmm.h>
#include <iostream>

typedef Glib::RefPtr<Gtk::Application> ApplicationRef;
typedef Glib::RefPtr<Gtk::ListStore>   ListStoreRef;

using namespace std;

class Example : public Gtk::Window
{

public:
    Example()
    {
        m_list_store_ref = Gtk::ListStore::create(m_model_columns);
        m_tree_view.set_model(m_list_store_ref);

        // Fill in the model with dummy data.
        m_add_row("apple", "lettuce");
        m_add_row("orange", "broccoli");
        m_add_row("banana", "cauliflower");

        // Add columns to the tree view.
        m_tree_view.append_column_editable("Fruit", m_model_columns.m_fruit);
        m_tree_view.append_column_editable("Vegetables", m_model_columns.m_vegetables);

        add(m_tree_view);

        add_events(Gdk::KEY_PRESS_MASK);

        show_all_children();
    }
    virtual ~Example() {}

protected:
    //Signal handlers:
    void on_button_clicked() { hide(); }

    //Member widgets:
    Gtk::TreeView m_tree_view;

    // Other objects
    ListStoreRef m_list_store_ref;

    // Model columns
    class ModelColumns : public Gtk::TreeModel::ColumnRecord
    {
    public:
        ModelColumns() { add(m_fruit); add(m_vegetables); }

        Gtk::TreeModelColumn<Glib::ustring> m_fruit;
        Gtk::TreeModelColumn<Glib::ustring> m_vegetables;
    };

    ModelColumns m_model_columns;

    void m_add_row(Glib::ustring fruit, Glib::ustring vegetable)
    {
        auto row = *(m_list_store_ref->append());
        row[m_model_columns.m_fruit]      = fruit;
        row[m_model_columns.m_vegetables] = vegetable;
    }

    bool on_key_press_event(GdkEventKey* event)
    {
        if (event->keyval==GDK_KEY_F2) {
            cout << "F2 was pressed." << endl;

            // What code should go here to make the currently selected cell active for editing?

            return true;
        }

        return Gtk::Window::on_key_press_event(event);
    }
};

int main(int argc, char *argv[])
{
    ApplicationRef app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.mwe");
    Example example;
    return app->run(example);
}

A: I found the answer. (The key was the post entitled Start PyGTK cellrenderer edit from code.) Here is the same MWE, which has the behavior I want:
#include <gtkmm.h>
#include <iostream>

typedef Glib::RefPtr<Gtk::Application> ApplicationRef;
typedef Glib::RefPtr<Gtk::ListStore>   ListStoreRef;

using namespace std;

class Example : public Gtk::Window
{

public:
    Example()
    {
        m_list_store_ref = Gtk::ListStore::create(m_model_columns);
        m_tree_view.set_model(m_list_store_ref);

        // Fill in the model with dummy data.
        m_add_row("apple", "lettuce");
        m_add_row("orange", "broccoli");
        m_add_row("banana", "cauliflower");

        // Add columns to the tree view.
        m_tree_view.append_column_editable("Fruit", m_model_columns.m_fruit);
        m_tree_view.append_column_editable("Vegetables", m_model_columns.m_vegetables);

        add(m_tree_view);

        add_events(Gdk::KEY_PRESS_MASK);

        show_all_children();
    }
    virtual ~Example() {}

protected:
    //Signal handlers:
    void on_button_clicked() { hide(); }

    //Member widgets:
    Gtk::TreeView m_tree_view;

    // Other objects
    ListStoreRef m_list_store_ref;

    // Model columns
    class ModelColumns : public Gtk::TreeModel::ColumnRecord
    {
    public:
        ModelColumns() { add(m_fruit); add(m_vegetables); }

        Gtk::TreeModelColumn<Glib::ustring> m_fruit;
        Gtk::TreeModelColumn<Glib::ustring> m_vegetables;
    };

    ModelColumns m_model_columns;

    void m_add_row(Glib::ustring fruit, Glib::ustring vegetable)
    {
        auto row = *(m_list_store_ref->append());
        row[m_model_columns.m_fruit]      = fruit;
        row[m_model_columns.m_vegetables] = vegetable;
    }

    bool on_key_press_event(GdkEventKey* event)
    {
        if (event->keyval==GDK_KEY_F2) {
            cout << "F2 was pressed." << endl;

            Gtk::TreeModel::Path path;
            Gtk::TreeViewColumn* col;

            m_tree_view.get_cursor(path, col);
            auto cell = col->get_first_cell();

            // If the cell is being edited, cancel the editing;
            // if the cell is not being edited, start editing.
            if(cell->property_editing()) {
                m_tree_view.set_cursor(path, *col, false);
            } else {
                m_tree_view.set_cursor(path, *col, true);
            }

            return true;
        }

        return Gtk::Window::on_key_press_event(event);
    }
};

int main(int argc, char *argv[])
{
    ApplicationRef app = Gtk::Application::create(argc, argv, "org.gtkmm.examples.mwe");
    Example example;
    return app->run(example);
}

A: You can toggle editable / non-editable with F2 key by below code.
bool on_key_press_event(GdkEventKey* event)
{
    if (GDK_KEY_F2) {
        cout << "F2 was pressed." << endl;

        // What code should go here to make the currently selected cell active for editing?
        Gtk::CellRendererText *column_fruit = (Gtk::CellRendererText*)m_tree_view.get_column_cell_renderer(0);
        Gtk::CellRendererText *column_vegetable = (Gtk::CellRendererText*)m_tree_view.get_column_cell_renderer(1);
        column_fruit->property_editable() = !column_fruit->property_editable();
        column_vegetable->property_editable() = !column_vegetable->property_editable();
    }
}


text:
Q: Where are programs usually installed for a particular user? On Windows, installing programs like Python without elevated privileges will default its install directory to "%LocalAppData%\Programs." Is this directory the "Program Files" equivalent, but only for that particular user?

A: I don't believe John is right about where apps MUST install. While programs installing within a limited user profile are relatively new in Windows, VS Code isn't the only one and it indeed installs to directories within the user profile, does not require admin rights to install, run, or update, and is actually a recommended method for running programs that do not need enhanced rights.
The logic is that a program that can run entirely within the much more limited rights of a limited, non-admin user accounts profile and its stricter limitations will, by nature, be much safer application.
Google Chrome also has a limited user install mode, just to name another prominent program that offers this.
VS Code, after it released its limited user version, pushes it as the recommended choice, which considering it is a Microsoft product, speaks to the acceptability of this method.

A:
On Windows, installing programs like Python without admin will default its install directory to "%LocalAppData%\Programs." Some programs install it right into the root of your user folder. Which is correct?
I'm trying to say, what is the windows recommended directory for installers (without elevated privileges) to install its binaries to? For example, VS Code's User Installer defaults its install directory to "%localappdata%\Programs" This is also the same case with Python Installer if you don't run it with elevated privileges.

%LocalAppData%\Programs is absolutely the correct installation location for Visual Studio Code since it utilizes the Electron Framework.  The Atom editor which is also built on the Electron Framework, default location also uses the %LocalAppData% directory, within the user profile on Windows.  I have no reason to believe that it also isn't the legitimate installation directory for Python.
Based on the fact that every legitimate application built upon the Electron Framework I have installed, installation directory was within %LocalAppData%, I can conclude that every application based on the Electron Framework will also be installed to the %LocalAppData% directory.

Visual Studio Code is built primarily with standard web technology (HTML, CSS, JavaScript).  We leverage Electron [previously Atom] as a cross-platform host.  This allows us to focus on the core experience and put our efforts into developer productivity (Editing, code navigation, code understanding, and debugging) and offer these features on Mac OSX, Linux and Windows.  We are working with the Electron team and actively contributing back to that framework.

Source: Microsoft's cross-platform Visual Studio Code app is based on technology from Github's Atom editor
I happen to install the Atom and is installed to the %LocalAppData% directory within my profile.  I also happen to have Authy installed on my system, which is also built upon the Electron Framework, and the executable for it is also located within %LocalAppData%
Chrome used to also use the %AppData% directory to store it's an executable file, which basically allowed any user to install Chrome on their PC since the have full permissions to the %AppData% directory.  It isn't relevant, but Chrome went away from that directory, for a variety of reasons a good number of years ago

More specifically, what directory, in Windows, was meant for installers to install their binaries/executables for a specific user?

The directory the executable for an application should exist in entirely depends on the permissions of the user running the application.  There are legitmant reasons to install an application to a directory within %LocalAppData.  One of the many reasons, include users with limited permissions, are able to install and run the application.  While the installation directory for Chrome no longer exists within %LocalAppData%, one of the many reasons it was installed there, is to avoid the UAC request when installing Chrome.

Is this directory the "Program Files" equivalent, but only for that particular user?

%LocalAppData% is absolutely not equivalent to Program Files and Program Files x86.
Windows doesn't tell programs anything. The installer either defaults to an installation directory, and given the permissios of the users, the installation is allowed to continue or the user selects the installation and directory and given the user has the correct permissions the installation is allowed to continue.
You could install everything to the root directory of the system drive if you really wanted to, provided you ran everything you installed with elevated permissions, Windows does not actually care about the location of an application's executable.


text:
Q: ConnectivityManager.requestNetwork in Android 6.0 I'm trying to get the new ConnectivityManager.bindProcessToNetwork(Network) using ConnectivityManager.requestNetwork(NetworkRequest, ConnectivityManager.NetworkCallback)
The reason is to force the app to call the future request in some specific network, which doesn't have a internet connectivity (it's a local hardware communication network). At this point, the system is sending the requests over 3G/4G network and never reach the desired Wifi network, because this network doesn't respond the connectivity check that android call.
When I call the requestNetwork method, I receive the following error:
java.lang.SecurityException: com.xyz.app was not granted  either of these permissions: android.permission.CHANGE_NETWORK_STATE, android.permission.WRITE_SETTINGS.

I try to call the new method to request permission available in Android 6.0:
 requestPermissions(new String[]{Manifest.permission.CHANGE_NETWORK_STATE, Manifest.permission.WRITE_SETTINGS}, PERMISSIONS_REQUEST_WIFI);

But the callback is always PackageManager.PERMISSION_DENIED.
I put both of these permissions in the AndroidManifest.xml, without success.
Notice: The Manifest.permission.WRITE_SETTINGS is not in the Permissions Groups.

A: I'm not sure if this was intended by Google, but the following is the behavior I'm seeing:
CHANGE_NETWORK_STATE seems to always be denied (as noted in the comments, its a signature permission) but it also doesn't seem to matter.  My ConnectivityManager network requests all seem to be gated by WRITE_SETTINGS only - so if you have WRITE_SETTINGS you don't need CHANGE_NETWORK_STATE.
As noted in comments, you do this differently than other permissions, using:
 Intent goToSettings = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
 goToSettings.setData(Uri.parse("package:" + Context.getPackageName()));
 startActivity(goToSettings);

And after that, my ConnectivityManager network requests were peachy.

To check if the permission is already granted before calling the ACTION_MANAGE_WRITE_SETTINGS activity, this answer has the solution using
Settings.System.canWrite(Context)
Can't get WRITE_SETTINGS permission

UPDATE: as of Android 6.0.1, CHANGE_NETWORK_STATE is auto granted when requested in your manifest file.  The above WRITE_SETTINGS checks are only required for 6.0

A: This was an Android 6.0 bug. It's fixed in Android 6.0.1, requestNetwork() can be called if you request CHANGE_NETWORK_STATE in the manifest. No need to call requestPermissions(), it's a normal permission.


text:
Q: Click method is not working with chrome emulator Below are the details of my setup:

chrome=67.0.3396.87,
  chromedriver=2.40.565498,
  selenium version-2.53.0

Below is the emulator code-
public ChromeOptions getChromeEmulators(int width, int height) {
    Map<String, Object> deviceMetrics = new HashMap<String, Object>();
    Map<String, Object> mobileEmulation = new HashMap<String, Object>();
    ChromeOptions chromeOptions = new ChromeOptions();
    try {
        deviceMetrics.put("width", width);
        deviceMetrics.put("height", height);
        deviceMetrics.put("pixelRatio", 3.0);
        mobileEmulation.put("deviceMetrics", deviceMetrics);
        mobileEmulation.put("userAgent",
"Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D)
AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile
Safari/535.19");
       chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
    }catch (Exception e) {
        e.printStackStarce();
    }
    return chromeOptions;
}

The click option is not working with chrome emulator, but it works on chrome browser with above versions. Can someone help?

A: This is a known issue of chromedriver in existence since the past few versions. No fix yet. At this point, the only workaround is to use chromerdriver : 2.33.506120 + chrome : 61.0.3163.79
Refer to the below bugs :
https://bugs.chromium.org/p/chromedriver/issues/detail?id=2144&desc=2
https://bugs.chromium.org/p/chromedriver/issues/detail?id=2172
Alternatively, u can try JavascriptExecutor (though this is not much preferred)
JavascriptExecutor script click. JavascriptExecutor js = (JavascriptExecutor)
driver; js.executeScript("arguments[0].click();",element);


text:
Q: SAX Parser in android loading with image and text I want to parse it through SAX Parser and the load the image through url and pass it to the next activity to show. But am failing to do so if any can help me out or give me some reusable code then it would be grateful. here is my xml file. Here is my parsed data class and adapter class don't to add items to arraylist. PLease help.
PARSEDDATA CLASS
public class ParseData extends DefaultHandler
{
    boolean title , cost , pubDate , link = false;
private String temp = "";

ArrayList<String> arrtitle = new ArrayList<String>();

ArrayList<String> arrcost = new ArrayList<String>();

ArrayList<String> arrpubDate = new ArrayList<String>();

ArrayList<String> arrlink = new ArrayList<String>();

//---------START ELEMENT----------//

@Override
public void startElement(String uri , String localName , String qName , Attributes attributes) throws SAXException
{
    super.startElement(uri, localName, qName, attributes);

    if(localName.equalsIgnoreCase("title"))
    {
        title = true;

    }else if(localName.equalsIgnoreCase("cost"))
    {
        cost = true;

    }else if(localName.equalsIgnoreCase("pubDate"))
    {
        pubDate = true;

    }else if(localName.equalsIgnoreCase("link"))
    {
        link = true;
    }
}
//--------END ELEMENT----------//

@Override
public void endElement(String uri , String localName , String qName) throws SAXException
{
    super.endElement(uri, localName, qName);
    if(localName.equalsIgnoreCase("title"))
    {
        title = false;

    }else if(localName.equalsIgnoreCase("cost"))
    {
        cost = false;

    }else if(localName.equalsIgnoreCase("pubDate"))
    {
        pubDate = false;

    }else if(localName.equalsIgnoreCase("link"))
        link = false;
}

@Override
public void characters(char[] ch, int start, int length)throws SAXException
{
    super.characters(ch, start, length);

    if(title)
    {

    }

    if(cost)
    {

    }

    if(pubDate)
    {

    }

    if(link)
    {

    }
}

}
BINDADAPTER CLASS
public class BindDataAdapter extends BaseAdapter
{
ArrayList<String> title;

ArrayList<String> cost;

ArrayList<String> pubDate;

LayoutInflater inflater;

//---------DEFAULT CONSTRUCTOR-----------//

public BindDataAdapter()
{

}

//-------PARAMETERIZED CONSTRUCTOR------//

public BindDataAdapter(Activity activity , ArrayList<String> title , ArrayList<String> cost , ArrayList<String> pubDate)
{
    this.title = title;

    this.cost = cost;

    this.pubDate = pubDate;

    inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

@Override
public int getCount()
{
    return title.size();
}

@Override
public Object getItem(int position)
{
    return position;
}

@Override
public long getItemId(int position)
{
    return position;
}

@Override
public View getView(int position , View convertView , ViewGroup parent)
{

    if(convertView == null)
    {
        convertView = inflater.inflate(R.layout.list_row , null);
    }

    TextView textViewtitle = (TextView) convertView.findViewById(R.id.type);

    TextView textViewcost = (TextView) convertView.findViewById(R.id.cost);

    TextView textViewdate = (TextView) convertView.findViewById(R.id.date);

    return convertView;
}

}

A: Use same code that you are using for parsing the data and For image, add extra variable and parameter as explaine in this link and use ImageLoader class to load images in the listView.
You ca also refer this, Android lazy image loader example and Loading Remote Images in a ListView on Android Link for reference.
Feel free to comment.


text:
Q: How to redirect a WCF service to an HTTPS endpoint with Windows credential Here is the situation I am trying to deal with:
We have a WCF client that works with an http endpoint and an https endpoint but not when it is redirected (302) from http to https.  We have an F5 load balancer that is performing the redirect and SSL functionality but as far as I can tell, it isn't doing anything unexpected to the requests.    The redirect seems to be the culprit where WCF doesn't want to provide Windows Kerberos authentication information after the redirect is performed.
The sequence for a successful call (i.e. http with no redirect) goes like this:

*

*Client - Sends POST request for service with http scheme

*Server - Responds with 401 unauthorized

*Client - Sends Negotiate POST with authorization

*Server - Responds with 100 Continue

*Client - Sends soap data and completes successfully

When the call is redirected and fails it goes like this:

*

*Client - Sends POST request for service with http scheme

*Server - Returns 302 with redirect to https scheme for same address

*Client - Sends GET for https address (I can't figure out why this is a GET and not a POST)

*Server - Responds with 401 unauthorized

*Client - throws exception "The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'Negotiate,NTLM'."

It is similar to this problem but not exactly the same (and there isn't really an answer there although it does reference "breaking WCF protocol" which I can find documetation on).  If we turn off the F5 redirect rule http and https traffic work fine.  Does WCF really not handle this simple redirect?  Is there a workaround or any documentation on this flaw?
Client config (note that when testing this with https, I change TransportCredentialOnly to Transport):
<client>
        <endpoint address="http://fooserver/MyService.svc/" binding="basicHttpBinding" bindingConfiguration="clientBinding" contract="Contracts.IMyService" />
</client>
<bindings>
<basicHttpBinding>
    <binding name="clientBinding">
        <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows" proxyCredentialType="Windows" />
        </security>
    </binding>
</basicHttpBinding>

Server config looks like this:
<system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    <services>
        <service behaviorConfiguration="MyServiceBehavior" name="MyService">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="securedBinding" contract="Contracts.IMyService">
            </endpoint>
        </service>
    </services>
    <bindings>
        <basicHttpBinding>
            <binding name="securedBinding">
                <security mode="TransportCredentialOnly">
                    <transport clientCredentialType="Windows" proxyCredentialType="Windows"/>
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <behaviors>
        <serviceBehaviors>
            <behavior name="MyServiceBehavior">
                <serviceMetadata httpGetEnabled="true"/>
                <serviceDebug includeExceptionDetailInFaults="true"/>
                <useRequestHeadersForMetadataAddress>
                    <defaultPorts>
                        <add scheme="http" port="80" />
                        <add scheme="https" port="443" />
                    </defaultPorts>
                </useRequestHeadersForMetadataAddress>
            </behavior>
        </serviceBehaviors>
    </behaviors>
</system.serviceModel>

A:
I can't figure out why this is a GET and not a POST

That is the cause of your problem.  After receiving a 302 response to a POST, it is expected behavior for a client to GET the new URL.  See the following at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

Also, the following SO post has some good info: Response.Redirect with POST instead of Get?
So WCF is doing what it should do by refusing to re-POST after a 302 redirect.  Unfortunately I'm not sure what can be done to resolve your problem, other than specifying the protocol correctly the first time to avoid the 302.

A: I just did something similar and I can confirm that this doesn't work. What is even worse it is probably not possible to change without replacing default WCF HTTP transport implementation.
Both redirection and authentication is handled directly inside WCF's HTTP processing which is internal. You cannot handle redirection manually which cause problem if you get 301 Moved permanently and WCF doesn't use your configured client credentials after redirection.
The problem with sending GET instead of POST after redirection should be theoretically solved by returning 307 Temporary redirect instead of 302 Found.


text:
Q: Package versions in Ubuntu I use Ubuntu through a virtual machine (VM Workstation Player) and sometimes download packages through the terminal. Some of the packages I download are not the latest version. For example, I downloaded Eclipse IDE and Wireshark and some versions were downloaded. Even when I try to update those packages, it tells me that the packages are up to date.
Why can't I download the latest versions and how can I fix this?

A: Some Linux distributions (distros) are more "conservative" or "prudent" than others and prefer to use more stable versions of packages, meaning you won't be able to download the latest versions through the standard repositories.
If you want the latest version of some softwares, you'll have to use alternative repositories by installing a Personal Package Archive (PPA) on your Ubuntu distro.
For instance, If you want to use the latest version of LibreOffice, you'll have to install this PPA:
https://launchpad.net/~libreoffice/+archive/ubuntu/ppa
Be careful to install only trusted PPA, coming from reliable sources (see Are "PPA's" safe to add to my system, and what are some "red flags" to watch out for?).
To install a PPA, you can:

*

*add a line to the sources.list file in /etc/apt. For LibreOffice, it's deb http://ppa.launchpad.net/libreoffice/ppa/ubuntu wily main

*on a terminal, type sudo add-apt-repository ppa:libreoffice/ppa


text:
Q: a leading whitespace before the result from regular expression I am using a rule to get substring in python using regular expression. But I found some results will have a leading whitespace while some of them don't. I know I can remove the whitespace with .strip(). But I want to understand why the whitespaces are there. Can anyone help?
Thanks
Ex 1. (no leading whitespace).
import re
utterance = 'can i make a call to +21231313'
re.findall('[-|#|+]*[0-9]*[-\s]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*', utterance.strip())

result:
['+21231313']

Ex 2. (leading whitespace).
import re
utterance = 'can i make a call to -21231313'
re.findall('[-|#|+]*[0-9]*[-\s]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*', utterance.strip())

result:
[' -21231313']

Ex 3. (leading whitespace).
import re
utterance = 'can i make a call to 21231313'
re.findall('[-|#|+]*[0-9]*[-\s]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*', utterance.strip())

result:
[' 21231313']

A: In RE, * will check for 0 or more occurrences of the expression. So the space comes only for the last block of your regex where every other block is interpreted as empty. Take a look to the state machine:

The last block([-\s\./0-9]*) will accept any number of the listed symbols that includes space and the sign - but not +. If your expression has the plus sign, the result will be:

Because the only block that accepts + is the first block, and there is not space in the first one. Because of that, if the regex recognize a plus sign, the match will not have any spaces.

A: The first chunk of patterns can match an empty string, '[-|#|+]*[0-9]*[-\s]*[(]{0,1}.
What you may use is make digit matching part obligatory while making the hyphen/space pattern optional and wrap that with an optional group, (?:[0-9]+[-\s]*)?. Also, you may avoid the whitespace at the end of the match if you re-factor the last [-\s\./0-9]* pattern to (?:[-\s./]*[0-9])*.
Use
[-#+]*(?:[0-9]+[-\s]*)?\(?[0-9]{1,4}\)?(?:[-\s./]*[0-9])*
      ^^^^^^^^^^^^^^^^^                ^^^^^^^^^^^^^^^^^^

See the regex demo
Details

*

*[-#+]* - zero or more -, # or +

*(?:[0-9]+[-\s]*)? - an optional non-capturing group matching 1 or 0 occurrences of 1+ digits and then 0+ hyphens/whitespaces

*\(? - an optional (

*[0-9]{1,4} - one to four digits

*\)? - an optional )

*(?:[-\s./]*[0-9])* - 0 or more occurrences of

*

*[-\s./]*  - 0 or more hyphens, whitespaces, . or /

*[0-9] - a digit.


text:
Q: MPNowPlayingInfoCenter is not showing but background playing does work I made MPNowPlayingInfoCenter but it isn't working. Background playing is working but MPNowPlayingCenter doesn't appear. This is how I made it.
import UIKit
import AVFoundation
import MediaPlayer

class AudioPlayViewController: UIViewController, AVAudioPlayerDelegate {
  var player: AVAudioPlayer!
  var updater: CADisplayLink! = nil

  @IBOutlet weak var playButton: UIButton!
  var url_2 = URL(string: "")
  var selectedFileName:String = ""

  override func viewDidLoad() {
    super.viewDidLoad()
    let path = selectedFileName
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let url = documentsURL.appendingPathComponent(path)
    url_2 = url

    do {
      player = try AVAudioPlayer(contentsOf: url)
      updater = CADisplayLink(target: self, selector: #selector(self.trackAudio))
      updater.preferredFramesPerSecond = 1
      updater.add(to: RunLoop.current, forMode: RunLoop.Mode.common)
      player.prepareToPlay()
      player.delegate = self
    catch {
      print(error)
    }
    let session = AVAudioSession.sharedInstance()
    do{
      try session.setCategory(AVAudioSession.Category.playback)
    }
    catch{
    }
  }

  func play(){
    player.play()
    MPNowPlayingInfoCenter.default().nowPlayingInfo = [
      MPMediaItemPropertyTitle: selectedFileName,
      MPMediaItemPropertyArtist: "Ariana",
      MPMediaItemPropertyLyrics: "test"
      ]
  }
}

I set Background Modes > Audio, Airplay, and Pictures in picture in Targets > Signing&Capabilities.

A: I solved it by adding
func setupNowPlayingInfoCenter(){
    UIApplication.shared.beginReceivingRemoteControlEvents()
    MPRemoteCommandCenter.shared().playCommand.addTarget {event in
      self.play()
      return .success
    }
    MPRemoteCommandCenter.shared().pauseCommand.addTarget {event in
      self.pause()
      return .success
    }
    MPRemoteCommandCenter.shared().nextTrackCommand.addTarget {event in
      self.goForward()
      return .success
    }
    MPRemoteCommandCenter.shared().previousTrackCommand.addTarget {event in
      self.goBackward()
      return .success
    }
  }

A: I found that you need to call UIApplication.shared.beginReceivingRemoteControlEvents() after you've setup the audio session, so the following worked for me:
try? AVAudioSession.sharedInstance().setCategory(.playback)
try? AVAudioSession.sharedInstance().setActive(true)
UIApplication.shared.beginReceivingRemoteControlEvents()


text:
Q: How to install RunSnakeRun on OS X with MacPorts? I've installed the wxWidgets-3.0 py27-wxpython-3.0 MacPorts packages. In a clean virtualenv I installed the wx, SquareMap, and RunSnakeRun pip packages. Attempting to run runsnake fails as follows:
Traceback (most recent call last):
  File "/Users/lhn/.virtualenvs/snake/bin/runsnake32", line 9, in <module>
    load_entry_point('RunSnakeRun==2.0.4', 'gui_scripts', 'runsnake32')()
  File "/Users/lhn/.virtualenvs/snake/lib/python2.7/site-packages/pkg_resources.py", line 353, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/Users/lhn/.virtualenvs/snake/lib/python2.7/site-packages/pkg_resources.py", line 2321, in load_entry_point
    return ep.load()
  File "/Users/lhn/.virtualenvs/snake/lib/python2.7/site-packages/pkg_resources.py", line 2048, in load
    entry = __import__(self.module_name, globals(),globals(), ['__name__'])
  File "/Users/lhn/.virtualenvs/snake/lib/python2.7/site-packages/runsnakerun/runsnake.py", line 14, in <module>
    from squaremap import squaremap
  File "/Users/lhn/.virtualenvs/snake/lib/python2.7/site-packages/squaremap/squaremap.py", line 3, in <module>
    import wx.lib.newevent
ImportError: No module named lib.newevent

In IDLE I see teh same import error:
Python 2.7.6 (default, Nov 18 2013, 15:12:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import wx
>>> import wx.lib.newevent
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named lib.newevent


text:
Q: THREE.js : efficient way to update dynamic line between two objects I am currently looking to the most efficient way to update a line connecting two three.js objects (Meshes) , when either one or both of the objects get changed (position, rotation, scale).

*

*Currently I have a polling method for every such connecting line , that updates its start & end based on the transforms of the two end objects, but this can get costly real fast when there are dozens of lines.

*I could go with an event based approach perhaps, but this requires dispatching change events from every 3D object that changes.
edit:
 perhaps some sort of scenegraph based hackery would be possible, but the three.js scene graph is just a tree, so no multiple parents etc are possible
Any pointers or better/ more optimised methods are welcome !
Thanks in advance!


text:
Q: Beginner: Class/Attribute Concept Confusion (Python) I am new to python and its OOP concepts, I was following below code and got little confused,
class Person:
  species = 'Homo sapiens'
  def __init__(self, name, age):
    self.name= name
    self.age = age

p = Person("ABC", 18)

p.species = 'No homo sapien'
print(p.species)
# prints --> No homo sapien

I haven't accessed or manipulated the value of class attribute species by just doing p.species so it should have thrown some error about species attribute, but got no error instead it did print.
p.__class__.species = 'Not found'
print("ABC is a {}".format(p.__class__.species))
# error --> SyntaxError: expression cannot contain assignment, perhaps you meant "=="?

This statement threw error as expected. So I want clarification regarding first statement. And can we change class attribute value?

A: When you assign to p.species, you are creating a new instance attribute that shadows the class attribute. Person.species will still evaluate to "Homo Sapiens".
>>> p = Person("ABC", 18)
>>> p.species = "No homo sapiens"
>>> p.species
'No homo sapiens'
>>> Person.species
'Homo sapiens'

If you want to change a class attribute, you have to do it via the class.
>>> p = Person("ABC", 18)
>>> Person.species = "Canis canis"
>>> p.species
'Canis canis'

Because no instance attribute named species exists, p.species falls back to Person.species.


text:
Q: Varying the start and end date of openssl self-signed certificates I have these three statements to generate a self-signed cert with a root certificate that I have.
openssl genrsa -out domain.org.key
openssl req -newkey rsa:2048 -nodes -keyout domain.org.key -subj "/C=CN/ST=GD/L=SZ/O=Acme, Inc./CN=*.domain.org" -out domain.org.csr
openssl x509 -req -extfile <(printf "subjectAltName=DNS:domain.org,DNS:www.domain.org") -days 1 -in domain.org.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -out domain.org.crt

However, over here the validity periods can be changed for only a single day. Does anyone know if there is an argument I could add to these that would let me vary the start date and the end date to the granularity of seconds, or minutes. For testing purposes, I need to create several certificates whose validity periods vary for just a few minutes. I've looked at other answers, and they suggest using the ca command:
openssl ca -config /path/to/myca.conf -in req.csr -out ourdomain.pem \
-startdate 0801010000Z -enddate 1001010000Z

But I am not sure how to combine the two since the second command only seems to be generating a key for the domain. Could anyone help combining the two commands, and or changing cert times some other way that doesn't involve changing my system time.

A: openssl command line does not provide command line options to set the start and end dates for the "x509 -req" option.
If you really need to do this, you can modify the openssl source to do what you want.
In the app\req.c you need to modify the "set_cert_times" call:
    if (days == 0) {
        /* set default days if it's not specified */
        days = 30;
    }
    if (!set_cert_times(x509ss, NULL, NULL, days))
        goto end;

int set_cert_times(X509 *x, const char *startdate, const char *enddate,
                   int days)

If you provide a startdate and enddate it will override the days parameter soyou can do this:
if (!set_cert_times(x509ss, "0801010000Z", "1001010000Z", days))
    goto end;

That will hardcode the start and end dates or with a little bit more work you can add support for the -startdate and -enddate parameters to the x509 -req processing.


text:
Q: How to show the highest percentage of each column in dataframe on the plot I have flights dataset that contains

3 columns ('on_time', 'early','delayed')
12 rows (months)

To illustrate departure time in each month, I have did staked bar plot on it.
My question is how to show on the plot the highest percentage of each column('on_time', 'early','delayed') compared to the total flights in the months.
for example:

on_time: 10% of flights in August
early: 70% of flights in October
delayed: 80% of flights in June

from mlxtend.plotting import stacked_barplot
fig= stacked_barplot(df,rotation=45,legend_loc='best')
fig.text(??)
fig.show()

A: You can add a table to your bar chart to display the data and highlight specific data.
For example (highly inspired by table)
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(3,12)
for i in range(0,12):
    data[:,i]=data[:,i]/sum(data[:,i])*100.0

columns = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Nov', 'Oct', 'Dec')
rows = ['on_time', 'early', 'delayed']

values = np.arange(0, 110, 10)
value_increment = 1

colors = np.zeros((3,3))
colors[0,0]=0.5
colors[1,1]=0.5
colors[2,2]=0.5
n_rows = len(data)
n_columns = len(data[0])

index = np.arange(len(columns)) + 0.3
bar_width = 0.4

# Initialize the vertical-offset for the stacked bar chart.
y_offset = np.zeros(len(columns))

# Plot bars and create text labels for the table
cell_text = []
colors_cell = np.ones((3,12,3))
p=list()
for row in range(n_rows):
    p.append(plt.bar(index, data[row,:], bar_width, bottom=y_offset, color=colors[row]))
    #
    y_offset = y_offset + data[row,:]
    cell_text.append(['%1.1f' % (x) for x in data[row]])
plt.legend((p[0][0], p[1][0], p[2][0]), ('on_time', 'early', 'delayed'))
for column in range(n_columns):
    arg_i = np.argmax(data[:,column])
    colors_cell[2-arg_i, column, 0] = 0.5
    colors_cell[2-arg_i, column, 1] = 0.5
    colors_cell[2-arg_i, column, 2] = 0.5
# Reverse colors and text labels to display the last value at the top.
colors = colors[::-1]
cell_text.reverse()

# Add a table at the bottom of the axes
the_table = plt.table(cellText=cell_text,
                      cellColours=colors_cell,
                      rowLabels=rows,
                      rowColours=colors,
                      colLabels=columns,
                      loc='bottom')
# Adjust layout to make room for the table:
plt.subplots_adjust(left=0.2, bottom=0.2)

plt.yticks(values * value_increment, ['%d' % val for val in values])
plt.xticks([])

plt.show()


text:
Q: How can I notify that the `DataContext` was replaced? How can I notify that the DataContext was replaced? Say I have a UserControl:
public partial class MyUserControl : UserControl {
    ...
    void OnSomethingHappens_Change_DataContext () {
        DataContext = new MyViewModelType();
    }
}

When I call OnSomethingHappens_Change_DataContext() all bindings cease to function. My current workaround implements INotifyPropertyChanged:
public partial class MyUserControl : UserControl, INotifyPropertyChanged {
    ...
    void OnSomethingHappens_Change_DataContext () {
        DataContext = new MyViewModelType();
        PropertyChanged(this, new PropertyChangedEventArgs("DataContext"));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

But it feels awkward to make a UserControl implement INotifyPropertyChanged. I tried:
    void OnSomethingHappens_Change_DataContext () {
        var oldDataContext = DataContext;
        DataContext = new MyViewModelType();
        OnPropertyChanged(new DependencyPropertyChangedEventArgs(DataContextProperty, oldDataContext, DataContext));
    }

But it doesn't work, no idea why...


text:
Q: How to use groovy constant from Shared Libray in Jenkins file (pipeline)? I want use grrovy constant from Shared Libray in my Jenkins pipeline. I try this but I have this error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: WorkflowScript: 27: Not a valid stage section definition: "def paramChecker = ParameterChecker.new(this)". Some extra configuration is required. @ line 27, column 9. stage('Checkout') {
def libIdentifier = "project-jenkins-pipeline"
def libGitBranch = params.LIB_GIT_BRANCH
if(libGitBranch) {
    libIdentifier += "@${libGitBranch}"
}

def com = library(identifier: libIdentifier, changelog: false).com

def Constants = com.project.Constants
def ParameterChecker = com.project.ParameterChecker

pipeline {
    agent {
        docker {
            label "linux"
            image "my-host:8082/project-build-java:jdk1.6-jdk1.8-mvn3.2.5"
            registryUrl 'http://my-host:8082'
            registryCredentialsId 'ReadNexusAccountService'
        }
    }
    stages {
        stage('Clean workspace') {
            steps {
                deleteDir()
            }
        }
        stage('Checkout') {
            def paramChecker = ParameterChecker.new(this)
            paramChecker.checkProjectAndBranchNames()
            checkoutGitSCM(
                url: "${Constants.BITBUCKET_URL}/${paramChecker.projectName}.git",
                tag: Constants.GIT_PROJECT_DEFAULT_BRANCH
            )
        }
        stage('Compilation Maven') {
            steps {
                timestamps {
                    sh 'mvn -version'
                }
            }
        }
    }
}

A: I had script in steps in stage('Checkout')
def libIdentifier = "project-jenkins-pipeline"
def libGitBranch = params.LIB_GIT_BRANCH
if(libGitBranch) {
    libIdentifier += "@${libGitBranch}"
}

def com = library(identifier: libIdentifier, changelog: false).com

pipeline {
    agent {
        docker {
            label "linux"
            image "my-host:8082/project-build-java:jdk1.6-jdk1.8-mvn3.2.5"
            registryUrl 'http://my-host:8082'
            registryCredentialsId 'ReadNexusAccountService'
        }
    }
    stages {
        stage('Clean workspace') {
            steps {
                deleteDir()
            }
        }
        stage('Checkout') {
            steps {
                script {
                    def Constants = com.project.Constants
                    def ParameterChecker = com.project.ParameterChecker
                    def paramChecker = ParameterChecker.new(this)
                    paramChecker.checkProjectAndBranchNames()
                    checkoutGitSCM(
                        url: "${Constants.BITBUCKET_URL}/${paramChecker.projectName}.git",
                        tag: Constants.GIT_PROJECT_DEFAULT_BRANCH
                    )
                }
            }
        }
        stage('Compilation Maven') {
            steps {
                timestamps {
                    sh 'mvn -version'
                }
            }
        }
    }
}

Thanks at @Matt Schuchard and Jenkins: Cannot define variable in pipeline stage


text:
Q: What are different types of string/int as in data types that can be input by the person playing a game in python. (I am using pycharm) How to input an integer data type as a user playing a game? I have tried many things but they don't work. I have tried inputing numbers but they still are strings not integers.

A: In python3 use:
x = int(input(3))

and in python2 use:
input(3)


text:
Q: readObject hangs the application I'm trying to create a live messenger application. But the code hangs when trying to readObject from an ObjectInputStream with no reason. No exception is thrown.
try {
    System.out.println("Trying to connect to server");
    socket = new Socket(InetAddress.getByName("localhost"),6789);
    System.out.println("Connected to server");

    inputStream = new ObjectInputStream(socket.getInputStream());

    outputStream = new ObjectOutputStream(socket.getOutputStream());
    outputStream.flush();

    System.out.println("Streams are set up.");

    window.toggleTyping(true);
    System.out.println("Typing is now enabled");

    String inputMsg = null;

    do {
        try {
            System.out.println("Reading object");
            inputMsg = (String)inputStream.readObject();
            System.out.println("Object read");

        } catch(ClassNotFoundException ee) {
            System.out.println("Clas not found exception");
            ee.printStackTrace();
        }

    } while(!inputMsg.equalsIgnoreCase("/exit"));

    closeConnection();

}catch(IOException ex) {
    ex.printStackTrace();
}

The last message that is printed is "Reading object".
 try {
        serverSocket = new ServerSocket(6789);
            System.out.println("Socket created. About to accept connections");
            Socket s = serverSocket.accept();
            new Thread(new Chat(s)).start();

    } catch(IOException e) {
        e.printStackTrace();
    }

And the class Chat:
    public class Chat implements Runnable {

private Socket socket;
private ObjectOutputStream outputStream;
private ObjectInputStream inputStream;

public Chat(Socket s) {
    System.out.println("Chat class constructor called");
    this.socket = s;

    try {
        outputStream = new ObjectOutputStream(socket.getOutputStream());
        outputStream.flush();

        inputStream = new ObjectInputStream(socket.getInputStream());
        System.out.println("Chat streams are now set up");

    }catch(IOException ex) {
        ex.printStackTrace();
    }

}
private void closeChat() {
    try {
        outputStream.close();
        inputStream.close();
        socket.close();
        System.out.println("Chat is now closed");
    }catch(IOException ex) {
        ex.printStackTrace();
    }

}

@Override
public void run() {
    System.out.println("Chat class method run called");
    try {
        outputStream.writeObject("Connection is cool");
        outputStream.flush();
        System.out.println("Text sent");
        String inputMsg = "";
        do {

            try {
                inputMsg = (String)inputStream.readObject();
                System.out.println("Message read:"+inputMsg);
            }catch(ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        while(!inputMsg.equalsIgnoreCase("/exit"));
        closeChat();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}
}

The reason every chat is a different thread is that I'm planning to implement multiple one on one chats someday.

A: This is because the reading method is a blocking method. This means it is trying to read until it gets a -1 to show that the read data are finished. Ensure that the OutputStream which writes to this socket is sending this. So you invoke at sending socket the ObjectOutputStream.flush(); method after you wrote the data or just close the output stream after writing. Closing this one would'nt be reasonable, because probably you may want to send further data throug this stream later.

Just a general thing: You don't need to flush the outputstream immediatley after you have created it


text:
Q: IngressRoute for Kubernetes-Dashboard using Traefik I'm moving my project to Kubernetes using Traefik for routing and MetalLB as my load balancer.
I've deployed several apps and I'd like to make use of official Kubernetes-Dashboard. So I deployed the Kubernetes-Dashboard using recommended config and created IngressRoute:
# dashboard.yaml
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: kubernetes-dashboard
  namespace: kubernetes-dashboard
spec:
  entryPoints:
    - websecure
  routes:
    - match: Host(`k8s.example.com`, `www.k8s.example.com`)
      kind: Rule
      middlewares:
        # - name: https-redirectscheme
        # - name: nginx-basic-auth
      services:
        - kind: Service
          name: kubernetes-dashboard
          # namespace: kubernetes-dashboard
          port: 443
  tls:
    secretName: k8s.example.com-tls

It shows up in the Traefik Dashboard, but when I try to access k8s.example.com I get Internal Server Error.
Thank you

A: I had the same problem - which is why I ended on this question. When I find out how to use the IngressRoute I'll update this answer.
This answer describes how to use NodePort instead.
kubectl patch svc kubernetes-dashboard -p '{"spec": {"type": "NodePort"}}'
# Confirm
kubectl get svc -n kubernetes-dashboard kubernetes-dashboard -o yaml

# patch the dashboard
tee ~/nodeport_dashboard_patch.yaml<<EOF
spec:
  ports:
  - nodePort: 32000
    port: 443
    protocol: TCP
    targetPort: 8443
EOF

kubectl patch svc kubernetes-dashboard --patch "$(cat ~/nodeport_dashboard_patch.yaml)"

Now the dashboard can be reached on the external IP Traefik gave you - in collaboration with MetalLB - with port :32000.
If you have a website routed to your cluster, you can use:
https://yourwebsite.com:32000

As described in the link you shared, fetch the token by using:
export SA_NAME= # admin user from the ServiceAccount
kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | grep ${SA_NAME} | awk '{print $1}')

(I could change this answer for a complete script to do this; If you'd like)

A: Found the answer here: https://stackoverflow.com/a/69999245/3883694
You can disable SSL certificate verification.
https://doc.traefik.io/traefik/routing/overview/#transport-configuration
---
apiVersion: traefik.containo.us/v1alpha1
kind: ServersTransport
metadata:
  name: traefik-dashboard-transport
  namespace: traefik
spec:
  serverName: traefik-dashboard
  insecureSkipVerify: true
---
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: dashboard
spec:
  entryPoints:
    - web
  routes:
    - match: (PathPrefix(`/dashboard`) || Host(`traefik.example.com`))
      kind: Rule
      services:
      - name: api@internal
        kind: TraefikService
      serversTransport: traefik-dashboard-transport


text:
Q: How do I construct a matrix from a dataframe that takes one of the columns from the dataframe and uses it as the column variables of the matrix? I have a dataframe with three columns - state names, dates, and a numerical values.
The matrix I am trying to create needs to have the state names as row names, and the dates as the column names, with the numerical values within the matrix. Obviously, there will be many NA values within the matrix. (there are 51 'states' and 84 dates). I've been working on this all day and the closest I've gotten is creating a dataframe with the correct number of dates and state names corresponding to each other, but the numerical values don't match up.
there are 84 dates, but not every state has 84 corresponding dates.
Goal = all states only are listed once alphabetical order... all dates only listed once... fill in empty spaces w/ NA

Thanks

A: Welcome to stackoverflow. When you post a question on stackoverflow it's better if you include an example of the data that you are trying to produce, look there : reproducible example. You'll get much faster responses even if your questions are trivial.
Below, most of the lines of code do reproduce your example :
# create vector of random dates
dates <- as.Date(sample( as.numeric(as.Date('2015-01-01')): as.numeric(as.Date('2018-01-01')), 200,
        replace = T),
    origin = '1970-01-01')
# create vector of states
library(datasets)
data(state)
name<-state.name
# create random number
values <- rnorm(50)

This is one of the ways to produce what you want
require(tidyverse)
df <- data.frame(dates, name, values)
df%>%spread(key=dates,value=values)%>%head(20)


text:
Q: Using Match() instead of Find() in Excel macro I've been using a macro for about 11 years without any problems. However, over the past 18 months some of the workbooks I've been using it on are very large and in these cases the macro can take a long time to run.
To address this I modified the macro to disable events and screen updating, and to make calculations 'manual'. This significantly improved things, but sometimes the improvements aren't enough.
For example, yesterday I ran the macro to compare a list of 288,000 email addresses against another list of 235,000 email addresses to identify any matches. This took about 14 hours to complete (and therefore beyond a typical work day).
I've done some research (1, 2, etc) and have identified that using Match() will be much faster than Find().
However, I am having problems modifying the code to use Match(). Below is the current working code that uses Find():
Sub FindMatchingData()

Application.EnableEvents = False
Application.Calculation = xlManual
Application.ScreenUpdating = False

Dim MySearchRange As Range
Dim c As Range
Dim findC As Variant

Set MyRange = Application.InputBox( _
Prompt:="Select the range of cells containing the data you are looking for:", Type:=8)

Set MySearchRange = Application.InputBox( _
    Prompt:="Select the range you wish to investigate:", Type:=8)

Response = InputBox(Prompt:="Specify the comment you wish to appear to indicate the data was found:")

MyOutputColumn = Application.InputBox( _
Prompt:="Enter the alphabetical column letter(s) to specify the column you want the message to appear in.")

Set Sht = MyRange.Parent

  For Each c In MyRange
    If Not c Is Nothing Then

Set findC = MySearchRange.Find(c.Value, LookIn:=xlValues)

        If Not findC Is Nothing Then
           Sht.Range(MyOutputColumn & c.Row).Cells.Value = Response
        End If
    End If
  Next
Excel.Application.SendKeys Keys:="^{HOME}", Wait:=True
DoEvents

Application.EnableEvents = True
Application.Calculation = xlAutomatic
Application.ScreenUpdating = True

MsgBox "Investigation completed."

End Sub

QUESTION:

*

*Can someone advise whether the above code can be amended easily to
use Match() instead, or am I better off starting totally from
scratch?

*If it can be amended, any help would be greatly appreciated
as I seem to be hitting a brick wall.

ADDITIONAL INFO: EXPECTED BEHAVIOUR OF THE MACRO
This macro provides an easy way for users to find matching data between two ranges, either within the same worksheet or across worksheets within the same workbook.
The expected behaviour is as follows:

*

*it prompts the user to:

*

*select the range containing the data they're looking for

*select the range to be searched to see if the data also exists there

*enter a comment that is used to indicate any matching data

*enter the column you want the comment populated into if a match was found

*Excel then proceeds to run the comparison between the selected ranges and starts populating the selected column wherever matches are found.

*When complete it presents the user with an Investigation completed message.

For example, if the user selects range A2:A40000 in Sheet 1 as containing the data to look for, and then selects range C2:C2000 in Sheet 2 as the range to search, and then enters the word "Yes" as the comment followed by selecting D as the column, the expected result when complete is that the user will see that cells in Column D in Sheet 1 will contain the word "Yes" if the data was found.

A: As the article you linked and I did in the comments says, loop arrays they are quicker than either Find or Match and use a for loop:
Sub FindMatchingData()

    Application.EnableEvents = False
    Application.Calculation = xlManual
    Application.ScreenUpdating = False

    Dim MySearchRange As Range
    Dim c As Range
    Dim findC As Variant

    Set myrange = Application.InputBox( _
    Prompt:="Select the range of cells containing the data you are looking for:", Type:=8)

    Dim myRangeArray As Variant
    myRangeArray = myrange.Value

    Set MySearchRange = Application.InputBox( _
        Prompt:="Select the range you wish to investigate:", Type:=8)

    Dim MSRArray As Variant
    MSRArray = MySearchRange.Value

    Dim Response As String
    Response = InputBox(Prompt:="Specify the comment you wish to appear to indicate the data was found:")

    myoutputcolumn = Application.InputBox( _
    Prompt:="Enter the alphabetical column letter(s) to specify the column you want the message to appear in.")

    Dim outArray As Variant
    ReDim outArray(1 To UBound(myRangeArray, 1), 1 To 1)

    Set sht = myrange.Parent

    Dim i As Long
    For i = 1 To UBound(myRangeArray, 1)
        Dim j As Long
        For j = 1 To UBound(MSRArray, 1)
            If myRangeArray(i, 1) = MSRArray(j, 1) Then
                outArray(i, 1) = Response
                Exit For
            End If
        Next j
    Next i

    sht.Cells(myrange.Row, myoutputcolumn).Resize(UBound(outArray, 1), 1).Value = outArray

    sht.Activate
    sht.Range("A1").Select

    Application.EnableEvents = True
    Application.Calculation = xlAutomatic
    Application.ScreenUpdating = True

    MsgBox "Investigation completed."

End Sub


text:
Q: How to use pf to route this scenario Scenario
I need pf on a Mac to do this: redirecting any connections to localhost:8080 to a public domain.
--> localhost:8080 --> public domain
Example
The public domain is hosting a nginx server. On my laptop, if I use curl -H'Host: public.com' localhost:8080 then:

*

*The server behind that public domain must receive a connection with correct Host header - public.com not localhost

*curl returns nginx default page


text:
Q: Word for lover of war, beginning with a B? I know there is a word beginning with the letter B for someone who loves war and loves to conjure up support of war?

A: I think you're looking for bellicose.

bellicose
  (adjective)
  demonstrating aggression and willingness to fight:
  a mood of bellicose jingoism

So: "a bellicose person".
As well, you could use the noun form , "bellicosity", to refer to a person's disposition.

His bellicosity always led him into conflicts with his neighbors.

NB: There is no agent form of bellicose, nor usage of the adjective as noun (see: He's a belligerent, don't listen to him.)

A: "Belligerent" is not a bad choice. I've heard it used to describe people who like to fight and/or engage in war. However, that usage is kind of a stretch. It really only means "engaged in war" (whether you like it or not).
A better choice would be "warmonger," which refers to a person who "encourages warfare" (which is closer to the "lover of war" that you asked about).
I hope this helps :)


text:
Q: Put a value out of a http request in swift To create a UITableView I have to initialize the number of rows, and in my case it depends on an HttpRequest (Sent with the Framework HttpSwift). My problem is that I can't output the number on the return of my request
request.GET("/media/", parameters: nil, completionHandler:{
    (response: HTTPResponse) in
        if let err = response.error {
            println("error: \(err.localizedDescription)")
            return //also notify app of failure as needed
        }
        if let data = response.responseObject as? NSData {
            let str = NSString(data: data, encoding: NSUTF8StringEncoding)
            var user = Medias(JSONDecoder(data))
            var nbRows:Int = user.medias.count
        }
})

println(nbRows) //NbRows don't have a value out of the request

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nbRows
}

A: The problem is that the request is performed in a background thread and the execution continues sequentially. Then when you do println(nbRows) the nbRows variable is not updated as the request has not been made yet or is being made.
So to fix this, make nbRows a global variable and then reload the tableView when the variable is set.
Use the following code:
request.GET("/media/", parameters: nil, completionHandler: {(response: HTTPResponse) in
            if let err = response.error {
                println("error: \(err.localizedDescription)")
                return //also notify app of failure as needed
            }
            if let data = response.responseObject as? NSData {
                let str = NSString(data: data, encoding: NSUTF8StringEncoding)
                //println(str)
                var user = Medias(JSONDecoder(data))
                self.nbRows = user.medias.count   // make nbRows a globalVariable
                println(nbRows)
                // need to update tableView in the main thread
                dispatch_async(dispatch_get_main_queue(), {
                    // reload the tableView
                    self.tableView.reloadData()
                })
            }
        })

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nbRows
}


text:
Q: JavaScript if/else issue: 'Yes" is treated as 'No' due to being case sensitive I am new at learning JS, and I wrote my own version of one of the exercises I was doing to try and remember what I had learned. Here is what I wrote:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<script>

alert("Good morning!");
var hire = prompt("Are you here because you're interested in hiring me?");

if (hire === "yes") {
    alert("You've just made my day. Carry on.")
}

else {
    alert("Well, I hope you're at least thinking about it.")
}

</script>

</body>
</html>

The problem is, if you don't type 'yes' in all lowercase letters, it assumes that the answer falls under the 'else' category and spits out the wrong answer. I have been reading about ways to convert it to uppercase, but I still can't figure out what extra code it needs. Thanks.

A: You should use .toLowerCase() in order to force their response to be in lower case. Then you can check against it always being in lower case.
if (hire.toLowerCase() === 'yes') {
    alert('You\'ve just made my day. Carry on.');
} else {
    alert('Well, I hope you\'re at least thinking about it.');
}

A: this would be fine
    <!DOCTYPE html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    </head>

    <body>

    <script>

    alert("Good morning!");
    var hire = prompt("Are you here because you're interested in hiring me?");

    if (hire.toLowerCase() === "yes") {
        alert("You've just made my day. Carry on.")
    }

    else {
        alert("Well, I hope you're at least thinking about it.")
    }

    </script>

    </body>
    </html>


text:
Q: Including comma's in a CSV file without delineation? I have a database of which I am exporting each tables contents into a .csv file. Some of the text from my database contains commas.  In some cases commas are needed to separate the columns in the .csv file but others are part of the text and I don't want them to have this affect.
How do I include commas in a .csv file without having them read as column separaters?
Is there any possible way of going about this.  I know I can escape the comma but I don't want this escape character to appear in my .csv file.  Is there any other approach to dealing with this?
I'm using an Sqlite D'base with C++.
I have tried the below and I'm still having some problems.  If I want to add a string of words containing a comma to some text then I would do this.
string x = "\"This is, a test\""; and this works fine.  All the text goes into one cell in my .csv file read by excel with no delineation.
But, If I have two strings and want to insert a comma which will be read as a comma an not as a delineator in my .csv file then how do I do it.
Below I have used the 'comma' variable to hold a comma but and tried to insert this into variable c.  No errors when building it but when that is inserted into a .csv file the comma is recognized as a delineator.
I have used many variations of the escape operator with no luck.  Any clues as to how to go about this?
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

ofstream output;

int main()
{
   output.open("file.csv",ios::out |ios::binary);
   string comma = ",";
   string a = "\"This is, a test\"";
   string b = "This is, a test";
   string c = "test1"+ comma+"test2";

   output << a << endl << b << endl << c << endl;
}