问:
Error handler not catching Error
This issue I am having is my Error handler is not catching an error if it occurs more then 2 times. This is what im useing.

```<code>Private Sub DBBackUp()
On Error GoTo ErrHandler:
If FSO.FolderExists(DBBackupFolderDir) = True And FSO.FileExists(DBDir) = True Then

AskAgianLoop:

    Application.CompactRepair DBDir, CARDBBackupFileDir, True
End if

ErrHandler:
If Err.Number = 58 Or Err.Number = 31523 Then
    GoTo AskAgianLoop
Else
  errMsg = "Error number: " & Str(Err.Number) & vbNewLine & _
           "Source: " & Err.Source & vbNewLine & _
           "Description: " & Err.Description
Debug.Print errMsg
Err.Clear
End If
Exit Sub
End Sub
</code>```

The above will prompt, with a security warning, the user 2 times each time its ran. If the user clicks cancel on one of them instead of open it will throw an error code with the value of 31523. It is then moved to the ErrHandler. Which will then ask the user again with the same security prompt. If the user presses cancel more than 2 times an error message with the value of 31523 shows and does not get caught by the Error handler.

答: Changing GoTo AskAgianLoop to Resume AskAgianLoop: Fixed the issue.

Title: Error handler not catching Error

Body:
This issue I am having is my Error handler is not catching an error if it occurs more then 2 times. This is what im useing.

Private Sub DBBackUp()
On Error GoTo ErrHandler:
If FSO.FolderExists(DBBackupFolderDir) = True And FSO.FileExists(DBDir) = True Then

AskAgianLoop:

    Application.CompactRepair DBDir, CARDBBackupFileDir, True
End if

ErrHandler:
If Err.Number = 58 Or Err.Number = 31523 Then
    GoTo AskAgianLoop
Else
  errMsg = "Error number: " & Str(Err.Number) & vbNewLine & _
           "Source: " & Err.Source & vbNewLine & _
           "Description: " & Err.Description
Debug.Print errMsg
Err.Clear
End If
Exit Sub
End Sub

The above will prompt, with a security warning, the user 2 times each time its ran. If the user clicks cancel on one of them instead of open it will throw an error code with the value of 31523. It is then moved to the ErrHandler. Which will then ask the user again with the same security prompt. If the user presses cancel more than 2 times an error message with the value of 31523 shows and does not get caught by the Error handler.


来源: stackexchange

问:
Gradle Error:Could not create an instance of type com.sun.tools.javac.api.JavacTool
I created a new root folder & it contains build.gradle with apply plugin ="java"
A folder src -> main -> java  (contains code)
When I run gradle assemble I'm getting this error

Could not create an instance of type com.sun.tools.javac.api.JavacTool.

:compileJava failed

:processResources UP-TO-DATE

Why is my build process not successful?(i'm on ubuntu 16.04)

答:
For me it was caused because I had multiples Java environments (openjdk-8 & openjdk-9)  on my laptop.

So I began to remove one environment:

```<code>$ sudo apt-get remove openjdk-9-*
</code>```

And then I set JAVA_HOME to openjdk-8. Just had

```<code>export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/
</code>```

To your .bashrc file (you may need to correct the link according to your system)

And that's it.

ContentLicense: CC BY-SA 3.0

Body:
For me it was caused because I had multiples Java environments (openjdk-8 & openjdk-9)  on my laptop.

So I began to remove one environment:

$ sudo apt-get remove openjdk-9-*

And then I set JAVA_HOME to openjdk-8. Just had

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/

To your .bashrc file (you may need to correct the link according to your system)

And that's it.


问:
Routing with query params not working
I want to route to this page passing a param: http://localhost:4200/inventory/client?id=2

What I do is:

```<code>this.router.navigate(['/inventory/client',{id:this.vendorId}]);
</code>```

But result involves a semicolon: http://localhost:4200/inventory/client;id=2

What should i do to change it to: http://localhost:4200/inventory/client?id=2

答:
Try this:

```<code> this.router.navigate(['/inventory/client'], { queryParams: { id: this.vendorId} });
</code>```

And have a look here: Passing Optional Parameters

Title: Routing with query params not working

Body:
I want to route to this page passing a param: http://localhost:4200/inventory/client?id=2

What I do is:

this.router.navigate(['/inventory/client',{id:this.vendorId}]);

But result involves a semicolon: http://localhost:4200/inventory/client;id=2

What should i do to change it to: http://localhost:4200/inventory/client?id=2

Body:
Try this:

 this.router.navigate(['/inventory/client'], { queryParams: { id: this.vendorId} });

And have a look here: Passing Optional Parameters


答:
You should use queryParams

```<code>this.router.navigate(['/inventory/client'], { queryParams: { id: this.vendorId} });
</code>```

Title: Routing with query params not working

Body:
You should use queryParams

this.router.navigate(['/inventory/client'], { queryParams: { id: this.vendorId} });


问:
convert the columns into Horizontal PIVOT
I have 3 column file with ID,name and value .

```<code>1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,Color,white
3,primarycolor,blue
5,size,M
5,Brand,Sports
5,Brand,Running
</code>```

I'm trying to convert this into a horizontal format based on the column 1 and column 2.

It's similar to the Pivot table with text values printed, it can't be done using Excel pivot it will allow only sum/count of values.

Can this be generated in UNIX?

```<code>,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue/white,,,,,shoe,blue,
5,Sports/Running,,,,,,,,M
</code>```

答:
Excel VBA:</p>

```<code>Sub Pivot()

    Dim rngData, rngOut, r, c, dR, dC
    Set dR = CreateObject("scripting.dictionary")
    Set dC = CreateObject("scripting.dictionary")

    Set rngData = ActiveSheet.Range("A2:C2") '<< first row of input
    Set rngOut = ActiveSheet.Range("G2")     '<< where to put output

    Do While Application.CountA(rngData) > 0
        r = rngData(1)
        c = rngData(2)
        If Not dR.exists(r) Then
            dR.Add r, dR.Count + 1
            rngOut.Offset(dR.Count, 0) = r
        End If
        If Not dC.exists(c) Then
            dC.Add c, dC.Count + 1
            rngOut.Offset(0, dC.Count) = c
        End If

        With rngOut.Offset(dR(r), dC(c))
            'if already has a value, add a newline separator
            .Value = .Value & IIf(.Value <> "", vbLf, "") & rngData(3)
        End With
        Set rngData = rngData.Offset(1, 0)
    Loop

End Sub
</code>```

Body:
I have 3 column file with ID,name and value .

1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,Color,white
3,primarycolor,blue
5,size,M
5,Brand,Sports
5,Brand,Running

I'm trying to convert this into a horizontal format based on the column 1 and column 2.

It's similar to the Pivot table with text values printed, it can't be done using Excel pivot it will allow only sum/count of values.

Can this be generated in UNIX?

,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue/white,,,,,shoe,blue,
5,Sports/Running,,,,,,,,M

Body:
Excel VBA:

Sub Pivot()

    Dim rngData, rngOut, r, c, dR, dC
    Set dR = CreateObject("scripting.dictionary")
    Set dC = CreateObject("scripting.dictionary")

    Set rngData = ActiveSheet.Range("A2:C2") '<< first row of input
    Set rngOut = ActiveSheet.Range("G2")     '<< where to put output

    Do While Application.CountA(rngData) > 0
        r = rngData(1)
        c = rngData(2)
        If Not dR.exists(r) Then
            dR.Add r, dR.Count + 1
            rngOut.Offset(dR.Count, 0) = r
        End If
        If Not dC.exists(c) Then
            dC.Add c, dC.Count + 1
            rngOut.Offset(0, dC.Count) = c
        End If

        With rngOut.Offset(dR(r), dC(c))
            'if already has a value, add a newline separator
            .Value = .Value & IIf(.Value <> "", vbLf, "") & rngData(3)
        End With
        Set rngData = rngData.Offset(1, 0)
    Loop

End Sub


问:
Extended css sprites not working with :hover?
I just encountered this article of an extention of css sprites that enables the spriting trick with foreground images . I tried to use the technique on :hover but it doesn't appear to work in IE and Opera. See my attempt to use this technique for a  menu here: http://www.kavoir.com/examples/jenny-css-sprites/menu.html

On FF and Safari, it works properly but just doesn't work at all in IE and Opera. Modified the code in a few ways but still doesn't work at all. Maybe it's impossible?

Tried to ask the author but she deleted my comment.

Any idea how to make this work on all browsers?

Update: Thanks for the answers but the :hover IS for , so I believe all IE browsers should work out the effects. Therefore the problem might very probably be about the clip property.

I just want to make sure if :hover works properly with clip on . Appears so far it doesn't.

答:
OK, here's what my research has uncovered (and correct me if I'm wrong):
IE supports a:hover, but it apparently will not apply it to child elements.

So, I've created a workaround using overflow:hidden and margins using your current markup. I would surmise that you could still use the clip property, but it may require another element (maybe not, though). The solution is up here and appears to work correctly in both FF and IE6 (have not tested in other browsers).

Also, I'd like to address annakata in saying that menu buttons and logos haven't historically been background images and have printed on printouts, so css spriting has changed that behavior (in favor of performance).

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: jennyfofenny


问:
Get the day change point(s) between two UNIX timestamps
I have the date range (two UNIX timestamps) and I need to find point(s) at 23:59:59 if exists.
How I can do it with Perl?

P.S. I think for() is not good idea because I can have very big range. Anything another variants?

答:
That's a generic algorithm. X is the 1st timestamp Y is the last one

1) Get the first change date, Z.

```<code>If Z > Y , there is no change.
</code>```

2) Get the last change date, W

```<code>   If W = Z, there is only one change date.
</code>```

3) Get the range of dates, R. Considering the range of one day is D

```<code>   R = W - Z .. The number of points will be the integer of (W - Z)/D
</code>```

Body:
That's a generic algorithm. X is the 1st timestamp Y is the last one

1) Get the first change date, Z.

If Z > Y , there is no change.

2) Get the last change date, W

   If W = Z, there is only one change date.

3) Get the range of dates, R. Considering the range of one day is D

   R = W - Z .. The number of points will be the integer of (W - Z)/D


问:
Managing the Azure Windows through PHP SDk
I am trying to configure the php sdk for managing the azure instance to perform basic operations like starting or stopping a VM,getting the IP of running VM,etc.I tried searching but didnt find any document.Is there any document available ? Also how to establish client session for the same ?</p>

答:
As far as I know, there is no SDK for PHP we can use to manage Azure VM at the present time. The REST Management API is the one you want to go for.

Reference:

Virtual Machines REST API


问:
ng-file-upload send array into database
i want to upload array of data that i have by using ng-file-upload, but if i repeat it, my database only got last image, can anyone know what's wrong with my code?

Here is my code

```<code>$scope.send = function () {
    console.log("aaa " + $scope.file);
    console.log("files total: " + $scope.portfolio_images_array.length);

    if ($scope.file && $scope.file1 && $scope.portfolio_images_array.length > 0) {
            Upload.upload({
                url: 'upload_url',
                data: {
                    user_id: 7,
                    profile_photo: $scope.file,
                    id_card_photo: $scope.file1,
                    name: $scope.name,
                    introduction: $scope.introduction,
                    portfolio_image: $scope.portfolio_images_array
                }
            }).then(function (resp) {
                console.log('Success ');
            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ');
            });
        }
};
</code>```

portfolio_image should get all the images, but now it only get the last image from portfolio_images_array.
For adding the data to portolio_image_array, i use this code:

```<code>$scope.addFiles = function (file) {
    console.log(file);
    $scope.portfolio_images_array.push(file);
}
</code>```

Please help me with this, Thanks

答:
i found an answer, we just need to add arrayKey, here is the code</p>

```<code>    $scope.send = function () {
    if ($scope.file && $scope.file1 && $scope.portfolio_images_array.length > 0) {
        Upload.upload({
            url: 'uploadURL',
            arrayKey: '',
            data: {
                user_id: 7,
                profile_photo: $scope.file,
                id_card_photo: $scope.file1,
                name: $scope.name,
                introduction: $scope.introduction,
                portfolio_image: $scope.portfolio_images_array
            }
        }).then(function (resp) {
            console.log('Success ');
        }, function (resp) {
            console.log('Error status: ' + resp.status);
        }, function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ');
        });
    }
};
</code>```

Title: ng-file-upload send array into database

Body:
i want to upload array of data that i have by using ng-file-upload, but if i repeat it, my database only got last image, can anyone know what's wrong with my code?

Here is my code

$scope.send = function () {
    console.log("aaa " + $scope.file);
    console.log("files total: " + $scope.portfolio_images_array.length);

    if ($scope.file && $scope.file1 && $scope.portfolio_images_array.length > 0) {
            Upload.upload({
                url: 'upload_url',
                data: {
                    user_id: 7,
                    profile_photo: $scope.file,
                    id_card_photo: $scope.file1,
                    name: $scope.name,
                    introduction: $scope.introduction,
                    portfolio_image: $scope.portfolio_images_array
                }
            }).then(function (resp) {
                console.log('Success ');
            }, function (resp) {
                console.log('Error status: ' + resp.status);
            }, function (evt) {
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ');
            });
        }
};

portfolio_image should get all the images, but now it only get the last image from portfolio_images_array.
For adding the data to portolio_image_array, i use this code:

$scope.addFiles = function (file) {
    console.log(file);
    $scope.portfolio_images_array.push(file);
}

Please help me with this, Thanks

Body:
i found an answer, we just need to add arrayKey, here is the code

    $scope.send = function () {
    if ($scope.file && $scope.file1 && $scope.portfolio_images_array.length > 0) {
        Upload.upload({
            url: 'uploadURL',
            arrayKey: '',
            data: {
                user_id: 7,
                profile_photo: $scope.file,
                id_card_photo: $scope.file1,
                name: $scope.name,
                introduction: $scope.introduction,
                portfolio_image: $scope.portfolio_images_array
            }
        }).then(function (resp) {
            console.log('Success ');
        }, function (resp) {
            console.log('Error status: ' + resp.status);
        }, function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ');
        });
    }
};


问:
ToConstant while binding in Kernel
We have a code something like below.

```<code>var xyz = method(); //method() returns an interface say **Interface1**

kernel.Bind<**Interface1**>().ToConstant(xyz);
</code>```

I saw on stackoverflow at the below link:

Usage of binding to constants and binding to types in scopes with Ninject

Can we use Kernel.Bind<**Interface1**>().To(typeof(xyz)).InSingletonScope() if we want the object creation not at the this point but when call is made.

答:
```<code>Bind<Interface1>().ToMethod(context => method()).InSingletonScope();
</code>```

Title: ToConstant while binding in Kernel

Body:
We have a code something like below.

var xyz = method(); //method() returns an interface say **Interface1**

kernel.Bind<**Interface1**>().ToConstant(xyz);

I saw on stackoverflow at the below link:

Usage of binding to constants and binding to types in scopes with Ninject

Can we use Kernel.Bind<**Interface1**>().To(typeof(xyz)).InSingletonScope() if we want the object creation not at the this point but when call is made.


问:
click on another link first link css remove and ul display
When I click 1st link drop-down slide down and class change of arrow, but when i open 1st link and click on the second link 1st link class not change.
here is my sample code

$(".navclick").click(function(event) {
 $('.navslidedown ul').each(function(){
 $(this).slideUp();

  });
  var $slide = $(this).next('.navslidedown ul');
  if ($slide.is(':visible')) {
      $slide.slideUp();
  }else{
      $slide.slideDown();
  }

});

$('.navclick').click(function() {
      $(this).toggleClass('navupclick').sibling().removeClass('navupclick');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navslidedown{  float: left;    width: 95%;}
.navslidedown ul{display:none}
.navslidedown li{ display:block; background:#e8ce49;    border-bottom: 1px solid #fbdc3b; margin-bottom:20px}

.navslidedown li a{padding-left:44px}
.navclick{background: url(http://54.85.78.249/design/dna/images/dpdwnarow.png) no-repeat center 0px;         display: block;   margin-bottom:15px; cursor:pointer}

.navupclick{background: url(http://54.85.78.249/design/dna/images/dpuparow.png) no-repeat center 0px;       display: block;   margin-bottom:15px   }</code>```

India

Delhi

Mumbai

     world

USA

Australia

```

答:
You have to apply a change in your jQuery $('.navclick').click(function() {

$(".navclick").click(function(event) {
  $('.navslidedown ul').each(function() {
    $(this).slideUp();
  });
  var $slide = $(this).next('.navslidedown ul');
  if ($slide.is(':visible')) {
    $slide.slideUp();
  } else {
    $slide.slideDown();
  }

});

$('.navclick').click(function() {
  $("a.navupclick").not(this).removeClass("navupclick");
  $(this).toggleClass('navupclick');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navslidedown {
  float: left;
  width: 95%;
}

.navslidedown ul {
  display: none
}

.navslidedown li {
  display: block;
  background: #e8ce49;
  border-bottom: 1px solid #fbdc3b;
  margin-bottom: 20px
}

.navslidedown li a {
  padding-left: 44px
}

.navclick {
  background: url(http://54.85.78.249/design/dna/images/dpdwnarow.png) no-repeat center 0px;
  display: block;
  margin-bottom: 15px;
  cursor: pointer
}

.navupclick {
  background: url(http://54.85.78.249/design/dna/images/dpuparow.png) no-repeat center 0px;
  display: block;
  margin-bottom: 15px
}</code>```

  India

Delhi

Mumbai

  world

USA

Australia

```

Body:
When I click 1st link drop-down slide down and class change of arrow, but when i open 1st link and click on the second link 1st link class not change.
here is my sample code

$(".navclick").click(function(event) {
 $('.navslidedown ul').each(function(){
 $(this).slideUp();

  });
  var $slide = $(this).next('.navslidedown ul');
  if ($slide.is(':visible')) {
      $slide.slideUp();
  }else{
      $slide.slideDown();
  }

});

$('.navclick').click(function() {
      $(this).toggleClass('navupclick').sibling().removeClass('navupclick');
});

.navslidedown{  float: left;    width: 95%;}
.navslidedown ul{display:none}
.navslidedown li{ display:block; background:#e8ce49;    border-bottom: 1px solid #fbdc3b; margin-bottom:20px}

.navslidedown li a{padding-left:44px}
.navclick{background: url(http://54.85.78.249/design/dna/images/dpdwnarow.png) no-repeat center 0px;         display: block;   margin-bottom:15px; cursor:pointer}

.navupclick{background: url(http://54.85.78.249/design/dna/images/dpuparow.png) no-repeat center 0px;       display: block;   margin-bottom:15px   }

India

Delhi

Mumbai

     world

USA

Australia

Body:
You have to apply a change in your jQuery $('.navclick').click(function() {

$(".navclick").click(function(event) {
  $('.navslidedown ul').each(function() {
    $(this).slideUp();
  });
  var $slide = $(this).next('.navslidedown ul');
  if ($slide.is(':visible')) {
    $slide.slideUp();
  } else {
    $slide.slideDown();
  }

});

$('.navclick').click(function() {
  $("a.navupclick").not(this).removeClass("navupclick");
  $(this).toggleClass('navupclick');
});

.navslidedown {
  float: left;
  width: 95%;
}

.navslidedown ul {
  display: none
}

.navslidedown li {
  display: block;
  background: #e8ce49;
  border-bottom: 1px solid #fbdc3b;
  margin-bottom: 20px
}

.navslidedown li a {
  padding-left: 44px
}

.navclick {
  background: url(http://54.85.78.249/design/dna/images/dpdwnarow.png) no-repeat center 0px;
  display: block;
  margin-bottom: 15px;
  cursor: pointer
}

.navupclick {
  background: url(http://54.85.78.249/design/dna/images/dpuparow.png) no-repeat center 0px;
  display: block;
  margin-bottom: 15px
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navslidedown">
  <a title="India" class="navclick">India</a>

  <ul>
    <li><a href="#">Delhi</a></li>
    <li><a href="#">Mumbai</a></li>
  </ul>
</div>

<div class="navslidedown">
  <a title="India" class="navclick">world</a>

  <ul>
    <li><a href="#">USA</a></li>
    <li><a href="#">Australia</a></li>
  </ul>
</div>


问:
making a special character (@) mandatory in php preg_match()
I'm trying to create a preg_match() for Bcc in the mail().
I have created below preg_match()

```<code>if(empty($mail_bcc))
        {
            $_SESSION['error'] .= "<li>Please enter BCC email id.</li>";
            $error = 1;
        }
         else if(!preg_match('/^\s*[A-Za-z0-9@. ,]+\s*$/',$mail_bcc)|| preg_match('/^ /',$mail_bcc) || preg_match('/ $/',$mail_bcc))
        {
            $_SESSION['error'] .= "<li>Please enter a valid BCC email id.No spaces are allowed and Separate BCC email addresses with commas (,)</li>";
            $error = 1;
        }
</code>```

for this i'm getting below result

abc.gmail.com = TRUE

abc.gmail.com,abc.gmail.com = TRUE

abc@gmail.com = = TRUE

but I want to make @ mandatory.
for below cases it should return False/Error

abc.gmail.com = FALSE

abc.gmail.com,abc.gmail.com FALSE

答:
To require at least one @ in a regex like yours, the simplest approach is to use a (?=[^@]*@) positive lookahead:

```<code>'/^(?=[^@]*@)\s*[A-Za-z0-9@. ,]+\s*$/'
   ^^^^^^^^^^
</code>```

The (?=[^@]*@) construct will start looking for any 0+ chars other than @ ([^@]*) up to the first @ right from the start of the string (^). If it finds a @, the rest of the consuming pattern will be searched for, else, the regex engine will fail the match right away.

Body:
I'm trying to create a preg_match() for Bcc in the mail().
I have created below preg_match()

if(empty($mail_bcc))
        {
            $_SESSION['error'] .= "
Please enter BCC email id.
";
            $error = 1;
        }
         else if(!preg_match('/^\s*[A-Za-z0-9@. ,]+\s*$/',$mail_bcc)|| preg_match('/^ /',$mail_bcc) || preg_match('/ $/',$mail_bcc))
        {
            $_SESSION['error'] .= "
Please enter a valid BCC email id.No spaces are allowed and Separate BCC email addresses with commas (,)
";
            $error = 1;
        }

for this i'm getting below result

abc.gmail.com = TRUE

abc.gmail.com,abc.gmail.com = TRUE

abc@gmail.com = = TRUE

but I want to make @ mandatory.
for below cases it should return False/Error

abc.gmail.com = FALSE

abc.gmail.com,abc.gmail.com FALSE

Body:
To require at least one @ in a regex like yours, the simplest approach is to use a (?=[^@]*@) positive lookahead:

'/^(?=[^@]*@)\s*[A-Za-z0-9@. ,]+\s*$/'
   ^^^^^^^^^^

The (?=[^@]*@) construct will start looking for any 0+ chars other than @ ([^@]*) up to the first @ right from the start of the string (^). If it finds a @, the rest of the consuming pattern will be searched for, else, the regex engine will fail the match right away.


问:
angularjs - validation error message
Can someone explain me the following code, I'm new to angular please help me :

```<code>{% if validation_error %}
   <div>{{ validation_error }}</div>
{% endif %}
</code>```

On web page :

Full code :

```<code><form name="login" method="POST" action="/app/login">
    <div class="form-container">
        <fieldset class="form-group">
            <input class="form-control form-control-sm text-uppercase" id="username" name="username" type="text" placeholder="Username">
            <input class="form-control form-control-sm" name="password" type="password" placeholder="Password">
        </fieldset>
        <button class="btn btn-primary btn-sm btn-block">signin</button>
        {% if validation_error %}
            <div class="small text-danger m-t-1">{{ validation_error }}</div>
        {% endif %}
    </div>
</form>
</code>```

答:
You can use angular validation with form's and inputs' names;

```<code><form name="login" method="POST" action="/app/login">
    <div class="form-container">
        <fieldset class="form-group">
            <input class="form-control form-control-sm text-uppercase" id="username" name="username" type="text" placeholder="Username">
            <input class="form-control form-control-sm" name="password" type="password" placeholder="Password">
        </fieldset>
        <button class="btn btn-primary btn-sm btn-block" ng-disabled="!login.$valid">signin</button>

        <div ng-if="!login.$valid" class="small text-danger m-t-1">form not valid</div>
        <div ng-if="!login.username.$valid" class="small text-danger m-t-1">username not valid</div>
    </div>
</form>
</code>```

For more: https://www.w3schools.com/angular/angular_validation.asp

Title: angularjs - validation error message

Body:
Can someone explain me the following code, I'm new to angular please help me :

{% if validation_error %}

{{ validation_error }}

{% endif %}

On web page :

Full code :

<form name="login" method="POST" action="/app/login">

        <fieldset class="form-group">
            <input class="form-control form-control-sm text-uppercase" id="username" name="username" type="text" placeholder="Username">
            <input class="form-control form-control-sm" name="password" type="password" placeholder="Password">
        </fieldset>
        <button class="btn btn-primary btn-sm btn-block">signin</button>
        {% if validation_error %}

{{ validation_error }}

        {% endif %}

</form>

Body:
You can use angular validation with form's and inputs' names;

<form name="login" method="POST" action="/app/login">
    <div class="form-container">
        <fieldset class="form-group">
            <input class="form-control form-control-sm text-uppercase" id="username" name="username" type="text" placeholder="Username">
            <input class="form-control form-control-sm" name="password" type="password" placeholder="Password">
        </fieldset>
        <button class="btn btn-primary btn-sm btn-block" ng-disabled="!login.$valid">signin</button>

        <div ng-if="!login.$valid" class="small text-danger m-t-1">form not valid</div>
        <div ng-if="!login.username.$valid" class="small text-danger m-t-1">username not valid</div>
    </div>
</form>

For more: https://www.w3schools.com/angular/angular_validation.asp


问:
Updating Image upload complete status in database using retrofit and rxjava
I am using Rxjava in conjunction with Retrofit. I want to update status of that image as completed in android database. So the real question is what if second image is uploaded first and after that first is uploaded?. Is onNext() is called sequentially as a images in queue gets executed or the images are uploaded in asynchronous manner. I want to know the required solution for this approach. My code so far is as follows.

```<code>tisImageEntities = SelectQuery.getImageByStatus(mContext);

    tisImageCount = 0;
    Observable.fromIterable(tisImageEntities)
            .map(tisImageEntity -> new TisImageUploadEntity(tisImageEntity.projectId,
                    tisImageEntity.imagePath.substring(tisImageEntity.imagePath.lastIndexOf("/") + 1), "fit.jpg",
                    tisImageEntity.detail, tisImageEntity.imageType,
                    getBase64EncodedString(tisImageEntity.imagePath)))
            .filter(tisImageUploadEntity -> null!=tisImageUploadEntity.Content)
            .flatMap(tisImageUploadEntity -> hitachiRetrofitApi.uploadTisImages(tisImageUploadEntity))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableObserver<ResponseBody>() {

                @Override
                public void onNext(ResponseBody responseBody) {
                    try {
                        String response = responseBody.string().toString();
                        UpdateQuery.updateTisImageStatus(mContext,tisImageEntities.get(tisImageCount).projectId); // here is image staatus updated correctly??
                        tisImageCount++;
                        Log.d(TAG, "on next for update entity" + response);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    cancleProgressDialog();
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "on complete for update entity");
                    cancleProgressDialog();
                }
            });
</code>```

So in onNext() the update query right? and is it updating the status sequentially? If not then please correct me

答:
flatMap() does not retain the order, so if you will execute multiple requests
 results will not be emitted sequentially but by result arrived order.

BTW, you should apply io scheduler to the returned Observable at the flatMap() (hitachiRetrofitApi.uploadTisImages(tisImageUploadEntity)) to get parallelism.

for preserving the order you can use concatMapEager() operator, which will gain you parallelism but will preserve the order of source items.

Additionally, just a suggestion, you have different option, as what you are trying to get here is to collect the request result along with the matching request image entity, you can use flatMap() overload with resultSelector param, with this way, you can send down the stream a pair of the result with the matching image entity, update the db with doOnNext(), and map just the result ResponseBody for the Subscriber to handle it.

```<code> Observable.fromIterable(tisImageEntities)
            .map(tisImageEntity -> new TisImageUploadEntity(tisImageEntity.projectId,
                    tisImageEntity.imagePath.substring(tisImageEntity.imagePath.lastIndexOf("/") + 1), "fit.jpg",
                    tisImageEntity.detail, tisImageEntity.imageType,
                    getBase64EncodedString(tisImageEntity.imagePath)))
            .filter(tisImageUploadEntity -> null != tisImageUploadEntity.Content)
            .flatMap(tisImageUploadEntity -> hitachiRetrofitApi.uploadTisImages(tisImageUploadEntity)
                            .subscribeOn(Schedulers.io()),
                    (tisImageUploadEntity, responseBody) -> Pair::new
            )
            .doOnNext(pair -> UpdateQuery.updateTisImageStatus(mContext, pair.first.projectId))
            .map(pair -> pair.second)
            .subscribeOn(Schedulers.io());
</code>```

Body:
I am using Rxjava in conjunction with Retrofit. I want to update status of that image as completed in android database. So the real question is what if second image is uploaded first and after that first is uploaded?. Is onNext() is called sequentially as a images in queue gets executed or the images are uploaded in asynchronous manner. I want to know the required solution for this approach. My code so far is as follows.

tisImageEntities = SelectQuery.getImageByStatus(mContext);

    tisImageCount = 0;
    Observable.fromIterable(tisImageEntities)
            .map(tisImageEntity -> new TisImageUploadEntity(tisImageEntity.projectId,
                    tisImageEntity.imagePath.substring(tisImageEntity.imagePath.lastIndexOf("/") + 1), "fit.jpg",
                    tisImageEntity.detail, tisImageEntity.imageType,
                    getBase64EncodedString(tisImageEntity.imagePath)))
            .filter(tisImageUploadEntity -> null!=tisImageUploadEntity.Content)
            .flatMap(tisImageUploadEntity -> hitachiRetrofitApi.uploadTisImages(tisImageUploadEntity))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(new DisposableObserver<ResponseBody>() {

                @Override
                public void onNext(ResponseBody responseBody) {
                    try {
                        String response = responseBody.string().toString();
                        UpdateQuery.updateTisImageStatus(mContext,tisImageEntities.get(tisImageCount).projectId); // here is image staatus updated correctly??
                        tisImageCount++;
                        Log.d(TAG, "on next for update entity" + response);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    cancleProgressDialog();
                }

                @Override
                public void onComplete() {
                    Log.d(TAG, "on complete for update entity");
                    cancleProgressDialog();
                }
            });

So in onNext() the update query right? and is it updating the status sequentially? If not then please correct me

Body:
flatMap() does not retain the order, so if you will execute multiple requests
 results will not be emitted sequentially but by result arrived order.

BTW, you should apply io scheduler to the returned Observable at the flatMap() (hitachiRetrofitApi.uploadTisImages(tisImageUploadEntity)) to get parallelism.

for preserving the order you can use concatMapEager() operator, which will gain you parallelism but will preserve the order of source items.

Additionally, just a suggestion, you have different option, as what you are trying to get here is to collect the request result along with the matching request image entity, you can use flatMap() overload with resultSelector param, with this way, you can send down the stream a pair of the result with the matching image entity, update the db with doOnNext(), and map just the result ResponseBody for the Subscriber to handle it.

 Observable.fromIterable(tisImageEntities)
            .map(tisImageEntity -> new TisImageUploadEntity(tisImageEntity.projectId,
                    tisImageEntity.imagePath.substring(tisImageEntity.imagePath.lastIndexOf("/") + 1), "fit.jpg",
                    tisImageEntity.detail, tisImageEntity.imageType,
                    getBase64EncodedString(tisImageEntity.imagePath)))
            .filter(tisImageUploadEntity -> null != tisImageUploadEntity.Content)
            .flatMap(tisImageUploadEntity -> hitachiRetrofitApi.uploadTisImages(tisImageUploadEntity)
                            .subscribeOn(Schedulers.io()),
                    (tisImageUploadEntity, responseBody) -> Pair::new
            )
            .doOnNext(pair -> UpdateQuery.updateTisImageStatus(mContext, pair.first.projectId))
            .map(pair -> pair.second)
            .subscribeOn(Schedulers.io());


答:
Change your code used to toggle the class.Instead of that remove the class navupclick form all anchor tag and add the class navupclick to the clicked anchor tag

$(".navclick").click(function(event) {

  $('.navclick').removeClass('navupclick');

 $('.navslidedown ul').each(function(){
   $(this).slideUp();
  });
  var $slide = $(this).next('.navslidedown ul');
  if ($slide.is(':visible')) {
      $slide.slideUp();
  }else{
      $slide.slideDown();
     $(this).addClass('navupclick');
  }

});
 ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navslidedown{  float: left;    width: 95%;}
.navslidedown ul{display:none}
.navslidedown li{ display:block; background:#e8ce49;    border-bottom: 1px solid #fbdc3b; margin-bottom:20px}

.navslidedown li a{padding-left:44px}
.navclick{background: url(http://54.85.78.249/design/dna/images/dpdwnarow.png) no-repeat center 0px;         display: block;   margin-bottom:15px; cursor:pointer}

.navupclick{background: url(http://54.85.78.249/design/dna/images/dpuparow.png) no-repeat center 0px;       display: block;   margin-bottom:15px   }</code>```

India

Delhi

Mumbai

     world

USA

Australia

```

Title: click on another link first link css remove and ul display

Body:
Change your code used to toggle the class.Instead of that remove the class navupclick form all anchor tag and add the class navupclick to the clicked anchor tag

$(".navclick").click(function(event) {

  $('.navclick').removeClass('navupclick');

 $('.navslidedown ul').each(function(){
   $(this).slideUp();
  });
  var $slide = $(this).next('.navslidedown ul');
  if ($slide.is(':visible')) {
      $slide.slideUp();
  }else{
      $slide.slideDown();
     $(this).addClass('navupclick');
  }

});

.navslidedown{  float: left;    width: 95%;}
.navslidedown ul{display:none}
.navslidedown li{ display:block; background:#e8ce49;    border-bottom: 1px solid #fbdc3b; margin-bottom:20px}

.navslidedown li a{padding-left:44px}
.navclick{background: url(http://54.85.78.249/design/dna/images/dpdwnarow.png) no-repeat center 0px;         display: block;   margin-bottom:15px; cursor:pointer}

.navupclick{background: url(http://54.85.78.249/design/dna/images/dpuparow.png) no-repeat center 0px;       display: block;   margin-bottom:15px   }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navslidedown">
<a  title="India"  class="navclick">India</a>

     <ul>
     <li><a href="#">Delhi</a></li>
     <li><a href="#">Mumbai</a></li>
     </ul>
     </div>

     <div class="navslidedown">
     <a  title="India"  class="navclick">world</a>

     <ul>
     <li><a href="#">USA</a></li>
     <li><a href="#">Australia</a></li>
     </ul>
     </div>


问:
Raspberry Pi 3 ,fann_create_standard not defined
I recently downloaded the FANN(Fast artificial neural network) library via the synaptic manager for raspberry pi. I am trying to run the default application as shown below:

```<code> #include "fann.h"
 #include "floatfann.h"
 include "fann_data.h"

 int main()
 {
const unsigned int num_input = 2;
const unsigned int num_output = 1;
const unsigned int num_layers = 3;
const unsigned int num_neurons_hidden = 3;
const float desired_error = (const float) 0.001;
const unsigned int max_epochs = 500000;
const unsigned int epochs_between_reports = 1000;

struct fann *ann = fann_create_standard(num_layers, num_input,
    num_neurons_hidden, num_output);

fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
fann_set_activation_function_output(ann, FANN_SIGMOID_SYMMETRIC);

fann_train_on_file(ann, "xor.data", max_epochs,
    epochs_between_reports, desired_error);

fann_save(ann, "xor_float.net");

fann_destroy(ann);

return 0;
}
</code>```

I am getting this output:

```<code>enter code here

||=== Build: Debug in ArtificialNeuralNetworkExample (compiler: GNU GCC    Compi ler) ===|
obj/Debug/main.o||In function `main':|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|14|undefined reference to `fann_create_standard'|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|17|undefined reference to `fann_set_activation_function_hidden'|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|18|undefined reference to `fann_set_activation_function_output'|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|20|undefined reference to `fann_train_on_file'|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|23|undefined reference to `fann_save'|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|25|undefined reference to `fann_destroy'|
||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|
</code>```

Also tried linking the library using gcc as follows:

```<code>gcc -lfann main.c
</code>```

Not sure what to do.

答:
I believe, you need to change the order in which the library appears in the compilation statement.

```<code> gcc -lfann main.c
</code>```

should be

```<code> gcc main.c -lfann
</code>```

as the functions used in main.c are present in libfann.so.

Quoting the online gcc manual,

-l library

[....] It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in z, those functions may not be loaded.

In your case, you're facing similar scenario, for your case, the library should appear after the main.c as the functions from the library are used in main.c

Body:
I recently downloaded the FANN(Fast artificial neural network) library via the synaptic manager for raspberry pi. I am trying to run the default application as shown below:

 #include "fann.h"
 #include "floatfann.h"
 include "fann_data.h"

 int main()
 {
const unsigned int num_input = 2;
const unsigned int num_output = 1;
const unsigned int num_layers = 3;
const unsigned int num_neurons_hidden = 3;
const float desired_error = (const float) 0.001;
const unsigned int max_epochs = 500000;
const unsigned int epochs_between_reports = 1000;

struct fann *ann = fann_create_standard(num_layers, num_input,
    num_neurons_hidden, num_output);

fann_set_activation_function_hidden(ann, FANN_SIGMOID_SYMMETRIC);
fann_set_activation_function_output(ann, FANN_SIGMOID_SYMMETRIC);

fann_train_on_file(ann, "xor.data", max_epochs,
    epochs_between_reports, desired_error);

fann_save(ann, "xor_float.net");

fann_destroy(ann);

return 0;
}

I am getting this output:

enter code here

||=== Build: Debug in ArtificialNeuralNetworkExample (compiler: GNU GCC    Compi ler) ===|
obj/Debug/main.o||In function `main':|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|14|undefined reference to `fann_create_standard'|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|17|undefined reference to `fann_set_activation_function_hidden'|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|18|undefined reference to `fann_set_activation_function_output'|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|20|undefined reference to `fann_train_on_file'|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|23|undefined reference to `fann_save'|
/home/pi/Documents/ArtificialNeuralNetworkExample/main.c|25|undefined reference to `fann_destroy'|
||=== Build failed: 6 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

Also tried linking the library using gcc as follows:

gcc -lfann main.c

Not sure what to do.

Body:
I believe, you need to change the order in which the library appears in the compilation statement.

 gcc -lfann main.c

should be

 gcc main.c -lfann

as the functions used in main.c are present in libfann.so.

Quoting the online gcc manual,

-l library

[....] It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in z, those functions may not be loaded.

In your case, you're facing similar scenario, for your case, the library should appear after the main.c as the functions from the library are used in main.c


问:
How to delete Azure Recovery Services vault?
When I am trying to delete the Azure Recovery Services Vault from Azure portal, I got the error like in below figure. Even I deleted all backup items and replicated items from the vault.

For deleting the Azure Recovery Services vault, I have followed the below link

Delete an Azure Backup vault

So, how to delete the Azure recovery Services vault using portal or power shell cmdlet?

答:
I used to encounter the same problem, there are SQL backups in the vault. You need find SQL backups and delete them.

You could check this answer to solve this issue.

```<code>$vault = Get-AzureRmRecoveryServicesVault -Name "VaultName"

Set-AzureRmRecoveryServicesVaultContext -Vault $vault

#VIEW THE BACKUP ITEMS
$container = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureSQL -FriendlyName $vault.Name

$item = Get-AzureRmRecoveryServicesBackupItem -Container $container -WorkloadType AzureSQLDatabase

$availableBackups = Get-AzureRmRecoveryServicesBackupRecoveryPoint -Item $item

$availableBackups
#REMOVE THE BACKUP ITEMS AND VAULT
$containers = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureSQL -FriendlyName $vault.Name

ForEach ($container in $containers)
{
    $items = Get-AzureRmRecoveryServicesBackupItem -container $container -WorkloadType AzureSQLDatabase

    ForEach ($item in $items)
    {
        Disable-AzureRmRecoveryServicesBackupProtection -item $item -RemoveRecoveryPoints -ea SilentlyContinue
    }

    Unregister-AzureRmRecoveryServicesBackupContainer -Container $container
}

Remove-AzureRmRecoveryServicesVault -Vault $vault
</code>```

Body:
I used to encounter the same problem, there are SQL backups in the vault. You need find SQL backups and delete them.

You could check this answer to solve this issue.

$vault = Get-AzureRmRecoveryServicesVault -Name "VaultName"

Set-AzureRmRecoveryServicesVaultContext -Vault $vault

#VIEW THE BACKUP ITEMS
$container = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureSQL -FriendlyName $vault.Name

$item = Get-AzureRmRecoveryServicesBackupItem -Container $container -WorkloadType AzureSQLDatabase

$availableBackups = Get-AzureRmRecoveryServicesBackupRecoveryPoint -Item $item

$availableBackups
#REMOVE THE BACKUP ITEMS AND VAULT
$containers = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureSQL -FriendlyName $vault.Name

ForEach ($container in $containers)
{
    $items = Get-AzureRmRecoveryServicesBackupItem -container $container -WorkloadType AzureSQLDatabase

    ForEach ($item in $items)
    {
        Disable-AzureRmRecoveryServicesBackupProtection -item $item -RemoveRecoveryPoints -ea SilentlyContinue
    }

    Unregister-AzureRmRecoveryServicesBackupContainer -Container $container
}

Remove-AzureRmRecoveryServicesVault -Vault $vault


问:
Parameter can't pass using ajax in Cross Domain
I have used cross domain to call one domain to another as below ,

My ajax call from mvc project as done below,

```<code>var tableparameter = '{TableName: "' + $("#tableOneTableName").val() + '" }';
$.ajax({
            type: "POST",
            url: "http://localhost:55016/api/ajaxapi/onchangetableone",
            data: tableparameter,
            success: function (response) {
               alert("hi");
            }
});
</code>```

Then i added below code in web.config file within web api project as below,

```<code><httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</code>```

Then i written action as below,

```<code>[HttpPost]
[Route("api/ajaxapi/onchangetableone")]
public List<DropDownListValuesForQuery> OnChangeTableOne(TableNameFormCustomFilters TableParameter)
{
        CaseModel query = new CaseModel();
        List<DropDownListValuesForQuery> listValues = new List<DropDownListValuesForQuery>();
        listValues = query.GetColumnNames(TableParameter.TableName);
        return listValues;
}
</code>```

And list values as below,

```<code>public class TableNameFormCustomFilters
{
        public int TableName { get; set; }
}
</code>```

Here i can access the webapi source using cross domain but the parameter value not come from script. Please give your suggestion.

Thanks in advance.....

答:
Check below code :

var TableParameter = { "TableName": $("#tableOneTableName").val() };

$.ajax(
{
url: 'http://localhost:55016/api/ajaxapi/onchangetableone/',
     type: "POST",
     async: false,
     contentType: "application/json;",
     data: JSON.stringify(TableParameter),
     success: function (result) {
     alert("hi");
 }
});
```

Cheers !!

Body:
I have used cross domain to call one domain to another as below ,

My ajax call from mvc project as done below,

var tableparameter = '{TableName: "' + $("#tableOneTableName").val() + '" }';
$.ajax({
            type: "POST",
            url: "http://localhost:55016/api/ajaxapi/onchangetableone",
            data: tableparameter,
            success: function (response) {
               alert("hi");
            }
});

Then i added below code in web.config file within web api project as below,

<httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>

Then i written action as below,

[HttpPost]
[Route("api/ajaxapi/onchangetableone")]
public List<DropDownListValuesForQuery> OnChangeTableOne(TableNameFormCustomFilters TableParameter)
{
        CaseModel query = new CaseModel();
        List<DropDownListValuesForQuery> listValues = new List<DropDownListValuesForQuery>();
        listValues = query.GetColumnNames(TableParameter.TableName);
        return listValues;
}

And list values as below,

public class TableNameFormCustomFilters
{
        public int TableName { get; set; }
}

Here i can access the webapi source using cross domain but the parameter value not come from script. Please give your suggestion.

Thanks in advance.....

Body:
Check below code :

var TableParameter = { "TableName": $("#tableOneTableName").val() };

$.ajax(
{
url: 'http://localhost:55016/api/ajaxapi/onchangetableone/',
     type: "POST",
     async: false,
     contentType: "application/json;",
     data: JSON.stringify(TableParameter),
     success: function (result) {
     alert("hi");
 }
});

Cheers !!


问:
Angular2 View not updated when using setInterval
I am using Angular2 RC5 - and I have a strange problem.
In my main component I use for testing purposes in my constructor:

```<code> setInterval(() => {
        this.test = new Date().getMilliseconds().toString();
    }, 500);
</code>```

Binding in my template is

```<code><p>{{test}}</p>
</code>```

Upon loading or reloading the page it either displays a value (but does not change on further ticks), somtimes it works as intended (updates value on every tick), and sometimes just displays the initial value and does not change at all. Seems random.

I get crazy over this, as it seems in the official plunker version it works without a problem. (Edit: Plunker link )

I get the same behaviour when using this code in other components aswell..

Anyone any idea?

答:
Use this, This worked fine for me.

import { Observable } from 'rxjs/Observable';

```<code>Observable.interval(500)
    .subscribe(() => {
    this.test = new Date().getMilliseconds().toString();
})
</code>```

Body:
I am using Angular2 RC5 - and I have a strange problem.
In my main component I use for testing purposes in my constructor:

 setInterval(() => {
        this.test = new Date().getMilliseconds().toString();
    }, 500);

Binding in my template is

{{test}}

Upon loading or reloading the page it either displays a value (but does not change on further ticks), somtimes it works as intended (updates value on every tick), and sometimes just displays the initial value and does not change at all. Seems random.

I get crazy over this, as it seems in the official plunker version it works without a problem. (Edit: Plunker link )

I get the same behaviour when using this code in other components aswell..

Anyone any idea?

Body:
Use this, This worked fine for me.

import { Observable } from 'rxjs/Observable';

Observable.interval(500)
    .subscribe(() => {
    this.test = new Date().getMilliseconds().toString();
})


问:
i'm not able to update the label when i tapped on stepper which is placed in uitable view cell
here is the image i had designed
here is the code for UITableviewCell and in this I had placed the stepper action method to trigger but unable to update the price label when I tap on stepper can anyone help me?

```<code>class productTableViewCell: UITableViewCell {

    @IBOutlet var stepper: UIStepper!
    @IBOutlet var imageview: UIImageView!
    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var priceLabel: UILabel!
    @IBOutlet var quantityTextField: UITextField!
    var pricearr = [String]()
    var price : String = ""
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    @IBAction func changeCart(_ sender: Any) {
        let value = Int(stepper.value)
        quantityTextField.text = String(value)
   }
}
</code>```

Here is the code for UITableViewCell and in this I had placed the stepper action method to trigger but unable to update the price label when I tap on the stepper can anyone help me?

```<code> @IBOutlet var tableDetails: UITableView!
    var productsArray = [String]()
    var nameArray = [String]()
    var priceArray = [String]()
    let urlstring = "http://www.json-generator.com/api/json/get/ceghMiWudK?indent=2"
    var price = [String]()
    var sum = 0

    override func viewDidLoad() {
        super.viewDidLoad()
       self.downloadJsonWithURL()
        tableDetails.delegate = self
        tableDetails.dataSource = self
        tableDetails.alwaysBounceVertical = false
        // Do any additional setup after loading the view.
    }

    func downloadJsonWithURL() {
            let url = NSURL(string: urlstring)
            URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
                if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                    print(jsonObj!.value(forKey: "Detail"))
                if let detailsArray = jsonObj!.value(forKey: "Detail") as? NSArray {
                    for item in detailsArray {
                        if let detailDict = item as? NSDictionary {
                            if let name = detailDict.value(forKey: "productName"){
                                self.nameArray.append(name as! String)
                            }
                            if let price = detailDict.value(forKey: "productPrice"){
                                self.priceArray.append(price as! String)
                            }
                            if let image = detailDict.value(forKey: "img"){
                                self.productsArray.append(image as! String)
                            }
                        }
                    }
                }
                OperationQueue.main.addOperation({
                    self.tableDetails.reloadData()
                    for item in self.priceArray{
                        let endIndex = item.index(item.endIndex, offsetBy: -5)
                        let truncated = item.substring(to: endIndex)
                        self.price.append(truncated)
                    }
                    print(self.price)
                })
            }
        }).resume()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 3
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if (section == 0){
            return productsArray.count
        }else{
            return 1
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! productTableViewCell
            let arr = self.productsArray[indexPath.row]
            let urls = NSURL(string: arr)
            let data = NSData (contentsOf: urls! as URL)
            cell.imageview.image = UIImage(data: data! as Data)
            cell.nameLabel.text = nameArray[indexPath.row]
            let x = priceArray[indexPath.row]
            let array = String(x)
            cell.priceLabel.text = array
            cell.quantityTextField.text = "1"
            cell.pricearr = [price[indexPath.row]]
            return cell
        }else if indexPath.section == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "couponcell", for: indexPath) as! CouponTableViewCell
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "checkout", for: indexPath) as! checkoutTableViewCell
            return cell
        }
    }
</code>```

答:
Add your stepper's outlet and action like in below image:

Replace your code with below one:

```<code> class productTableViewCell: UITableViewCell {

            @IBOutlet var stepper: UIStepper!
            @IBOutlet var imageview: UIImageView!
            @IBOutlet var nameLabel: UILabel!
            @IBOutlet var priceLabel: UILabel!
            @IBOutlet var quantityTextField: UITextField!
            var pricearr = [String]()
            var price : String = ""
            override func awakeFromNib() {
                super.awakeFromNib()
                // Initialization code
            }
            @IBAction func changeCart(_ sender: Any) {
                let value = Int(stepper.value)
                quantityTextField.text = String(value)
                let x = Int(pricearr[0])
                priceLabel.text = String(x! * value)
            }
        }
</code>```

Your code has one bug is that when you scroll tableView that time cell will be reset to its default value because of cell reuse.

EDIT:

Better way to achieve your goal (as far as I understood) can be as defined below :

Remove stepper action

Remove action from UITableview cell class

class productTableViewCell: UITableViewCell {

```<code>    @IBOutlet var stepper: UIStepper!
    @IBOutlet var imageview: UIImageView!
    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var priceLabel: UILabel!
    @IBOutlet var quantityTextField: UITextField!
    var price : String = ""
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
}
</code>```

3.Replace your core logic with below code

```<code>@IBOutlet var tableDetails: UITableView!
    var CartArray : [[String: String]] = []
    var itemsArray : [[String: AnyObject]] = []
    let urlstring = "http://www.json-generator.com/api/json/get/ceghMiWudK?indent=2"
    var sum = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        self.downloadJsonWithURL()
        tableDetails.delegate = self
        tableDetails.dataSource = self
        tableDetails.alwaysBounceVertical = false
        // Do any additional setup after loading the view.
    }
    func downloadJsonWithURL() {
        let url = NSURL(string: urlstring)
        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
              //  print(jsonObj!.value(forKey: "Detail"))
                self.itemsArray = (jsonObj!.value(forKey: "Detail") as? [[String: AnyObject]])!

                OperationQueue.main.addOperation({
                    self.tableDetails.reloadData()
                })
            }
        }).resume()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if (section == 0){
            return itemsArray.count
        }else{
            return 1
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        //if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! productTableViewCell
            let arr = itemsArray[indexPath.row]
            let urls = NSURL(string: arr["img"] as! String)
            let data = NSData (contentsOf: urls! as URL)
            cell.imageview.image = UIImage(data: data! as Data)
            cell.nameLabel.text = arr["productName"] as? String
            var price = arr["productPrice"] as! String

        var aQuntity : Float = 1
        let itemId : Int =  arr["sku"] as! Int

        for aDic in CartArray{
            if aDic["id"] == String(itemId){

            aQuntity = Float(String(aDic["quantity"]!))!
            }
        }

        cell.stepper.value = Double(Int(aQuntity))
        cell.stepper.tag = indexPath.row

        cell.stepper.addTarget(self, action: #selector(stapperValueChange), for:.valueChanged)
        price = price.replacingOccurrences(of: "KD", with: "")

            cell.priceLabel.text = String(Float(price)! * aQuntity)
        cell.quantityTextField.text = String(aQuntity)
            cell.price = price
            return cell
       // }
//        else if indexPath.section == 1{
//            let cell = tableView.dequeueReusableCell(withIdentifier: "couponcell", for: indexPath) as! CouponTableViewCell
//            return cell
//        }else {
//            let cell = tableView.dequeueReusableCell(withIdentifier: "checkout", for: indexPath) as! checkoutTableViewCell
//            return cell
//        }

    }

    func stapperValueChange (stepper : UIStepper){
        let index : Int = stepper.tag
        let arr = itemsArray[index]

        let cell : productTableViewCell = tableDetails.cellForRow(at: IndexPath(row: index, section: 0)) as! productTableViewCell

                let value = Float(stepper.value)
                cell.quantityTextField.text = String(value)
                let x = Float(cell.price)
                cell.priceLabel.text = String(Int(x! * value))
        let itemId : Int =  arr["sku"] as! Int

        var aFoundIndex : Int?
        var counter : Int = 0

        _ = CartArray.filter { (aDic) -> Bool in

            if aDic["id"] ==  String(itemId){
            aFoundIndex = counter
            }
            counter += 1
            return false
        }

        if(aFoundIndex != nil){
        CartArray.remove(at: aFoundIndex!)
        }

        CartArray.append(["quantity" : String(value),"id" : String(itemId)])
    }
</code>```

Body:
here is the image i had designed
here is the code for UITableviewCell and in this I had placed the stepper action method to trigger but unable to update the price label when I tap on stepper can anyone help me?

class productTableViewCell: UITableViewCell {

    @IBOutlet var stepper: UIStepper!
    @IBOutlet var imageview: UIImageView!
    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var priceLabel: UILabel!
    @IBOutlet var quantityTextField: UITextField!
    var pricearr = [String]()
    var price : String = ""
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    @IBAction func changeCart(_ sender: Any) {
        let value = Int(stepper.value)
        quantityTextField.text = String(value)
   }
}

Here is the code for UITableViewCell and in this I had placed the stepper action method to trigger but unable to update the price label when I tap on the stepper can anyone help me?

 @IBOutlet var tableDetails: UITableView!
    var productsArray = [String]()
    var nameArray = [String]()
    var priceArray = [String]()
    let urlstring = "http://www.json-generator.com/api/json/get/ceghMiWudK?indent=2"
    var price = [String]()
    var sum = 0

    override func viewDidLoad() {
        super.viewDidLoad()
       self.downloadJsonWithURL()
        tableDetails.delegate = self
        tableDetails.dataSource = self
        tableDetails.alwaysBounceVertical = false
        // Do any additional setup after loading the view.
    }

    func downloadJsonWithURL() {
            let url = NSURL(string: urlstring)
            URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
                if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
                    print(jsonObj!.value(forKey: "Detail"))
                if let detailsArray = jsonObj!.value(forKey: "Detail") as? NSArray {
                    for item in detailsArray {
                        if let detailDict = item as? NSDictionary {
                            if let name = detailDict.value(forKey: "productName"){
                                self.nameArray.append(name as! String)
                            }
                            if let price = detailDict.value(forKey: "productPrice"){
                                self.priceArray.append(price as! String)
                            }
                            if let image = detailDict.value(forKey: "img"){
                                self.productsArray.append(image as! String)
                            }
                        }
                    }
                }
                OperationQueue.main.addOperation({
                    self.tableDetails.reloadData()
                    for item in self.priceArray{
                        let endIndex = item.index(item.endIndex, offsetBy: -5)
                        let truncated = item.substring(to: endIndex)
                        self.price.append(truncated)
                    }
                    print(self.price)
                })
            }
        }).resume()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 3
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if (section == 0){
            return productsArray.count
        }else{
            return 1
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! productTableViewCell
            let arr = self.productsArray[indexPath.row]
            let urls = NSURL(string: arr)
            let data = NSData (contentsOf: urls! as URL)
            cell.imageview.image = UIImage(data: data! as Data)
            cell.nameLabel.text = nameArray[indexPath.row]
            let x = priceArray[indexPath.row]
            let array = String(x)
            cell.priceLabel.text = array
            cell.quantityTextField.text = "1"
            cell.pricearr = [price[indexPath.row]]
            return cell
        }else if indexPath.section == 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "couponcell", for: indexPath) as! CouponTableViewCell
            return cell
        }else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "checkout", for: indexPath) as! checkoutTableViewCell
            return cell
        }
    }

Body:
Add your stepper's outlet and action like in below image:

Replace your code with below one:

 class productTableViewCell: UITableViewCell {

            @IBOutlet var stepper: UIStepper!
            @IBOutlet var imageview: UIImageView!
            @IBOutlet var nameLabel: UILabel!
            @IBOutlet var priceLabel: UILabel!
            @IBOutlet var quantityTextField: UITextField!
            var pricearr = [String]()
            var price : String = ""
            override func awakeFromNib() {
                super.awakeFromNib()
                // Initialization code
            }
            @IBAction func changeCart(_ sender: Any) {
                let value = Int(stepper.value)
                quantityTextField.text = String(value)
                let x = Int(pricearr[0])
                priceLabel.text = String(x! * value)
            }
        }

Your code has one bug is that when you scroll tableView that time cell will be reset to its default value because of cell reuse.

EDIT:

Better way to achieve your goal (as far as I understood) can be as defined below :

Remove stepper action

Remove action from UITableview cell class

class productTableViewCell: UITableViewCell {

    @IBOutlet var stepper: UIStepper!
    @IBOutlet var imageview: UIImageView!
    @IBOutlet var nameLabel: UILabel!
    @IBOutlet var priceLabel: UILabel!
    @IBOutlet var quantityTextField: UITextField!
    var price : String = ""
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
}

3.Replace your core logic with below code

@IBOutlet var tableDetails: UITableView!
    var CartArray : [[String: String]] = []
    var itemsArray : [[String: AnyObject]] = []
    let urlstring = "http://www.json-generator.com/api/json/get/ceghMiWudK?indent=2"
    var sum = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        self.downloadJsonWithURL()
        tableDetails.delegate = self
        tableDetails.dataSource = self
        tableDetails.alwaysBounceVertical = false
        // Do any additional setup after loading the view.
    }
    func downloadJsonWithURL() {
        let url = NSURL(string: urlstring)
        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
              //  print(jsonObj!.value(forKey: "Detail"))
                self.itemsArray = (jsonObj!.value(forKey: "Detail") as? [[String: AnyObject]])!

                OperationQueue.main.addOperation({
                    self.tableDetails.reloadData()
                })
            }
        }).resume()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        if (section == 0){
            return itemsArray.count
        }else{
            return 1
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        //if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! productTableViewCell
            let arr = itemsArray[indexPath.row]
            let urls = NSURL(string: arr["img"] as! String)
            let data = NSData (contentsOf: urls! as URL)
            cell.imageview.image = UIImage(data: data! as Data)
            cell.nameLabel.text = arr["productName"] as? String
            var price = arr["productPrice"] as! String

        var aQuntity : Float = 1
        let itemId : Int =  arr["sku"] as! Int

        for aDic in CartArray{
            if aDic["id"] == String(itemId){

            aQuntity = Float(String(aDic["quantity"]!))!
            }
        }

        cell.stepper.value = Double(Int(aQuntity))
        cell.stepper.tag = indexPath.row

        cell.stepper.addTarget(self, action: #selector(stapperValueChange), for:.valueChanged)
        price = price.replacingOccurrences(of: "KD", with: "")

            cell.priceLabel.text = String(Float(price)! * aQuntity)
        cell.quantityTextField.text = String(aQuntity)
            cell.price = price
            return cell
       // }
//        else if indexPath.section == 1{
//            let cell = tableView.dequeueReusableCell(withIdentifier: "couponcell", for: indexPath) as! CouponTableViewCell
//            return cell
//        }else {
//            let cell = tableView.dequeueReusableCell(withIdentifier: "checkout", for: indexPath) as! checkoutTableViewCell
//            return cell
//        }

    }

    func stapperValueChange (stepper : UIStepper){
        let index : Int = stepper.tag
        let arr = itemsArray[index]

        let cell : productTableViewCell = tableDetails.cellForRow(at: IndexPath(row: index, section: 0)) as! productTableViewCell

                let value = Float(stepper.value)
                cell.quantityTextField.text = String(value)
                let x = Float(cell.price)
                cell.priceLabel.text = String(Int(x! * value))
        let itemId : Int =  arr["sku"] as! Int

        var aFoundIndex : Int?
        var counter : Int = 0

        _ = CartArray.filter { (aDic) -> Bool in

            if aDic["id"] ==  String(itemId){
            aFoundIndex = counter
            }
            counter += 1
            return false
        }

        if(aFoundIndex != nil){
        CartArray.remove(at: aFoundIndex!)
        }

        CartArray.append(["quantity" : String(value),"id" : String(itemId)])
    }


问:
400 bad request (making game with node and socket.io)
Making a game, I have no idea what I am doing when it comes to the online aspect.

I am using node.js using my computer as the server host and client (localhost:3000)

```<code>var express = require('express'); //no idea what I am doing here
var app = express();
var server = app.listen(3000);
var socket = require("socket.io");
var io = socket(server);
io.sockets.on('connection', newConnection);
app.use(express.static("public"));

console.log("server is up"); //tells me that the server is ready

function newConnection(socket) {
    console.log("new player!", socket.id); //tells me when a new player connects.
}
</code>```

also have this code within the main public javascript file

```<code>var socket;
socket = io.connect("localhost:3000");
</code>```

Whenever a new player  connects i get 400 bad request errors and the game thinks multiple players have joined.

picture to aid

so pls help.

答:
You will need to handle what happens when someone connects to your server.

```<code>var express = require('express');
var app = express();
var server = require("http").createServer(app);
server.listen(3000)  //server listens on port 3000
var io = require("socket.io")(server)

//this will be called when a new client connects
io.on("connection", (socket)=>{
   //socket is the socket object of the new client
   console.log("new socket connected with socket id = " + socket.id)

})
</code>```

Look at socket.io docs for more info.

Body:
Making a game, I have no idea what I am doing when it comes to the online aspect.

I am using node.js using my computer as the server host and client (localhost:3000)

var express = require('express'); //no idea what I am doing here
var app = express();
var server = app.listen(3000);
var socket = require("socket.io");
var io = socket(server);
io.sockets.on('connection', newConnection);
app.use(express.static("public"));

console.log("server is up"); //tells me that the server is ready

function newConnection(socket) {
    console.log("new player!", socket.id); //tells me when a new player connects.
}

also have this code within the main public javascript file

var socket;
socket = io.connect("localhost:3000");

Whenever a new player  connects i get 400 bad request errors and the game thinks multiple players have joined.

picture to aid

so pls help.

Body:
You will need to handle what happens when someone connects to your server.

var express = require('express');
var app = express();
var server = require("http").createServer(app);
server.listen(3000)  //server listens on port 3000
var io = require("socket.io")(server)

//this will be called when a new client connects
io.on("connection", (socket)=>{
   //socket is the socket object of the new client
   console.log("new socket connected with socket id = " + socket.id)

})

Look at socket.io docs for more info.


问:
Visual Studio 2015/2017 local NuGet feed HTTP 403
We've created a local NuGet feed with Nuget.Server. It is a simple ASP.NET application that is hosted on an IIS web server that is part of our local company network.

The url of the feed looks like this:

```<code>https://abc.company.com/packages/nuget
</code>```

The ISS authentication is enabled as followed:

The .NET authrization looks like this:

If I call the above mentioned feed url with Postman or Fiddler I get the following response:

```<code><?xml version="1.0" encoding="utf-8" standalone="yes"?>
<service xml:base="https://abc.company.com/packages/nuget/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app">
    <workspace>
        <atom:title>Default</atom:title>
        <collection href="Packages">
            <atom:title>Packages</atom:title>
        </collection>
    </workspace>
</service>
</code>```

If I now add the URL in the Visual Studio NuGet package sources:

and then choose the newly created package source the following screen appears where I enter my domain credentials (domain\user), but nothing happens:

As described before, when I access the site with any Browser (IE, Chrome, Edge) I don't have to enter my credentials and Fiddler/Postman do also not require any credentials.

On the VS PackageManager Output I get the following error message:

```<code>[Local] The V2 feed at 'https://abc.company.com/packages/nuget/Search()?$filter=IsAbsoluteLatestVersion&searchTerm=''&targetFramework='net462'&includePrerelease=true&$skip=0&$top=26' returned an unexpected status code '403 Forbidden ( The server denied the specified Uniform Resource Locator (URL). Contact the server administrator.  )'.
</code>```

When I call this URL with a browser I don't get any errors.

What is wrong in this setup?

答:
The problem was caused by our company proxy, that was also taken into account when opening internal sites. So I've added the following environment variable:

```<code>NO_PROXY
</code>```

as value I've added the company internal domain:

```<code>NO_PROXY = "abc.company.com"
</code>```

No it works locally and on our build agents.

Body:
We've created a local NuGet feed with Nuget.Server. It is a simple ASP.NET application that is hosted on an IIS web server that is part of our local company network.

The url of the feed looks like this:

https://abc.company.com/packages/nuget

The ISS authentication is enabled as followed:

The .NET authrization looks like this:

If I call the above mentioned feed url with Postman or Fiddler I get the following response:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<service xml:base="https://abc.company.com/packages/nuget/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:app="http://www.w3.org/2007/app" xmlns="http://www.w3.org/2007/app">
    <workspace>
        <atom:title>Default</atom:title>
        <collection href="Packages">
            <atom:title>Packages</atom:title>
        </collection>
    </workspace>
</service>

If I now add the URL in the Visual Studio NuGet package sources:

and then choose the newly created package source the following screen appears where I enter my domain credentials (domain\user), but nothing happens:

As described before, when I access the site with any Browser (IE, Chrome, Edge) I don't have to enter my credentials and Fiddler/Postman do also not require any credentials.

On the VS PackageManager Output I get the following error message:

[Local] The V2 feed at 'https://abc.company.com/packages/nuget/Search()?$filter=IsAbsoluteLatestVersion&searchTerm=''&targetFramework='net462'&includePrerelease=true&$skip=0&$top=26' returned an unexpected status code '403 Forbidden ( The server denied the specified Uniform Resource Locator (URL). Contact the server administrator.  )'.

When I call this URL with a browser I don't get any errors.

What is wrong in this setup?

Body:
The problem was caused by our company proxy, that was also taken into account when opening internal sites. So I've added the following environment variable:

NO_PROXY

as value I've added the company internal domain:

NO_PROXY = "abc.company.com"

No it works locally and on our build agents.


问:
Finding entries in one MySQL table based on conditions on another table
I've got a table of hardware and a table of incidents. Each hardware has a unique tag, and the incidents are tied to the tag.

How can I select all the hardware which has at least one incident listed as unresolved?

I can't just do a join, because then if one piece of hardware had multiple unresolved issues, it would show up multiple times.

答:
This can also work</p>

```<code>SELECT hd.name, inc.issue, FROM hardware hd INNER JOIN inc ON hd.tag = inc.tag AND inc.issue = 'unresolved' group by hd.name
</code>```

OwnerDisplayName: Asmor

Body:
This can also work

SELECT hd.name, inc.issue, FROM hardware hd INNER JOIN inc ON hd.tag = inc.tag AND inc.issue = 'unresolved' group by hd.name


问:
sending username and password via post request in volley in android
I am using this url to send post reqeust via volley:"http://136.243.146.41:8443/api/GetMainCategories".
here is my code:

```<code>    void MakePostRequest() {
    StringRequest postRequest = new StringRequest(Request.Method.POST, mainmenurl,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject("{response}");

                        //makemainmenulist();
                        Toast.makeText(Cofeelist.this,"success!--->>>>"+response, Toast.LENGTH_LONG).show();
                        Log.i("sucsses!.....",response);
                        //  value1= jsonResponse.getString("Your ID1");
                      //  value2= jsonResponse.getString("Your ID2");

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(Cofeelist.this,"error1!--->>>>"+e, Toast.LENGTH_LONG).show();
                        Log.i("Error1!.....",e+"");

                        // banner_id = null;
                       // full_id = null;
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                   Toast.makeText(Cofeelist.this,"error2!--->>>>"+error, Toast.LENGTH_LONG).show();
                    Log.i("error2!.....",error+"");

                    // value1= null;
                   // value2= null;
                }
            }
    ) {
        // here is params will add to your url using post method
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("username", "pourya");
            params.put("key", "54a65sdf4a35s4d");
            return params;
        }
    };
    Volley.newRequestQueue(this).add(postRequest);
}
</code>```

but i got this error:"com.android.volley.NoConnectionError: java.io.EOFException ".i changed the url to"tarkhinehapp/api/GetMainCategories" but i got another error "  com.android.volley.ServerError"

答:
I used volley lib to connect to server and sent username and pass via querystring in url as below:

```<code>        MyVolleyStringRequest mainmenureq=new MyVolleyStringRequest(Request.Method.GET, G.urlBase+"MainCategoriesApi?username="+"username"+"&"+"key="+"pass",new MyListener(this));
</code>```

the volley made my job so easy!

Body:
I am using this url to send post reqeust via volley:"http://136.243.146.41:8443/api/GetMainCategories".
here is my code:

    void MakePostRequest() {
    StringRequest postRequest = new StringRequest(Request.Method.POST, mainmenurl,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject("{response}");

                        //makemainmenulist();
                        Toast.makeText(Cofeelist.this,"success!--->>>>"+response, Toast.LENGTH_LONG).show();
                        Log.i("sucsses!.....",response);
                        //  value1= jsonResponse.getString("Your ID1");
                      //  value2= jsonResponse.getString("Your ID2");

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(Cofeelist.this,"error1!--->>>>"+e, Toast.LENGTH_LONG).show();
                        Log.i("Error1!.....",e+"");

                        // banner_id = null;
                       // full_id = null;
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                   Toast.makeText(Cofeelist.this,"error2!--->>>>"+error, Toast.LENGTH_LONG).show();
                    Log.i("error2!.....",error+"");

                    // value1= null;
                   // value2= null;
                }
            }
    ) {
        // here is params will add to your url using post method
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("username", "pourya");
            params.put("key", "54a65sdf4a35s4d");
            return params;
        }
    };
    Volley.newRequestQueue(this).add(postRequest);
}

but i got this error:"com.android.volley.NoConnectionError: java.io.EOFException ".i changed the url to"tarkhinehapp/api/GetMainCategories" but i got another error "  com.android.volley.ServerError"

Body:
I used volley lib to connect to server and sent username and pass via querystring in url as below:

        MyVolleyStringRequest mainmenureq=new MyVolleyStringRequest(Request.Method.GET, G.urlBase+"MainCategoriesApi?username="+"username"+"&"+"key="+"pass",new MyListener(this));

the volley made my job so easy!


问:
how to represent members in a list of list as a list in python
I have a list of lists. How can I get a specific index members in each element as a list without using a loop and assignment. Below code snippet is an example. Actual list contains more than 3 sublists. Output should be like a list say mem_lst given below.</p>

```<code>    alst = [['abc', 1 , 2], ['cde', 2, 2], ['xyz', 2, 2]]
    o/p: mem_lst = [ 'abc', 'cde', 'xyz']
</code>```

答:
```<code>In [1]: alst = [['abc', 1 , 2], ['cde', 2, 2], ['xyz', 2, 2]]

In [2]: import operator

In [3]: map(operator.itemgetter(0), alst)
Out[3]: <map at 0x104b43160>

In [4]: list(_)
Out[4]: ['abc', 'cde', 'xyz']
</code>```

In this approach you don't use loop, and you can use map as a iterator to avoiding storage of list, but if you strongly need a list, just need to wrap it in list()

Body:
I have a list of lists. How can I get a specific index members in each element as a list without using a loop and assignment. Below code snippet is an example. Actual list contains more than 3 sublists. Output should be like a list say mem_lst given below.

    alst = [['abc', 1 , 2], ['cde', 2, 2], ['xyz', 2, 2]]
    o/p: mem_lst = [ 'abc', 'cde', 'xyz']

Body:
In [1]: alst = [['abc', 1 , 2], ['cde', 2, 2], ['xyz', 2, 2]]

In [2]: import operator

In [3]: map(operator.itemgetter(0), alst)
Out[3]: <map at 0x104b43160>

In [4]: list(_)
Out[4]: ['abc', 'cde', 'xyz']

In this approach you don't use loop, and you can use map as a iterator to avoiding storage of list, but if you strongly need a list, just need to wrap it in list()


问:
Required Mime Type for CSV
Is there some way to get proper mime type for .csv files to include in the attachment of my jsp page?</p>

Title: Required Mime Type for CSV

Body: Content-Type: text/csv


问:
How to modify IP & port use react-native Android?
I used the react-native Android demo project AwesomeProject and within the project I executed:

```<code>react-native start
</code>```

In a second terminal:

```<code>react-native run-android
</code>```

To start webserver and install the Android APK. The default webserver configuration is localhost:8081, how can I modify the webserver port, and how do I update recording of the IP & Port in Android project.

Edit:

I just found out that can modify ip address in Android debug setting, it seems "getDebugServerHost" is a private API, does Facebook provide any API to change ip&port?

答:
There is a small work around for this. Anyone running this on a physical device(or even otherwise) can restart their adb session using a different port.

eg.

```<code>react-native start --port=1234
</code>```

On a different cmd/terminal window.

```<code>react-native run-android
</code>```

After which I am greeted by these messages.

```<code>BUILD SUCCESSFUL

Total time: 22.589 secs
Running C:\SDK/platform-tools/adb -s VY0025160560725694 reverse tcp:8081
tcp:8081
</code>```

This runs it on default reverse port of 8081, which is blocked by McAfee.

Work around:

```<code>adb reverse tcp:8081 tcp:1234
</code>```

Try it out. It works for me.

Note: You may have to kill and re-open the app.

Currently I am unable to provide an answer for an emulated device since I do not have one installed on my system. But the symantics should be similar.

<s>Note: This may break automatic code updates using watchman.</s>

Body:
I used the react-native Android demo project AwesomeProject and within the project I executed:

react-native start

In a second terminal:

react-native run-android

To start webserver and install the Android APK. The default webserver configuration is localhost:8081, how can I modify the webserver port, and how do I update recording of the IP & Port in Android project.

Edit:

I just found out that can modify ip address in Android debug setting, it seems "getDebugServerHost" is a private API, does Facebook provide any API to change ip&port?

Body:
There is a small work around for this. Anyone running this on a physical device(or even otherwise) can restart their adb session using a different port.

eg.

react-native start --port=1234

On a different cmd/terminal window.

react-native run-android

After which I am greeted by these messages.

BUILD SUCCESSFUL

Total time: 22.589 secs
Running C:\SDK/platform-tools/adb -s VY0025160560725694 reverse tcp:8081
tcp:8081

This runs it on default reverse port of 8081, which is blocked by McAfee.

Work around:

adb reverse tcp:8081 tcp:1234

Try it out. It works for me.

Note: You may have to kill and re-open the app.

Currently I am unable to provide an answer for an emulated device since I do not have one installed on my system. But the symantics should be similar.

<s>Note: This may break automatic code updates using watchman.</s>


问:
std::vector new runs out of memory
I am writing a program in C++ for a embedded platform STM32. I used to use normal arrays but for the first time I am using vectors in it. So far it runs well in the majority of the cases. However in a very few cases I got the error stated in the title eventhough it shouldn't. Would appreciate some help as I run out of ideas.

My situation

The vectors are like this

```<code>struct Boundary{
  vector<unsigned short> x; //The x coordinates
  vector<unsigned short> y; //The y coordinates
};
</code>```

Everytime I use these vectors I clear them with

```<code>boundary0.x.clear();
boundary0.y.clear();
</code>```

I add elements with the normal push_back

The strange part

Sometimes, the program finishes with the "Operator new out of memory" when adding elements to the vector.

"!Ah, you run out of memory!"- you would say, but that is the strange part. The vector so far has only 275 elements which being short gives 550 bytes.

But this very same program has handled the same vector with many more elements (500 or more) without problem.

Somehow, you previously leaked out memory!- can be said, and I suspect that. Perhaps I used this before and failed to clean it up (although I cleaned it as I stated) but this error appears even when I disconnect and connect the processor wiping out any previous used memory.

I am at lost why this could be happening. Any help or comment or advice greatly appreciated.

答:
When adding an element to a vector using Vector::push_back and the number of elements reach its initial capacity, then the internally reserved buffer will be reallocated (i.e. the existing one might be freed and a larger chunk of memory is allocated). This might "fragment" your memory, as smaller chunks of free memory get available yet the system requires larger chunks, which at some point it might not find any more if the system has rather low memory). Hence, if you do this very often with a lot of vectors, it could get a problem on an embedded system.

Hard to say if this is actually the reason - but I'd try to initialize the vector with a capacity that it will most likely not overreach. Maybe that solves your problem. So you could try out:

```<code>struct Boundary{
    vector<unsigned short> x = vector<unsigned short>(500); //The x coordinates
    vector<unsigned short> y = vector<unsigned short>(500); //The y coordinates
};
</code>```

Title: std::vector new runs out of memory

Body:
I am writing a program in C++ for a embedded platform STM32. I used to use normal arrays but for the first time I am using vectors in it. So far it runs well in the majority of the cases. However in a very few cases I got the error stated in the title eventhough it shouldn't. Would appreciate some help as I run out of ideas.

My situation

The vectors are like this

struct Boundary{
  vector<unsigned short> x; //The x coordinates
  vector<unsigned short> y; //The y coordinates
};

Everytime I use these vectors I clear them with

boundary0.x.clear();
boundary0.y.clear();

I add elements with the normal push_back

The strange part

Sometimes, the program finishes with the "Operator new out of memory" when adding elements to the vector.

"!Ah, you run out of memory!"- you would say, but that is the strange part. The vector so far has only 275 elements which being short gives 550 bytes.

But this very same program has handled the same vector with many more elements (500 or more) without problem.

Somehow, you previously leaked out memory!- can be said, and I suspect that. Perhaps I used this before and failed to clean it up (although I cleaned it as I stated) but this error appears even when I disconnect and connect the processor wiping out any previous used memory.

I am at lost why this could be happening. Any help or comment or advice greatly appreciated.

Body:
When adding an element to a vector using Vector::push_back and the number of elements reach its initial capacity, then the internally reserved buffer will be reallocated (i.e. the existing one might be freed and a larger chunk of memory is allocated). This might "fragment" your memory, as smaller chunks of free memory get available yet the system requires larger chunks, which at some point it might not find any more if the system has rather low memory). Hence, if you do this very often with a lot of vectors, it could get a problem on an embedded system.

Hard to say if this is actually the reason - but I'd try to initialize the vector with a capacity that it will most likely not overreach. Maybe that solves your problem. So you could try out:

struct Boundary{
    vector<unsigned short> x = vector<unsigned short>(500); //The x coordinates
    vector<unsigned short> y = vector<unsigned short>(500); //The y coordinates
};


问:
How to order by custom time format in laravel?
I have to order a database table with a custom time format.
 The time format used in the table is like this:

1:30:PM

8:35:PM

5:50:PM

7:00 PM

I tried the following, but it does not sort them all in the correct order.

```<code>            ->orderBy('time_schedule.start_time', 'asc');
</code>```

After sorting the with the above method the result comes like

1:30:PM

5:50:PM

8:35:PM

7:00 PM

I'm not able to change the format saved, as i'm not working on that part of the application.

Also the data have to come sorted form laravel, cannot use front end sorting in my situation.

Please let me know whether there is a way to sort this with laravel.

答:
You could use STR_TO_DATE function like:

```<code>SELECT
  start_time
FROM
  tablename
ORDER BY
  STR_TO_DATE(start_time, '%l:%i %p');
</code>```

For this you have to use raw query.

Reference

Body:
I have to order a database table with a custom time format.
 The time format used in the table is like this:

1:30:PM

8:35:PM

5:50:PM

7:00 PM

I tried the following, but it does not sort them all in the correct order.

            ->orderBy('time_schedule.start_time', 'asc');

After sorting the with the above method the result comes like

1:30:PM

5:50:PM

8:35:PM

7:00 PM

I'm not able to change the format saved, as i'm not working on that part of the application.

Also the data have to come sorted form laravel, cannot use front end sorting in my situation.

Please let me know whether there is a way to sort this with laravel.

Body:
You could use STR_TO_DATE function like:

SELECT
  start_time
FROM
  tablename
ORDER BY
  STR_TO_DATE(start_time, '%l:%i %p');

For this you have to use raw query.

Reference


答:
You can use closer for that</p>

```<code>->orderBy(function($item) {
     return Carbon::createFromFormat('g:i a', $item->date)->format('Y-m-d H:i:s);
});
</code>```

Title: How to order by custom time format in laravel?

Body:
You can use closer for that

->orderBy(function($item) {
     return Carbon::createFromFormat('g:i a', $item->date)->format('Y-m-d H:i:s);
});