问:
How to redirect all except main page with NGINX?
This is my NGINX conf file:

```<code>server {
    listen 80;
    listen [::]:80;
    server_name other.com;
    root        /home/user/html;

        location = / {

        }

        location / {
           return 301 https://mydom.com$request_uri;
        }
}
</code>```

It suppose to redirect every request except main route ("/"). But now it redirect everything with main route too. Where is my mistake?

答:
Your location = / block isolates a single URI - the original request.

By default, Nginx processes any request that ends with a /, by checking if it resolves to a directory, and checking the directory for any files matching those listed in the index directive (default: index.html).

The index directive causes an internal redirection which causes Nginx to repeat the search for a matching location.

You will also need to isolate the redirected request.

For example:

```<code>location = / { }
location = /index.html { }
location / { ... }
</code>```

Alternatively, bypass the index directive and handle it a single location using a try_files statement.

For example:

```<code>location = / { try_files /index.html =404; }
location / { ... }
</code>```

See this document for details.

Body:
This is my NGINX conf file:

server {
    listen 80;
    listen [::]:80;
    server_name other.com;
    root        /home/user/html;

        location = / {

        }

        location / {
           return 301 https://mydom.com$request_uri;
        }
}

It suppose to redirect every request except main route ("/"). But now it redirect everything with main route too. Where is my mistake?

Body:
Your location = / block isolates a single URI - the original request.

By default, Nginx processes any request that ends with a /, by checking if it resolves to a directory, and checking the directory for any files matching those listed in the index directive (default: index.html).

The index directive causes an internal redirection which causes Nginx to repeat the search for a matching location.

You will also need to isolate the redirected request.

For example:

location = / { }
location = /index.html { }
location / { ... }

Alternatively, bypass the index directive and handle it a single location using a try_files statement.

For example:

location = / { try_files /index.html =404; }
location / { ... }

See this document for details.


来源: stackexchange

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

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

Then the text field :

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

And finally the php file:

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

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

答:
Replace

<button onclick="doWork(this.msg);">Send</button>
with

 <button onclick="doWork(msg);">Send</button>

this.msg is the same as button.msg, which does not make sense.

ContentLicense: CC BY-SA 3.0

Title: Problem with AJAX chat

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

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

Then the text field :

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

And finally the php file:

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

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


问:
Custom tags applied to Azure web app pages in Azure Application Insights
Use case: Categorizing page views in an Azure web app for analytics reporting

Using Azure Application Insights, I can see a list of pages in an Azure web app and its number of views in the past X days.

The web app is a documentation website. I would like to categorize each page with a tag like install-info or api-doc or intro-material, etc. The goal is that I can easily see information like "X number of page views were around install information" or "API pages received 25% of traffic," etc.

Currently I am exporting a table of each page and its number of views. Then I manually categorize each page in Excel. There are hundreds of pages. I would love to export a table that included a third column showing the page's custom tag.

Looking at Microsoft documentation, it sounds like this is possible with custom coding and the API, but I would like a simpler strategy if one exists, as I am not a sophisticated coder.

If there are alternative methods of achieving my goal than the solution I'm asking about in this question, I would be grateful to know.

Thank you.

答:
If I understood you correctly, you want to add an extra tag(column) for different kind of url, right?

If that's the case, you can take use of case and extend statement of kusto.

Here is an sample code:

```<code>pageViews
| where name contains "WebApplication5"
| extend mytags = case(
    //here, I'm using name for each condition, you can use other field as per your need.
    name=="Home Page - WebApplication5","index page",
    name=="Privacy Policy - WebApplication5","privacy page",
    "others"
)
| project name,mytags
</code>```

Then export the result. The test result is as below:

Please feel free to modify this code to meet your requirement, and also let me know if you still have more issues about that.

ContentLicense: CC BY-SA 4.0

Body:
If I understood you correctly, you want to add an extra tag(column) for different kind of url, right?

If that's the case, you can take use of case and extend statement of kusto.

Here is an sample code:

pageViews
| where name contains "WebApplication5"
| extend mytags = case(
    //here, I'm using name for each condition, you can use other field as per your need.
    name=="Home Page - WebApplication5","index page",
    name=="Privacy Policy - WebApplication5","privacy page",
    "others"
)
| project name,mytags

Then export the result. The test result is as below:

Please feel free to modify this code to meet your requirement, and also let me know if you still have more issues about that.


问:
Visio: Creating Automatic Numbered Label
I'm currently working on creating a new stencil for several components I use in Visio and I'm stuck at the point of providing proper labels. If you use a resistor from Visio stencil it automatically generates a label "R1" (for first resistor) and "Rk" for the kth resistor. How can I do something similar for my own stencil ?

1- I need to generate a label "ABCD #" (# number automatically generated based on instance count)

2- How can I position the location of this field?

PS:

1- Visio components have a custom defined field which allows for this (which I don't know how to create)

2- For capacitor for example the shapesheet shows an interesting entry

=SETF(GetRef(User.Label),"""C""&"&ThePage!User.AccumulatorCount)&SETF(GetRef(ThePage!User.AccumulatorCount),ThePage!User.AccumulatorCount+1)

which supposedly is how the count and name are generated (I'm not sure how the AccumulatorCount is defined it differs from element to element).

Thank You!

答:
The EventDrop ShapeSheet cells for various electrical shapes have formulas similar to the one you have discovered:
 SETF(GetRef(User.Label),"""C""&"&ThePage!User.AccumulatorCount)&SETF(GetRef(ThePage!User.AccumulatorCount),ThePage!User.AccumulatorCount+1)

The ShapeSheet for the page has a cell: User.AccumulatorCount for capacitors. Other User cells will be added as other shapes are dropped. You can set up your own system by adding a User cell to the page, say: User.Widget. Then you place the "Widget" version of the "SETF" formula into your own shapes.

You can create user cells by:

Open the ShapeSheet for the Page (right-click blank area of page, Show ShapeSheet)

Right-click in ShapeSheet and choose Add Section

Add a User-defined cells section

Find the User-defined cells section and similarly add rows to it via
right-clicking

You change the row names by typing over the red, row-name text on the left.

You enter values and formulas in the cells as you would in Excel.

You can toggle viewing formulas vs. viewing values by pressing F5
while in the ShapeSheet.

You have to make the User cell in the page first, so that your shape can reference it. Once your shape references the page cell, you can drag your shape into a stencil, and it will "drag the page User cell along too". So now, you can drop your Widget shape into a new document, and it will create the page User cell on the fly.

The system is basic and fragile. The count only goes up, and never down. If you have shapes with 1, 2, 3, 4 and you delete 1 and 2, the next shape will still be 5.


问:
Problem with sending custom variable Value in tradingview alert message
I'm trying to send Custom variable value using plot function inside pine-script.

```<code>plot(0.42, title="SL")
alertcondition(condition=b_long , title='L', message='msg_{{plot("SL"}}_{{close}}')
</code>```

This works only when i dont have long pine-script, more than ~400 lines of code.

Problem is that tradeview  does not replace {{plot("SL")}} with value that is circulated inside pine-script.
and the message i got is msg_{{plot("SL"}}_8873.34 instead of  msg_0.42_8873.34
I have  encounters strange problem that makes problem only when i have pinescript is long

Do you have similar problem?
Any ideas how to solve it?
Posting Support Ticketing on tradeview  is currently impossible.

答:
I had the exact same issue and tested all kinds of stuff. In the end I rebuild a simple new study with sending the most simple custom variable to an alert and it worked (magically). After that I added the code from the study that didn't work and for some reason it now works. This feels like a bug, because there is literally no difference between the 2 study's. Hope this works for you as well!

Edit: The only difference is now that all the indicators are now plotted below the graph. Not sure that makes a difference.

Body:
I'm trying to send Custom variable value using plot function inside pine-script.

plot(0.42, title="SL")
alertcondition(condition=b_long , title='L', message='msg_{{plot("SL"}}_{{close}}')

This works only when i dont have long pine-script, more than ~400 lines of code.

Problem is that tradeview  does not replace {{plot("SL")}} with value that is circulated inside pine-script.
and the message i got is msg_{{plot("SL"}}_8873.34 instead of  msg_0.42_8873.34
I have  encounters strange problem that makes problem only when i have pinescript is long

Do you have similar problem?
Any ideas how to solve it?
Posting Support Ticketing on tradeview  is currently impossible.


问:
Web API MultipartAsync Task no result
The goal is to upload a single file to my webserver and then store it to mssql database by using multipartcontent. While the file is uploading, a progress bar should be displayed in the client (WPF application). The following code sample shows only the upload to memorystream (no database connection).

The connection from client to server works, the upload to the MemoryStream at server-side works and receiving receiving the percentage to client side works (section ContinueWith in my sample code). The problem is, the client doesn't receive the final CreateResponse request - like a timeout or lost connection, I am not sure because i doesn't get an error/exception. The client never receives the task final result.

WebApi:

```<code>public class AttachmentsController : ApiController
{
    [HttpPost]
    [Route("api/Attachments/Upload")]
    public async Task<HttpResponseMessage> Upload()
    {
        if (!Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        try
        {
            AttachmentUpload _resultAttachmentUpload = null;

            var _provider = new InMemoryMultipartFormDataStreamProvider();

            await Request.Content.ReadAsMultipartAsync(_provider)
                .ContinueWith(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        throw new HttpResponseException(
                            HttpStatusCode.InternalServerError);
                    }

                    return new AttachmentUpload()
                    {
                        FileName = _provider.Files[0].Headers.ContentDisposition
                            .FileName.Trim('\"'),
                        Size = _provider.Files[0].ReadAsStringAsync().Result
                            .Length / 1024
                    };
                });

            return Request.CreateResponse<AttachmentUpload>(HttpStatusCode.Accepted,
                _resultAttachmentUpload);
        }
        catch (Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                e.ToString());
        }
    }
}
</code>```

WPF Client UploadService.cs:

```<code>private async Task<Attachment> UploadAttachment(AttachmentUpload uploadData,
    string filePath)
{
    try
    {
        var _encoding = Encoding.UTF8;
        MultipartFormDataContent _multipartFormDataContent =
            new MultipartFormDataContent();

        _multipartFormDataContent.Add(new StreamContent(new MemoryStream(
            File.ReadAllBytes(filePath))), uploadData.FileName, uploadData.FileName);
        _multipartFormDataContent.Add(new StringContent(uploadData.Id.ToString()),
            "AttachmentId", "AttachmentId");
        _multipartFormDataContent.Add(new StringContent(
            uploadData.Upload.ToString(CultureInfo.CurrentCulture)), "AttachmentUpload",
            "AttachmentUpload");
        _multipartFormDataContent.Add(new StringContent(
            uploadData.DocumentId.ToString()), "DocumentId", "DocumentId");
        _multipartFormDataContent.Add(new StringContent(
            uploadData.User, _encoding), "User", "User");

        //ProgressMessageHandler is instantiate in ctor to show progressbar
        var _client = new HttpClient(ProgressMessageHandler);
        _client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("multipart/form-data"));
        _client.Timeout = TimeSpan.FromMinutes(5);

        var _requestUri = new Uri(BaseAddress + "api/Attachments/Upload");

        var _httpRequestTask = await _client.PostAsync(_requestUri,
            _multipartFormDataContent)
            .ContinueWith<AttachmentUpload>(request =>
            {
                var _httpResponse = request.Result;

                if (!_httpResponse.IsSuccessStatusCode)
                {
                    throw new Exception();
                }

                var _response = _httpResponse.Content.ReadAsStringAsync();

                AttachmentUpload _upload =
                    JsonConvert.DeserializeObject<AttachmentUpload>(_response.Result);

                return _upload;
            });

        var _resultAttachment = _httpRequestTask;

        return new Attachment()
        {
            Id = _resultAttachment.Id,
            FileName = _resultAttachment.FileName,
            Comment = _resultAttachment.Comment,
            Upload = _resultAttachment.Upload,
        };

    }
    catch (Exception e)
    {
        //Handle exceptions
        //file not found, access denied, no internet connection etc etc
        var tmp = e;
        throw e;
    }
}
</code>```

The program lacks at var _httpRequestTask = await _client.PostAsync(...).
The debugger never reaches the line var _resultAttachment = _httpRequestTask;.

Thank you very much for your help.

答:
First of all, don't mix await and ContinueWith, the introduction of async / await effectively renders ContinueWith obsolete.

The reason that var _resultAttachment = _httpRequestTask; is never hit is because you have created a deadlock.

WPF has a synchronisation context, that ensures continuations resume on the UI thread.

In the line AttachmentUpload _upload = JsonConvert.DeserializeObject<AttachmentUpload>(_response.Result);, _response.Result is a blocking call; it blocks the current thread, until the Task referenced by _response has completed.

The ReadAsStringAsync method, which generated the Task, will attempt to resume once the asynchronous work has completed, and the WPF synchronisation context will force it to use the UI thread, which has been blocked by _response.Result, hence the deadlock.

To remedy this, use the await keyword for every asynchronous call:

```<code>var _httpResponse = await _client.PostAsync(_requestUri, _multipartFormDataContent);

if (!_httpResponse.IsSuccessStatusCode)
{
    throw new Exception();
}

var _response = await _httpResponse.Content.ReadAsStringAsync();

var _resultAttachment = JsonConvert.DeserializeObject<AttachmentUpload>(_response);
</code>```

You should also notice that the code is much more readable without the ContinueWith.

Title: Web API MultipartAsync Task no result

Body:
The goal is to upload a single file to my webserver and then store it to mssql database by using multipartcontent. While the file is uploading, a progress bar should be displayed in the client (WPF application). The following code sample shows only the upload to memorystream (no database connection).

The connection from client to server works, the upload to the MemoryStream at server-side works and receiving receiving the percentage to client side works (section ContinueWith in my sample code). The problem is, the client doesn't receive the final CreateResponse request - like a timeout or lost connection, I am not sure because i doesn't get an error/exception. The client never receives the task final result.

WebApi:

public class AttachmentsController : ApiController
{
    [HttpPost]
    [Route("api/Attachments/Upload")]
    public async Task<HttpResponseMessage> Upload()
    {
        if (!Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        try
        {
            AttachmentUpload _resultAttachmentUpload = null;

            var _provider = new InMemoryMultipartFormDataStreamProvider();

            await Request.Content.ReadAsMultipartAsync(_provider)
                .ContinueWith(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        throw new HttpResponseException(
                            HttpStatusCode.InternalServerError);
                    }

                    return new AttachmentUpload()
                    {
                        FileName = _provider.Files[0].Headers.ContentDisposition
                            .FileName.Trim('\"'),
                        Size = _provider.Files[0].ReadAsStringAsync().Result
                            .Length / 1024
                    };
                });

            return Request.CreateResponse<AttachmentUpload>(HttpStatusCode.Accepted,
                _resultAttachmentUpload);
        }
        catch (Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                e.ToString());
        }
    }
}

WPF Client UploadService.cs:

private async Task<Attachment> UploadAttachment(AttachmentUpload uploadData,
    string filePath)
{
    try
    {
        var _encoding = Encoding.UTF8;
        MultipartFormDataContent _multipartFormDataContent =
            new MultipartFormDataContent();

        _multipartFormDataContent.Add(new StreamContent(new MemoryStream(
            File.ReadAllBytes(filePath))), uploadData.FileName, uploadData.FileName);
        _multipartFormDataContent.Add(new StringContent(uploadData.Id.ToString()),
            "AttachmentId", "AttachmentId");
        _multipartFormDataContent.Add(new StringContent(
            uploadData.Upload.ToString(CultureInfo.CurrentCulture)), "AttachmentUpload",
            "AttachmentUpload");
        _multipartFormDataContent.Add(new StringContent(
            uploadData.DocumentId.ToString()), "DocumentId", "DocumentId");
        _multipartFormDataContent.Add(new StringContent(
            uploadData.User, _encoding), "User", "User");

        //ProgressMessageHandler is instantiate in ctor to show progressbar
        var _client = new HttpClient(ProgressMessageHandler);
        _client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("multipart/form-data"));
        _client.Timeout = TimeSpan.FromMinutes(5);

        var _requestUri = new Uri(BaseAddress + "api/Attachments/Upload");

        var _httpRequestTask = await _client.PostAsync(_requestUri,
            _multipartFormDataContent)
            .ContinueWith<AttachmentUpload>(request =>
            {
                var _httpResponse = request.Result;

                if (!_httpResponse.IsSuccessStatusCode)
                {
                    throw new Exception();
                }

                var _response = _httpResponse.Content.ReadAsStringAsync();

                AttachmentUpload _upload =
                    JsonConvert.DeserializeObject<AttachmentUpload>(_response.Result);

                return _upload;
            });

        var _resultAttachment = _httpRequestTask;

        return new Attachment()
        {
            Id = _resultAttachment.Id,
            FileName = _resultAttachment.FileName,
            Comment = _resultAttachment.Comment,
            Upload = _resultAttachment.Upload,
        };

    }
    catch (Exception e)
    {
        //Handle exceptions
        //file not found, access denied, no internet connection etc etc
        var tmp = e;
        throw e;
    }
}

The program lacks at var _httpRequestTask = await _client.PostAsync(...).
The debugger never reaches the line var _resultAttachment = _httpRequestTask;.

Thank you very much for your help.

Body:
First of all, don't mix await and ContinueWith, the introduction of async / await effectively renders ContinueWith obsolete.

The reason that var _resultAttachment = _httpRequestTask; is never hit is because you have created a deadlock.

WPF has a synchronisation context, that ensures continuations resume on the UI thread.

In the line AttachmentUpload _upload = JsonConvert.DeserializeObject<AttachmentUpload>(_response.Result);, _response.Result is a blocking call; it blocks the current thread, until the Task referenced by _response has completed.

The ReadAsStringAsync method, which generated the Task, will attempt to resume once the asynchronous work has completed, and the WPF synchronisation context will force it to use the UI thread, which has been blocked by _response.Result, hence the deadlock.

To remedy this, use the await keyword for every asynchronous call:

var _httpResponse = await _client.PostAsync(_requestUri, _multipartFormDataContent);

if (!_httpResponse.IsSuccessStatusCode)
{
    throw new Exception();
}

var _response = await _httpResponse.Content.ReadAsStringAsync();

var _resultAttachment = JsonConvert.DeserializeObject<AttachmentUpload>(_response);

You should also notice that the code is much more readable without the ContinueWith.


问:
object property coming up as undefined
Through recursion i'm adding data to the obj['prop'] property in forms of db query results.

let obj = {};

if (obj['prop'] == undefined) {
  obj['prop'] = {};
}

console.log(obj);```
</div>
</div>
</p>

<p>Why isn't this working?
I've tried this too.</p>

```if(!obj['prop']){
 obj['prop'] = {}
}
```

<p>I know it has nothing to do with the presented error...</p>

<p>However i'm applying values with multiple nested properties to an object.</p>

```obj['prop']['prop2'] = results
```

<p>And it didn't allow me to so I applied the property inside the object before adding further nested properties. But it's not working. It's still coming up with property 'prop' undefined.</p>

<p>My function:</p>

``` posts: function(request, cb){
            application = (request.query.application) ? request.query.application : "*";
            type = (request.query.type) ? request.query.type : "*";
            wall = (request.query.wall) ? request.query.wall : "*";
            db.query(
                "SELECT * FROM Client.Posts WHERE Application = ? AND Wall_Type = ? AND Wall_Name = ?;",
                [
                    application,
                    type,
                    wall
                ],
                function(error, posts){
                    if(posts.length == 0){
                        cb(posts);
                    }else{
                        repliesDone = false;
                        likesDone = false;
                        commentsDone = false;
                        commentLikesDone = false;
                        repliesLikesDone = false;
                        function PostRecursionComments(posts, length, i){
                            if(posts[i]['DATA'] == undefined){
                                posts[i]['DATA'] = {};
                            }
                            db.query(
                                "SELECT * FROM Client.Comments WHERE Client.Comments.Post_ID = ?",
                                [
                                    posts[i]['ID']
                                ],
                                function(error, comments){
                                    for(i = 0; i < comments.length; i++){
                                        db.query(
                                            "SELECT * FROM Client.Likes WHERE Type = 'Comment' AND TypeID = ?",
                                            [
                                                comments[i]['ID']
                                            ],
                                            function(error, commentLikes){
                                                commentLikesDone = true;
                                                posts[i]['DATA']['Comments'][i]['DATA']['Likes'] = commentLikes;
                                            }
                                        );
                                    }
                                    posts[i]['DATA']['Comments'] = comments;
                                    if(posts.length - 1 == i){
                                        commentsDone = true;
                                    }else{
                                        i++;
                                        PostRecursionComments(posts, posts.length, i);
                                    }
                                }
                            );
                        }
                        PostRecursionComments(posts, posts.length, 0);
                        function CommentsRecursionReplies(comments, length, i, z, posts){
                            if(comments[z]['DATA'] == undefined){
                                comments[z]['DATA'] = {};
                            }
                            db.query(
                                "SELECT * FROM Client.Replies WHERE Client.Replies.Parent_Is_Comment = 1 AND Client.Replies.Parent_ID = ?",
                                [
                                    commentsz[z]['ID']
                                ],
                                function(error, replies){
                                    for(i = 0; i < replies.length; i++){
                                        db.query(
                                            "SELECT * FROM Client.Likes WHERE Type = 'Reply' AND TypeID = ?",
                                            [
                                                replies[i]['ID']
                                            ],
                                            function(error, replyLikes){
                                                replyLikesDone = true;
                                                comments[z]['DATA']['Replies'][i]['DATA']['Likes'] = replyLikes;
                                            }
                                        );
                                    }
                                    comments[z]['DATA']['Replies'] = replies;
                                    if(posts[i]['DATA']['Comments'].length - 1 == z){
                                    }else{
                                        z++;
                                        CommentsRecursionReplies(posts[i]['DATA']['Comments'], posts['DATA']['Comments'].length, i, z, posts);
                                    }
                                }
                            );
                        }
                        for(i = 0; i < posts.length; i++){
                            if(posts[i]['DATA']['Comments']){
                                CommentsRecursionReplies(posts[i]['DATA']['Comments'], posts[i]['DATA']['Comments'].length, i, 0, posts);
                            }
                            repliesDone = true;
                        }
                        function RepliesRecursionReplies(replies, length, i, j, z, posts){
                            if(replies[z]['DATA'] == undefined){
                                replies[z]['DATA'] = {};
                            }
                            /*  truth tables? */
                            db.query(
                                "SELECT * FROM Client.Replies WHERE Client.Replies.Parent_Is_Comment = 0 AND Client.Replies.Parent_ID = ?",
                                [
                                    posts[i]['DATA']['Comments'][j]['Replies'][z]['ID']
                                ],
                                function(error, replies){
                                    if(!posts[i]['DATA']['Comments'][j]['Replies'][z]['DATA']){
                                        posts[i]['DATA']['Comments'][j]['Replies'][z]['DATA'] = {};
                                    }
                                    posts[i]['DATA']['Comments'][j]['Replies'][z]['DATA']['Replies'] = replies;
                                    if(posts[i]['DATA']['Comments'][j]['Replies'].length - z == 0){
                                        /* enumerator and properties... */
                                        repliesRepliesDone = true;
                                    }else{
                                        z++;
                                        RepliesRecursionReplies(replies, replies.length, i, j, z, posts);
                                    }
                                }
                            );
                        }
                        for(i = 0; i < posts[i].length; i++){
                            for(j = 0; j < posts[i]['DATA']['Comments'].length; j++){
                                RepliesRecursionReplies(posts[i]['DATA']['Comments'][j]['Replies'], posts[i]['DATA']['Comments'][j]['Replies'].length, i, j, 0, posts);
                            }
                        }
                        function PostRecursionLikes(posts, length, i){
                            if(posts[i]['DATA'] == undefined){
                                posts[i]['DATA'] = {};
                            }
                            db.query(
                                "SELECT * FROM Client.Likes WHERE Type = 'Post' AND TypeID = ?",
                                [
                                    posts[i]['ID']
                                ],
                                function(error, likes){
                                    post['DATA']['Likes'] = likes;
                                    if(posts.length - 1 == i){
                                        likesDone = true;
                                    }else{
                                        i++;
                                        PostRecursionLikes(posts, posts.length, i);
                                    }
                                }
                            );
                        }
                        PostRecursionLikes(posts, posts.length, 0);
                        function callback(data){
                            if(commentsDone && repliesDone && likesDone && commentLikesDone && replikesLikesDone){
                                cb(data);
                            }else{
                                setTimeout(function(){
                                    callback(data)
                                }, 1);
                            }
                        }
                        callback(posts);
                    }
                }
            );
        }
```

答:
It indeed doesn't work.

Thast beqause it isn't realy undefined it's empty. That means it can ether be ' ' or null. So try tackeling those conditions too and it should work perfect!

let obj = {};

if(obj['prop'] == 'undefined' || obj['prop'] == '' || obj['prop'] == null){
  obj['prop'] = {};
}
console.log(obj['prop'])```

Title: object property coming up as undefined

Body:
Through recursion i'm adding data to the obj['prop'] property in forms of db query results.

let obj = {};

if (obj['prop'] == undefined) {
  obj['prop'] = {};
}

console.log(obj);

Why isn't this working?
I've tried this too.

if(!obj['prop']){
 obj['prop'] = {}
}

I know it has nothing to do with the presented error...

However i'm applying values with multiple nested properties to an object.

obj['prop']['prop2'] = results

And it didn't allow me to so I applied the property inside the object before adding further nested properties. But it's not working. It's still coming up with property 'prop' undefined.

My function:

 posts: function(request, cb){
            application = (request.query.application) ? request.query.application : "*";
            type = (request.query.type) ? request.query.type : "*";
            wall = (request.query.wall) ? request.query.wall : "*";
            db.query(
                "SELECT * FROM Client.Posts WHERE Application = ? AND Wall_Type = ? AND Wall_Name = ?;",
                [
                    application,
                    type,
                    wall
                ],
                function(error, posts){
                    if(posts.length == 0){
                        cb(posts);
                    }else{
                        repliesDone = false;
                        likesDone = false;
                        commentsDone = false;
                        commentLikesDone = false;
                        repliesLikesDone = false;
                        function PostRecursionComments(posts, length, i){
                            if(posts[i]['DATA'] == undefined){
                                posts[i]['DATA'] = {};
                            }
                            db.query(
                                "SELECT * FROM Client.Comments WHERE Client.Comments.Post_ID = ?",
                                [
                                    posts[i]['ID']
                                ],
                                function(error, comments){
                                    for(i = 0; i < comments.length; i++){
                                        db.query(
                                            "SELECT * FROM Client.Likes WHERE Type = 'Comment' AND TypeID = ?",
                                            [
                                                comments[i]['ID']
                                            ],
                                            function(error, commentLikes){
                                                commentLikesDone = true;
                                                posts[i]['DATA']['Comments'][i]['DATA']['Likes'] = commentLikes;
                                            }
                                        );
                                    }
                                    posts[i]['DATA']['Comments'] = comments;
                                    if(posts.length - 1 == i){
                                        commentsDone = true;
                                    }else{
                                        i++;
                                        PostRecursionComments(posts, posts.length, i);
                                    }
                                }
                            );
                        }
                        PostRecursionComments(posts, posts.length, 0);
                        function CommentsRecursionReplies(comments, length, i, z, posts){
                            if(comments[z]['DATA'] == undefined){
                                comments[z]['DATA'] = {};
                            }
                            db.query(
                                "SELECT * FROM Client.Replies WHERE Client.Replies.Parent_Is_Comment = 1 AND Client.Replies.Parent_ID = ?",
                                [
                                    commentsz[z]['ID']
                                ],
                                function(error, replies){
                                    for(i = 0; i < replies.length; i++){
                                        db.query(
                                            "SELECT * FROM Client.Likes WHERE Type = 'Reply' AND TypeID = ?",
                                            [
                                                replies[i]['ID']
                                            ],
                                            function(error, replyLikes){
                                                replyLikesDone = true;
                                                comments[z]['DATA']['Replies'][i]['DATA']['Likes'] = replyLikes;
                                            }
                                        );
                                    }
                                    comments[z]['DATA']['Replies'] = replies;
                                    if(posts[i]['DATA']['Comments'].length - 1 == z){
                                    }else{
                                        z++;
                                        CommentsRecursionReplies(posts[i]['DATA']['Comments'], posts['DATA']['Comments'].length, i, z, posts);
                                    }
                                }
                            );
                        }
                        for(i = 0; i < posts.length; i++){
                            if(posts[i]['DATA']['Comments']){
                                CommentsRecursionReplies(posts[i]['DATA']['Comments'], posts[i]['DATA']['Comments'].length, i, 0, posts);
                            }
                            repliesDone = true;
                        }
                        function RepliesRecursionReplies(replies, length, i, j, z, posts){
                            if(replies[z]['DATA'] == undefined){
                                replies[z]['DATA'] = {};
                            }
                            /*  truth tables? */
                            db.query(
                                "SELECT * FROM Client.Replies WHERE Client.Replies.Parent_Is_Comment = 0 AND Client.Replies.Parent_ID = ?",
                                [
                                    posts[i]['DATA']['Comments'][j]['Replies'][z]['ID']
                                ],
                                function(error, replies){
                                    if(!posts[i]['DATA']['Comments'][j]['Replies'][z]['DATA']){
                                        posts[i]['DATA']['Comments'][j]['Replies'][z]['DATA'] = {};
                                    }
                                    posts[i]['DATA']['Comments'][j]['Replies'][z]['DATA']['Replies'] = replies;
                                    if(posts[i]['DATA']['Comments'][j]['Replies'].length - z == 0){
                                        /* enumerator and properties... */
                                        repliesRepliesDone = true;
                                    }else{
                                        z++;
                                        RepliesRecursionReplies(replies, replies.length, i, j, z, posts);
                                    }
                                }
                            );
                        }
                        for(i = 0; i < posts[i].length; i++){
                            for(j = 0; j < posts[i]['DATA']['Comments'].length; j++){
                                RepliesRecursionReplies(posts[i]['DATA']['Comments'][j]['Replies'], posts[i]['DATA']['Comments'][j]['Replies'].length, i, j, 0, posts);
                            }
                        }
                        function PostRecursionLikes(posts, length, i){
                            if(posts[i]['DATA'] == undefined){
                                posts[i]['DATA'] = {};
                            }
                            db.query(
                                "SELECT * FROM Client.Likes WHERE Type = 'Post' AND TypeID = ?",
                                [
                                    posts[i]['ID']
                                ],
                                function(error, likes){
                                    post['DATA']['Likes'] = likes;
                                    if(posts.length - 1 == i){
                                        likesDone = true;
                                    }else{
                                        i++;
                                        PostRecursionLikes(posts, posts.length, i);
                                    }
                                }
                            );
                        }
                        PostRecursionLikes(posts, posts.length, 0);
                        function callback(data){
                            if(commentsDone && repliesDone && likesDone && commentLikesDone && replikesLikesDone){
                                cb(data);
                            }else{
                                setTimeout(function(){
                                    callback(data)
                                }, 1);
                            }
                        }
                        callback(posts);
                    }
                }
            );
        }


问:
Angular Drag and Drop - can't drop items to the target location
I'm having a problem with the my Angular 9 project where the drag and drop functionality doesn't work consistently. Whenever I try to drag an object to its destination location, the drop never completes. Most of the time the object returns back to its original location or it moves to another position either before or after the target position where I want to move the object to. Here is my code:

```<code><div class="col-sm-12">

          <div cdkDropList class="example-list cdk-drop-list-receiving" (cdkDropListDropped)="drop($event)">
            <ng-container *ngFor="let word of Words; let i = index;">
                <div class="row" *ngIf="((i % 2) == 0)"  style="margin-right: 0px; margin-left: 0px;" >
                  <div class="col-sm-1 text-center" style="padding: 20px 10px; border: 1px solid black"> {{ i }}</div>
                  <div class="col-sm-5 text-center example-box"  style="border: 1px solid black" cdkDrag ><div class="example-custom-placeholder" *cdkDragPlaceholder></div>{{ Words[i].Title }}</div>
                  <div class="col-sm-1 text-center" style="padding: 20px 10px; border: 1px solid black"> {{ i+1 }}</div>
                  <div class="col-sm-5 text-center example-box" *ngIf="Words[i+1] !== undefined" style="border: 1px solid black" cdkDrag ><div class="example-custom-placeholder" *cdkDragPlaceholder></div>{{ Words[i+1].Title }}</div>
                </div>

            </ng-container>
          </div>
        </div>
</code>```

Here is a link to the app live so you can visualize the issues that I'm seeing: [UPDATE] https://stackblitz.com/edit/drag-and-drop-issue

Thank you in advance

答:
Cdk drop list either work vertically or horizontally. In your code indexes were messed up. What you really needed was a CdkDropListGroup to let it operate both way. I have created an code for same with your layout. I have made the same array behave like two different cdkdroplist inside same cdkDropListGroup.

Working Stackblitz :- https://stackblitz.com/edit/drag-and-drop-issue-gw4epd

HTML

```<code><div cdkDropListGroup class="row example-list cdk-drop-list-receiving">
    <div class="row">
        <div class="col-6 group" cdkDropList id="listOne" (cdkDropListDropped)="drop($event)" [cdkDropListConnectedTo]="['listTwo']">
            <ng-container *ngFor="let word of Words; let i=index">
                <div *ngIf="(i%2)==0" class="row" style="margin-right: 0px; margin-left: 0px;">
                    <div class="col-sm-2 text-center" style="padding: 20px 10px; border: 1px solid black"> {{ i }}
                    </div>
                    <div class="col-sm-10 text-center example-box" style="border: 1px solid black" cdkDrag>
                        <div class="example-custom-placeholder col-sm-10" *cdkDragPlaceholder></div>
                        {{ Words[i].Title }}
                    </div>
                </div>
            </ng-container>
        </div>
        <div class="col-6 group" cdkDropList id="listTwo" (cdkDropListDropped)="drop($event)" [cdkDropListConnectedTo]="['listOne']">
            <ng-container *ngFor="let word of Words; let i=index">
                <div *ngIf="(i%2)!==0" class="row" style="margin-right: 0px; margin-left: 0px;">
                    <div class="col-sm-2 text-center" style="padding: 20px 10px; border: 1px solid black"> {{ i }}
                    </div>
                    <div class="col-sm-10 text-center example-box" style="border: 1px solid black" cdkDrag>
                        <div class="example-custom-placeholder col-sm-10" *cdkDragPlaceholder></div>
                        {{ Words[i].Title }}
                    </div>
                </div>
            </ng-container>
        </div>
    </div>
</div>

<!-- Copyright 2019 Google LLC. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license -->
</code>```

TS :-

```<code>import {Component} from '@angular/core';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';

/**
 * @title Drag&Drop custom placeholder
 */
@Component({
  selector: 'cdk-drag-drop-custom-placeholder-example',
  templateUrl: 'cdk-drag-drop-custom-placeholder-example.html',
  styleUrls: ['cdk-drag-drop-custom-placeholder-example.css'],
})
export class CdkDragDropCustomPlaceholderExample {
  Words = [
    {Title: 'Test A'},
    {Title: 'Test B'},
    {Title: 'Test C'},
    {Title: 'Test D'},
    {Title: 'Test E'},
    {Title: 'Test F'},
    {Title: 'Test G'},
    {Title: 'Test H'},
    {Title: 'Test I'},
    {Title: 'Test J'},
    {Title: 'Test K'},
    {Title: 'Test L'},
    {Title: 'Test M'},
    {Title: 'Test N'},
    {Title: 'Test O'}

  ];

  drop(event: CdkDragDrop<string[]>) {
    console.log(event);
    if (event.previousContainer === event.container) {
      console.log("same Container");
      if(event.previousContainer.id === 'listOne'){
        moveItemInArray(this.Words, event.previousIndex*2, event.currentIndex*2);
      } else {
        moveItemInArray(this.Words, (event.previousIndex*2)+1, (event.currentIndex*2)+1)
      }
    } else {
      console.log("different Container");
      var connectedTo = event.previousContainer.connectedTo.toString();
      console.log(connectedTo)
      if(connectedTo ==='listOne') {
        console.log('list2');
        moveItemInArray(this.Words, (event.previousIndex*2)+1, (event.currentIndex*2));
      } else {
        console.log('list1');
        moveItemInArray(this.Words, (event.previousIndex*2), (event.currentIndex*2)+1);
      }
    }
  }
}

/**  Copyright 2019 Google LLC. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license */
</code>```

CSS :-

```<code>.example-list {
  width: 500px;
  max-width: 100%;
  border: solid 1px #ccc;
  min-height: 60px;
  display: block;
  background: white;
  border-radius: 4px;
  overflow: hidden;
}

.group{
  padding: 0;
  margin: 0;
}

.example-box {
  padding: 20px 10px;
  border-bottom: solid 1px #ccc;
  color: rgba(0, 0, 0, 0.87);
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  cursor: move;
  background: white;
  font-size: 14px;
}

.cdk-drag-preview {
  box-sizing: border-box;
  border-radius: 4px;
  box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
              0 8px 10px 1px rgba(0, 0, 0, 0.14),
              0 3px 14px 2px rgba(0, 0, 0, 0.12);
}

.cdk-drag-animating {
  transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}

.example-box:last-child {
  border: none;
}

.example-list.cdk-drop-list-dragging .example-box:not(.cdk-drag-placeholder) {
  transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}

.example-custom-placeholder {
  background: #ccc;
  border: dotted 3px #999;
  min-height: 60px;
  transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}
</code>```

Body:
I'm having a problem with the my Angular 9 project where the drag and drop functionality doesn't work consistently. Whenever I try to drag an object to its destination location, the drop never completes. Most of the time the object returns back to its original location or it moves to another position either before or after the target position where I want to move the object to. Here is my code:

            <ng-container *ngFor="let word of Words; let i = index;">

 {{ i }}

{{ Words[i].Title }}

 {{ i+1 }}

{{ Words[i+1].Title }}

            </ng-container>

Here is a link to the app live so you can visualize the issues that I'm seeing: [UPDATE] https://stackblitz.com/edit/drag-and-drop-issue

Thank you in advance

Body:
Cdk drop list either work vertically or horizontally. In your code indexes were messed up. What you really needed was a CdkDropListGroup to let it operate both way. I have created an code for same with your layout. I have made the same array behave like two different cdkdroplist inside same cdkDropListGroup.

Working Stackblitz :- https://stackblitz.com/edit/drag-and-drop-issue-gw4epd

HTML

<div cdkDropListGroup class="row example-list cdk-drop-list-receiving">
    <div class="row">
        <div class="col-6 group" cdkDropList id="listOne" (cdkDropListDropped)="drop($event)" [cdkDropListConnectedTo]="['listTwo']">
            <ng-container *ngFor="let word of Words; let i=index">
                <div *ngIf="(i%2)==0" class="row" style="margin-right: 0px; margin-left: 0px;">
                    <div class="col-sm-2 text-center" style="padding: 20px 10px; border: 1px solid black"> {{ i }}
                    </div>
                    <div class="col-sm-10 text-center example-box" style="border: 1px solid black" cdkDrag>
                        <div class="example-custom-placeholder col-sm-10" *cdkDragPlaceholder></div>
                        {{ Words[i].Title }}
                    </div>
                </div>
            </ng-container>
        </div>
        <div class="col-6 group" cdkDropList id="listTwo" (cdkDropListDropped)="drop($event)" [cdkDropListConnectedTo]="['listOne']">
            <ng-container *ngFor="let word of Words; let i=index">
                <div *ngIf="(i%2)!==0" class="row" style="margin-right: 0px; margin-left: 0px;">
                    <div class="col-sm-2 text-center" style="padding: 20px 10px; border: 1px solid black"> {{ i }}
                    </div>
                    <div class="col-sm-10 text-center example-box" style="border: 1px solid black" cdkDrag>
                        <div class="example-custom-placeholder col-sm-10" *cdkDragPlaceholder></div>
                        {{ Words[i].Title }}
                    </div>
                </div>
            </ng-container>
        </div>
    </div>
</div>

<!-- Copyright 2019 Google LLC. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license -->

TS :-

import {Component} from '@angular/core';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';

/**
 * @title Drag&Drop custom placeholder
 */
@Component({
  selector: 'cdk-drag-drop-custom-placeholder-example',
  templateUrl: 'cdk-drag-drop-custom-placeholder-example.html',
  styleUrls: ['cdk-drag-drop-custom-placeholder-example.css'],
})
export class CdkDragDropCustomPlaceholderExample {
  Words = [
    {Title: 'Test A'},
    {Title: 'Test B'},
    {Title: 'Test C'},
    {Title: 'Test D'},
    {Title: 'Test E'},
    {Title: 'Test F'},
    {Title: 'Test G'},
    {Title: 'Test H'},
    {Title: 'Test I'},
    {Title: 'Test J'},
    {Title: 'Test K'},
    {Title: 'Test L'},
    {Title: 'Test M'},
    {Title: 'Test N'},
    {Title: 'Test O'}

  ];

  drop(event: CdkDragDrop<string[]>) {
    console.log(event);
    if (event.previousContainer === event.container) {
      console.log("same Container");
      if(event.previousContainer.id === 'listOne'){
        moveItemInArray(this.Words, event.previousIndex*2, event.currentIndex*2);
      } else {
        moveItemInArray(this.Words, (event.previousIndex*2)+1, (event.currentIndex*2)+1)
      }
    } else {
      console.log("different Container");
      var connectedTo = event.previousContainer.connectedTo.toString();
      console.log(connectedTo)
      if(connectedTo ==='listOne') {
        console.log('list2');
        moveItemInArray(this.Words, (event.previousIndex*2)+1, (event.currentIndex*2));
      } else {
        console.log('list1');
        moveItemInArray(this.Words, (event.previousIndex*2), (event.currentIndex*2)+1);
      }
    }
  }
}

/**  Copyright 2019 Google LLC. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at http://angular.io/license */

CSS :-

.example-list {
  width: 500px;
  max-width: 100%;
  border: solid 1px #ccc;
  min-height: 60px;
  display: block;
  background: white;
  border-radius: 4px;
  overflow: hidden;
}

.group{
  padding: 0;
  margin: 0;
}

.example-box {
  padding: 20px 10px;
  border-bottom: solid 1px #ccc;
  color: rgba(0, 0, 0, 0.87);
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  cursor: move;
  background: white;
  font-size: 14px;
}

.cdk-drag-preview {
  box-sizing: border-box;
  border-radius: 4px;
  box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
              0 8px 10px 1px rgba(0, 0, 0, 0.14),
              0 3px 14px 2px rgba(0, 0, 0, 0.12);
}

.cdk-drag-animating {
  transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}

.example-box:last-child {
  border: none;
}

.example-list.cdk-drop-list-dragging .example-box:not(.cdk-drag-placeholder) {
  transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}

.example-custom-placeholder {
  background: #ccc;
  border: dotted 3px #999;
  min-height: 60px;
  transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}


问:
HtmlAgilityPack Issue in reading some sites
I am having an issue with reading some sites using HtmlAgilityPack. for example https://faranesh.com and https://cbi.ir

Problem: urlResponse return ="\r\n\r\n\r\n

I tried this code but it return null values only. I want to access the site code but I can't please help me.

C# reading code is:

```<code>    {
        var url = @"https://www.cbi.ir/";

        HtmlWeb web = new HtmlWeb();

        var Doc = web.Load(url);

        var node = Doc.DocumentNode.SelectSingleNode("//title");

        Console.WriteLine($"Title is {node.InnerText}");
    }
</code>```

答:
It looks like the examples you're sending are Single Page Applications or highly JavaScript based. The first example returns the following HTML:

```<code><!DOCTYPE html>
<html lang="fa-IR">
<head>
<script type="9055e798d34ceda9b8089665-text/javascript">(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
            new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','GTM-MSQZK3S');</script>
<script type="9055e798d34ceda9b8089665-text/javascript">
        !function (t, e, n) {
            t.yektanetAnalyticsObject = n, t[n] = t[n] || function () {
                t[n].q.push(arguments)
            }, t[n].q = t[n].q || [];
            var a = new Date, r = a.getFullYear().toString() + "0" + a.getMonth() + "0" + a.getDate() + "0" + a.getHours(),
                    c = e.getElementsByTagName("script")[0], s = e.createElement("script");
            s.id = "ua-script-yn-2448-adv"; s.dataset.analyticsobject = n;
            s.async = 1; s.type = "text/javascript";
            s.src = "https://cdn.yektanet.com/rg_woebegone/scripts_v2/yn-2448-adv/rg.complete.js?v=" + r, c.parentNode.insertBefore(s, c)
        }(window, document, "yektanet");
    </script>
<base href="/">
<meta charset="UTF-8">
<meta name="theme-color" content="#2e9ed8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="language" content="fa" />
<link rel="apple-touch-icon" sizes="180x180" href="./apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="./favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="./favicon-16x16.png">
<link rel="manifest" href="./site.webmanifest">
<link rel="mask-icon" href="./safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#ffc40d">
<meta name="theme-color" content="#ffffff">
<meta name="google-signin-scope" content="profile email">
<link rel="search" type="application/opensearchdescription+xml" title="Faranesh" href="./opensearch.xml" />
<link rel="manifest" href="./manifest.json" />

</code>```

As you can see there is no body and no title tag initially.

If you want to parse the content, including the JavaScript generated DOM elements you'll need to automate a Headless browser instead of parsing the raw HTML returned by the server.

https://github.com/dhamaniasad/HeadlessBrowsers

For example, try:

https://github.com/hardkoded/puppeteer-sharp

Not tested locally, but from the examples in their repository, something along these lines:

```<code>await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
    Headless = true
});
var page = await browser.NewPageAsync();
await page.GoToAsync("https://faranesh.com/");

var title = @"document.title";
Console.WriteLine($"Title: {title}");
</code>```

Body:
I am having an issue with reading some sites using HtmlAgilityPack. for example https://faranesh.com and https://cbi.ir

Problem: urlResponse return ="\r\n\r\n\r\n

I tried this code but it return null values only. I want to access the site code but I can't please help me.

C# reading code is:

    {
        var url = @"https://www.cbi.ir/";

        HtmlWeb web = new HtmlWeb();

        var Doc = web.Load(url);

        var node = Doc.DocumentNode.SelectSingleNode("//title");

        Console.WriteLine($"Title is {node.InnerText}");
    }

Body:
It looks like the examples you're sending are Single Page Applications or highly JavaScript based. The first example returns the following HTML:

<!DOCTYPE html>
<html lang="fa-IR">
<head>
<script type="9055e798d34ceda9b8089665-text/javascript">(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
            new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','GTM-MSQZK3S');</script>
<script type="9055e798d34ceda9b8089665-text/javascript">
        !function (t, e, n) {
            t.yektanetAnalyticsObject = n, t[n] = t[n] || function () {
                t[n].q.push(arguments)
            }, t[n].q = t[n].q || [];
            var a = new Date, r = a.getFullYear().toString() + "0" + a.getMonth() + "0" + a.getDate() + "0" + a.getHours(),
                    c = e.getElementsByTagName("script")[0], s = e.createElement("script");
            s.id = "ua-script-yn-2448-adv"; s.dataset.analyticsobject = n;
            s.async = 1; s.type = "text/javascript";
            s.src = "https://cdn.yektanet.com/rg_woebegone/scripts_v2/yn-2448-adv/rg.complete.js?v=" + r, c.parentNode.insertBefore(s, c)
        }(window, document, "yektanet");
    </script>
<base href="/">
<meta charset="UTF-8">
<meta name="theme-color" content="#2e9ed8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="language" content="fa" />
<link rel="apple-touch-icon" sizes="180x180" href="./apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="./favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="./favicon-16x16.png">
<link rel="manifest" href="./site.webmanifest">
<link rel="mask-icon" href="./safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#ffc40d">
<meta name="theme-color" content="#ffffff">
<meta name="google-signin-scope" content="profile email">
<link rel="search" type="application/opensearchdescription+xml" title="Faranesh" href="./opensearch.xml" />
<link rel="manifest" href="./manifest.json" />

As you can see there is no body and no title tag initially.

If you want to parse the content, including the JavaScript generated DOM elements you'll need to automate a Headless browser instead of parsing the raw HTML returned by the server.

https://github.com/dhamaniasad/HeadlessBrowsers

For example, try:

https://github.com/hardkoded/puppeteer-sharp

Not tested locally, but from the examples in their repository, something along these lines:

await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
    Headless = true
});
var page = await browser.NewPageAsync();
await page.GoToAsync("https://faranesh.com/");

var title = @"document.title";
Console.WriteLine($"Title: {title}");


问:
how to convert a binary string 128bit to decimal string in c++?
```<code>void convertBinaryToDecimal(std::string BinarySrc, std::string& DecimalDest)
{

}
</code>```

I need to convert a string binary length 128 bit to string Decimal

答:
The algorithm is simple:

using a 128-bit unsigned variable v initialized to 0;

for each bit read from BinarySrc, v = v + v + bit;

then produce decimal digits: digit = '0' + v % 10 while (v /= 10) != 0.

finally, reverse the string of decimal digits.

This should be easy to convert to code.

Body:
void convertBinaryToDecimal(std::string BinarySrc, std::string& DecimalDest)
{

}

I need to convert a string binary length 128 bit to string Decimal


问:
Clear previous output of widget every time it runs
I would like to clear the previous output when the widget is rerun.

for example

```<code>from IPython.display import display, clear_output

import ipywidgets as widgets
from datetime import datetime, timedelta
</code>```

```<code>button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):

    # DO SOMETHING #

    out = widgets.Output()
    out.clear_output(wait=True)
    out.append_stdout(f'Ran at {datetime.now()}')
    display(out)

button.on_click(on_button_clicked)
widgets.VBox([button])

</code>```

Every time i click on the RUN button it "appends" the print statement

I also tried this:

```<code>button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):

    # DO SOMETHING #

    out = widgets.Output()
    out.clear_output(wait=True)
    with out:
        print(f'Ran at {datetime.now()}')
    display(out)

button.on_click(on_button_clicked)
widgets.VBox([button])
</code>```

答:
This works</p>

```<code>
from IPython.display import display, clear_output

import ipywidgets as widgets
from datetime import datetime, timedelta

button = widgets.Button(description='RUN',button_style='info')

out = widgets.Output()

@out.capture(clear_output=True)
def on_button_clicked(b):
    # DO SOMETHING #
    print ( f'Ran at {datetime.now()}')

button.on_click(on_button_clicked)
widgets.VBox([button])

</code>```

Body:
I would like to clear the previous output when the widget is rerun.

for example

from IPython.display import display, clear_output

import ipywidgets as widgets
from datetime import datetime, timedelta

button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):

    # DO SOMETHING #

    out = widgets.Output()
    out.clear_output(wait=True)
    out.append_stdout(f'Ran at {datetime.now()}')
    display(out)

button.on_click(on_button_clicked)
widgets.VBox([button])

Every time i click on the RUN button it "appends" the print statement

I also tried this:

button = widgets.Button(description='RUN',button_style='info')

def on_button_clicked(b):

    # DO SOMETHING #

    out = widgets.Output()
    out.clear_output(wait=True)
    with out:
        print(f'Ran at {datetime.now()}')
    display(out)

button.on_click(on_button_clicked)
widgets.VBox([button])

Body:
This works

from IPython.display import display, clear_output

import ipywidgets as widgets
from datetime import datetime, timedelta

button = widgets.Button(description='RUN',button_style='info')

out = widgets.Output()

@out.capture(clear_output=True)
def on_button_clicked(b):
    # DO SOMETHING #
    print ( f'Ran at {datetime.now()}')

button.on_click(on_button_clicked)
widgets.VBox([button])


问:
Avoiding duplicate deletion in python regex
I am removing lines from a bunch of txt files using regex using Python; however, I came across a case where it sometimes does a duplicate deletion if the line contains a string fairly similar to the first one

```<code>s = 'market.fruit.apple'
</code>```

The txt file might contain the following lines

```<code>market.fruit.apple
market.fruit.apple.all
</code>```

But if I run

```<code>open_file = open('test.txt', 'r')
read_file = open_file.read()
r = re.compile(r"(?<!\S){0}.*(?:[\r\n]\s*)?".format(s))
read_file = r.sub('',read_file)
write_file = open('test.txt', 'w')
write_file.write(read_file)
</code>```

it removes both market.fruit.apple and market.fruit.apple.all when only the first one should be removed. How do I avoid it? I tried setting the count parameter to 1 but that didn't do anything. I was thinking of doing a string similarity between the strings and use a different regex if it matches the right condition but I figured this might be unneccesary overhead if I scale this up.

Edit: Corrected some typos in the example above, can be repro in regex101.com/r/q7qWVh/1

答:
You may use

```<code>r"(?<!\S){0}[\s=].*(?:[\r\n]\s*)?".format(re.escape(s))
</code>```

Note the use re.escape, it is necessary since you are using a variable representing literal text into the regex pattern.

If your variable is market.fruit.apple, your regex will look like

```<code>(?<!\S)market\.fruit\.apple[\s=].*(?:[\r\n]\s*)?
</code>```

See the regex demo

Details

(?<!\S) - a left-hand whitespace boundary

market\.fruit\.apple - the keyword

[\s=] - a whitespace or = char

.* - any 0 or more chars other than line break chars as many as possible

(?:[\r\n]\s*)? - an optional sequence of a CR or LF line break char and then any 0 or more whitespaces.

Body:
I am removing lines from a bunch of txt files using regex using Python; however, I came across a case where it sometimes does a duplicate deletion if the line contains a string fairly similar to the first one

s = 'market.fruit.apple'

The txt file might contain the following lines

market.fruit.apple
market.fruit.apple.all

But if I run

open_file = open('test.txt', 'r')
read_file = open_file.read()
r = re.compile(r"(?<!\S){0}.*(?:[\r\n]\s*)?".format(s))
read_file = r.sub('',read_file)
write_file = open('test.txt', 'w')
write_file.write(read_file)

it removes both market.fruit.apple and market.fruit.apple.all when only the first one should be removed. How do I avoid it? I tried setting the count parameter to 1 but that didn't do anything. I was thinking of doing a string similarity between the strings and use a different regex if it matches the right condition but I figured this might be unneccesary overhead if I scale this up.

Edit: Corrected some typos in the example above, can be repro in regex101.com/r/q7qWVh/1

Body:
You may use

r"(?<!\S){0}[\s=].*(?:[\r\n]\s*)?".format(re.escape(s))

Note the use re.escape, it is necessary since you are using a variable representing literal text into the regex pattern.

If your variable is market.fruit.apple, your regex will look like

(?<!\S)market\.fruit\.apple[\s=].*(?:[\r\n]\s*)?

See the regex demo

Details

(?<!\S) - a left-hand whitespace boundary

market\.fruit\.apple - the keyword

[\s=] - a whitespace or = char

.* - any 0 or more chars other than line break chars as many as possible

(?:[\r\n]\s*)? - an optional sequence of a CR or LF line break char and then any 0 or more whitespaces.


问:
import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database";
i had problem to

```<code>import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database";
</code>```

i imported AngularFireDatabase but FirebaseListObservable was under a red line after searching
this post helped me resolve my problem
Getting an error: "Has no exported member AngularFire, AuthProviders, AUthMethods, FirebaseListObservable" in AngularFire2?

```<code>import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database-deprecated";
</code>```

but when i compile i get and it cant help i dont know what to do where searching ect
core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: No provider for AngularFireDatabase!
Error: No provider for AngularFireDatabase!

"angularfire2": "^5.0.0-rc.2",
"core-js": "^2.4.1",
"firebase": "^4.5.0",

答:
You can't use FirebaseListObservable in current version of angularfire2.

It worked in old version of angularfire2 like 4.0.0-rc.1.

So, install it and it will work totally fine (in terminal):

npm i angularfire2@4.0.0-rc.1

and import:

```<code>import {AngularFireDatabase,FirebaseListObservable} from 'angularfire2/database';

import { AngularFireAuthModule, AngularFireAuth } from 'angularfire2/auth';
</code>```

Body:
i had problem to

import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database";

i imported AngularFireDatabase but FirebaseListObservable was under a red line after searching
this post helped me resolve my problem
Getting an error: "Has no exported member AngularFire, AuthProviders, AUthMethods, FirebaseListObservable" in AngularFire2?

import { AngularFireDatabase, FirebaseListObservable } from "angularfire2/database-deprecated";

but when i compile i get and it cant help i dont know what to do where searching ect
core.es5.js:1020 ERROR Error: Uncaught (in promise): Error: No provider for AngularFireDatabase!
Error: No provider for AngularFireDatabase!

"angularfire2": "^5.0.0-rc.2",
"core-js": "^2.4.1",
"firebase": "^4.5.0",

Body:
You can't use FirebaseListObservable in current version of angularfire2.

It worked in old version of angularfire2 like 4.0.0-rc.1.

So, install it and it will work totally fine (in terminal):

npm i angularfire2@4.0.0-rc.1

and import:

import {AngularFireDatabase,FirebaseListObservable} from 'angularfire2/database';

import { AngularFireAuthModule, AngularFireAuth } from 'angularfire2/auth';


问:
How to filter on entityBundle using graphql query in drupal
I am using the GraphQl api for Drupal 8. Unfortunately I don't know either technology particularly well.

I have the following query

```<code>query {
  nodeQuery (offset: 0, limit: 23) {
    entities {
      entityLabel
      entityBundle
      entityId
    }
    count
  }
}
</code>```

which returns stuff that looks like this

```<code>{
  "data": {
    "nodeQuery": {
      "entities": [
        {
          "entityLabel": "Frontpage",
          "entityBundle": "section_page",
          "entityId": "20"
        },
      ....
</code>```

Some of the entities returned are not section_page entities however, so I would like to do a filter that allows me to filter them out.

I have done the following

```<code>query {
  nodeQuery (offset: 0, limit: 23,filter: {conditions: {field: "entityBundle", value: "section_page", operator: EQUAL}}) {
    entities {
      entityLabel
      entityBundle
      entityId
    }
    count
  }
}
</code>```

which doesn't work and I wouldn't really expect it to that much because obviously entityBundle is not a child of the node, so I should somehow filter on entityBundle inside entities. Haven't figured out how to do it.

The error I get when I run that query is

```<code>{
  "errors": [
    {
      "message": "Internal server error",
      "category": "internal",
      "locations": [
        {
          "line": 32,
          "column": 5
        }
      ],
      "path": [
        "nodeQuery",
        "entities"
      ]
    },
    {
      "message": "Internal server error",
      "category": "internal",
      "locations": [
        {
          "line": 37,
          "column": 5
        }
      ],
      "path": [
        "nodeQuery",
        "count"
      ]
    }
  ],
  "data": {
    "nodeQuery": {
      "entities": null,
      "count": null
    }
  }
}
</code>```

答:
Ok, figured it out, surprisingly

```<code>query {
  nodeQuery (offset: 0, limit: 23, filter: {conditions: [
    {operator: EQUAL, field: "type", value: ["section_page"]}]}) {
    entities {
      entityLabel
      entityBundle
      entityId
    }
    count
  }
}
</code>```

since it seems that the type of the field was also the same as the entityBundle value.

Body:
I am using the GraphQl api for Drupal 8. Unfortunately I don't know either technology particularly well.

I have the following query

query {
  nodeQuery (offset: 0, limit: 23) {
    entities {
      entityLabel
      entityBundle
      entityId
    }
    count
  }
}

which returns stuff that looks like this

{
  "data": {
    "nodeQuery": {
      "entities": [
        {
          "entityLabel": "Frontpage",
          "entityBundle": "section_page",
          "entityId": "20"
        },
      ....

Some of the entities returned are not section_page entities however, so I would like to do a filter that allows me to filter them out.

I have done the following

query {
  nodeQuery (offset: 0, limit: 23,filter: {conditions: {field: "entityBundle", value: "section_page", operator: EQUAL}}) {
    entities {
      entityLabel
      entityBundle
      entityId
    }
    count
  }
}

which doesn't work and I wouldn't really expect it to that much because obviously entityBundle is not a child of the node, so I should somehow filter on entityBundle inside entities. Haven't figured out how to do it.

The error I get when I run that query is

{
  "errors": [
    {
      "message": "Internal server error",
      "category": "internal",
      "locations": [
        {
          "line": 32,
          "column": 5
        }
      ],
      "path": [
        "nodeQuery",
        "entities"
      ]
    },
    {
      "message": "Internal server error",
      "category": "internal",
      "locations": [
        {
          "line": 37,
          "column": 5
        }
      ],
      "path": [
        "nodeQuery",
        "count"
      ]
    }
  ],
  "data": {
    "nodeQuery": {
      "entities": null,
      "count": null
    }
  }
}

Body:
Ok, figured it out, surprisingly

query {
  nodeQuery (offset: 0, limit: 23, filter: {conditions: [
    {operator: EQUAL, field: "type", value: ["section_page"]}]}) {
    entities {
      entityLabel
      entityBundle
      entityId
    }
    count
  }
}

since it seems that the type of the field was also the same as the entityBundle value.


问:
Different sort-by by one key Clojure
Hey I have this Code but I would like to reverse only the :a key.

```<code>(sort-by (juxt :a :b) [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}])
;;=> [{:a 1 :b 2} {:a 1 :b 3} {:a 2 :b 1}]
</code>```

I tried this but this was in the wrong order.

```<code>(sort-by (juxt :a :b) #(compare %2 %1)  [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}])
;;=> ({:a 2, :b 1} {:a 1, :b 3} {:a 1, :b 2})
</code>```

I would like to get.

```<code>;;=> ({:a 2, :b 1} {:a 1, :b 2} {:a 1, :b 3})
</code>```

Any Ideas?
Can I do this also in juxt?

Title: Different sort-by by one key Clojure

Body:
Hey I have this Code but I would like to reverse only the :a key.

(sort-by (juxt :a :b) [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}])
;;=> [{:a 1 :b 2} {:a 1 :b 3} {:a 2 :b 1}]

I tried this but this was in the wrong order.

(sort-by (juxt :a :b) #(compare %2 %1)  [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}])
;;=> ({:a 2, :b 1} {:a 1, :b 3} {:a 1, :b 2})

I would like to get.

;;=> ({:a 2, :b 1} {:a 1, :b 2} {:a 1, :b 3})

Any Ideas?
Can I do this also in juxt?

Body: (sort-by (juxt (comp - :a) :b) [{:a 1 :b 3} {:a 1 :b 2} {:a 2 :b 1}])


问:
Unable to show image in usercontrol
I am facing an issue since 2 days, I have a user control which simply has  I have Images saved in my project. I have provided proper path to it and still it is not showing that image. I used Chrome's developer's tool to inspect the issue and it give me

```<code>src="/images/Uploads/home_banner1.jpg"
</code>```

when I right clicked on scr and opened link in new tab, url looked like  localhost/images/Uploads/home_banner1.jpg that means it is trying to find image in root's images/.... folder, right? I am sure I have an image there with the same name but still webpage says,"The resource cannot be found." means 404 error. I removed image name from url and pressed enter and it shows all files in that folder, even after clicking file under directory it still give 404 error, what is this, how to solve, did any one came across it? I ahve lot of questions in my mind, please help me solve this.

EDIT

I have solved it ('compromised' would be better word rather 'solved'). I placed same images in different folder and its running fine, It was never an issue with security of that folder means problem must be something else. I know it is tedious to rectify this but still if someone faced and rectified the same, you could share how you did so. I am getting more curious to find out why changing folder did work for me?

Thanks all.

答:
Sounds like you should be using an Image control:</p>

```<code><asp:Image ID="myimage" runat="server" ImageURL="~/Uploads/home_banner1.jpg" />
</code>```

Title: Unable to show image in usercontrol

Body:
I am facing an issue since 2 days, I have a user control which simply has  I have Images saved in my project. I have provided proper path to it and still it is not showing that image. I used Chrome's developer's tool to inspect the issue and it give me

src="/images/Uploads/home_banner1.jpg"

when I right clicked on scr and opened link in new tab, url looked like  localhost/images/Uploads/home_banner1.jpg that means it is trying to find image in root's images/.... folder, right? I am sure I have an image there with the same name but still webpage says,"The resource cannot be found." means 404 error. I removed image name from url and pressed enter and it shows all files in that folder, even after clicking file under directory it still give 404 error, what is this, how to solve, did any one came across it? I ahve lot of questions in my mind, please help me solve this.

EDIT

I have solved it ('compromised' would be better word rather 'solved'). I placed same images in different folder and its running fine, It was never an issue with security of that folder means problem must be something else. I know it is tedious to rectify this but still if someone faced and rectified the same, you could share how you did so. I am getting more curious to find out why changing folder did work for me?

Thanks all.

Body:
Sounds like you should be using an Image control:

<asp:Image ID="myimage" runat="server" ImageURL="~/Uploads/home_banner1.jpg" />


问:
shinyproxy: how to bypass login page feature to avoid logging twice?
I already have a login page in my organization which access users' ID and password from HR system (see below).

My question is: how can I bypass the built-in login feature of shinyproxy and the navbar above my app(see picture below)?

Thanks for any suggestion and comment.

答:
I find the solution as follows:

Just set authentication: none and hide-navbar: true in proxy in application.yml, and that's it.

```<code>proxy:
  title: Standalone Docker Engine with euler Example
  port: 8080
  authentication: none
  hide-navbar: true
</code>```

Body:
I find the solution as follows:

Just set authentication: none and hide-navbar: true in proxy in application.yml, and that's it.

proxy:
  title: Standalone Docker Engine with euler Example
  port: 8080
  authentication: none
  hide-navbar: true


问:
Is it protocol abuse to report server-side errors through the HTTP status?
I noticed that ColdFusion (version 8 at least) returns the HTTP status code 500 (internal server error) when an uncaught exception occurs in a CFML page. Is this kind of behavior abusing the HTTP status codes, or is it, on the opposite, a nice behavior I should try to reproduce for my other, non-ColdFusion app?

答: This is a nice behavior. Especially if you are creating services. Applications consuming your end points can simply check the HTTP status to know if there is an error. Typically, you may also include some text about the error in the body.</p>


问:
getting this TypeError: is_valid() missing 1 required positional argument: 'self'
i am getting the typeError:
is_valid() missing 1 required positional argument: 'self'

please make me correct where i have done the mistake

```<code>def register(request):
registered = False

if request.method == "POST":
    user_form = UserForm(request.POST)
    profile_form = UserProfileInfoForm(request.POST, request.FILES)

    if user_form.is_valid() and UserProfileInfoForm.is_valid():
        user = user_form.save()
        user.set_password(user.password)
        user.save()

        profile = profile_form.save(commit=False)
        profile.user = user

        if 'profile_pic' in request.FILES:
            profile.profile_pic = request.FILES['profile_pic']

        profile.save()
        registered = True

    else:
        print(user_form.errors, profile_form.errors)

else:
    user_form = UserForm()
    profile_form = UserProfileInfoForm()

return render(request, 'basic_app/registration.html',
              {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})
</code>```

答:
You forget to take the instance of class. But, you used class. So, do this:

```<code>if user_form.is_valid() and profile_form.is_valid():
</code>```

Body:
i am getting the typeError:
is_valid() missing 1 required positional argument: 'self'

please make me correct where i have done the mistake

def register(request):
registered = False

if request.method == "POST":
    user_form = UserForm(request.POST)
    profile_form = UserProfileInfoForm(request.POST, request.FILES)

    if user_form.is_valid() and UserProfileInfoForm.is_valid():
        user = user_form.save()
        user.set_password(user.password)
        user.save()

        profile = profile_form.save(commit=False)
        profile.user = user

        if 'profile_pic' in request.FILES:
            profile.profile_pic = request.FILES['profile_pic']

        profile.save()
        registered = True

    else:
        print(user_form.errors, profile_form.errors)

else:
    user_form = UserForm()
    profile_form = UserProfileInfoForm()

return render(request, 'basic_app/registration.html',
              {'user_form': user_form, 'profile_form': profile_form, 'registered': registered})

Body:
You forget to take the instance of class. But, you used class. So, do this:

if user_form.is_valid() and profile_form.is_valid():


问:
Click on ion-label to toggle the ion-toggle
I am creating a page with ionic 5.

I am making a 'remember me' button with use of <ion-toggle>.

<ion-item>
    <ion-label>remember me</ion-label>
    <ion-toggle class="button"></ion-toggle>
</ion-item>
```

The Ion-toggle is working fine, but I can't toggle it by clicking on the label next to it.

I have tried many solutions.

The link for the API documentation is: https://ionicframework.com/docs/api/toggle

Is there any way to make both the ion toggle and the text clickable?

I'm using ionic angular

Thanks in advance

答:
In ts file :
Declare:

```<code>@ViewChild('mytoggle', {static: true}) mytoggle: IonToggle;

changeToggle() {
    const toggle = this.mytoggle.checked;
    toggle = !toggle;
}
</code>```

In html :

```<code> <ion-item>
            <ion-label (click)="changeToggle()">remember me</ion-label>
            <ion-toggle class="button">
   </ion-toggle>
          </ion-item>
</code>```

Body:
I am creating a page with ionic 5.

I am making a 'remember me' button with use of <ion-toggle>.

<ion-item>
    <ion-label>remember me</ion-label>
    <ion-toggle class="button"></ion-toggle>
</ion-item>

The Ion-toggle is working fine, but I can't toggle it by clicking on the label next to it.

I have tried many solutions.

The link for the API documentation is: https://ionicframework.com/docs/api/toggle

Is there any way to make both the ion toggle and the text clickable?

I'm using ionic angular

Thanks in advance

Body:
In ts file :
Declare:

@ViewChild('mytoggle', {static: true}) mytoggle: IonToggle;

changeToggle() {
    const toggle = this.mytoggle.checked;
    toggle = !toggle;
}

In html :

 <ion-item>
            <ion-label (click)="changeToggle()">remember me</ion-label>
            <ion-toggle class="button">
   </ion-toggle>
          </ion-item>


问:
I don’t know how to explain, but something strange happened with the font in Eclipse ... (screenshots inside)
I have a macBook and I liked the font from IntelliJ IDEA called JetBrainsMono. Using the macOS OS "Fonts" utility, I installed this font. But I use Eclipse most often and therefore I decided to install such a font in Eclipse. I did this through "Eclipse" -> "Preferences" -> "Appearance" -> "Colors and Fonts" -> "Basic" -> "Text Font" -> "Edit". After that, familiar combinations of characters began to look different (don't give an attention to red highlighting):

This is "-> <= !=  <=>" sequence, which was corrected automatically when I typed in. I know that in other text editor it will take a familiar look - in "Notepad" for example. But I want disable this feature in Eclipse. How can I do this?

答: As @howgler said, these are part of the font and this combinations of symbols looks this way in any application.</p>


问:
How to find row at which summed total is greater than a certain amount?
I would like to find the row at which running summed value has reached a specified amount and several criteria have been met (similar to sumifs).

I can't just add a cumulative row, as suggested here:

Count rows until the sum value of the rows is greater than a value

....because I have other criteria to meet in the data, and therefore can't have a running total.

In the following dummy example, I'd like to find the date at which the "Design" project has spent or exceeded $30,000

答:
A late answer, but one that doesn't use a Helper Column.

By using Matrix Multiplication (MMULT) on a TRANSPOSEd array of whether the Row is larger than itself and the list itself, we can produce an array of the Running Total.

```<code>MMULT(--(TRANSPOSE(ROW(D2:D21))<=ROW(D2:D21)), D2:D21)
</code>```

If we shrink this to just the first 3 rows, to demonstrate, then you are making this calculation:

```<code>[[--(2<=2)][--(3<=2)][--(4<=2]     [[10,000]
 [--(2<=3)][--(3<=3)][--(4<=3]  ∙   [ 8,000]
 [--(2<=4)][--(3<=4)][--(4<=4]]     [ 6,000]]
</code>```

Which gives us this:

```<code>[[1][0][0]     [[10,000]    [[10,000]
 [1][1][0]  ∙   [ 8,000]  =  [18,000]
 [1][1][1]]     [ 6,000]]    [24,000]]
</code>```

We can then compare that against the target value as a condition and divide by the result to eliminate values with #DIV0! errors, and use AGGREGATE to get the smallest non-error value

```<code>=AGGREGATE(15, 6, Row(D2:D21) / (MMULT(--(TRANSPOSE(ROW(D2:D21))<=ROW(D2:D21)), D2:D21)<30000), 1)
</code>```

This will give us the first row where the Running Total is >= $30,000

Body:
A late answer, but one that doesn't use a Helper Column.

By using Matrix Multiplication (MMULT) on a TRANSPOSEd array of whether the Row is larger than itself and the list itself, we can produce an array of the Running Total.

MMULT(--(TRANSPOSE(ROW(D2:D21))<=ROW(D2:D21)), D2:D21)

If we shrink this to just the first 3 rows, to demonstrate, then you are making this calculation:

[[--(2<=2)][--(3<=2)][--(4<=2]     [[10,000]
 [--(2<=3)][--(3<=3)][--(4<=3]  ∙   [ 8,000]
 [--(2<=4)][--(3<=4)][--(4<=4]]     [ 6,000]]

Which gives us this:

[[1][0][0]     [[10,000]    [[10,000]
 [1][1][0]  ∙   [ 8,000]  =  [18,000]
 [1][1][1]]     [ 6,000]]    [24,000]]

We can then compare that against the target value as a condition and divide by the result to eliminate values with #DIV0! errors, and use AGGREGATE to get the smallest non-error value

=AGGREGATE(15, 6, Row(D2:D21) / (MMULT(--(TRANSPOSE(ROW(D2:D21))<=ROW(D2:D21)), D2:D21)<30000), 1)

This will give us the first row where the Running Total is >= $30,000


答: No it's not abusing, it's a really nice thing to do. AJAX errors are also reported in the status code, description in the body.</p>

Title: Is it protocol abuse to report server-side errors through the HTTP status?

Body: I noticed that ColdFusion (version 8 at least) returns the HTTP status code 500 (internal server error) when an uncaught exception occurs in a CFML page. Is this kind of behavior abusing the HTTP status codes, or is it, on the opposite, a nice behavior I should try to reproduce for my other, non-ColdFusion app?


问:
Vapor 4 User Authentication and Authorisation
I've recently started with vapor4 (didn't use any older version) and I'm trying to figure out how to implement user authorization and authentication. While i understand basic concepts, having worked with Laravel before I still can't figure out what to do in vapor.

I extended my User with. Ik there is no pw hashing, this is for testing and basic understanding. We'll ignore that for now.

extension User: ModelAuthenticatable
{
    static let usernameKey = \User.$name
    static let passwordHashKey = \User.$password

    func verify(password: String) throws -> Bool {
        return password == self.password
    }
}
```

<p>The problem is i can't find a tutorial how to use this authentication. I just kind of try stuff to get it to work, but to no success. This is in my routes file.</p>

<pre class="lang-swift prettyprint-override"><code>let auth = app.grouped(User.authenticator())
auth.get("sign-in") { req in
    "I'm authenticated"
}
</code>```

My first goal would just be to receive a success or failure answer when trying this route. Ultimately i want to switch to a token based solution but one step at a time.

stuff i read was: https://docs.vapor.codes/4.0/authentication/ and https://theswiftdev.com/all-about-authentication-in-vapor-4/. Anyway i couldn't quit figure it out how to use the described authenticators.

答:
While writing this i finally figured it out. Anyway for people stumbling on this. It's as easy as this:

let auth = app.grouped(User.authenticator(), User.guardMiddleware())
auth.get("sign-in") { req in
    "I'm authenticated"
}
```

Your user-class offers a guardMiddleware by default. You don't have to implement anything else, just use it in your route.

Body:
I've recently started with vapor4 (didn't use any older version) and I'm trying to figure out how to implement user authorization and authentication. While i understand basic concepts, having worked with Laravel before I still can't figure out what to do in vapor.

I extended my User with. Ik there is no pw hashing, this is for testing and basic understanding. We'll ignore that for now.

extension User: ModelAuthenticatable
{
    static let usernameKey = \User.$name
    static let passwordHashKey = \User.$password

    func verify(password: String) throws -> Bool {
        return password == self.password
    }
}

The problem is i can't find a tutorial how to use this authentication. I just kind of try stuff to get it to work, but to no success. This is in my routes file.

let auth = app.grouped(User.authenticator())
auth.get("sign-in") { req in
    "I'm authenticated"
}

My first goal would just be to receive a success or failure answer when trying this route. Ultimately i want to switch to a token based solution but one step at a time.

stuff i read was: https://docs.vapor.codes/4.0/authentication/ and https://theswiftdev.com/all-about-authentication-in-vapor-4/. Anyway i couldn't quit figure it out how to use the described authenticators.

Body:
While writing this i finally figured it out. Anyway for people stumbling on this. It's as easy as this:

let auth = app.grouped(User.authenticator(), User.guardMiddleware())
auth.get("sign-in") { req in
    "I'm authenticated"
}

Your user-class offers a guardMiddleware by default. You don't have to implement anything else, just use it in your route.


问:
How to find each value of one column to the column of other data frame with different lengths of rows?
I have two data frames, Dataframe1 which has three columns: uniquid, poistion1(x, y position) and position 2(x, y position) and Dataframe2 have four columns: Top, Bottom, Left, and Right and each column has (x, y position) values. Both dataframe has a different number of rows.

```<code>    DataFrame1
Unique Id   Position 1    Position 2
  1         (28, 50)        (49, 94)
  2         (18, 181)       (616, 90)
  3         (578, 253)      (15, 182)
  4         (600, 96)       (44, 307)

   DataFrame2
Top         Bottom          Left            Right
(25,30)     (445,25)        (846,52)        (16, 180)
(46, 307)   (569, 264)      (28, 50)        (22, 185)
(36, 201)   (95, 330)                       (49, 94)
(600, 96)   (616, 90)
</code>```

I want to search for each value of the position1 match in which column of Datafram2? Suppose, position1 first value (28,50) available in the Left columns of DataFrame2 then in the dataFrame1, write in the newposition1 for unique id one should write Column name+uniqueID (Ex. “Left1”). If the value is not available in any columns of Dataframe2, then write “NotFound.” And the same for position2.

Expected Output:

```<code>DataFrame1
Unique Id  Position 1    Position 2   newposition1    newposition2
1          (28, 50)      (49, 94)        Left1          Right1
2          (18, 181)     (616, 90)     NotFound         Bottom2
3          (578, 253)    (15, 182)      NotFound        NotFound
4          (600, 96)     (44, 307)        Top4          NotFound
</code>```

I tried couple of solution but didn't work for me.
Any help would be much appreciated. Thank you in advanced.

答:
Use Dataframe.melt on df2 and map the values:

```<code>s = df2.melt().dropna().set_index("value")["variable"]

df["newpos1"] = df["Position 1"].map(s) + df["Unique Id"].astype(str)
df["newpos2"] = df["Position 2"].map(s) + df["Unique Id"].astype(str)

print (df)

   Unique Id  Position 1 Position 2 newpos1  newpos2
0          1    (28, 50)   (49, 94)   Left1   Right1
1          2   (18, 181)  (616, 90)     NaN  Bottom2
2          3  (578, 253)  (15, 182)     NaN      NaN
3          4   (600, 96)  (44, 307)    Top4      NaN
</code>```

Body:
I have two data frames, Dataframe1 which has three columns: uniquid, poistion1(x, y position) and position 2(x, y position) and Dataframe2 have four columns: Top, Bottom, Left, and Right and each column has (x, y position) values. Both dataframe has a different number of rows.

    DataFrame1
Unique Id   Position 1    Position 2
  1         (28, 50)        (49, 94)
  2         (18, 181)       (616, 90)
  3         (578, 253)      (15, 182)
  4         (600, 96)       (44, 307)

   DataFrame2
Top         Bottom          Left            Right
(25,30)     (445,25)        (846,52)        (16, 180)
(46, 307)   (569, 264)      (28, 50)        (22, 185)
(36, 201)   (95, 330)                       (49, 94)
(600, 96)   (616, 90)

I want to search for each value of the position1 match in which column of Datafram2? Suppose, position1 first value (28,50) available in the Left columns of DataFrame2 then in the dataFrame1, write in the newposition1 for unique id one should write Column name+uniqueID (Ex. “Left1”). If the value is not available in any columns of Dataframe2, then write “NotFound.” And the same for position2.

Expected Output:

DataFrame1
Unique Id  Position 1    Position 2   newposition1    newposition2
1          (28, 50)      (49, 94)        Left1          Right1
2          (18, 181)     (616, 90)     NotFound         Bottom2
3          (578, 253)    (15, 182)      NotFound        NotFound
4          (600, 96)     (44, 307)        Top4          NotFound

I tried couple of solution but didn't work for me.
Any help would be much appreciated. Thank you in advanced.

Body:
Use Dataframe.melt on df2 and map the values:

s = df2.melt().dropna().set_index("value")["variable"]

df["newpos1"] = df["Position 1"].map(s) + df["Unique Id"].astype(str)
df["newpos2"] = df["Position 2"].map(s) + df["Unique Id"].astype(str)

print (df)

   Unique Id  Position 1 Position 2 newpos1  newpos2
0          1    (28, 50)   (49, 94)   Left1   Right1
1          2   (18, 181)  (616, 90)     NaN  Bottom2
2          3  (578, 253)  (15, 182)     NaN      NaN
3          4   (600, 96)  (44, 307)    Top4      NaN