问:
How to remove the attributes in div tag without class,id and style rest of attributes need to be delete using coldfusion?
I have attribute like this.
Example:

```<code><div class="issue-document" id="assr_0335-5985_1991_num_76_1_1619" itemprop="hasPart" itemscope="" itemtype="https://facebook.com>

<cfset mystring = 'This is some text. It is true that <div class="issue-document" id="assr_0335-5985_1991_num_76_1_1619" itemprop="hasPart" itemscope="" itemtype="https://facebook.com">Harry Potter</div> is a good, but is better'>
<cfset MyReplace = ReReplaceNoCase(mystring,"<div [^>]*>","","ALL")>

<cfoutput>```Original string: #mystring#

Without link: #myreplace#```</cfoutput>
</code>```

I need to remove only itemscope and itemprop like this rest of the attribute like id,class, style i don't want to remove using coldfusion in regular expression. Can any one please help to find the solution.

答:
```<code><cfset myReplace = reReplaceNoCase(mystring, '\b(itemscope|itemprop)="[^"]*"', "", "all")) />
</code>```

https://trycf.com/gist/8d84d7d355f7c54e5533eeed22d097ba/acf2016?theme=monokai

Body:
I have attribute like this.
Example:

<cfset mystring = 'This is some text. It is true that
Harry Potter
 is a good, but is better'>
<cfset MyReplace = ReReplaceNoCase(mystring,"
]*>","","ALL")>

<cfoutput>
Original string: #mystring#

Without link: #myreplace#
</cfoutput>

I need to remove only itemscope and itemprop like this rest of the attribute like id,class, style i don't want to remove using coldfusion in regular expression. Can any one please help to find the solution.

Body:
<cfset myReplace = reReplaceNoCase(mystring, '\b(itemscope|itemprop)="[^"]*"', "", "all")) />

https://trycf.com/gist/8d84d7d355f7c54e5533eeed22d097ba/acf2016?theme=monokai


来源: stackexchange

问:
Best practices for writing SQL scripts for deployment
I was wondering what are the best practices in order to write SQL scripts to set up databases for production and/or development, for instance:

Should I include the CREATE DATABASE statement?

Should I create users for the database in the same script?

Is correct to disable FK check before executing the body of the script?

May I include the hole script in a transaction?

Is better to generate 1 script per database than one script for all of them?

Thanks!

答:
The best practices will differ considerably on whether it is the first time set-up or a new version being pushed.  For the first time set-up yes you need create database and create table scripts. For a new version, you need to script only the changes from the previous version, so no create database and no create table unless it is a new table. Now you need alter table statements becasue you don't want to lose the existing data. I do usually write stored procs, functions and views with a drop and create statment as dropping those pbjects doesn't generally affect the underlying data.

I find it best to create all database changes with scripts that are stored in source control under the version. So if a client is new, you run the create version 1.0 scripts, then apply all the other versions in order. If a client is just upgrading from version 1.2 to version 1.3, then you run just the scripts in version 1.3 source control repository. This would also include scripts to populate or add records to lookup tables.

For transactions you may want to break them up into several chunks not to leave a prod database locked in one transaction.

We also write reversal scripts to return to the old version if need be.  This makes life easier if you have a part of a change that causes unanticipated problems on prod (usually performance issues).

ContentLicense: CC BY-SA 2.5


问:
Python Requests SSL Error inconsistency
So here is the situation.

I am running a python script that should log into a website, and save the cookies to do more operations in the website.
The program runs as expected on my computer, but... When I brought it to my Boss' computer, the program failed.

Here is the traceback message:

```<code>requests.exceptions.SSLError: HTTPSConnectionPool(host='www.somehost.com', port=443): Max retries exceeded with url: www.somehost.com (Caused by SSLError(SSLError(1, u'[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)'),))
</code>```

This is my code:

```<code>from requests import Session

# create the session variable
s = Session()

# get the cookie format of any web page that will kick the bot out to log in
s.get(base_url + "prodmirr/servlet/Product/additional_template_list.html", verify=False)
</code>```

It is definitely not a firewall issue. It can run as expected on my computer, even though I am cursed with McAfee, and my boss is lucky enough to use Windows Defender. We checked, and there is nothing that is blocked on his computer. We are both running the latest version of Windows 10.

We both have the same version of urllib. The solution in the possible duplicate question has changed nothing at all.

If any additional information is needed, please do not hesitate to ask.
Thanks in advance.

答:
I have solved the problem, after working on it almost all day. All of these issues seem to be happening with Requests Version 2.18.4, which is what my boss was using.

I am using version 2.11.1

To go from 2.18.4 to 2.11.1, simply execute the following commands in cmd.exe

```<code>pip uninstall requests
pip install requests==2.11.1
</code>```

This fixes all problems with SSL. Thanks for your help.

ContentLicense: CC BY-SA 3.0

Title: Python Requests SSL Error inconsistency

Body:
So here is the situation.

I am running a python script that should log into a website, and save the cookies to do more operations in the website.
The program runs as expected on my computer, but... When I brought it to my Boss' computer, the program failed.

Here is the traceback message:

requests.exceptions.SSLError: HTTPSConnectionPool(host='www.somehost.com', port=443): Max retries exceeded with url: www.somehost.com (Caused by SSLError(SSLError(1, u'[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)'),))

This is my code:

from requests import Session

# create the session variable
s = Session()

# get the cookie format of any web page that will kick the bot out to log in
s.get(base_url + "prodmirr/servlet/Product/additional_template_list.html", verify=False)

It is definitely not a firewall issue. It can run as expected on my computer, even though I am cursed with McAfee, and my boss is lucky enough to use Windows Defender. We checked, and there is nothing that is blocked on his computer. We are both running the latest version of Windows 10.

We both have the same version of urllib. The solution in the possible duplicate question has changed nothing at all.

If any additional information is needed, please do not hesitate to ask.
Thanks in advance.

Body:
I have solved the problem, after working on it almost all day. All of these issues seem to be happening with Requests Version 2.18.4, which is what my boss was using.

I am using version 2.11.1

To go from 2.18.4 to 2.11.1, simply execute the following commands in cmd.exe

pip uninstall requests
pip install requests==2.11.1

This fixes all problems with SSL. Thanks for your help.


问:
get value of specific resource string
I have developed a multilingual application where my resource file resides in App_GlobalResources. Resource file structure is as below:

App_GlobalResources

--------Resource.ar.resx

--------Resource.resx

I want to display resourcekey value with both culture. How can I get value of specific resourcekey in both culture.

答:
you can do this with ResourceManager</p>

```<code>        ResourceManager rm = new ResourceManager(typeof(*Your Resource Class*));
        rm.GetString("Resource Key", new CultureInfo("en"));
        rm.GetString("Resource Key", new CultureInfo("ar"));
</code>```

Title: get value of specific resource string

Body:
you can do this with ResourceManager

        ResourceManager rm = new ResourceManager(typeof(*Your Resource Class*));
        rm.GetString("Resource Key", new CultureInfo("en"));
        rm.GetString("Resource Key", new CultureInfo("ar"));


问:
Can anyone help me to add text to my d3 force graph?
I'm making a d3 force graph and I like to post some text on each node. I search on the internet and I only found SVG solutions but in my code, I don't use the SVG but I found that u can use d3 events like mouse over and I don't understand how to put it in my code.

with this code structure can anyone help me to solve my problem?

```<code><body>
  <h1>Graph</h1>
  <canvas id="network" width="1000" height="1000"></canvas>

  <script src="https://d3js.org/d3.v4.min.js"></script>

  <script>
  /* global d3 */
  var canvas = d3.select("#network"),
    width = canvas.attr("width"),
    height = canvas.attr("height"),
    ctx = canvas.node().getContext("2d"),
    r = 10,
    x = d3.scaleOrdinal().range([20,width -20]),
    color = d3.scaleOrdinal(d3.schemeCategory20),
    simulation = d3.forceSimulation()
      .force("x", d3.forceX(width/2))
      .force("y", d3.forceY(height/2))
      .force("collide", d3.forceCollide(r+1))
      .force("charge", d3.forceManyBody()
        .strength(-200))
      .force("link", d3.forceLink()
        .id(function (d) { return d.champion; }));

  d3.json("docs/Champions.json", function (err, graph) {
    if (err) throw err;

    simulation.nodes(graph.nodes);
    simulation.force("link")
      .links(graph.links);
    simulation.on("tick", update);

    canvas
        .call(d3.drag()
            .container(canvas.node())
            .subject(dragsubject)
            .on("start", dragstarted)
            .on("drag", dragged)
            .on("end", dragended));

    function update() {
      ctx.clearRect(0, 0, width, height);

      ctx.beginPath();
      ctx.globalAlpha = 0.5;
      ctx.strokeStyle = "#808080";
      graph.links.forEach(drawLink);
      ctx.stroke();

      ctx.globalAlpha = 1.0;
      graph.nodes.forEach(drawNode);
    }

    function dragsubject() {
      return simulation.find(d3.event.x, d3.event.y);
    }

  });

  function dragstarted() {
    if (!d3.event.active) simulation.alphaTarget(0.3).restart();
    d3.event.subject.fx = d3.event.subject.x;
    d3.event.subject.fy = d3.event.subject.y;
    console.log(d3.event.subject.champion);
  }

  function dragged() {
    d3.event.subject.fx = d3.event.x;
    d3.event.subject.fy = d3.event.y;
  }

  function dragended() {
    if (!d3.event.active) simulation.alphaTarget(0);
    d3.event.subject.fx = null;
    d3.event.subject.fy = null;
  }

  function drawNode(d) {
    ctx.beginPath();
    ctx.fillStyle = color(d.region);
    ctx.moveTo(d.x, d.y);
    ctx.arc(d.x, d.y, r, 0, Math.PI*2);
    ctx.fill();
  }

  function drawLink(l) {
    ctx.moveTo(l.source.x, l.source.y);
    ctx.lineTo(l.target.x, l.target.y);
  }

  </script>

</body>
</html>
</code>```

The JSON file that I use is like

```<code>{ "nodes": [
  {"champion":"name",
  "region":"place"},
   {...}
  ],
  "links": [
  {"source": "...",
   "target":"..."},
  {...}
]}
</code>```

答:
It's been a while since this was asked, but since i also wondered how to achieve what was asked in the original question, here's the solution for the record:

In order to add the text from e.g. the "champion" field of the JSON file, add the following line:

```<code>ctx.fillText(d.champion, d.x, d.y);
</code>```

to the function:

```<code>function drawNode(d)
</code>```

e.g.:

```<code>function drawNode(d) {
   ctx.beginPath();
   ctx.fillStyle = color(d.region);
   ctx.moveTo(d.x, d.y);
   ctx.arc(d.x, d.y, r, 0, Math.PI*2);
   ctx.fill();
   ctx.fillText(d.champion, d.x, d.y);
}
</code>```

Body:
I'm making a d3 force graph and I like to post some text on each node. I search on the internet and I only found SVG solutions but in my code, I don't use the SVG but I found that u can use d3 events like mouse over and I don't understand how to put it in my code.

with this code structure can anyone help me to solve my problem?

Graph

  <canvas id="network" width="1000" height="1000"></canvas>

The JSON file that I use is like

{ "nodes": [
  {"champion":"name",
  "region":"place"},
   {...}
  ],
  "links": [
  {"source": "...",
   "target":"..."},
  {...}
]}

Body:
It's been a while since this was asked, but since i also wondered how to achieve what was asked in the original question, here's the solution for the record:

In order to add the text from e.g. the "champion" field of the JSON file, add the following line:

ctx.fillText(d.champion, d.x, d.y);

to the function:

function drawNode(d)

e.g.:

function drawNode(d) {
   ctx.beginPath();
   ctx.fillStyle = color(d.region);
   ctx.moveTo(d.x, d.y);
   ctx.arc(d.x, d.y, r, 0, Math.PI*2);
   ctx.fill();
   ctx.fillText(d.champion, d.x, d.y);
}


问:
How to update an individual port tree in Freebsd ports?
I tried portupgrade -a more than 2 hours ago and it is still upgrading. Come to think of it, I didn't really need to upgrade the whole ports trees. The one I needed to update is pecl-APC which resides under www/. Could someone tell me how to update only that specific port? Thank you in advance.</p>

答: You can use : portupgrade -R app_name</p>

Body: You can use : portupgrade -R app_name


问:
Not able to install dockerized Pact-broker on centos
I'm trying to setup pact broker in centos machine using the instructions mentioned at https://github.com/DiUS/pact_broker-docker

I have installed docker and installed postgresql (not in docker container, but as separate service).

I tried running following command (bundled in https://github.com/DiUS/pact_broker-docker)

docker run --name pactbroker --link pactbroker-db:postgres -e PACT_BROKER_DATABASE_USERNAME=pactbrokeruser -e PACT_BROKER_DATABASE_PASSWORD=Thtest -e PACT_BROKER_DATABASE_HOST=postgres -e PACT_BROKER_DATABASE_NAME=pactbroker -d -p 80:80 dius/pact-broker

and i'm getting following message

Unable to find image 'dius/pact-broker:latest' locally
Pulling repository dius/pact-broker
Get https://index.docker.io/v1/repositories/dius/pact-broker/images: dial tcp 54.236.81.192:443: connection timed out

tried different mechanism like
1. ran script/test.sh
2. cd pact_broker-docker-master ; docker build .

still no luck.

More details :

uname -a

Linux mock-tomcat-132867461-1-210308209 2.6.32-504.30.3.el6.x86_64 #1 SMP Wed Jul 15 10:13:09 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux .

cat /etc/*release

CentOS release 6.9 (Final)
LSB_VERSION=base-4.0-amd64:base-4.0-noarch:core-4.0-amd64:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-noarch
CentOS release 6.9 (Final)
CentOS release 6.9 (Final)

Note: my machine is behind the company proxy.

答:
I think your company's proxy is the issue. The relevant error message is:

```<code>Unable to find image 'dius/pact-broker:latest' locally
Pulling repository dius/pact-broker
Get https://index.docker.io/v1/repositories/dius/pact-broker/images: dial tcp 54.236.81.192:443: connection timed out
</code>```

Try doing docker pull dius/pact-broker:latest and I'm guessing you'll see the same issue.

Perhaps this blog post will help you debug your proxy issues. Good luck.

Body:
I think your company's proxy is the issue. The relevant error message is:

Unable to find image 'dius/pact-broker:latest' locally
Pulling repository dius/pact-broker
Get https://index.docker.io/v1/repositories/dius/pact-broker/images: dial tcp 54.236.81.192:443: connection timed out

Try doing docker pull dius/pact-broker:latest and I'm guessing you'll see the same issue.

Perhaps this blog post will help you debug your proxy issues. Good luck.


问:
JavaScript Raphael using delay
I have this code, but the delay on the animations is is only from the start of the animation, and the generation of circles is not spread out as they all appear at once.

```<code>function generateCircles2(){
    if (totalDelay < 110){
       totalDelay += 1;
       var position = Math.floor(Math.random() * 600);
       var size = Math.floor(Math.random() * 8);
       var circle = paper.circle(-50,position,size);
       var time = Math.floor(Math.random() * 4000) + 2000;
       circle.attr("fill", "#000000");
       var cirAni = Raphael.animation({cy: position, cx: 850}, time, generateCircles3());
       circle.animate(cirAni.delay(100));

    }
}

function generateCircles3(){
    var position = Math.floor(Math.random() * 600);
    var size = Math.floor(Math.random() * 8);
    var circle = paper.circle(-50,position,size);
    var time = Math.floor(Math.random() * 4000) + 2000;
    circle.attr("fill", "#000000");
    var cirAni = Raphael.animation({cy: position, cx: 850}, time, generateCircles2());
    circle.animate(cirAni.delay(100));
}
</code>```

How can I get the circles generated one every 100ms and not all at once? Thanks

答:
I played with your fiddle. It was not working. But then I got it working.

I fiddled with it a bit. Here is what I got. I am not 100% sure if this is what you are looking for tho.

Created this new fiddle

Basically, what I did was to separate instantiation of each circle 100 ms apart.

```<code>var paper = Raphael(0, 0, 800, 600);

function generateCircles2() {
  if (totalDelay < 110) {
  setTimeout(function(){
    totalDelay += 1;
    var position = Math.floor(Math.random() * 600);
    var size = Math.floor(Math.random() * 8);
    var circle = paper.circle(-50, position, size);
    var time = Math.floor(Math.random() * 4000) + 2000;
    circle.attr("fill", "#000000");
    var cirAni = Raphael.animation({
      cy: position,
      cx: 850
    }, time, generateCircles3());
    circle.animate(cirAni.delay(100));
    }, 100);

  }
}

function generateCircles3() {
setTimeout(function(){
  var position = Math.floor(Math.random() * 600);
  var size = Math.floor(Math.random() * 8);
  var circle = paper.circle(-50, position, size);
  var time = Math.floor(Math.random() * 4000) + 2000;
  circle.attr("fill", "#000000");
  var cirAni = Raphael.animation({
    cy: position,
    cx: 850
  }, time, generateCircles2());
  circle.animate(cirAni.delay(100));
  },100);
}

var totalDelay = 0;
generateCircles2();
</code>```

Title: JavaScript Raphael using delay

Body:
I have this code, but the delay on the animations is is only from the start of the animation, and the generation of circles is not spread out as they all appear at once.

function generateCircles2(){
    if (totalDelay < 110){
       totalDelay += 1;
       var position = Math.floor(Math.random() * 600);
       var size = Math.floor(Math.random() * 8);
       var circle = paper.circle(-50,position,size);
       var time = Math.floor(Math.random() * 4000) + 2000;
       circle.attr("fill", "#000000");
       var cirAni = Raphael.animation({cy: position, cx: 850}, time, generateCircles3());
       circle.animate(cirAni.delay(100));

    }
}

function generateCircles3(){
    var position = Math.floor(Math.random() * 600);
    var size = Math.floor(Math.random() * 8);
    var circle = paper.circle(-50,position,size);
    var time = Math.floor(Math.random() * 4000) + 2000;
    circle.attr("fill", "#000000");
    var cirAni = Raphael.animation({cy: position, cx: 850}, time, generateCircles2());
    circle.animate(cirAni.delay(100));
}

How can I get the circles generated one every 100ms and not all at once? Thanks

Body:
I played with your fiddle. It was not working. But then I got it working.

I fiddled with it a bit. Here is what I got. I am not 100% sure if this is what you are looking for tho.

Created this new fiddle

Basically, what I did was to separate instantiation of each circle 100 ms apart.

var paper = Raphael(0, 0, 800, 600);

function generateCircles2() {
  if (totalDelay < 110) {
  setTimeout(function(){
    totalDelay += 1;
    var position = Math.floor(Math.random() * 600);
    var size = Math.floor(Math.random() * 8);
    var circle = paper.circle(-50, position, size);
    var time = Math.floor(Math.random() * 4000) + 2000;
    circle.attr("fill", "#000000");
    var cirAni = Raphael.animation({
      cy: position,
      cx: 850
    }, time, generateCircles3());
    circle.animate(cirAni.delay(100));
    }, 100);

  }
}

function generateCircles3() {
setTimeout(function(){
  var position = Math.floor(Math.random() * 600);
  var size = Math.floor(Math.random() * 8);
  var circle = paper.circle(-50, position, size);
  var time = Math.floor(Math.random() * 4000) + 2000;
  circle.attr("fill", "#000000");
  var cirAni = Raphael.animation({
    cy: position,
    cx: 850
  }, time, generateCircles2());
  circle.animate(cirAni.delay(100));
  },100);
}

var totalDelay = 0;
generateCircles2();


问:
Web API GET that takes optional parameters that can have multiple values for the same named parameter
I need to develop a new web API GET that will have multiple optional parameters along with 2 parameters that will not be optional. The optional parameters can have multiple values for the same name. For example, the following parameters can have several values at the same time with one api call:
State, PaymentType, PaymentSource.

The non optional parameters would be FromDate and ToDate.

The optional parameters will be populated from user selected values from a front end UI list boxes. So for example the State listbox will have all states listed as selectable options. So if the user selects 10 states then the optional State parameter for the API needs to contain all 10 states as a value for that parameter. The same will be true for the other optional parameters as well.

I have never done this before so I'm not sure how or if this can be done. All APIs that I have experience with only had a single value for each parameter. How can these parameters for my API be created this way ? should they be a list ?

答:
This should do the trick

```<code>[Route("api/foo/{State}/{PaymentType}/{PaymentSource}/{FromDate?}/{ToDate?}")]
public IHttpActionResult Get([FromUri] List<string> State, [FromUri] List<string> PaymentType, [FromUri] List<string> PaymentSource, [FromUri] List<string> FromDate = null, [FromUri] List<string> ToDate = null)
{ ... }
</code>```

The query string parameter should be of this format

```<code>~/api/foo?State[]=value1&State[]=value2&PaymentType[]=...
</code>```

Body:
This should do the trick

[Route("api/foo/{State}/{PaymentType}/{PaymentSource}/{FromDate?}/{ToDate?}")]
public IHttpActionResult Get([FromUri] List<string> State, [FromUri] List<string> PaymentType, [FromUri] List<string> PaymentSource, [FromUri] List<string> FromDate = null, [FromUri] List<string> ToDate = null)
{ ... }

The query string parameter should be of this format

~/api/foo?State[]=value1&State[]=value2&PaymentType[]=...


问:
Generic Build failure - check logs for details
My build fails without any useful information. The problem started when I added ethers library as a dependency to my package.json file.

Here's output from web console:

```<code>Pulling image "registry.access.redhat.com/rhscl/nodejs-6-rhel7@sha256:0860a4ccdc062f5ab05ec872298557f02f79c94b75820ded9a16211d8ab390ce" ...
---> Installing application source ...
---> Building your Node application from source
> grpc@1.7.1 install /opt/app-root/src/node_modules/grpc
> node-pre-gyp install --fallback-to-build --library=static_library
</code>```

Command oc status -v gives nothing usefull either.

All I can say is that the issue has something to do with node-pre-gyp or node-gyp compiling. I'm totally out of my depth here. Any advice?

答:
The npm installer can at times chew up quite a lot of memory when doing installs and require more than the default memory resources given to a build pod. When it fails due to that, there aren't really any messages in the logs. You may see something in events under monitoring.

The default memory resources for a build is 512Mi. See following answer which deals with similar issue for Python:

Pandas on OpenShift v3

for description of how to increase memory available to a build.

Body:
My build fails without any useful information. The problem started when I added ethers library as a dependency to my package.json file.

Here's output from web console:

Pulling image "registry.access.redhat.com/rhscl/nodejs-6-rhel7@sha256:0860a4ccdc062f5ab05ec872298557f02f79c94b75820ded9a16211d8ab390ce" ...
---> Installing application source ...
---> Building your Node application from source
> grpc@1.7.1 install /opt/app-root/src/node_modules/grpc
> node-pre-gyp install --fallback-to-build --library=static_library

Command oc status -v gives nothing usefull either.

All I can say is that the issue has something to do with node-pre-gyp or node-gyp compiling. I'm totally out of my depth here. Any advice?


问:
C printf %d incorrect value with leading zeros?
The C function printf seems to print different values depending on whether or not leading zeros are present.

I was trying to determine the numerical values for the mode argument in the Linux 'open' system call.

printf("mode:%d\n",S_IRWXU);

printf("mode:%d\n",00700);

both gave me 448, while

printf("mode:%d\n",700); gives me 700, as I would expect from both.

What is going on here?

I am using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.5) 5.4.0 20160609

答:
A numerical constant with one or more leading zeros is an octal constant, while one without a leading zero is a decimal constant and one with a leading 0x is a hexadecimal constant.  This holds in any context, whether the value is passed to printf or any other function.

In the case of printf, you're using the %d format specifier which prints the value in decimal.  If you pass in an octal constant, you'll see the decimal value of that octal number.  In this example, 0700b8 == 7 * 8^2 + 0 * 8^1 + 0 * 8^0 == 7 * 64 == 448b10

If you're dealing with file permissions, those values are typically denoted as octal, so you should always use a leading 0 with those.


问:
Convert n-byte int to bytes in python3
I want to convert an 32-byte (although I might need other lengths) integer to a bytes object in python. Is there a clean and simple way to do this?</p>

答:
I'm guessing you need a 32-bit integer, and big-endian to boot:

```<code>>>> from ctypes import c_uint32
>>> l = c_uint32(0x12345678)
>>> bytes(l)
b'xV4\x12'
</code>```

There is c_uint8, c_uint16 and c_uint64 as well. For longer ints you need to make it manually, using divmod(x, 256).

```<code>>>> def bytify(v):
...   v, r = divmod(v, 256)
...   yield r
...   if v == 0:
...      raise StopIteration
...   for r in bytify(v):
...     yield r
...
>>> [x for x in bytify(0x12345678)]
[120, 86, 52, 18]
>>> bytes(bytify(0x12345678))
b'xV4\x12
>>> bytes(bytify(0x123456789098765432101234567890987654321))
b'!Ce\x87\t\x89gE#\x01!Ce\x87\t\x89gE#\x01'
</code>```

Title: Convert n-byte int to bytes in python3

Body:
I'm guessing you need a 32-bit integer, and big-endian to boot:

>>> from ctypes import c_uint32
>>> l = c_uint32(0x12345678)
>>> bytes(l)
b'xV4\x12'

There is c_uint8, c_uint16 and c_uint64 as well. For longer ints you need to make it manually, using divmod(x, 256).

>>> def bytify(v):
...   v, r = divmod(v, 256)
...   yield r
...   if v == 0:
...      raise StopIteration
...   for r in bytify(v):
...     yield r
...
>>> [x for x in bytify(0x12345678)]
[120, 86, 52, 18]
>>> bytes(bytify(0x12345678))
b'xV4\x12
>>> bytes(bytify(0x123456789098765432101234567890987654321))
b'!Ce\x87\t\x89gE#\x01!Ce\x87\t\x89gE#\x01'


问:
why angular2 component constructor parameters must be provided
I am brand new to Angular. When I am doing the Heros tutorial, I noticed type of component constructor parameters must be a dependency. In other words, I must include it in providers array.

For example:

```<code>import { SomeServiceClass } from '...';
@Component({
  ...
})
export class MyComponent implements OnInit {

  constructor(input1: SomeServiceClass) { }

  ngOnInit() {
  }
}
</code>```

This code is not going to work unless I include SomeServiceClass in providers array. I tried input1: string. It doesn't work neither! I believe it is totally valid typescript code. The problem must be the way angular2 instantiates the component classes.

Question 1: How are component classed actually instantiated by Angular?

And, since I never instantiate service class, I can't imagine which service class instance is passed to component constructor.

Question 2: Does angular create one instance of service to be used by every component or it generates one instance for each component?

答:
This code is not going to work unless I include SomeServiceClass in providers array. I tried input1: string. It doesn't work neither! I believe it is totally valid typescript code. The problem must be the way angular2 instantiates the component classes.

The reason you need to add SomeServiceClass to a providers array of somengModule is simple. Angular chose not to perform any dependency analysis based on code structure. They could have used the ES Module import in the injecting component to resolve the dependency and auto register it.

As evidence, Aurelia does exactly that.

In other words, in Aurelia, the following is sufficient to inject and use a dependency

```<code>import {autoinject} from 'aurelia-framework';
import {SomeServiceClass} from '...';

@autoinject export class MyComponent {
  constructor(input1: SomeServiceClass) {}
}
</code>```

And it works.

How are component classed actually instantiated by Angular?

And, since I never instantiate service class, I can't imagine which service class instance is passed to component constructor.

A class in JavaScript is really a constructor function, and a constructor function is really a glorified factory function, and a factory function is really a glorified function.

What does that mean?

It means that Angular (and most DI frameworks) simply create an instance of the service when it is first requested by calling the provided class with new.

A simplified version of such code might look like

```<code>function instantiateComponent<T>(Component: new (...args: any[]) => T) {
  const requiredDependencies = resolveDependencies(Component);

  return new Component(...requiredDependencies);
}

function resolveDependencies(Dep: new (...args: any[]) => any): object[] {
  const requiredDependencies = metaDataUtils.getDependencies(Dep);

  return requiredDependencies.map(Dep => {
     const alreadyCreatedDependency = injectorCache.find(dep => dep instanceof Dep);

     if(alreadyCreatedDependency !== undefined) {
       return alreadyCreatedDependency;
     }
     else {
       const requiredDependencies = metaDataUtils.getDependencies(Dep);

       // resolution is recursive
       const newDependency = new Dep(...requiredDependencies.map(resolveDependencies));

       injectorCache.push(newDependency);

       return newDependency;
     }
  });
}
</code>```

Does angular create one instance of service to be used by every component or it generates one instance for each component?

This one is tricky, by default only one instance is created per application.

This is an application level singleton and all components requesting it receive the same instance.

However, there are different implicit and explicit behaviors in Angular as well.

If a lazily loaded ngModule lists the same service in its providers array, a second instance will be created and that instance will be shared by children of the lazily loaded module. That is actually an over simplification but it is already confusing and, given that whether or not a module is loaded lazily is determined by its consumers, it can lead to serious and subtle bugs.

Finally, a component may explicitly declare its own providers in the @Component metadata. Any component doing so have will have a new instance of the service created and shared by all instances of that component.

Note: Just to be specific when you say

I noticed type of component constructor parameters must be a dependency.

you are not strictly correct. Dependencies are not types, they are values. TypeScript types are completely erased at compile time and what actually gets injected are values. A class is a value

```<code>class C {}
</code>```

but TypeScript also infers the existence of some types from its declaration. But what is injected is the value C, not the type C.

Body:
I am brand new to Angular. When I am doing the Heros tutorial, I noticed type of component constructor parameters must be a dependency. In other words, I must include it in providers array.

For example:

import { SomeServiceClass } from '...';
@Component({
  ...
})
export class MyComponent implements OnInit {

  constructor(input1: SomeServiceClass) { }

  ngOnInit() {
  }
}

This code is not going to work unless I include SomeServiceClass in providers array. I tried input1: string. It doesn't work neither! I believe it is totally valid typescript code. The problem must be the way angular2 instantiates the component classes.

Question 1: How are component classed actually instantiated by Angular?

And, since I never instantiate service class, I can't imagine which service class instance is passed to component constructor.

Question 2: Does angular create one instance of service to be used by every component or it generates one instance for each component?

Body:
This code is not going to work unless I include SomeServiceClass in providers array. I tried input1: string. It doesn't work neither! I believe it is totally valid typescript code. The problem must be the way angular2 instantiates the component classes.

The reason you need to add SomeServiceClass to a providers array of somengModule is simple. Angular chose not to perform any dependency analysis based on code structure. They could have used the ES Module import in the injecting component to resolve the dependency and auto register it.

As evidence, Aurelia does exactly that.

In other words, in Aurelia, the following is sufficient to inject and use a dependency

import {autoinject} from 'aurelia-framework';
import {SomeServiceClass} from '...';

@autoinject export class MyComponent {
  constructor(input1: SomeServiceClass) {}
}

And it works.

How are component classed actually instantiated by Angular?

And, since I never instantiate service class, I can't imagine which service class instance is passed to component constructor.

A class in JavaScript is really a constructor function, and a constructor function is really a glorified factory function, and a factory function is really a glorified function.

What does that mean?

It means that Angular (and most DI frameworks) simply create an instance of the service when it is first requested by calling the provided class with new.

A simplified version of such code might look like

function instantiateComponent<T>(Component: new (...args: any[]) => T) {
  const requiredDependencies = resolveDependencies(Component);

  return new Component(...requiredDependencies);
}

function resolveDependencies(Dep: new (...args: any[]) => any): object[] {
  const requiredDependencies = metaDataUtils.getDependencies(Dep);

  return requiredDependencies.map(Dep => {
     const alreadyCreatedDependency = injectorCache.find(dep => dep instanceof Dep);

     if(alreadyCreatedDependency !== undefined) {
       return alreadyCreatedDependency;
     }
     else {
       const requiredDependencies = metaDataUtils.getDependencies(Dep);

       // resolution is recursive
       const newDependency = new Dep(...requiredDependencies.map(resolveDependencies));

       injectorCache.push(newDependency);

       return newDependency;
     }
  });
}

Does angular create one instance of service to be used by every component or it generates one instance for each component?

This one is tricky, by default only one instance is created per application.

This is an application level singleton and all components requesting it receive the same instance.

However, there are different implicit and explicit behaviors in Angular as well.

If a lazily loaded ngModule lists the same service in its providers array, a second instance will be created and that instance will be shared by children of the lazily loaded module. That is actually an over simplification but it is already confusing and, given that whether or not a module is loaded lazily is determined by its consumers, it can lead to serious and subtle bugs.

Finally, a component may explicitly declare its own providers in the @Component metadata. Any component doing so have will have a new instance of the service created and shared by all instances of that component.

Note: Just to be specific when you say

I noticed type of component constructor parameters must be a dependency.

you are not strictly correct. Dependencies are not types, they are values. TypeScript types are completely erased at compile time and what actually gets injected are values. A class is a value

class C {}

but TypeScript also infers the existence of some types from its declaration. But what is injected is the value C, not the type C.

ContentLicense: CC BY-SA 4.0


问:
Convert from Iterable to Page Object
I have a method which returns all the documents found in the couchbase repo and the result is a Page<MyObject> object which is fine:

```<code>...
import org.springframework.data.domain.Page;

  Page<MyObject> myObjects = myRepo
      .findAll(new PageRequest(page == null ? 0 : page, size));
...
</code>```

And I have another method which returns a Iterable<MyObject> as you can see below. The method is working fine and the results retrieved from couchbase are ok.

```<code>...
  Bucket myBucket = myRepo.getCouchbaseOperations().getCouchbaseBucket();
  PrefixQuery field = SearchQuery.prefix(searchParameter);

  SearchQueryResult searchQueryResult = myBucket
    .query(new SearchQuery("text-search", field)
    .fields("name").explain());

  List <String> idList = new ArrayList<>();
  for (SearchQueryRow searchQueryRow : searchQueryResult.hits()) {
    idList.add(searchQueryRow.id());
  }

  Iterable<MyObject> myObjects = myRepo.findAll(idList);
...
</code>```

My question is: How can I convert Iterable<MyObject> myObjects into a Page<MyObject> myObjects?

答:
I finally found how to do it, I'm posting the answer in case it can help anyone in the future. I achieved it by doing:</p>

```<code>Iterable<MyObject> myObjects = myRepo.findAll(idList);
List<MyObject> myObjectsList = IteratorUtils.toList(myObjects.iterator());
Page<MyObject> myObjectsPage = new PageImpl<MyObject>(
                                     myObjectsList,
                                     new PageRequest(page, size),
                                     myObjectsList.size());
</code>```

Title: Convert from Iterable to Page Object

Body:
I have a method which returns all the documents found in the couchbase repo and the result is a Page<MyObject> object which is fine:

...
import org.springframework.data.domain.Page;

  Page<MyObject> myObjects = myRepo
      .findAll(new PageRequest(page == null ? 0 : page, size));
...

And I have another method which returns a Iterable<MyObject> as you can see below. The method is working fine and the results retrieved from couchbase are ok.

...
  Bucket myBucket = myRepo.getCouchbaseOperations().getCouchbaseBucket();
  PrefixQuery field = SearchQuery.prefix(searchParameter);

  SearchQueryResult searchQueryResult = myBucket
    .query(new SearchQuery("text-search", field)
    .fields("name").explain());

  List <String> idList = new ArrayList<>();
  for (SearchQueryRow searchQueryRow : searchQueryResult.hits()) {
    idList.add(searchQueryRow.id());
  }

  Iterable<MyObject> myObjects = myRepo.findAll(idList);
...

My question is: How can I convert Iterable<MyObject> myObjects into a Page<MyObject> myObjects?

Body:
I finally found how to do it, I'm posting the answer in case it can help anyone in the future. I achieved it by doing:

Iterable<MyObject> myObjects = myRepo.findAll(idList);
List<MyObject> myObjectsList = IteratorUtils.toList(myObjects.iterator());
Page<MyObject> myObjectsPage = new PageImpl<MyObject>(
                                     myObjectsList,
                                     new PageRequest(page, size),
                                     myObjectsList.size());


问:
Python loop ending but then ends but then repeats for no reason
I am making a program for the backend of a profiling system for my exam practice. I have the username and passwords stored in a .txt file. It says it is valid when I enter the password and goes to the next part of the program but then loops back and asks for the details again???

Here is my code where I think the problem is:

```<code>def Login(): #Login function
    f = open('login.txt','r')
    username = f.readline().strip()
    password = f.readline().strip()

    usernameLog = input('Please enter your username: ')

    validuser = False
    while validuser == False:
        if usernameLog == username:
            print('Username accepted')

            time.sleep(1)

            userpassLog = input('Please enter a password: ')

            if userpassLog == password:
                print('Successfully logged in')

                time.sleep(0.5)
                Options()
                validuser = True
            else:
                print('Please enter a valid password')
            validuser = False
        else:
            print('Invalid username please re-enter it.')
            validuser = False
            Login()
    f.close()
</code>```

答:
breaking solved the issue:</p>

```<code>while validuser == False:
    if usernameLog == username:
        print('Username accepted')

        time.sleep(1)

        userpassLog = input('Please enter a password: ')

        if userpassLog == password:
            validuser = True
            print('Successfully logged in')

            time.sleep(0.5)
            Options()
            break
</code>```

Body:
I am making a program for the backend of a profiling system for my exam practice. I have the username and passwords stored in a .txt file. It says it is valid when I enter the password and goes to the next part of the program but then loops back and asks for the details again???

Here is my code where I think the problem is:

def Login(): #Login function
    f = open('login.txt','r')
    username = f.readline().strip()
    password = f.readline().strip()

    usernameLog = input('Please enter your username: ')

    validuser = False
    while validuser == False:
        if usernameLog == username:
            print('Username accepted')

            time.sleep(1)

            userpassLog = input('Please enter a password: ')

            if userpassLog == password:
                print('Successfully logged in')

                time.sleep(0.5)
                Options()
                validuser = True
            else:
                print('Please enter a valid password')
            validuser = False
        else:
            print('Invalid username please re-enter it.')
            validuser = False
            Login()
    f.close()

Body:
breaking solved the issue:

while validuser == False:
    if usernameLog == username:
        print('Username accepted')

        time.sleep(1)

        userpassLog = input('Please enter a password: ')

        if userpassLog == password:
            validuser = True
            print('Successfully logged in')

            time.sleep(0.5)
            Options()
            break


问:
How can I clean up my user permissions code in Ruby/Rails?
I am writing a system where every user can manage other users' permissions.

I have a business requirement where a logged_in_user can't demote someone higher than them in rankings.  My positions are the following:

```<code>STAFF < MANAGER < ORGANIZATION_ADMIN
</code>```

I am trying to display the permission buttons for the users and have the following (ugly) method that gets the job done, but feels like awful code.

```<code># Iterate through all users and allow for their permissions to be modified
other_users.each do |other_user|
  buttons_to_show = get_buttons_to_show(logged_in_user, other_user)

  if buttons_to_show.include?(ORGANIZATION_ADMIN)
    puts "Make other_user #{ORGANIZATION_ADMIN}" # Will be a button on UI

  if buttons_to_show.include?(MANAGER)
    puts "Make other_user #{MANAGER}" # Will be a button on UI

  if buttons_to_show.include?(STAFF)
    puts "Make other_user #{STAFF}" # Will be a button on UI
end

def get_buttons_to_show(current_user, other_user)
  buttons_to_show = []

  if (current_user.at_least_staff? && other_user.role != MANAGER && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_manager? && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_organization_admin?)
    buttons_to_show << STAFF
  end

  if (current_user.at_least_manager? && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_organization_admin?)
    buttons_to_show << MANAGER
  end

  if current_user.at_least_organization_admin?
    buttons_to_show << ORGANIZATION_ADMIN
  end

  buttons_to_show
end
</code>```

答: I decided to use Pundit and move all of those methods into my policies.  Works like a charm and is much cleaner.</p>

Body:
I am writing a system where every user can manage other users' permissions.

I have a business requirement where a logged_in_user can't demote someone higher than them in rankings.  My positions are the following:

STAFF < MANAGER < ORGANIZATION_ADMIN

I am trying to display the permission buttons for the users and have the following (ugly) method that gets the job done, but feels like awful code.

# Iterate through all users and allow for their permissions to be modified
other_users.each do |other_user|
  buttons_to_show = get_buttons_to_show(logged_in_user, other_user)

  if buttons_to_show.include?(ORGANIZATION_ADMIN)
    puts "Make other_user #{ORGANIZATION_ADMIN}" # Will be a button on UI

  if buttons_to_show.include?(MANAGER)
    puts "Make other_user #{MANAGER}" # Will be a button on UI

  if buttons_to_show.include?(STAFF)
    puts "Make other_user #{STAFF}" # Will be a button on UI
end

def get_buttons_to_show(current_user, other_user)
  buttons_to_show = []

  if (current_user.at_least_staff? && other_user.role != MANAGER && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_manager? && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_organization_admin?)
    buttons_to_show << STAFF
  end

  if (current_user.at_least_manager? && other_user.role != ORGANIZATION_ADMIN) ||
      (current_user.at_least_organization_admin?)
    buttons_to_show << MANAGER
  end

  if current_user.at_least_organization_admin?
    buttons_to_show << ORGANIZATION_ADMIN
  end

  buttons_to_show
end


问:
Tableview hidden under navigation bar (but only for one tab)
I am using Xcode 5 with storyboard and auto layout. My views are:

root navigation view

tab view controller (its the default view for the navigation view)

two tab views

In both tab views, I put a UITableView on it, and I set up the standard IB stuff. Both tab view controllers are nearly identical in code in terms of setup (they both derive from UIViewController).

For the tableview however, things are weird. The first table view has the right setting, where the cells start "below the navigation" and you can scroll it up. The second table view starts with the cells "under the navigation" - it seems like the insets are wrong.

But why would it be wrong for just the second tab view, and not the first? I did not do anything funky with either, and I've pored over the code multiple times to be sure that both tableview controllers are nearly identical (except in the cell contents).

(on the second image, notice the bit of green under the "Carrier" status bar).

答:
As per my understanding, storyboard doesn't allow embedding tab bar controller inside navigation controller, so it look like it is not recommended design by apple. However, in one of my application I used this design and it stared causing issues with iOS 11 with introduction of safe area.

As a fix, I unchecked the "Under Top Bars" property of view controller where I was facing the issue.


问:
Can not figure out why dates are not restricted
This is my code from Shopify. I am trying to restrict holidays. The weekends are blocked out fine. Can someone please tell me why my unavailable dates does not work? I am trying to restrict holidays.</p>

```<code>var currentDate = new Date();
var n = currentDate.getHours();
var m = +2;

if (n < 14){
m = 4;
} else {
m = 5;
}

$(document).ready( function() {
      $(function() {
        $("#date").datepicker( {
          minDate: m,
          maxDate: '+2M',
          beforeShowDay: jQuery.datepicker.noWeekends
        } );
      });
    });

var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
var unavailableDates = ["2017/11/23","2017/11/24","2017/12/25","2017/12/26","2018/01/01"]; // yyyy/MM/dd
var unavailableDays = ["Saturday","Sunday"];

function unavailable(date) {
    ymd = date.getFullYear() + "/" + ("0"+(date.getMonth()+1)).slice(-2) + "/" + ("0"+date.getDate()).slice(-2);
    day = new Date(ymd).getDay();
    if ($.inArray(ymd, unavailableDates) < 0 && $.inArray(days[day], unavailableDays) < 0) {
        return [true, "enabled", "Book Now"];
    } else {
        return [false,"disabled","Booked Out"];
    }
}
</code>```

答:
This should do it:

var currentDate = new Date();
var n = currentDate.getHours();
var m = +2;

if (n < 14) {
  m = 4;
} else {
  m = 5;
}

var unavailableDates = ["2017/11/23", "2017/11/24", "2017/12/25", "2017/12/26", "2018/01/01"]; // yyyy/MM/dd

$(document).ready(function() {
  $(function() {
    $("#date").datepicker({
      minDate: m,
      maxDate: '+2M',
      beforeShowDay: function(date) {
        var noWeekend = $.datepicker.noWeekends(date);
        var datestring = jQuery.datepicker.formatDate('yy/mm/dd', date);
        if (noWeekend[0]) {
          return [unavailableDates.indexOf(datestring) == -1];
        } else return noWeekend;
      }
    });
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<p>Date: <input type="text" id="date"></p></code>```

Body:
This is my code from Shopify. I am trying to restrict holidays. The weekends are blocked out fine. Can someone please tell me why my unavailable dates does not work? I am trying to restrict holidays.

var currentDate = new Date();
var n = currentDate.getHours();
var m = +2;

if (n < 14){
m = 4;
} else {
m = 5;
}

$(document).ready( function() {
      $(function() {
        $("#date").datepicker( {
          minDate: m,
          maxDate: '+2M',
          beforeShowDay: jQuery.datepicker.noWeekends
        } );
      });
    });

var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
var unavailableDates = ["2017/11/23","2017/11/24","2017/12/25","2017/12/26","2018/01/01"]; // yyyy/MM/dd
var unavailableDays = ["Saturday","Sunday"];

function unavailable(date) {
    ymd = date.getFullYear() + "/" + ("0"+(date.getMonth()+1)).slice(-2) + "/" + ("0"+date.getDate()).slice(-2);
    day = new Date(ymd).getDay();
    if ($.inArray(ymd, unavailableDates) < 0 && $.inArray(days[day], unavailableDays) < 0) {
        return [true, "enabled", "Book Now"];
    } else {
        return [false,"disabled","Booked Out"];
    }
}

Body:
This should do it:

var currentDate = new Date();
var n = currentDate.getHours();
var m = +2;

if (n < 14) {
  m = 4;
} else {
  m = 5;
}

var unavailableDates = ["2017/11/23", "2017/11/24", "2017/12/25", "2017/12/26", "2018/01/01"]; // yyyy/MM/dd

$(document).ready(function() {
  $(function() {
    $("#date").datepicker({
      minDate: m,
      maxDate: '+2M',
      beforeShowDay: function(date) {
        var noWeekend = $.datepicker.noWeekends(date);
        var datestring = jQuery.datepicker.formatDate('yy/mm/dd', date);
        if (noWeekend[0]) {
          return [unavailableDates.indexOf(datestring) == -1];
        } else return noWeekend;
      }
    });
  });
});

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<p>Date: <input type="text" id="date"></p>


问:
ASP.NET MVC - Easy way to temporarily require authorisation for whole site except one page
I am building a site with a mixture of public and member-only pages.  The login system works fine as it is.

However I'd like to launch a closed, invite-only preview and temporarily require visitors log in for all actions except the welcome page.

Currently I have [Authorize] attributes on certain action methods.  I could add additional attributes to the other action methods too, but this feels a bit hacky and will make it harder to remove them correctly later when I want to revert to having more open content.

So, how can I effectively add a site-wide authorisation requirement?  Recall that I want the single /Home/Index route to remain public as well, so that people I've invited can read some information before activating their invites.

答:
I think doing this in the web.config file would be the best since it is temporary and will not require that you add any C# code or rely on roles/names etc.

Do the following in your web.config

```<code><configuration>
      <!-- system.web is the only already in your web.config
           don't add this, just add the authorization element
           to the existing system.web element -->
  <system.web>
     <authorization>
        <deny users="?"/>
     </authorization>
  </system.web>

  <!-- the login path -->
  <location path="Login/Index">
     <system.web>
        <authorization>
           <allow users="?"/>
        </authorization>
     </system.web>
  </location>

  <!-- welcome page -->
  <location path="Home/Index">
     <system.web>
        <authorization>
           <allow users="?"/>
        </authorization>
     </system.web>
  </location>

  <!-- static files (images, css, js etc.) folder -->
  <location path="Content">
     <system.web>
        <authorization>
           <allow users="?"/>
        </authorization>
     </system.web>
  </location>

</configuration>
</code>```

The first <authorization> element will restrict access to your application to only authenticated/logged in users. The subsequent <location> elements place exceptions on specific paths (login page, welcome screen and static files).

Make sure you verify that the path attribute is correct for each location based on your application.

Some more details on the location element can be found at MSDN 'location element'.

Body:
I think doing this in the web.config file would be the best since it is temporary and will not require that you add any C# code or rely on roles/names etc.

Do the following in your web.config

<configuration>
      <!-- system.web is the only already in your web.config
           don't add this, just add the authorization element
           to the existing system.web element -->
  <system.web>
     <authorization>
        <deny users="?"/>
     </authorization>
  </system.web>

  <!-- the login path -->
  <location path="Login/Index">
     <system.web>
        <authorization>
           <allow users="?"/>
        </authorization>
     </system.web>
  </location>

  <!-- welcome page -->
  <location path="Home/Index">
     <system.web>
        <authorization>
           <allow users="?"/>
        </authorization>
     </system.web>
  </location>

  <!-- static files (images, css, js etc.) folder -->
  <location path="Content">
     <system.web>
        <authorization>
           <allow users="?"/>
        </authorization>
     </system.web>
  </location>

</configuration>

The first <authorization> element will restrict access to your application to only authenticated/logged in users. The subsequent <location> elements place exceptions on specific paths (login page, welcome screen and static files).

Make sure you verify that the path attribute is correct for each location based on your application.

Some more details on the location element can be found at MSDN 'location element'.


问:
how to load .vbs files which are stored in c drive into uft 11.5 or 12.0
I have some code that I have written in VBScript and is stored as a .vbs file in my C:\ drive. How can I use that code in my UFT program?</p>

答: In your UFT program (GUItest) you can use the option of "Associate Function Library" by right clicking your test Associate Function Library in UFT. After selecting the option you can select your .vbs file and the functions in that file will be available for use</p>


问:
In Spock framework, how do I access data table variable from "error" listener?
I have a test with a data table, e.g. like this:

```<code>@Unroll
"Basic session start on platform = #platform"() {
    when: "user stats a session on a platform"
    def response = startSession(platform, id) // it does a REST request

    then: "response contains a userId"
    assert verifyUserId(response.userId) // method verifies userId with an internal algorithm and returns true\false if it is valid or not

    where:
    id | platform
    1  | "Facebook"
    2  | "Google"
    3  | "Apple"
}
</code>```

I have also wrote a listener for errors.

```<code>class MyListener extends AbstractListener {
...
   public void error(ErrorInfo error) { ... }
...
}
</code>```

So that in case an assertion error happens during test execution, the code goes into this "error" method.

The question is, how can I get values of variables from the "where" block from inside the "error" method?

I don't do direct assertions for the data table variables, so ErrorInfo.Exception does not contain them.

I also could not find any other suitable members of the "ErrorInfo" object - I can only find variable names in ErrorInfo.getMethod().getFeature(), but not their values that were there when the error happened.

答:
The main issue here is that ErrorInfo doesn't provide current spec instance, that's why you can't get iteration variables. So I would suggest two ways:

First one is to use iteration interceptor:

```<code>class ListenForErrorsExtension implements IGlobalExtension {

    void visitSpec(SpecInfo specInfo) {
        specInfo.addListener(new Listener())
        specInfo.allFeatures*.addIterationInterceptor(new IMethodInterceptor() {
            @Override
            void intercept(IMethodInvocation invocation) {
                holder.put(invocation.iteration.dataValues)
                invocation.proceed()
            }

        })
    }
</code>```

The second one was kindly suggested in comments by Opal. You could instantinate not AbstractRunListener, but IRunListener

```<code>class ErrorExtension implements IGlobalExtension{
....
    @Override
    void beforeIteration(IterationInfo iteration) {
        holder.put(iteration.dataValues)
    }
....
}
</code>```

It gives you access to each iterration, but the main idea is still following:

You have to create thread safe holder, put iterration data to it BEFORE error happened and then extract.

Body:
I have a test with a data table, e.g. like this:

@Unroll
"Basic session start on platform = #platform"() {
    when: "user stats a session on a platform"
    def response = startSession(platform, id) // it does a REST request

    then: "response contains a userId"
    assert verifyUserId(response.userId) // method verifies userId with an internal algorithm and returns true\false if it is valid or not

    where:
    id | platform
    1  | "Facebook"
    2  | "Google"
    3  | "Apple"
}

I have also wrote a listener for errors.

class MyListener extends AbstractListener {
...
   public void error(ErrorInfo error) { ... }
...
}

So that in case an assertion error happens during test execution, the code goes into this "error" method.

The question is, how can I get values of variables from the "where" block from inside the "error" method?

I don't do direct assertions for the data table variables, so ErrorInfo.Exception does not contain them.

I also could not find any other suitable members of the "ErrorInfo" object - I can only find variable names in ErrorInfo.getMethod().getFeature(), but not their values that were there when the error happened.

Body:
The main issue here is that ErrorInfo doesn't provide current spec instance, that's why you can't get iteration variables. So I would suggest two ways:

First one is to use iteration interceptor:

class ListenForErrorsExtension implements IGlobalExtension {

    void visitSpec(SpecInfo specInfo) {
        specInfo.addListener(new Listener())
        specInfo.allFeatures*.addIterationInterceptor(new IMethodInterceptor() {
            @Override
            void intercept(IMethodInvocation invocation) {
                holder.put(invocation.iteration.dataValues)
                invocation.proceed()
            }

        })
    }

The second one was kindly suggested in comments by Opal. You could instantinate not AbstractRunListener, but IRunListener

class ErrorExtension implements IGlobalExtension{
....
    @Override
    void beforeIteration(IterationInfo iteration) {
        holder.put(iteration.dataValues)
    }
....
}

It gives you access to each iterration, but the main idea is still following:

You have to create thread safe holder, put iterration data to it BEFORE error happened and then extract.


问:
Destroy orphaned polymorphic association in Active Record
I recently created a notifications system using a polymorphic association in my Rails application. All was working well until the system stopped showing notifications for certain users. I realized the culprit was an orphaned notification - where Notification.notifiable_id was returning a non-existent user. Here's a diagram:

Notification is created on Comment creation

User model:

```<code>has_many Notifications, dependent: destroy
</code>```

So there is still the possibility that The user responsible for creating the notification can delete their account, leaving the Notification record orphaned on one end.

Questions:
1. How do I delete all notifications where Notification.notifiable_id is not found?

How do I prevent this issue from breaking the Notifications system in the future?

I realized after posting this I had misunderstood the polymorphic association. I had actually set up Notification.notifiable to point back to a Comment created by a User, not the User itself.

I fixed issue #2 by modifying the Comment model (as well as other models acting as 'notifiable')

```<code>    has_many :notifications, as: :notifiable, dependent: :destroy
</code>```

答:
For your data fix

```<code>Notification.all.each do |notification|
  notification.destroy if notification.notifiable.nil?
end
</code>```

Looks like you are missing a colon on your dependent: :destroy. This would have prevented your Notifications from being properly destroyed when a User record is destroyed.

Body:
I recently created a notifications system using a polymorphic association in my Rails application. All was working well until the system stopped showing notifications for certain users. I realized the culprit was an orphaned notification - where Notification.notifiable_id was returning a non-existent user. Here's a diagram:

Notification is created on Comment creation

User model:

has_many Notifications, dependent: destroy

So there is still the possibility that The user responsible for creating the notification can delete their account, leaving the Notification record orphaned on one end.

Questions:
1. How do I delete all notifications where Notification.notifiable_id is not found?

How do I prevent this issue from breaking the Notifications system in the future?

I realized after posting this I had misunderstood the polymorphic association. I had actually set up Notification.notifiable to point back to a Comment created by a User, not the User itself.

I fixed issue #2 by modifying the Comment model (as well as other models acting as 'notifiable')

    has_many :notifications, as: :notifiable, dependent: :destroy

Body:
For your data fix

Notification.all.each do |notification|
  notification.destroy if notification.notifiable.nil?
end

Looks like you are missing a colon on your dependent: :destroy. This would have prevented your Notifications from being properly destroyed when a User record is destroyed.


问:
How to implement hyperparameter search in Tensorflow?
I would like to implement a hyperparameter search in Tensorflow, like the one presented in this video. Unfortunately I was not able to find any tutorials about it.

I've found some code which uses it, but I was not able to understand it properly. Implementing the bayesian optimization would be the best, but I would like to try the grid or random search first.

Should I create the different graphs before? How is it possible to do the training on multiple graphs, and how to compare them?

答:
You can use DyTB (dynamic training bench): this tool allows you to focus only on the hyperparameter search, using tensorboard to compare the measured stats of the varisous trained model.

DyTB creates for you a unique name associated with the current set of hyperparameters and use it as a log dir.
Creating different log directories allows the use of Tensorboard for an easy comparison.

For instance, you can train VGG on Cifar10 with this single line (both VGG and Cifar10 are some of predefined model & dataset available):

```<code>import tensorflow as tf
from dytb.inputs.predefined import Cifar10
from dytb.train import train
from dytb.models.predefined.VGG import VGG

# Instantiate the model
vgg = VGG()

# Instantiate the CIFAR-10 input source
cifar10 = Cifar10.Cifar10()

# 1: Train VGG on Cifar10 for 50 epochs
# Place the train process on GPU:0
device = '/gpu:0'
with tf.device(device):
    info = train(
        model=vgg,
        dataset=cifar10,
        hyperparameters={
            "epochs": 50,
            "batch_size": 50,
            "regularizations": {
                "l2": 1e-5,
                "augmentation": {
                    "name": "FlipLR",
                    "fn": tf.image.random_flip_left_right,
                    # factor is the estimated amount of augmentation
                    # that "fn" introduces.
                    # In this case, "fn" doubles the training set size
                    # Thus, an epoch is now seen as the original training
                    # training set size * 2
                    "factor": 2,
                }
            },
            "gd": {
                "optimizer": tf.train.AdamOptimizer,
                "args": {
                    "learning_rate": 1e-3,
                    "beta1": 0.9,
                    "beta2": 0.99,
                    "epsilon": 1e-8
                }
            }
        })
</code>```

During the training of this model, you can monitor the loss trend and the accuracy value using tensorboard.

A new folder is created for you, using some of the representative hyperparameters used:

```<code>tensorboard --logdir "log/VGG/CIFAR-10_Adam_l2=1e-05_fliplr/"
</code>```

as you can see, a folder for the model is created and the hyperparameter used to train it are added next, as subfolder.

This means that if you change the Optimizer (from ADAM to MomentumOptimizer) or you add a comment, or you change the l2 regularization parameter, ecc, DyTB creates a subfolder into the VGG folder.

This allow you to compare the measured metric with tensorboard, using the model directory as logdir, in this way:

```<code>tensorboard --logdir log/VGG
</code>```

For a more comprehensive guide, just have a look at the DyTB README.md or the python-notebook example.

Body:
You can use DyTB (dynamic training bench): this tool allows you to focus only on the hyperparameter search, using tensorboard to compare the measured stats of the varisous trained model.

DyTB creates for you a unique name associated with the current set of hyperparameters and use it as a log dir.
Creating different log directories allows the use of Tensorboard for an easy comparison.

For instance, you can train VGG on Cifar10 with this single line (both VGG and Cifar10 are some of predefined model & dataset available):

import tensorflow as tf
from dytb.inputs.predefined import Cifar10
from dytb.train import train
from dytb.models.predefined.VGG import VGG

# Instantiate the model
vgg = VGG()

# Instantiate the CIFAR-10 input source
cifar10 = Cifar10.Cifar10()

# 1: Train VGG on Cifar10 for 50 epochs
# Place the train process on GPU:0
device = '/gpu:0'
with tf.device(device):
    info = train(
        model=vgg,
        dataset=cifar10,
        hyperparameters={
            "epochs": 50,
            "batch_size": 50,
            "regularizations": {
                "l2": 1e-5,
                "augmentation": {
                    "name": "FlipLR",
                    "fn": tf.image.random_flip_left_right,
                    # factor is the estimated amount of augmentation
                    # that "fn" introduces.
                    # In this case, "fn" doubles the training set size
                    # Thus, an epoch is now seen as the original training
                    # training set size * 2
                    "factor": 2,
                }
            },
            "gd": {
                "optimizer": tf.train.AdamOptimizer,
                "args": {
                    "learning_rate": 1e-3,
                    "beta1": 0.9,
                    "beta2": 0.99,
                    "epsilon": 1e-8
                }
            }
        })

During the training of this model, you can monitor the loss trend and the accuracy value using tensorboard.

A new folder is created for you, using some of the representative hyperparameters used:

tensorboard --logdir "log/VGG/CIFAR-10_Adam_l2=1e-05_fliplr/"

as you can see, a folder for the model is created and the hyperparameter used to train it are added next, as subfolder.

This means that if you change the Optimizer (from ADAM to MomentumOptimizer) or you add a comment, or you change the l2 regularization parameter, ecc, DyTB creates a subfolder into the VGG folder.

This allow you to compare the measured metric with tensorboard, using the model directory as logdir, in this way:

tensorboard --logdir log/VGG

For a more comprehensive guide, just have a look at the DyTB README.md or the python-notebook example.


问:
Align text in TableColumn /Paragraph
It possible vertical  align text in TableColumn on middle?

I add  paragraph to the table cell of table. And this table I add to richTexBox control.
Problem is that middle column consists of  images(emoticons) and it is "align  to the  vertical center".

It’s difficult for me to describe it.

Here is an image:

I would like align first and third column vertical on the middle. I want text in this 3 columns on the same "level:.

Func which create Table with this 3 columns is here:

```<code>    public Table ConvertToTabRp(IRp rp, string avatarNick)
    {
        var tempRp = new Rp { RpText = rp.RpText, Nick = rp.Nick, Time = rp.Time, Your = rp.Your };

        if (tempRp.Your)
            tempRp.Nick = avatarNick;

        string time = string.Format(CultureInfo.CurrentCulture, "{0}", DateTime.ParseExact(tempRp.Time, "yyyy-MM-dd HH:mm:ss", null)
            .ToString("dd-MM-yyyy HH:mm:ss").Replace("-", "."));

        var tab = new Table {Margin = new Thickness(0, 0, 0, 0)};

        var gridLenghtConvertor = new GridLengthConverter();

        //1. col
        tab.Columns.Add(new TableColumn { Name = "colNick", Width = (GridLength)gridLenghtConvertor.ConvertFromString("100") });
        //2.col
        tab.Columns.Add(new TableColumn { Name = "colMsg", Width = (GridLength)gridLenghtConvertor.ConvertFromString("Auto") });
        //3.col
        tab.Columns.Add(new TableColumn { Name = "colDt", Width = (GridLength)gridLenghtConvertor.ConvertFromString("150") });

        tab.RowGroups.Add(new TableRowGroup());
        tab.RowGroups[0].Rows.Add(new TableRow());

        var tabRow = tab.RowGroups[0].Rows[0];

        //1.col - NICK
        var pNick = new Paragraph(new LineBreak()) { TextAlignment = TextAlignment.Left };
        pNick.Inlines.Add(new Run(tempRp.Nick));

        if (!tempRp.Your)
        {
            pNick.Foreground = Brushes.DodgerBlue;
        }
        tabRow.Cells.Add(new TableCell(pNick));

        //2.col - MESSAGE
        tabRow.Cells.Add(new TableCell(ConvertToRpWithEmoticons(tempRp.RpText)) { TextAlignment = TextAlignment.Left});

        //3.col  - DATE TIME
        var pTime = new Paragraph(new LineBreak()) { TextAlignment = TextAlignment.Right };
        pTime.Inlines.Add(time);
        tabRow.Cells.Add(new TableCell(pTime));

        return tab;

    }
</code>```

maybe solution can be:

```<code>        var pNick = new Paragraph(new LineBreak()) { TextAlignment = TextAlignment.Left , **VerticalTextAligment = Center** };
</code>```

I don’t how vertical align in paragraph.

EDIT:

Maybe is problem in way how I add image to paragraph, here is it code:

```<code>            var image = new Image
            {
                Source = new BitmapImage(new Uri(path, UriKind.RelativeOrAbsolute)),
                Width = 20,
                Height = 20,
            };
            para.Inlines.Add(new Run(separatemsg.Text) { BaselineAlignment = BaselineAlignment.TextBottom });
            //insert smile
            para.Inlines.Add(new InlineUIContainer(image) {BaselineAlignment = BaselineAlignment.Bottom});
</code>```

and this paragraph is add to 2. column.

答:
Try use the BaselineAlignment-property.

Use a Run-Inline to put your text into the paragraphs and set the BaselineAlignment-property.

You can use this also for the image. Use for this the BaselineAlignment-property of the InlineUIContainer

Title: Align text in TableColumn /Paragraph

Body:
It possible vertical  align text in TableColumn on middle?

I add  paragraph to the table cell of table. And this table I add to richTexBox control.
Problem is that middle column consists of  images(emoticons) and it is "align  to the  vertical center".

It’s difficult for me to describe it.

Here is an image:

I would like align first and third column vertical on the middle. I want text in this 3 columns on the same "level:.

Func which create Table with this 3 columns is here:

    public Table ConvertToTabRp(IRp rp, string avatarNick)
    {
        var tempRp = new Rp { RpText = rp.RpText, Nick = rp.Nick, Time = rp.Time, Your = rp.Your };

        if (tempRp.Your)
            tempRp.Nick = avatarNick;

        string time = string.Format(CultureInfo.CurrentCulture, "{0}", DateTime.ParseExact(tempRp.Time, "yyyy-MM-dd HH:mm:ss", null)
            .ToString("dd-MM-yyyy HH:mm:ss").Replace("-", "."));

        var tab = new Table {Margin = new Thickness(0, 0, 0, 0)};

        var gridLenghtConvertor = new GridLengthConverter();

        //1. col
        tab.Columns.Add(new TableColumn { Name = "colNick", Width = (GridLength)gridLenghtConvertor.ConvertFromString("100") });
        //2.col
        tab.Columns.Add(new TableColumn { Name = "colMsg", Width = (GridLength)gridLenghtConvertor.ConvertFromString("Auto") });
        //3.col
        tab.Columns.Add(new TableColumn { Name = "colDt", Width = (GridLength)gridLenghtConvertor.ConvertFromString("150") });

        tab.RowGroups.Add(new TableRowGroup());
        tab.RowGroups[0].Rows.Add(new TableRow());

        var tabRow = tab.RowGroups[0].Rows[0];

        //1.col - NICK
        var pNick = new Paragraph(new LineBreak()) { TextAlignment = TextAlignment.Left };
        pNick.Inlines.Add(new Run(tempRp.Nick));

        if (!tempRp.Your)
        {
            pNick.Foreground = Brushes.DodgerBlue;
        }
        tabRow.Cells.Add(new TableCell(pNick));

        //2.col - MESSAGE
        tabRow.Cells.Add(new TableCell(ConvertToRpWithEmoticons(tempRp.RpText)) { TextAlignment = TextAlignment.Left});

        //3.col  - DATE TIME
        var pTime = new Paragraph(new LineBreak()) { TextAlignment = TextAlignment.Right };
        pTime.Inlines.Add(time);
        tabRow.Cells.Add(new TableCell(pTime));

        return tab;

    }

maybe solution can be:

        var pNick = new Paragraph(new LineBreak()) { TextAlignment = TextAlignment.Left , **VerticalTextAligment = Center** };

I don’t how vertical align in paragraph.

EDIT:

Maybe is problem in way how I add image to paragraph, here is it code:

            var image = new Image
            {
                Source = new BitmapImage(new Uri(path, UriKind.RelativeOrAbsolute)),
                Width = 20,
                Height = 20,
            };
            para.Inlines.Add(new Run(separatemsg.Text) { BaselineAlignment = BaselineAlignment.TextBottom });
            //insert smile
            para.Inlines.Add(new InlineUIContainer(image) {BaselineAlignment = BaselineAlignment.Bottom});

and this paragraph is add to 2. column.


问:
Datadog: Slow queries from MongoDB
I have a MongoDB using the database profiler to collect the slowest queries. How can I send this information to Datadog and analyze it in my Datadog dashboard?</p>

答:
Once the datadog is properly installed on your server, you can use the custom metric feature to let datadog read your query result into a custom metric and then use that metric to create a dashboard.

You can find more on custom metric on datadog here

They work with yaml file so be cautious with the formatting of the yaml file that will hold your custom metric.

Title: Datadog: Slow queries from MongoDB


问:
HandShake Failure in python(_ssl.c:590)
When I execute the below line,

```<code>req = urllib2.Request(requestwithtoken)
self.response = urllib2.urlopen(req,self.request).read()
</code>```

I am getting the following exception:

```<code>SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)
</code>```

The thing is I am able to get the token by pinging the service by using curl.
During the process of retrieving the token, all the certificates were verified.
In turn, by using the generated token, i am not able to connect to the service.
I am getting the above error while trying.
What could be the reason for that?

答:
I also had the same issue. Check which version of requests you are using.

```<code>import requests
print requests.__version__
</code>```

If the version is 2.18.4, you should try downgrading to version 2.11.1. I did this, and it fixed my problem.
To do this, issue the following commands in the terminal

```<code>pip uninstall requests
pip install requests==2.11.1
</code>```

Hope this helps.

Title: HandShake Failure in python(_ssl.c:590)

Body:
When I execute the below line,

req = urllib2.Request(requestwithtoken)
self.response = urllib2.urlopen(req,self.request).read()

I am getting the following exception:

SSLError: [SSL: SSLV3_ALERT_HANDSHAKE_FAILURE] sslv3 alert handshake failure (_ssl.c:590)

The thing is I am able to get the token by pinging the service by using curl.
During the process of retrieving the token, all the certificates were verified.
In turn, by using the generated token, i am not able to connect to the service.
I am getting the above error while trying.
What could be the reason for that?

Body:
I also had the same issue. Check which version of requests you are using.

import requests
print requests.__version__

If the version is 2.18.4, you should try downgrading to version 2.11.1. I did this, and it fixed my problem.
To do this, issue the following commands in the terminal

pip uninstall requests
pip install requests==2.11.1

Hope this helps.


问:
How to detect internet connectivity on a non gateway interface linux
I have a Linux system with 2 NICs, one of which (eth0) is the default gateway. The other (eth1) is not a default gateway. Both have network connections with internet connectivity - so the link state is up.

I want to periodically check on eth1 to see if Internet traffic can be routed through it. Whilst I am checking eth1, I need to keep my Internet traffic routing through eth0 uninterrupted. If I can make a connection through eth1, I will then switch my default gateway (as that is my cheaper connection).

I am trying to check the connection by opening a socket, binding it to eth1 and connecting to a port. I have used 8.8.8.8:443 for my example.

```<code>bool canConnect(const string interface)
{
    bool        result = false;
    sockaddr_in host;
    timeval     timeout;

    int sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
    if (sock == -1)
        return result;

    struct ifreq ifr;
    ::strncpy(ifr.ifr_name, interface.c_str(), IFNAMSIZ);

    int res = setsockopt(_sock, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
    if (res < 0)
    {
        ::close(sock);
        return result;
    }

    int reuse = 1;
    if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) < 0)
    {
        ::close(sock);
        return result;
    }

    ::inet_pton(AF_INET, "8.8.8.8", host.sin_addr);
    host.sin_family      = AF_INET;
    host.sin_port        = htons(443);

    if (::connect(sock, (struct sockaddr *)&host , sizeof(host)) < 0)
    {
        int error = errno;
        if (error != EINPROGRESS) // socket is non-blocking
        {
            ::close(sock);
            return result;
        }
    }

    fd_set writeSet;
    fd_set readSet;
    FD_ZERO(&readSet);
    FD_ZERO(&writeSet);
    FD_SET(sock, &readSet);
    FD_SET(sock, &writeSet);

    timeout.tv_sec  = 5;
    timeout.tv_usec = 0;

    int res = ::select(sock + 1, &readSet, &writeSet, NULL, &timeout);
    if (res < 0)
    {
        ::close(sock);
        return result;
    }

    else if (res == 0)
    {
        // function always exits here
        ::close(sock);
        return result;
    }

    else if (FD_ISSET(sock, &writeSet) || FD_ISSET(sock, &readSet))
    {
        int val;
        socklen_t len = sizeof(val);
        ::getsockopt(sock, SOL_SOCKET, SO_ERROR, &val, &len);
        if (val == 0)
            result = true;
    }
    ::close(sock);

    return result;
}
</code>```

When I run the code, select() always times out. I never manage to make a connection to 8.8.8.8:443, even though eth1 has Internet connectivity (I have proven this by switching the default gateway to eth1 temporarily.

Am I missing some code, or do I need kernel options to make this work?

I have IP forwarding turn on.

答:
If connect() is successful and waiting, you should be checking select() for writable only, not readable at all.  This is stated in the connect() mangage:

EINPROGRESS

  The socket is nonblocking and the connection cannot be
  completed immediately.  It is possible to select(2) or poll(2)
  for completion by selecting the socket for writing.  After
  select(2) indicates writability, use getsockopt(2) to read the
  SO_ERROR option at level SOL_SOCKET to determine whether
  connect() completed successfully (SO_ERROR is zero) or
  unsuccessfully (SO_ERROR is one of the usual error codes
  listed here, explaining the reason for the failure).

Besides, a socket is readable only if there is inbound data to be read, but you are connecting to an HTTPS port, so there will never be any data to read in your example, as you are not sending an HTTPS handshake request.

Also, you should not be calling select() unless connect() actually fails with EINPROGRESS. If connect() returns 0, the connection was successful right way without blocking.  So, you should move your select() call inside your if (connect < 0) block after checking errno.

Also, you are not passing the correct socket to setsockopt(SO_BINDTODEVICE).

Also, you are not passing the correct value to the dst parameter of inet_pton().  You are passing it an in_addr, but it expects an in_addr* instead.

Also, there is no need to use SO_REUSEADDR in this example, since you are not bind()'ing to a specific local IP/port pair before calling connect().

Try something more like this:

```<code>bool canConnect(const string &interface)
{
    bool result = false;

    int sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
    if (sock == -1)
        return result;

    struct ifreq ifr;
    ::strncpy(ifr.ifr_name, interface.c_str(), IFNAMSIZ);

    int res = setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
    if (res < 0)
    {
        ::close(sock);
        return result;
    }

    sockaddr_in host;
    ::inet_pton(AF_INET, "8.8.8.8", &(host.sin_addr));
    host.sin_family      = AF_INET;
    host.sin_port        = htons(443);

    result = (::connect(sock, (struct sockaddr *)&host, sizeof(host)) == 0);
    if (!result)
    {
        if (errno != EINPROGRESS) // socket is non-blocking
        {
            ::close(sock);
            return result;
        }

        fd_set writeSet;
        timeval timeout;

        FD_ZERO(&writeSet);
        FD_SET(sock, &writeSet);

        timeout.tv_sec  = 5;
        timeout.tv_usec = 0;

        res = ::select(sock + 1, NULL, &writeSet, NULL, &timeout);
        if (res <= 0)
        {
            ::close(sock);
            return result;
        }

        int val;
        socklen_t len = sizeof(val);
        ::getsockopt(sock, SOL_SOCKET, SO_ERROR, &val, &len);
        result = (val == 0);
    }

    ::close(sock);
    return result;
}
</code>```

That being said, 8.8.8.8 is a DNS server, so why would you think it is running an HTTPS server as well?  Make sure you are connecting to an actual HTTPS server (why HTTPS and not HTTP?).   You might consider using getaddrinfo() instead to get the IP address for www.google.com (or any other commonly used webserver) instead of hard-coding 8.8.8.8.

Body:
I have a Linux system with 2 NICs, one of which (eth0) is the default gateway. The other (eth1) is not a default gateway. Both have network connections with internet connectivity - so the link state is up.

I want to periodically check on eth1 to see if Internet traffic can be routed through it. Whilst I am checking eth1, I need to keep my Internet traffic routing through eth0 uninterrupted. If I can make a connection through eth1, I will then switch my default gateway (as that is my cheaper connection).

I am trying to check the connection by opening a socket, binding it to eth1 and connecting to a port. I have used 8.8.8.8:443 for my example.

bool canConnect(const string interface)
{
    bool        result = false;
    sockaddr_in host;
    timeval     timeout;

    int sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
    if (sock == -1)
        return result;

    struct ifreq ifr;
    ::strncpy(ifr.ifr_name, interface.c_str(), IFNAMSIZ);

    int res = setsockopt(_sock, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
    if (res < 0)
    {
        ::close(sock);
        return result;
    }

    int reuse = 1;
    if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(int)) < 0)
    {
        ::close(sock);
        return result;
    }

    ::inet_pton(AF_INET, "8.8.8.8", host.sin_addr);
    host.sin_family      = AF_INET;
    host.sin_port        = htons(443);

    if (::connect(sock, (struct sockaddr *)&host , sizeof(host)) < 0)
    {
        int error = errno;
        if (error != EINPROGRESS) // socket is non-blocking
        {
            ::close(sock);
            return result;
        }
    }

    fd_set writeSet;
    fd_set readSet;
    FD_ZERO(&readSet);
    FD_ZERO(&writeSet);
    FD_SET(sock, &readSet);
    FD_SET(sock, &writeSet);

    timeout.tv_sec  = 5;
    timeout.tv_usec = 0;

    int res = ::select(sock + 1, &readSet, &writeSet, NULL, &timeout);
    if (res < 0)
    {
        ::close(sock);
        return result;
    }

    else if (res == 0)
    {
        // function always exits here
        ::close(sock);
        return result;
    }

    else if (FD_ISSET(sock, &writeSet) || FD_ISSET(sock, &readSet))
    {
        int val;
        socklen_t len = sizeof(val);
        ::getsockopt(sock, SOL_SOCKET, SO_ERROR, &val, &len);
        if (val == 0)
            result = true;
    }
    ::close(sock);

    return result;
}

When I run the code, select() always times out. I never manage to make a connection to 8.8.8.8:443, even though eth1 has Internet connectivity (I have proven this by switching the default gateway to eth1 temporarily.

Am I missing some code, or do I need kernel options to make this work?

I have IP forwarding turn on.

Body:
If connect() is successful and waiting, you should be checking select() for writable only, not readable at all.  This is stated in the connect() mangage:

EINPROGRESS

  The socket is nonblocking and the connection cannot be
  completed immediately.  It is possible to select(2) or poll(2)
  for completion by selecting the socket for writing.  After
  select(2) indicates writability, use getsockopt(2) to read the
  SO_ERROR option at level SOL_SOCKET to determine whether
  connect() completed successfully (SO_ERROR is zero) or
  unsuccessfully (SO_ERROR is one of the usual error codes
  listed here, explaining the reason for the failure).

Besides, a socket is readable only if there is inbound data to be read, but you are connecting to an HTTPS port, so there will never be any data to read in your example, as you are not sending an HTTPS handshake request.

Also, you should not be calling select() unless connect() actually fails with EINPROGRESS. If connect() returns 0, the connection was successful right way without blocking.  So, you should move your select() call inside your if (connect < 0) block after checking errno.

Also, you are not passing the correct socket to setsockopt(SO_BINDTODEVICE).

Also, you are not passing the correct value to the dst parameter of inet_pton().  You are passing it an in_addr, but it expects an in_addr* instead.

Also, there is no need to use SO_REUSEADDR in this example, since you are not bind()'ing to a specific local IP/port pair before calling connect().

Try something more like this:

bool canConnect(const string &interface)
{
    bool result = false;

    int sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
    if (sock == -1)
        return result;

    struct ifreq ifr;
    ::strncpy(ifr.ifr_name, interface.c_str(), IFNAMSIZ);

    int res = setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr));
    if (res < 0)
    {
        ::close(sock);
        return result;
    }

    sockaddr_in host;
    ::inet_pton(AF_INET, "8.8.8.8", &(host.sin_addr));
    host.sin_family      = AF_INET;
    host.sin_port        = htons(443);

    result = (::connect(sock, (struct sockaddr *)&host, sizeof(host)) == 0);
    if (!result)
    {
        if (errno != EINPROGRESS) // socket is non-blocking
        {
            ::close(sock);
            return result;
        }

        fd_set writeSet;
        timeval timeout;

        FD_ZERO(&writeSet);
        FD_SET(sock, &writeSet);

        timeout.tv_sec  = 5;
        timeout.tv_usec = 0;

        res = ::select(sock + 1, NULL, &writeSet, NULL, &timeout);
        if (res <= 0)
        {
            ::close(sock);
            return result;
        }

        int val;
        socklen_t len = sizeof(val);
        ::getsockopt(sock, SOL_SOCKET, SO_ERROR, &val, &len);
        result = (val == 0);
    }

    ::close(sock);
    return result;
}

That being said, 8.8.8.8 is a DNS server, so why would you think it is running an HTTPS server as well?  Make sure you are connecting to an actual HTTPS server (why HTTPS and not HTTP?).   You might consider using getaddrinfo() instead to get the IP address for www.google.com (or any other commonly used webserver) instead of hard-coding 8.8.8.8.


问:
Could not find com.opentok.android:opentok-android-sdk
Do you have an issue with your tokbox maven's ?
Because since this morning i can't compile my project, i have this error :

Could not find any matches for com.opentok.android:opentok-android-sdk:2.8.+

also after upgrade sdk version to 2.12.1 it's same

The maven links are in 404 :
https://bintray.com/tokbox/maven/opentok-android-sdk
http://tokbox.bintray.com/maven

Thanks

答:
Opentok suggests to use this url as workaround until they fix the issue.

maven { url 'https://tokbox-telefonica.bintray.com/maven' }


问:
Yacc actions return 0 for any variable ($)
I'm new to Lex/Yacc. Found these lex & yacc files which parse ansi C.

To experiment I added an action to print part of the parsing:

```<code>constant
    : I_CONSTANT    { printf("I_CONSTANT %d\n", $1); }
    | F_CONSTANT
    | ENUMERATION_CONSTANT  /* after it has been defined as such */
    ;
</code>```

The problem is, no matter where I put the action, and whatever $X I use, I always get value 0.

Here I got printed:

```<code>I_CONSTANT 0
</code>```

Even though my input is:

```<code>int foo(int x)
{
    return 5;
}
</code>```

Any idea?

答:
Nothing in the lex file you point to actually sets semantic values for any token. As the author says, the files are just a grammar and "the bulk of the work" still needs to be done. (There are other caveats having to do with the need for a preprocessor.)

Since nothing in the lex file ever sets yylval, it will always be 0, and that is what yacc/bison will find when it sets up the semantic value for the token ($1 in this case).

Body:
I'm new to Lex/Yacc. Found these lex & yacc files which parse ansi C.

To experiment I added an action to print part of the parsing:

constant
    : I_CONSTANT    { printf("I_CONSTANT %d\n", $1); }
    | F_CONSTANT
    | ENUMERATION_CONSTANT  /* after it has been defined as such */
    ;

The problem is, no matter where I put the action, and whatever $X I use, I always get value 0.

Here I got printed:

I_CONSTANT 0

Even though my input is:

int foo(int x)
{
    return 5;
}

Any idea?


问:
How to transpose a dataset in a csv file?
For example, i would like to transform:

Name,Time,Score
Dan,68,20
Suse,42,40
Tracy,50,38
```
<p>Into:</p>
<pre class="lang-none prettyprint-override"><code>Name,Dan,Suse,Tracy
Time,68,42,50
Score,20,40,38
</code>```

Edit: The original question used the term "transpose" incorrectly.

答:
The simplest way is:

```<code>import numpy as np
import pandas as pd

_mat = pd.read_csv("test.csv")
_mat = _mat[_mat.columns[0:3]].values
_t_mat = np.transpose(_mat)
</code>```

Result:

Input matrix is : [[1 2 3]  [4 5 6]]

the output is: [[1 4]  [2 5]  [3 6]]

Body:
For example, i would like to transform:

Name,Time,Score
Dan,68,20
Suse,42,40
Tracy,50,38

Into:

Name,Dan,Suse,Tracy
Time,68,42,50
Score,20,40,38

Edit: The original question used the term "transpose" incorrectly.

Body:
The simplest way is:

import numpy as np
import pandas as pd

_mat = pd.read_csv("test.csv")
_mat = _mat[_mat.columns[0:3]].values
_t_mat = np.transpose(_mat)

Result:

Input matrix is : [[1 2 3]  [4 5 6]]

the output is: [[1 4]  [2 5]  [3 6]]


问:
Django self-recursive foreignkey filter query for all childs
I have this model with a self referencing Foreign Key relation:

```<code>class Person(TimeStampedModel):
    name = models.CharField(max_length=32)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')
</code>```

Now I want to get all the multi level children for a person. How do I write a Django query for it? It needs to behave like recursive function.

答:
If you know the max depth of your tree, you could try something like this (untested):</p>

```<code>Person.objects.filter(Q(parent=my_person)|Q(parent__parent=my_person)| Q(parent__parent__parent=my_person))
</code>```

Body:
I have this model with a self referencing Foreign Key relation:

class Person(TimeStampedModel):
    name = models.CharField(max_length=32)
    parent = models.ForeignKey('self', null=True, blank=True, related_name='children')

Now I want to get all the multi level children for a person. How do I write a Django query for it? It needs to behave like recursive function.

Body:
If you know the max depth of your tree, you could try something like this (untested):

Person.objects.filter(Q(parent=my_person)|Q(parent__parent=my_person)| Q(parent__parent__parent=my_person))


问:
What I can get if I only use libvirt for kvm/qemu?
I think the major feature of libvirt is abstract the different target, but if I only use kvm/qemu, what I can get from libvirt ?</p>

答:
the use of this abstraction layer becomes very handy when you start to script or automate KVM deplyments but ...

The main added value in the KVM QEMU setup is the Live Migation of a Virtual Machine to an ohter Hardware with Hypervisor.