问:
Periodic Exception in WSDL Export Extension
I have a SOAP service that's been running for a little over a month now. Over the past two weeks we've had situations where the service will randomly start to generate exceptions. Each time, they seem to be related to the export extension, and the error is always along the following lines:

An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior

With "System.ArgumentException: The named node is from a different document context." seeming to be the root cause each time.

What's bugging me is that this service hasn't changed in a month and a half, so I'm confused how suddenly we'd be getting the argument errors all of a sudden. Is this more indicative of an underlying issue (memory leak or similar)?

I have very limited access to the machine this is running on, but can try and get any supporting information as needed. Here's the full exception the wsdl is coming back with:

```<code>    An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
    System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
     Endpoint: [endpoint name here... hidden for security] ----> System.ArgumentException: The named node is from a different document context.
       at System.Xml.XmlAttributeCollection.Append(XmlAttribute node)
       at System.ServiceModel.Description.SoapHelper.CreateSoapFaultBinding(String name, WsdlEndpointConversionContext endpointContext, FaultBinding wsdlFaultBinding, Boolean isEncoded)
       at System.ServiceModel.Description.MessageContractExporter.MessageBindingExporter.ExportMessageBinding(OperationDescription operation, Type messageContractExporterType)
       at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlEndpointConversionContext endpointContext, IWsdlExportExtension extension)
       --- End of inner ExceptionDetail stack trace ---
       at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
       at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
       at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
       at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
       at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleMetadataRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
       at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
       at SyncInvokeGet(Object , Object[] , Object[] )
       at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
       at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
</code>```

EDIT: I wanted to clarify that the service doesn't always hit this exception. Sometimes the wsdl comes back fine, other times it throws this exception (I'd say currently it's a 50/50 shot of getting a successful return). I can't make heads or tails as to why. My initial thought goes to an environment problem, but if that's the case, I don't have a clue where to point the hosting team to look.

EDIT 2: Since asking the initial inquiry I've found out that the client has put the services on multiple servers and is using a load balancer, which, I believe, accounts for the random responses we're getting. I've advised them how to proceed in at least isolating the problem and will go from there.

答:
Is difficult to tell by just looking at that error. it doesn’t look like a communication error, but just in case, make sure you are not using singleton as you may create a bottleneck, Per Call is the default method and it works for most of situations, use singleton only if you specifically need it and wrap logic around to avoid bottlenecks.

It seems the error is serializing the data, so make sure your Data Contracts and Data Members are well defined, avoid using plain objects, use typed objects. Declare Data Members as properties

Hope this helps,
Sebastian

Body:
I have a SOAP service that's been running for a little over a month now. Over the past two weeks we've had situations where the service will randomly start to generate exceptions. Each time, they seem to be related to the export extension, and the error is always along the following lines:

An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior

With "System.ArgumentException: The named node is from a different document context." seeming to be the root cause each time.

What's bugging me is that this service hasn't changed in a month and a half, so I'm confused how suddenly we'd be getting the argument errors all of a sudden. Is this more indicative of an underlying issue (memory leak or similar)?

I have very limited access to the machine this is running on, but can try and get any supporting information as needed. Here's the full exception the wsdl is coming back with:

    An ExceptionDetail, likely created by IncludeExceptionDetailInFaults=true, whose value is:
    System.InvalidOperationException: An exception was thrown in a call to a WSDL export extension: System.ServiceModel.Description.DataContractSerializerOperationBehavior
     Endpoint: [endpoint name here... hidden for security] ----> System.ArgumentException: The named node is from a different document context.
       at System.Xml.XmlAttributeCollection.Append(XmlAttribute node)
       at System.ServiceModel.Description.SoapHelper.CreateSoapFaultBinding(String name, WsdlEndpointConversionContext endpointContext, FaultBinding wsdlFaultBinding, Boolean isEncoded)
       at System.ServiceModel.Description.MessageContractExporter.MessageBindingExporter.ExportMessageBinding(OperationDescription operation, Type messageContractExporterType)
       at System.ServiceModel.Description.WsdlExporter.CallExtension(WsdlEndpointConversionContext endpointContext, IWsdlExportExtension extension)
       --- End of inner ExceptionDetail stack trace ---
       at System.ServiceModel.Description.ServiceMetadataBehavior.MetadataExtensionInitializer.GenerateMetadata()
       at System.ServiceModel.Description.ServiceMetadataExtension.EnsureInitialized()
       at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.InitializationData.InitializeFrom(ServiceMetadataExtension extension)
       at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.GetInitData()
       at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.TryHandleMetadataRequest(Message httpGetRequest, String[] queries, Message& replyMessage)
       at System.ServiceModel.Description.ServiceMetadataExtension.HttpGetImpl.ProcessHttpRequest(Message httpGetRequest)
       at SyncInvokeGet(Object , Object[] , Object[] )
       at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
       at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
       at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

EDIT: I wanted to clarify that the service doesn't always hit this exception. Sometimes the wsdl comes back fine, other times it throws this exception (I'd say currently it's a 50/50 shot of getting a successful return). I can't make heads or tails as to why. My initial thought goes to an environment problem, but if that's the case, I don't have a clue where to point the hosting team to look.

EDIT 2: Since asking the initial inquiry I've found out that the client has put the services on multiple servers and is using a load balancer, which, I believe, accounts for the random responses we're getting. I've advised them how to proceed in at least isolating the problem and will go from there.


来源: stackexchange

问:
How to store each JSON data with restsharper in c#?
I need to get the values from the JSON response, I've tried to do the following but the messagebox shows empty in the Project class.

I've tried to Google my problem (also restsharp tutorials) but until now I wasn't able to fix the problem that I'm having. I've gotten clues here and there online and this is how far I've gotten over the last few days.

The result I am expecting is that each value from the API goes into the variable, which I can then grab per value. I don't want the plain JSON content.

Api Class

```<code>private async void Submit_Button_Click(object sender, RoutedEventArgs e)
{
    var client = new RestClient("http://apage.com/");
    var request = new RestRequest("api/project");
    request.Method = Method.GET;

    request.AddHeader("Accept", "application/json");

    client.AddDefaultHeader("Authorization",
        string.Format("Bearer {0}", "token goes here"));

    var response = client.Execute(request);

    var deserialize = new JsonDeserializer();
    Project output = deserialize.Deserialize<Project>(response);

    Project project = new Project();
    project.check();
}
</code>```

Project Class

```<code>class Project
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Slug { get; set; }
    public string Description { get; set; }
    public string Deadline { get; set; }
    public int User_id { get; set; }
    public string Created_at { get; set; }
    public string Updated_at { get; set; }

    public void check()
    {
        MessageBox.Show(Title);
    }
}
</code>```

JSON Code

```<code>{
    "projects": [
        {
            "id": 29,
            "title": "a_project",
            "slug": "a_project",
            "description": "f",
            "deadline": "2020-04-08 00:00:00",
            "user_id": 19,
            "created_at": "2020-02-11 16:59:45",
            "updated_at": "2020-02-11 16:59:45"
        }
    ]
}
</code>```

Github link: https://github.com/s1129092/n212/blob/master/WpfApp1/MainWindow.xaml.cs

答:
Assuming you have a class like this:

```<code>public class ProjectsModel
{
    public List<Project> Projects { get; set; }
}
</code>```

You can use the following code to get the response data:

```<code>var response = client.Execute<ProjectsModel>(request).Data;
var projects = response.Projects;
</code>```

Then for example:

```<code>foreach(Project p in projects)
{
    MessageBox.Show(p.Title);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to get the values from the JSON response, I've tried to do the following but the messagebox shows empty in the Project class.

I've tried to Google my problem (also restsharp tutorials) but until now I wasn't able to fix the problem that I'm having. I've gotten clues here and there online and this is how far I've gotten over the last few days.

The result I am expecting is that each value from the API goes into the variable, which I can then grab per value. I don't want the plain JSON content.

Api Class

private async void Submit_Button_Click(object sender, RoutedEventArgs e)
{
    var client = new RestClient("http://apage.com/");
    var request = new RestRequest("api/project");
    request.Method = Method.GET;

    request.AddHeader("Accept", "application/json");

    client.AddDefaultHeader("Authorization",
        string.Format("Bearer {0}", "token goes here"));

    var response = client.Execute(request);

    var deserialize = new JsonDeserializer();
    Project output = deserialize.Deserialize<Project>(response);

    Project project = new Project();
    project.check();
}

Project Class

class Project
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Slug { get; set; }
    public string Description { get; set; }
    public string Deadline { get; set; }
    public int User_id { get; set; }
    public string Created_at { get; set; }
    public string Updated_at { get; set; }

    public void check()
    {
        MessageBox.Show(Title);
    }
}

JSON Code

{
    "projects": [
        {
            "id": 29,
            "title": "a_project",
            "slug": "a_project",
            "description": "f",
            "deadline": "2020-04-08 00:00:00",
            "user_id": 19,
            "created_at": "2020-02-11 16:59:45",
            "updated_at": "2020-02-11 16:59:45"
        }
    ]
}

Github link: https://github.com/s1129092/n212/blob/master/WpfApp1/MainWindow.xaml.cs

Body:
Assuming you have a class like this:

public class ProjectsModel
{
    public List<Project> Projects { get; set; }
}

You can use the following code to get the response data:

var response = client.Execute<ProjectsModel>(request).Data;
var projects = response.Projects;

Then for example:

foreach(Project p in projects)
{
    MessageBox.Show(p.Title);
}


问:
Use Font Awesome with "background: url" css
I have a dream !

This 'star' is generated with Font Awesome.

star1

I wan't to replace the green color with an image like this :

star2

This is a Fiddle with what i have try:
http://jsfiddle.net/jmcpeak/M6N24

```<code>  background: url(https://paperpackagingplace.com/wp-content/uploads/2016/01/yellow-2.jpg) -100px -40px no-repeat;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
</code>```

Do know how i can do this ?

答:
Depends on which icon you want to change, you just need to target specific class or all i elements.

.fa-star:before {
  background: url(https://ktfnews.com/wp-content/uploads/2017/10/World-512x360.jpg) -100px -40px no-repeat;
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<i class="fa fa-star fa-stack-2x"></i></code>```

Body:
I have a dream !

This 'star' is generated with Font Awesome.

star1

I wan't to replace the green color with an image like this :

star2

This is a Fiddle with what i have try:
http://jsfiddle.net/jmcpeak/M6N24

  background: url(https://paperpackagingplace.com/wp-content/uploads/2016/01/yellow-2.jpg) -100px -40px no-repeat;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;

Do know how i can do this ?

Body:
Depends on which icon you want to change, you just need to target specific class or all i elements.

.fa-star:before {
  background: url(https://ktfnews.com/wp-content/uploads/2017/10/World-512x360.jpg) -100px -40px no-repeat;
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<i class="fa fa-star fa-stack-2x"></i>


问:
Problem with Sqlite Query - How to convert the code from SQLite v0.9.0 to v1.0.0
I am prettry new to Julia and I am just playing around, and suddenly
the following code starts throwing errors, but it has worked in the past.

```<code>using SQLite
db = SQLite.DB("db")
data = SQLite.Query(db,"SELECT * FROM d")
</code>```

throws:

ERROR: LoadError: MethodError: no method matching
SQLite.Query(::SQLite.DB, ::String)

can someone please enlighten me wha the problem is? Thank you.

I also tried with lower case: query.

答:
Here is a short MWE of differences using SQLLite (v0.9.0 vs v1.0.0) with the current Julia version (1.3.1).

You do not have the table so you need to create it first:

```<code>using SQLite
using DataFrames
db = SQLite.DB("db")
# v0.9.0
SQLite.Query(db,"CREATE TABLE d (col1 INT, col2 varchar2(100))")
# v1.0.0
DBInterface.execute(db,"CREATE TABLE d (col1 INT, col2 varchar2(100))")
</code>```

Now you can check if the table exits:

```<code>julia> SQLite.tables(db) |> DataFrame
1×1 DataFrames.DataFrame
│ Row │ name    │
│     │ String⍰ │
├─────┼─────────┤
│ 1   │ d       │
</code>```

Let's insert some rows (note how one should sepearate data from SQL code via precompiled statements):

```<code>stmt = SQLite.Stmt(db, "INSERT INTO d (col1, col2) VALUES (?, ?)")
#v0.9.0
SQLite.execute!(stmt; values=(1, "Hello world"))
SQLite.execute!(stmt; values=(2, "Goodbye world"))
#v1.0.0
DBInterface.execute(stmt, (1, "Hello world"))
DBInterface.execute(stmt, (2, "Goodbye world"))
</code>```

Now let us get the data

v0.9.0

```<code>julia> data = SQLite.Query(db,"SELECT * FROM d") |> DataFrame
3×2 DataFrame
│ Row │ col1   │ col2          │
│     │ Int64⍰ │ String⍰       │
├─────┼────────┼───────────────┤
│ 1   │ 1      │ Hello world   │
│ 2   │ 2      │ Goodbye world │
</code>```

v1.0.0

```<code>julia> data = DBInterface.execute(db, "select * from d") |> DataFrame
3×2 DataFrame
│ Row │ col1   │ col2          │
│     │ Int64⍰ │ String⍰       │
├─────┼────────┼───────────────┤
│ 1   │ 1      │ Hello world   │
│ 2   │ 2      │ Goodbye world │
</code>```

Body:
I am prettry new to Julia and I am just playing around, and suddenly
the following code starts throwing errors, but it has worked in the past.

using SQLite
db = SQLite.DB("db")
data = SQLite.Query(db,"SELECT * FROM d")

throws:

ERROR: LoadError: MethodError: no method matching
SQLite.Query(::SQLite.DB, ::String)

can someone please enlighten me wha the problem is? Thank you.

I also tried with lower case: query.

Body:
Here is a short MWE of differences using SQLLite (v0.9.0 vs v1.0.0) with the current Julia version (1.3.1).

You do not have the table so you need to create it first:

using SQLite
using DataFrames
db = SQLite.DB("db")
# v0.9.0
SQLite.Query(db,"CREATE TABLE d (col1 INT, col2 varchar2(100))")
# v1.0.0
DBInterface.execute(db,"CREATE TABLE d (col1 INT, col2 varchar2(100))")

Now you can check if the table exits:

julia> SQLite.tables(db) |> DataFrame
1×1 DataFrames.DataFrame
│ Row │ name    │
│     │ String⍰ │
├─────┼─────────┤
│ 1   │ d       │

Let's insert some rows (note how one should sepearate data from SQL code via precompiled statements):

stmt = SQLite.Stmt(db, "INSERT INTO d (col1, col2) VALUES (?, ?)")
#v0.9.0
SQLite.execute!(stmt; values=(1, "Hello world"))
SQLite.execute!(stmt; values=(2, "Goodbye world"))
#v1.0.0
DBInterface.execute(stmt, (1, "Hello world"))
DBInterface.execute(stmt, (2, "Goodbye world"))

Now let us get the data

v0.9.0

julia> data = SQLite.Query(db,"SELECT * FROM d") |> DataFrame
3×2 DataFrame
│ Row │ col1   │ col2          │
│     │ Int64⍰ │ String⍰       │
├─────┼────────┼───────────────┤
│ 1   │ 1      │ Hello world   │
│ 2   │ 2      │ Goodbye world │

v1.0.0

julia> data = DBInterface.execute(db, "select * from d") |> DataFrame
3×2 DataFrame
│ Row │ col1   │ col2          │
│     │ Int64⍰ │ String⍰       │
├─────┼────────┼───────────────┤
│ 1   │ 1      │ Hello world   │
│ 2   │ 2      │ Goodbye world │


问:
How to round a linear-gradient background that is divided horizontally in two?
I have a big section with this background: background: linear-gradient(180deg, #fff 20%, #98DB43 20%); And I am trying to round the top left and right corners of the bottom section (with the #98DB43 colour).

答:
You can consider radial gradient to simulate the rounded corners

.box {
  height:200px;
  width:200px;
  background:
    radial-gradient(farthest-side at bottom right,transparent 100%,#fff 100%)
    left 0 top  calc(20% + 0.2*40px) /* background-position */
    /40px 40px, /* background-size */
    radial-gradient(farthest-side at bottom left ,transparent 100%,#fff 100%)
    right 0 top calc(20% + 0.2*40px) /* background-position */
    /40px 40px, /* background-size */

    linear-gradient(180deg, #fff 20%, #98DB43 20%);
  background-repeat:no-repeat;
  border:1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div></code>```

Use different coloration to better understand the trick:

.box {
  height:200px;
  width:200px;
  background:
    radial-gradient(farthest-side at bottom right,red 100%,blue 100%)
    left 0 top  calc(20% + 0.2*40px)
    /40px 40px,
    radial-gradient(farthest-side at bottom left ,yellow 100%,green 100%)
    right 0 top calc(20% + 0.2*40px)
    /40px 40px,

    linear-gradient(180deg, #fff 20%, #98DB43 20%);
  background-repeat:no-repeat;
  border:1px solid;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div></code>```

Related to understand the logic behind the calculation of the background-position:
Using percentage values with background-position on a linear gradient

You can add CSS variables to have better control:

.box {
  --r:40px; /* control the radius */
  --p:0.2;  /* gradient percentage (from 0 to 1)*/

  height:200px;
  width:200px;
  background:
    radial-gradient(farthest-side at bottom right,transparent 100%,#fff 100%)
    left 0 top  calc(calc(var(--p)*100%) + var(--p)*var(--r)) /* background-position */
    /var(--r) var(--r), /* background-size */
    radial-gradient(farthest-side at bottom left ,transparent 100%,#fff 100%)
    right 0 top calc(calc(var(--p)*100%) + var(--p)*var(--r)) /* background-position */
    /var(--r) var(--r), /* background-size */

    linear-gradient(180deg, #fff calc(var(--p)*100%), #98DB43 calc(var(--p)*100%));
  background-repeat:no-repeat;
  border:1px solid;
  display:inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box"></div>
<div class="box" style="--r:20px;--p:0.3"></div>
<div class="box" style="--r:10px;--p:0.5"></div>
<div class="box" style="--r:50px;--p:0.6"></div></code>```

Body:
You can consider radial gradient to simulate the rounded corners

.box {
  height:200px;
  width:200px;
  background:
    radial-gradient(farthest-side at bottom right,transparent 100%,#fff 100%)
    left 0 top  calc(20% + 0.2*40px) /* background-position */
    /40px 40px, /* background-size */
    radial-gradient(farthest-side at bottom left ,transparent 100%,#fff 100%)
    right 0 top calc(20% + 0.2*40px) /* background-position */
    /40px 40px, /* background-size */

    linear-gradient(180deg, #fff 20%, #98DB43 20%);
  background-repeat:no-repeat;
  border:1px solid;
}

<div class="box"></div>

Use different coloration to better understand the trick:

.box {
  height:200px;
  width:200px;
  background:
    radial-gradient(farthest-side at bottom right,red 100%,blue 100%)
    left 0 top  calc(20% + 0.2*40px)
    /40px 40px,
    radial-gradient(farthest-side at bottom left ,yellow 100%,green 100%)
    right 0 top calc(20% + 0.2*40px)
    /40px 40px,

    linear-gradient(180deg, #fff 20%, #98DB43 20%);
  background-repeat:no-repeat;
  border:1px solid;
}

<div class="box"></div>

Related to understand the logic behind the calculation of the background-position:
Using percentage values with background-position on a linear gradient

You can add CSS variables to have better control:

.box {
  --r:40px; /* control the radius */
  --p:0.2;  /* gradient percentage (from 0 to 1)*/

  height:200px;
  width:200px;
  background:
    radial-gradient(farthest-side at bottom right,transparent 100%,#fff 100%)
    left 0 top  calc(calc(var(--p)*100%) + var(--p)*var(--r)) /* background-position */
    /var(--r) var(--r), /* background-size */
    radial-gradient(farthest-side at bottom left ,transparent 100%,#fff 100%)
    right 0 top calc(calc(var(--p)*100%) + var(--p)*var(--r)) /* background-position */
    /var(--r) var(--r), /* background-size */

    linear-gradient(180deg, #fff calc(var(--p)*100%), #98DB43 calc(var(--p)*100%));
  background-repeat:no-repeat;
  border:1px solid;
  display:inline-block;
}

<div class="box"></div>
<div class="box" style="--r:20px;--p:0.3"></div>
<div class="box" style="--r:10px;--p:0.5"></div>
<div class="box" style="--r:50px;--p:0.6"></div>


问:
Synchronous delay in code execution
I have a code which needs to be executed after some delay say 5000 ms.Currently I am using setTimeout but it is asynchronous and i want the execution to wait for its return. I have tried using the following:

```<code>function pauseComp(ms)
 {
     var curr = new Date().getTime();
     ms += curr;
     while (curr   < ms) {
         curr = new Date().getTime();
     }
 }
</code>```

But the code i want to delay is drawing some objects using raphaeljs and the display is not at all smooth. I am trying to use doTimeout plugin. I need to have a delay only once as the delay and code to be delayed are both in a loop. I have no requirement for a id so I am not using it.
For example:

```<code>for(i; i<5; i++){ $.doTimeout(5000,function(){
         alert('hi');  return false;}, true);}
</code>```

This waits for 5 sec befor giving first Hi and then successive loop iterations show alert immediately after the first. What I want it to do is wait 5 sec give alert again wait and then give alert and so on.

Any hints/ suggestions are appreciated!

答:
Node solution

Use fs.existsSync() to delay

```<code>const fs = require('fs');
const uuidv4 = require('uuid/v4');

/**
 * Tie up execution for at-least the given number of millis.  This is not efficient.
 * @param millis Min number of millis to wait
 */
function sleepSync(millis) {
    if (millis <= 0) return;
    const proceedAt = Date.now() + millis;
    while (Date.now() < proceedAt) fs.existsSync(uuidv4());
}
</code>```

fs.existsSync(uuidv4()) is intended to do a few things:

Occupy the thread by generating a uuid and looking for a non-existent file

New uuid each time defeats the file system cache

Looking for a file is likely an optimised operation that should allow other activity to continue (i.e. not pin the CPU)

ContentLicense: CC BY-SA 3.0

Title: Synchronous delay in code execution

Body:
I have a code which needs to be executed after some delay say 5000 ms.Currently I am using setTimeout but it is asynchronous and i want the execution to wait for its return. I have tried using the following:

function pauseComp(ms)
 {
     var curr = new Date().getTime();
     ms += curr;
     while (curr   < ms) {
         curr = new Date().getTime();
     }
 }

But the code i want to delay is drawing some objects using raphaeljs and the display is not at all smooth. I am trying to use doTimeout plugin. I need to have a delay only once as the delay and code to be delayed are both in a loop. I have no requirement for a id so I am not using it.
For example:

for(i; i<5; i++){ $.doTimeout(5000,function(){
         alert('hi');  return false;}, true);}

This waits for 5 sec befor giving first Hi and then successive loop iterations show alert immediately after the first. What I want it to do is wait 5 sec give alert again wait and then give alert and so on.

Any hints/ suggestions are appreciated!

Body:
Node solution

Use fs.existsSync() to delay

const fs = require('fs');
const uuidv4 = require('uuid/v4');

/**
 * Tie up execution for at-least the given number of millis.  This is not efficient.
 * @param millis Min number of millis to wait
 */
function sleepSync(millis) {
    if (millis <= 0) return;
    const proceedAt = Date.now() + millis;
    while (Date.now() < proceedAt) fs.existsSync(uuidv4());
}

fs.existsSync(uuidv4()) is intended to do a few things:

Occupy the thread by generating a uuid and looking for a non-existent file

New uuid each time defeats the file system cache

Looking for a file is likely an optimised operation that should allow other activity to continue (i.e. not pin the CPU)


问:
Convert Minutes to HH:MM:SS - Swift
I have some text fields in an array. HH:MM:SS. I'm having two issues, one is when one of the fields is left blank, the app crashes and I want it to just read as "0" if blank. Second, I use below to convert HH:MM:SS to Minutes. I do 0:18:30 and the math below to decimal comes out to 18.5

Now how would I convert this back to HH:MM:SS? array[0] is hours, array[1] is minutes, array[2] is seconds.

```<code>stepOne = (Float(array[0])! * 60) + Float(array[1])! + (Float(array[2])! / 60)
</code>```

答:
What you need is to calculate the number of seconds instead of number of minutes. Using the reduce method just multiply the first element by 3600 and then divide the multiplier by 60 after each iteration. Next you can use DateComponentsFormatter to display the resulting seconds time interval using .positional units style to the user:

```<code>let array = [0,18,30]
var n = 3600
let seconds = array.reduce(0) {
    defer { n /= 60 }
    return $0 + $1 * n
}
</code>```

```<code>let dcf = DateComponentsFormatter()
dcf.allowedUnits = [.hour, .minute, .second]
dcf.unitsStyle = .positional
dcf.zeroFormattingBehavior = .pad
let string = dcf.string(from: TimeInterval(seconds))  // "00:18:30"
</code>```

Title: Convert Minutes to HH:MM:SS - Swift

Body:
I have some text fields in an array. HH:MM:SS. I'm having two issues, one is when one of the fields is left blank, the app crashes and I want it to just read as "0" if blank. Second, I use below to convert HH:MM:SS to Minutes. I do 0:18:30 and the math below to decimal comes out to 18.5

Now how would I convert this back to HH:MM:SS? array[0] is hours, array[1] is minutes, array[2] is seconds.

stepOne = (Float(array[0])! * 60) + Float(array[1])! + (Float(array[2])! / 60)

Body:
What you need is to calculate the number of seconds instead of number of minutes. Using the reduce method just multiply the first element by 3600 and then divide the multiplier by 60 after each iteration. Next you can use DateComponentsFormatter to display the resulting seconds time interval using .positional units style to the user:

let array = [0,18,30]
var n = 3600
let seconds = array.reduce(0) {
    defer { n /= 60 }
    return $0 + $1 * n
}

let dcf = DateComponentsFormatter()
dcf.allowedUnits = [.hour, .minute, .second]
dcf.unitsStyle = .positional
dcf.zeroFormattingBehavior = .pad
let string = dcf.string(from: TimeInterval(seconds))  // "00:18:30"


问:
Find the cycle time of a ticket number for different intervals
```<code>TicketNo    ActionDate                  OldStatus    NewStatus      CycleTime/Sec
1001        2014-02-14 10:17:05.000     Assigned     InProgress     -
1001        2014-03-05 02:03:44.000     InProgress   Reply          1611999
1001        2014-03-11 10:00:14.000     Reply        Resolved       546990
1002        2015-03-20 04:44:14.000     InProgress   Reply          -
1002        2015-03-21 05:40:02.000     Reply        Resolved       89748
</code>```

I have to calculate cycle time for every change in status of the ticket.

In the example above, i am trying to calculate the seconds from action date when the ticket is routed from old status to new status.

I tried using ranking function but did not get the output in wanted.

select
*
,row_number() over (partition by a.ticketno, a.oldstatus  order by a. actiondate ) rn

from Ticketing a

I would really appreciate if anyone can suggest some ideas how to solve this calculation.

答:
I took Sean's excellent solution and tweaked it to avoid a sort. I'm using a temp table so that I can exclude the temp variable creation/population from the execution plan I'm about to post.

```<code>-- Temp table with sample data
IF OBJECT_ID('tempdb..#Something') IS NOT NULL DROP TABLE #Something;
CREATE TABLE #Something
(    TicketNo INT
    , ActionDate DATETIME
    , OldStatus  VARCHAR(50)
    , NewStatus  VARCHAR(50)
);
INSERT #Something VALUES
  (1001, '2014-02-14 10:17:05.000', 'Assigned', 'InProgress')
, (1001, '2014-03-05 02:03:44.000', 'InProgress', 'Reply')
, (1001, '2014-03-11 10:00:14.000', 'Reply', 'Resolved')
, (1002, '2015-03-20 04:44:14.000', 'InProgress', 'Reply')
, (1002, '2015-03-21 05:40:02.000', 'Reply', 'Resolved')

-- TOP (1) Solution
SELECT s.TicketNo, s.ActionDate, s.OldStatus, s.NewStatus,
       CycleTimeSeconds = DATEDIFF(SECOND, MyLag.ActionDate, s.ActionDate)
FROM   #Something AS s
OUTER APPLY
(
    SELECT TOP (1) ActionDate
    FROM     #Something s2
    WHERE    s2.TicketNo   = s.TicketNo
    AND      s2.ActionDate < s.ActionDate
    ORDER BY s2.ActionDate DESC
) AS MyLag;

-- Using MAX instead of TOP (1) to avoid a DESC sort operation
SELECT s.TicketNo, s.ActionDate, s.OldStatus, s.NewStatus,
       CycleTimeSeconds = DATEDIFF(SECOND, MyLag.ActionDate, s.ActionDate)
FROM #Something AS s
CROSS APPLY
(
    SELECT ActionDate = MAX(ActionDate)
    FROM   #Something s2
    WHERE  s2.TicketNo   = s.TicketNo
    AND    s2.ActionDate < s.ActionDate
) AS MyLag;
</code>```

Since the subquery is only evaluating one column we can leverage an Aggregate function without a GROUP BY. Because I'm using an Aggregate (MAX) I'll always get a row back which is why I changed the OUTER APPLY to CROSS APPLY. Nothing wrong with OUTER APPLY but changing it removes scalar operator from this execution plan - no performance gain, just a cleaner execution plan.

There is a very big additional benefit to this approach: It's not only avoiding a sort, we're avoiding a DESCending sort. If there were an index on ActionDate the optimizer could leverage it to avoid a DESCending sort by performing a *ordered-backward scan. Adding a UNIQUE constraint on ActionDate to the original temp variable (something I don't suggest but it works for this example) run a TOP (1) query sorted by ActionDate DESC.

```<code>declare @Something table
(
    TicketNo int
    , ActionDate datetime UNIQUE
    , OldStatus varchar(50)
    , NewStatus varchar(50)
)

insert @Something values
  (1001, '2014-02-14 10:17:05.000', 'Assigned', 'InProgress')
, (1001, '2014-03-05 02:03:44.000', 'InProgress', 'Reply')
, (1001, '2014-03-11 10:00:14.000', 'Reply', 'Resolved')
, (1002, '2015-03-20 04:44:14.000', 'InProgress', 'Reply')
, (1002, '2015-03-21 05:40:02.000', 'Reply', 'Resolved')

SELECT TOP (1) ActionDate
FROM     @Something AS s2
ORDER BY s2.ActionDate DESC;
</code>```

Note the backward scan:

Backward scans kill parallelism. Itzik Ben-Gan discusses that here: Avoiding a Sort with Descending Order.

One difference between ordered-forward and ordered-backward scans is
  that the former can potentially use parallelism, whereas the latter
  doesn’t currently have an implementation with parallelism in the
  storage engine

Here APPLY is allowing us a sort-free operation with parallel processing in the optimizer's back pocket if needed. Just more evidence that APPLY is awesome... not that any further evidence was needed ;)

Body:
TicketNo    ActionDate                  OldStatus    NewStatus      CycleTime/Sec
1001        2014-02-14 10:17:05.000     Assigned     InProgress     -
1001        2014-03-05 02:03:44.000     InProgress   Reply          1611999
1001        2014-03-11 10:00:14.000     Reply        Resolved       546990
1002        2015-03-20 04:44:14.000     InProgress   Reply          -
1002        2015-03-21 05:40:02.000     Reply        Resolved       89748

I have to calculate cycle time for every change in status of the ticket.

In the example above, i am trying to calculate the seconds from action date when the ticket is routed from old status to new status.

I tried using ranking function but did not get the output in wanted.

select
*
,row_number() over (partition by a.ticketno, a.oldstatus  order by a. actiondate ) rn

from Ticketing a

I would really appreciate if anyone can suggest some ideas how to solve this calculation.

Body:
I took Sean's excellent solution and tweaked it to avoid a sort. I'm using a temp table so that I can exclude the temp variable creation/population from the execution plan I'm about to post.

-- Temp table with sample data
IF OBJECT_ID('tempdb..#Something') IS NOT NULL DROP TABLE #Something;
CREATE TABLE #Something
(    TicketNo INT
    , ActionDate DATETIME
    , OldStatus  VARCHAR(50)
    , NewStatus  VARCHAR(50)
);
INSERT #Something VALUES
  (1001, '2014-02-14 10:17:05.000', 'Assigned', 'InProgress')
, (1001, '2014-03-05 02:03:44.000', 'InProgress', 'Reply')
, (1001, '2014-03-11 10:00:14.000', 'Reply', 'Resolved')
, (1002, '2015-03-20 04:44:14.000', 'InProgress', 'Reply')
, (1002, '2015-03-21 05:40:02.000', 'Reply', 'Resolved')

-- TOP (1) Solution
SELECT s.TicketNo, s.ActionDate, s.OldStatus, s.NewStatus,
       CycleTimeSeconds = DATEDIFF(SECOND, MyLag.ActionDate, s.ActionDate)
FROM   #Something AS s
OUTER APPLY
(
    SELECT TOP (1) ActionDate
    FROM     #Something s2
    WHERE    s2.TicketNo   = s.TicketNo
    AND      s2.ActionDate < s.ActionDate
    ORDER BY s2.ActionDate DESC
) AS MyLag;

-- Using MAX instead of TOP (1) to avoid a DESC sort operation
SELECT s.TicketNo, s.ActionDate, s.OldStatus, s.NewStatus,
       CycleTimeSeconds = DATEDIFF(SECOND, MyLag.ActionDate, s.ActionDate)
FROM #Something AS s
CROSS APPLY
(
    SELECT ActionDate = MAX(ActionDate)
    FROM   #Something s2
    WHERE  s2.TicketNo   = s.TicketNo
    AND    s2.ActionDate < s.ActionDate
) AS MyLag;

Since the subquery is only evaluating one column we can leverage an Aggregate function without a GROUP BY. Because I'm using an Aggregate (MAX) I'll always get a row back which is why I changed the OUTER APPLY to CROSS APPLY. Nothing wrong with OUTER APPLY but changing it removes scalar operator from this execution plan - no performance gain, just a cleaner execution plan.

There is a very big additional benefit to this approach: It's not only avoiding a sort, we're avoiding a DESCending sort. If there were an index on ActionDate the optimizer could leverage it to avoid a DESCending sort by performing a *ordered-backward scan. Adding a UNIQUE constraint on ActionDate to the original temp variable (something I don't suggest but it works for this example) run a TOP (1) query sorted by ActionDate DESC.

declare @Something table
(
    TicketNo int
    , ActionDate datetime UNIQUE
    , OldStatus varchar(50)
    , NewStatus varchar(50)
)

insert @Something values
  (1001, '2014-02-14 10:17:05.000', 'Assigned', 'InProgress')
, (1001, '2014-03-05 02:03:44.000', 'InProgress', 'Reply')
, (1001, '2014-03-11 10:00:14.000', 'Reply', 'Resolved')
, (1002, '2015-03-20 04:44:14.000', 'InProgress', 'Reply')
, (1002, '2015-03-21 05:40:02.000', 'Reply', 'Resolved')

SELECT TOP (1) ActionDate
FROM     @Something AS s2
ORDER BY s2.ActionDate DESC;

Note the backward scan:

Backward scans kill parallelism. Itzik Ben-Gan discusses that here: Avoiding a Sort with Descending Order.

One difference between ordered-forward and ordered-backward scans is
  that the former can potentially use parallelism, whereas the latter
  doesn’t currently have an implementation with parallelism in the
  storage engine

Here APPLY is allowing us a sort-free operation with parallel processing in the optimizer's back pocket if needed. Just more evidence that APPLY is awesome... not that any further evidence was needed ;)


问:
Can I setup multi port from one web app with Go?
As I know, I can run simple web server with Golang just use http package, like

```<code>http.ListenAndServe(PORT, nil)
</code>```

where PORT is TCP address to listen.

Can I use PORT as PORTS, for example http.ListenAndServe(":80, :8080", nil) from one application?

Possible my question is stupid, but "Who don't ask, He will not get answer!"

答:
Here is a simple working Example:</p>

```<code>package main

import (
    "fmt"
    "net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "hello")
}

func world(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "world")
}

func main() {
    serverMuxA := http.NewServeMux()
    serverMuxA.HandleFunc("/hello", hello)

    serverMuxB := http.NewServeMux()
    serverMuxB.HandleFunc("/world", world)

    go func() {
        http.ListenAndServe("localhost:8081", serverMuxA)
    }()

    http.ListenAndServe("localhost:8082", serverMuxB)
}
</code>```

Body:
As I know, I can run simple web server with Golang just use http package, like

http.ListenAndServe(PORT, nil)

where PORT is TCP address to listen.

Can I use PORT as PORTS, for example http.ListenAndServe(":80, :8080", nil) from one application?

Possible my question is stupid, but "Who don't ask, He will not get answer!"

Body:
Here is a simple working Example:

package main

import (
    "fmt"
    "net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "hello")
}

func world(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "world")
}

func main() {
    serverMuxA := http.NewServeMux()
    serverMuxA.HandleFunc("/hello", hello)

    serverMuxB := http.NewServeMux()
    serverMuxB.HandleFunc("/world", world)

    go func() {
        http.ListenAndServe("localhost:8081", serverMuxA)
    }()

    http.ListenAndServe("localhost:8082", serverMuxB)
}


问:
Android Studio waiting for build to finish
I have a problem. When I start a new project in Android Studio and select a navigation drawer activity it happens. I don't have access to my activiy_main_drawer.xml on "Design" and it keeps saying "Waiting for build to finish.". I really don't know what I have to do. I tried to uninstall and reinstall Android Studio, and it didn't help.

答:
I've also faced this problem. The above solution wasn't worked for me.
I just restarted my Android Studio by closing the Android Studio application and opening it again from Start Menu. It works for me. Try this solution if the above not working. Hope this will helpful for you.


问:
Find count of each consecutive characters
Need to find the count of each consecutive characters in a row.
Ex: aaaabbccaa
output: 4a2b2c2a

Character may repeat but need to count only consecutive ones. I also need to maintain original sequence.

I tried following but it groups all characters so was not useful.

```<code>str.GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).ToList().ForEach(x => str+= x.Count + "" + x.Key)
</code>```

答:
This small program will do the trick, but it's not a single line nice linq statement. Just my two cents.</p>

```<code>using System;
using System.Linq;
using System.Collections.Generic;

public class Simple {

  public static void Main() {

var text = "aaaabbccaa"; //output: 4a3b2c2a
var lista = new List<string>();
var previousLetter = text.Substring(1,1);
var item = string.Empty;
foreach (char letter in text)
{
    if (previousLetter == letter.ToString()){
        item += letter.ToString();
    }
    else
    {
        lista.Add(item);
        item = letter.ToString();
    }
    previousLetter = letter.ToString();
}
lista.Add(item);
foreach (var i in lista)
     Console.WriteLine(i.Substring(1,1) + i.Select(y => y).ToList().Count().ToString());
  }
}
</code>```

Body:
Need to find the count of each consecutive characters in a row.
Ex: aaaabbccaa
output: 4a2b2c2a

Character may repeat but need to count only consecutive ones. I also need to maintain original sequence.

I tried following but it groups all characters so was not useful.

str.GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).ToList().ForEach(x => str+= x.Count + "" + x.Key)

Body:
This small program will do the trick, but it's not a single line nice linq statement. Just my two cents.

using System;
using System.Linq;
using System.Collections.Generic;

public class Simple {

  public static void Main() {

var text = "aaaabbccaa"; //output: 4a3b2c2a
var lista = new List<string>();
var previousLetter = text.Substring(1,1);
var item = string.Empty;
foreach (char letter in text)
{
    if (previousLetter == letter.ToString()){
        item += letter.ToString();
    }
    else
    {
        lista.Add(item);
        item = letter.ToString();
    }
    previousLetter = letter.ToString();
}
lista.Add(item);
foreach (var i in lista)
     Console.WriteLine(i.Substring(1,1) + i.Select(y => y).ToList().Count().ToString());
  }
}


问:
Error: Invariant failed: You should not use <Link> outside a <Router> (storybookjs)
It somehow works on normal react-scripts start. but when trying to view individual components via storybook it throws an error like a said on the title above.

here's my code.

index.tsx

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
</code>```

App.tsx

```<code>import React from 'react';
import { BrowserRouter, Route, Switch, Link } from "react-router-dom";
import { Register } from './pages/register/register'
import { Login } from './pages/login/login'
import { Home } from './pages/home/home'

const App: React.FC = () => {
  return (
    <div id="app-root">
      <BrowserRouter>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/register" exact component={Register} />
          <Route path="/login" exact component={Login} />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;
</code>```

login.tsx

```<code>export const Login = () => {
   return (
        <div className={styles.loginPage}>
            <div className={styles.body}>
                <div>
                    <Link to="/" className={styles.link}>
                        <img src={arrowImage} className={styles.arrowImage} alt="arrowImage" />
                    </Link>
                </div>
            </div>
        </div>
   )
};
</code>```

the other 2 components which is Home and Register practically has the same code with the login.tsx just different names. For some reason it works on the normal browser, but when I run storybook with the components it shows the error. I'm confused Im not sure what I've missed, as it is working on the normal browser without storybook.

storybook screenshot: https://user-images.githubusercontent.com/24859633/69216293-d38e0c80-0ba6-11ea-8434-201041f30af7.png

答:
Looks like a suggestion here from 'afholderman':
https://github.com/storybookjs/storybook/issues/8892#issuecomment-580842862</p>

```<code>import {MemoryRouter} from 'react-router-dom';
...
<MemoryRouter>
    <Link to="/" className={styles.link}>
        <img src={arrowImage} className={styles.arrowImage} alt="arrowImage" />
    </Link>
</MemoryRouter>
....
</code>```

Body:
It somehow works on normal react-scripts start. but when trying to view individual components via storybook it throws an error like a said on the title above.

here's my code.

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

App.tsx

import React from 'react';
import { BrowserRouter, Route, Switch, Link } from "react-router-dom";
import { Register } from './pages/register/register'
import { Login } from './pages/login/login'
import { Home } from './pages/home/home'

const App: React.FC = () => {
  return (

      <BrowserRouter>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/register" exact component={Register} />
          <Route path="/login" exact component={Login} />
        </Switch>
      </BrowserRouter>

  );
}

export default App;

login.tsx

export const Login = () => {
   return (

                    <Link to="/" className={styles.link}>

                    </Link>

   )
};

the other 2 components which is Home and Register practically has the same code with the login.tsx just different names. For some reason it works on the normal browser, but when I run storybook with the components it shows the error. I'm confused Im not sure what I've missed, as it is working on the normal browser without storybook.

storybook screenshot: https://user-images.githubusercontent.com/24859633/69216293-d38e0c80-0ba6-11ea-8434-201041f30af7.png

Body:
Looks like a suggestion here from 'afholderman':
https://github.com/storybookjs/storybook/issues/8892#issuecomment-580842862

import {MemoryRouter} from 'react-router-dom';
...
<MemoryRouter>
    <Link to="/" className={styles.link}>
        <img src={arrowImage} className={styles.arrowImage} alt="arrowImage" />
    </Link>
</MemoryRouter>
....


问:
Search index with python without a loop
I have a list in python, for example A = [-22,-10,0,3,8] and I want to find A[x]=x, that means that the index and number in the list have the same value. In this case x=3 because A[3]=3.

Can I find x without a loop?

EDIT: It's a academic problem and I have a clue "You don't need to visit each position in the array" and the numbers will be ordered and unique

答: Given that the list elements are integers, in order and distinct, the problem can be solved by binary search. This is because the sequence a[i] - i is non-decreasing. A binary search does not visit "each" position in the array; only O(log n) of them.

Title: Search index with python without a loop


问:
How to properly resolve query MySql using sequelize and Graphql
I am learning GraphQL and trying to get data from MySql tables via sequelize in the resolve function on GraphQL. I have a Clients table associated with a Pets Table, where Pets belong to Client.
Here is my code:

```<code>const PetsType = new GraphQLObjectType({
    name: "Pet",
    fields: () => ({
        id: { type: GraphQLString },
        name: { type: GraphQLString },
        breed: { type: GraphQLString },
        type: { type: GraphQLString },
        ClientId: { type: GraphQLString },
        Comments: {
            type: CommentsType,
            resolve(parentValue, args) {
                return db.Comments;
            }
        }
    })
});

const ClientType = new GraphQLObjectType({
    name: "Client",
    fields: () => ({
        id: { type: GraphQLString },
        lastName: { type: GraphQLString },
        firstName: { type: GraphQLString },
        primaryPhoneNumber: { type: GraphQLString },
        cellphone: { type: GraphQLString },
        workPhone: { type: GraphQLString },
        email: { type: GraphQLString },
        Pets: {
            type: PetsType,
            resolve(parentValue, args) {
                return db.Pet.findOne({
                    where: { ClientId: parentValue.id }
                });
            }
        }
    })
});
</code>```

Using findOne works for clients with only one pet or only returns the first pet of a client who owns more than one. However, some clients have more than one pet, so findOne() doesn't really solve my problem.
I've tried:

```<code>return db.Pet.findAll({
                        where: { ClientId: parentValue.id }
                    });
</code>```

But it returns the client with the fields on Pets null.

Here are my Sequelize models for both, Clients and Pets:
Clients:

```<code>module.exports = function(sequelize, DataTypes) {
    var Client = sequelize.define(
        "Client",
        {
            lastName: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            firstName: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            primaryPhoneNumber: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            cellphone: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            workPhone: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            email: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            }
        },

        {
            timestamps: false
        }
    );

    Client.associate = function(models) {
        // Associating Clients with Pets
        // When a Client is deleted, also delete any associated Pets
        Client.belongsTo(models.User);
        Client.hasMany(models.Pet, {
            onDelete: "cascade"
        });
    };

    return Client;
};
</code>```

Pets:

```<code>module.exports = function(sequelize, DataTypes) {
    var Pet = sequelize.define(
        "Pet",
        {
            name: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            breed: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            type: {
                type: DataTypes.TEXT,
                allowNull: true
            }
        },
        {
            timestamps: false
        }
    );

    Pet.associate = function(models) {
        Pet.belongsTo(models.Client);
        Pet.hasMany(models.Comment, {
            onDelete: "cascade"
        });
    };

    return Pet;
};
</code>```

How can I retreive all Pets that belong to this client?
Thanks in advance.

答: As Daniel Rearden suggested, I changed it to: type: new GraphQLList(PetsType) to return a list of objects</p>

Body:
I am learning GraphQL and trying to get data from MySql tables via sequelize in the resolve function on GraphQL. I have a Clients table associated with a Pets Table, where Pets belong to Client.
Here is my code:

const PetsType = new GraphQLObjectType({
    name: "Pet",
    fields: () => ({
        id: { type: GraphQLString },
        name: { type: GraphQLString },
        breed: { type: GraphQLString },
        type: { type: GraphQLString },
        ClientId: { type: GraphQLString },
        Comments: {
            type: CommentsType,
            resolve(parentValue, args) {
                return db.Comments;
            }
        }
    })
});

const ClientType = new GraphQLObjectType({
    name: "Client",
    fields: () => ({
        id: { type: GraphQLString },
        lastName: { type: GraphQLString },
        firstName: { type: GraphQLString },
        primaryPhoneNumber: { type: GraphQLString },
        cellphone: { type: GraphQLString },
        workPhone: { type: GraphQLString },
        email: { type: GraphQLString },
        Pets: {
            type: PetsType,
            resolve(parentValue, args) {
                return db.Pet.findOne({
                    where: { ClientId: parentValue.id }
                });
            }
        }
    })
});

Using findOne works for clients with only one pet or only returns the first pet of a client who owns more than one. However, some clients have more than one pet, so findOne() doesn't really solve my problem.
I've tried:

return db.Pet.findAll({
                        where: { ClientId: parentValue.id }
                    });

But it returns the client with the fields on Pets null.

Here are my Sequelize models for both, Clients and Pets:
Clients:

module.exports = function(sequelize, DataTypes) {
    var Client = sequelize.define(
        "Client",
        {
            lastName: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            firstName: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            primaryPhoneNumber: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            cellphone: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            workPhone: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            },
            email: {
                type: DataTypes.TEXT,
                allowNull: true,
                len: [1]
            }
        },

        {
            timestamps: false
        }
    );

    Client.associate = function(models) {
        // Associating Clients with Pets
        // When a Client is deleted, also delete any associated Pets
        Client.belongsTo(models.User);
        Client.hasMany(models.Pet, {
            onDelete: "cascade"
        });
    };

    return Client;
};

Pets:

module.exports = function(sequelize, DataTypes) {
    var Pet = sequelize.define(
        "Pet",
        {
            name: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            breed: {
                type: DataTypes.TEXT,
                allowNull: false,
                len: [1]
            },
            type: {
                type: DataTypes.TEXT,
                allowNull: true
            }
        },
        {
            timestamps: false
        }
    );

    Pet.associate = function(models) {
        Pet.belongsTo(models.Client);
        Pet.hasMany(models.Comment, {
            onDelete: "cascade"
        });
    };

    return Pet;
};

How can I retreive all Pets that belong to this client?
Thanks in advance.


问:
Cannot deploy trained model to Google Cloud Ai-Platform with custom prediction routine: Model requires more memory than allowed
I am trying to deploy a pretrained pytorch model to AI Platform with a custom prediction routine. After following the instructions described here the deployment fails with the following error:

```<code>ERROR: (gcloud.beta.ai-platform.versions.create) Create Version failed. Bad model detected with error: Model requires more memory than allowed. Please try to decrease the model size and re-deploy. If you continue to have error, please contact Cloud ML.
</code>```

The contents of the model folder are 83.89 MB large and are below the 250 MB limit that's described in the documentation. The only files in the folder are the checkpoint file (.pth) for the model and the tarball required for the custom prediction routine.

Command to create the model:

```<code>gcloud beta ai-platform versions create pose_pytorch --model pose --runtime-version 1.15 --python-version 3.5 --origin gs://rcg-models/pytorch_pose_estimation --package-uris gs://rcg-models/pytorch_pose_estimation/my_custom_code-0.1.tar.gz --prediction-class predictor.MyPredictor
</code>```

Changing the runtime version to 1.14 leads to the same error.
I have tried changing the --machine-type argument to mls1-c4-m2 like Parth suggested but I still get the same error.

The setup.py file that generates my_custom_code-0.1.tar.gz looks like this:

```<code>setup(
    name='my_custom_code',
    version='0.1',
    scripts=['predictor.py'],
    install_requires=["opencv-python", "torch"]
)
</code>```

Relevant code snippet from the predictor:

```<code>    def __init__(self, model):
        """Stores artifacts for prediction. Only initialized via `from_path`.
        """
        self._model = model
        self._client = storage.Client()

    @classmethod
    def from_path(cls, model_dir):
        """Creates an instance of MyPredictor using the given path.

        This loads artifacts that have been copied from your model directory in
        Cloud Storage. MyPredictor uses them during prediction.

        Args:
            model_dir: The local directory that contains the trained Keras
                model and the pickled preprocessor instance. These are copied
                from the Cloud Storage model directory you provide when you
                deploy a version resource.

        Returns:
            An instance of `MyPredictor`.
        """

        net = PoseEstimationWithMobileNet()
        checkpoint_path = os.path.join(model_dir, "checkpoint_iter_370000.pth")
        checkpoint = torch.load(checkpoint_path, map_location='cpu')
        load_state(net, checkpoint)

        return cls(net)
</code>```

Additionally I have enabled logging for the model in AI Platform and I get the following outputs:

```<code>2019-12-17T09:28:06.208537Z OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k
2019-12-17T09:28:13.474653Z WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/google/cloud/ml/prediction/frameworks/tf_prediction_lib.py:48: The name tf.saved_model.tag_constants.SERVING is deprecated. Please use tf.saved_model.SERVING instead.
2019-12-17T09:28:13.474680Z {"textPayload":"","insertId":"5df89fad00073e383ced472a","resource":{"type":"cloudml_model_version","labels":{"project_id":"rcg-shopper","region":"","version_id":"lightweight_pose_pytorch","model_id":"pose"}},"timestamp":"2019-12-17T09:28:13.474680Z","logName":"projects/rcg-shopper/logs/ml.googleapis…
2019-12-17T09:28:13.474807Z WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/google/cloud/ml/prediction/frameworks/tf_prediction_lib.py:50: The name tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY is deprecated. Please use tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY instead.
2019-12-17T09:28:13.474829Z {"textPayload":"","insertId":"5df89fad00073ecd4836d6aa","resource":{"type":"cloudml_model_version","labels":{"project_id":"rcg-shopper","region":"","version_id":"lightweight_pose_pytorch","model_id":"pose"}},"timestamp":"2019-12-17T09:28:13.474829Z","logName":"projects/rcg-shopper/logs/ml.googleapis…
2019-12-17T09:28:13.474918Z WARNING:tensorflow:
2019-12-17T09:28:13.474927Z The TensorFlow contrib module will not be included in TensorFlow 2.0.
2019-12-17T09:28:13.474934Z For more information, please see:
2019-12-17T09:28:13.474941Z   * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md
2019-12-17T09:28:13.474951Z   * https://github.com/tensorflow/addons
2019-12-17T09:28:13.474958Z   * https://github.com/tensorflow/io (for I/O related ops)
2019-12-17T09:28:13.474964Z If you depend on functionality not listed there, please file an issue.
2019-12-17T09:28:13.474999Z {"textPayload":"","insertId":"5df89fad00073f778735d7c3","resource":{"type":"cloudml_model_version","labels":{"version_id":"lightweight_pose_pytorch","model_id":"pose","project_id":"rcg-shopper","region":""}},"timestamp":"2019-12-17T09:28:13.474999Z","logName":"projects/rcg-shopper/logs/ml.googleapis…
2019-12-17T09:28:15.283483Z ERROR:root:Failed to import GA GRPC module. This is OK if the runtime version is 1.x
2019-12-17T09:28:16.890923Z Copying gs://cml-489210249453-1560169483791188/models/pose/lightweight_pose_pytorch/15316451609316207868/user_code/my_custom_code-0.1.tar.gz...
2019-12-17T09:28:16.891150Z / [0 files][    0.0 B/  8.4 KiB]
2019-12-17T09:28:17.007684Z / [1 files][  8.4 KiB/  8.4 KiB]
2019-12-17T09:28:17.009154Z Operation completed over 1 objects/8.4 KiB.
2019-12-17T09:28:18.953923Z Processing /tmp/custom_code/my_custom_code-0.1.tar.gz
2019-12-17T09:28:19.808897Z Collecting opencv-python
2019-12-17T09:28:19.868579Z   Downloading https://files.pythonhosted.org/packages/d8/38/60de02a4c9013b14478a3f681a62e003c7489d207160a4d7df8705a682e7/opencv_python-4.1.2.30-cp37-cp37m-manylinux1_x86_64.whl (28.3MB)
2019-12-17T09:28:21.537989Z Collecting torch
2019-12-17T09:28:21.552871Z   Downloading https://files.pythonhosted.org/packages/f9/34/2107f342d4493b7107a600ee16005b2870b5a0a5a165bdf5c5e7168a16a6/torch-1.3.1-cp37-cp37m-manylinux1_x86_64.whl (734.6MB)
2019-12-17T09:28:52.401619Z Collecting numpy>=1.14.5
2019-12-17T09:28:52.412714Z   Downloading https://files.pythonhosted.org/packages/9b/af/4fc72f9d38e43b092e91e5b8cb9956d25b2e3ff8c75aed95df5569e4734e/numpy-1.17.4-cp37-cp37m-manylinux1_x86_64.whl (20.0MB)
2019-12-17T09:28:53.550662Z Building wheels for collected packages: my-custom-code
2019-12-17T09:28:53.550689Z   Building wheel for my-custom-code (setup.py): started
2019-12-17T09:28:54.212558Z   Building wheel for my-custom-code (setup.py): finished with status 'done'
2019-12-17T09:28:54.215365Z   Created wheel for my-custom-code: filename=my_custom_code-0.1-cp37-none-any.whl size=7791 sha256=fd9ecd472a6a24335fd24abe930a4e7d909e04bdc4cf770989143d92e7023f77
2019-12-17T09:28:54.215482Z   Stored in directory: /tmp/pip-ephem-wheel-cache-i7sb0bmb/wheels/0d/6e/ba/bbee16521304fc5b017fa014665b9cae28da7943275a3e4b89
2019-12-17T09:28:54.222017Z Successfully built my-custom-code
2019-12-17T09:28:54.650218Z Installing collected packages: numpy, opencv-python, torch, my-custom-code

</code>```

答:
After hours of good old trial errors, I came to the same conclusion as @kyamagu, "install_requires try to fetch PyPI hosted torch package which is a huge GPU built wheel and that is exceeding the deployment quota."

However, his solution did not work for me. So after many more hours of trial errors (thanks to lacking documentation and wrong ones) I came up with this solution:

We need to get the cpu-built wheels of the Pytorch which is around 100 MBs rather than the 700 MBs GPU-builts that are the default PyPI hosted. you can find them here: https://download.pytorch.org/whl/cpu/torch_stable.html

Next, we need to place them in our gs storage and then give the path as part of the --package-uris like this:

```<code>gcloud beta ai-platform versions create v17 \
    --model=newest \
    --origin=gs://bucket \
    --runtime-version=1.15 \
    --python-version=3.7 \
    --package-uris=gs://bucket/predictor-0.1.tar.gz,gs://bucket/torch-1.3.0+cpu-cp37-cp37m-linux_x86_64.whl \
    --prediction-class=predictor.MyPredictor \
    --machine-type=mls1-c4-m4
</code>```

Also, watch out for the order of the package-uris, the predictor package should be first and there should not be any space after commas.

Hope this helps. cheers!

Body:
I am trying to deploy a pretrained pytorch model to AI Platform with a custom prediction routine. After following the instructions described here the deployment fails with the following error:

ERROR: (gcloud.beta.ai-platform.versions.create) Create Version failed. Bad model detected with error: Model requires more memory than allowed. Please try to decrease the model size and re-deploy. If you continue to have error, please contact Cloud ML.

The contents of the model folder are 83.89 MB large and are below the 250 MB limit that's described in the documentation. The only files in the folder are the checkpoint file (.pth) for the model and the tarball required for the custom prediction routine.

Command to create the model:

gcloud beta ai-platform versions create pose_pytorch --model pose --runtime-version 1.15 --python-version 3.5 --origin gs://rcg-models/pytorch_pose_estimation --package-uris gs://rcg-models/pytorch_pose_estimation/my_custom_code-0.1.tar.gz --prediction-class predictor.MyPredictor

Changing the runtime version to 1.14 leads to the same error.
I have tried changing the --machine-type argument to mls1-c4-m2 like Parth suggested but I still get the same error.

The setup.py file that generates my_custom_code-0.1.tar.gz looks like this:

setup(
    name='my_custom_code',
    version='0.1',
    scripts=['predictor.py'],
    install_requires=["opencv-python", "torch"]
)

Relevant code snippet from the predictor:

    def __init__(self, model):
        """Stores artifacts for prediction. Only initialized via `from_path`.
        """
        self._model = model
        self._client = storage.Client()

    @classmethod
    def from_path(cls, model_dir):
        """Creates an instance of MyPredictor using the given path.

        This loads artifacts that have been copied from your model directory in
        Cloud Storage. MyPredictor uses them during prediction.

        Args:
            model_dir: The local directory that contains the trained Keras
                model and the pickled preprocessor instance. These are copied
                from the Cloud Storage model directory you provide when you
                deploy a version resource.

        Returns:
            An instance of `MyPredictor`.
        """

        net = PoseEstimationWithMobileNet()
        checkpoint_path = os.path.join(model_dir, "checkpoint_iter_370000.pth")
        checkpoint = torch.load(checkpoint_path, map_location='cpu')
        load_state(net, checkpoint)

        return cls(net)

Additionally I have enabled logging for the model in AI Platform and I get the following outputs:

2019-12-17T09:28:06.208537Z OpenBLAS WARNING - could not determine the L2 cache size on this system, assuming 256k
2019-12-17T09:28:13.474653Z WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/google/cloud/ml/prediction/frameworks/tf_prediction_lib.py:48: The name tf.saved_model.tag_constants.SERVING is deprecated. Please use tf.saved_model.SERVING instead.
2019-12-17T09:28:13.474680Z {"textPayload":"","insertId":"5df89fad00073e383ced472a","resource":{"type":"cloudml_model_version","labels":{"project_id":"rcg-shopper","region":"","version_id":"lightweight_pose_pytorch","model_id":"pose"}},"timestamp":"2019-12-17T09:28:13.474680Z","logName":"projects/rcg-shopper/logs/ml.googleapis…
2019-12-17T09:28:13.474807Z WARNING:tensorflow:From /usr/local/lib/python3.7/dist-packages/google/cloud/ml/prediction/frameworks/tf_prediction_lib.py:50: The name tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY is deprecated. Please use tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY instead.
2019-12-17T09:28:13.474829Z {"textPayload":"","insertId":"5df89fad00073ecd4836d6aa","resource":{"type":"cloudml_model_version","labels":{"project_id":"rcg-shopper","region":"","version_id":"lightweight_pose_pytorch","model_id":"pose"}},"timestamp":"2019-12-17T09:28:13.474829Z","logName":"projects/rcg-shopper/logs/ml.googleapis…
2019-12-17T09:28:13.474918Z WARNING:tensorflow:
2019-12-17T09:28:13.474927Z The TensorFlow contrib module will not be included in TensorFlow 2.0.
2019-12-17T09:28:13.474934Z For more information, please see:
2019-12-17T09:28:13.474941Z   * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md
2019-12-17T09:28:13.474951Z   * https://github.com/tensorflow/addons
2019-12-17T09:28:13.474958Z   * https://github.com/tensorflow/io (for I/O related ops)
2019-12-17T09:28:13.474964Z If you depend on functionality not listed there, please file an issue.
2019-12-17T09:28:13.474999Z {"textPayload":"","insertId":"5df89fad00073f778735d7c3","resource":{"type":"cloudml_model_version","labels":{"version_id":"lightweight_pose_pytorch","model_id":"pose","project_id":"rcg-shopper","region":""}},"timestamp":"2019-12-17T09:28:13.474999Z","logName":"projects/rcg-shopper/logs/ml.googleapis…
2019-12-17T09:28:15.283483Z ERROR:root:Failed to import GA GRPC module. This is OK if the runtime version is 1.x
2019-12-17T09:28:16.890923Z Copying gs://cml-489210249453-1560169483791188/models/pose/lightweight_pose_pytorch/15316451609316207868/user_code/my_custom_code-0.1.tar.gz...
2019-12-17T09:28:16.891150Z / [0 files][    0.0 B/  8.4 KiB]
2019-12-17T09:28:17.007684Z / [1 files][  8.4 KiB/  8.4 KiB]
2019-12-17T09:28:17.009154Z Operation completed over 1 objects/8.4 KiB.
2019-12-17T09:28:18.953923Z Processing /tmp/custom_code/my_custom_code-0.1.tar.gz
2019-12-17T09:28:19.808897Z Collecting opencv-python
2019-12-17T09:28:19.868579Z   Downloading https://files.pythonhosted.org/packages/d8/38/60de02a4c9013b14478a3f681a62e003c7489d207160a4d7df8705a682e7/opencv_python-4.1.2.30-cp37-cp37m-manylinux1_x86_64.whl (28.3MB)
2019-12-17T09:28:21.537989Z Collecting torch
2019-12-17T09:28:21.552871Z   Downloading https://files.pythonhosted.org/packages/f9/34/2107f342d4493b7107a600ee16005b2870b5a0a5a165bdf5c5e7168a16a6/torch-1.3.1-cp37-cp37m-manylinux1_x86_64.whl (734.6MB)
2019-12-17T09:28:52.401619Z Collecting numpy>=1.14.5
2019-12-17T09:28:52.412714Z   Downloading https://files.pythonhosted.org/packages/9b/af/4fc72f9d38e43b092e91e5b8cb9956d25b2e3ff8c75aed95df5569e4734e/numpy-1.17.4-cp37-cp37m-manylinux1_x86_64.whl (20.0MB)
2019-12-17T09:28:53.550662Z Building wheels for collected packages: my-custom-code
2019-12-17T09:28:53.550689Z   Building wheel for my-custom-code (setup.py): started
2019-12-17T09:28:54.212558Z   Building wheel for my-custom-code (setup.py): finished with status 'done'
2019-12-17T09:28:54.215365Z   Created wheel for my-custom-code: filename=my_custom_code-0.1-cp37-none-any.whl size=7791 sha256=fd9ecd472a6a24335fd24abe930a4e7d909e04bdc4cf770989143d92e7023f77
2019-12-17T09:28:54.215482Z   Stored in directory: /tmp/pip-ephem-wheel-cache-i7sb0bmb/wheels/0d/6e/ba/bbee16521304fc5b017fa014665b9cae28da7943275a3e4b89
2019-12-17T09:28:54.222017Z Successfully built my-custom-code
2019-12-17T09:28:54.650218Z Installing collected packages: numpy, opencv-python, torch, my-custom-code

Body:
After hours of good old trial errors, I came to the same conclusion as @kyamagu, "install_requires try to fetch PyPI hosted torch package which is a huge GPU built wheel and that is exceeding the deployment quota."

However, his solution did not work for me. So after many more hours of trial errors (thanks to lacking documentation and wrong ones) I came up with this solution:

We need to get the cpu-built wheels of the Pytorch which is around 100 MBs rather than the 700 MBs GPU-builts that are the default PyPI hosted. you can find them here: https://download.pytorch.org/whl/cpu/torch_stable.html

Next, we need to place them in our gs storage and then give the path as part of the --package-uris like this:

gcloud beta ai-platform versions create v17 \
    --model=newest \
    --origin=gs://bucket \
    --runtime-version=1.15 \
    --python-version=3.7 \
    --package-uris=gs://bucket/predictor-0.1.tar.gz,gs://bucket/torch-1.3.0+cpu-cp37-cp37m-linux_x86_64.whl \
    --prediction-class=predictor.MyPredictor \
    --machine-type=mls1-c4-m4

Also, watch out for the order of the package-uris, the predictor package should be first and there should not be any space after commas.

Hope this helps. cheers!


问:
Transform selector to style in CSS
I get this element when I copy the selector on my console

#feed-body > div > div:nth-child(1) > div.description > span > span.image > img
```

<p>If I want to style or overwrite the styling of img with !important what would be the CSS?</p>

<p>I tried </p>

<pre class="lang-css prettyprint-override"><code>span.image img {width:100% !important}
</code>```

but is not working (the default is max-width: 84px which I want to change).

I also tried with max-width: 300px !important but no results.

Am I giving style to the wrong class or is something else?

答:
Try to inspect your page and see in the 'style' section if there is another rule overwriting this rule.

Also, max-width could limit your width rule, so you may need to overwrite both:

```<code>width: 100% !important; max-width: initial !important;
</code>```

Title: Transform selector to style in CSS

Body:
I get this element when I copy the selector on my console

#feed-body > div > div:nth-child(1) > div.description > span > span.image > img

If I want to style or overwrite the styling of img with !important what would be the CSS?

I tried

span.image img {width:100% !important}

but is not working (the default is max-width: 84px which I want to change).

I also tried with max-width: 300px !important but no results.

Am I giving style to the wrong class or is something else?

Body:
Try to inspect your page and see in the 'style' section if there is another rule overwriting this rule.

Also, max-width could limit your width rule, so you may need to overwrite both:

width: 100% !important; max-width: initial !important;


问:
Infopath 2007 browser form code not working in MOSS 2007
I have a Sharepoint 2007 (MOSS) Server and i want to publish an InfoPath form with managed code to it.

I have already published alot of InfoPath forms in the past, and everything is working fine.

The only problem is, that the code that i put in the Form, is not running in the sharepoint site, but only in the infopath application preview.

Any ideas?

The code is a simple one that change the DataSource location and adds a filter to it like here: http://edgedev.blogspot.com/2008/09/bending-infopath-and-sharepoint-to-your.html

答:
I think you published the form to a document library. I know that your infopath codes runs only on "Form Library" document libraries.

Try it,

P.S.: And you must publish it as "administration approved form"


问:
How do I make my running numbers stop at a specified number and remain that way?
```<code>function pad(val) {
  return val > 9 ? val : "0" + val;
}
setInterval(function() {
  $("#seconds").html(pad(++sec % 25000));
}, 1);
</code>```

I simply want these seconds to stop at 25,000 and remain that way unless the page is obviously refreshed...what can I add to this code?

答:
you could just add an if statement.

let sec = 0;
function pad(val) {
  return val > 9 ? val : "0" + val;
}
setInterval(function() {
  if (sec < 25000) {
    $("#seconds").html(pad(++sec % 25000));
  }
}, 1);```
</div>
</div>
</p>

<p>and if you want to clear interval so it stops running all together</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const countUp = setInterval(function() {
  if (sec < 25000) {
    $("#seconds").html(pad(++sec % 25000));
  } else {
    clearInterval(countUp);
  }
}, 1);</code>```

Body:
function pad(val) {
  return val > 9 ? val : "0" + val;
}
setInterval(function() {
  $("#seconds").html(pad(++sec % 25000));
}, 1);

I simply want these seconds to stop at 25,000 and remain that way unless the page is obviously refreshed...what can I add to this code?

Body:
you could just add an if statement.

let sec = 0;
function pad(val) {
  return val > 9 ? val : "0" + val;
}
setInterval(function() {
  if (sec < 25000) {
    $("#seconds").html(pad(++sec % 25000));
  }
}, 1);

and if you want to clear interval so it stops running all together

const countUp = setInterval(function() {
  if (sec < 25000) {
    $("#seconds").html(pad(++sec % 25000));
  } else {
    clearInterval(countUp);
  }
}, 1);


问:
How to include files in a cron job?
I run a cron job on a MediaTemple (gs) hosting, the command is the following:

```<code>php5 /home/144061/data/test.php
</code>```

Inside the php file, and include statement is located.

The cron job returns an error:

```<code>Warning: include(../domains/test.com/html/wp-blog-header.php): failed to open stream: No such file or directory in /nfs/c10/h02/mnt/144061/data/delete_seen.php on line 3

Warning: include(): Failed opening '../domains/test.com/html/wp-blog-header.php' for inclusion (include_path='.:/usr/local/php-5.3.15/share/pear') in /nfs/c10/h02/mnt/144061/data/delete_seen.php on line 3
</code>```

I want to be able to include wordpress header in my cron file so that I can use wordpress functions and database connection in my cron script, what's wrong with my include statement?

答:
If anyone is still struggling with this, please note that your include path must be relative to you CRON path run directory. Otherwise, it won't find the files you're trying to include. For example, in Cpanel, I used the following : require('home/yourdomain/public_html/wp-load.php').

Also, instead of including the header, you should include wp-load.php, which includes all of the core Wordpress functionalities.

Title: How to include files in a cron job?

Body:
I run a cron job on a MediaTemple (gs) hosting, the command is the following:

php5 /home/144061/data/test.php

Inside the php file, and include statement is located.

The cron job returns an error:

Warning: include(../domains/test.com/html/wp-blog-header.php): failed to open stream: No such file or directory in /nfs/c10/h02/mnt/144061/data/delete_seen.php on line 3

Warning: include(): Failed opening '../domains/test.com/html/wp-blog-header.php' for inclusion (include_path='.:/usr/local/php-5.3.15/share/pear') in /nfs/c10/h02/mnt/144061/data/delete_seen.php on line 3

I want to be able to include wordpress header in my cron file so that I can use wordpress functions and database connection in my cron script, what's wrong with my include statement?


问:
php checkbox array access
```<code>$i=0;
while (db_data) {
$i++;
echo '<input type="checkbox" name="v['.$i.']" value="'.$url.'"';
if ($v[$i]) {
  echo ' checked';
  $s .= $url;
}
echo '/>';

}
</code>```

I have the above array of checkboxes. It worked on my pc, but not on the server; it seems like the confusing part is on $v[$i].

$v is not defined, but sure used no where else. the problem is my checkbox selection never restored, and code never get into the if statement.

however, if i add the following, i can see the value. just the checkbox lost after the processing
    $v=$_POST['v'];
    while (list ($key,$val) = @each ($v)) {
    $x .= ' 11*'.$key.'-'.$val.'*22 ';
    }

my goal is to preserve the checkbox checked on the form, and i need the $s elsewhere. any solution to replace $v[$i]?

Can anybody help me fix this? Thank you.

答:
change

```<code>name="v['.$i.']"
</code>```

to

```<code>name="v[]"
</code>```

the fact that PHP picks that up as an array is a unintended feature of PHP that wasn't intentionally designed. you don't need to set the indexes, just define it as an array.

Title: php checkbox array access

Body:
$i=0;
while (db_data) {
$i++;
echo '<input type="checkbox" name="v['.$i.']" value="'.$url.'"';
if ($v[$i]) {
  echo ' checked';
  $s .= $url;
}
echo '/>';

}

I have the above array of checkboxes. It worked on my pc, but not on the server; it seems like the confusing part is on $v[$i].

$v is not defined, but sure used no where else. the problem is my checkbox selection never restored, and code never get into the if statement.

however, if i add the following, i can see the value. just the checkbox lost after the processing
    $v=$_POST['v'];
    while (list ($key,$val) = @each ($v)) {
    $x .= ' 11*'.$key.'-'.$val.'*22 ';
    }

my goal is to preserve the checkbox checked on the form, and i need the $s elsewhere. any solution to replace $v[$i]?

Can anybody help me fix this? Thank you.

Body:
change

name="v['.$i.']"

to

name="v[]"

the fact that PHP picks that up as an array is a unintended feature of PHP that wasn't intentionally designed. you don't need to set the indexes, just define it as an array.


问:
Sort alphanumeric dictionary keys based on only numeric part in key
I have a dictionary like the one below:

dictionary = {
  "sf_init#12" : "string",
  "sf_code#5" : "string",
  ...
}
```

I want the keys to be sorted in the order:

sf_code#5

sf_init#12

...

I tried using split() in a lambda function and then sorted the numeric part, but it did not work.
Anyone who has a better idea how to sort this?

(Note) : I am using Python2. Also, I do not want natural sorting.

答:
The sort you use in your comments specifies to sort on the 2nd and 1st characters of the keys.  These are 'f', 's' for both keys.  If you want to sort by the number at the end, you need to extract those.  Try

```<code>dicts = {"sf_init#27": 'g', "sf_code#5" :'h'}
for i in sorted(dicts.keys(), key=lambda k: k.split('#')[-1], reverse=True):
    print (i)
</code>```

Output

```<code>sf_code#5
sf_init#27
</code>```

Body:
I have a dictionary like the one below:

dictionary = {
  "sf_init#12" : "string",
  "sf_code#5" : "string",
  ...
}

I want the keys to be sorted in the order:

sf_code#5

sf_init#12

...

I tried using split() in a lambda function and then sorted the numeric part, but it did not work.
Anyone who has a better idea how to sort this?

(Note) : I am using Python2. Also, I do not want natural sorting.

Body:
The sort you use in your comments specifies to sort on the 2nd and 1st characters of the keys.  These are 'f', 's' for both keys.  If you want to sort by the number at the end, you need to extract those.  Try

dicts = {"sf_init#27": 'g', "sf_code#5" :'h'}
for i in sorted(dicts.keys(), key=lambda k: k.split('#')[-1], reverse=True):
    print (i)

Output

sf_code#5
sf_init#27


问:
How do i fix the angle of my mathematical triangle of squares?
I need to fix my output as shown at the bottom, i have code that outputs the correct math values
but it does not output the correct angle that is expected of the example output that i have provided below. ( I know this is pretty simple for most of you stack users but im a beginner in java and this is something that confuses me ). I have not come up with any ideas on what i can do to fix this issue and put in the correct angle.

Instructions:

```<code>-Write a program using a Scanner that asks the user for a number
 n between 1 and 9 (inclusive).
-The program prints a triangle with n rows.
-The first row contains only the square of 1, and it is right-justified.
-The second row contains the square of 2 followed by the square of 1,
and is right justified.
-Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2
 and 1, and so forth until n rows are printed.

 Assuming the user enters 4, the program prints the following triangle to the console

          1
       4  1
    9  4  1
16  9  4  1
</code>```

Code:

```<code>import java.util.Scanner;

public class Triangle {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a number between 1 and 9 inclusive:");
    int n = scan.nextInt();
    for (int i = 1 ; i <=n; i++) {
        for (int j = n-i; j >=1; j--) {
            System.out.print("");
        }
        for (int k = i; k <= n; k++ ) {
            System.out.print("  " + i * i);
        }
        System.out.println("  ");
    }
    scan.close();
}
}
</code>```

My output:

```<code>Please enter a number between 1 and 9 inclusive:  4

  1  1  1  1
  4  4  4
  9  9
  16
</code>```

答:
I have used the code you guys provided and it had some logical issues when inputting a number past 4 it would not square the triangle correctly and would only create the shape. I have solved the issue by adding a while loop and editing the for loops and not it outputs correctly.

Incorrect output:

```<code>Please enter a number between 1 and 9 inclusive: 8

                      9
                   4  9
                1  4  9
             0  1  4  9
          1  0  1  4  9
       4  1  0  1  4  9
    9  4  1  0  1  4  9
16  9  4  1  0  1  4  9
</code>```

Correct Code Given:

```<code>import java.util.Scanner;

public class AverageGrades {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a number between 1 and 9 inclusive:");
    int n = scan.nextInt();

    for (int row = 1; row <= n; row ++) {
        for (int col = n; col >= 1; col--) {
            if (col <= row) {
                System.out.print(String.format("%2d ", col * col));
            } else {
                System.out.print("   ");
            }
        }
        System.out.println();
    }

}

}
</code>```

My Code:

```<code>import java.util.Scanner;

public class TriangleTest {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.print("Enter Number between 1 and 9 : ");
    int n = scan.nextInt();

    while(n < 0 || n > 9)
    {
        System.out.print("Please enter a valid value between 1 and 9 :");
        n = scan.nextInt();
    }

    for(int i = 0; i < n; i++)
    {

        for(int j = 0; j <= n*2-(i + i); j++)
        {

            System.out.print("  ");
        }

        for(int l = i + 1; l > 0; l--)
        {
            int r = l*l;
            System.out.print(r +  "  ");
        }
        System.out.println("\n");

    }
    scan.close();
}

}
</code>```

Correct Output:

```<code>Enter Number between 1 and 9 : 10
Please enter a valid value between 1 and 9 :9

                                1

                             4  1

                          9  4  1

                      16  9  4  1

                  25  16  9  4  1

              36  25  16  9  4  1

          49  36  25  16  9  4  1

      64  49  36  25  16  9  4  1

  81  64  49  36  25  16  9  4  1
</code>```

Body:
I need to fix my output as shown at the bottom, i have code that outputs the correct math values
but it does not output the correct angle that is expected of the example output that i have provided below. ( I know this is pretty simple for most of you stack users but im a beginner in java and this is something that confuses me ). I have not come up with any ideas on what i can do to fix this issue and put in the correct angle.

Instructions:

-Write a program using a Scanner that asks the user for a number
 n between 1 and 9 (inclusive).
-The program prints a triangle with n rows.
-The first row contains only the square of 1, and it is right-justified.
-The second row contains the square of 2 followed by the square of 1,
and is right justified.
-Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2
 and 1, and so forth until n rows are printed.

 Assuming the user enters 4, the program prints the following triangle to the console

          1
       4  1
    9  4  1
16  9  4  1

Code:

import java.util.Scanner;

public class Triangle {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a number between 1 and 9 inclusive:");
    int n = scan.nextInt();
    for (int i = 1 ; i <=n; i++) {
        for (int j = n-i; j >=1; j--) {
            System.out.print("");
        }
        for (int k = i; k <= n; k++ ) {
            System.out.print("  " + i * i);
        }
        System.out.println("  ");
    }
    scan.close();
}
}

My output:

Please enter a number between 1 and 9 inclusive:  4

  1  1  1  1
  4  4  4
  9  9
  16

Body:
I have used the code you guys provided and it had some logical issues when inputting a number past 4 it would not square the triangle correctly and would only create the shape. I have solved the issue by adding a while loop and editing the for loops and not it outputs correctly.

Incorrect output:

Please enter a number between 1 and 9 inclusive: 8

                      9
                   4  9
                1  4  9
             0  1  4  9
          1  0  1  4  9
       4  1  0  1  4  9
    9  4  1  0  1  4  9
16  9  4  1  0  1  4  9

Correct Code Given:

import java.util.Scanner;

public class AverageGrades {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter a number between 1 and 9 inclusive:");
    int n = scan.nextInt();

    for (int row = 1; row <= n; row ++) {
        for (int col = n; col >= 1; col--) {
            if (col <= row) {
                System.out.print(String.format("%2d ", col * col));
            } else {
                System.out.print("   ");
            }
        }
        System.out.println();
    }

}

}

My Code:

import java.util.Scanner;

public class TriangleTest {

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.print("Enter Number between 1 and 9 : ");
    int n = scan.nextInt();

    while(n < 0 || n > 9)
    {
        System.out.print("Please enter a valid value between 1 and 9 :");
        n = scan.nextInt();
    }

    for(int i = 0; i < n; i++)
    {

        for(int j = 0; j <= n*2-(i + i); j++)
        {

            System.out.print("  ");
        }

        for(int l = i + 1; l > 0; l--)
        {
            int r = l*l;
            System.out.print(r +  "  ");
        }
        System.out.println("\n");

    }
    scan.close();
}

}

Correct Output:

Enter Number between 1 and 9 : 10
Please enter a valid value between 1 and 9 :9

                                1

                             4  1

                          9  4  1

                      16  9  4  1

                  25  16  9  4  1

              36  25  16  9  4  1

          49  36  25  16  9  4  1

      64  49  36  25  16  9  4  1

  81  64  49  36  25  16  9  4  1


问:
Php get subjectAltName from csr
Good evening my friend
I generated san csr via openssl function using php. But i cant get subjectAltName. Please How can i extract subjetAltName from csr? </p>

```<code>shell_exec('openssl req -noout -text -in'. $csr)
</code>```

答:
I hope this helps:

```<code>$r = shell_exec('openssl req -noout -text -in '. $csr)
                                             ^- a space here!
</code>```

for my test however openssl did not print a Subject Alt Name, so i'll show how to get the Subject:

```<code>preg_match('/Subject:\s*(.*)\n/', $r, $matches);
$subject = $matches[1];
</code>```

Title: Php get subjectAltName from csr

Body:
Good evening my friend
I generated san csr via openssl function using php. But i cant get subjectAltName. Please How can i extract subjetAltName from csr?

shell_exec('openssl req -noout -text -in'. $csr)

Body:
I hope this helps:

$r = shell_exec('openssl req -noout -text -in '. $csr)
                                             ^- a space here!

for my test however openssl did not print a Subject Alt Name, so i'll show how to get the Subject:

preg_match('/Subject:\s*(.*)\n/', $r, $matches);
$subject = $matches[1];