答:
From document.getElementsByClassName('isq') get an array and iterate through it and set the innerHTML to ''.

var divs = document.getElementsByClassName('isq');

var emptyDivs = function(){
  Array.from(divs).forEach(function(ele){
    ele.innerHTML = '';
  });
}

emptyDivs();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row r1">
    <div class="square o1">
        <div class="isq i1">adsfas</div>
        <div class="isq i2">adfasd</div>
        <div class="isq i3"></div>
        <div class="isq i4"></div>
        <div class="isq i5"></div>
        <div class="isq i6"></div>
        <div class="isq i7"></div>
        <div class="isq i8"></div>
        <div class="isq i9"></div>
    </div>
    <div class="square o2">
        <div class="isq i1">adfasdf</div>
        <div class="isq i2"></div>
        <div class="isq i3"></div>
        <div class="isq i4"></div>
        <div class="isq i5"></div>
        <div class="isq i6"></div>
        <div class="isq i7"></div>
        <div class="isq i8"></div>
        <div class="isq i9"></div>
    </div>
    <div class="square o3">
        <div class="isq i1"></div>
        <div class="isq i2"></div>
        <div class="isq i3"></div>
        <div class="isq i4"></div>
        <div class="isq i5"></div>
        <div class="isq i6"></div>
        <div class="isq i7"></div>
        <div class="isq i8"></div>
        <div class="isq i9"></div>
    </div>
</div></code>```

Body:
From document.getElementsByClassName('isq') get an array and iterate through it and set the innerHTML to ''.

var divs = document.getElementsByClassName('isq');

var emptyDivs = function(){
  Array.from(divs).forEach(function(ele){
    ele.innerHTML = '';
  });
}

emptyDivs();

<div class="row r1">
    <div class="square o1">
        <div class="isq i1">adsfas</div>
        <div class="isq i2">adfasd</div>
        <div class="isq i3"></div>
        <div class="isq i4"></div>
        <div class="isq i5"></div>
        <div class="isq i6"></div>
        <div class="isq i7"></div>
        <div class="isq i8"></div>
        <div class="isq i9"></div>
    </div>
    <div class="square o2">
        <div class="isq i1">adfasdf</div>
        <div class="isq i2"></div>
        <div class="isq i3"></div>
        <div class="isq i4"></div>
        <div class="isq i5"></div>
        <div class="isq i6"></div>
        <div class="isq i7"></div>
        <div class="isq i8"></div>
        <div class="isq i9"></div>
    </div>
    <div class="square o3">
        <div class="isq i1"></div>
        <div class="isq i2"></div>
        <div class="isq i3"></div>
        <div class="isq i4"></div>
        <div class="isq i5"></div>
        <div class="isq i6"></div>
        <div class="isq i7"></div>
        <div class="isq i8"></div>
        <div class="isq i9"></div>
    </div>
</div>


来源: stackexchange

问:
Validate file exist in the AjaxFileUpload are uploaded or Pending
How can I validate that the file selected in AjaxFileUpload is already uploaded or are Pending

Here is my .aspx page code

```<code> <form id="form1" runat="server">
    <asp:ToolkitScriptManager runat="server">
    </asp:ToolkitScriptManager>
    <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
        Width="400px" OnUploadComplete="OnUploadComplete" Mode="Auto" />
</form>
</code>```

.aspx.cs code is

```<code> protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string fileName = Path.GetFileName(e.FileName);
        AjaxFileUpload1.SaveAs(Server.MapPath("~/uploads/" + fileName));
    }
</code>```

I had implement java script as through which I am able to validate that file exist in Ajaxfileupload or not but which file is Pending for that I am not able to validate.

```<code>  function validate() {
        if ($(".ajax__fileupload_fileItemInfo").length > 0) {
            alert('file exist .');
        }
        else {
            alert('select your file');
        }
    }
</code>```

Suppose I had already uploaded 2 files and then after I add a new file to get upload but How can I validate that 2 files are uploaded and the new placed file is not uploaded.
I need to validate this from java script

I need to validate this on any button onclientclick event.

答:
I had found the answer that worked for me
Implement the code </p>

```<code>function validateImageUploaded() {
    if ($(".ajax__fileupload_fileItemInfo").length > 0) {
        if ($("div.ajax__fileupload_fileItemInfo").children('div').hasClass("pendingState"))
        {
            alert("found");
            return false;
        }
    }
    else {
        alert('select your file');
        return false;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I validate that the file selected in AjaxFileUpload is already uploaded or are Pending

Here is my .aspx page code

 <form id="form1" runat="server">
    <asp:ToolkitScriptManager runat="server">
    </asp:ToolkitScriptManager>
    <asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
        Width="400px" OnUploadComplete="OnUploadComplete" Mode="Auto" />
</form>

.aspx.cs code is

 protected void OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
    {
        string fileName = Path.GetFileName(e.FileName);
        AjaxFileUpload1.SaveAs(Server.MapPath("~/uploads/" + fileName));
    }

I had implement java script as through which I am able to validate that file exist in Ajaxfileupload or not but which file is Pending for that I am not able to validate.

  function validate() {
        if ($(".ajax__fileupload_fileItemInfo").length > 0) {
            alert('file exist .');
        }
        else {
            alert('select your file');
        }
    }

Suppose I had already uploaded 2 files and then after I add a new file to get upload but How can I validate that 2 files are uploaded and the new placed file is not uploaded.
I need to validate this from java script

I need to validate this on any button onclientclick event.

Body:
I had found the answer that worked for me
Implement the code

function validateImageUploaded() {
    if ($(".ajax__fileupload_fileItemInfo").length > 0) {
        if ($("div.ajax__fileupload_fileItemInfo").children('div').hasClass("pendingState"))
        {
            alert("found");
            return false;
        }
    }
    else {
        alert('select your file');
        return false;
    }
}


问:
Unable to find htdocs on xampp
I have installed XAMPP for macOS Sierra.

I have one icon in application for XAMPP.

I am able to run the server & it's services but I am not able to find the htdocs folder.

I have not found it under \Library\Webserver

答:
```<code>/Applications/XAMPP/xamppfiles
</code>```

That's where you will find htdocs.

ContentLicense: CC BY-SA 4.0

Title: Unable to find htdocs on xampp

Body:
/Applications/XAMPP/xamppfiles

That's where you will find htdocs.


问:
PHP Regex to match url contains url fragment
I have one url fragment: page/login and i need to know if another url fragment contains them.

These, will match:

```<code>/admin/page/login/
/admin/page/login
admin/page/login
http://www.dot.com/admin/page/login
/admin/page/login?id=10
/admin/page/login/id/10
/admin/page/login/?id=10
/admin/page/login/user?id=10
/admin/page/login/user/?id=10
page/login
page/login/
page/login/id/10
/page/login/id/10
</code>```

And these not:

```<code>/admin/firstpage/login
admin/page/loginOk
/admin/page/loginOk/id/10
mypage/login/id/10
/mypage/login/id/10
mypage/login
</code>```

I tried: page\/login[\/\s\?], \/?page\/login[\/\s\?] without any result

答:
You can use a word boundary so partial matches aren't matched.

```<code>\bpage\/login[\/\s?]
</code>```

Demo: https://regex101.com/r/yhNsdw/1/

Also if you change your delimiter none of the forward slashes will need to be escaped.

Body:
I have one url fragment: page/login and i need to know if another url fragment contains them.

These, will match:

/admin/page/login/
/admin/page/login
admin/page/login
http://www.dot.com/admin/page/login
/admin/page/login?id=10
/admin/page/login/id/10
/admin/page/login/?id=10
/admin/page/login/user?id=10
/admin/page/login/user/?id=10
page/login
page/login/
page/login/id/10
/page/login/id/10

And these not:

/admin/firstpage/login
admin/page/loginOk
/admin/page/loginOk/id/10
mypage/login/id/10
/mypage/login/id/10
mypage/login

I tried: page\/login[\/\s\?], \/?page\/login[\/\s\?] without any result

Body:
You can use a word boundary so partial matches aren't matched.

\bpage\/login[\/\s?]

Demo: https://regex101.com/r/yhNsdw/1/

Also if you change your delimiter none of the forward slashes will need to be escaped.


问:
Angular JS : Failed to instantiate module test due to:
I'm running some Javascript inside a HTML file. And I'm trying to use some Angular JS with the function ng-repeat. Each time I run it, I get this error in the console :

```<code>angular.js:38 Uncaught Error: [$injector:modulerr]
</code>```

And when I click on the link within the error message in the console, I get this:

Failed to instantiate module test due to:
Error: [$injector:nomod] http://errors.angularjs.org/1.6.4/$injector/nomod?p0=test
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:6:425
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:26:270
    at b (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:25:299)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:26:44
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:42:117
    at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:7:495)
    at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:41:476)
    at eb (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:46:44)
    at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:21:373)
    at Sc (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:22:179

Here is my Javascript inside my HTML file:

```<code>//Get User ID and Trip ID in URL

function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
    var sParameterName = sURLVariables[i].split('=');
    if (sParameterName[0] == sParam)
    {
        return sParameterName[1];
    }
}
}

 var userid = GetURLParameter('userid');
 var tripid = GetURLParameter('tripid');

  </script>

<script>

 //Get photos URL inside a particular Trip ID from a User ID

  var database = firebase.database();
  database.ref(`photos/${userid}/trips/${tripid}`).once('value') //
  will return you all the photo objects inside the `tripId`
  .then(photosSnap => {
  var photosObj = photosSnap.val();
  var photosUrl = Object.keys(photosObj).map(key =>
  photosObj[key].photourl);
  // then you can return the array or use it here;

   var app = angular.module('test', []);

     app.controller('MainCtrl', function($scope) {
       $scope.urls = photosUrl;

   });

console.log(photosUrl); // will be an array of all the photourls
}).catch(err => alert(err));
</code>```

And finally my HTML which uses ng-repeat:

```<code><div class="spot" ng-app="test" ng-controller="MainCtrl">

     <ul>
        <li ng-repeat="url in urls">{{url}}</li>
     </ul>

 </div>
</code>```

I'm using a controller with scope to loop inside my HTML with an array. So first I don't know where my error message comes from, and second I'm not sure i'm using the controller and ng-repeat properly.

Thanks

PS: I included in the head tag of my HTML file this link :

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</code>```

EDIT: my Javascript inside my HTML updated (I moved everything inside the controller)

The error message is gone, my html just doesn't display any url (though the console shows there are 4 urls in my array photosUrl)

```<code> <script>

  //Get photos URL inside a particular Trip ID from a User ID

var app = angular.module('test', []);

app.controller('MainCtrl', function($scope) {

    var database = firebase.database();
    database.ref(`photos/${userid}/trips/${tripid}`).once('value') //
    will return you all the photo objects inside the `tripId`
    .then(photosSnap => {
    var photosObj = photosSnap.val();
    var photosUrl = Object.keys(photosObj).map(key =>
    photosObj[key].photourl);
    // then you can return the array or use it here;

    $scope.urls = photosUrl;

console.log(photosUrl); // will be an array of all the photourls
}).catch(err => alert(err));

     });

  </script>
</code>```

答:
You should move the database into your 'MainCtrl' controller.

Or, in a perfect world, you would abstract that logic into a seperate factory/service, and inject THAT into your controller.

Body:
I'm running some Javascript inside a HTML file. And I'm trying to use some Angular JS with the function ng-repeat. Each time I run it, I get this error in the console :

angular.js:38 Uncaught Error: [$injector:modulerr]

And when I click on the link within the error message in the console, I get this:

Failed to instantiate module test due to:
Error: [$injector:nomod] http://errors.angularjs.org/1.6.4/$injector/nomod?p0=test
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:6:425
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:26:270
    at b (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:25:299)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:26:44
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:42:117
    at q (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:7:495)
    at g (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:41:476)
    at eb (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:46:44)
    at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:21:373)
    at Sc (https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js:22:179

Here is my Javascript inside my HTML file:

//Get User ID and Trip ID in URL

function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
    var sParameterName = sURLVariables[i].split('=');
    if (sParameterName[0] == sParam)
    {
        return sParameterName[1];
    }
}
}

 var userid = GetURLParameter('userid');
 var tripid = GetURLParameter('tripid');

  </script>

EDIT: my Javascript inside my HTML updated (I moved everything inside the controller)

The error message is gone, my html just doesn't display any url (though the console shows there are 4 urls in my array photosUrl)


问:
Wrong redirection Uri with Google OAuth2
I have been working in a web Symfony app that uses a google oauth2. Well, to use it I had to create a Client and a Secret id for development environtment.

The redirection uri is:

```<code>http://melomaniacs.com/app_dev.php/validate/
</code>```

and it is working properly.
When I finish and put on a EC2 instance, I created a new Client an Secret id for a production environment and set them properly on parameters, and the uri is:

```<code>http://www.melomaniacsweb.com/validate/
</code>```

The problem is google is redirecting to the dev one uri, not the new one.

I tried:
php bin/console cache:warmup --env=prod
clearing the browser cache

Anybody know why this behaviour?

Thanks

答:
It solves by clearing cache without warmup first:</p>

```<code>php bin/console cache:clear --env=prod --no-debug --no-warmup

php bin/console cache:warmup --env=prod
</code>```

Body:
I have been working in a web Symfony app that uses a google oauth2. Well, to use it I had to create a Client and a Secret id for development environtment.

The redirection uri is:

http://melomaniacs.com/app_dev.php/validate/

and it is working properly.
When I finish and put on a EC2 instance, I created a new Client an Secret id for a production environment and set them properly on parameters, and the uri is:

http://www.melomaniacsweb.com/validate/

The problem is google is redirecting to the dev one uri, not the new one.

I tried:
php bin/console cache:warmup --env=prod
clearing the browser cache

Anybody know why this behaviour?

Thanks

Body:
It solves by clearing cache without warmup first:

php bin/console cache:clear --env=prod --no-debug --no-warmup

php bin/console cache:warmup --env=prod


问:
Stuck with evenly resizing an image animation
I'm trying to recreate this effect:

http://www.eginstill.com/

I tired everything, I got it to resize but can't get that effect where image is fixed and its being resized from all sides.

Here is my code:

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

    ```

Not sure what to do. Thanks.

答:
Please see the snippet in this code.

I changed your IDs by class (it's more convenient, we prefer use class instead of ids.)

updated the css of .img-01 element

$(document).ready(function() {
  $(".img-01").click(function() {
    $(this).animate({
      top: '20px',
      right: '100px',
      left: '30px',
      bottom: '20px'
    }, 1500);
  });
});

$(document).ready(function() {

  $('.photograph').hide();
  $('.photograph').each(function(i) {
    if (this.complete) {
      $(this).fadeIn();
    } else {
      $(this).load(function() {
        $(this).fadeIn();
      });
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 0;
  margin: 0;
}

.menu {
  float: left;
  width: 200px;
  height: 1000px;
  background: black;
  display: inline-block;
}

.img-01 {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    background-image: url(https://s-media-cache-ak0.pinimg.com/236x/95/c3/70/95c3708a97e9a7e56d4e13166dd5dd24.jpg);
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

```

Body:
I'm trying to recreate this effect:

http://www.eginstill.com/

I tired everything, I got it to resize but can't get that effect where image is fixed and its being resized from all sides.

Here is my code:

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

Not sure what to do. Thanks.

Body:
Please see the snippet in this code.

I changed your IDs by class (it's more convenient, we prefer use class instead of ids.)

updated the css of .img-01 element

$(document).ready(function() {
  $(".img-01").click(function() {
    $(this).animate({
      top: '20px',
      right: '100px',
      left: '30px',
      bottom: '20px'
    }, 1500);
  });
});

$(document).ready(function() {

  $('.photograph').hide();
  $('.photograph').each(function(i) {
    if (this.complete) {
      $(this).fadeIn();
    } else {
      $(this).load(function() {
        $(this).fadeIn();
      });
    }
  });
});

body {
  padding: 0;
  margin: 0;
}

.menu {
  float: left;
  width: 200px;
  height: 1000px;
  background: black;
  display: inline-block;
}

.img-01 {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background-attachment: fixed;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    background-image: url(https://s-media-cache-ak0.pinimg.com/236x/95/c3/70/95c3708a97e9a7e56d4e13166dd5dd24.jpg);
}

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>

  <div id="menu"></div>

  <div class="img-01">
    </div>

  <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</body>

</html>


问:
Where to place tsconfig.json in Symfony Encore to define TypeScript config?
Symfony Encore now supports using TypeScript by default (Add support to enableTypescriptLoader), and it works great. However, I would like to configure my TypeScript configuration using a tsconfig.json file.

I tried figuring out where to place this, but I got lost in the rabbithole and didn't figure out where I should place the file for ts-loader to pick it up. Or if there is a configuration that enables this.

答:
Having the tsconfig.json in same place of webpack.config.js should do the job.

ts-loader assumes the same as default configuration.

Check ts-loader configuration documentation, there is one option for configuring file name in case it is located somewhere else.

UPDATE:
Keep an eye on this docs there is some documentation on the way.

Configuration goes like:

```<code>.enableTypeScriptLoader(function (typeScriptConfigOptions) {
    typeScriptConfigOptions.transpileOnly = true;
    typeScriptConfigOptions.configFileName = '/path/to/tsconfig.json';
});
</code>```

But again, loader defaults for configFileName option is: tsconfig.json so, should be enough having the file in same directory of webpack.config.js or in same directory from where you run webpack, not sure now actually. I always run webpack from same dir as webpack.config.js :)

Cheers

Body:
Having the tsconfig.json in same place of webpack.config.js should do the job.

ts-loader assumes the same as default configuration.

Check ts-loader configuration documentation, there is one option for configuring file name in case it is located somewhere else.

UPDATE:
Keep an eye on this docs there is some documentation on the way.

Configuration goes like:

.enableTypeScriptLoader(function (typeScriptConfigOptions) {
    typeScriptConfigOptions.transpileOnly = true;
    typeScriptConfigOptions.configFileName = '/path/to/tsconfig.json';
});

But again, loader defaults for configFileName option is: tsconfig.json so, should be enough having the file in same directory of webpack.config.js or in same directory from where you run webpack, not sure now actually. I always run webpack from same dir as webpack.config.js :)

Cheers


问:
Not able to access protected variables
I have created a simple test project to use a class as a custom List type and have a couple of questions regarding the use of different syntax when declaring variables.

I have a class called CustomerInfo which defines all the variables required to be stored for the customer information which will be added to a list as seen below:

```<code>    protected string Firstname { get; set; }

    protected string Surname { get; set; }

    protected int Age
    {
        get
        {
            return Age;
        }
        set
        {
            if(value < 0)
            {
                throw new AgeException("Age cannot be a value below 0");
            }
            else
            {
                Age = value;
            }
        }
    }

    protected string Gender { get; set; }
</code>```

Questions:

1) Why does the code below not allow me to access the protected variables in the CustomerInfo class even though I am inheriting the class?

```<code>class Program : CustomerInfo
{
    static void Main(string[] args)
    {
        CustomerInfo custInfo = new CustomerInfo();
        custInfo.Firstname = "Richard"; //not working
        custInfo.Surname = "Smith"; //not working

        List<CustomerInfo> custList = new List<CustomerInfo>();
        custList.Add(custInfo);
    }
}
</code>```

2) When looking at Windows Forms applications they already contain an inheritence of Form in the code of any Form you create. If you have to inherit a class to access the protected variables & methods it has, how can you access the variables if each form already has an inheritance that you cannot remove?

Thanks

答:
The protected keyword is a member access modifier. A protected member
  is accessible within its class and by derived class instances.
  Source MSDN

```<code>CustomerInfo custInfo = new CustomerInfo();
custInfo.Firstname = "Richard"; //not working
custInfo.Surname = "Smith"; //not working
</code>```

This code is not working because your custInfo's Firtsname and Surname are not accessible in the Program class. But you should be able to do the following, as your Program class is inherited from CustomerInfo :

```<code>Firstname = "Richard";
Surname = "Smith";
</code>```

For the second question you can do something like the following:

```<code>Class1 : Form
{
     // here will be your protected members
}
Class2 : Class1
</code>```

Title: Not able to access protected variables

Body:
I have created a simple test project to use a class as a custom List type and have a couple of questions regarding the use of different syntax when declaring variables.

I have a class called CustomerInfo which defines all the variables required to be stored for the customer information which will be added to a list as seen below:

    protected string Firstname { get; set; }

    protected string Surname { get; set; }

    protected int Age
    {
        get
        {
            return Age;
        }
        set
        {
            if(value < 0)
            {
                throw new AgeException("Age cannot be a value below 0");
            }
            else
            {
                Age = value;
            }
        }
    }

    protected string Gender { get; set; }

Questions:

1) Why does the code below not allow me to access the protected variables in the CustomerInfo class even though I am inheriting the class?

class Program : CustomerInfo
{
    static void Main(string[] args)
    {
        CustomerInfo custInfo = new CustomerInfo();
        custInfo.Firstname = "Richard"; //not working
        custInfo.Surname = "Smith"; //not working

        List<CustomerInfo> custList = new List<CustomerInfo>();
        custList.Add(custInfo);
    }
}

2) When looking at Windows Forms applications they already contain an inheritence of Form in the code of any Form you create. If you have to inherit a class to access the protected variables & methods it has, how can you access the variables if each form already has an inheritance that you cannot remove?

Thanks

Body:
The protected keyword is a member access modifier. A protected member
  is accessible within its class and by derived class instances.
  Source MSDN

CustomerInfo custInfo = new CustomerInfo();
custInfo.Firstname = "Richard"; //not working
custInfo.Surname = "Smith"; //not working

This code is not working because your custInfo's Firtsname and Surname are not accessible in the Program class. But you should be able to do the following, as your Program class is inherited from CustomerInfo :

Firstname = "Richard";
Surname = "Smith";

For the second question you can do something like the following:

Class1 : Form
{
     // here will be your protected members
}
Class2 : Class1


问:
How do I put extra number at the end of username if duplicate
Hard to explain, and let me show an example.

If username foo already exists in MySQL I want php script will allow it but to be foo1

Then if foo1 exists too, script will generate the username will be foo2

If foo2 existed then become foo3

How to make like that?

Like Col. Shrapnel said Natural increment which seems more sensible. just like "New Folder(3)" stuff in Windows

答:
Some variation of

```<code>$number = 1;
$query = "select name from users where username = ".$username.$number;
$res = mysql_query($query);
$num_rows = mysql_num_rows($res);
while ($num_rows) {
 $number ++;
 $query = "select name from users where username = ".$username.$number;
 $res = mysql_query($query);
 $num_rows = mysql_num_rows($res);
}
</code>```

The above will increment the number until one is found that is not currently in the database.

You will obviously have to edit the values to suit your setup

ContentLicense: CC BY-SA 2.5

Body:
Some variation of

$number = 1;
$query = "select name from users where username = ".$username.$number;
$res = mysql_query($query);
$num_rows = mysql_num_rows($res);
while ($num_rows) {
 $number ++;
 $query = "select name from users where username = ".$username.$number;
 $res = mysql_query($query);
 $num_rows = mysql_num_rows($res);
}

The above will increment the number until one is found that is not currently in the database.

You will obviously have to edit the values to suit your setup


问:
How to calculate taking input from four fields in yii2 dynamic form
I've five fields- rate, qty. discount, cgst_percent, cgst_amount.
I want to calculate cgst_amount. The formula should be -

```<code>cgst_amount = ((rate*qty - (rate*qty*discount)/100)*cgst_percent)/100
</code>```

To Start with simple steps, I tried cgst_amount = rate*qty

The javascript part is as below -

```<code><?php
/* start getting the cgst */
$script = <<< JS
function getGst(item) {
    var index  = item.attr("id").replace(/[^0-9.]/g, "");
    var qtyvar = ratevar = discvar = cgstpercentvar = cgstvar = 0;

    var id = item.attr("id");
    var myString = id.split("-").pop();

    if (myString == "rate") {
        fetch1 = index.concat("-qty");
        fetch2 = index.concat("-discount");
        fetch3 = index.concat("-cgst_rate");
    } else if (myString == "qty") {
        fetch1 = index.concat("-rate");
        fetch2 = index.concat("-discount");
        fetch3 = index.concat("-cgst_rate");
    } else if (myString == "discount"){
        fetch1 = index.concat("-qty");
        fetch2 = index.concat("-rate");
        fetch3 = index.concat("-cgst_rate");
    } else {
        fetch1 = index.concat("-qty");
        fetch2 = index.concat("-rate");
        fetch3 = index.concat("-discount");
    }

    temp1 = $("#productsales-"+fetch1+"").val();
    temp2 = $("#productsales-"+fetch2+"").val();
    temp3 = $("#productsales-"+fetch3+"").val();
    //alert (temp2);

    if (!isNaN(temp1) && temp1.length != 0) {
        ratevar = temp1;
    }

    if (isNaN(temp2) || temp2.length != 0) {
        discvar = temp2;
    }

    if (isNaN(temp3) || temp3.length != 0) {
        cgstpercentvar = temp3;
    }

    qtyvar = item.val();
    if (isNaN(qtyvar) || qtyvar.length == 0) {
        qtyvar = 0;
    }
    //alert (qtyvar);
    if (!isNaN(qtyvar) && !isNaN(ratevar) && !isNaN(discvar) && !isNaN(cgstpercentvar)) {
        cgstvar = (parseFloat(qtyvar) * parseFloat(ratevar)).toFixed(2);

    }

    cgstField = "productsales-".concat(index).concat("-cgst_amount");

    $("#"+cgstField+"").val(cgstvar);

}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the cgst */
?>
</code>```

Whn I key in rate and qty I get multiply of them as output in cgst_amount textbox. No problem so far. As soon as I key in anything in discount,the same texts are getting written in cgst_amount as output.

I'm not quite sure about the javascript part.

It is an extension of - Calculate from 3 inputfield in dynamic form yii2 and Calculate 3 fields and display the result in the 4th in yii2 dynamic form

If I work on the full formula, the javascript calculation part becomes - cgstvar = ((((parseFloat(ratevar) * parseFloat(qtyvar)) - (parseFloat(ratevar) * parseFloat(qtyvar) * parseFloat(discvar))/100) * parseFloat(cgstpercentvar))/100).toFixed(2);

And the example is as below image -

The actual result should have been - 5.43. Instead I'm getting -0.00

答:
You meshed up with fields and variables, i have updated a script a bit :</p>

```<code>function getGst(item) {
    var index  = item.attr("id").replace(/[^0-9.]/g, "");
    var qtyvar = ratevar = discvar = cgstpercentvar = cgstvar = 0;

    var id = item.attr("id");
    var myString = id.split("-").pop();

    quantity = index.concat("-qty");
    rate = index.concat("-rate");
    discount = index.concat("-discount");
    cgstRate = index.concat("-cgst_rate");

    temp1 = $("#productsales-"+quantity+"").val();
    temp2 = $("#productsales-"+rate+"").val();
    temp3 = $("#productsales-"+discount+"").val();
    temp4 = $("#productsales-"+cgstRate+"").val();

    if (isNaN(temp1) || temp1.length != 0) {
        qtyvar = temp1;
    }

    if (!isNaN(temp2) && temp2.length != 0) {
        ratevar = temp2;
    }

    if (isNaN(temp3) || temp3.length != 0) {
        discvar = temp3;
    }

    if (isNaN(temp4) || temp4.length != 0) {
        cgstpercentvar = temp4;
    }

    if (!isNaN(qtyvar) && !isNaN(ratevar) && !isNaN(discvar) && !isNaN(cgstpercentvar)) {
        cgstvar = ((((parseFloat(ratevar) * parseFloat(qtyvar)) - (parseFloat(ratevar) * parseFloat(qtyvar) * parseFloat(discvar))/100) * parseFloat(cgstpercentvar))/100).toFixed(2);
    }

    cgstField = "productsales-".concat(index).concat("-cgst_amount");

    $("#"+cgstField+"").val(cgstvar);

}
</code>```

Body:
I've five fields- rate, qty. discount, cgst_percent, cgst_amount.
I want to calculate cgst_amount. The formula should be -

cgst_amount = ((rate*qty - (rate*qty*discount)/100)*cgst_percent)/100

To Start with simple steps, I tried cgst_amount = rate*qty

The javascript part is as below -

<?php
/* start getting the cgst */
$script = <<< JS
function getGst(item) {
    var index  = item.attr("id").replace(/[^0-9.]/g, "");
    var qtyvar = ratevar = discvar = cgstpercentvar = cgstvar = 0;

    var id = item.attr("id");
    var myString = id.split("-").pop();

    if (myString == "rate") {
        fetch1 = index.concat("-qty");
        fetch2 = index.concat("-discount");
        fetch3 = index.concat("-cgst_rate");
    } else if (myString == "qty") {
        fetch1 = index.concat("-rate");
        fetch2 = index.concat("-discount");
        fetch3 = index.concat("-cgst_rate");
    } else if (myString == "discount"){
        fetch1 = index.concat("-qty");
        fetch2 = index.concat("-rate");
        fetch3 = index.concat("-cgst_rate");
    } else {
        fetch1 = index.concat("-qty");
        fetch2 = index.concat("-rate");
        fetch3 = index.concat("-discount");
    }

    temp1 = $("#productsales-"+fetch1+"").val();
    temp2 = $("#productsales-"+fetch2+"").val();
    temp3 = $("#productsales-"+fetch3+"").val();
    //alert (temp2);

    if (!isNaN(temp1) && temp1.length != 0) {
        ratevar = temp1;
    }

    if (isNaN(temp2) || temp2.length != 0) {
        discvar = temp2;
    }

    if (isNaN(temp3) || temp3.length != 0) {
        cgstpercentvar = temp3;
    }

    qtyvar = item.val();
    if (isNaN(qtyvar) || qtyvar.length == 0) {
        qtyvar = 0;
    }
    //alert (qtyvar);
    if (!isNaN(qtyvar) && !isNaN(ratevar) && !isNaN(discvar) && !isNaN(cgstpercentvar)) {
        cgstvar = (parseFloat(qtyvar) * parseFloat(ratevar)).toFixed(2);

    }

    cgstField = "productsales-".concat(index).concat("-cgst_amount");

    $("#"+cgstField+"").val(cgstvar);

}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the cgst */
?>

Whn I key in rate and qty I get multiply of them as output in cgst_amount textbox. No problem so far. As soon as I key in anything in discount,the same texts are getting written in cgst_amount as output.

I'm not quite sure about the javascript part.

It is an extension of - Calculate from 3 inputfield in dynamic form yii2 and Calculate 3 fields and display the result in the 4th in yii2 dynamic form

If I work on the full formula, the javascript calculation part becomes - cgstvar = ((((parseFloat(ratevar) * parseFloat(qtyvar)) - (parseFloat(ratevar) * parseFloat(qtyvar) * parseFloat(discvar))/100) * parseFloat(cgstpercentvar))/100).toFixed(2);

And the example is as below image -

The actual result should have been - 5.43. Instead I'm getting -0.00

Body:
You meshed up with fields and variables, i have updated a script a bit :

function getGst(item) {
    var index  = item.attr("id").replace(/[^0-9.]/g, "");
    var qtyvar = ratevar = discvar = cgstpercentvar = cgstvar = 0;

    var id = item.attr("id");
    var myString = id.split("-").pop();

    quantity = index.concat("-qty");
    rate = index.concat("-rate");
    discount = index.concat("-discount");
    cgstRate = index.concat("-cgst_rate");

    temp1 = $("#productsales-"+quantity+"").val();
    temp2 = $("#productsales-"+rate+"").val();
    temp3 = $("#productsales-"+discount+"").val();
    temp4 = $("#productsales-"+cgstRate+"").val();

    if (isNaN(temp1) || temp1.length != 0) {
        qtyvar = temp1;
    }

    if (!isNaN(temp2) && temp2.length != 0) {
        ratevar = temp2;
    }

    if (isNaN(temp3) || temp3.length != 0) {
        discvar = temp3;
    }

    if (isNaN(temp4) || temp4.length != 0) {
        cgstpercentvar = temp4;
    }

    if (!isNaN(qtyvar) && !isNaN(ratevar) && !isNaN(discvar) && !isNaN(cgstpercentvar)) {
        cgstvar = ((((parseFloat(ratevar) * parseFloat(qtyvar)) - (parseFloat(ratevar) * parseFloat(qtyvar) * parseFloat(discvar))/100) * parseFloat(cgstpercentvar))/100).toFixed(2);
    }

    cgstField = "productsales-".concat(index).concat("-cgst_amount");

    $("#"+cgstField+"").val(cgstvar);

}


问:
Why is this html photo gallery not centering?
I'm trying to put a photo library on my webpage but it just won't center properly and it's driving me nuts. Any suggestions?
I've tried putting so many different things for centering in the code but nothing works :/

HTML:

```<code>  <div style="display: inline-block; position: relative; text-align: center; width: 100%" >
    <h3 align="center" class="highlight">Photo Library</h3>
    <div align="center" class="" style="max-height:450px;max-width:800px;margin: 30px 30px 30px 30px; text-align: center">
      <img class="mySlides" src="images/slideshow/1.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/2.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/3.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/4.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/5.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/6.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/7.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/8.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/9.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/10.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/11.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/12.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/13.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/14.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/15.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/16.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/17.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/18.png" style="width:auto">
      <img class="mySlides" src="images/slideshow/19.png" style="width:auto">
      <img class="mySlides" src="images/slideshow/20.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/21.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/22.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/23.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/24.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/25.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/26.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/27.jpg" style="width:auto">
      <img class="mySlides" src="images/slideshow/28.jpg" style="width:auto">
    </div>
</code>```

Script:

```<code><script>
  var myIndex = 0;
  carousel();

  function carousel() {
      var i;
      var x = document.getElementsByClassName("mySlides");
      for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
      }
      myIndex++;
      if (myIndex > x.length) {myIndex = 1}
      x[myIndex-1].style.display = "block";
      setTimeout(carousel, 5000);
  }
</script>
</code>```

CSS:

```<code>.mySlides {
    display:none;
    width: 200px;
    height: 400px;
    align-self: center;
    text-align: center;
    align-content: center;
}
</code>```

答:
At first set the display to block. then give the margin to auto

```<code>.mySlides {
    display:block;
    margin: auto;
    width: 200px;
    height: 400px;

}
</code>```

Body:
I'm trying to put a photo library on my webpage but it just won't center properly and it's driving me nuts. Any suggestions?
I've tried putting so many different things for centering in the code but nothing works :/

HTML:

Photo Library

Script:

CSS:

.mySlides {
    display:none;
    width: 200px;
    height: 400px;
    align-self: center;
    text-align: center;
    align-content: center;
}

Body:
At first set the display to block. then give the margin to auto

.mySlides {
    display:block;
    margin: auto;
    width: 200px;
    height: 400px;

}


问:
Copying to clipboard doesn't work javascript
```<code>var $temp = $("<input>");
$("body").append($temp);
$temp.val('123').select();
document.execCommand("copy");
$temp.remove();
</code>```

What is wrong with this code? It should be correct

Doesn't work at all for me.

I have read many threads here and this seems to work for others.

I have no Idea why this doesn't work for me. In console I nothing.

答:
Reading the answers to this question:

All document.execCommand('copy') calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the users clipboard when they don't expect it.

The example:

function copyToClipBoard(txt) {
    try {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val(txt).select();
        var retVal = document.execCommand("copy");
        console.log('Copy to clipboard returns: ' + retVal);
        $temp.remove();
    } catch (err) {
        console.log('Error while copying to clipboard: ' + err);
    }
}

$('button').on('click', function (e) {
    copyToClipBoard('123');
});

copyToClipBoard('123');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="display:inline-block;">
    <button style="vertical-align:top;">Copy To ClipBoard</button>
    <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
  </textarea>
</div></code>```

Body:
var $temp = $("<input>");
$("body").append($temp);
$temp.val('123').select();
document.execCommand("copy");
$temp.remove();

What is wrong with this code? It should be correct

Doesn't work at all for me.

I have read many threads here and this seems to work for others.

I have no Idea why this doesn't work for me. In console I nothing.

Body:
Reading the answers to this question:

All document.execCommand('copy') calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the users clipboard when they don't expect it.

The example:

function copyToClipBoard(txt) {
    try {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val(txt).select();
        var retVal = document.execCommand("copy");
        console.log('Copy to clipboard returns: ' + retVal);
        $temp.remove();
    } catch (err) {
        console.log('Error while copying to clipboard: ' + err);
    }
}

$('button').on('click', function (e) {
    copyToClipBoard('123');
});

copyToClipBoard('123');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style="display:inline-block;">
    <button style="vertical-align:top;">Copy To ClipBoard</button>
    <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
  </textarea>
</div>


问:
fading video over swift spritkit scene
I am porting a showroom application from as3/starling to a native swift iPad app.

I have 2 questions:

How can I fade a video over my spritekit content (from alpha 0 to 1).

How to control the iPad volume with an individual UI element without showing the iOS onscreen-volume notification graphic.

答:
My first answer answers your initial question, and this answer is tailored to the subsequent questions that were posted in the comments. I feel that both answers are useful to the community, instead of combining into just one which I think would be confusing.

Here I implement a volume slider and a scrubbing slider that controls the VideoNode's AVPlayer object.. you get the full power of the AVPlayer but with the convenience of the SKVideoNode. Also, the volume for playing video is controlled without having to adjust the system volume and subsequent gray sound box pop-up:

```<code>import SpriteKit
import MediaPlayer

class GameScene: SKScene {

  let seekSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
  let volSlider  = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))

  // Because it takes time for us to load the video, we don't know it's duration,
  // hence we don't know what the `.maximumValue` should be for the seekSlider
  let defaultMax = Float(0.123456789)

  var player: AVPlayer!
  var videoNode: SKVideoNode!

  func seekSliderChangedValue(sender: UISlider) {
    // Wait for file to finish loading so we can get accurate end duration:
      if sender.maximumValue == defaultMax {
      if CMTimeGetSeconds(player.currentItem!.duration).isNaN { return }
      else { sender.maximumValue = Float(CMTimeGetSeconds(player.currentItem!.duration)) }
    }

    let value = CMTimeMake(Int64(seekSlider.value), 1)
    player.seek(to: value)
    player.play()
  }

  func volSliderChangedValue(sender: UISlider) {
    player.volume = sender.value
  }

  override func didMove(to view: SKView) {
    removeAllChildren()  // Delete this in your actual project.

    // Add some labels:
    let seekLabel = SKLabelNode(text: "Seek")
    seekLabel.setScale(3)
    seekLabel.verticalAlignmentMode = .center
    seekLabel.position = CGPoint(x: frame.minX + seekLabel.frame.width/2,
                                 y: frame.maxY - seekLabel.frame.height)
    let volLabel  = SKLabelNode(text: "Volume")
    volLabel.setScale(3)
    volLabel.verticalAlignmentMode = .center
    volLabel.position = CGPoint(x: frame.minX + volLabel.frame.width/2,
                                y: frame.minY + volLabel.frame.height + volSlider.frame.height)

    // Make player and node:
    let url = Bundle.main.url(forResource: "sample", withExtension: "mp4")!
    player = AVPlayer(url: url)
    videoNode = SKVideoNode(avPlayer: player!)

    //Configure seek slider:
    seekSlider.addTarget(self, action: #selector(seekSliderChangedValue), for: UIControlEvents.valueChanged)
    seekSlider.maximumValue = defaultMax
    let seekOrigin = convertPoint(toView: CGPoint(x: seekLabel.frame.minX, y: seekLabel.frame.minY))
    seekSlider.frame = CGRect(origin: seekOrigin, size: CGSize(width: 200, height: 15))

    //Configure vol slider:
    volSlider.addTarget(self, action: #selector(volSliderChangedValue), for: UIControlEvents.valueChanged)
    volSlider.value = 1
    let volOrigin = convertPoint(toView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
    volSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))

    //Scene stuff:
    view.addSubview(seekSlider)
    view.addSubview(volSlider)
    addChild(seekLabel)
    addChild(volLabel)
    addChild(videoNode)

    // Start video and animation:
    videoNode.alpha = 0
    videoNode.play()
    videoNode.run(.fadeIn(withDuration: 5))
  }
}
</code>```

Title: fading video over swift spritkit scene

Body:
My first answer answers your initial question, and this answer is tailored to the subsequent questions that were posted in the comments. I feel that both answers are useful to the community, instead of combining into just one which I think would be confusing.

Here I implement a volume slider and a scrubbing slider that controls the VideoNode's AVPlayer object.. you get the full power of the AVPlayer but with the convenience of the SKVideoNode. Also, the volume for playing video is controlled without having to adjust the system volume and subsequent gray sound box pop-up:

import SpriteKit
import MediaPlayer

class GameScene: SKScene {

  let seekSlider = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))
  let volSlider  = UISlider(frame: CGRect(x: 0, y: 0, width: 200, height: 15))

  // Because it takes time for us to load the video, we don't know it's duration,
  // hence we don't know what the `.maximumValue` should be for the seekSlider
  let defaultMax = Float(0.123456789)

  var player: AVPlayer!
  var videoNode: SKVideoNode!

  func seekSliderChangedValue(sender: UISlider) {
    // Wait for file to finish loading so we can get accurate end duration:
      if sender.maximumValue == defaultMax {
      if CMTimeGetSeconds(player.currentItem!.duration).isNaN { return }
      else { sender.maximumValue = Float(CMTimeGetSeconds(player.currentItem!.duration)) }
    }

    let value = CMTimeMake(Int64(seekSlider.value), 1)
    player.seek(to: value)
    player.play()
  }

  func volSliderChangedValue(sender: UISlider) {
    player.volume = sender.value
  }

  override func didMove(to view: SKView) {
    removeAllChildren()  // Delete this in your actual project.

    // Add some labels:
    let seekLabel = SKLabelNode(text: "Seek")
    seekLabel.setScale(3)
    seekLabel.verticalAlignmentMode = .center
    seekLabel.position = CGPoint(x: frame.minX + seekLabel.frame.width/2,
                                 y: frame.maxY - seekLabel.frame.height)
    let volLabel  = SKLabelNode(text: "Volume")
    volLabel.setScale(3)
    volLabel.verticalAlignmentMode = .center
    volLabel.position = CGPoint(x: frame.minX + volLabel.frame.width/2,
                                y: frame.minY + volLabel.frame.height + volSlider.frame.height)

    // Make player and node:
    let url = Bundle.main.url(forResource: "sample", withExtension: "mp4")!
    player = AVPlayer(url: url)
    videoNode = SKVideoNode(avPlayer: player!)

    //Configure seek slider:
    seekSlider.addTarget(self, action: #selector(seekSliderChangedValue), for: UIControlEvents.valueChanged)
    seekSlider.maximumValue = defaultMax
    let seekOrigin = convertPoint(toView: CGPoint(x: seekLabel.frame.minX, y: seekLabel.frame.minY))
    seekSlider.frame = CGRect(origin: seekOrigin, size: CGSize(width: 200, height: 15))

    //Configure vol slider:
    volSlider.addTarget(self, action: #selector(volSliderChangedValue), for: UIControlEvents.valueChanged)
    volSlider.value = 1
    let volOrigin = convertPoint(toView: CGPoint(x: volLabel.frame.minX, y: volLabel.frame.minY))
    volSlider.frame = CGRect(origin: volOrigin, size: CGSize(width: 200, height: 15))

    //Scene stuff:
    view.addSubview(seekSlider)
    view.addSubview(volSlider)
    addChild(seekLabel)
    addChild(volLabel)
    addChild(videoNode)

    // Start video and animation:
    videoNode.alpha = 0
    videoNode.play()
    videoNode.run(.fadeIn(withDuration: 5))
  }
}


问:
Is it a solvable problem to generate a regular expression that matches some input set?
I provide some input set which contains known separated number of text blocks.

I want to make a program that automatically generate 1 or more regular expressions each of which matches every text block in the input set.

I see some relatively easy ways to implement a brute-force search. But I'm not an expert in compilers theory. That's why I'm curious:

1) is this problem solvable? or there are some principle impossibility to make such algorithm?

2) is it possible to achieve polynomial complexity for this algorithm and avoid brute forcing?

答:
The problem is, there are a huge number of regular expressions (actually, an infinite number) that will match a given set of inputs. They range from very "greedy" expressions that will match everything

```<code>.*
</code>```

To very non "greedy" expression that will match exactly the input set

```<code>InputA OR inputB OR inputC etc
</code>```

In between those two you can vary the expression in a variety of ways to make it more and less greedy (eg, replace specific digits with an expression which matches any digit, etc).

You'll have to tell us a little more about the problem for us to know where in that range of possible answers is the correct one ;)

Body:
The problem is, there are a huge number of regular expressions (actually, an infinite number) that will match a given set of inputs. They range from very "greedy" expressions that will match everything

.*

To very non "greedy" expression that will match exactly the input set

InputA OR inputB OR inputC etc

In between those two you can vary the expression in a variety of ways to make it more and less greedy (eg, replace specific digits with an expression which matches any digit, etc).

You'll have to tell us a little more about the problem for us to know where in that range of possible answers is the correct one ;)


问:
BigQuery quantiles into Data Studio
I have some timeseries IOT that is collected minutely, but Data Studio only seems to support Daily aggregations. This would be fine if I could also get min/max/quantile in a timeseries chart. I cannot seem to find a way to get quantile data into a chart though. Is there a way to get Big Query quantile results into a Data Studio timeseries chart?</p>

答:
Perhaps something like this would work? You would need to input a custom query and uncheck "Use Legacy SQL":

```<code>SELECT
  date,
  min_value,
  max_value,
  quantile_value,
  quantile
FROM (
  SELECT
    date,
    MIN(measurement) AS min_value,
    MAX(measurement) AS max_value,
    APPROX_QUANTILES(measurement, 100) AS quantiles
  FROM YourTable
  GROUP BY date
)
CROSS JOIN UNNEST(quantiles) AS quantile_value
WITH OFFSET quantile;
</code>```

This gives you per-day min, max, and quantiles based on the assumption that you have some kind of column with measurements.

Title: BigQuery quantiles into Data Studio

Body:
Perhaps something like this would work? You would need to input a custom query and uncheck "Use Legacy SQL":

SELECT
  date,
  min_value,
  max_value,
  quantile_value,
  quantile
FROM (
  SELECT
    date,
    MIN(measurement) AS min_value,
    MAX(measurement) AS max_value,
    APPROX_QUANTILES(measurement, 100) AS quantiles
  FROM YourTable
  GROUP BY date
)
CROSS JOIN UNNEST(quantiles) AS quantile_value
WITH OFFSET quantile;

This gives you per-day min, max, and quantiles based on the assumption that you have some kind of column with measurements.


问:
E-R modelling and business rules
How can I insert in an E-R model a concept like this:
"an user can insert an evalutation of another user who participates to the same event"

where the participation must be deducted from an approved subscription to an event.

I made a recursive relation "Evaluation" from Subscription (which is related to User and to Event) to itself, but I'm not sure it is correct.

Maybe for concepts like this I need to use a business rule?

Thanks.

答:
Consider the following example ER diagram:

We can implement Evaluation and Participation in SQL as:

```<code>CREATE TABLE Participation (
    UserID INT NOT NULL,
    EventID INT NOT NULL,
    PRIMARY KEY (UserID, EventID),
    FOREIGN KEY (UserID) REFERENCES User (UserID),
    FOREIGN KEY (EventID) REFERENCES Event (EventID)
);

CREATE TABLE Evaluation (
    EvaluationID INT NOT NULL,
    ScoringUserID INT NOT NULL,
    ScoredUserID INT NOT NULL,
    EventID INT NOT NULL,
    Score INT NOT NULL,
    PRIMARY KEY (EvaluationID)
);
</code>```

Now, normally we would create foreign key constraints for Evaluation like this:

```<code>ALTER TABLE Evaluation
ADD FOREIGN KEY (ScoringUserID) REFERENCES User (UserID),
ADD FOREIGN KEY (ScoredUserID) REFERENCES User (UserID),
ADD FOREIGN KEY (EventID) REFERENCES Event (EventID);
</code>```

However, in this case a pair of overlapping foreign key constraints referencing Participation will enforce the required business rule:

```<code>ALTER TABLE Evaluation
ADD FOREIGN KEY (ScoringUserID, EventID) REFERENCES Participation (UserID, EventID),
ADD FOREIGN KEY (ScoredUserID, EventID) REFERENCES Participation (UserID, EventID);
</code>```

There's some redundancy but it's controlled and required for consistency. Alternatively, it's possible to use triggers to achieve the same effect.

These overlapping FK constraints can't be represented in ER diagrams, though they could be represented logically. In a table diagram, we could draw Crow's foot lines between the tables, but that wouldn't indicate the composite overlapping columns involved.

Title: E-R modelling and business rules

Body:
Consider the following example ER diagram:

We can implement Evaluation and Participation in SQL as:

CREATE TABLE Participation (
    UserID INT NOT NULL,
    EventID INT NOT NULL,
    PRIMARY KEY (UserID, EventID),
    FOREIGN KEY (UserID) REFERENCES User (UserID),
    FOREIGN KEY (EventID) REFERENCES Event (EventID)
);

CREATE TABLE Evaluation (
    EvaluationID INT NOT NULL,
    ScoringUserID INT NOT NULL,
    ScoredUserID INT NOT NULL,
    EventID INT NOT NULL,
    Score INT NOT NULL,
    PRIMARY KEY (EvaluationID)
);

Now, normally we would create foreign key constraints for Evaluation like this:

ALTER TABLE Evaluation
ADD FOREIGN KEY (ScoringUserID) REFERENCES User (UserID),
ADD FOREIGN KEY (ScoredUserID) REFERENCES User (UserID),
ADD FOREIGN KEY (EventID) REFERENCES Event (EventID);

However, in this case a pair of overlapping foreign key constraints referencing Participation will enforce the required business rule:

ALTER TABLE Evaluation
ADD FOREIGN KEY (ScoringUserID, EventID) REFERENCES Participation (UserID, EventID),
ADD FOREIGN KEY (ScoredUserID, EventID) REFERENCES Participation (UserID, EventID);

There's some redundancy but it's controlled and required for consistency. Alternatively, it's possible to use triggers to achieve the same effect.

These overlapping FK constraints can't be represented in ER diagrams, though they could be represented logically. In a table diagram, we could draw Crow's foot lines between the tables, but that wouldn't indicate the composite overlapping columns involved.


问:
Check if Model is empty
I am doing below query to fetch data to view however if AccountMediaServerKey table is empty. Model is throwing null exception error in view. Any idea how to check if model is null when NO data fetched from database

```<code>var MediaKey = (from p in db.AccountMediaServerKey
                where p.Tagger == USID && p.TagTo == USID
                select new MediaServerHomeModel
                {
                    Stream=p.Stream,
                    Event = p.Event,
                    Status = p.Status

                }).FirstOrDefault();
</code>```

答:
you have 2 ways
first check your query if its null

```<code>if (MediaKey == null)
{
 //do some thing
}
</code>```

Or you can check it before query like below :

without filtering:

```<code>if(db.AccountMediaServerKey.Any())
 {

 }
</code>```

with filtering:

```<code>if(db.AccountMediaServerKey.Any(p=> p.Tagger == USID && p.TagTo == USID))
 {

 }
</code>```

Title: Check if Model is empty

Body:
I am doing below query to fetch data to view however if AccountMediaServerKey table is empty. Model is throwing null exception error in view. Any idea how to check if model is null when NO data fetched from database

var MediaKey = (from p in db.AccountMediaServerKey
                where p.Tagger == USID && p.TagTo == USID
                select new MediaServerHomeModel
                {
                    Stream=p.Stream,
                    Event = p.Event,
                    Status = p.Status

                }).FirstOrDefault();

Body:
you have 2 ways
first check your query if its null

if (MediaKey == null)
{
 //do some thing
}

Or you can check it before query like below :

without filtering:

if(db.AccountMediaServerKey.Any())
 {

 }

with filtering:

if(db.AccountMediaServerKey.Any(p=> p.Tagger == USID && p.TagTo == USID))
 {

 }


问:
REST URL for a resource
I have doubt since a long time regarding the URL link for resources like user and questions here on stack exchange sites. When I goto my profile page I expect something like:

https://stackoverflow.com/users/codeyogi

But I see:

https://stackoverflow.com/users/4260745/codeyogi

Why there is an extra random number? since the user names are unique.

答:
Why there is an extra random number? since the user names are unique.

Because in REST, the spelling of the URL doesn't matter, so the server can encode any information it likes into it, where it likes, and change the scheme when it likes.

I expect something like:
  https://stackoverflow.com/users/codeyogi

That would also be a valid spelling.  But there's no reason for you, as the client, to care what spelling is going to be used -- you just follow links, and it all works.

Don't have an answer as to why stack exchange uses this particular spelling; the apidocs hint that all of the uri templates make room for an ID, so maybe the usernames aren't unique across time?

Title: REST URL for a resource


问:
Parsing nested JSON in go language
How could I parse and extract certain values from below JSON

Here is the sample JSON response

```<code>{
   "success":true,
   "endpoint":"https://api.abcxyz.com",
   "info":{
      "Guestconnected":134,
      "Guestratio":100000.06963,
      "symbol1":{
         "code":"NY",
         "symbol":"*",
         "name":"newyear",
         "codev":391.78161,
         "symbolAppearsAfter":false,
         "local":true
      },
      "symbol2":{
         "code":"HNY",
         "symbol":"@",
         "name":"HappyNewYear",
         "codev":1000000.0960,
         "symbolAppearsAfter":true,
         "local":false
      },
      "latest":{
         "value":1597509,
         "autovalue":"00099cf8da58a36c08f2ef98650ff6043ddfb",
         "height":474696,
         "time":1499527696
      }
   },
   "Allguest":{
      "all":4,
      "filtered":4,
      "total_invitations":15430,
      "sent_invitations":15430,
      "final_invitations":0
   },
   "Guestlist":[
      {
         "GuestCode":"369AR",
         "all":2,
         "total_invitations":5430,
         "sent_invitations":5430,
         "final_invitations":0,
         "change":0,
         "accounts":0
      },
      {
         "GuestCode":"6POIA96TY",
         "all":2,
         "total_invitations":10000,
         "sent_invitations":10000,
         "final_invitations":0,
         "change":0,
         "accounts":0
      }
   ]
}
</code>```

My Code is :

```<code>package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

type object struct {
    Success bool `json:"success"`
    Endpoint string `json:"endpoint"`
    Allguest struct {
        All int `json:"all"`
        Filtered int `json:"filtered"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
    } `json:"Allguest"`
    Guestlist []struct {
        GuestCode string `json:"GuestCode"`
        All int `json:"all"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
        Change int `json:"change"`
        Accounts int `json:"accounts"`
    } `json:"Guestlist"`
}

func main() {

uri := "https://siteurl.com/api?lists=1"
res, err := http.Get(uri)
fmt.Println(uri)
if err != nil {
fmt.Println("Error:", err)
    log.Fatal(err)
}
defer res.Body.Close()

 var s object
err := json.NewDecoder(res.Body).Decode(&s)
if err != nil {
    log.Fatal(err)
    fmt.Println("Error:", err)
}
fmt.Println(s.Success)
fmt.Println(s.Allguest.TotalInvitations)
for i := 0; i < 6; i++ {
fmt.Println(s.Guestlist[i].TotalInvitations)
)

}
</code>```

The problem is :

If the response is null it is giving index out of range error how can we avoid this ?

Applying condition if TotalInvitations value is greater than 100 then save in 100.csv else save in others.csv

答:
If the response is null it is giving index out of range error how can
  we avoid this?

Unless I'm misunderstanding you, the response being null shouldn't matter.  If you receive 2 Guestlist items, you can only loop over those 2, meaning for i := 0; i < 6; i++ is wrong.  Change it to for i := 0; i < len(s.Guestlist); i++ or for i := range s.Guestlist.

Applying condition if TotalInvitations value is greater than 100 then
  save in 100.csv else save in others.csv

You will probably want the os package's Create function to create a new file for writing or the OpenFile function, the O_CREATE, O_WRONLY, and O_APPEND file-open flags, and you can pass 0755 as the permission mode (or another set of octal permissions if you want to change access of a file).

You can then use csvWriter := csv.NewWriter(csvFile) to wrap the resulting io.Writer (assuming there is no error opening the file).  From there, you can just write whatever information you require to the file as CSV records.  Don't forget to call csvWriter.Flush to flush the output buffer and csvWriter.Error to check whether there was an error flushing the output buffer.  Also don't forget to close the file you opened.

Title: Parsing nested JSON in go language

Body:
How could I parse and extract certain values from below JSON

Here is the sample JSON response

{
   "success":true,
   "endpoint":"https://api.abcxyz.com",
   "info":{
      "Guestconnected":134,
      "Guestratio":100000.06963,
      "symbol1":{
         "code":"NY",
         "symbol":"*",
         "name":"newyear",
         "codev":391.78161,
         "symbolAppearsAfter":false,
         "local":true
      },
      "symbol2":{
         "code":"HNY",
         "symbol":"@",
         "name":"HappyNewYear",
         "codev":1000000.0960,
         "symbolAppearsAfter":true,
         "local":false
      },
      "latest":{
         "value":1597509,
         "autovalue":"00099cf8da58a36c08f2ef98650ff6043ddfb",
         "height":474696,
         "time":1499527696
      }
   },
   "Allguest":{
      "all":4,
      "filtered":4,
      "total_invitations":15430,
      "sent_invitations":15430,
      "final_invitations":0
   },
   "Guestlist":[
      {
         "GuestCode":"369AR",
         "all":2,
         "total_invitations":5430,
         "sent_invitations":5430,
         "final_invitations":0,
         "change":0,
         "accounts":0
      },
      {
         "GuestCode":"6POIA96TY",
         "all":2,
         "total_invitations":10000,
         "sent_invitations":10000,
         "final_invitations":0,
         "change":0,
         "accounts":0
      }
   ]
}

My Code is :

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

type object struct {
    Success bool `json:"success"`
    Endpoint string `json:"endpoint"`
    Allguest struct {
        All int `json:"all"`
        Filtered int `json:"filtered"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
    } `json:"Allguest"`
    Guestlist []struct {
        GuestCode string `json:"GuestCode"`
        All int `json:"all"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
        Change int `json:"change"`
        Accounts int `json:"accounts"`
    } `json:"Guestlist"`
}

func main() {

uri := "https://siteurl.com/api?lists=1"
res, err := http.Get(uri)
fmt.Println(uri)
if err != nil {
fmt.Println("Error:", err)
    log.Fatal(err)
}
defer res.Body.Close()

 var s object
err := json.NewDecoder(res.Body).Decode(&s)
if err != nil {
    log.Fatal(err)
    fmt.Println("Error:", err)
}
fmt.Println(s.Success)
fmt.Println(s.Allguest.TotalInvitations)
for i := 0; i < 6; i++ {
fmt.Println(s.Guestlist[i].TotalInvitations)
)

}

The problem is :

If the response is null it is giving index out of range error how can we avoid this ?

Applying condition if TotalInvitations value is greater than 100 then save in 100.csv else save in others.csv


问:
different results of IN Condition
Don't quite understand IN statement. First variant works fine:

```<code>select manufacturers.id
from manufacturers
where manufacturers.id in (select manufacturerId
                           from pcs group by manufacturerId
                           having count(manufacturerId) > 1)
</code>```

But when I make subquery a procedure:

```<code>CREATE PROCEDURE [dbo].Get_manufacturers @productType varchar(50)
as
begin
declare @query varchar(500)
set @query='select manufacturerId from ' +  QuoteName(@productType) + '
               group by manufacturerId having count(manufacturerId) > 1'
declare @t table (manufacturerId int)
insert into @t exec(@query)
select manufacturerId from @t;
end

select manufacturers.id
from manufacturers
where manufacturers.id in (Get_manufacturers 'pcs')
</code>```

I get an error: Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'pcs'

Get_manufacturers 'pcs' works properly. Where am I wrong?

答:
As @Gordon Linoff said, procedures does not return tables.
But, if you want to store output data from stored procedures, you need to put it into table e. g.:

```<code>DECLARE @manufactures TABLE (Id int)
INSERT INTO @manufactures
exec Get_manufacturers 'pcs'

select manufacturers.id
from manufacturers
where manufacturers.id IN (SELECT Id FROM @manufactures)
</code>```

Instead of table variable, you can use temporary table.

Title: different results of IN Condition

Body:
Don't quite understand IN statement. First variant works fine:

select manufacturers.id
from manufacturers
where manufacturers.id in (select manufacturerId
                           from pcs group by manufacturerId
                           having count(manufacturerId) > 1)

But when I make subquery a procedure:

CREATE PROCEDURE [dbo].Get_manufacturers @productType varchar(50)
as
begin
declare @query varchar(500)
set @query='select manufacturerId from ' +  QuoteName(@productType) + '
               group by manufacturerId having count(manufacturerId) > 1'
declare @t table (manufacturerId int)
insert into @t exec(@query)
select manufacturerId from @t;
end

select manufacturers.id
from manufacturers
where manufacturers.id in (Get_manufacturers 'pcs')

I get an error: Msg 102, Level 15, State 1, Line 4
Incorrect syntax near 'pcs'

Get_manufacturers 'pcs' works properly. Where am I wrong?

Body:
As @Gordon Linoff said, procedures does not return tables.
But, if you want to store output data from stored procedures, you need to put it into table e. g.:

DECLARE @manufactures TABLE (Id int)
INSERT INTO @manufactures
exec Get_manufacturers 'pcs'

select manufacturers.id
from manufacturers
where manufacturers.id IN (SELECT Id FROM @manufactures)

Instead of table variable, you can use temporary table.


问:
Limit category depth to parent level
There's a couple of problems I need solved here.

1) I can't seem to get this to only list the parent categories.

2) Is there a way I can also show the number of trashed posts next to where I echo $live_posts

```<code><ul>
<?php
    $categories = get_categories();
    foreach ($categories as $cat) {
    $posts = new WP_Query( array(

    'depth'  => 1,
    'post_status' => array('publish'),
    'cat' => $cat->cat_ID));

    $live_posts = $posts->post_count;
?>
    <li>
        <a href="#"><?php echo $cat->cat_name; ?> (<?php echo $live_posts; ?>)</a>
    </li>
<?php }
?>
</ul>
</code>```

Regarding the first problem, I thought 'depth' => 1 was supposed to limit to the parents, but for reasons unknown it's not working. Unless I'm missing something obvious?

Thanks in advance!

答:
```<code>$args = array(
    'taxonomy' => 'category',
    'orderby' => 'name',
    'order' => 'ASC',
    'parent' => 0,
    'hide_empty' => false,
);
$the_query = new WP_Term_Query($args);
$categories = $the_query->get_terms();
print_r($the_query);
exit;
</code>```

Title: Limit category depth to parent level

Body:
There's a couple of problems I need solved here.

1) I can't seem to get this to only list the parent categories.

2) Is there a way I can also show the number of trashed posts next to where I echo $live_posts

<?php
    $categories = get_categories();
    foreach ($categories as $cat) {
    $posts = new WP_Query( array(

    'depth'  => 1,
    'post_status' => array('publish'),
    'cat' => $cat->cat_ID));

    $live_posts = $posts->post_count;
?>

        <?php echo $cat->cat_name; ?> (<?php echo $live_posts; ?>)

<?php }
?>

Regarding the first problem, I thought 'depth' => 1 was supposed to limit to the parents, but for reasons unknown it's not working. Unless I'm missing something obvious?

Thanks in advance!


问:
Armadillo's cx_mat and Boost's odeint compilation error
I was going to solve several matrix differential equations, of the form d/dt (X) = F(X), where X is a large complex matrix, and F denotes some function of it. I tried to use Boost's odeint with state_type as Armadillo's cx_mat. But it produces compilation error for controlled stepper type. My sample code is as follows

```<code>#include <armadillo>
#include <iostream>
#include <boost/numeric/odeint.hpp>

using namespace std;
using namespace arma;
using namespace boost::numeric::odeint;

using state_type = arma::cx_mat;

void ode(const state_type& X, state_type& derr, double) {
  derr =  X;  // sample derivative, can be anything else
}

// define resizable and norm_inf
namespace boost { namespace numeric { namespace odeint {

template <>
struct is_resizeable<arma::cx_mat> {
    typedef boost::true_type type;
    const static bool value = type::value;
};

template <>
struct same_size_impl<arma::cx_mat, arma::cx_mat> {
    static bool same_size(const arma::cx_mat& x, const arma::cx_mat& y)
    {
      return arma::size(x) == arma::size(y);
    }
};

template<>
struct resize_impl<arma::cx_mat, arma::cx_mat> {
      static void resize(arma::cx_mat& v1, const arma::cx_mat& v2) {
      v1.resize(arma::size(v2));
    }
};

template<>
 struct vector_space_norm_inf<state_type> {
    typedef double result_type;
    result_type operator()(const state_type& p) const
    {
      return arma::norm(p, "inf");
    }
};

} } } // namespace boost::numeric::odeint

using stepper =  runge_kutta_dopri5<state_type, double, state_type, double, vector_space_algebra>;

int main () {

  cx_mat A = randu<cx_mat>(4, 4);

  integrate_adaptive( make_controlled<stepper>(1E-10, 1E-10),  ode, A, 0.0 , 10.0, 0.1);
}
</code>```

This code gives the following compilation error:

```<code>/usr/include/armadillo_bits/Mat_meat.hpp:5153:3: error: static assertion failed: error: incorrect or unsupported type
   arma_type_check(( is_same_type< eT, typename T1::elem_type >::no ));
</code>```

What I can understand that Armadillo does not support copying a real matrix (mat) into a complex one (cx_mat), like

```<code>mat Z = something;
cx_mat Y = Z;  // ERROR
</code>```

Which happens somewhere in odeint. Right now I am overcoming this by copying whole matrix into std::vector<std::complex<double> > put it into the function ode, then inside the function again copy whole std::vector<std::complex<double> > into cx_mat, calculate F(X), then copy it into std::vector<std::complex<double> > and return. Obviously, this is very slow and inefficient.

Any simple solution to the problem??
If possible, I may want to shift to Eigen, if that helps.

答: Yes, complex valued state types don't play well with adaptive steppers because odeint does not differentiate between state_type and error_type. I.e. it uses state_type also to store the error, but this does not work for complex valued state_types, while the error should be double-valued matrix. I'm not sure how well Eigen plays with this, but it might be worth a try. Feel free to file a ticket on https://github.com/headmyshoulder/odeint-v2 , but this will be quite a big change...</p>

Body:
I was going to solve several matrix differential equations, of the form d/dt (X) = F(X), where X is a large complex matrix, and F denotes some function of it. I tried to use Boost's odeint with state_type as Armadillo's cx_mat. But it produces compilation error for controlled stepper type. My sample code is as follows

#include <armadillo>
#include <iostream>
#include <boost/numeric/odeint.hpp>

using namespace std;
using namespace arma;
using namespace boost::numeric::odeint;

using state_type = arma::cx_mat;

void ode(const state_type& X, state_type& derr, double) {
  derr =  X;  // sample derivative, can be anything else
}

// define resizable and norm_inf
namespace boost { namespace numeric { namespace odeint {

template <>
struct is_resizeable<arma::cx_mat> {
    typedef boost::true_type type;
    const static bool value = type::value;
};

template <>
struct same_size_impl<arma::cx_mat, arma::cx_mat> {
    static bool same_size(const arma::cx_mat& x, const arma::cx_mat& y)
    {
      return arma::size(x) == arma::size(y);
    }
};

template<>
struct resize_impl<arma::cx_mat, arma::cx_mat> {
      static void resize(arma::cx_mat& v1, const arma::cx_mat& v2) {
      v1.resize(arma::size(v2));
    }
};

template<>
 struct vector_space_norm_inf<state_type> {
    typedef double result_type;
    result_type operator()(const state_type& p) const
    {
      return arma::norm(p, "inf");
    }
};

} } } // namespace boost::numeric::odeint

using stepper =  runge_kutta_dopri5<state_type, double, state_type, double, vector_space_algebra>;

int main () {

  cx_mat A = randu<cx_mat>(4, 4);

  integrate_adaptive( make_controlled<stepper>(1E-10, 1E-10),  ode, A, 0.0 , 10.0, 0.1);
}

This code gives the following compilation error:

/usr/include/armadillo_bits/Mat_meat.hpp:5153:3: error: static assertion failed: error: incorrect or unsupported type
   arma_type_check(( is_same_type< eT, typename T1::elem_type >::no ));

What I can understand that Armadillo does not support copying a real matrix (mat) into a complex one (cx_mat), like

mat Z = something;
cx_mat Y = Z;  // ERROR

Which happens somewhere in odeint. Right now I am overcoming this by copying whole matrix into std::vector<std::complex<double> > put it into the function ode, then inside the function again copy whole std::vector<std::complex<double> > into cx_mat, calculate F(X), then copy it into std::vector<std::complex<double> > and return. Obviously, this is very slow and inefficient.

Any simple solution to the problem??
If possible, I may want to shift to Eigen, if that helps.


问:
presenting Unix Timestamps with Swift
Using a current timestamp and a given timestamp, what is the best way to present them on a page? If the given timestamp represents "yesterday" the presentation should say yesterday. if the given timestamp was minutes or hours ago, it should only include how many. etc. is it best to subtract one from the other and evaluate what the difference means or is there a built-in library or framework that can be used? so far I am working with the following playground:</p>

```<code>    let ts = 1499299978.149724
    let current_ts: Double

    let date = NSDate(timeIntervalSince1970: ts)

    let dayTimePeriodFormatter = DateFormatter()

    let totalFormat  = "MMM dd YYYY hh:mm a" //just for reference
    dayTimePeriodFormatter.dateFormat = "hh:mm a" //add to this as desired

    let dateString = dayTimePeriodFormatter.string(from: date as Date)
</code>```

答:
this should get you started:

```<code>    let midnight = startOfToday.timeIntervalSince1970
    let secondsInADay = 86400.0

    if ts > midnight {
        print ("today")
        code
    } else if ts > midnight - secondsInADay {
        print ("yesterday")
        code
    } else if ts > midnight - secondsInADay - secondsInADay {
        print ("2 days ago")
        code
    } else if ts > midnight - secondsInADay * 3 {
        print ("3 days ago")
        code
    }
</code>```

inside the "today" block you can use a similar process to check for seconds ago, minutes ago, else then subtract the ts from the current ts then divide by 60 accordingly to get the number you need

Title: presenting Unix Timestamps with Swift

Body:
Using a current timestamp and a given timestamp, what is the best way to present them on a page? If the given timestamp represents "yesterday" the presentation should say yesterday. if the given timestamp was minutes or hours ago, it should only include how many. etc. is it best to subtract one from the other and evaluate what the difference means or is there a built-in library or framework that can be used? so far I am working with the following playground:

    let ts = 1499299978.149724
    let current_ts: Double

    let date = NSDate(timeIntervalSince1970: ts)

    let dayTimePeriodFormatter = DateFormatter()

    let totalFormat  = "MMM dd YYYY hh:mm a" //just for reference
    dayTimePeriodFormatter.dateFormat = "hh:mm a" //add to this as desired

    let dateString = dayTimePeriodFormatter.string(from: date as Date)

Body:
this should get you started:

    let midnight = startOfToday.timeIntervalSince1970
    let secondsInADay = 86400.0

    if ts > midnight {
        print ("today")
        code
    } else if ts > midnight - secondsInADay {
        print ("yesterday")
        code
    } else if ts > midnight - secondsInADay - secondsInADay {
        print ("2 days ago")
        code
    } else if ts > midnight - secondsInADay * 3 {
        print ("3 days ago")
        code
    }

inside the "today" block you can use a similar process to check for seconds ago, minutes ago, else then subtract the ts from the current ts then divide by 60 accordingly to get the number you need


问:
Index out of bounds / IndexError
I am trying to move a kernel around an array of an image to create a gaussian filter. I am getting an IndexError, and Idk why. This is the code: error at line 34

```<code>import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt

imagen_nueva = np.empty((1931, 1282))

imagen = scipy.misc.imread("C:\\Users\\Reymi\\Downloads\\imagen.png")

imagen_real = scipy.pad(array=imagen, pad_width=[1, 1], mode='constant',
constant_values=0)

(dim_x,dim_y)=np.shape(imagen_real)
print((dim_x,dim_y))

ker1 = np.array([[1/16, 1/8, 1/16],
            [1/8, 1/4, 1/8],
            [1/16, 1/8, 1/16]])

def multiplicar_entero():
    global imagen_nueva
    for i in range(1,dim_x+1):
    for j in range(1,dim_y+1):
        matriz_elemento = np.array([[imagen_real[i + 1, j - 1],
imagen_real[i + 1, j], imagen_real[i + 1, j - 1]],
                        [imagen_real[i, j - 1], imagen_real[i, j],
imagen_real[i, j + 1]],
                        [imagen_real[i - 1, j - 1], imagen_real[i - 1, j],
imagen_real[i - 1, j + 1]]])
        valor = np.sum(matriz_elemento*ker1)
        imagen_real[i, j] = valor
        imagen_nueva = np.append(imagen[i, j], (1931, 1282))
</code>```

As for the confusing matrix with is, and js. It is the matrix 3x3 of each element of the array. I know it may not be the best way of doing it

答:
With some minor modifications to your code, such as fixing indentation and using an open source image i do not get any error. So it seems like an indentation errror.

See working code below:

```<code>import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt

imagen_nueva = np.empty((1931, 1282))

imagen = scipy.resize(misc.ascent(), (1931, 1282))

imagen_real = scipy.pad(array=imagen, pad_width=[1, 1], mode='constant',
                        constant_values=0)

(dim_x, dim_y) = np.shape(imagen_real)
print((dim_x, dim_y))

ker1 = np.array([[1/16, 1/8, 1/16],
                 [1/8, 1/4, 1/8],
                 [1/16, 1/8, 1/16]])

def multiplicar_entero():
    global imagen_nueva
    for i in range(1, dim_x + 1):
        for j in range(1, dim_y + 1):
            matriz_elemento = np.array([[imagen_real[i + 1, j - 1], imagen_real[i + 1, j], imagen_real[i + 1, j - 1]],
                                        [imagen_real[i, j - 1], imagen_real[i, j], imagen_real[i, j + 1]],
                                        [imagen_real[i - 1, j - 1], imagen_real[i - 1, j], imagen_real[i - 1, j + 1]]])

            valor = np.sum(matriz_elemento*ker1)
            imagen_real[i, j] = valor
            imagen_nueva = np.append(imagen[i, j], (1931, 1282))
</code>```

Title: Index out of bounds / IndexError

Body:
I am trying to move a kernel around an array of an image to create a gaussian filter. I am getting an IndexError, and Idk why. This is the code: error at line 34

import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt

imagen_nueva = np.empty((1931, 1282))

imagen = scipy.misc.imread("C:\\Users\\Reymi\\Downloads\\imagen.png")

imagen_real = scipy.pad(array=imagen, pad_width=[1, 1], mode='constant',
constant_values=0)

(dim_x,dim_y)=np.shape(imagen_real)
print((dim_x,dim_y))

ker1 = np.array([[1/16, 1/8, 1/16],
            [1/8, 1/4, 1/8],
            [1/16, 1/8, 1/16]])

def multiplicar_entero():
    global imagen_nueva
    for i in range(1,dim_x+1):
    for j in range(1,dim_y+1):
        matriz_elemento = np.array([[imagen_real[i + 1, j - 1],
imagen_real[i + 1, j], imagen_real[i + 1, j - 1]],
                        [imagen_real[i, j - 1], imagen_real[i, j],
imagen_real[i, j + 1]],
                        [imagen_real[i - 1, j - 1], imagen_real[i - 1, j],
imagen_real[i - 1, j + 1]]])
        valor = np.sum(matriz_elemento*ker1)
        imagen_real[i, j] = valor
        imagen_nueva = np.append(imagen[i, j], (1931, 1282))

As for the confusing matrix with is, and js. It is the matrix 3x3 of each element of the array. I know it may not be the best way of doing it

Body:
With some minor modifications to your code, such as fixing indentation and using an open source image i do not get any error. So it seems like an indentation errror.

See working code below:

import numpy as np
import scipy
from scipy import misc
import matplotlib.pyplot as plt

imagen_nueva = np.empty((1931, 1282))

imagen = scipy.resize(misc.ascent(), (1931, 1282))

imagen_real = scipy.pad(array=imagen, pad_width=[1, 1], mode='constant',
                        constant_values=0)

(dim_x, dim_y) = np.shape(imagen_real)
print((dim_x, dim_y))

ker1 = np.array([[1/16, 1/8, 1/16],
                 [1/8, 1/4, 1/8],
                 [1/16, 1/8, 1/16]])

def multiplicar_entero():
    global imagen_nueva
    for i in range(1, dim_x + 1):
        for j in range(1, dim_y + 1):
            matriz_elemento = np.array([[imagen_real[i + 1, j - 1], imagen_real[i + 1, j], imagen_real[i + 1, j - 1]],
                                        [imagen_real[i, j - 1], imagen_real[i, j], imagen_real[i, j + 1]],
                                        [imagen_real[i - 1, j - 1], imagen_real[i - 1, j], imagen_real[i - 1, j + 1]]])

            valor = np.sum(matriz_elemento*ker1)
            imagen_real[i, j] = valor
            imagen_nueva = np.append(imagen[i, j], (1931, 1282))


问:
Resuming Home Screen
I navigate to the subsequent activities in my project and from one activity i want to come at the home screen...Please suggest the exact code for it.

Thanks

答: Check this old answer: Android moving back to first activity on button click</p>

Title: Resuming Home Screen


问:
Stack unsupported version
I'm trying to build libssh2-hs with stack (lts-3.20) and I get some errors:

```<code>$ stack build
No compiler found, expected minor version match with ghc-7.10.2 (x86_64-ncurses6) (based on resolver setting in /home/black/programmation/haskell/libssh2-hs/stack.yaml).
To install the correct GHC into /home/black/.stack/programs/x86_64-linux/, try running "stack setup" or use the "--install-ghc" flag.
$ stack setup
No information found for ghc-7.10.2.
Supported versions for OS key 'linux64-ncurses6': GhcVersion 7.10.3, GhcVersion 8.0.1, GhcVersion 8.0.2
</code>```

I use archlinux 64 bits, what happens here and what can I do?

答:
The source of the problem is hinted at by this error message:

```<code>No information found for ghc-7.10.2.
  Supported versions for OS key 'linux64-ncurses6': GhcVersion 7.10.3, GhcVersion 8.0.1, GhcVersion 8.0.2
</code>```

Arch Linux provides by default libncurses6, while the standard builds of GHC expect libncurses5/libtinfo5. Stack can fetch alternative GHC builds that use libncurses6; however, they are only available from GHC 7.10.3 onward, which explains why you are having this issue with a snapshot that uses GHC 7.10.2. The following suggestion, taken from Stack issue #3177, should solve it:

Install ncurses5-compat-libs from AUR and then force Stack to use the standard GHC bindist by doing something like stack --ghc-build=standard setup.

(Note that the --ghc-build=standard might not be necessary -- if I remember correctly, when I ran into this issue several months ago stack setup detected the appropriate GHC build once I installed ncurses5-compat-libs, with no need to specify it explicitly.)

Title: Stack unsupported version

Body:
I'm trying to build libssh2-hs with stack (lts-3.20) and I get some errors:

$ stack build
No compiler found, expected minor version match with ghc-7.10.2 (x86_64-ncurses6) (based on resolver setting in /home/black/programmation/haskell/libssh2-hs/stack.yaml).
To install the correct GHC into /home/black/.stack/programs/x86_64-linux/, try running "stack setup" or use the "--install-ghc" flag.
$ stack setup
No information found for ghc-7.10.2.
Supported versions for OS key 'linux64-ncurses6': GhcVersion 7.10.3, GhcVersion 8.0.1, GhcVersion 8.0.2

I use archlinux 64 bits, what happens here and what can I do?

Body:
The source of the problem is hinted at by this error message:

No information found for ghc-7.10.2.
  Supported versions for OS key 'linux64-ncurses6': GhcVersion 7.10.3, GhcVersion 8.0.1, GhcVersion 8.0.2

Arch Linux provides by default libncurses6, while the standard builds of GHC expect libncurses5/libtinfo5. Stack can fetch alternative GHC builds that use libncurses6; however, they are only available from GHC 7.10.3 onward, which explains why you are having this issue with a snapshot that uses GHC 7.10.2. The following suggestion, taken from Stack issue #3177, should solve it:

Install ncurses5-compat-libs from AUR and then force Stack to use the standard GHC bindist by doing something like stack --ghc-build=standard setup.

(Note that the --ghc-build=standard might not be necessary -- if I remember correctly, when I ran into this issue several months ago stack setup detected the appropriate GHC build once I installed ncurses5-compat-libs, with no need to specify it explicitly.)


问:
Errors with my python code
My python cod keeps giving me errors like indention and syntax which I keep fixing them but to no avail. So here is the code I'm using I'm still not sure what I'm doing wrong here (BTW this is just due to an argument with a friend about what I can't do)</p>

```<code>import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"], stdout=subprocess.PIPE).communicate()[0]
        return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
        global numberOfSockets
        global numberOfViewers
        while True:
                if numberOfSockets < numberOfViewers:
                        numberOfSockets += 1
                        print "Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers)
                        urls.append(getURL())

def view(): # Opens connections to send views
        global numberOfSockets
        while True:
                url=q.get()
                requests.head(url)
                if (url in urlsUsed):
                        urls.remove(url)
                        urlsUsed.remove(url)
                        numberOfSockets -= 1
                else:
                        urlsUsed.append(url)
                q.task_done()

if __name__ == '__main__':
        for i in range(0, builderThreads):
                threading.Thread(target = build).start()

        while True:
                while (numberOfViewers != numberOfSockets): # Wait until sockets are built
                        time.sleep(1)

                q=Queue(concurrent*2)
                for i in range(concurrent):
                        try:
                                t=threading.Thread(target=view)
                                t.daemon=True
                                t.start()
                        except:
                                print 'thread error'
                try:
                        for url in urls:
                                print url
                                q.put(url.strip())
                                q.join()
                except KeyboardInterrupt:
                        sys.exit(1)
</code>```

答:
Python uses indentation for defining blocks instead of {}.

Also you should keep using the first indentation formating during all document. It means if you start with tabs you have to always use tabs even if spaces look the same visually and if you are using 4 space you can't change later in the  code for tabs or more space.

The error you mentioned usually occurs because you pasted code from the internet and it is using tabs and you are using spaces or vice versa.

I recommend to re-indend the whole code as it's short.

Title: Errors with my python code

Body:
My python cod keeps giving me errors like indention and syntax which I keep fixing them but to no avail. So here is the code I'm using I'm still not sure what I'm doing wrong here (BTW this is just due to an argument with a friend about what I can't do)

import requests
import subprocess
import json
import sys
import threading
import time
from Queue import Queue

numberOfViewers = int(sys.argv[1])
builderThreads = int(sys.argv[2])
startTime = time.time()
numberOfSockets = 0
concurrent = 25
urls = []
urlsUsed = []

def getURL(): # Get tokens
  output = subprocess.Popen(["livestreamer", "twitch.tv/CHANNEL_NAME", "-j"], stdout=subprocess.PIPE).communicate()[0]
        return json.loads(output)['streams']['worst']['url'] # Parse json and return the URL parameter

def build(): # Builds a set of tokens, aka viewers
        global numberOfSockets
        global numberOfViewers
        while True:
                if numberOfSockets < numberOfViewers:
                        numberOfSockets += 1
                        print "Building viewers " + str(numberOfSockets) + "/" + str(numberOfViewers)
                        urls.append(getURL())

def view(): # Opens connections to send views
        global numberOfSockets
        while True:
                url=q.get()
                requests.head(url)
                if (url in urlsUsed):
                        urls.remove(url)
                        urlsUsed.remove(url)
                        numberOfSockets -= 1
                else:
                        urlsUsed.append(url)
                q.task_done()

if __name__ == '__main__':
        for i in range(0, builderThreads):
                threading.Thread(target = build).start()

        while True:
                while (numberOfViewers != numberOfSockets): # Wait until sockets are built
                        time.sleep(1)

                q=Queue(concurrent*2)
                for i in range(concurrent):
                        try:
                                t=threading.Thread(target=view)
                                t.daemon=True
                                t.start()
                        except:
                                print 'thread error'
                try:
                        for url in urls:
                                print url
                                q.put(url.strip())
                                q.join()
                except KeyboardInterrupt:
                        sys.exit(1)