问:
How do i push back the new input of constructor to the default input of the constructor in C++?
I have a class to implement graph in c++ as below. This is the default coding and it cannot be modified.

```<code>Graph(vector<Edge> const &edges, int N)
{
    // construct a vector of vectors of Pairs to represent an adjacency list
    vector<vector<Pair> > adjList;
    // resize the vector to N elements of type vector<Pair>
    adjList.resize(N);

    // add edges to the directed graph
    for (auto &edge: edges)
    {
        int src = edge.src;
        int dest = edge.dest;
        int weight = edge.weight;

        // insert at the end
        adjList[src].push_back(make_pair(dest, weight));
    }

    this->N = N;
}
</code>```

In the main program, i have the default input for the constructor as below. I have to check whether the graph has a cycle or not. If it does not, the program has to generate random edges until cycle is found in the graph. The default graph does not contain cycle and it has the edges as below:

```<code>vector<Edge> edges =
    {
        // (x, y, w) -> edge from x to y having weight w
        { 0,1,6 }, { 0,2,12 }, { 1,4,9 }, { 3,4,1 }, { 3,2,4 }
    };
</code>```

I tried appending the random edges to the default graph using the code below. However,it does not work.

```<code>do
{
  src=rand()%5;
  dest=rand()%5;
  weight=rand()%20;

  vector<Edge> edges1{
    {src, dest, weight}};

  Graph graph1(edges1,N);
  graph.push_back(graph1);

  if(graph.isCyclic())
  {
    //print the graph
  }
}while(!graph.isCyclic());
</code>```

I think the push_back() function is not used properly. Anyone knows how? Thanks.

答:
Based on the limited information provided it seems the following would work.

```<code>vector<Edge> edges = ...;
for (;;)
{
    int src=rand()%5;
    int dest=rand()%5;
    int weight=rand()%20;
    Edge new_edge{src, dest, weight};
    edges.push_back(new_edge);
    Graph graph(edges, N);
    if (graph.isCyclic())
    {
        //print the graph
        break; // exit the loop
    }
}
</code>```

But this code recreates the graph each time round the loop, so there may be something more efficient possible.

UPDATE

Seems the following might work, it avoids recreating the graph each time

```<code>vector<Edge> edges = ...;
Graph graph(edges, N);
for (;;)
{
    int src=rand()%5;
    int dest=rand()%5;
    int weight=rand()%20;
    graph.adjList[src].push_back(std::make_pair(dest, weight));
    if (graph.isCyclic())
    {
        //print the graph
        break; // exit the loop
    }
}
</code>```

Body:
I have a class to implement graph in c++ as below. This is the default coding and it cannot be modified.

Graph(vector<Edge> const &edges, int N)
{
    // construct a vector of vectors of Pairs to represent an adjacency list
    vector<vector<Pair> > adjList;
    // resize the vector to N elements of type vector<Pair>
    adjList.resize(N);

    // add edges to the directed graph
    for (auto &edge: edges)
    {
        int src = edge.src;
        int dest = edge.dest;
        int weight = edge.weight;

        // insert at the end
        adjList[src].push_back(make_pair(dest, weight));
    }

    this->N = N;
}

In the main program, i have the default input for the constructor as below. I have to check whether the graph has a cycle or not. If it does not, the program has to generate random edges until cycle is found in the graph. The default graph does not contain cycle and it has the edges as below:

vector<Edge> edges =
    {
        // (x, y, w) -> edge from x to y having weight w
        { 0,1,6 }, { 0,2,12 }, { 1,4,9 }, { 3,4,1 }, { 3,2,4 }
    };

I tried appending the random edges to the default graph using the code below. However,it does not work.

do
{
  src=rand()%5;
  dest=rand()%5;
  weight=rand()%20;

  vector<Edge> edges1{
    {src, dest, weight}};

  Graph graph1(edges1,N);
  graph.push_back(graph1);

  if(graph.isCyclic())
  {
    //print the graph
  }
}while(!graph.isCyclic());

I think the push_back() function is not used properly. Anyone knows how? Thanks.

Body:
Based on the limited information provided it seems the following would work.

vector<Edge> edges = ...;
for (;;)
{
    int src=rand()%5;
    int dest=rand()%5;
    int weight=rand()%20;
    Edge new_edge{src, dest, weight};
    edges.push_back(new_edge);
    Graph graph(edges, N);
    if (graph.isCyclic())
    {
        //print the graph
        break; // exit the loop
    }
}

But this code recreates the graph each time round the loop, so there may be something more efficient possible.

UPDATE

Seems the following might work, it avoids recreating the graph each time

vector<Edge> edges = ...;
Graph graph(edges, N);
for (;;)
{
    int src=rand()%5;
    int dest=rand()%5;
    int weight=rand()%20;
    graph.adjList[src].push_back(std::make_pair(dest, weight));
    if (graph.isCyclic())
    {
        //print the graph
        break; // exit the loop
    }
}


来源: stackexchange

问:
Problem with AJAX chat
The problem is this.I want to save every message in MySQL DB and I try to do this making this javascript function:

```<code>function doWork(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// Използваните браузъри
  xmlhttp=new XMLHttpRequest();
  }
else
  {// Кой ли ползва тези версии..
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.open("GET","newmsg.php?q="+str,true);
    xmlhttp.send();
}
</code>```

Then the text field :

```<code>  <div id="sender">
     Your message: <input type="text" name="msg" size="30" id="msg" />
     <button onclick="doWork(this.msg);">Send</button>
  </div>
</code>```

And finally the php file:

```<code>$q=$_GET["q"];
  (str)$q;
    $db_connect = mysql_connect('localhost', 'root', 'diamond');
    if(!$db_connect)
        {
         die('Не може да се осъществи връзка с базата данни' . mysql_error());
        }
mysql_select_db("chat", $db_connect);
$sql = "INSERT INTO messages (user_id, time, text) VALUES ('1','1234','$q')";
mysql_query($sql);
mysql_close($db_connect);
</code>```

And what actually happen is that the user_id and time fields are filled properly, but the 'text' filed says "undefined".
What does it mean and how can I fix the problem(s)?
Thanks
Leron

答:
Typecast (str) doesn't exist, it's (string). And you have to do this by assignment:

```<code>$q = (string) $q;
</code>```

Actually it's pretty pointless since URL's are strings. So leave that line out.

Also, as the other repliers mentioned, that's not the right way to get the value. If you do it the following way, the button will be accessible with the return key too. With onclick the user is forced to click on the button. Add return false so that the form doesn't get submitted. this points to <form>.

```<code><form onsubmit="alert(this.msg.value); return false">
    <p>
        <input type="text" name="msg" />
        <button type="submit">Send</button>
    </p>
</form>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Problem with AJAX chat

Body:
The problem is this.I want to save every message in MySQL DB and I try to do this making this javascript function:

function doWork(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// Използваните браузъри
  xmlhttp=new XMLHttpRequest();
  }
else
  {// Кой ли ползва тези версии..
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.open("GET","newmsg.php?q="+str,true);
    xmlhttp.send();
}

Then the text field :

     Your message: <input type="text" name="msg" size="30" id="msg" />
     <button onclick="doWork(this.msg);">Send</button>

And finally the php file:

$q=$_GET["q"];
  (str)$q;
    $db_connect = mysql_connect('localhost', 'root', 'diamond');
    if(!$db_connect)
        {
         die('Не може да се осъществи връзка с базата данни' . mysql_error());
        }
mysql_select_db("chat", $db_connect);
$sql = "INSERT INTO messages (user_id, time, text) VALUES ('1','1234','$q')";
mysql_query($sql);
mysql_close($db_connect);

And what actually happen is that the user_id and time fields are filled properly, but the 'text' filed says "undefined".
What does it mean and how can I fix the problem(s)?
Thanks
Leron

Body:
Typecast (str) doesn't exist, it's (string). And you have to do this by assignment:

$q = (string) $q;

Actually it's pretty pointless since URL's are strings. So leave that line out.

Also, as the other repliers mentioned, that's not the right way to get the value. If you do it the following way, the button will be accessible with the return key too. With onclick the user is forced to click on the button. Add return false so that the form doesn't get submitted. this points to <form>.

<form onsubmit="alert(this.msg.value); return false">
    <p>
        <input type="text" name="msg" />
        <button type="submit">Send</button>
    </p>
</form>


问:
OpenCV faceDetecter yaml model loading error
I have an error loading a .yaml model to FacemarkLBF from openCV.

```<code>cv_landmarks = cv::face::FacemarkLBF::create();
std::cout << "Loading OpenCV model for landmark detection." << std::endl;
cv_landmarks->loadModel("lbfmodel.yaml");
faceDetector.load("haarcascade_frontalface_alt2.xml");
</code>```

Im getting this error:

```<code>loading data from : lbfmodel.yaml
libc++abi.dylib: terminating with uncaught exception of type cv::Exception: OpenCV(4.3.0) /tmp/opencv-20200408-5080-l00ytm/opencv-4.3.0/opencv_contrib/modules/face/src/facemarkLBF.cpp:487: error: (-5:Bad argument) No valid input file was given, please check the given filename. in function 'loadModel'
</code>```

This model works fine on visual studio, but I need to make the project using Xcode to use it later for iOS.

PS: I tried different models, and I got always the same error.

答: Provide absolute path for reading the model and it will work then.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have an error loading a .yaml model to FacemarkLBF from openCV.

cv_landmarks = cv::face::FacemarkLBF::create();
std::cout << "Loading OpenCV model for landmark detection." << std::endl;
cv_landmarks->loadModel("lbfmodel.yaml");
faceDetector.load("haarcascade_frontalface_alt2.xml");

Im getting this error:

loading data from : lbfmodel.yaml
libc++abi.dylib: terminating with uncaught exception of type cv::Exception: OpenCV(4.3.0) /tmp/opencv-20200408-5080-l00ytm/opencv-4.3.0/opencv_contrib/modules/face/src/facemarkLBF.cpp:487: error: (-5:Bad argument) No valid input file was given, please check the given filename. in function 'loadModel'

This model works fine on visual studio, but I need to make the project using Xcode to use it later for iOS.

PS: I tried different models, and I got always the same error.


问:
Is there an alternative for positive & negative lookahead and negative lookbehind for my REGEX that would work in Safari?
I have a REGEX to check the validity of a username which looks like this:

/^(?=.{5,30}$)(?![_.-])(?!.*[_.-]{2})[a-zA-Z0-9._-]+(?<![_.-])$/

Basically, my username has the following constraints:

it should be 5-30 characters long,

it can contain any alphanumeric [a-z A-Z 0-9] characters,

it could contain symbols like _.-

it can't start or end with these symbols

the symbols can't be adjacent to each other

This REGEX works perfectly in Chrome, but as we all know, Safari doesn't support lookbehind in REGEX. However, I am not sure if they do support lookahead.

My question is, is there a way to convert this REGEX into something that Safari understands?

Thanks in advance!

答:
You could use the following regular expression.

```<code>^(?=.{5,30}$)[a-z0-9]+(?:[._-][a-z0-9]+)*[a-z0-9]*$
</code>```

with the case-indifferent flag set.

The regex engine performs the following operations.

```<code>^             match beginning of string
(?=.{5,30}$)  assert string contains 5-30 chars
[a-z0-9]+     match 1+ alphanumeric chars
(?:           begin non-capture group
  [._-]       match one char in char class
  [a-z0-9]+   match 1+ chars in char class
)*            end non-cap group and execute 0+ times
[a-z0-9]*     match 0+ chars in char class
$             # match end of line
</code>```

Body:
You could use the following regular expression.

^(?=.{5,30}$)[a-z0-9]+(?:[._-][a-z0-9]+)*[a-z0-9]*$

with the case-indifferent flag set.

The regex engine performs the following operations.

^             match beginning of string
(?=.{5,30}$)  assert string contains 5-30 chars
[a-z0-9]+     match 1+ alphanumeric chars
(?:           begin non-capture group
  [._-]       match one char in char class
  [a-z0-9]+   match 1+ chars in char class
)*            end non-cap group and execute 0+ times
[a-z0-9]*     match 0+ chars in char class
$             # match end of line


问:
how to force to crash firebasecrashlytics?
I am developing news app and  I am new to firebase Crashlytics I want to force to crash and I want to get a report of the crash but I am not getting any crash reports how can I achieve that

below my Implementation

```<code>binding.root.setOnClickListener { v ->

                FirebaseCrashlytics.getInstance()

                val intent = Intent(v.context, DetailActivity::class.java)
                intent.putExtra(urlKey, articleList[position].url)

                v.context.startActivity(intent)
            }
</code>```

below my firebase crashlytics console screenshot
my firebasecrashlytics console

I want to know where I am making mistake how can I force to crash my app

答:
how can I force to crash my app

Just throw an exception that gets handled by crashlytics unhandled exception handler, e.g.

```<code>throw RuntimeException("crash testing")
</code>```

Body:
I am developing news app and  I am new to firebase Crashlytics I want to force to crash and I want to get a report of the crash but I am not getting any crash reports how can I achieve that

below my Implementation

binding.root.setOnClickListener { v ->

                FirebaseCrashlytics.getInstance()

                val intent = Intent(v.context, DetailActivity::class.java)
                intent.putExtra(urlKey, articleList[position].url)

                v.context.startActivity(intent)
            }

below my firebase crashlytics console screenshot
my firebasecrashlytics console

I want to know where I am making mistake how can I force to crash my app

Body:
how can I force to crash my app

Just throw an exception that gets handled by crashlytics unhandled exception handler, e.g.

throw RuntimeException("crash testing")


问:
Common DLL referencing throughout Silverlight project
I have a common silverlight project. This project project, among other things, includes constants and static classes.

The silverlight App i have references this common library.
In addition, i have a handful of external modules that are loaded on-demand (via Prism). Each module is its own .Xap file and they too reference the common library.

So now each Xap in my silverlight application has a reference to the Common.dll.
Does this mean the common.dll is loaded every time a xap is loaded, or does it essentially mean only the main App's common.dll is ever loaded?

The ultimate question im getting at is this:
If i make a code change (bug fix) in the common.dll, do i have to release ALL Xap files or just the main App xap?

Thanks.

答:
By default DLLs are loaded on demand. This means that you can't really guarantee which directory they will load from. This is a common issue among modular applications and one that there isn't a ready prescription for. It depends on requirements, essentially.

Some things you can do:

GAC the Common.dll in the target environment. This will allow you to control the versioning of that DLL centrally.

Release everything every time Common.dll changes (as you mentioned).

We have opted for number 2 (we treat our "Common.dll" as a contract assembly that changes rarely) in order to keep our xcopy deployments intact.

Number 1 might make more sense if you anticipate that code churn on Common.dll will be high or you want to keep your deployment schedules for modules completely autonomous (like if the modules were being developed and deployed by seperate teams with seperate build and source respositories, for example).

Edit: It looks like Silverlight has something to provide an xcopy variant of the GAC approach. ChrisF's answer is probably the way I would go with Silverlight (we do WPF, so that's a bit different).  I'll leave this here for posterity.


问:
Why is the web page show a scroll bar when `body` set to `min-height: 100vh`?
I already reset all the margin and padding to 0.
see the codepen: https://codepen.io/geeklog/pen/zYvVeOZ

hello

```

<pre class="lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  background-color: pink;
}

.container {
  margin: 10px auto;
  background-color: orange;
}
</code>```

答:
margin: 10px auto;
```

Unlike paddings, CSS margins are not exactly a spacing measure when it is applied to an element inside. When you apply a margin to the elements like above, the top margin will tend to go outside of the parent element. It is just an example of the general margin collapsing behavior.

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

Therefore, in your code snippet, it's not only the body with the height of 100vh that you see on the screen. It also includes 10px of space right above the body element.

To resolve this issue, remove margin from .container and consider applying padding-top: 10px; to the body element instead.

Body:
I already reset all the margin and padding to 0.
see the codepen: https://codepen.io/geeklog/pen/zYvVeOZ

hello

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  min-height: 100vh;
  background-color: pink;
}

.container {
  margin: 10px auto;
  background-color: orange;
}

Body:
margin: 10px auto;

Unlike paddings, CSS margins are not exactly a spacing measure when it is applied to an element inside. When you apply a margin to the elements like above, the top margin will tend to go outside of the parent element. It is just an example of the general margin collapsing behavior.

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing

Therefore, in your code snippet, it's not only the body with the height of 100vh that you see on the screen. It also includes 10px of space right above the body element.

To resolve this issue, remove margin from .container and consider applying padding-top: 10px; to the body element instead.


问:
Subquery within scalar subquery fails with error ORA-00936 Missing Expression

This is the query that does not work:

```<code>SELECT distinct ord.DateOrdered
   , (SELECT docno
      FROM th_mm_c_orderline_history
      WHERE th_mm_c_orderline_history_id
            in (SELECT max(th_mm_c_orderline_history_id)
                FROM th_mm_c_orderline_history
                GROUP BY c_orderline_id )
      order by docno,c_orderline_id) as docno
FROM c_order ord
INNER JOIN c_orderline on c_orderline.c_order_id = ord.c_order_id
INNER JOIN th_mm_c_orderline_history
      on th_mm_c_orderline_history.c_order_id=ord.c_order_id
</code>```

It is throwing me ORA-00936 Missing expression error

This query works fine:

```<code>SELECT docno
FROM th_mm_c_orderline_history
WHERE th_mm_c_orderline_history_id
      in (SELECT max(th_mm_c_orderline_history_id)
          FROM th_mm_c_orderline_history
          GROUP BY c_orderline_id )
order by docno,c_orderline_id as docno
</code>```

答:
Just remove the order by clause from the inline select. You can not use orde by clause there. You can use it in the outer select if you need it...This is how you can do all three of them without the error:</p>

```<code>SELECT distinct ord.DateOrdered
       , (SELECT docno FROM th_mm_c_orderline_history
          WHERE th_mm_c_orderline_history_id
                 in (SELECT max(th_mm_c_orderline_history_id)
                     FROM th_mm_c_orderline_history
                     GROUP BY c_orderline_id)
          ) as docno
FROM c_order ord
INNER JOIN c_orderline on c_orderline.c_order_id = ord.c_order_id
INNER JOIN th_mm_c_orderline_history on th_mm_c_orderline_history.c_order_id=ord.c_order_id
</code>```

Body:
This is the query that does not work:

SELECT distinct ord.DateOrdered
   , (SELECT docno
      FROM th_mm_c_orderline_history
      WHERE th_mm_c_orderline_history_id
            in (SELECT max(th_mm_c_orderline_history_id)
                FROM th_mm_c_orderline_history
                GROUP BY c_orderline_id )
      order by docno,c_orderline_id) as docno
FROM c_order ord
INNER JOIN c_orderline on c_orderline.c_order_id = ord.c_order_id
INNER JOIN th_mm_c_orderline_history
      on th_mm_c_orderline_history.c_order_id=ord.c_order_id

It is throwing me ORA-00936 Missing expression error

This query works fine:

SELECT docno
FROM th_mm_c_orderline_history
WHERE th_mm_c_orderline_history_id
      in (SELECT max(th_mm_c_orderline_history_id)
          FROM th_mm_c_orderline_history
          GROUP BY c_orderline_id )
order by docno,c_orderline_id as docno

Body:
Just remove the order by clause from the inline select. You can not use orde by clause there. You can use it in the outer select if you need it...This is how you can do all three of them without the error:

SELECT distinct ord.DateOrdered
       , (SELECT docno FROM th_mm_c_orderline_history
          WHERE th_mm_c_orderline_history_id
                 in (SELECT max(th_mm_c_orderline_history_id)
                     FROM th_mm_c_orderline_history
                     GROUP BY c_orderline_id)
          ) as docno
FROM c_order ord
INNER JOIN c_orderline on c_orderline.c_order_id = ord.c_order_id
INNER JOIN th_mm_c_orderline_history on th_mm_c_orderline_history.c_order_id=ord.c_order_id


问:
Reformatting response data in react.js setState method
im recently trying to convert a Vue project to a React project . Here is a problem that im facing.

I have a data that comes in the format of :

```<code>0:
iteration: -1
    state:
        description: null
        id: 1
        label: "Start"
        slug: "start"
</code>```

I wish to do a save this into my component state but in a different format :

```<code>0:
iteration: -1
description: null
id: 1
label: "Start"
slug: "start"
</code>```

The reason for doing this is to be able to get the idof the object by calling response.data.id , instead of response.data.state.id

答:
You can map over the data and reformat it by returning the desired object from it

```<code>const newData = data.map(item => ({
   iteration: item.iteration,
   ...item.state
}));
</code>```

Now newData will have the format you want. If you have more keys within item that you want to have in the data, you can make modifications in the above returned object

Body:
im recently trying to convert a Vue project to a React project . Here is a problem that im facing.

I have a data that comes in the format of :

0:
iteration: -1
    state:
        description: null
        id: 1
        label: "Start"
        slug: "start"

I wish to do a save this into my component state but in a different format :

0:
iteration: -1
description: null
id: 1
label: "Start"
slug: "start"

The reason for doing this is to be able to get the idof the object by calling response.data.id , instead of response.data.state.id

Body:
You can map over the data and reformat it by returning the desired object from it

const newData = data.map(item => ({
   iteration: item.iteration,
   ...item.state
}));

Now newData will have the format you want. If you have more keys within item that you want to have in the data, you can make modifications in the above returned object


问:
why can not use strlen(char[]) to compare a value
```<code>#include <stdio.h>
#include <string.h>

int main(void) {

    char words[2][3] = {{'a','b','c'},{'A','B','C'}};

        for(int j= 0 ;j < 2;j++){

            long diff =   0 - (strlen(words[j]));

            printf("%d , %d \n"  ,  (diff <= 0)  ,  (0  -  strlen(words[j]) <= 0 )  );

        }

    return 0;
}
</code>```

/*

1 , 0

1 , 0

*/

why ? I expected result is  1,1  .
enter image description here

答:
strlen expects a pointer to a string. A "string" in C is a zero terminated array of characters.

Neither {'a','b','c'} nor {'A','B','C'} arrays are zero terminated. So calling strlen on them is undefined behavior.

You need to put a terminating zero character '\0' (or just 0 for byte strings) after the array that compose the string. So to make execution of your program defined, you have to:

```<code>#include <stdio.h>
#include <string.h>
int main(void) {
    char words[2][4] = { // note - include space for zero in size.
        // equal to "abc"
        {'a','b','c','\0'},
        // string literal can be used as initializers too
        // and they are zero teminated
        "ABC"
    };
    for(int j= 0 ;j < 2;j++){
        long diff =   0 - (strlen(words[j]));
        printf("%d , %d \n"  ,  (diff <= 0)  ,  (0  -  strlen(words[j]) <= 0 )  );
    }
    return 0;
}
</code>```

why diff <= 0 and (0 - strlen(words[j]) <= 0 ) is diffrent ?

Because strlen returns an unsigned type size_t, the expression 0 - strlen(words[j]) has unsigned type, so it can't be negative. On substraction from zero unsigned underflow happens and it results in a very big unsigned value.

diff has type long, so it is signed. On diff initialization diff =   0 - (strlen(words[j])); the unsigned result of 0 - (strlen(words[j])) is converted to type long which results in a small negative signed value (on your machine).

Body:
#include <stdio.h>
#include <string.h>

int main(void) {

    char words[2][3] = {{'a','b','c'},{'A','B','C'}};

        for(int j= 0 ;j < 2;j++){

            long diff =   0 - (strlen(words[j]));

            printf("%d , %d \n"  ,  (diff <= 0)  ,  (0  -  strlen(words[j]) <= 0 )  );

        }

    return 0;
}

/*

1 , 0

1 , 0

*/

why ? I expected result is  1,1  .
enter image description here

Body:
strlen expects a pointer to a string. A "string" in C is a zero terminated array of characters.

Neither {'a','b','c'} nor {'A','B','C'} arrays are zero terminated. So calling strlen on them is undefined behavior.

You need to put a terminating zero character '\0' (or just 0 for byte strings) after the array that compose the string. So to make execution of your program defined, you have to:

#include <stdio.h>
#include <string.h>
int main(void) {
    char words[2][4] = { // note - include space for zero in size.
        // equal to "abc"
        {'a','b','c','\0'},
        // string literal can be used as initializers too
        // and they are zero teminated
        "ABC"
    };
    for(int j= 0 ;j < 2;j++){
        long diff =   0 - (strlen(words[j]));
        printf("%d , %d \n"  ,  (diff <= 0)  ,  (0  -  strlen(words[j]) <= 0 )  );
    }
    return 0;
}

why diff <= 0 and (0 - strlen(words[j]) <= 0 ) is diffrent ?

Because strlen returns an unsigned type size_t, the expression 0 - strlen(words[j]) has unsigned type, so it can't be negative. On substraction from zero unsigned underflow happens and it results in a very big unsigned value.

diff has type long, so it is signed. On diff initialization diff =   0 - (strlen(words[j])); the unsigned result of 0 - (strlen(words[j])) is converted to type long which results in a small negative signed value (on your machine).


问:
How to display schema example with flask_restplus?
[Using Python, Flask, flask_restplus, Swagger]

I'm trying to display a schema model as the picture below using flask_restplus.
Prototype schema in yml and not python:

I created the schema_model but I'm not sure how to input it into the code so that it pairs to the GET call. How do I display the schema_model?

```<code>import requests
from flask import Flask, request, json, jsonify, Blueprint
from flask_restplus import Resource, Api, reqparse, fields, SchemaModel

app = Flask(__name__)
api = Api(app, title='Function Test', doc='/FT')

rbt = api.namespace('RBT', description='Accessible by API')

address = api.schema_model('Address', {
    'properties': {
        'road': {
            'type': 'string'
        },
    },
    'type': 'object'
})

@rbt.route('/<string:resource>/<string:responder>/<string:tag>')
class RBT(Resource):

    @rbt.doc(responses={
        200: 'Success',
        400: 'Validation Error',
        500: 'Internal Server Error'
    })

    #@rbt.marshal_with(address)
    def get(self, resource, responder, tag, **kwargs):
        '''TC#1 Definition'''
        url2 = 'http://' + host +  port + '/' + resource + '?' +responder
        print(url2)

        url = 'http://httpbin.org/get'

        parameters = {'resource': resource, 'responder':responder, 'tag': tag}
        r = requests.get(url)
        data = r.text

        return data
</code>```

答:
Few remarks about general concepts of serializing (aka marshaling) and deserializing in flask rest_plus:

for out-putting (serializing) use @api.marshall_with(some_serializer) - this will be used for displaying the returned object in GET but also resulting created object if your return object in response in POST or some other method.

for in-putting (deserializing) user @api.expect(some_deserializer, validate=True) - this will be used to convert incoming JSON into python objects and making validation that the shape of data is correct.

regarding JSON schema based serializers - the sad, but the straightforward answer is:

the functionality of api.schema_model() (JSON schema-based de/serializer) IS NOT WORKING properly in rest_plus see the github issues:

https://github.com/noirbizarre/flask-restplus/issues/293

https://github.com/noirbizarre/flask-restplus/issues/275

Body:
[Using Python, Flask, flask_restplus, Swagger]

I'm trying to display a schema model as the picture below using flask_restplus.
Prototype schema in yml and not python:

I created the schema_model but I'm not sure how to input it into the code so that it pairs to the GET call. How do I display the schema_model?

import requests
from flask import Flask, request, json, jsonify, Blueprint
from flask_restplus import Resource, Api, reqparse, fields, SchemaModel

app = Flask(__name__)
api = Api(app, title='Function Test', doc='/FT')

rbt = api.namespace('RBT', description='Accessible by API')

address = api.schema_model('Address', {
    'properties': {
        'road': {
            'type': 'string'
        },
    },
    'type': 'object'
})

@rbt.route('/<string:resource>/<string:responder>/<string:tag>')
class RBT(Resource):

    @rbt.doc(responses={
        200: 'Success',
        400: 'Validation Error',
        500: 'Internal Server Error'
    })

    #@rbt.marshal_with(address)
    def get(self, resource, responder, tag, **kwargs):
        '''TC#1 Definition'''
        url2 = 'http://' + host +  port + '/' + resource + '?' +responder
        print(url2)

        url = 'http://httpbin.org/get'

        parameters = {'resource': resource, 'responder':responder, 'tag': tag}
        r = requests.get(url)
        data = r.text

        return data


问:
Add SCons files to ack searches
I love the code search utility ack. It is smart enough to look through Makefiles, but doesn't know about the SConstruct and SConscript files that scons uses. How do I add those to the files that ack will look in?

答:
Here is a patch that treats SCons files like make files:</p>

```<code>--- ~/bin/ack-old 2011-06-01 15:43:51.000000000 -0600
+++ ~/bin/ack     2011-06-01 15:42:09.000000000 -0600
@@ -1583,6 +1583,8 @@

     return 'skipped' unless is_searchable( $basename );

+    return ('python',TEXT)      if $basename eq 'SConstruct' || $basename eq 'SConscript';
+
     my $lc_basename = lc $basename;
     return ('make',TEXT)        if $lc_basename eq 'makefile' || $lc_basename eq 'gnumakefile';
     return ('rake','ruby',TEXT) if $lc_basename eq 'rakefile';
</code>```

ContentLicense: CC BY-SA 2.5

Title: Add SCons files to ack searches

Body:
Here is a patch that treats SCons files like make files:

--- ~/bin/ack-old 2011-06-01 15:43:51.000000000 -0600
+++ ~/bin/ack     2011-06-01 15:42:09.000000000 -0600
@@ -1583,6 +1583,8 @@

     return 'skipped' unless is_searchable( $basename );

+    return ('python',TEXT)      if $basename eq 'SConstruct' || $basename eq 'SConscript';
+
     my $lc_basename = lc $basename;
     return ('make',TEXT)        if $lc_basename eq 'makefile' || $lc_basename eq 'gnumakefile';
     return ('rake','ruby',TEXT) if $lc_basename eq 'rakefile';


问:
make the 3 sum of 3 ion-range equal to 100
I have 3 ion-range that the user can change (by default the range if 0 to 100. I'd like to make a dynamic interface so that if a user move on of the 3 ion-range (or if he moves 2), the sum of the 3 ion-range will always are 100.

I have started something like that (in home page) :
https://stackblitz.com/edit/ionic-pt7dzp

It kinka works.
In fact, if we move the 2 first range the third one if 100 - (the 2 others value) but it's not really good. For example the second range should have new min and max depending on the value selected in range1 (if range 1 if 40, then range 2 should be 0 to 60 and so one).
But this is only if the user move range1, if he begins to move range3, nothing happen...

I could bing min and max depending on value selected but I will have many many if and the thing will be 'not so good'.

How can I set something I value1 + value2 + value3 = 100 and the value change automatically when I change (maybe add other rules like, if value1 = 50; value 2 = (100 - 50) / 2 and value 3 the same..).

Thank you for you help.

答:
You are on the right track. Everytime one of the values changes you have to change the other two accordingly. In the change function in your stackblitz you pass the name of the value but you do not actually use it to adapt the logic accordingly.

When one value changes the other two would have to change accordingly. I would do something like this:

```<code>change (name: string) {
  if (name == 'value1') {
    const remainder = 100 - this.value1;
    this.value2 = Math.floor(remainder * this.value2 / (this.value2 + this.value3));
    this.value3 = remainder - this.value2;
  }
  // the same for value2 and value3 accordingly
}
</code>```

Let's say value1 was 10, value2 was 40 and value3 was 50. If you now change value1 to 20 the remainder of 80 is distributed between value2 and value3 in the ratio they previously had. This would result in: value1 = 20, value2 = 35, value3 = 45

Body:
You are on the right track. Everytime one of the values changes you have to change the other two accordingly. In the change function in your stackblitz you pass the name of the value but you do not actually use it to adapt the logic accordingly.

When one value changes the other two would have to change accordingly. I would do something like this:

change (name: string) {
  if (name == 'value1') {
    const remainder = 100 - this.value1;
    this.value2 = Math.floor(remainder * this.value2 / (this.value2 + this.value3));
    this.value3 = remainder - this.value2;
  }
  // the same for value2 and value3 accordingly
}

Let's say value1 was 10, value2 was 40 and value3 was 50. If you now change value1 to 20 the remainder of 80 is distributed between value2 and value3 in the ratio they previously had. This would result in: value1 = 20, value2 = 35, value3 = 45


问:
How can I know if APEX_JSON is installed on my database?
I want to work with json data, in an Oracle database, so I tried the apex_json package.

I tried this example from Oracle:

```<code>DECLARE
  s varchar2(32767) := '{ "a": 1, "b": ["hello", "world"]}';
BEGIN
  apex_json.parse(s);
  sys.dbms_output.put_line('a is '||apex_json.get_varchar2(p_path => 'a'));
END;
</code>```

But I get this error:

APEX_JSON.parse must be declared.

How can I verify that APEX_JSON is installed on my db_server?
Is there anything I need to do to activate it?

答:
Login as sysdba

Execute the script below:

select comp_name, version, status from dba_registry where comp_id='APEX';

It shows all details.

Body:
I want to work with json data, in an Oracle database, so I tried the apex_json package.

I tried this example from Oracle:

DECLARE
  s varchar2(32767) := '{ "a": 1, "b": ["hello", "world"]}';
BEGIN
  apex_json.parse(s);
  sys.dbms_output.put_line('a is '||apex_json.get_varchar2(p_path => 'a'));
END;

But I get this error:

APEX_JSON.parse must be declared.

How can I verify that APEX_JSON is installed on my db_server?
Is there anything I need to do to activate it?


问:
Using cy.get() in Cypress to search for selectors with one of two properties
I'm using Cypress to write automated tests. This is for a codebase I have no control over, so I can't make any changes to the app itself.

I'm attempting to run a .each loop to run through a set of collapsible fields to verify the data in each of them is correct. The fields list medical problems and associated data. The issue is that there are two lists of fields, one for active problems, and one for resolved problems, where the only difference between them is the data-cy tags. Those are the only unique identifiers for these elements, so I have to use the data-cy tags to select these without selecting other elements in the same container.

I'd be able to run the exact same .each function on both sets of elements, but I currently can't due to the elements not having the same data-cy tags. Is it possible for me to to have the Cypress .get call search for elements with one of two properties? Something like the following:

cy.get('[data-cy="problem-entry"]' OR '[data-cy="resolved-problem"]')

EDIT: Also, to clarify - I am currently able to get the test to behave by just duplicating the .each loop, once for each data-cy tag. Since the loop is several hundred lines of code, I want to remove the redundancy to clean this up a bit.

答:
This answer is not perfect fix, but may work in your case: if these selectors are the only data-cy with the word "problem" in their value, you could do something like this:cy.get('[data-cy*="problem"]'). This will choose any data-cy which contains word "problem".

If that is not the case, I would like to address your "EDIT" message: you may put the whole code (several hundred lines) in a Cypress custom command and then call it, so instead of copying the code and calling it twice, you would just call your custom command twice (one line each).


问:
Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved
I just installed and re-installed IntelliJ. Every Java file is coming up RED. I checked the JDK; it is at 1.6.##. The maven clean install build worked just fine.

I'm getting the usual highlighted errors. On every declaration:

Cannot resolve symbol SomeEntityBean/Bean

and on every method:

Cannot resolve method SomeFunction()

How do I fix these false errors?

答:
Using IntelliJ 2019.3 and a Gradle project dependent on my own Gradle project, the only thing that fixed it for me was Reimport All Gradle Projects under View -> Tool Windows -> Gradle (and refresh button).

Before that I tried restarting IDE, I tried "Invalidate Caches and Restart", I tried Rebuild project, neither helped.


问:
Dapper Dommel - Usinng Like-queries issue
I'm trying to use Like-queries as shown in Dommel documetation:

```<code>using (var con = new SqlConnection())
{
   var products = con.Select<Product>(p => p.Name == "Awesome bike");
   var products = con.Select<Product>(p => p.Created < new DateTime(2014, 12, 31) && p.InStock > 5);
}
</code>```

but when i try to execute this piece of code:

```<code>using (DbContext ctx = new DbContext())
{
    IEnumerable<User> users = ctx.Connection.Select<User>(u => u.UserName.StartsWith("op", StringComparison.InvariantCultureIgnoreCase));
    usersBindingSource.DataSource = users.ToList();
}
</code>```

I'm getting this exeption:

An expression of non-boolean type specified in a context where condition is expected, near '('

I'm using Dommel.1.11.0

Thanks.

答: The author of Dommel (Henk Mollema) says that StartsWith is only available from version 2.0, currently in beta.</p>

Body:
I'm trying to use Like-queries as shown in Dommel documetation:

using (var con = new SqlConnection())
{
   var products = con.Select<Product>(p => p.Name == "Awesome bike");
   var products = con.Select<Product>(p => p.Created < new DateTime(2014, 12, 31) && p.InStock > 5);
}

but when i try to execute this piece of code:

using (DbContext ctx = new DbContext())
{
    IEnumerable<User> users = ctx.Connection.Select<User>(u => u.UserName.StartsWith("op", StringComparison.InvariantCultureIgnoreCase));
    usersBindingSource.DataSource = users.ToList();
}

I'm getting this exeption:

An expression of non-boolean type specified in a context where condition is expected, near '('

I'm using Dommel.1.11.0

Thanks.


问:
SystemError: unknown opcode when loading model with Keras
I have trained a model on Kaggle on this link :
https://www.kaggle.com/dcosmin/shufflenet-with-keras
using the source code from this link : https://github.com/opconty/keras-shufflenetV2/blob/master/shufflenetv2.py. After the training has finished, I saved a model called ShuffleNetV2.h5 and the weights.hdf5. When i try to run the code on my computer:

```<code># model = tf.keras.models.load_model('L-CNN v4.0.h5')
# model = tf.keras.models.load_model('MobileNetV2 - 131 - 2.0.h5')
model = tf.keras.models.load_model('ShuffleNetV2 - 131.h5')

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
</code>```

I need to run this code on the latest version of Keras and Tensorflow with Python 3.7 - I need to run it on Raspberry Pi. The error:

```<code> SystemError                               Traceback (most recent call last)
<ipython-input-15-914c5b8863a1> in <module>
      1 #model = tf.keras.models.load_model('L-CNN v4.0.h5')
      2 #model = tf.keras.models.load_model('MobileNetV2 - 131 - 2.0.h5')
----> 3 model = tf.keras.models.load_model('ShuffleNetV2 - 131.h5')
      4 #model=load_model('ShuffleNetV2 - 131.h5')
      5 model.compile(loss='categorical_crossentropy',

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\saving\save.py in load_model(filepath, custom_objects, compile)
    144   if (h5py is not None and (
    145       isinstance(filepath, h5py.File) or h5py.is_hdf5(filepath))):
--> 146     return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
    147
    148   if isinstance(filepath, six.string_types):

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\saving\hdf5_format.py in load_model_from_hdf5(filepath, custom_objects, compile)
    166     model_config = json.loads(model_config.decode('utf-8'))
    167     model = model_config_lib.model_from_config(model_config,
--> 168                                                custom_objects=custom_objects)
    169
    170     # set weights

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\saving\model_config.py in model_from_config(config, custom_objects)
     53                     '`Sequential.from_config(config)`?')
     54   from tensorflow.python.keras.layers import deserialize  # pylint: disable=g-import-not-at-top
---> 55   return deserialize(config, custom_objects=custom_objects)
     56
     57

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\layers\serialization.py in deserialize(config, custom_objects)
    104       module_objects=globs,
    105       custom_objects=custom_objects,
--> 106       printable_module_name='layer')

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\utils\generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    301             custom_objects=dict(
    302                 list(_GLOBAL_CUSTOM_OBJECTS.items()) +
--> 303                 list(custom_objects.items())))
    304       with CustomObjectScope(custom_objects):
    305         return cls.from_config(cls_config)

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\engine\network.py in from_config(cls, config, custom_objects)
    935     """
    936     input_tensors, output_tensors, created_layers = reconstruct_from_config(
--> 937         config, custom_objects)
    938     model = cls(inputs=input_tensors, outputs=output_tensors,
    939                 name=config.get('name'))

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\engine\network.py in reconstruct_from_config(config, custom_objects, created_layers)
   1901       if layer in unprocessed_nodes:
   1902         for node_data in unprocessed_nodes.pop(layer):
-> 1903           process_node(layer, node_data)
   1904
   1905   input_tensors = []

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\engine\network.py in process_node(layer, node_data)
   1849       if not isinstance(input_tensors, dict) and len(flat_input_tensors) == 1:
   1850         input_tensors = flat_input_tensors[0]
-> 1851       output_tensors = layer(input_tensors, **kwargs)
   1852
   1853       # Update node index map.

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in __call__(self, inputs, *args, **kwargs)
    771                     not base_layer_utils.is_in_eager_or_tf_function()):
    772                   with auto_control_deps.AutomaticControlDependencies() as acd:
--> 773                     outputs = call_fn(cast_inputs, *args, **kwargs)
    774                     # Wrap Tensors in `outputs` in `tf.identity` to avoid
    775                     # circular dependencies.

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\layers\core.py in call(self, inputs, mask, training)
    844     with backprop.GradientTape(watch_accessed_variables=True) as tape,\
    845         variable_scope.variable_creator_scope(_variable_creator):
--> 846       result = self.function(inputs, **kwargs)
    847     self._check_variables(created_variables, tape.watched_variables())
    848     return result

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\layers\core.py in channel_shuffle(x)

SystemError: unknown opcode
</code>```

I really need to fix this incompatibilities. Can you tell me if I have to change something on Kaggle to train it again or i don;t know..

答:
This error is due to a version difference. You can solve this by saving the architecture as code, and the weights in an h5. This will be compatible across versions.
This was raised in Keras repository.
https://github.com/keras-team/keras/issues/9595</p>

Body:
I have trained a model on Kaggle on this link :
https://www.kaggle.com/dcosmin/shufflenet-with-keras
using the source code from this link : https://github.com/opconty/keras-shufflenetV2/blob/master/shufflenetv2.py. After the training has finished, I saved a model called ShuffleNetV2.h5 and the weights.hdf5. When i try to run the code on my computer:

# model = tf.keras.models.load_model('L-CNN v4.0.h5')
# model = tf.keras.models.load_model('MobileNetV2 - 131 - 2.0.h5')
model = tf.keras.models.load_model('ShuffleNetV2 - 131.h5')

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

I need to run this code on the latest version of Keras and Tensorflow with Python 3.7 - I need to run it on Raspberry Pi. The error:

 SystemError                               Traceback (most recent call last)
<ipython-input-15-914c5b8863a1> in <module>
      1 #model = tf.keras.models.load_model('L-CNN v4.0.h5')
      2 #model = tf.keras.models.load_model('MobileNetV2 - 131 - 2.0.h5')
----> 3 model = tf.keras.models.load_model('ShuffleNetV2 - 131.h5')
      4 #model=load_model('ShuffleNetV2 - 131.h5')
      5 model.compile(loss='categorical_crossentropy',

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\saving\save.py in load_model(filepath, custom_objects, compile)
    144   if (h5py is not None and (
    145       isinstance(filepath, h5py.File) or h5py.is_hdf5(filepath))):
--> 146     return hdf5_format.load_model_from_hdf5(filepath, custom_objects, compile)
    147
    148   if isinstance(filepath, six.string_types):

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\saving\hdf5_format.py in load_model_from_hdf5(filepath, custom_objects, compile)
    166     model_config = json.loads(model_config.decode('utf-8'))
    167     model = model_config_lib.model_from_config(model_config,
--> 168                                                custom_objects=custom_objects)
    169
    170     # set weights

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\saving\model_config.py in model_from_config(config, custom_objects)
     53                     '`Sequential.from_config(config)`?')
     54   from tensorflow.python.keras.layers import deserialize  # pylint: disable=g-import-not-at-top
---> 55   return deserialize(config, custom_objects=custom_objects)
     56
     57

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\layers\serialization.py in deserialize(config, custom_objects)
    104       module_objects=globs,
    105       custom_objects=custom_objects,
--> 106       printable_module_name='layer')

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\utils\generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    301             custom_objects=dict(
    302                 list(_GLOBAL_CUSTOM_OBJECTS.items()) +
--> 303                 list(custom_objects.items())))
    304       with CustomObjectScope(custom_objects):
    305         return cls.from_config(cls_config)

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\engine\network.py in from_config(cls, config, custom_objects)
    935     """
    936     input_tensors, output_tensors, created_layers = reconstruct_from_config(
--> 937         config, custom_objects)
    938     model = cls(inputs=input_tensors, outputs=output_tensors,
    939                 name=config.get('name'))

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\engine\network.py in reconstruct_from_config(config, custom_objects, created_layers)
   1901       if layer in unprocessed_nodes:
   1902         for node_data in unprocessed_nodes.pop(layer):
-> 1903           process_node(layer, node_data)
   1904
   1905   input_tensors = []

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\engine\network.py in process_node(layer, node_data)
   1849       if not isinstance(input_tensors, dict) and len(flat_input_tensors) == 1:
   1850         input_tensors = flat_input_tensors[0]
-> 1851       output_tensors = layer(input_tensors, **kwargs)
   1852
   1853       # Update node index map.

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in __call__(self, inputs, *args, **kwargs)
    771                     not base_layer_utils.is_in_eager_or_tf_function()):
    772                   with auto_control_deps.AutomaticControlDependencies() as acd:
--> 773                     outputs = call_fn(cast_inputs, *args, **kwargs)
    774                     # Wrap Tensors in `outputs` in `tf.identity` to avoid
    775                     # circular dependencies.

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\layers\core.py in call(self, inputs, mask, training)
    844     with backprop.GradientTape(watch_accessed_variables=True) as tape,\
    845         variable_scope.variable_creator_scope(_variable_creator):
--> 846       result = self.function(inputs, **kwargs)
    847     self._check_variables(created_variables, tape.watched_variables())
    848     return result

C:\ProgramData\Anaconda3\envs\Computer Vision\lib\site-packages\tensorflow_core\python\keras\layers\core.py in channel_shuffle(x)

SystemError: unknown opcode

I really need to fix this incompatibilities. Can you tell me if I have to change something on Kaggle to train it again or i don;t know..


问:
Create a folder and sub folder in Excel VBA
I have a pull down menu of companies that is populated by a list on another sheet. Three columns, Company, Job #, and Part Number.

When a job is created I need a folder for said company and a sub-folder for said Part Number.

If you go down the path it would look like:

C:\Images\Company Name\Part Number\

If either company name or Part number exists don't create, or overwrite the old one. Just go to next step. So if both folders exist nothing happens, if one or both don't exist create as required.

Another question is there a way to make it so it works on Macs and PCs the same?

答:
For those looking for a cross-platform way that works on both Windows and Mac, the following works: </p>

```<code>Sub CreateDir(strPath As String)
    Dim elm As Variant
    Dim strCheckPath As String

    strCheckPath = ""
    For Each elm In Split(strPath, Application.PathSeparator)
        strCheckPath = strCheckPath & elm & Application.PathSeparator
        If (Len(strCheckPath) > 1 And Not FolderExists(strCheckPath)) Then
            MkDir strCheckPath
        End If
    Next
End Sub

Function FolderExists(FolderPath As String) As Boolean
     FolderExists = True
     On Error Resume Next
     ChDir FolderPath
     If Err <> 0 Then FolderExists = False
     On Error GoTo 0
End Function
</code>```

Body:
For those looking for a cross-platform way that works on both Windows and Mac, the following works:

Sub CreateDir(strPath As String)
    Dim elm As Variant
    Dim strCheckPath As String

    strCheckPath = ""
    For Each elm In Split(strPath, Application.PathSeparator)
        strCheckPath = strCheckPath & elm & Application.PathSeparator
        If (Len(strCheckPath) > 1 And Not FolderExists(strCheckPath)) Then
            MkDir strCheckPath
        End If
    Next
End Sub

Function FolderExists(FolderPath As String) As Boolean
     FolderExists = True
     On Error Resume Next
     ChDir FolderPath
     If Err <> 0 Then FolderExists = False
     On Error GoTo 0
End Function


问:
Extending a line segment to fit into a bounding box
I have a line segment defined by two pointFs, along with a 2D bounding rectangle.  I want to extend the line segment as much as possible in both directions so that the segment is flush with the walls of the bounding box.  Here are some examples of what I'm trying to do:

Does anyone have any suggestions on how to do this?

答:
An extended version of the @andredor algorithm to cover all cases (also when the segments are not parallel to the axes - e.g. when the segments are diagonal). With elaborate explanation of the method as documentation.</p>

```<code>def extend_line(xmin, ymin, xmax, ymax, x1, y1, x2, y2):
    """
    Extend a line so that it reaches the walls of the bbox.

    Args:
        xmin(int): The very left coordinate of the bbox.
        ymin(int): The very top coordinate of the bbox.
        xmax(int): The very right coordinate of the bbox.
        ymax(int): The very bottom coordinate of the bbox.
        x1(int): The start x coordinate of the line.
        y1(int): The start y coordinate of the line.
        x2(int): The end x coordinate of the line.
        y2(int): The end y coordinate of the line.

    Returns:
        - (list): The start and end (x, y) coordinates of the extended line.
    """

    # If we imagine extending the line until it crosses the top wall of the
    # bbox at point `(xmin, y_for_xmin)` and then imagine drawing
    # perpendicular lines from each point `(x1, y1)`, `(x2, y2)` to the wall
    # of the bbox, we end up with 2 perpendicular trianlges with the same
    # angles - similar triangles. The rule of the similar triangles is that
    # the side lengths of two similar triangles are proportional.
    # That's how we get the equal ratios:
    # `| y_for_xmin - y1 | / | xmin - x1 | == | y2 - y1 | / | x2 - x1 |`
    # After we move some numbers from one to the other side of this equation,
    # we get the value for `y_for_xmin`. That's where the line should cross
    # the top wall of the bbox. We do the same for all other coordinates.
    # NOTE: These calculations are valid if one starts to draw a line from top
    # to botton and from left to right. In case the direction is reverted, we
    # need to switch the min and max for each point (x, y). We do that below.
    y_for_xmin = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1)
    y_for_xmax = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1)
    x_for_ymin = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1)
    x_for_ymax = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1)

    # The line is vertical
    if (x2 - x1) < (y2 - y1):
        # The line is drawn from right to left
        if x1 > x2:
            # Switch the min and max x coordinates for y,
            # because the direction is from right (min) to left (max)
            y_for_xmin, y_for_xmax = y_for_xmax, y_for_xmin
    # The line is horizontal
    else:
        # The line is drawn from bottom to top
        if y1 > y2:
            # Switch the min and max y coordinates for x,
            # because the direction is from bottom (min) to top (max)
            x_for_ymin, x_for_ymax = x_for_ymax, x_for_ymin

    # The line is drawn from right to left
    if x1 > x2:
        # Get the maximal value for x1.
        # When `x_for_ymin < xmin`(line goes out of the
        # bbox from the top), we clamp to xmin.
        x1 = max(max(int(x_for_ymin), xmin), x1)
    # The line is drawn from left to right
    else:
        # Get the minimal value for x1.
        # When `x_for_ymin < xmin`(line goes out of the
        # bbox from the top), we clamp to xmin.
        x1 = min(max(int(x_for_ymin), xmin), x1)

    # Get the maximal value for x2.
    # When `x_for_ymax > xmax` (line goes out of the
    # bbox from the bottom), we clamp to xmax.
    x2 = max(min(int(x_for_ymax), xmax), x2)

    # Get the minimal value for y1
    # When `y_for_xmin < ymin`(line goes out of the
    # bbox from the left), we clamp to ymin.
    y1 = min(max(int(y_for_xmin), ymin), ymax)

    # Get the minimal value for y2
    y2 = min(int(y_for_xmax), ymax)

    # Done
    return [x1, y1, x2, y2]
</code>```

Body:
An extended version of the @andredor algorithm to cover all cases (also when the segments are not parallel to the axes - e.g. when the segments are diagonal). With elaborate explanation of the method as documentation.

def extend_line(xmin, ymin, xmax, ymax, x1, y1, x2, y2):
    """
    Extend a line so that it reaches the walls of the bbox.

    Args:
        xmin(int): The very left coordinate of the bbox.
        ymin(int): The very top coordinate of the bbox.
        xmax(int): The very right coordinate of the bbox.
        ymax(int): The very bottom coordinate of the bbox.
        x1(int): The start x coordinate of the line.
        y1(int): The start y coordinate of the line.
        x2(int): The end x coordinate of the line.
        y2(int): The end y coordinate of the line.

    Returns:
        - (list): The start and end (x, y) coordinates of the extended line.
    """

    # If we imagine extending the line until it crosses the top wall of the
    # bbox at point `(xmin, y_for_xmin)` and then imagine drawing
    # perpendicular lines from each point `(x1, y1)`, `(x2, y2)` to the wall
    # of the bbox, we end up with 2 perpendicular trianlges with the same
    # angles - similar triangles. The rule of the similar triangles is that
    # the side lengths of two similar triangles are proportional.
    # That's how we get the equal ratios:
    # `| y_for_xmin - y1 | / | xmin - x1 | == | y2 - y1 | / | x2 - x1 |`
    # After we move some numbers from one to the other side of this equation,
    # we get the value for `y_for_xmin`. That's where the line should cross
    # the top wall of the bbox. We do the same for all other coordinates.
    # NOTE: These calculations are valid if one starts to draw a line from top
    # to botton and from left to right. In case the direction is reverted, we
    # need to switch the min and max for each point (x, y). We do that below.
    y_for_xmin = y1 + (y2 - y1) * (xmin - x1) / (x2 - x1)
    y_for_xmax = y1 + (y2 - y1) * (xmax - x1) / (x2 - x1)
    x_for_ymin = x1 + (x2 - x1) * (ymin - y1) / (y2 - y1)
    x_for_ymax = x1 + (x2 - x1) * (ymax - y1) / (y2 - y1)

    # The line is vertical
    if (x2 - x1) < (y2 - y1):
        # The line is drawn from right to left
        if x1 > x2:
            # Switch the min and max x coordinates for y,
            # because the direction is from right (min) to left (max)
            y_for_xmin, y_for_xmax = y_for_xmax, y_for_xmin
    # The line is horizontal
    else:
        # The line is drawn from bottom to top
        if y1 > y2:
            # Switch the min and max y coordinates for x,
            # because the direction is from bottom (min) to top (max)
            x_for_ymin, x_for_ymax = x_for_ymax, x_for_ymin

    # The line is drawn from right to left
    if x1 > x2:
        # Get the maximal value for x1.
        # When `x_for_ymin < xmin`(line goes out of the
        # bbox from the top), we clamp to xmin.
        x1 = max(max(int(x_for_ymin), xmin), x1)
    # The line is drawn from left to right
    else:
        # Get the minimal value for x1.
        # When `x_for_ymin < xmin`(line goes out of the
        # bbox from the top), we clamp to xmin.
        x1 = min(max(int(x_for_ymin), xmin), x1)

    # Get the maximal value for x2.
    # When `x_for_ymax > xmax` (line goes out of the
    # bbox from the bottom), we clamp to xmax.
    x2 = max(min(int(x_for_ymax), xmax), x2)

    # Get the minimal value for y1
    # When `y_for_xmin < ymin`(line goes out of the
    # bbox from the left), we clamp to ymin.
    y1 = min(max(int(y_for_xmin), ymin), ymax)

    # Get the minimal value for y2
    y2 = min(int(y_for_xmax), ymax)

    # Done
    return [x1, y1, x2, y2]


问:
JS intervals and timeouts unexpectedly stop in webkit
Does anyone meet the problem when all the timeouts and intervals are stopped without any reason?

It seems that it happens in WebKit browsers, including QtWebKit custom app. Especially when minimized, but not every time.

I've never seen the problem at my PC, but several customers report the symptoms that point on it, and in logs I see that their client stops pinging the server.

The project uses ExtJS, Google Maps and some other open-source libraries.

答: I know you said it's mostly when the browser is minimized, but is the page responsive at all if you are seeing this behavior on an active/visible page?  If the page is unresponsive, slow to react to user interaction, etc, could be some other JavaScript function (other than your timeouts/intervals) is sucking up the thread.  And since JS is single threaded (with some HTML5 exceptions), then it could prevent other JS from running.</p>


问:
can we add multiple file paths for azure data explorer command in azure DevOps task
can we add multiple file paths for azure data explorer command in azure DevOps task?
If yes, what is the order of execution?

I basically just want to point all the files (create table scripts, alter table scripts, functions scripts) in a single task.

答:
There is no predetermined order for the execution in file path match pattern.
I've added a feature to our backlog to support this, but for the time being you'll need to split the step to multiple steps. </p>


问:
Inbound and Outbound Rules Confusion Azure
I am using same NSG for two subnets in a VM. Now i have created a Custom rule where VM1 cannot accept packets from VM2. But default NSG rule allows VM2 to send packets to VM1.

Here are the pictures - Vm2 to Vm1 outbound default rule created by NSG

Vm1 custom inbound rule set by me

Does VM2 communicate with VM1 or can VM1 receive packets from VM2?

答:
As your screenshot displayed, VM2 can send packages to VM1 but VM1 can not receive packages from VM2 because the inbound traffic from VM2 is blocked.

For a short test. VM1 is VMb and VM2 is VMc in my example.

The NSG setting of both subnets

From VMb to VMC

From VMC to VMb


问:
i am building a django projects using a medium blogpost, i cannot understand the purpose of these three lines of code
this application is a order manager and I am new to django therefore
i do not know what these line of code do so please help me understand what this piece of code is used for

```<code>objects = models.Manager()
browser = ProductManager()
tag_final_value.short_description = 'Value'
</code>```

this my models.py file

```<code>class Product(models.Model):
    title = models.CharField(max_length=150, unique=True)
    category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
    active = models.BooleanField(default=True)
    value = models.DecimalField(default=0.00, decimal_places=2, max_digits=10)
    discount_value = models.DecimalField(default=0.00, decimal_places=2, max_digits=10)
    final_value = models.DecimalField(default=0.00, decimal_places=2, max_digits=10)
    qty = models.PositiveIntegerField(default=0)

    objects = models.Manager()
    browser = ProductManager()

    class Meta:
        verbose_name_plural = 'Products'

    def save(self, *args, **kwargs):
        self.final_value = self.discount_value if self.discount_value > 0 else self.value
        super().save(*args, **kwargs)

    def __str__(self):
        return self.title

    def tag_final_value(self):
        return f'{CURRENCY} {self.final_value}'
    tag_final_value.short_description = 'Value'

</code>```

this my managers.py file

```<code>from django.db import models

class ProductManager(models.Manager):

    def active(self):
        return self.filter(active=True)

    def have_qty(self):
        return self.active().filter(qty__gte=1)
</code>```

答:
objects is your default manager
You can get all objects on particular model by using
products = Products.objects.all()
browser is your custom model you have created by using a class ProductManager.
You can get all objects using this manager by using
products = Products.browser.all()

Basically, by defining a custom manager you can narrow down your queryset with some methods you would like to add. So, that you don't have to user filters and other complex queryset all the time you can just call your custom manager

You can read more here.

Body:
this application is a order manager and I am new to django therefore
i do not know what these line of code do so please help me understand what this piece of code is used for

objects = models.Manager()
browser = ProductManager()
tag_final_value.short_description = 'Value'

this my models.py file

class Product(models.Model):
    title = models.CharField(max_length=150, unique=True)
    category = models.ForeignKey(Category, null=True, on_delete=models.SET_NULL)
    active = models.BooleanField(default=True)
    value = models.DecimalField(default=0.00, decimal_places=2, max_digits=10)
    discount_value = models.DecimalField(default=0.00, decimal_places=2, max_digits=10)
    final_value = models.DecimalField(default=0.00, decimal_places=2, max_digits=10)
    qty = models.PositiveIntegerField(default=0)

    objects = models.Manager()
    browser = ProductManager()

    class Meta:
        verbose_name_plural = 'Products'

    def save(self, *args, **kwargs):
        self.final_value = self.discount_value if self.discount_value > 0 else self.value
        super().save(*args, **kwargs)

    def __str__(self):
        return self.title

    def tag_final_value(self):
        return f'{CURRENCY} {self.final_value}'
    tag_final_value.short_description = 'Value'

this my managers.py file

from django.db import models

class ProductManager(models.Manager):

    def active(self):
        return self.filter(active=True)

    def have_qty(self):
        return self.active().filter(qty__gte=1)


问:
Elastic Search on multiple fields with fuzziness matches and sort on multiple fields combined scores
I'm working with Elastic Search in Laravel my index has 3 fields text,mood,haloha_id.
First I want to match "haloha_id"(consider haloha_id as post and text as comments on that post) if match then do further matching.
suppose "haloha_id" is matched now I want to match a substring in the "text" field then match "mood"(which is integer either 0,1,2 etc) "mood should be matched only if some of "text" is matched otherwise not.I'm making Like Mine query mean comments matching with user's comments for the specific post will be shown only. The issue in my query is that

My own Comments doesn't appear to the top hence its matched 100%

If someone "mood" and "comments" matched 100% to mine then it doesn't appear to the top.

I removed "mood" related query but score has no effect it means score doesn't include mood matched score.

Here is my query.

```<code> "query"=>[

    "bool"=>[
        "should"=>[
            "match"=>[
                "text"=>[
                    "query"=>$userHaloha->filtered_text,
                    "fuzziness"=>"AUTO",
                ]
            ]
        ],
        "minimum_should_match"=>1,
        "must"=>[
            "match"=>[
                "mood"=>$userHaloha->mood,
            ],
            "match"=>[
                "haloha_id"=>$userHaloha->haloha_id
            ]
        ]
</code>```

答:
Query is self explanatory. I have added "haloha_id" to filter block (which doesnot score documents), "text" to must block(to score documents) and "mood" to should block(to boost documents)

```<code>{
  "query": {
    "bool": {
      "filter": [
        {
          "match": {
            "haloha_id": "5ecf6bff25a36366cd134db2"
          }
        }
      ],
      "must": [
        {
          "match": {
            "text": {
              "query": "chilli ",
              "fuzziness": "auto"
            }
          }
        }
      ],
      "should": [
        {
          "term": {
            "mood": {
              "value": 2
            }
          }
        }
      ]
    }
  }
}
</code>```

Issue in mood:3 getting higher ranked than mood:2(searched term in should clause) is due to sharding

From docs

If you notice that two documents with the same content get different
  scores or that an exact match is not ranked first, then the issue
  might be related to sharding. By default, Elasticsearch makes each
  shard responsible for producing its own scores. However since index
  statistics are an important contributor to the scores, this only works
  well if shards have similar index statistics. The assumption is that
  since documents are routed evenly to shards by default, then index
  statistics should be very similar and scoring would work as expected.
  However in the event that you either:

use routing at index time, query multiple indices, or have too little
  data in your index then there are good chances that all shards that
  are involved in the search request do not have similar index
  statistics and relevancy could be bad.

If you have a small dataset, the easiest way to work around this issue
  is to index everything into an index that has a single shard
  (index.number_of_shards: 1), which is the default. Then index
  statistics will be the same for all documents and scores will be
  consistent.

Body:
I'm working with Elastic Search in Laravel my index has 3 fields text,mood,haloha_id.
First I want to match "haloha_id"(consider haloha_id as post and text as comments on that post) if match then do further matching.
suppose "haloha_id" is matched now I want to match a substring in the "text" field then match "mood"(which is integer either 0,1,2 etc) "mood should be matched only if some of "text" is matched otherwise not.I'm making Like Mine query mean comments matching with user's comments for the specific post will be shown only. The issue in my query is that

My own Comments doesn't appear to the top hence its matched 100%

If someone "mood" and "comments" matched 100% to mine then it doesn't appear to the top.

I removed "mood" related query but score has no effect it means score doesn't include mood matched score.

Here is my query.

 "query"=>[

    "bool"=>[
        "should"=>[
            "match"=>[
                "text"=>[
                    "query"=>$userHaloha->filtered_text,
                    "fuzziness"=>"AUTO",
                ]
            ]
        ],
        "minimum_should_match"=>1,
        "must"=>[
            "match"=>[
                "mood"=>$userHaloha->mood,
            ],
            "match"=>[
                "haloha_id"=>$userHaloha->haloha_id
            ]
        ]

Body:
Query is self explanatory. I have added "haloha_id" to filter block (which doesnot score documents), "text" to must block(to score documents) and "mood" to should block(to boost documents)

{
  "query": {
    "bool": {
      "filter": [
        {
          "match": {
            "haloha_id": "5ecf6bff25a36366cd134db2"
          }
        }
      ],
      "must": [
        {
          "match": {
            "text": {
              "query": "chilli ",
              "fuzziness": "auto"
            }
          }
        }
      ],
      "should": [
        {
          "term": {
            "mood": {
              "value": 2
            }
          }
        }
      ]
    }
  }
}

Issue in mood:3 getting higher ranked than mood:2(searched term in should clause) is due to sharding

From docs

If you notice that two documents with the same content get different
  scores or that an exact match is not ranked first, then the issue
  might be related to sharding. By default, Elasticsearch makes each
  shard responsible for producing its own scores. However since index
  statistics are an important contributor to the scores, this only works
  well if shards have similar index statistics. The assumption is that
  since documents are routed evenly to shards by default, then index
  statistics should be very similar and scoring would work as expected.
  However in the event that you either:

use routing at index time, query multiple indices, or have too little
  data in your index then there are good chances that all shards that
  are involved in the search request do not have similar index
  statistics and relevancy could be bad.

If you have a small dataset, the easiest way to work around this issue
  is to index everything into an index that has a single shard
  (index.number_of_shards: 1), which is the default. Then index
  statistics will be the same for all documents and scores will be
  consistent.


问:
IIS URL rewrite not working, the input URL not even captured?
The Failed Request Tracing works fine to log failed rewritings. I can view the log files and at least understand why the rewriting not working.

The regex pattern has passed a matching test OK, but the input URLs I enter in the browser are not even captured. All the URLs mapped to controller actions are captured (my website is an ASP.NET MVC app) however the URL I need to be rewritten is not mapped to any, the page shows 404. But I expect it to be rewritten to some working URL (to test it out, so that instead of showing 404, it should be rewritten to the target url and shows the returned content from there).

My URL rewriting rule uses a Reverse Proxy template.

I hope what I understand here is correct. How can I diagnose this? My purpose is just to do something like turning IIS into a reverse proxy by capturing all requests through my website, check if any matching the defined regex pattern before requesting to the rewritten URL and returning back the content to the original client.

Update

For those who may not know about ASP.NET MVC:

Suppose my website has a controller called HomeController with action Index and the URL mapped to it is /Home/Index.

The URL I mean not mapped to any action here may be /Home/TestProxy
Here the HomeController does not expose any action TestProxy and also there is not any routing rule maps /Home/TestProxy to any action. So in this case the ASP.NET MVC app will shows a 404 page.

As I said above, for the URLs mapped to a valid controller action, they seem to be captured and considered as input URLs (before being checked against the rewriting rule). But for URLs not mapped to any controller action (showing 404), I don't see any logged as input URLs (so of course they will not be checked against the rewriting rule and it won't work).

Update 2

Actually my tested URL is not even mapped to a controller so looks like it's not logged by the Failed Requests Tracing rule I setup. Now I've tried using a URL mapped to a controller but not to any action (it still shows 404) but successfully logged by the Failed Request Tracing rule. I can see this in the log file:

```<code><EventData>
   <Data Name="ContextId">{80000034-0000-F000-B63F-84710C7967BB}</Data>
   <Data Name="Pattern">testproxy/(.*)</Data>
   <Data Name="Input">home/testproxy/index</Data>
   <Data Name="Negate">false</Data>
   <Data Name="Matched">true</Data>
</EventData>
</code>```

So it reported a matched pattern, but still the page shows 404, whereas I expected it to return the content from the rewritten url (which should be http://10.0.0.5/index - I confirm that this URL works if requested directly, it's just another simple published website on local network). I don't even know if this is possible now or I did something wrong here.

答:
URL rewrite inbound rule get executed before controller action.It is appreciated if you could post full error message in your Failed request tracing log.

If the request http://10.0.0.5/index but return 404 from IIS. It sounds like your ARR proxy was not enabled at all. First of all, please try to disable reverse proxy outbound rule. Then go to IIS manager->server node->application request routing cache->Server proxy setting->Enable proxy.

Update:

The rewrite rule has worked and it seems that the request was stopped by

[HttpException]: The controller for path '/questions/62078944/iis-url-rewrite-not-working-the-input-url-not-even-captured' was not found or does not implement IController.
   at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
   at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->"

Body:
The Failed Request Tracing works fine to log failed rewritings. I can view the log files and at least understand why the rewriting not working.

The regex pattern has passed a matching test OK, but the input URLs I enter in the browser are not even captured. All the URLs mapped to controller actions are captured (my website is an ASP.NET MVC app) however the URL I need to be rewritten is not mapped to any, the page shows 404. But I expect it to be rewritten to some working URL (to test it out, so that instead of showing 404, it should be rewritten to the target url and shows the returned content from there).

My URL rewriting rule uses a Reverse Proxy template.

I hope what I understand here is correct. How can I diagnose this? My purpose is just to do something like turning IIS into a reverse proxy by capturing all requests through my website, check if any matching the defined regex pattern before requesting to the rewritten URL and returning back the content to the original client.

Update

For those who may not know about ASP.NET MVC:

Suppose my website has a controller called HomeController with action Index and the URL mapped to it is /Home/Index.

The URL I mean not mapped to any action here may be /Home/TestProxy
Here the HomeController does not expose any action TestProxy and also there is not any routing rule maps /Home/TestProxy to any action. So in this case the ASP.NET MVC app will shows a 404 page.

As I said above, for the URLs mapped to a valid controller action, they seem to be captured and considered as input URLs (before being checked against the rewriting rule). But for URLs not mapped to any controller action (showing 404), I don't see any logged as input URLs (so of course they will not be checked against the rewriting rule and it won't work).

Update 2

Actually my tested URL is not even mapped to a controller so looks like it's not logged by the Failed Requests Tracing rule I setup. Now I've tried using a URL mapped to a controller but not to any action (it still shows 404) but successfully logged by the Failed Request Tracing rule. I can see this in the log file:

<EventData>
   <Data Name="ContextId">{80000034-0000-F000-B63F-84710C7967BB}</Data>
   <Data Name="Pattern">testproxy/(.*)</Data>
   <Data Name="Input">home/testproxy/index</Data>
   <Data Name="Negate">false</Data>
   <Data Name="Matched">true</Data>
</EventData>

So it reported a matched pattern, but still the page shows 404, whereas I expected it to return the content from the rewritten url (which should be http://10.0.0.5/index - I confirm that this URL works if requested directly, it's just another simple published website on local network). I don't even know if this is possible now or I did something wrong here.


问:
Gradle sync failed: Unable to find method after update to Gradle 4.0.0
I updated gradle to 4.0.0

```<code>classpath 'com.android.tools.build:gradle:4.0.0'
</code>```

and the distributionUrl to:

```<code>distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip
</code>```

after sync the prject I got:

Unable to find method 'org.gradle.api.tasks.TaskInputs.property(Ljava/lang/String;Ljava/lang/Object;)Lorg/gradle/api/tasks/TaskInputs;'.

I know, if I downgrade the version the project will sync properly. but is there some incompatibility somewhere ? if it's true why there is some updates ?

答:
How I solved an issue like was taking two steps:

delete your Gradle and reinstall a new version

Navigate to to File and click on Invalidate and clear cache to restart android studio

Either option 1 or 2 might work.

Body:
I updated gradle to 4.0.0

classpath 'com.android.tools.build:gradle:4.0.0'

and the distributionUrl to:

distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip

after sync the prject I got:

Unable to find method 'org.gradle.api.tasks.TaskInputs.property(Ljava/lang/String;Ljava/lang/Object;)Lorg/gradle/api/tasks/TaskInputs;'.

I know, if I downgrade the version the project will sync properly. but is there some incompatibility somewhere ? if it's true why there is some updates ?


问:
Using the remote function of jquery validation
I'm trying to figure out how I can turn this:

```<code>$('#username').blur(function(){
    $.post('register/isUsernameAvailable',
           {"username":$('#username').val()},
           function(data){
               if(data.username == "found"){
                   alert('username already in use');
               }
           }, 'json');
});
</code>```

into something close to this:

```<code>rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: {
                url: 'register/isUsernameAvailable',
                type: 'post',
                data: {
                    'username': $('#username').val()
                }

            }
        }
</code>```

However I'm having a hard time finishing it off. What I want is instead of the alert to have it display the error message but I can set the message inside the actual jquery validation messages.

http://docs.jquery.com/Plugins/Validation/Methods/remote#options

UPDATE:

For some reason its not doing it as a POST its doing it as a GET request and not sure why. Here's the updated code:

```<code>rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: {
                url: 'register/isUsernameAvailable',
                dataType: 'post',
                data: {
                    'username': $('#username').val()
                },
                success: function(data) {
                    if (data.username == 'found')
                    {
                        message: {
                            username: 'The username is already in use!'
                        }
                    }
                }

            }
        },
</code>```

UPDATE 2:

Now I'm getting somewhere I'm back to getting the POST request. I'm getting two more problems. One of which is the fact that for another POST request to be done the user has to refresh the form. And the last problem is that if the returned username is found it DOES NOT show the error message.

```<code>rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: {
                type: 'post',
                url: 'register/isUsernameAvailable',
                data: {
                    'username': $('#username').val()
                },
                dataType: 'json',
                success: function(data) {
                    if (data.username == 'found')
                    {
                        message: {
                            username: 'The username is already in use!'
                        }
                    }
                }

            }
        },
</code>```

UPDATE:

```<code>public function isUsernameAvailable()
{
    if ($this->usersmodel->isUsernameAvailable($this->input->post('username')))
    {
        return false;
    }
    else
    {
        return true;
    }
}
</code>```

UPDATE 4:

Controller:

```<code>public function isUsernameAvailable()
{
    if ($this->usersmodel->isUsernameAvailable($this->input->post('username')))
    {
        return false;
    }
    else
    {
        return true;
    }
}

public function isEmailAvailable()
{
    if ($this->usersmodel->isEmailAvailable($this->input->post('emailAddress')))
    {
        return false;
    }
    else
    {
        return true;
    }
}
</code>```

MODEL:

```<code>/**
 * Check if username available for registering
 *
 * @param   string
 * @return  bool
 */
function isUsernameAvailable($username)
{
    $this->db->select('username');
    $this->db->where('LOWER(username)=', strtolower($username));
    $query = $this->db->get($this->usersTable);
    if ($query->num_rows() == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * Check if email available for registering
 *
 * @param   string
 * @return  bool
 */
function isEmailAvailable($email)
{
    $this->db->select('email');
    $this->db->where('LOWER(email)=', strtolower($email));
    $query = $this->db->get($this->usersTable);
    if($query->num_rows() == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

答:
```<code>Jquery Code:
 rules: {
        email: {
                required: true,
                maxlength: 50,
                email: true,
                 remote: {
        url: "<?php echo base_url('user/email_check') ?>",
        type: "post",
        data: {
          email: function() {
            return $( "#email" ).val();
          }
        }
      }
            },
    },
     messages: {
      email: {
          required: "E-mailadres",
          email: "Please enter valid email",
          maxlength: "The email name should less than or equal to 50 characters",
          remote: jQuery.validator.format("{0} is already taken.")
        },
    },

PHP Code:
  if($results->num_rows == 0)
    {
        echo "true";  //good to register
    }
    else
    {
        echo "false"; //already registered
    }
</code>```

Body:
I'm trying to figure out how I can turn this:

$('#username').blur(function(){
    $.post('register/isUsernameAvailable',
           {"username":$('#username').val()},
           function(data){
               if(data.username == "found"){
                   alert('username already in use');
               }
           }, 'json');
});

into something close to this:

rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: {
                url: 'register/isUsernameAvailable',
                type: 'post',
                data: {
                    'username': $('#username').val()
                }

            }
        }

However I'm having a hard time finishing it off. What I want is instead of the alert to have it display the error message but I can set the message inside the actual jquery validation messages.

http://docs.jquery.com/Plugins/Validation/Methods/remote#options

UPDATE:

For some reason its not doing it as a POST its doing it as a GET request and not sure why. Here's the updated code:

rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: {
                url: 'register/isUsernameAvailable',
                dataType: 'post',
                data: {
                    'username': $('#username').val()
                },
                success: function(data) {
                    if (data.username == 'found')
                    {
                        message: {
                            username: 'The username is already in use!'
                        }
                    }
                }

            }
        },

UPDATE 2:

Now I'm getting somewhere I'm back to getting the POST request. I'm getting two more problems. One of which is the fact that for another POST request to be done the user has to refresh the form. And the last problem is that if the returned username is found it DOES NOT show the error message.

rules: {
        username: {
            minlength: 6,
            maxlength: 12,
            remote: {
                type: 'post',
                url: 'register/isUsernameAvailable',
                data: {
                    'username': $('#username').val()
                },
                dataType: 'json',
                success: function(data) {
                    if (data.username == 'found')
                    {
                        message: {
                            username: 'The username is already in use!'
                        }
                    }
                }

            }
        },

UPDATE:

public function isUsernameAvailable()
{
    if ($this->usersmodel->isUsernameAvailable($this->input->post('username')))
    {
        return false;
    }
    else
    {
        return true;
    }
}

UPDATE 4:

Controller:

public function isUsernameAvailable()
{
    if ($this->usersmodel->isUsernameAvailable($this->input->post('username')))
    {
        return false;
    }
    else
    {
        return true;
    }
}

public function isEmailAvailable()
{
    if ($this->usersmodel->isEmailAvailable($this->input->post('emailAddress')))
    {
        return false;
    }
    else
    {
        return true;
    }
}

MODEL:

/**
 * Check if username available for registering
 *
 * @param   string
 * @return  bool
 */
function isUsernameAvailable($username)
{
    $this->db->select('username');
    $this->db->where('LOWER(username)=', strtolower($username));
    $query = $this->db->get($this->usersTable);
    if ($query->num_rows() == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * Check if email available for registering
 *
 * @param   string
 * @return  bool
 */
function isEmailAvailable($email)
{
    $this->db->select('email');
    $this->db->where('LOWER(email)=', strtolower($email));
    $query = $this->db->get($this->usersTable);
    if($query->num_rows() == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}


问:
Join recordsets where joined value is between base value and higher base value in another row
I want to join a recordset where a particular value in a column of the joining table falls between values over rows of the base tables. Given table b is left joined to a:

```<code>WITH a (v) AS (
 VALUES (1),(3),(5),(7),(9)
), b (v) AS (
 VALUES (1),(2),(3),(4),(5)
) SELECT a.v, b.v FROM a
LEFT JOIN b ON b.v >= a.v /* AND ??? */
</code>```

the target output (c) I hope to achieve is:

```<code>a  join  b   =   c
v        v       v
-        -      ---
1        1      1,1
3        2      1,2
5        3      3,3
7        4      3,4
9        5      5,5
                7,
                9
</code>```

I suspect a subquery or window function might do the trick but the solution is not apparent to me and hoping there might be a few good suggestions :)

答:
```<code>WITH
  a (v) AS (SELECT column1 FROM ( VALUES (1),(3),(5),(7),(9) ) a)
, b (v) AS (SELECT column1 FROM ( VALUES (1),(2),(3),(4),(5) ) b)
, a2    AS (select a.v, lead(a.v) over () as v_l from a)
select a2.v,b.v from a2 left join  b on (b.v < a2.v_l and b.v >= a2.v)
</code>```

Body:
I want to join a recordset where a particular value in a column of the joining table falls between values over rows of the base tables. Given table b is left joined to a:

WITH a (v) AS (
 VALUES (1),(3),(5),(7),(9)
), b (v) AS (
 VALUES (1),(2),(3),(4),(5)
) SELECT a.v, b.v FROM a
LEFT JOIN b ON b.v >= a.v /* AND ??? */

the target output (c) I hope to achieve is:

a  join  b   =   c
v        v       v
-        -      ---
1        1      1,1
3        2      1,2
5        3      3,3
7        4      3,4
9        5      5,5
                7,
                9

I suspect a subquery or window function might do the trick but the solution is not apparent to me and hoping there might be a few good suggestions :)


问:
Flutter convert JSON string to multi-level list
I want to convert a string to multi-level list, but I cannot find a efficient way to do.

From String:
[[1,2,3],[1,2]]

To List:
List< List < int>>

答:
Shorter version:</p>

```<code>import 'dart:convert';

void main() {
  var jsonMap = "[[1,2,3],[1,2]]";
  List<List<int>> items = (jsonDecode(jsonMap) as List).map((lst) =>
      (lst as List).map((i) => (i as int)).toList()).toList();
  print(items);
}
</code>```

Body:
Shorter version:

import 'dart:convert';

void main() {
  var jsonMap = "[[1,2,3],[1,2]]";
  List<List<int>> items = (jsonDecode(jsonMap) as List).map((lst) =>
      (lst as List).map((i) => (i as int)).toList()).toList();
  print(items);
}


问:
onPostHandler extension not called when an error is thrown in the handler
I'm upgrading from hapi14 to hapi17, when throwing or returning an error inside a handler onPostHandlers are not called, this isn't listed as a breaking change in either 16 or 17.

I believe this is a result of changing from callbacks to async but i'd love to get it confirmed or find out what the problem is that is preventing the onPostHandler extension being called in the event of an error being throw in the handler.

```<code>const Boom = require('boom');

const extensions = {
  handleOnPostHandler: function (request, h) {
    console.log('we hit it wooo');
    return h.continue;
  }
};

const operations = {
  error: {
    description: 'Endpoint that simulates errors',
    auth: false,
    handler: function (request, h) {
      // comment me out to call the onPostHandler
      throw new Boom('an error');

      // uncomment me to call the onPostHandler
      // return 'potato';
    }
  }
};

exports.register = function (server) {
  server.ext('onPostHandler', extensions.handleOnPostHandler);
  server.route({ method: 'GET', path: '/debug/error', config: operations.error });
};
</code>```

Is there a gross mistake i'm missing or is this expected?

答: This was an undocumented feature that was removed in Hapi6 and as such when upgrading to >16 this functionality cannot be emulated.</p>

Body:
I'm upgrading from hapi14 to hapi17, when throwing or returning an error inside a handler onPostHandlers are not called, this isn't listed as a breaking change in either 16 or 17.

I believe this is a result of changing from callbacks to async but i'd love to get it confirmed or find out what the problem is that is preventing the onPostHandler extension being called in the event of an error being throw in the handler.

const Boom = require('boom');

const extensions = {
  handleOnPostHandler: function (request, h) {
    console.log('we hit it wooo');
    return h.continue;
  }
};

const operations = {
  error: {
    description: 'Endpoint that simulates errors',
    auth: false,
    handler: function (request, h) {
      // comment me out to call the onPostHandler
      throw new Boom('an error');

      // uncomment me to call the onPostHandler
      // return 'potato';
    }
  }
};

exports.register = function (server) {
  server.ext('onPostHandler', extensions.handleOnPostHandler);
  server.route({ method: 'GET', path: '/debug/error', config: operations.error });
};

Is there a gross mistake i'm missing or is this expected?