text:
Q: ipset rules on iptables do not match I want to block all ip Adresses except from a specific country. So i installed ipset and downloaded the ip range list from ipdeny.com and did this:
ipset create allow-list hash:net
for i in $( cat /home/pi/firewall/country-aggregated.zone ); do sudo ipset -A allow-list $i; done

If i do "sudo ipset list":
Name: allow-list
Type: hash:net
Revision: 6
Header: family inet hashsize 1024 maxelem 65536
Size in memory: 5408
References: 0
Number of entries: 97
Members:
89.183.60.0/22
etc...

Then i have to add a rule to the DOCKER-USER and INPUT to block all services. To test it, i blocked the country and tested if i could access the services and still i could. So something is wrong with my configuration.
sudo iptables -I DOCKER-USER -m set --match-set allow-list src -j DROP
sudo iptables -A INPUT -m set --match-set allow-list src -j DROP

My iptable filter tables (iptables -L -v -n) with DOCKER-USER chain and INPUT chain looks like this:
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
  310 19940 ACCEPT     all  --  *      *       192.168.1.102        0.0.0.0/0
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0            match-set allow-list src

Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
3564K 2076M DOCKER-USER  all  --  *      *       0.0.0.0/0            0.0.0.0/0
3564K 2076M DOCKER-ISOLATION-STAGE-1  all  --  *      *       0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
    0     0 DOCKER     all  --  *      docker0  0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  docker0 docker0  0.0.0.0/0            0.0.0.0/0
 5350 2397K ACCEPT     all  --  *      br-c80792c5d0cc  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
 6261  414K DOCKER     all  --  *      br-c80792c5d0cc  0.0.0.0/0            0.0.0.0/0
11135 1009K ACCEPT     all  --  br-c80792c5d0cc !br-c80792c5d0cc  0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  br-c80792c5d0cc br-c80792c5d0cc  0.0.0.0/0            0.0.0.0/0
3037K 1724M ACCEPT     all  --  *      br-89ecb09e5185  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
29923 1796K DOCKER     all  --  *      br-89ecb09e5185  0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  br-89ecb09e5185 !br-89ecb09e5185  0.0.0.0/0            0.0.0.0/0
29923 1796K ACCEPT     all  --  br-89ecb09e5185 br-89ecb09e5185  0.0.0.0/0            0.0.0.0/0
   69 10621 ACCEPT     all  --  *      br-451331e576b8  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
   10  1222 DOCKER     all  --  *      br-451331e576b8  0.0.0.0/0            0.0.0.0/0
    0     0 ACCEPT     all  --  br-451331e576b8 !br-451331e576b8  0.0.0.0/0            0.0.0.0/0
   10  1222 ACCEPT     all  --  br-451331e576b8 br-451331e576b8  0.0.0.0/0            0.0.0.0/0
 349K  210M ACCEPT     all  --  *      br-2db6a76ed3c5  0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
31128 1866K DOCKER     all  --  *      br-2db6a76ed3c5  0.0.0.0/0            0.0.0.0/0
94113  135M ACCEPT     all  --  br-2db6a76ed3c5 !br-2db6a76ed3c5  0.0.0.0/0            0.0.0.0/0
29958 1798K ACCEPT     all  --  br-2db6a76ed3c5 br-2db6a76ed3c5  0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain DOCKER (5 references)
 pkts bytes target     prot opt in     out     source               destination
 1170 68000 ACCEPT     tcp  --  !br-2db6a76ed3c5 br-2db6a76ed3c5  0.0.0.0/0            172.25.0.2           tcp dpt:8080
    0     0 ACCEPT     tcp  --  !br-c80792c5d0cc br-c80792c5d0cc  0.0.0.0/0            172.28.0.2           tcp dpt:443
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:30009
    0     0 ACCEPT     tcp  --  !br-451331e576b8 br-451331e576b8  0.0.0.0/0            172.20.0.3           tcp dpt:80
    0     0 ACCEPT     tcp  --  !br-c80792c5d0cc br-c80792c5d0cc  0.0.0.0/0            172.28.0.2           tcp dpt:80
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:30008
    0     0 ACCEPT     udp  --  !br-c80792c5d0cc br-c80792c5d0cc  0.0.0.0/0            172.28.0.2           udp dpt:67
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:30007
    0     0 ACCEPT     tcp  --  !br-c80792c5d0cc br-c80792c5d0cc  0.0.0.0/0            172.28.0.2           tcp dpt:53
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:30006
 6261  414K ACCEPT     udp  --  !br-c80792c5d0cc br-c80792c5d0cc  0.0.0.0/0            172.28.0.2           udp dpt:53
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:30005
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:30004
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:30003
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:3000Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination2
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:30001
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:30000
    0     0 ACCEPT     tcp  --  !docker0 docker0  0.0.0.0/0            172.17.0.2           tcp dpt:21

Chain DOCKER-ISOLATION-STAGE-1 (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DOCKER-ISOLATION-STAGE-2  all  --  docker0 !docker0  0.0.0.0/0            0.0.0.0/0
11135 1009K DOCKER-ISOLATION-STAGE-2  all  --  br-c80792c5d0cc !br-c80792c5d0cc  0.0.0.0/0            0.0.0.0/0
    0     0 DOCKER-ISOLATION-STAGE-2  all  --  br-89ecb09e5185 !br-89ecb09e5185  0.0.0.0/0            0.0.0.0/0
    0     0 DOCKER-ISOLATION-STAGE-2  all  --  br-451331e576b8 !br-451331e576b8  0.0.0.0/0            0.0.0.0/0
94113  135M DOCKER-ISOLATION-STAGE-2  all  --  br-2db6a76ed3c5 !br-2db6a76ed3c5  0.0.0.0/0            0.0.0.0/0
3564K 2076M RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain DOCKER-ISOLATION-STAGE-2 (5 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DROP       all  --  *      docker0  0.0.0.0/0            0.0.0.0/0
    0     0 DROP       all  --  *      br-c80792c5d0cc  0.0.0.0/0            0.0.0.0/0
    0     0 DROP       all  --  *      br-89ecb09e5185  0.0.0.0/0            0.0.0.0/0
    0     0 DROP       all  --  *      br-451331e576b8  0.0.0.0/0            0.0.0.0/0
    0     0 DROP       all  --  *      br-2db6a76ed3c5  0.0.0.0/0            0.0.0.0/0
 105K  136M RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

Chain DOCKER-USER (1 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0            match-set allow-list src
1831K 1083M RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

nat table (iptables -t nat -nvL)
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
 7467  484K DOCKER     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
    0     0 MASQUERADE  all  --  *      !docker0  172.17.0.0/16        0.0.0.0/0
 3957  267K MASQUERADE  all  --  *      !br-c80792c5d0cc  172.28.0.0/16        0.0.0.0/0
    0     0 MASQUERADE  all  --  *      !br-89ecb09e5185  172.24.0.0/16        0.0.0.0/0
    0     0 MASQUERADE  all  --  *      !br-451331e576b8  172.20.0.0/16        0.0.0.0/0
    5   392 MASQUERADE  all  --  *      !br-2db6a76ed3c5  172.25.0.0/16        0.0.0.0/0
    0     0 MASQUERADE  tcp  --  *      *       172.25.0.2           172.25.0.2           tcp dpt:8080
    0     0 MASQUERADE  tcp  --  *      *       172.28.0.2           172.28.0.2           tcp dpt:443
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:30009
    0     0 MASQUERADE  tcp  --  *      *       172.20.0.3           172.20.0.3           tcp dpt:80
    0     0 MASQUERADE  tcp  --  *      *       172.28.0.2           172.28.0.2           tcp dpt:80
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:30008
    0     0 MASQUERADE  udp  --  *      *       172.28.0.2           172.28.0.2           udp dpt:67
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:30007
    0     0 MASQUERADE  tcp  --  *      *       172.28.0.2           172.28.0.2           tcp dpt:53
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:30006
    0     0 MASQUERADE  udp  --  *      *       172.28.0.2           172.28.0.2           udp dpt:53
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:30005
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:30004
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:30003
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:30002
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:30001
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:30000
    0     0 MASQUERADE  tcp  --  *      *       172.17.0.2           172.17.0.2           tcp dpt:21

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
   21  1407 DOCKER     all  --  *      *       0.0.0.0/0           !127.0.0.0/8          ADDRTYPE match dst-type LOCAL

Chain DOCKER (2 references)
 pkts bytes target     prot opt in     out     source               destination
    0     0 RETURN     all  --  docker0 *       0.0.0.0/0            0.0.0.0/0
    0     0 RETURN     all  --  br-c80792c5d0cc *       0.0.0.0/0            0.0.0.0/0
    0     0 RETURN     all  --  br-89ecb09e5185 *       0.0.0.0/0            0.0.0.0/0
    0     0 RETURN     all  --  br-451331e576b8 *       0.0.0.0/0            0.0.0.0/0
    0     0 RETURN     all  --  br-2db6a76ed3c5 *       0.0.0.0/0            0.0.0.0/0
 1195 69492 DNAT       tcp  --  !br-2db6a76ed3c5 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:8080 to:172.25.0.2:8080
    0     0 DNAT       tcp  --  !br-c80792c5d0cc *       0.0.0.0/0            0.0.0.0/0            tcp dpt:443 to:172.28.0.2:443
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:30009 to:172.17.0.2:30009
    0     0 DNAT       tcp  --  !br-451331e576b8 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:6875 to:172.20.0.3:80
    0     0 DNAT       tcp  --  !br-c80792c5d0cc *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80 to:172.28.0.2:80
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:30008 to:172.17.0.2:30008
    0     0 DNAT       udp  --  !br-c80792c5d0cc *       0.0.0.0/0            0.0.0.0/0            udp dpt:67 to:172.28.0.2:67
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:30007 to:172.17.0.2:30007
    0     0 DNAT       tcp  --  !br-c80792c5d0cc *       0.0.0.0/0            0.0.0.0/0            tcp dpt:53 to:172.28.0.2:53
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:30006 to:172.17.0.2:30006
 6253  413K DNAT       udp  --  !br-c80792c5d0cc *       0.0.0.0/0            0.0.0.0/0            udp dpt:53 to:172.28.0.2:53
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:30005 to:172.17.0.2:30005
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:30004 to:172.17.0.2:30004
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:30003 to:172.17.0.2:30003
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:30002 to:172.17.0.2:30002
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:30001 to:172.17.0.2:30001
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:30000 to:172.17.0.2:30000
    0     0 DNAT       tcp  --  !docker0 *       0.0.0.0/0            0.0.0.0/0            tcp dpt:21 to:172.17.0.2:21

mangle table (iptables -t mangle -L -nv):
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

raw table:
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

The server is a raspberry pi.
What could be the problem?

A: I spoke with my isp and its their fault. They have an weird network. So i always only get an internal ip address from every package that arrive.


text:
Q: large variance from inverse probability weighting (inverse propensity score) I heard if the observed data that will be used in the inverse probability weighting method is too small, the estimator based on the weighting will have a large variance.
Could you explain why that is so?

A: In general, a small data set yields high variance in effect estimates. Weighting decreases the effective sample size of the weighted sample, which further increases the variance. The effective sample size is defined as $$ESS = \frac{(\sum{w})^2}{\sum{w^2}},$$ and when the weights are scaled to add up to the sample size $n$, is equal to $$\frac{n}{1+var(w)},$$where $var()$ is the population variance (i.e., $\frac{1}{n}\sum{(w-\bar{w})^2}$). From that formula, it's clear that if the weights are any different from each other, $var(w)$ will increase, and $ESS < n$.
In addition to this, small data sets increase the tendency of propensity score models to overfit, yielding very high and very low propensity scores. These themselves can dramatically increase the variance of weights, which will affect the effect sample size as previously described.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django Rest Framework - prevent access to API? I'm using Django Rest Framework and Token Authentication. Everything works great so far.
http://www.django-rest-framework.org/api-guide/authentication#tokenauthentication
But I'm realizing that anyone could create a third party app that hooks into my API. There'd be no way for me to detect it or stop it.
Am I missing something? I followed the directions, and I:

*

*Send "username=blah&password=blah" to https://example.com/api/auth/, and receive a Token in return. Anyone could do this from a third party app.

*That token is passed in the authentication header to retrieve data from the API. Anyone could do this if they have their user token.

Even if a user knows their own Token, I only want them to be able to access the API through the official native app.
1. How do I secure my API (using Token authentication) and make sure that only MY apps can connect to it?
2. Could I include some kind of secret key in a header? I'm using HTTPS in production, are headers as well as form data (username/password) interceptable/readable? (By the person running the app).
Still learning, thank you.

A: Perhaps I don't understand you question fully, but:
yes, everyone with a username and a password in your application can create tokens, if you added obtain_auth_token to your urlconfig (what you don't have to).
So you can:

*

*only give your apps username and password

*or deactivate the obtain_auth_token view and create the tokens in the admin or manually.

To answer your HTTPS question:
HTTPS encryption is between the client and the server and lies between TCP and HTTP. So everyone in between (a man in the middle) can't see any headers, data, or even the path. When using SNI the hostname (Host header) is visible, but nothing else.
Hope this helps a little.


text:
Q: How to set the sheet name for a C# generated Excel spreadsheet? We generate an Excel spreadsheet in our C# .net website by writing out an HTML table to Response. This works great, but the sheet name gets set to the same as the file name.
Is there away to set this? We require a certain sheet name when importing.
Code:
string filename = String.Format( "{0}-CopyDataBack_{1}.xls", Master.EventID.ToString(), DateTime.Now.ToString( "dd-MM-yy_HHmm" ) );

Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=" + filename );
Response.Charset = "";
this.EnableViewState = false;

System.Text.StringBuilder tableOut = new System.Text.StringBuilder();
// ... Create an HTML table in a StringBuilder ...
Response.Write( tableOut );
Response.End();

A: By creating a table and setting content-type to Excel you can't define a worksheet name, nor to create more worksheets.
You can to generate your complete Excel workbook by using OpenXML SDK, but your client will need to handle Office 2007 file formats by using Microsoft Office Compatibility Pack for Word, Excel, and PowerPoint 2007 File Formats.


text:
Q: How to get the correct frame of UICollectionViewCell in it's subclass I have a UICollectionView and I set it's cellSize in viewDidLoad:
    let cellWidth = self.view.frame.width / 2
    self.collectionViewFlowLayout.itemSize = CGSize(width: cellWidth, height: 100)`

I try to add a gradient layer to my custom UICollectionViewCell. But the frame size is the one I set from storyboard. I can't get the correct, calculated frame size in my UICollectionViewCell subclass's layoutSubviews method.
How am I going to get the correct frame size?


text:
Q: What is wrong with my redirect machanism? So I try to create a C++ web server with services and stuff. It is alive here, this is how to compile in in 3 lines under regular user on Linux, and here is it svn.
To redirect users I use such function:
void http_utils::send_found_302( std::string redirect_lication, boost::shared_ptr<boost::asio::ip::tcp::socket> socket, boost::shared_ptr<http_response> response )
{
    response->status = 302;
    response->description = "Found";
    response->headers.insert(std::pair<std::string, std::string>("Location", redirect_lication));
    response->send(*socket);
}

And in Chrome and Safary and IE. I can register and log in into my server. But FF... FF allows me to registe user in DB (meaning sends correct request), but when server trys to redirect it to page I want it shows me sad page=(
So example with pictures: we input credantials:

We hit on submit... and is gets stuck on connection for ever...:

When we try just to use that URL it tries to go to we see that it got part of "Found response" but has not redirected itself...( If we would try to login with chrome we would get all correct, also if we would just follow that url in chrome we would get redirected to where needed and see such image:

I created a simple user: demo_user@gmail.com with pass 123456 so you can try it out...
So what is wrong with the way I redirect? what shall be added to response to make it work for FF?

At the end of the day I made this:
   void http_utils::send_found_302( const std::string & redirect_lication, boost::shared_ptr<boost::asio::ip::tcp::socket> socket, boost::shared_ptr<http_response> response )
    {
            /* if there was no Fire Fox and probably other dull browsers we would do this (Chrome, IE, Safari tested):
             *
             *\code
                    response->status = 302;
                    response->description = "Found";
                    response->headers.insert(std::pair<std::string, std::string>("Location", redirect_lication));
                    response->send(*socket);
             * \endcode
             *
             * but indeed there are.
             *
             * We could also create simple HTML redirection page - would work anywhere.
             * \code
            std::ostringstream data_stream;
            data_stream << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"><meta http-equiv=\"refresh\" content=\"0; url= "
                    << redirect_lication << "\">
Please turn on JavaScript!
<a href=\""
                    << redirect_lication << "\">
Content awaits you here.
";
            response->headers.insert(std::pair<std::string, std::string>("Cache-Control", "max-age=0"));
            response->headers.insert(std::pair<std::string, std::string>("Pragma", "no-cache"));
            http_utils::send(data_stream.str(), socket, response);
             * \endcode
             *
             * so we decided to mix - html page and HTTP redirection
             */

            response->description = "Found";
            response->headers.insert(std::pair<std::string, std::string>("Location", redirect_lication));
            response->headers.insert(std::pair<std::string, std::string>("Content-Location", redirect_lication));
            response->headers.insert(std::pair<std::string, std::string>("Refresh", std::string("0; url=" + redirect_lication)));
            response->headers.insert(std::pair<std::string, std::string>("Cache-Control", "max-age=0"));
            response->headers.insert(std::pair<std::string, std::string>("Pragma", "no-cache"));
            std::ostringstream data_stream;
            data_stream << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"><meta http-equiv=\"refresh\" content=\"0; url= "
                    << redirect_lication << "\">
Please turn on JavaScript!
<a href=\""
                    << redirect_lication << "\">
Content awaits you here.
";

            http_utils::send(302, data_stream.str(), socket, response);

    }

Let me explain: Current FF did not like my 302 and 303 redirection... so Simple solution - was to move the battle to the other side - side of HTML so I created simple code that returns HTML page that would auto redirect user or at least present him with correct link. Tested it - all worked as was desired (with short local links). Than I added solution that also worked not only I send HTML page but, also relocation headers. This shall work anywhere, and if browser is smart it shall not load contents of redirection page at all...)
So now all works.=) And thanks to KayEss answer I made all links absolute now... Why not?)

A: For best portability the location header needs to be an absolute URL. It looks like you're trying to send a relative one.
I.e.:
Location: http://example.com/path/image.png

Instead of:
Location: image.png


text:
Q: has_one, reject_if, and accept_nested_attributes_for still triggers validation I'm trying to provide a place to set a single service login for an account, yet not require that the account owner enter the service login credentials every time the rest of the record is updated.
My understanding is that the :reject_if option on accepts_nested_attributes_for is the way to have the nested hash values ignored. Yet, in Rails 4.1, I'm getting a "password can't be blank".
I've traced through the nested_attributes code and it seems to properly ignore the values, yet nothing I do to avoid the update works. I've even deleted the web_service_user_attributes hash from the params passed to update, so I'm wondering if there is something else going on.
Am I understanding :reject_if correctly for a has_one association?
Parent model code:
class Account
  has_one :web_service_user

  accepts_nested_attributes_for :web_service_user, :allow_destroy => true, :reject_if => :password_not_specified, :update_only => true

  def password_not_specified(attributes)
    attributes[:password].blank?
  end
end

Child model code:
class WebServiceUser
  devise :database_authenticatable

  belongs_to :account

  validates_uniqueness_of :username
  validates_presence_of :password, if: Proc.new{|wsu| !username.blank? }
end

Controller code:
def update
  respond_to do |format|
    if @licensee.update(account_params)
  #etc...
end

private
def account_params
  params.require(:account).permit(:name, :area_of_business, :address1, :address2, :city, :state_code, :zip, :website_url, :web_service_user_attributes => [:id, :username, :password, :_destroy])
end

A: Ok, it appears that my primary goof was trying to validate the presence of :password. I really wanted to validate the length of the password if it existed.
class WebServiceUser
  devise :database_authenticatable

  belongs_to :account

  validates_uniqueness_of :username
  validates_length_of :password, :minimum => 14, if: Proc.new { |u| !u.password.nil? }
end


text:
Q: Can't update SQL database I'm creating a website in ASP.NET (in c#) with campaigns listed into a datalist (seperated from each other by using a
 in the datalist so each campaign is listed into a block).
I can't update a specific column in the Campaigns table via c# because it can't find the scalar variable @camp_id (the ID of the campaign).
I'm using this command to update:
sqlCmd = "UPDATE Campagnes SET camp_status=2 WHERE camp_id=@camp_id";

Someone who knows how to make it possible to update 'camp_status' to 2 by using the 'camp_id' so only the 'camp_status' of that specific campaign (and not from others in the datalist) will be updated?
Edit: this is my whole code I'm using:
    SqlConnection conn = new SqlConnection();
    SqlCommand cmd = new SqlCommand();

    string sqlConn;
    string sqlCmd;

    sqlConn = @"Data Source=my-ip,1433;Initial Catalog=DbName;
    Integrated Security=False;user id=sa;password=password";
    sqlCmd= "UPDATE Campagnes SET camp_status=2 WHERE camp_id=@camp_id";

    conn.ConnectionString = sqlConn;
    cmd.Connection = conn;
    cmd.CommandText = sqlCmd;
    conn.Open();

    cmd.ExecuteNonQuery();

    conn.Close();

So as you can see I'm not using parameters yet because I don't know how to add this and how it reads the value from the database.
The full code I'm using at the moment:
SqlConnection conn2 = new SqlConnection();
        SqlCommand cmd2 = new SqlCommand();

        string sqlConn2;
        string sqlCmd2;

        sqlConn2 = @"Data Source=my-ip,1433;Initial Catalog=dbname;Integrated Security=False;user id=sa;password=password";
        sqlCmd2 = "select * from Campagnes";

        conn2.ConnectionString = sqlConn2;
        cmd2.Connection = conn2;
        cmd2.CommandText = sqlCmd2;
        conn2.Open();

        SqlDataReader dr = cmd2.ExecuteReader();

        while (dr.Read())
        {
            id = dr.GetInt32(0);

            SqlConnection conn = new SqlConnection();
            SqlCommand cmd = new SqlCommand();

            string sqlConn;
            string sqlCmd;

            sqlConn = @"Data Source=my-ip,1433;Initial Catalog=dbname;Integrated Security=False;user id=sa;password=password";
            sqlCmd = "UPDATE Campagnes SET camp_status=1 WHERE camp_id=" + id;

            cmd.Parameters.AddWithValue("@camp_id", id);

            conn.ConnectionString = sqlConn;
            cmd.Connection = conn;
            cmd.CommandText = sqlCmd;
            conn.Open();

            cmd.ExecuteNonQuery();

            conn.Close();
        }

Can't upload my image right here so here an external link to the screenshot: http://i.imgur.com/P8MeKm4.png
As you can see in the image, all the seperated white blocks are one datalist, but seperated by a div that will be generated when a new campaign will be added. When we click the edit button in the bottom of the right, the camp_status needs to be set to 2 (so the admin knows that the campaign needs to be edited).
ASP Source:
    div id="popUpPanel">

Waarom vindt u dat deze campagne nog niet in orde is? Geef uw feedback hieronder in:

                <asp:TextBox ID="TextBox1" CssClass="box" TextMode="MultiLine" runat="server"></asp:TextBox>
                <asp:Button ID="Button1" OnClick="Button1_Click"  runat="server" Text="OK" />

            <asp:DataList CellPading="5" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" style="margin-right: 0px" >
                <ItemTemplate>

                     <asp:Label ID="titelLabel" runat="server" style="font-size: xx-large" Text='<%# Eval("titel") %>' />

                        <asp:Label ID="Label1" runat="server" style="font-size: xx-large; display: none;" Text='<%# Eval("camp_id") %>' />

                    <asp:Label ID="datum_geplaatstLabel"  runat="server" Text='<%# Eval("datum_geplaatst") %>' />

                        Korte beschrijving:

                    <asp:Label ID="korte_beschrijvingLabel"  runat="server" Text='<%# Eval("korte_beschrijving") %>' />

                        Lange beschrijving:

                    <asp:Label ID="lange_beschrijvingLabel" runat="server" Text='<%# Eval("lange_beschrijving") %>' />

                                    <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/edit.png" OnClientClick="showPopUp(); return false;" Style="margin-left:9px;" />

                                    <asp:ImageButton ID="ImageButton1" runat="server" asp:Imagebutt="" ImageUrl="~/img/vink.png" Style="margin-left:0px;" />

                </ItemTemplate>
            </asp:DataList>

            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebhoostConnectionString %>" SelectCommand="SELECT [titel], [datum_geplaatst], [korte_beschrijving], [lange_beschrijving], [camp_id] FROM [Campagnes]"></asp:SqlDataSource>

So when we click on the 'Button1' in the PopupPanel the camp_status needs to be set to 2 only of that specific campaign. As you can see in the source I was also trying to use the label I was talking about, but everytime a new div is created, all coming labels will have 'Label1' as ID so it will also pick all campaign ID's and not just one..

ASP source code (using the CommandArgument in the button):

Waarom vindt u dat deze campagne nog niet in orde is? Geef uw feedback hieronder in:

            <asp:TextBox ID="TextBox1" CssClass="box" TextMode="MultiLine" runat="server"></asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Submit" CommandArgument='<%= Campagnes.camp_id %>' />

        <asp:DataList CellPading="5" ID="DataList1" runat="server" DataSourceID="SqlDataSource1" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" style="margin-right: 0px" >
            <ItemTemplate>

                 <asp:Label ID="titelLabel" runat="server" style="font-size: xx-large" Text='<%# Eval("titel") %>' />

                    <asp:Label ID="Label1" runat="server" style="font-size: xx-large; display: none;" Text='<%# Eval("camp_id") %>' />

                <asp:Label ID="datum_geplaatstLabel"  runat="server" Text='<%# Eval("datum_geplaatst") %>' />

                    Korte beschrijving:

                <asp:Label ID="korte_beschrijvingLabel"  runat="server" Text='<%# Eval("korte_beschrijving") %>' />

                    Lange beschrijving:

                <asp:Label ID="lange_beschrijvingLabel" runat="server" Text='<%# Eval("lange_beschrijving") %>' />

                                <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/edit.png" OnClientClick="showPopUp(); return false;" Style="margin-left:9px;" />

                                <asp:ImageButton ID="ImageButton1" runat="server" asp:Imagebutt="" ImageUrl="~/img/vink.png" Style="margin-left:0px;" />

            </ItemTemplate>
        </asp:DataList>

        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:WebhoostConnectionString %>" SelectCommand="SELECT [titel], [datum_geplaatst], [korte_beschrijving], [lange_beschrijving], [camp_id] FROM [Campagnes]"></asp:SqlDataSource>

C# source code (edited EventArgs to CommandEventArgs e):
string id;

    SqlConnection conn2 = new SqlConnection();
    SqlCommand cmd2 = new SqlCommand();

    string sqlConn2;
    string sqlCmd2;

    sqlConn2 = @"Data Source=81.169.242.73,1433;Initial Catalog=Webhoost;Integrated Security=False;user id=sa;password=63310Kw1c";
    sqlCmd2 = "select * from Campagnes";

    conn2.ConnectionString = sqlConn2;
    cmd2.Connection = conn2;
    cmd2.CommandText = sqlCmd2;
    conn2.Open();

    SqlDataReader dr = cmd2.ExecuteReader();

    while (dr.Read())
    {
      id = e.CommandArgument.ToString();

            SqlConnection conn = new SqlConnection();
        SqlCommand cmd = new SqlCommand();

        string sqlConn;
        string sqlCmd;

        sqlConn = @"Data Source=81.169.242.73,1433;Initial Catalog=Webhoost;Integrated Security=False;user id=sa;password=63310Kw1c";
        sqlCmd = "UPDATE Campagnes SET camp_status=1 WHERE camp_id=" + id;

        cmd.Parameters.AddWithValue("@camp_id", id);

        conn.ConnectionString = sqlConn;
        cmd.Connection = conn;
        cmd.CommandText = sqlCmd;
        conn.Open();

        cmd.ExecuteNonQuery();

        conn.Close();
    }

A: You have to define and add the parameter @camp_id
cmd.Parameters.AddWithValue("@camp_id", youCampIdValue);


text:
Q: where can I find signal and alarm function definitions? I studied about signal and alarm functions but not satisfied hence thought that their definitions can help me.

A: THIS MIGHT help----->. Good Explanations ::
1.http://www.gnu.org/software/libc/manual/html_node/Signal-Handling.html#Signal-Handling
2.http://www.cs.cf.ac.uk/Dave/C/node24.html
3.http://www.thegeekstuff.com/2012/03/catch-signals-sample-c-code/

A: The signal(3) C library function is usually a thin wrapper around a system call to the underlying kernel. alarm(3) does a bit more work, but again falls back on the kernel's idea of time handling and signal delivery.
If you really want to know how they work, you'd have to dig into the source of a Unix(y) kernel. Be warned, the code you'll find is probably very complex, kernel programmers have to handle some very exotic corner cases, and be wary of weird uses thay might lead to security problems. All that while keeping it as fast as possible (it's code that'll be used hundreds or thousands of times a second on millions of machines).
Next best would be to check out a book on Unix internals.

A: Man pages are the best places to know about the working and usage of any system-defined function. From your question, you actually mean the implementations of the functions(I guess).
But ask yourself, why do you need to look into the code? All that happens is it induces more questions, since most of the variables and functions used will be defined somewhere else and you need to look into them again.
If you are so dissatisfied, then try some tough problems involving these functions.


text:
Q: How to define variable in vue template? Problem
I have the need to temporarily store the results of a method call in Vue templates. This is particularly common inside loops, where I cannot easily use computed properties.

{{ vehicleType }}

     {{ getVehicleTypeData(vehicleType).costPerMile }}

     {{ getVehicleTypeData(vehicleType).costPerHour }}

Javascript snippet:
getVehicleTypeData: function(vehicleType){
    let options = _.find(this.vehicleTypeOptions, (obj)=>{
      return obj.vehicleType==vehicleType;
    });

    return options;
}

To improve performance, I really need a variable to store the method call result.
What is the Vue way to solve this problem?

A: You can just create a computed property which merges the type obj into the vehiclesTypes array.
computed: {

  vehicles() {
    return this.vehicleTypes.map(vehicle => {
       return {
         value: vehicle,
         type: { ...this.getVehicleTypeData(vehicle) }
       }
    })
  }

},

methods: {
  getVehicleTypeData(vehicleType){
    let options = _.find(this.vehicleTypeOptions, (obj)=>{
      return obj.vehicleType==vehicleType;
    });

    return options;
  }
}

And you can do:

{{ vehicle.value }}

     {{ vehicle.type.costPerMile }}

     {{ vehicle.type.costPerHour }}

If you follow the logic I am sure it will work. Though I don't know the values of vehiclesTypes so the code above it may need some changes.
I hope it can help you.

A: One option is to define a component. You can pass the value you need to "store" to it as a prop, and it can use it multiple ways. This is the more Vue-ish approach.
Another option is to wrap your function call in an array and use v-for to create an alias for it. This is more of a hacky/lazy optimization, but it's not brittle, just odd to read.

new Vue({
  el: '#app',
  data: {
    vehicleTypes: [0, 1]
  },
  methods: {
    getVehicleTypeData(type) {
      return [{
        costPerMile: 10,
        costPerHour: 40
      }][type];
    }
  }
});

{{ vehicleType }}

    <template v-for="data in [getVehicleTypeData(vehicleType)]">

       {{ data.costPerMile }}
 {{ data.costPerHour }}

    </template>

A: I've found a solution from some research, and I post answer myself, but not sure if there are any other best solutions.
Javascript snippet:
const Pass = {
  render() {
    return this.$scopedSlots.default(this.$attrs)
  }
}

export default {
  components: {
    Pass
  },
  data: function () {
    return {
      vehicleTypeOptions: [],
    }
  },
  methods: {
    getVehicleData: function(vehicleType){
      let option = _.find(this.vehicleTypeOptions, (obj)=>{
        return obj.vehicleType==vehicleType;
      });
      return option;
    },
    loadData: function(){
      // get data from server using API and set to vehicleTypeOptions
    }
  },
  mounted: function(){
    this.loadData();
  }
}

Template snippet:
<Pass v-for="vehicleType in VehicleTypes" v-bind:key="vehicleType" :temp="getVehicleData(vehicleType)">

{{ vehicleType }}

          Cost per mile: ${{ temp.costPerMile }},
          Cost per hour: ${{ temp.costPerHour }},
          Cost per day: ${{ temp.costPerDay }}

</Pass>

A: A quick way to work around Vue's current shortcomings is to use scoping through v-for and a single loop. A hopefully explanatory example:
<v-list>
  <v-list-tile v-for="(module, idx) in modules">
    <template v-for="scope in [{ isLocked: someFunction(module)}]">

      <v-list-tile-action v-if="scope.isLocked">
        <v-icon color="amber">lock</v-icon>
      </v-list-tile-action>
    </template>
  </v-list-tile>
</v-list>

The <template> element above does the trick. You call your function (someFunction) in a temporary size-1 array of objects, assign it to a property (isLocked), which in turn is assigned to a scoped variable (scope). You can now access whatever someFunction returns as many times as you like without sacrificing performance through scope.isLocked.

A: Unfortunately it is impossible in the current version :(
In your example you can make a computed with calculated values and use it.

{{ vehicleType }}

     {{ vtData[idx].costPerMile }}

     {{ vtData[idx].costPerHour }}

...

computed: {
  vtData() {
    return this.vehicleTypes.map(vt => this.getVehicleTypeData(vt));
  }
}

A: Anywhere in template you can hack your code with :set="VAART = 12" and magically the VAART variable will be set(but not will be reactive)
Tested this magic trick on VUE 3


text:
Q: Pagination in while loop with php I'm newbee about php,trying to learn.
I've search other topic about while loop pagination but not satisfied.
I have 70 user records in my database,wants to list them with html table. I'm showing all records with this code. How can i make simple pagination with these codes? Please help me.

        ID
        Name
        Surname
        Email
        Password
        Date
        Gender

    <?php
    $q = "SELECT * FROM users ORDER BY uid ASC";
    $r = mysqli_query($dbc,$q);

    while($userlist = mysqli_fetch_assoc($r)){ ?>

          <?php echo $userlist['uid']; ?>
          <?php echo $userlist['name']; ?>
          <?php echo $userlist['surname']; ?>
          <?php echo $userlist['email']; ?>
          <?php echo $userlist['password']; ?>
          <?php echo $userlist['date']; ?>
          <?php echo $userlist['gender']; ?>

      <?php } ?>

A: The follow provide very simple pagination as a starting point. You will need to supply formatting for the pagination and such.

            ID
            Name
            Surname
            Email
            Password
            Date
            Gender

<?php
    $q = "SELECT count(*) as `numrows` FROM `users` ORDER BY `uid` ASC";
    $c = mysqli_query($dbc,$q);
    if($c) {
        if($t = mysqli_fetch_assoc($c)) {
            $numrows = $t['numrows'];
        }
    }

    $numrows = 0;
    $rowsperpage = 10;
    $currpage = isset($_REQUEST['currpageno']) && $_REQUEST['currpageno'] != 0 ? $_REQUEST['currpageno'] : 1;
    $numpages = ceil($numrows / $rowsperpage);
    $startrow = ($currpage - 1) * $rowsperpage;
    if($startrow > $numrows) {
        $startrow = $numrows - $rowsperpage;
    }
    if($startrow < 0) {
        $startrow = 0;
    }

    $q = "SELECT * FROM `users` ORDER BY `uid` ASC LIMIT ".$startrow.",".$rowsperpage.";";
    $r = mysqli_query($dbc,$q);

    while($userlist = mysqli_fetch_assoc($r)){
?>

                <?php echo $userlist['uid']; ?>
                <?php echo $userlist['name']; ?>
                <?php echo $userlist['surname']; ?>
                <?php echo $userlist['email']; ?>
                <?php echo $userlist['password']; ?>
                <?php echo $userlist['date']; ?>
                <?php echo $userlist['gender']; ?>

        <?php } ?>

<?php
    for($pgno = 1;$pgno <= $numpages;$pgno++) {
        echo "".$pgno."";
    }
?>


text:
Q: Symfony: how to place a specific item in first position with query_builder option? In a form, I use an EntityType field, which allows selection of several items from entity Member. I am sending the id of a specific member to my form through the form's option (a variable named $selfId) and would like to use the query_builder function to return a list of members where this specific member would appear in first position. How could I achieve this? I'm using Symfony 3.
I'm thinking of something like this:
->add('members',    EntityType::class, array(
        'required'      => true,
        'label'         => 'Members',
        'class'         => 'AppBundle:Member',
        'multiple'      => true,
        'query_builder' => function (MemberRepository $er) use ($selfId) {
                                $qb = $er->createQueryBuilder('m');
                                return $qb
                                          ->orderBy('m.id = :selfId') // invented code!!!!!!!
                                          ->setParameter('selfId', $selfId)
                                          ;
                            }
        ))
;

A: There is an item you can add to the code above item called preferred_choices that should do what you are asking
http://symfony.com/doc/current/reference/forms/types/entity.html#preferred-choices


text:
Q: SFML Crash using Clear function I'm new to SFML and am currently reading through the documentation.  For some reason, however, my "program" crashes whenever I call the Clear() function.  My program code is as follows:
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <cstdlib>
#include <iostream>

void HandleEvents(sf::RenderWindow &App)
{
    sf::Event Event;
    while (App.GetEvent(Event)) {
        if (Event.Type == sf::Event::Closed) {
            App.Close();
            exit(0);
        }
        if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape)) {
            App.Close();
            exit(0);
        }
    }
}

int main()
{
    sf::RenderWindow App(sf::VideoMode(800, 640, 32), "SFML Graphics");
    App.SetFramerateLimit(60);      // cap the framerate at 60 FPS
    while (App.IsOpened()) {
        HandleEvents(App);      // handle events... duh
        App.Clear();      // When I remove this line, the program doesn't crash....
        App.Display();
    }
    return EXIT_SUCCESS;
}

So do any SFML gurus have advice for me?  I've tried researching this problem but the only other person I've seen who tried to ask this had a broken link (because of the new SFML forums).
Thanks.


text:
Q: Obejctive-c: UIImageView 22x22 is grainy I would like to use an image as a checkmark in my UITableViewCell.
This image is 512 × 512.
I created a large UIImageView 22 x 22, and inserted this image.
The result is shown below. The checkmark looks very grainy, even though the image quality is high. Why does this happen, and how can I fix this?

A: Downscaling can also produce visual artifacts. It also unnecessarily uses up processing power if it's done at runtime.
I think it would be better to downscale the asset to 22x22 (+ Retina dimensions of course) in your favorite graphics editor and use this already downscaled asset.


text:
Q: Powershell How to round a TimeSpan? I have a TimeSpan that I want to round before adding it to my file.
Sometimes its ok like this: 12:03:55 but sometimes it is like this: 04:12:32.96472749
It should not look like this just give me the seconds so I thought of rounding it up or down it doesnt even matter.
I tried this: ([Math]::Round($result))    => Where $result is the timespan but it is saying that the method is overloaded even though I saw it on StackOverflow like this...
also this does not work either: ([Math]::Round($result,2))
Maybe someone can help me because I think there is a special way to round TimeSpans and not normal decimals.
Edit:
I just checked out String Formatting like this:
$formattedTime = "{0:hh\:mm\:ss}" -f ([TimeSpan] $result)

It looks good but I need to add Days in front if the date goes over 24Hours .. so something like 'dd' maybe?
Ty Faded~

A: You cannot format a TimeSpan object as if it were a DateTime object.
For that, you need to put together your own format string and use the individual properties you need:
Without days:
$ts = [timespan]::new(0,12,3,55,964.72749)
('{0} {1:D2}:{2:D2}:{3:D2}' -f $ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds).TrimStart("0 ")

# returns 12:03:55

With days (same format string)
$ts = [timespan]::new(11,12,3,55,964.72749)
('{0} {1:D2}:{2:D2}:{3:D2}' -f $ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds).TrimStart("0 ")

# returns 11 12:03:55

The time properties of a TimeSpan object are ReadOnly, so you cannot set the Milliseconds to 0 unfortunately.
If you do want to get a 'rounded' TimeSpan object where the Milliseconds are stripped off, you can do this:
$ts = [timespan]::new(0,12,3,55,964.72749)
# create a new TimeSpan object from the properties, leaving out the MilliSeconds
$ts = [timespan]::new($ts.Days, $ts.Hours, $ts.Minutes, $ts.Seconds)


text:
Q: Why do we use kilograms instead of newtons to measure weight in everyday life? What was the reason to use kilograms to measure weight (e.g. body weight, market vegetables etc.) instead of using newtons in everyday life?

A: Yes. When we use kilograms to measure weight, we are actually referring to $kg_f$ or kilogram-force.
http://en.wikipedia.org/wiki/Kilogram-force
From Wikipedia: One kilogram-force is equal to the magnitude of the force exerted by one kilogram of mass in a 9.80665 m/s2 gravitational field.
In other words, the weight(force) of one kg is equal to one kgf, or 9.8N.

A: The problem is that while mass is the same everywhere on earth, weight is not - it can vary as much as 0.7% from the North Pole (heavy) to the mountains of Peru (light). This is in part caused by the rotation of the earth, and in part by the fact that the earth's surface is not (quite) a sphere.
When you are interested in "how much" of something there is - say, a bag of sugar - you really don't care about the local force of gravity on the bag: you want to know how many cups of coffee you can sweeten with it. Enter the kilogram.
If I calibrate scales using a reference weight, they will indicate (at that location) the amount of mass present in a sample relative to the calibration (reference). So if I have a 1 kg calibration weight, it might read 9.81 N in one place, and 9.78 N in another place; but if I put the reference weight on the scales and then say "if you feel this force, call it 1 kg" - that is what I get. You can now express relative weights as a ratio to the reference.
All I need to do when I move to Jamaica (would that I could…) is recalibrate my scales - and my coffee will taste just as sweet as before. Well - with Blue Mountain I might not need sugar but that's another story.
So there it is. We use the kilogram because it is a more useful metric in "daily life". The only time we care about weight is when we're about to snap the cables in the elevator (too much sweetened coffee?) or have some other engineering task where we care about the actual force of gravity (as opposed to the quantity of material).
So why don't we call it "mass"? Well, according to http://www.etymonline.com/index.php?term=weigh, "weight" is a very old word,

The original sense was of motion, which led to that of lifting, then to that of "measure the weight of." The older sense of "lift, carry" survives in the nautical phrase weigh anchor.

Before Newton, the concept of inertia didn't exist; so the distinction between mass and weight made no sense when the word was first introduced. And we stuck with it...

A: So what I understand from reading the other answers is this:
Here on earth:
1 Kilogram of lettuce: Mass-> 1 Kg,  Weight-> 1 Kgf
In another hypotetical planet where gravity is half of earth:
1 Kilogram of lettuce: Mass-> 1 Kg,  Weight-> 0.5 Kgf
Since there is no practical easy way to measure mass, in everyday life we use the kilogram as a unit of weight assuming that the gravitational field is fairly constant around earth. However scales have to be calibrated locally to compensate the slight gravitational field variation in different places.

A:
Why do we use kilograms instead of newtons to measure weight in everyday life?

The other answers are all very good, but the everyday life answer is that it's because gravity is constant.  Yes, I know, it's not really constant, but for most everyday life purposes, it is.
Because gravity is constant, we don't need to distinguish between mass and weight.
In everyday life.  For most purposes.


text:
Q: Как подключить функцию Delphi XE В данный код:
....................................
while not eof(ft) do
 begin
  readln(ft,s);
 Len := Length(S);
  Pos1 := 0;
 for P := Len downto 1 do
begin
 While Pos('  ',s)<>0 do
  if S[P] = ' ' then
  begin
    if Pos1 = 0 then
    begin
      Pos1 := P;
    end
    else
    begin
    Delete(S, P, Pos1 - P + 1);
      Pos1 := 0;
    end;

  end;
end;
writeln(ft2,s)
  end;
 end;
closefile(ft);
closefile(ft2);
end;
end;

Подключить вот эту функцию:
function test(s:string):string;
var  p1,p2:Word;
begin
repeat
p1:=Pos('test1',s);
p2:=Pos('test2',s);
Delete(s,p1,p2-p1+5);
until (p1=0)or(p2=0);
Result:=s;
end;

A: Внесите ее над var в главной программе. Вот так :
function test(s:string):string;
var  p1,p2:Word;
begin
repeat
p1:=Pos('test1',s);
p2:=Pos('test2',s);
Delete(s,p1,p2-p1+5);
until (p1=0)or(p2=0);
Result:=s;
end;

var
    ft, ft2: TextFile;
    i, p, Len, Pos1: integer;
    s:string;
    p : integer;

begin
if OpenDialog1.Execute then begin
  AssignFile(ft, OpenDialog1.FileName);
  Reset(ft);
....................................
while not eof(ft) do
 begin
  readln(ft,s);
 Len := Length(S);
  Pos1 := 0;
 for P := Len downto 1 do
begin
 While Pos('  ',s)<>0 do
  if S[P] = edit2.text then
  begin
    if Pos1 = 0 then
    begin
      Pos1 := P;
    end
    else
    begin
    Delete(S, P, Pos1 - P + 1);
      Pos1 := 0;
    end;

  end;
end;
writeln(ft2,s)
  end;
 end;
closefile(ft);
closefile(ft2);
end;
end.


text:
Q: geom_col to show a ranking with the lowest number as the tallest bar I have a dataset of rankings of different items where I want the lowest value to show the tallest bar on the chart. Below is a small sample of the data and the code to build the chart, followed what the chart currently looks like.
data <- data.frame(ranks = c("rank1","rank2", "rank3") , value = c(13,2,18))

ggplot(data) +
  geom_col(aes(x = ranks, y = value))

What I'd like the chart to look like is something like this (using the same data) with the y-axis reversed:

A: If you can tolerate a warning, you can set ymax = after_stat(-Inf). This trick is abusing the fact that the columns are parameterised as rectangles, and is not the recommended way to use ggplot2. You can set it to -1 * desired_lowest_point too, but the scale doesn't automatically adjust the limit.
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.5
data <- data.frame(ranks = c("rank1","rank2", "rank3") , value = c(13,2,18))

ggplot(data) +
  geom_col(aes(x = ranks, y = value,
               ymax = after_scale(-Inf))) +
  scale_y_reverse()
#> Warning: Ignoring unknown aesthetics: ymax

Created on 2021-04-22 by the reprex package (v1.0.0)


text:
Q: WP minimum Quantity at single product page I'm using the following answer code that enable product quantity fields in shop and archive pages:
Show quantity box with add to cart ajax enabled in Woocommerce shop page and its work great.
This code work fine the problem is: when i am on a single product page and product has a minimum amount to order (5 for example) the code put the same minimum amount at the releated products (even if they dont have a minimum amount for order)


text:
Q: running psql command in a java program I have a requirement where using java code I need to create/delete/alter postgres tables.
I have written a program as below:
public static void main(String[] args) throws IOException {
        System.out.println("Hello World!");
        Process p = Runtime.getRuntime().exec("psql -U postgres -d testdb -h localhost -p 5433 -f D:\test.sql");
    }

test.sql file looks like below,
Create TABLE MyTable1
(
    VersionNumber VARCHAR(32) NOT NUll
);

Create TABLE MyTable2
(
    VersionNumber VARCHAR(32) NOT NUll
);

Create TABLE MyTable3
(
    VersionNumber VARCHAR(32) NOT NUll
);

problem:
If I run the same psql command:
psql -U postgres -d testdb -h localhost -p 5433 -f D:\test.sql

in command line, it asks for password and the tables get created.
But in java program, there is not provision to provide password. Please let me know on how to achieve it.

A: You can use a connection URL instead:
psql -f d:\test.sql postgresql://postgres:password@localhost:5433/testdb

A: First of all, it would be better to actually use JDBC to connect to the database and run your SQL statements.  If you're set on using command-line psql, you can use PGPASSWORD environment variable to set the password:
String command = "psql -U postgres -d testdb -h localhost -p 5433 -f D:\test.sql";
String[] envVars = { "PGPASSWORD=yourpassword" };
Process p = Runtime.getRuntime().exec(command, envVars);

You can read the password from the stdin if necessary.  But, again, it's better to do this over JDBC.

A: Regarding to a_horse_with_no_name answer
and using Java-code launch of psql at Windows OS
and using ProcessBuilder
following slight modification works for me:
    ProcessBuilder builder = new ProcessBuilder();
    String connUrl = "postgresql://user:password@host:port/dbname";
    String sqlFileToProcess = "--file=Disk:\\path\\to\\file.sql";
    builder.command("psql.exe", sqlFileToProcess, connUrl);
    builder.directory(new File("Disk:\\Path\\to\\psql\\containing\\folder"));
    Process process = builder.start();
    int exitCode = 0;
    try {
         exitCode = process.waitFor();
         int len;
         if ((len = process.getErrorStream().available()) > 0) {
             byte[] buf = new byte[len];
             process.getErrorStream().read(buf);
             System.err.println("Command error:\t\""+new String(buf)+"\"");
         }
    } catch (InterruptedException e) {
         e.printStackTrace();
    }
   assert exitCode == 0;

Don`t know why, but if:
-f Disk:\\path\\to\\file.sql

as argument in Java-code throws:
Command error:  "unrecognized win32 error code: 123 psql: error:  Disk:/path/to/file.sql: Invalid argument
"

(pay attention to redirection of slashes and backslashes in otput and input)


text:
Q: When will Opera support border-radius? Is there a release or any news on when they will support border-radius?
I heard that they have supported it in the past, with something like -o-border-radius, what happened to it?

A: Apparently, after Opera 10 (Presto 2.2). Look for it in the next version of Presto (2.3?).
Documentation: http://www.opera.com/docs/specs/presto23/css/properties/
Developer Comments: http://dev.opera.com/forums/topic/258986?t=1252795344&page=1#comment2936734
EDIT: Opera 10.5 (pre-beta) supports border-radius: http://labs.opera.com/downloads/

A: It never supported -o-border-radius: http://dev.opera.com/forums/topic/651612


text:
Q: Get an element inside two tags and looping through multiple variable So I have a price that I get as a variable but I keep getting "USD 60" where I want just "60". After that I need to loop through multiple variables(price and quantity) then write two sentences. "An order was placed with a quantity of 2 and price of 60" "An order was placed with a quantity of 5 and price of 20." This is as close as can get it but the loop isn't working.

                2

            5

USD 60.00
USD 20.00

var price = document.getElementsByClassName('v1_shop_cart_articles_col_price').getElementByTagName('span')[1].innerHTML;
var qty = document.getElementsByClassName('v1_shop_cart_articles_col_qty');

for(var i=0; i<qty.length; i++) {
    document.write('An order was placed with a quantity of '+
                    parseInt(qty[i].innerHTML, 10) + price +
                   '.');
    }

A: http://codepen.io/anon/pen/hKafl
without a table, your td's weren't showing up - so your qty and price arrays were empty. also, when you were trying to get the price value, weren't accessing a specific element in the price array.


text:
Q: Is there a way to define the namespace your Compose Swarm lives in, in the yaml? I have a simple docker-compose file which is used to launch my containers.   I wish to have another yaml file which contains additional, optional containers. It can live in a separate directory.  My goal is to find a way to force the namespace of the created swarms so they exist within the same network/use space so they can talk to each other.
compose1.yaml
  services:
    web:
      build: .

compose2.yaml
  services:
    web1:
      build: .

So if i run both of these they would be prepended with the folder they exist in, in my case: a, and b respectively.
I wanted to ensure that they flow together, despite not being in the same file hierarchy.
I have been coming over keywords in the docker-compse documents, and was not sure what the best way to do this in the yaml file would be, but noticed in the CLI, might be able up to update various names.
How does one accomplish this?
Note:  I have also created a third file under the b directory, a sibling to compose2.yaml.   So i can run those separately and they work just fine.
a/
  compose.yaml
b/
  compose2.yaml
  another.yaml

So i have been able to merge them together by doing:  cd /b/ && docker-compose -f compose2.yaml -f another.yaml up -d to run 2 files together, and they exist under the B namespace.  Likewise, I can also run them sequentially instead of referencing them in 1 command.
So my question is how can I do something like:
docker-compose --namespace test compose.yaml up
docker-compose --namespace test compose2.yaml up

such that I could view items accordingly with docker? It seems that I would need to consider running the command from under the first shared parent folder?
so if a and b existed under test, I could just do:
cd /test
docker-compose -f a/compose.yaml up -d
docker-compose -f b/compose2.yaml up -d

then my services would be listed as:  test_web, test_db-box, etc.

A: So I found out that one person's namespace is another person's project-name.
That being said, after understanding nuances, the project-name ( -p | --project-name ) is the prepend for the compose services.
docker-compose --project-name foo -f a/compose.yaml up
docker-compose --project-name foo -f b/compose2.yaml up

This will create the services:   foo_web_1
The format for this is: %{prepend}%{servicename}%{number}
The issue then is, Can we find a way to implement this CLI property to work from within the YAML file, possibly as a config option for the file.   The Docker Compose website information states that you can supply an environment variable ( _ COMPOSE_PROJECT_NAME_ ) to change change the project name from the default of the base directory, BUT not from within a Compose YAML.
If i want to then launch multiple compose files, under a particular project what I would want to do is to just encapsulate it with a BASH or SHELL script.
#/bin/bash
export COMPOSE_PROJECT_NAME=ultimate-project
docker-compose -f a/compose.yaml up -d
docker-compose -f b/compose2.yaml up -d

and that would create services :
ultimate-project_web_1
ultimate-project_web2_1


text:
Q: Why the data resets after save in database? I'm trying to save new phone number in database
First by another method get phone number and temporary save it and send a code to user then by following methods check if user entered correct code
The controller:
    @GetMapping("/check-code/{code}")
    public Boolean checkPhoneNumberCode(@PathVariable("code") int code){
        return phoneService.validateCode(code);
    }

The service:
    @Override
    public Boolean validateCode(int code) {
        Integer phoneNumberCode = cacheService.getPhoneNumberCode(phoneNumber.toString());
        if (!phoneNumberCode.equals(code)) {
            resendCode();
            return false;
        }
        updateUser();
        clear();
        return true;

    }

after the code was ok updateUser() method will call:
    @Override
    public void updateUser() {
        User user = userRepository.findByIdAndIsDeletedFalse(userId).get();
        user.setPhoneNumber(phoneNumber);
        userRepository.save(user);
    }

The UserRepository:
public interface UserRepository extends MongoRepository<User, String> {

And at the end of updateUser() method data must be updated and it updated
but when updateUser() method finishes
and validateCode() method finishes
I've checked, before checkPhoneNumberCode() method finishes, data still updated (before "}" finishes and  program exit from debug mode) but when program exit from debug mode (checkPhoneNumberCode() method completes) data will reset and back to what was before
I'm using Intellij as IDE and Java for back-end and MongoDB for database I don't think it relates to front-end but I'm using angular for front-end
Github repository
Controller: src -> main -> ToDoWeb -> controller -> PhoneController;
Service: src -> main -> ToDoWeb -> service -> impl -> PhoneServiceImpl;
Repository: src -> main -> ToDoWeb -> repository -> UserRepository;

A: It would be difficult to know exactly what the problem is without taking a look at your repository. My guess would be that you're not implementing the repository well, and Spring is not able to create a Transaction by default. This question deals with something similar.
Check that your userRepository either extends from something like CrudRepository or JPARepository. Another option would be to annotate with @Transactional manually on the methods that modify the data in the database.

Also, check that your database creation policy is not set to CREATE, since this would re-create your data every-time the application is run. You'll probably find this in your application.properties file. (I doubt your problem is related to this, but there's no harm in making sure). You can find more information about this in this question.
hibernate.hbm2ddl.auto=update

I hope this helps, or at least it guides you in the right direction


text:
Q: Program that listens to a TCP/IP port for text and execute (emulate) a key stroke on keyboard? I am looking for a program to be run on Windows Vista that would listens to a TCP/IP port and execute or emulate a keyboard's key stroke (or a combination of keystrokes, such as Ctrl + D). It's like AAC Keys, except that AAC Keys only listens to serial port.
Thanks and appreciated!

A: You can program something in AutoIt for that. Look at the TCP function set and the Send() function. TCPListen() in particular will listen for TCP connections on a specified port and TCPAccept() will check and accept the connection to the created socket, and the Send() function emulates any keystrokes you want. You can use a conditional in a loop to check the socket for an accepted connection and perform a keystroke set of your choice once accepted.


text:
Q: C# JavacriptSerializer date time issue I created custom type contains datetime field and when serialize and deserialize it value of date time changed, i use javaScriptSerializer
my code:
  Data _Data=new Data();
     _Data.Name="Islam";
     _Data.DateFrom=DateTime.Now;
     string _strData = new JavaScriptSerializer().Serialize(_Data);

    Data _NewData= new JavaScriptSerializer().Deserialize<Data>(_strData);
    // value of _Data.DateFrom changed after deserialize it

can i solve it?

A: Use to ToLocalTime();
Data data=new Data();
data.Name="Islam";
data.DateFrom=DateTime.Now;
string _strData = new JavaScriptSerializer().Serialize(data);

Data newData = new JavaScriptSerializer().Deserialize<Data>(_strData);
var dt = newData.DateFrom.ToLocalTime();


text:
Q: ReactJS - Detect third-party DOM insert using Mutation Observer Inside the component, a third-party JavaScript library has injected some content into a specific DIV (voice-service) after React render. I wanted to add or remove some CSS class on that DIV (voice-service) when the DOM was injected using Mutation Observer, like -
When DOM injected -

 // third-party content

When DOM Not injected -

// third-party content

heroVoice Component:
import React, { useRef, useState, useEffect } from 'react';

const heroVoice = (props) => {

    const elementRef = useRef();
    const [voiceAvailability, setVoiceAvailability] = useState(false);

    useEffect(() => {
        const config = { attributes: false, characterData: false, childList: true, subtree: true, attributeOldValue: false, characterDataOldValue: false };
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                const newNodes = mutation.addedNodes;
                newNodes.forEach(node => {
                    if (node.classList && node.classList.contains('pocket-sphinx-container')) {
                        setVoiceAvailability(status => !status);
                    }
                });
            });
        });
        observer.observe(elementRef.current, config);
    }, []);

    return (
        <div
            ref={elementRef}
            id="maxVoiceContainer"
            className={`voice-service ${voiceAvailability ? ' service--active' : 'service--inactive'}`}
        >
          // third-party content

    );
}

export default heroVoice;

Wanted to know -

*

*Do I need to disconnect the observer?

*Looks good? best practices?

*Also, I do not want to re-render when the state was updated!

A: Q: Do I need to disconnect the observer?
It's not needed directly, but I recommand it with the mutationObserver.disconnect()  Method, because you is called One time on ComponentDidMount.
An empty Array at the second parameter means it.
Ref
Looks good? best practices?
Yes looks quite good. Avoid nested forEach. Better use first a map and than an forEach

 mutations.map(mutation => mutation.addedNodes).forEach(node => {
  if (node.classList && node.classList.contains('pocket-sphinx-container')) {
    setVoiceAvailability(status => !status);
  }
 });

Also, I do not want to re-render when the state was updated!
React's lifecycle is build for this. There are two possibilities. First, you can use Redux or you make a local variable which is being setted in the forEach. But generally don't use a setState hook in a forEach


text: Q: How to add issues to a specific Git branch instead of the master branch I want to create an issue or add comments to a GitLab branch other than the master branch, such that our team can discuss the suggested changes in that branch. Is there a way to do this?


text:
Q: airflow application logs from kubernetes pods to ElasticSeacrh Hi We are running airflow application hosted on kubernetes , we are using airflow base image airflow-2.1.2-python-3.8.10 , when we enable the logs EFK log configuration with remote logging pods getting crash , pls help us we are trying since last 6 months and still no success to see our airflow application logs in Kibana . for any information let me know I can provide ,  I just wanted my airflow application logs to be shipped to EFK and can be visualize in Kibana :)
Thank you


text:
Q: Continuous Image capture using Camera2 api How to capture continuous images using Camera 2 api's.
I wrote a simple application and a thread in it to capture continuous images but it is not working

A: It would be nice if you provided your code so we could see what's wrong.
In general terms, you'll want to create a CameraDevice object and call the CameraDevice.createCaptureSession(List <Surface>, CameraCaptureSession.StateCallback, Handler) method by specifying which surfaces you might like to output to (maybe just 1). Once the CameraCaptureSession.StateCallback (that you specified in the createCaptureSession method) calls the onConfigured(CameraCaptureSession) method, call the CameraDevice.createCaptureRequest(int) method, which returns a CaptureRequest.Builder object. With this, you can use the CaptureRequest.Builder.addTarget(Surface) method to specify which of the pre-specified surface(s) you want to output to (probably all of them). Once you're done adding targets, call the CaptureRequest.Builder.build() method, which returns a CaptureRequest object. You can then use the CameraCaptureSession object that was provided to you by the onConfigured(CameraCaptureSession) method to finally pass your CaptureRequest object to the CameraCaptureSession.setRepeatingRequest(CaptureRequest, CameraCaptureSession.CaptureCallback, Handler) method. This will start continuous output to the surfaces that you specified.
Seriously, this api is so complicated, you'd think they didn't want you to use it. If you need more detailed information about what these classes and methods do, the Android documentation is very good.


text:
Q: Spring MVC mapping - why path is changing? I have this piece of code:
    @RequestMapping(value="login/authUser", method=RequestMethod.POST)
public String authUser(@RequestParam("login") String login,
                        @RequestParam("password") String password, ModelMap model)
(...)

Which should catch user's authentication:

        <form id="loginForm" action="login/authUser" method="post">
            Login:
            <input id="login" type="text" title="podaj login" name="login"/>

            Hasło:
            <input id ="password" type="password" title="podaj haslo, minimum 8 znaków" name="password">

            <input id ="loginAuthorisationFailed" type="text"/>

            <input id="loginButton" type="submit" value="Zaloguj">

        </form>

And if it's bad, it should return index.jsp and information about bad data
(...)
else{
            model.put("info", "Bad data!");
            return "index";

Info goes to the h1 HTML tag:

${info}

And this is path then I see in browser:
http://localhost:8084/pracainz/login/authUser

But then I try to log again, path in browser is different:
http://localhost:8084/pracainz/login/login/authUser

and Tomcat shows me error:
The requested resource () is not available.

It adds extra "/login" and I don't know why. What can I do to stop form behaving in this way, what can I do to force ,,reset" of path every time when I try to send form to Spring?
Unfortunately, this is not working:
action="${pageContext.servletContext.contextPath}/login/authUser"

I would be very happy if anybody want to help me.
Thank you in advance!
SOLVED:
Solution:
I should use:
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
(...)

<form:form id="loginForm" action="${pageContext.servletContext.contextPath}/login/authUser" method="post">
 (...)
</form:form>

Instead simple  HTML tag

A: Use the Spring tag library and more specifically spring:url to create the correct url for action. Check out this SO question for details


text:
Q: How to solve this equation? $|x-5|=10$ How to solve the following equation? $$|x-5|=10$$
Many thanks!

A: Surely, you must revise absolute value equations. (You can start  here.)
Anyway, as regards this particular equation, you get:
$(x-5)=10$, if $x>5$
or
$-(x-5) = 10$, if $x<5$
Solutions: $x= -5$ or $x= +15$
(From Wolfram Alpha) Plot:

A: Assuming that we are talking about the usual absolute value on the reals,
the more general approach to me would be (for $z \geq 0$)
$|x|=z \Leftrightarrow |x|^2 = z^2 \Leftrightarrow x^2 = z^2$
Now in your case take $x := x-5$, $z:= 10$.

A: Hint: $$|X|=X\quad\text{ or }\quad|X|=-X$$

A: Just read the equation out loud: "The distance from $x$ to $5$ equals $10$." Obviously there are two solutions.

A: $|x-5|=10 \implies x-5=\pm10 \implies x=5\pm 10 \implies x=15$, or, $ x=-5.$


text:
Q: oracledb sequelize ORM coders.
Necesito realizar una conexión a una base de datos Oracle, por medio de sequelize. El inconveniente es que al seguir los pasos de la documentación no me ha sido posible realizar correctamente la configuración, según se indica debo tener instalado "Visual Studio 2017 Redistributable", busque otra alternativa ingresando el comando: npm --add-python-to-path='true' --debug install --global windows-build-tools. En los dos casos me arroja el siguiente error:

¿Alguien sabe los pasos que debo seguir, para poder utilizar sequelize con oracledb? En serio, les agradecería su colaboración y buena onda.


text:
Q: Setting up a comparison to make one thing look appealing Is there a term for the (unethical) sales practice of:

*

*Customer requests product of a certain level of quality

*Salesperson provides two options.

*Option 1 is clearly inadequate, falling well and obviously short of the requirement

*Option 2 is also inadequate, but far superior to option 1

*You pick Option 2 as in comparison it appears to be the best choice
Presumably this allows the salesperson to unload products at a higher price than they were really worth.
I think the word "foist" has a similar idea in mind but I am not sure if it is really specific to this situation. Also I do not think this is a "bait and switch".


text:
Q: Mail body with multiple line body I'd like to send an email using C#
            SmtpClient client = new SmtpClient(_smtp, int.Parse(_port));
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.EnableSsl = bool.Parse(_enableSsl);
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(APIKey, SecretKey);
            MailMessage mail = new MailMessage();
            mail.From = _from;
            mail.To.Add(_to);
            mail.Subject = _subject;
            mail.Body = _body;
            if(Uri.IsWellFormedUriString(url, UriKind.Absolute)) mail.Body += "
" + url + "
" + "Cordialement";
            mail.IsBodyHtml = false;

            client.Send(mail);

The mail is sent, but its body is received as a single line .
So How can I fix this issue?

A: Since you have the following line in your code:
mail.Body += "
" + url + "
" + "Cordialement";

I'm going to guess that the rest of your mail.Body also contains HTML.
If you are placing HTML in the body of the MailMessage, you need to set  IsBodyHtml to true - you have it set to false.
mail.IsBodyHtml = true;


text:
Q: Unable to get RabbitMQ running on Windows 10 I've run the Erlang and RabbitMQ installers "As Administrator".
Both seem to have installed correctly.
The RabbitMQ server is running.
However, when I run any command line Rabbit commands (rabbitmqctl, rabbitmq-plugins enable rabbitmq_management, etc.), I get the following error message/dump.  I obviously cannot access the Management Console or communicate with the service at all.
Any ideas on the below error and what could be causing this?  I've installed on other Win10 machines before without any issues.
=SUPERVISOR REPORT==== 20-Jun-2018::10:08:39.865000 ===
supervisor: {local,'Elixir.Logger.Supervisor'}
errorContext: start_error
reason: noproc
offender: [{pid,undefined},
           {id,'Elixir.Logger.ErrorHandler'},
           {mfargs,
               {'Elixir.Logger.Watcher',start_link,
                   [{error_logger,'Elixir.Logger.ErrorHandler',
                        {true,false,500}}]}},
           {restart_type,permanent},
           {shutdown,5000},
           {child_type,worker}]
=CRASH REPORT==== 20-Jun-2018::10:08:39.865000 ===
  crasher:
   initial call: application_master:init/4
   pid: <0.80.0>
    registered_name: []
    exception exit: {{shutdown,
                         {failed_to_start_child,'Elixir.Logger.ErrorHandler',
                             noproc}},
                     {'Elixir.Logger.App',start,[normal,[]]}}
      in function  application_master:init/4 (application_master.erl, line
138)
    ancestors: [<0.79.0>]
    message_queue_len: 1
    messages: [{'EXIT',<0.81.0>,normal}]
    links: [<0.79.0>,<0.42.0>]
    dictionary: []
   trap_exit: true
    status: running
    heap_size: 376
    stack_size: 27
    reductions: 193
  neighbours:
=CRASH REPORT==== 20-Jun-2018::10:08:39.865000 ===
  crasher:
    initial call: Elixir.Logger.Watcher:init/1
    pid: <0.87.0>
    registered_name: []
    exception exit: noproc
      in function  gen:do_for_proc/2 (gen.erl, line 228)
      in call from gen_event:rpc/2 (gen_event.erl, line 239)
      in call from 'Elixir.Logger.Watcher':init/1 (lib/logger/watcher.ex,
line 23)
      in call from gen_server:init_it/2 (gen_server.erl, line 374)
      in call from gen_server:init_it/6 (gen_server.erl, line 342)
    ancestors: ['Elixir.Logger.Supervisor',<0.81.0>]
    message_queue_len: 0
    messages: []
    links: [<0.82.0>]
    dictionary: []
    trap_exit: true
    status: running
    heap_size: 376
    stack_size: 27
    reductions: 254
  neighbours:
=INFO REPORT==== 20-Jun-2018::10:08:39.881000 ===
    application: logger
    exited: {{shutdown,

{failed_to_start_child,'Elixir.Logger.ErrorHandler',noproc}},
             {'Elixir.Logger.App',start,[normal,[]]}}
    type: temporary
Could not start application logger: Logger.App.start(:normal, []) returned an
error: shutdown: failed to start child: Logger.ErrorHandler
    ** (EXIT) no process: the process is not alive or there's no process
currently associated with the given name, possibly because its application
isn't started

A: I also encountered this problem yesterday after installing the latest version of RabbitMQ onto a Windows 10 box.  Finally found the cause this morning:  It's related to the version of the Erlang OTP that I had installed (the latest - 21.0).  Apparently the version of Elixir used by RabbitMQ has issues with this version of the Erlang OTP - at least that's the conclusion I came to after reading this thread here.
After uninstalling that erlang version, and installing version 19.3 from this page, I was able to use the RabbitMQ console commands without this error message being thrown every time.  (I did however have to fix the ERLANG_HOME environment variable also... the uninstall/reinstall of erlang had for some reason left this pointing at the old (v21) folder which no longer existed.)

A: I got a bonus error with erlang 19.3 :
λ rabbitmq-service install
C:\Programs\erl8.3\erts-8.3\bin\erlsrv: Service RabbitMQ added to system.
bad "MBa" value: ageffcbf
Usage: beam.smp.dll [flags] [ -- [init_args] ]

However the service installed and started successfully with no side effects so far.


text:
Q: In Google scripts, how do you pass a doc url variable into an href statement? I have a bound Google script in a Google Sheets that creates a menu and populates the menu onOpen of the sheet with a bunch of functions. One function creates a new Google Doc. I then want to open that doc, but I can't figure out how to pass the doc's URL into an href statement. See code below:
function createLandscapeLyricDoc() {
  var doc = DocumentApp.create('Rename');
  var title = "replace with song title and then link this text to song title cell in Catalog Spreadsheet"
  var url = doc.getUrl();
  var body = doc.getBody();
  var paragraph = body.insertParagraph(0, "");
  var text1 = paragraph.appendText("© replace with writer(s)");
  text1.setFontSize(8);
  var rowsData = [['PUT FIRST VERSE/CHORUS HERE.  (SUGGEST USE ALL CAPS.)', 'PUT SECOND VERSE/NEXT CHORUS/BRIDGE/ETC HERE.']];
  var style = {};
  body.insertParagraph(0, title)
  .setHeading(DocumentApp.ParagraphHeading.HEADING3);
  table = body.appendTable(rowsData);
  style[DocumentApp.Attribute.BORDER_WIDTH] = 0;
  table.setAttributes(style);
  /*line below is the one that does not work as the variable "url" is not being read correctly (as I don't know how to use it or if this can even be done)*/
  var html = "Open 1-Column Lyric Template";
  var selection = SpreadsheetApp.getActiveSheet();
  var userInterface = HtmlService.createHtmlOutput(html);
  SpreadsheetApp.getUi().showModalDialog(userInterface, 'Open Landscape New Lyric Doc');

It has been suggested that this question has already been answered here and while I can see why that suggestion was made, I have the following observations:
1) I am way too much of a newbie to Google script coding to know enough terminology to form a search query at Stack Overflow to find that answer. And in fact, had I somehow stumbled across that "answer," I am not sure I would have recognized it as such as the overall code is so different from the code I was struggling with.
2) That solution did not appear as one of the suggested ones for me to review before I asked my question.
Considering these two points together, especially for newbie coders, I think having my question on this site will be helpful to others that fit my profile (and not that of an experienced coder) because this question and answer probably will show up for others trying to do what I was/am trying to do whereas How to use a variable inside a string Q&A will not.

A: Answered by Sandy Good:
var html = 'Open 1-Column Lyric Template;'

A: I find that doing it this way in complex strings is somewhat easier.
var html = Utilities.formatString('Open 1-Column Lyric Template',url);

*

*Utilities.formatString()


text:
Q: Given a function, prove that it's injective Given a function $f: \mathbf{N}_0 \to \mathbf{N}_0$, defined
$$
f(x) =
\begin{cases}
x+3 & \text{if } x \in \mathbf{N}_{\text{even}} \\
x-1 & \text{if } x \in \mathbf{N}_{\text{odd}}
\end{cases}
$$
I have to prove that the function is injective.
My attempt:
Suppose that $f(a) = f(b), \forall a,b \in N_{even}$
$a+3=b+3 \implies a = b$
Suppose that $f(a) = f(b), \forall a,b \in N_{odd}$
$a-1=b-1 \implies a = b$
Since $a,b$ are arbitrary, $f$ is injective.

A: Proving that $f$ is injective means to prove that$$(\forall a,b\in\mathbb{N}_0):f(a)=f(b)\implies a=b.$$So, take $a,b\in\mathbb{N}_0$ and assume that $f(a)=f(b)$. Note that $f$ maps odd numbers into even numbers and vice-versa. So, since $f(a)=f(b)$, $a$ and $b$ are both odd or both even. If $a$ and $b$ are even, then$$f(a)=f(b)\iff a+3=b+3\iff a=b.$$If $a$ and $b$  are odd, then$$f(a)=f(b)\iff a-1=b-1\iff a=b.$$

A: Sorry, but your attempt is incomplete.
What you have to prove is that, if $f(a)=f(b)$, then $a=b$.
There are four cases:

*

*$a$ and $b$ even

*$a$ even and $b$ odd

*$a$ odd and $b$ even

*$a$ and $b$ odd

In case 1, we have $a+3=b+3$, hence $a=b$.
In case 4, we have $a-1=b-1$, hence $a=b$.
You're missing the other two cases, which actually are the same, so I'll only deal with 2. In this case, $a-1=b+3$, therefore
$$
a=b+4
$$
which is a contradiction.
The fact that cases 2 and 3 can't happen doesn't allow you to skip them without justification.


text:
Q: Show posts of a specific category first in WordPress loop I'd like to show posts from a category first in the homepage and then continue the default order of WordPress posts.
Is it even possible?
I've tried using 2 loops and filter the first one with the category that I want however I don't think that the pagination will work as expected.

A: Try this (untested code, though).
$total_posts_to_display = 10; // Change accordingly

$id_of_category_1 = 4; // Change accordingly

$filtered_posts = array(); // Array to be filled in with all posts, ordered by "category 1" first

$posts_in_category_1 = get_posts( array(
    'numberposts' => $total_posts_to_display,
    'category'    => $id_of_category_1
) );

$ramaining_posts_number = $total_posts_to_display - count( $posts_in_category_1 );

if ( $ramaining_posts_number > 1 ) {
   $excluded_post_ids = array();
   foreach( $posts_in_category_1 as $ep ) {
       array_push( $excluded_post_ids, $ep->ID );
   }
   $remaining_posts = get_posts( array(
       'numberposts' => $ramaining_posts_number,
       'exclude'     => $excluded_post_ids
   ) );
} else {
   $remaining_posts = array();
}

$filtered_posts = array_merge( $posts_in_category_1, $remaining_posts );

I have a more sophisticated solution that will support pagination too! You will need to place it in functions.php:
add_action( 'pre_get_posts', 'my_custom_home_post_ordering' );

function my_custom_home_post_ordering( $query ) {
    if ( ! is_home() ) {
        return;
    }
    if ( ! $query->is_main_query() ) {
        return;
    }
    $posts_in_category_1 = get_posts( array(
        'posts_per_page' => -1,
        'category'       => 4 // Change accordingly. You may also use 'category_name', instead.
        'fields'         => 'ids'
    ) );
    $query->set( 'post__in', $posts_in_category_1 );
    $query->set( 'orderby', 'post__in' );
}


text:
Q: VB.Net parse string as date I have looked but cannot find a solution for my problem. I am importing data from a CSV file with the following code:
Using connection As New SqlClient.SqlConnection(SqlconnectionString)
    Dim cmd As New SqlClient.SqlCommand(strsql, connection)
    With cmd.Parameters
        .Add("@PLAASNOMMER", SqlDbType.VarChar, 50, "F1")
        .Add("@PLAASNAAM", SqlDbType.VarChar, 50, "F2")
        .Add("@BLOKNOMMER", SqlDbType.VarChar, 50, "F3")
        .Add("@AREA", SqlDbType.VarChar, 50, "F4")
        .Add("@KULT", SqlDbType.VarChar, 50, "F7")
        .Add("@WINGERDKLAS", SqlDbType.VarChar, 50, "F8")

        .Add("@ANALISEDATUM", SqlDbType.Date).Value = Date.ParseExact("F9", "dd/MM/yyyy", DBNull.Value)

        .Add("@SUIKERWAARDE", SqlDbType.Decimal, 50, "F10")
        .Add("@PHWAARDE", SqlDbType.Decimal, 50, "F11")
        .Add("@SUURWAARDE", SqlDbType.Decimal, 50, "F12")
    End With

    Dim adapter As New SqlClient.SqlDataAdapter()
    adapter.InsertCommand = cmd
    Dim iRowsInserted As Int32 = adapter.Update(dt)

I have "empty" dates in the CSV file as "/ / ". I am using the code (line 10) :
.Add("@ANALISEDATUM", SqlDbType.Date).Value = Date.ParseExact("F9", "dd/MM/yyyy", DBNull.Value)

However I am getting an error

Unable to cast object of type 'System.DBNull' to type 'System.IFormatProvider'.

What am I missing?
My CSV date looks like this:
plaasno,name1,blokno,name2,analise_dt,name3,kult,wingklas,datum,suiker,ph,suur,deurryppnt,geur
"11332","MONOTONKA","1-MON","KLEINPLASIE","20090115","","PIN","KULT","  /  /",0.00,0.00,0.00,0.00,0.00
"11332","MONOTONKA","10-MON","KLEINPLASIE","20090115","","COL","BULK","  /  /",0.00,0.00,0.00,0.00,0.00
"11332","MONOTONKA","10-MON","VREDENDAL","20180228","","COL","BULK","28/02/18",23.50,3.08,10.42,0.00,0.00
"11332","MONOTONKA","12-MON","KLEINPLASIE","20090115","","CHB","BULK","  /  /",0.00,0.00,0.00,0.00,0.00
"11332","MONOTONKA","12-MON","VREDENDAL","20180214","","CHB","BULK","14/02/18",18.70,3.09,11.78,0.00,0.00
"11332","MONOTONKA","13-MON","KLEINPLASIE","20090115","","CHB","BULK","  /  /",0.00,0.00,0.00,0.00,0.00
"11332","MONOTONKA","13-MON","VREDENDAL","20180214","","CHB","BULK","14/02/18",18.30,3.03,13.28,0.00,0.00

A: The error itself is pretty explanatory, you are passing System.DBNull to a parameter which expects to be passed iFormatProvider for Date.ParseExact-method here:
Date.ParseExact("F9", "dd/MM/yyyy", DBNull.Value)

Not sure why are you trying to do this, perhaps you want to pass null if the value cannot be parsed? If that is the case you could do if-clause with TryParseExact and if it returns false, add DBNull.Value as a value for the paremeter.
Also as @AndrewMorton pointed out, you are passing a literal string "F9" (and all the other fields also) to the function and not the value from the csv. Your code is incomplete. Anyway as per your question, I have explained why you get the error you described.

A: .TryParseExact has a few more parameters.
If had to put .Add in twice because I could not assign a DBNull.Value  to a Date variable.

    Dim d As Date
    Dim F9 As String = "String that must match your format parameter"
    'Your command and parameter code
    If Date.TryParseExact(F9, "yyyy-mm-dd", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, d) Then
        .Add("@ANALISEDATUM", SqlDbType.Date).Value = d
    Else
        .Add("@ANALISEDATUM", SqlDbType.Date).Value = DBNull.Value
    End If