问:
Span flex element on 2 rows in a grid
I'm working on a grid layout and I need it to be customizable dynamically. For example starting with this 4 x 2 grid:

html, body {
    background: #f2f2f2;
    padding: 0;
    margin: 0;
    height: 100%;
}

* {
  box-sizing: border-box;
}

.grid-container {
    background: #f2f2f2;
    position: absolute;
    display: flex;
    flex-wrap: wrap;
    top: 0;
    bottom: 0px;
    width: 100%;
}

.grid-cell {
    flex: 1;
    flex-wrap: wrap;
    margin: 0 -1px -1px 0;
    padding: 10px;
}

.panel-wes {
    background: #ffffff;
    width: 100%;
    height: 100%;
    border-top: 3px solid #e7eaec;
    border-bottom: 3px solid #e7eaec;
}```
<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 class="grid-container">
  <div class="grid-cell" x="0" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="0" y="0"</div>
  </div>
  <div class="grid-cell" x="1" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="1" y="0"</div>
  </div>
  <div class="grid-cell" x="2" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="2" y="0"</div>
  </div>
  <div class="grid-cell" x="3" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="3" y="0"</div>
  </div>
  <div class="grid-cell" x="0" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="0" y="1"</div>
  </div>
  <div class="grid-cell" x="1" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px);">
    <div class="panel-wes">x="1" y="1"</div>
  </div>
  <div class="grid-cell" x="2" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="2" y="1"</div>
  </div>
  <div class="grid-cell" x="3" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="3" y="1"</div>
  </div>
</div></code>```

I can make one of my tiles span on multiple columns this way:

html, body {
    background: #f2f2f2;
    padding: 0;
    margin: 0;
    height: 100%;
}

* {
  box-sizing: border-box;
}

.grid-container {
    background: #f2f2f2;
    position: absolute;
    display: flex;
    flex-wrap: wrap;
    top: 0;
    bottom: 0px;
    width: 100%;
}

.grid-cell {
    flex: 1;
    flex-wrap: wrap;
    margin: 0 -1px -1px 0;
    padding: 10px;
}

.panel-wes {
    background: #ffffff;
    width: 100%;
    height: 100%;
    border-top: 3px solid #e7eaec;
    border-bottom: 3px solid #e7eaec;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="grid-cell" x="0" y="0" style="min-width: calc(50% + 1px); max-width: calc(50% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="0" y="0"</div>
  </div>
  <!--div class="grid-cell" x="1" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="1" y="0"</div>
  </div-->
  <div class="grid-cell" x="2" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="2" y="0"</div>
  </div>
  <div class="grid-cell" x="3" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="3" y="0"</div>
  </div>
  <div class="grid-cell" x="0" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="0" y="1"</div>
  </div>
  <div class="grid-cell" x="1" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px);">
    <div class="panel-wes">x="1" y="1"</div>
  </div>
  <div class="grid-cell" x="2" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="2" y="1"</div>
  </div>
  <div class="grid-cell" x="3" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="3" y="1"</div>
  </div>
</div></code>```

But I can't find a way to span a tile on multiple rows because this is what happens when I try:

html, body {
    background: #f2f2f2;
    padding: 0;
    margin: 0;
    height: 100%;
}

* {
  box-sizing: border-box;
}

.grid-container {
    background: #f2f2f2;
    position: absolute;
    display: flex;
    flex-wrap: wrap;
    top: 0;
    bottom: 0px;
    width: 100%;
}

.grid-cell {
    flex: 1;
    flex-wrap: wrap;
    margin: 0 -1px -1px 0;
    padding: 10px;
}

.panel-wes {
    background: #ffffff;
    width: 100%;
    height: 100%;
    border-top: 3px solid #e7eaec;
    border-bottom: 3px solid #e7eaec;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="grid-cell" x="0" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(100% + 1px); max-height: calc(100% + 1px);">
    <div class="panel-wes">x="0" y="0"</div>
  </div>
  <div class="grid-cell" x="1" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="1" y="0"</div>
  </div>
  <div class="grid-cell" x="2" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="2" y="0"</div>
  </div>
  <div class="grid-cell" x="3" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="3" y="0"</div>
  </div>
  <!--div class="grid-cell" x="0" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="0" y="1"</div>
  </div-->
  <div class="grid-cell" x="1" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px);">
    <div class="panel-wes">x="1" y="1"</div>
  </div>
  <div class="grid-cell" x="2" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="2" y="1"</div>
  </div>
  <div class="grid-cell" x="3" y="1" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
    <div class="panel-wes">x="3" y="1"</div>
  </div>
</div></code>```

I found an article talking about this and it suggested to create a "column" div but then I will not be able to achieve horizontal spanning. Is there any known solution to this problem?

答:
Using your current grid system, you would need to do something like this: add a second column as a sibling of the 100% height one and then put the remaining boxes inside the second column.

In the below code, I added the wrapper cell and added display:flex to that cell.  I then changed the widths of the cells inside that wrapper to 33%.

I have also removed the padding from the wrapper grid-cell (because of your negative margins, it actually needs 1px padding to remove the padding)

Finally, I added a horizontal span cell too, just to show you it does both

html,
body {
  background: #f2f2f2;
  padding: 0;
  margin: 0;
  height: 100%;
}

* {
  box-sizing: border-box;
}

.grid-container {
  background: #f2f2f2;
  position: absolute;
  display: flex;
  flex-wrap: wrap;
  top: 0;
  bottom: 0px;
  width: 100%;
}

.grid-cell {
  display: flex; /* add this */
  flex: 1;
  flex-wrap: wrap;
  margin: 0 -1px -1px 0;
  padding: 10px;
}

.panel-wes {
  background: #ffffff;
  width: 100%;
  height: 100%;
  border-top: 3px solid #e7eaec;
  border-bottom: 3px solid #e7eaec;
}

.no-padding {
  padding: 1px;
}

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="grid-cell" x="0" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(100% + 1px); max-height: calc(100% + 1px);">
    <div class="panel-wes">x="0" y="0"</div>
  </div>
  <div class="grid-cell no-padding">
    <div class="grid-cell" x="1" y="0" style="min-width: calc(33% + 1px); max-width: calc(33% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
      <div class="panel-wes">x="1" y="0"</div>
    </div>
    <div class="grid-cell" x="2" y="0" style="min-width: calc(33% + 1px); max-width: calc(33% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
      <div class="panel-wes">x="2" y="0"</div>
    </div>
    <div class="grid-cell" x="3" y="0" style="min-width: calc(33% + 1px); max-width: calc(33% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
      <div class="panel-wes">x="3" y="0"</div>
    </div>
    <div class="grid-cell" x="1" y="1" style="min-width: calc(33% + 1px); max-width: calc(33% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
      <div class="panel-wes">x="1" y="1"</div>
    </div>
    <div class="grid-cell" x="2" y="1" style="min-width: calc(66% + 1px); max-width: calc(33% + 1px);">
      <div class="panel-wes">x="2" y="1"</div>
    </div>
  </div>
</div></code>```

Title: Span flex element on 2 rows in a grid

Body:
I'm working on a grid layout and I need it to be customizable dynamically. For example starting with this 4 x 2 grid:

html, body {
    background: #f2f2f2;
    padding: 0;
    margin: 0;
    height: 100%;
}

* {
  box-sizing: border-box;
}

.grid-container {
    background: #f2f2f2;
    position: absolute;
    display: flex;
    flex-wrap: wrap;
    top: 0;
    bottom: 0px;
    width: 100%;
}

.grid-cell {
    flex: 1;
    flex-wrap: wrap;
    margin: 0 -1px -1px 0;
    padding: 10px;
}

.panel-wes {
    background: #ffffff;
    width: 100%;
    height: 100%;
    border-top: 3px solid #e7eaec;
    border-bottom: 3px solid #e7eaec;
}

x="0" y="0"

x="1" y="0"

x="2" y="0"

x="3" y="0"

x="0" y="1"

x="1" y="1"

x="2" y="1"

x="3" y="1"

I can make one of my tiles span on multiple columns this way:

html, body {
    background: #f2f2f2;
    padding: 0;
    margin: 0;
    height: 100%;
}

* {
  box-sizing: border-box;
}

.grid-container {
    background: #f2f2f2;
    position: absolute;
    display: flex;
    flex-wrap: wrap;
    top: 0;
    bottom: 0px;
    width: 100%;
}

.grid-cell {
    flex: 1;
    flex-wrap: wrap;
    margin: 0 -1px -1px 0;
    padding: 10px;
}

.panel-wes {
    background: #ffffff;
    width: 100%;
    height: 100%;
    border-top: 3px solid #e7eaec;
    border-bottom: 3px solid #e7eaec;
}

x="0" y="0"

x="2" y="0"

x="3" y="0"

x="0" y="1"

x="1" y="1"

x="2" y="1"

x="3" y="1"

But I can't find a way to span a tile on multiple rows because this is what happens when I try:

html, body {
    background: #f2f2f2;
    padding: 0;
    margin: 0;
    height: 100%;
}

* {
  box-sizing: border-box;
}

.grid-container {
    background: #f2f2f2;
    position: absolute;
    display: flex;
    flex-wrap: wrap;
    top: 0;
    bottom: 0px;
    width: 100%;
}

.grid-cell {
    flex: 1;
    flex-wrap: wrap;
    margin: 0 -1px -1px 0;
    padding: 10px;
}

.panel-wes {
    background: #ffffff;
    width: 100%;
    height: 100%;
    border-top: 3px solid #e7eaec;
    border-bottom: 3px solid #e7eaec;
}

x="0" y="0"

x="1" y="0"

x="2" y="0"

x="3" y="0"

x="1" y="1"

x="2" y="1"

x="3" y="1"

I found an article talking about this and it suggested to create a "column" div but then I will not be able to achieve horizontal spanning. Is there any known solution to this problem?

Body:
Using your current grid system, you would need to do something like this: add a second column as a sibling of the 100% height one and then put the remaining boxes inside the second column.

In the below code, I added the wrapper cell and added display:flex to that cell.  I then changed the widths of the cells inside that wrapper to 33%.

I have also removed the padding from the wrapper grid-cell (because of your negative margins, it actually needs 1px padding to remove the padding)

Finally, I added a horizontal span cell too, just to show you it does both

html,
body {
  background: #f2f2f2;
  padding: 0;
  margin: 0;
  height: 100%;
}

* {
  box-sizing: border-box;
}

.grid-container {
  background: #f2f2f2;
  position: absolute;
  display: flex;
  flex-wrap: wrap;
  top: 0;
  bottom: 0px;
  width: 100%;
}

.grid-cell {
  display: flex; /* add this */
  flex: 1;
  flex-wrap: wrap;
  margin: 0 -1px -1px 0;
  padding: 10px;
}

.panel-wes {
  background: #ffffff;
  width: 100%;
  height: 100%;
  border-top: 3px solid #e7eaec;
  border-bottom: 3px solid #e7eaec;
}

.no-padding {
  padding: 1px;
}

<div class="grid-container">
  <div class="grid-cell" x="0" y="0" style="min-width: calc(25% + 1px); max-width: calc(25% + 1px); min-height: calc(100% + 1px); max-height: calc(100% + 1px);">
    <div class="panel-wes">x="0" y="0"</div>
  </div>
  <div class="grid-cell no-padding">
    <div class="grid-cell" x="1" y="0" style="min-width: calc(33% + 1px); max-width: calc(33% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
      <div class="panel-wes">x="1" y="0"</div>
    </div>
    <div class="grid-cell" x="2" y="0" style="min-width: calc(33% + 1px); max-width: calc(33% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
      <div class="panel-wes">x="2" y="0"</div>
    </div>
    <div class="grid-cell" x="3" y="0" style="min-width: calc(33% + 1px); max-width: calc(33% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
      <div class="panel-wes">x="3" y="0"</div>
    </div>
    <div class="grid-cell" x="1" y="1" style="min-width: calc(33% + 1px); max-width: calc(33% + 1px); min-height: calc(50% + 1px); max-height: calc(50% + 1px);">
      <div class="panel-wes">x="1" y="1"</div>
    </div>
    <div class="grid-cell" x="2" y="1" style="min-width: calc(66% + 1px); max-width: calc(33% + 1px);">
      <div class="panel-wes">x="2" y="1"</div>
    </div>
  </div>
</div>


来源: stackexchange

问:
Display XML format data in html div
I need to display a XML format data fetched from the database to be displayed in a division. But its not displaying with the xml tags on. Is there any way to get xml data as such with the tags in the div?

The xml which i need is given below:

```<code><Name>public</name><Number>848065065639AuthDemoClient:STGKSITM01:20140109052539707</Number><Ret>y</Ret><Tmestamp>2014-01-09T17:22:15.318+05:30GCSD017263</timestamp>
</code>```

But its getting displayed as follows:

public848065065639AuthDemoClient:STGKSITM01:20140109052539707y2014-01-09T17:22:15.318+05:30GCSD017263

Please suggest a solution

答:
In your HTML, you can try displaying it in a textarea like below , it will display XML as it is JsFiddle Example

```<code><div>
<textarea rows="20" cols="40" style="border:none;" disabled>
    <?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <country>Columbia</country>
        <price>10.90</price>
        <year>1985</year>
    </cd>
</catalog>
</textarea>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Display XML format data in html div

Body:
I need to display a XML format data fetched from the database to be displayed in a division. But its not displaying with the xml tags on. Is there any way to get xml data as such with the tags in the div?

The xml which i need is given below:

<Name>public</name><Number>848065065639AuthDemoClient:STGKSITM01:20140109052539707</Number><Ret>y</Ret><Tmestamp>2014-01-09T17:22:15.318+05:30GCSD017263</timestamp>

But its getting displayed as follows:

public848065065639AuthDemoClient:STGKSITM01:20140109052539707y2014-01-09T17:22:15.318+05:30GCSD017263

Please suggest a solution

Body:
In your HTML, you can try displaying it in a textarea like below , it will display XML as it is JsFiddle Example

<div>
<textarea rows="20" cols="40" style="border:none;" disabled>
    <?xml version="1.0" encoding="ISO-8859-1"?>
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <country>Columbia</country>
        <price>10.90</price>
        <year>1985</year>
    </cd>
</catalog>
</textarea>


问:
Issue in pagination angularjs
I am having an issue with pagination :
This is my html

```<code>    <div class="panel panel-info" ng-repeat="item in filteredTodos | orderBy: 'Date' : true | filter : search">
     {{item.Name}}
    </div>
<div data-pagination="" data-num-pages="numPages()"
      data-current-page="currentPage" data-max-size="maxSize"
      data-boundary-links="true"></div>
</code>```

and this is my controller :

```<code>$scope.filteredTodos = []
  $scope.currentPage = 1
  $scope.numPerPage = 4
  $scope.maxSize = 5

  $scope.makeTodos = function() {
    $scope.Offre = [];
    $http({
                header: 'content-type:application/json',
                method: 'GET',
                url: '/GetOffre',
            }).success(function (messages) {
            $scope.Offre =messages  ;
      });

  };
  $scope.makeTodos();

  $scope.numPages = function () {
    return Math.ceil($scope.Offre.length / $scope.numPerPage);
  };

  $scope.$watch('currentPage + numPerPage', function() {
    var begin = (($scope.currentPage - 1) * $scope.numPerPage)
    , end = begin + $scope.numPerPage;

    $scope.filteredTodos = $scope.Offre.slice(begin, end);
  });
</code>```

so the problem is when i want to show my result
result

i tried to change the currentPage = 0 so in view i can click in 1 and i can see the result only when i click on 1... and when i refresh the page the same issue is repeated

答:
Use limitto in you ng-repeat it's better than $watch</p>

```<code><div class="panel panel-info" ng-repeat="item in filteredTodos | orderBy: 'Date' : true | filter : search"|limitTo:(($scope.currentPage - 1) * $scope.numPerPage):$scope.numPerPage*$scope.currentPage>
 {{item.Name}}
</div>
</code>```

Title: Issue in pagination angularjs

Body:
I am having an issue with pagination :
This is my html

     {{item.Name}}

and this is my controller :

$scope.filteredTodos = []
  $scope.currentPage = 1
  $scope.numPerPage = 4
  $scope.maxSize = 5

  $scope.makeTodos = function() {
    $scope.Offre = [];
    $http({
                header: 'content-type:application/json',
                method: 'GET',
                url: '/GetOffre',
            }).success(function (messages) {
            $scope.Offre =messages  ;
      });

  };
  $scope.makeTodos();

  $scope.numPages = function () {
    return Math.ceil($scope.Offre.length / $scope.numPerPage);
  };

  $scope.$watch('currentPage + numPerPage', function() {
    var begin = (($scope.currentPage - 1) * $scope.numPerPage)
    , end = begin + $scope.numPerPage;

    $scope.filteredTodos = $scope.Offre.slice(begin, end);
  });

so the problem is when i want to show my result
result

i tried to change the currentPage = 0 so in view i can click in 1 and i can see the result only when i click on 1... and when i refresh the page the same issue is repeated

Body:
Use limitto in you ng-repeat it's better than $watch

<div class="panel panel-info" ng-repeat="item in filteredTodos | orderBy: 'Date' : true | filter : search"|limitTo:(($scope.currentPage - 1) * $scope.numPerPage):$scope.numPerPage*$scope.currentPage>
 {{item.Name}}
</div>


问:
Best way for z-ordering sprites on isometric map with cocos2d
after few headaches i figured out that using CCSpriteBatchNode with cocos2d olny allows to z-order sprites added to it as child (which is obvious, now i see..)

```<code>    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"token_default.plist"];
    CCSpriteBatchNode *tokenSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"token_default.png"];
    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"objects_default.plist"];
    CCSpriteBatchNode *objectsSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"objects_default.png"];

    CCSprite *token = [[[CCSprite alloc] initWithSpriteFrameName:@"token_SE.png"] autorelease];
    [token setPosition:tokenSpawnPoint];
    CCSprite *enemy = [[[CCSprite alloc] initWithSpriteFrameName:@"token_blak_SE.png"] autorelease];
    [enemy setPosition:enemySpawnPoint];
    CCSprite *houseA = [[[CCSprite alloc] initWithSpriteFrameName:@"house_small.png"] autorelease];
    [houseA setPosition:[self randomHousePosition]];
    CCSprite *houseB = [[[CCSprite alloc] initWithSpriteFrameName:@"house_big.png"] autorelease];
    [houseB setPosition:[self randomHousePosition]];

    [tokenSpriteSheet addChild:token];
    [tokenSpriteSheet addChild:enemy];
    [objectsSpriteSheet addChild:houseA];
    [objectsSpriteSheet addChild:houseB];
</code>```

and since i have to add them to the display list as follows..

```<code>    [_isoMap addChild:objectsSpriteSheet];
    [_isoMap addChild:tokenSpriteSheet];
</code>```

there is no way i can change the z-order of single tokens between other houses...

they will be always rendered over the house until i change the order of these batch nodes

btw, i can "merge" all sprites' arts in one big single batch node... doing so it became possible to order sprites using sprite's coordinates

```<code>    [fullSpriteSheet reorderChild:token z:token.position.y];
</code>```

i'm a little stuck with it...... is there a way to achieve that, having different sprite bacth nodes? or is possible to programmatically merge two batchnodes? (or something like that)

i found KnightFight, a really interesting open project on github by LozArcher.. he used CCSpriteFrame and CCSprite's setDisplayFrame method, instead of batch nodes... but i can't run it since it seems to be an older version of cocos2d (apparently not working with xcode 4)

答:
Set the Sprites Z order to it's Y position on the map. Reorder your dynamic sprites in an update loop. Calculate the Z order using the Sprites current Y position and the visible height of the map.</p>

```<code>void LocalGameController::SetZOrderForObject(cocos2d::Sprite *object){
  int objectZOrder = visibleSize.height - object->getPositionY();
  context->reorderChild(object, objectZOrder);
}
</code>```

Body:
after few headaches i figured out that using CCSpriteBatchNode with cocos2d olny allows to z-order sprites added to it as child (which is obvious, now i see..)

    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"token_default.plist"];
    CCSpriteBatchNode *tokenSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"token_default.png"];
    [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"objects_default.plist"];
    CCSpriteBatchNode *objectsSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"objects_default.png"];

    CCSprite *token = [[[CCSprite alloc] initWithSpriteFrameName:@"token_SE.png"] autorelease];
    [token setPosition:tokenSpawnPoint];
    CCSprite *enemy = [[[CCSprite alloc] initWithSpriteFrameName:@"token_blak_SE.png"] autorelease];
    [enemy setPosition:enemySpawnPoint];
    CCSprite *houseA = [[[CCSprite alloc] initWithSpriteFrameName:@"house_small.png"] autorelease];
    [houseA setPosition:[self randomHousePosition]];
    CCSprite *houseB = [[[CCSprite alloc] initWithSpriteFrameName:@"house_big.png"] autorelease];
    [houseB setPosition:[self randomHousePosition]];

    [tokenSpriteSheet addChild:token];
    [tokenSpriteSheet addChild:enemy];
    [objectsSpriteSheet addChild:houseA];
    [objectsSpriteSheet addChild:houseB];

and since i have to add them to the display list as follows..

    [_isoMap addChild:objectsSpriteSheet];
    [_isoMap addChild:tokenSpriteSheet];

there is no way i can change the z-order of single tokens between other houses...

they will be always rendered over the house until i change the order of these batch nodes

btw, i can "merge" all sprites' arts in one big single batch node... doing so it became possible to order sprites using sprite's coordinates

    [fullSpriteSheet reorderChild:token z:token.position.y];

i'm a little stuck with it...... is there a way to achieve that, having different sprite bacth nodes? or is possible to programmatically merge two batchnodes? (or something like that)

i found KnightFight, a really interesting open project on github by LozArcher.. he used CCSpriteFrame and CCSprite's setDisplayFrame method, instead of batch nodes... but i can't run it since it seems to be an older version of cocos2d (apparently not working with xcode 4)

Body:
Set the Sprites Z order to it's Y position on the map. Reorder your dynamic sprites in an update loop. Calculate the Z order using the Sprites current Y position and the visible height of the map.

void LocalGameController::SetZOrderForObject(cocos2d::Sprite *object){
  int objectZOrder = visibleSize.height - object->getPositionY();
  context->reorderChild(object, objectZOrder);
}


问:
Grouping Angular services together to inject them in multiple Controllers
I am currently trying to refactor everything on our company following best practices and JohnPapa's style guide, which means that among other things, I am supposed to switch from setTimeout to $timeout, setInterval to $interval, etc.

However, I find it tiring, messy, and counter-intuitive to have to inject those services every single time. This results in long repetitive controller declarations where half of the elements are useless and obvious.

```<code>angular.module('myModule',[])
    .controller('MyController', ['$scope', '$http', '$timeout', '$interval', MyController])
    .controller('MyController2', ['$scope', '$http', '$timeout', '$interval', MyController2])
    .controller('MyController3', ['$scope', '$http', '$timeout', '$interval', MyController3])
</code>```

I find this ugly, and a pain to maintain; this is the reason why I've always favored setTimeout over $timeout, but now I'm trying to improve.

Would there be a way to "mass inject" services?

For example something such as:

```<code>var baseServices = {
    http: $http,
    scope: $scope,
    timeout: $timeout,
    interval: $interval,
};

angular.module('myModule',[])
    .controller('MyController', ['baseServices', MyController])
    .controller('MyController2', ['baseServices', MyController2])
    .controller('MyController3', ['baseServices', MyController3])

var MyController = function(baseServices){
        baseServices.$timeout(...);
}
</code>```

Is this something remotely possible?

答:
Maybe you could use a factory to group all these services and use it from your controller</p>

```<code>angular.module('myModule',[])
   .controller('MyController', ['baseServices', MyController])
angularApp.factory('baseServices', baseServices );
function baseServices ($scope, $http, $timeout, $interval) {
        return {
            scope: $scope,
            http: $http,
            timeout: $timeout,
            interval: $interval
        };
}
</code>```

Body:
I am currently trying to refactor everything on our company following best practices and JohnPapa's style guide, which means that among other things, I am supposed to switch from setTimeout to $timeout, setInterval to $interval, etc.

However, I find it tiring, messy, and counter-intuitive to have to inject those services every single time. This results in long repetitive controller declarations where half of the elements are useless and obvious.

angular.module('myModule',[])
    .controller('MyController', ['$scope', '$http', '$timeout', '$interval', MyController])
    .controller('MyController2', ['$scope', '$http', '$timeout', '$interval', MyController2])
    .controller('MyController3', ['$scope', '$http', '$timeout', '$interval', MyController3])

I find this ugly, and a pain to maintain; this is the reason why I've always favored setTimeout over $timeout, but now I'm trying to improve.

Would there be a way to "mass inject" services?

For example something such as:

var baseServices = {
    http: $http,
    scope: $scope,
    timeout: $timeout,
    interval: $interval,
};

angular.module('myModule',[])
    .controller('MyController', ['baseServices', MyController])
    .controller('MyController2', ['baseServices', MyController2])
    .controller('MyController3', ['baseServices', MyController3])

var MyController = function(baseServices){
        baseServices.$timeout(...);
}

Is this something remotely possible?

Body:
Maybe you could use a factory to group all these services and use it from your controller

angular.module('myModule',[])
   .controller('MyController', ['baseServices', MyController])
angularApp.factory('baseServices', baseServices );
function baseServices ($scope, $http, $timeout, $interval) {
        return {
            scope: $scope,
            http: $http,
            timeout: $timeout,
            interval: $interval
        };
}


问:
Exporting contacts
Can someone tell me how the contacts.apk application does the "export" functionality. Does it read each and every row of the contacts.db using cursors and then convert them into .vcf. This seems to be painfully slow, but the application seems to be doing this much faster. It would be great if someone can point me to the code that does the "export" functionality.</p>

答: The Android source code is on android.git.kernel.org.</p>

ContentLicense: CC BY-SA 2.5

Title: Exporting contacts


问:
Passing an array between pages in ionic 2
I'm new in Ionic 2 and I'm having troubles with passing data between pages. In my Home.ts file  I have a global array that contains some numbers I calculated and i want to pass it to my Table.ts file, to show it in a HTML table with the *ngFor method.

this is the Function in Home.ts where i fill the array and try to push (i will skip the calculations, becacause i know they are correct).

```<code>`import { Component } from '@angular/core';
 import { AlertController } from 'ionic-angular';
 import { IonicPage,NavController, NavParams} from 'ionic-angular';
 import {Table} from '../table/table';

 export class HomePage {

 averagesList: Array <number> =[];

 constructor(public alerCtrl: AlertController,
             public navCtrl: NavController,
             public navParams: NavParams)
             {}

 Calculate(){

 var Averages=[];

 //Calculations on the 'Averages' Array

 this.averagesList = Averages;

this.navCtrl.push(Table,this.averagesList);
 }

}
</code>```

So I try to print it in my Table.ts file but it gives me undefined result

```<code>import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {HomePage} from '../home/home';
@IonicPage()
@Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class Table{

constructor(public navCtrl: NavController, public navParams: NavParams) {

}

ionViewDidLoad() {

console.log(this.navParams.get('averagesList'));
}
}
</code>```

I've tried to pass a let variable and it worked, so why doesn't it work with arrays?

答:
It's better to use service for passing nested data. In your case calculations object.

You can create messageService and listen to changes, something like below.

```<code>import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {Subject} from 'rxjs/Subject';

@Injectable()

 export class LocalMsgService {

private subject = new Subject();

sendMessage(message) {
    this.subject.next(message);
}

clearMessage() {
    this.subject.next();
}

  getMessage(): Observable<any> {
     return this.subject.asObservable();
  }
}
</code>```

Which can be used in your home.ts and table.ts pages as follows

Home.ts

```<code>    //other imports comes here
    import {LocalMsgService} from 'services/localMsg';

    @Component({
        selector: 'home-component',
        templateUrl: 'home.html'
    })
    export class HomePage {
        constructor( private msgService: LocalMsgService) {

          }

        dataToPass() {
            console.log(this.averagesList);
            this.msgService.sendMessage(this.averagesList);
        }

    }
</code>```

Table.ts

```<code>       //other imports comes here
       import {LocalMsgService} from 'services/localMsg';
       import {Subscription} from 'rxjs/Subscription';

        @Component({
           selector: 'page-table',
          templateUrl: 'table.html',
        })

        export class TablePage{

            items: any;
            subscription: Subscription;

            constructor(
            public localMsgService : LocalMsgService) {
                this.subscription = this.localMsgService.getMessage().subscribe(msg => {
                    this.items = msg;
                });
            }

        }
</code>```

Body:
I'm new in Ionic 2 and I'm having troubles with passing data between pages. In my Home.ts file  I have a global array that contains some numbers I calculated and i want to pass it to my Table.ts file, to show it in a HTML table with the *ngFor method.

this is the Function in Home.ts where i fill the array and try to push (i will skip the calculations, becacause i know they are correct).

`import { Component } from '@angular/core';
 import { AlertController } from 'ionic-angular';
 import { IonicPage,NavController, NavParams} from 'ionic-angular';
 import {Table} from '../table/table';

 export class HomePage {

 averagesList: Array <number> =[];

 constructor(public alerCtrl: AlertController,
             public navCtrl: NavController,
             public navParams: NavParams)
             {}

 Calculate(){

 var Averages=[];

 //Calculations on the 'Averages' Array

 this.averagesList = Averages;

this.navCtrl.push(Table,this.averagesList);
 }

}

So I try to print it in my Table.ts file but it gives me undefined result

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {HomePage} from '../home/home';
@IonicPage()
@Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class Table{

constructor(public navCtrl: NavController, public navParams: NavParams) {

}

ionViewDidLoad() {

console.log(this.navParams.get('averagesList'));
}
}

I've tried to pass a let variable and it worked, so why doesn't it work with arrays?

Body:
It's better to use service for passing nested data. In your case calculations object.

You can create messageService and listen to changes, something like below.

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {Subject} from 'rxjs/Subject';

@Injectable()

 export class LocalMsgService {

private subject = new Subject();

sendMessage(message) {
    this.subject.next(message);
}

clearMessage() {
    this.subject.next();
}

  getMessage(): Observable<any> {
     return this.subject.asObservable();
  }
}

Which can be used in your home.ts and table.ts pages as follows

Home.ts

    //other imports comes here
    import {LocalMsgService} from 'services/localMsg';

    @Component({
        selector: 'home-component',
        templateUrl: 'home.html'
    })
    export class HomePage {
        constructor( private msgService: LocalMsgService) {

          }

        dataToPass() {
            console.log(this.averagesList);
            this.msgService.sendMessage(this.averagesList);
        }

    }

Table.ts

       //other imports comes here
       import {LocalMsgService} from 'services/localMsg';
       import {Subscription} from 'rxjs/Subscription';

        @Component({
           selector: 'page-table',
          templateUrl: 'table.html',
        })

        export class TablePage{

            items: any;
            subscription: Subscription;

            constructor(
            public localMsgService : LocalMsgService) {
                this.subscription = this.localMsgService.getMessage().subscribe(msg => {
                    this.items = msg;
                });
            }

        }


问:
How to know what record I am in? Dynamics AX7
Here is the scenario:

In the Sales and marketing > Sales orders > All sales orders

I entered the lines by double-clicking the Sales order number

by doing that I am entering the lines of the sales order.

Now in my lines, there is a button there where I will use to add a syntax where I will insert fields in my newly created table.

I would like to know how can I know what record I am in (before entering the lines/before double-clicking the sales order number). I need to know what Sales order number I'm in as I enter the lines of the record.

答: In every form the current record of a specific FormDataSource has the same name of the FormDataSource. For example in the SalesTableListPage form the only datasource is called "SalesTable", so the current sales order record is identified in your code with the salesTable identifier.


问:
How to delay Picasso image loading?
I have implemented a shared element activity transition animation between MainActivity (GridView) and DetailActivity. When item is clicked, the image in Grid item will zoom-in to become the background image in DetailActivity. I have made the transition very smooth by saving the image on the MainActivity into a file, then use it as placeholder image in DetailActivity before the higher quality image is downloaded via picasso. When picasso finished its task the higher quality image will replace the placeholder one very neatly.

Code from onCreateView() in DetailActivityFragment.java

```<code>ImageView iv = (ImageView) mRootview.findViewById(R.id.movie_poster);
try {
    // Prepare "InterimPoster" jpeg file to be placeholder image
    Bitmap bitmap = BitmapFactory.decodeStream(c.openFileInput("InterimPoster"));
    Picasso.with(c).load("http://image.tmdb.org/t/p/w780" + mMovieInfo[2])
            .placeholder(new BitmapDrawable(getResources(), bitmap))
            .fit()
            .centerCrop()
            .noFade()
            .into(iv);

} catch (FileNotFoundException e) {
    e.printStackTrace();
}
</code>```

As for animation, I implement it like in the link here step 1-3 https://guides.codepath.com/android/Shared-Element-Activity-Transition

However, sometimes there's flicker when the higher quality image finished download before the transition animation is completed. The zooming-in image will be replaced with new image while moving which is an unpleasant animation.

So I wonder how can I fix this flicker? One thing I can think of is to delay the image download because I already have lower quality image as a placeholder. How can I do that?

Here the video.
Usually, on my test device it's smooth 80% of the time, but luckily in this video it flicker most of the time.

答:
Try the below code:

First use picasso normally to load placeholder into the imageview

```<code>iv.setImageBitmap(bitmap);
</code>```

Then use SharedElement Listener like this

```<code>Transition sharedElementEnterTransition = getWindow().getSharedElementEnterTransition();sharedElementEnterTransition.addListener(new TransitionListenerAdapter() {
     @Override
      public void onTransitionEnd(android.support.transition.Transition transition) {
                super.onTransitionEnd(transition);
         Picasso.with(c).load("http://image.tmdb.org/t/p/w780" + mMovieInfo[2])
        .placeholder(new BitmapDrawable(getResources(), bitmap))
        .fit()
        .centerCrop()
        .noFade()
        .into(iv);
       }
  });
</code>```

Title: How to delay Picasso image loading?

Body:
I have implemented a shared element activity transition animation between MainActivity (GridView) and DetailActivity. When item is clicked, the image in Grid item will zoom-in to become the background image in DetailActivity. I have made the transition very smooth by saving the image on the MainActivity into a file, then use it as placeholder image in DetailActivity before the higher quality image is downloaded via picasso. When picasso finished its task the higher quality image will replace the placeholder one very neatly.

Code from onCreateView() in DetailActivityFragment.java

ImageView iv = (ImageView) mRootview.findViewById(R.id.movie_poster);
try {
    // Prepare "InterimPoster" jpeg file to be placeholder image
    Bitmap bitmap = BitmapFactory.decodeStream(c.openFileInput("InterimPoster"));
    Picasso.with(c).load("http://image.tmdb.org/t/p/w780" + mMovieInfo[2])
            .placeholder(new BitmapDrawable(getResources(), bitmap))
            .fit()
            .centerCrop()
            .noFade()
            .into(iv);

} catch (FileNotFoundException e) {
    e.printStackTrace();
}

As for animation, I implement it like in the link here step 1-3 https://guides.codepath.com/android/Shared-Element-Activity-Transition

However, sometimes there's flicker when the higher quality image finished download before the transition animation is completed. The zooming-in image will be replaced with new image while moving which is an unpleasant animation.

So I wonder how can I fix this flicker? One thing I can think of is to delay the image download because I already have lower quality image as a placeholder. How can I do that?

Here the video.
Usually, on my test device it's smooth 80% of the time, but luckily in this video it flicker most of the time.

Body:
Try the below code:

First use picasso normally to load placeholder into the imageview

iv.setImageBitmap(bitmap);

Then use SharedElement Listener like this

Transition sharedElementEnterTransition = getWindow().getSharedElementEnterTransition();sharedElementEnterTransition.addListener(new TransitionListenerAdapter() {
     @Override
      public void onTransitionEnd(android.support.transition.Transition transition) {
                super.onTransitionEnd(transition);
         Picasso.with(c).load("http://image.tmdb.org/t/p/w780" + mMovieInfo[2])
        .placeholder(new BitmapDrawable(getResources(), bitmap))
        .fit()
        .centerCrop()
        .noFade()
        .into(iv);
       }
  });


问:
what is Promotional and Feature graphic in Android Market/Play Store?
What does it mean and need whether we are uploading our app into the market? Please Explain or give me a related links.</p>

答:
In market client on phones at least
  featured apps with high ratings get to
  display the promotional graphic.

This is the one that shows up on top
  even before you start searching the
  market for a specific app.

See this answer from Android market forum.

Edited: One of the google employee gives some clarifications here

Update: Both links above are now broken but the detailed information can be found here

Selected applications have the ability
  to be featured atop their respective
  categories. This is not a guaranteed
  feature, but uploading promotional
  graphics is something that we
  recommend.


问:
Trying to get all content of directory from one server to another using ssh2_scp_recv in php
The below script is working successfully.

Getting file from one server to another

```<code>if(ssh2_scp_recv($conn, '/var/www/html/captures/store/2016/04/HK/15721022890870/test/vcredist.bmp',
    '/var/www/html/captures/store/2016/04/HK/15721022890870/test/vcredist.bmp')){
echo "\n recevied \n";
  }else{
 echo "\n not recevied\n";
  }
</code>```

But instead for fetching just a static file, I want to fetch folder with all its content inside.

With above example, the directory I would like to fetch to local server is  "15721022890870"

```<code>/var/www/html/captures/store/2016/04/HK/15721022890870/
</code>```

I have tried below code but doesn't work,

The remote server has directory, but the local server doesn't have, so I want to make directory then copy all its content inside

```<code>if(ssh2_scp_recv($conn, '/var/www/html/captures/store/2016/04/HK/15721022890870/',
    '/var/www/html/captures/store/2016/04/HK/')){
echo "\n recevied done \n";
  }else{
  echo "\n not done \n";
   }
</code>```

答:
```<code><?php
$username = "your_username";
$password = "your_pass";
$url      = 'your_stp_server_url';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');
$localDir  = '/path/to/your/local/dir';
$remoteDir = '/path/to/your/remote/dir';
// download all the files
$files    = scandir('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
      ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
    }
  }
}
?>
</code>```

This is from server to computer but you can modify the $localDir

Body:
The below script is working successfully.

Getting file from one server to another

if(ssh2_scp_recv($conn, '/var/www/html/captures/store/2016/04/HK/15721022890870/test/vcredist.bmp',
    '/var/www/html/captures/store/2016/04/HK/15721022890870/test/vcredist.bmp')){
echo "\n recevied \n";
  }else{
 echo "\n not recevied\n";
  }

But instead for fetching just a static file, I want to fetch folder with all its content inside.

With above example, the directory I would like to fetch to local server is  "15721022890870"

/var/www/html/captures/store/2016/04/HK/15721022890870/

I have tried below code but doesn't work,

The remote server has directory, but the local server doesn't have, so I want to make directory then copy all its content inside

if(ssh2_scp_recv($conn, '/var/www/html/captures/store/2016/04/HK/15721022890870/',
    '/var/www/html/captures/store/2016/04/HK/')){
echo "\n recevied done \n";
  }else{
  echo "\n not done \n";
   }

Body:
<?php
$username = "your_username";
$password = "your_pass";
$url      = 'your_stp_server_url';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');
$localDir  = '/path/to/your/local/dir';
$remoteDir = '/path/to/your/remote/dir';
// download all the files
$files    = scandir('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
      ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
    }
  }
}
?>

This is from server to computer but you can modify the $localDir


问:
why selected cell in collection view doesn't show correctly in the UICollection View Swift 3?
I am using swift 3 and I have collection view in my app that shows iPhone gallery in that . every things are good But I want the user could select some photos and this can be happen But the problem is that I used another small image in every cells that when the user select that cell the picture will showing a tick that user could understand that cell has been selected - this will work at the beginning but when the user scroll the collection view some cells that user didn't select them has this tick too!
**Remember that select and did deselect are working well and the problem is just for showing this tick **
**I have image with tag in cell and that image will showing a tick or nothing when the user select the cell or didDeselect that **

I know that these codes are more than you think But many some Guys need to access all of the codes so you can see my codes below

```<code> import UIKit
 import Photos
 class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
let arr_img = NSMutableArray()

@IBOutlet var collview: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    let allPhotosOptions : PHFetchOptions = PHFetchOptions.init()
    allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
    let allPhotosResult = PHAsset.fetchAssets(with: .image, options: allPhotosOptions)
    allPhotosResult.enumerateObjects({ (asset, idx, stop) in

        self.arr_img.add(asset)
    })

}
func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {
    let retinaScale = UIScreen.main.scale
    let retinaSquare = CGSize(width: size * retinaScale, height: size * retinaScale)//CGSizeMake(size * retinaScale, size * retinaScale)
    let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)
    let square = CGRect(x: 0, y: 0, width: cropSizeLength, height: cropSizeLength)//CGRectMake(0, 0, CGFloat(cropSizeLength), CGFloat(cropSizeLength))
    let cropRect = square.applying(CGAffineTransform(scaleX: 1.0/CGFloat(asset.pixelWidth), y: 1.0/CGFloat(asset.pixelHeight)))

    let manager = PHImageManager.default()
    let options = PHImageRequestOptions()
    var thumbnail = UIImage()

    options.isSynchronous = true
    options.deliveryMode = .highQualityFormat
    options.resizeMode = .exact
    options.normalizedCropRect = cropRect

    manager.requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in
        thumbnail = result!
    })
    return thumbnail
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK:
//MARK: Collectioview methods
func collectionView(_ collectionView: UICollectionView,
                    numberOfItemsInSection section: Int) -> Int {
    return arr_img.count
}
func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
                                                  for: indexPath)
    let imgview : UIImageView = cell.viewWithTag(20) as! UIImageView
    imgview.image = self.getAssetThumbnail(asset: self.arr_img.object(at: indexPath.row) as! PHAsset, size: 150)

    return cell
}

}

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
 let cell = collectionView.cellForItem(at: indexPath as IndexPath)
    if cell!.isSelected == true {

        print(indexPath)
        cell?.backgroundColor = UIColor.orange
        print("Cell is Selected!")
        let selectView : UIImageView = cell?.viewWithTag(22) as! UIImageView
        selectView.image = UIImage(named: "Select.png")
    }

    else if cell!.isSelected != true        {

        collectionView.cellForItem(at: indexPath as IndexPath)

    cell?.backgroundColor = UIColor.clear
        let selectView : UIImageView = cell?.viewWithTag(22) as! UIImageView
        selectView.image = nil

        print("Cell is  Not Selected!")

    }

}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath as IndexPath)

    print(indexPath)
    if cell?.isSelected == true {
        cell?.backgroundColor = UIColor.orange
        print("Cell is Selected In Deselect!")
        let selectView : UIImageView = cell!.viewWithTag(22) as! UIImageView
        selectView.image = nil
        collectionView.cellForItem(at: indexPath as IndexPath)

    }
    else if cell?.isSelected != true        {
        cell?.backgroundColor = UIColor.clear
        collectionView.cellForItem(at: indexPath as IndexPath)

        print("Cell is DeSelected!")
        let selectView : UIImageView = cell!.viewWithTag(22) as! UIImageView
        selectView.image = nil

    }

}
</code>```

答:
Just take a button inside your cell and give tag to it.

Take array and do following.

```<code>let arr_selected = NSMutableArray()
</code>```

```<code>func collectionView(_ collectionView: UICollectionView,
                        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
                                                      for: indexPath)

        let btn_check : UIButton = cell.viewWithTag(30) as! UIButton
        if arr_selected.contains(indexPath.row){
            btn_check.isSelected = true
        }else{
            btn_check.isSelected = false
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        if arr_selected.contains(indexPath.row){
            arr_selected.remove(indexPath.row)
        }else{
            arr_selected.add(indexPath.row)
        }
        self.collview.reloadData()
    }
</code>```

if you want demo, then you can download from HERE

Body:
I am using swift 3 and I have collection view in my app that shows iPhone gallery in that . every things are good But I want the user could select some photos and this can be happen But the problem is that I used another small image in every cells that when the user select that cell the picture will showing a tick that user could understand that cell has been selected - this will work at the beginning but when the user scroll the collection view some cells that user didn't select them has this tick too!
**Remember that select and did deselect are working well and the problem is just for showing this tick **
**I have image with tag in cell and that image will showing a tick or nothing when the user select the cell or didDeselect that **

I know that these codes are more than you think But many some Guys need to access all of the codes so you can see my codes below

 import UIKit
 import Photos
 class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
let arr_img = NSMutableArray()

@IBOutlet var collview: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()
    let allPhotosOptions : PHFetchOptions = PHFetchOptions.init()
    allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
    let allPhotosResult = PHAsset.fetchAssets(with: .image, options: allPhotosOptions)
    allPhotosResult.enumerateObjects({ (asset, idx, stop) in

        self.arr_img.add(asset)
    })

}
func getAssetThumbnail(asset: PHAsset, size: CGFloat) -> UIImage {
    let retinaScale = UIScreen.main.scale
    let retinaSquare = CGSize(width: size * retinaScale, height: size * retinaScale)//CGSizeMake(size * retinaScale, size * retinaScale)
    let cropSizeLength = min(asset.pixelWidth, asset.pixelHeight)
    let square = CGRect(x: 0, y: 0, width: cropSizeLength, height: cropSizeLength)//CGRectMake(0, 0, CGFloat(cropSizeLength), CGFloat(cropSizeLength))
    let cropRect = square.applying(CGAffineTransform(scaleX: 1.0/CGFloat(asset.pixelWidth), y: 1.0/CGFloat(asset.pixelHeight)))

    let manager = PHImageManager.default()
    let options = PHImageRequestOptions()
    var thumbnail = UIImage()

    options.isSynchronous = true
    options.deliveryMode = .highQualityFormat
    options.resizeMode = .exact
    options.normalizedCropRect = cropRect

    manager.requestImage(for: asset, targetSize: retinaSquare, contentMode: .aspectFit, options: options, resultHandler: {(result, info)->Void in
        thumbnail = result!
    })
    return thumbnail
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK:
//MARK: Collectioview methods
func collectionView(_ collectionView: UICollectionView,
                    numberOfItemsInSection section: Int) -> Int {
    return arr_img.count
}
func collectionView(_ collectionView: UICollectionView,
                    cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
                                                  for: indexPath)
    let imgview : UIImageView = cell.viewWithTag(20) as! UIImageView
    imgview.image = self.getAssetThumbnail(asset: self.arr_img.object(at: indexPath.row) as! PHAsset, size: 150)

    return cell
}

}

 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
 let cell = collectionView.cellForItem(at: indexPath as IndexPath)
    if cell!.isSelected == true {

        print(indexPath)
        cell?.backgroundColor = UIColor.orange
        print("Cell is Selected!")
        let selectView : UIImageView = cell?.viewWithTag(22) as! UIImageView
        selectView.image = UIImage(named: "Select.png")
    }

    else if cell!.isSelected != true        {

        collectionView.cellForItem(at: indexPath as IndexPath)

    cell?.backgroundColor = UIColor.clear
        let selectView : UIImageView = cell?.viewWithTag(22) as! UIImageView
        selectView.image = nil

        print("Cell is  Not Selected!")

    }

}

func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItem(at: indexPath as IndexPath)

    print(indexPath)
    if cell?.isSelected == true {
        cell?.backgroundColor = UIColor.orange
        print("Cell is Selected In Deselect!")
        let selectView : UIImageView = cell!.viewWithTag(22) as! UIImageView
        selectView.image = nil
        collectionView.cellForItem(at: indexPath as IndexPath)

    }
    else if cell?.isSelected != true        {
        cell?.backgroundColor = UIColor.clear
        collectionView.cellForItem(at: indexPath as IndexPath)

        print("Cell is DeSelected!")
        let selectView : UIImageView = cell!.viewWithTag(22) as! UIImageView
        selectView.image = nil

    }

}

Body:
Just take a button inside your cell and give tag to it.

Take array and do following.

let arr_selected = NSMutableArray()

func collectionView(_ collectionView: UICollectionView,
                        cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell",
                                                      for: indexPath)

        let btn_check : UIButton = cell.viewWithTag(30) as! UIButton
        if arr_selected.contains(indexPath.row){
            btn_check.isSelected = true
        }else{
            btn_check.isSelected = false
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        if arr_selected.contains(indexPath.row){
            arr_selected.remove(indexPath.row)
        }else{
            arr_selected.add(indexPath.row)
        }
        self.collview.reloadData()
    }

if you want demo, then you can download from HERE


问:
iphone - stuff inside alertview
I have a part on my app that I show the users, the files they have created and have stored inside the app's directory. I want to allow the users to rename the files.

I am wondering of doing this:

The user selects a file

The user taps on the RENAME button.

An alertview pops showing the old name and having a textview where the user can type the new name.

My question is: is this blessed by Apple? This sounds like a hack to the alertview.

Will the app be approved?

I googled around and I saw mixed opinions about that.

thanks

答:
Generally I think the correct HIG-happy UI would be a UITableView with the list of of files. The user taps and Edit button and the page rows become editable, allowing you to delete a row/file (with a verification alert) and a disclosure arrow that pushes a detail view where you can change the name.

An alternative, though not HIG-friendly, is displaying the file name in a UITextField where the borderStyle set to UITextBorderStyleNone and the enabled set to NO. When the user taps the Rename button you change the borderStyle to UITextBorderStyleRoundedRect and enabled set to YES, setting the firstResponder to the text field so the cursor is flashing inside the textField. You'd need OK and Cancel buttons.

Or you could add a text field to the UIAlertView, also against the HIG but perhaps better.

Title: iphone - stuff inside alertview


问:
Django not finding some JS and CSS resources
Perhaps this is a laughable problem but am really lost. It was working fine until I ported the project to a new laptop. Here is my filesystem structure:

```<code>bill
   ==>bill (contains settings.py)
   ==>static
   ==>welcome
   ==>manage.py
</code>```

Now in static i have my directory, i have folder plugins, js and css. The following are in my base.html template:

```<code> <!DOCTYPE html>
 {% load staticfiles %}
 <html lang="en">
 <head>
  <title>{% block ownername %}{% endblock %} {% block title %}{% endblock  %}</title>

<script src="{% static 'plugins/jQuery/jquery-2.2.3.min.js' %}"></script>

 <!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
 <link rel="stylesheet" href="{% static 'plugins/datepicker/datepicker3.css' %}">

**<link rel="stylesheet" href="{% static 'plugins/lobibox/lobibox.min.css' %}">**

 <script src="{% static 'plugins/slimScroll/jquery.slimscroll.min.js' %}"></script>

**<script src="{% static 'plugins/moments/moment.min.js' %}"></script>**
</code>```

It loads some resources while it gives 404 for some other resources that are there and working in my old laptop (the bold ones such as moment.min.js and css files). The configuration is the same since I used virtual environment to start it.

What am I missing please? I am really lost on what it is doing.

答:
No question is laughable :)

To begin with, change {% load staticfiles %} to {% load static %}.

Then make sure you've got the correct settings in terms of static files. A good setup would look like this:

```<code>STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'
</code>```

If you are running your app without DEBUG=True, then also run python manage.py collectstatic --no-input from your terminal - that should do the trick to serve static assets in prod environment.

Try it and let us know how it went.

Body:
Perhaps this is a laughable problem but am really lost. It was working fine until I ported the project to a new laptop. Here is my filesystem structure:

bill
   ==>bill (contains settings.py)
   ==>static
   ==>welcome
   ==>manage.py

Now in static i have my directory, i have folder plugins, js and css. The following are in my base.html template:

 <!DOCTYPE html>
 {% load staticfiles %}

  <title>{% block ownername %}{% endblock %} {% block title %}{% endblock  %}</title>

<link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}">
 <link rel="stylesheet" href="{% static 'plugins/datepicker/datepicker3.css' %}">

**<link rel="stylesheet" href="{% static 'plugins/lobibox/lobibox.min.css' %}">**

****

It loads some resources while it gives 404 for some other resources that are there and working in my old laptop (the bold ones such as moment.min.js and css files). The configuration is the same since I used virtual environment to start it.

What am I missing please? I am really lost on what it is doing.

Body:
No question is laughable :)

To begin with, change {% load staticfiles %} to {% load static %}.

Then make sure you've got the correct settings in terms of static files. A good setup would look like this:

STATIC_ROOT = os.path.join(BASE_DIR, "static")
STATIC_URL = '/static/'

If you are running your app without DEBUG=True, then also run python manage.py collectstatic --no-input from your terminal - that should do the trick to serve static assets in prod environment.

Try it and let us know how it went.


问:
Maybe bails out of fold
Why does computing the following expression terminate?

```<code>foldr (\x t -> if x > 5 then Just x else t) Nothing $ [1..]
</code>```

Is there anything special about Maybe (or one of the type classes it implements) that causes evaluation to stop after the lambda returns a Just?

答:
Maybe ,Just, and Nothing play no active role here. What we see is just laziness at work. Indeed, for any (total) function f and value a, this would also terminate:

```<code>foldr (\x t -> if x > 5 then f x else t) a $ [1..]
</code>```

This is perfectly equivalent to the plain recursion

```<code>foo [] = a
foo (x:xs) = if x > 5 then f x else foo xs
</code>```

when called as foo [1..]. Eventually, x becomes 6, f 6 is returned, and no more recursive calls are made.

Title: Maybe bails out of fold

Body:
Why does computing the following expression terminate?

foldr (\x t -> if x > 5 then Just x else t) Nothing $ [1..]

Is there anything special about Maybe (or one of the type classes it implements) that causes evaluation to stop after the lambda returns a Just?

Body:
Maybe ,Just, and Nothing play no active role here. What we see is just laziness at work. Indeed, for any (total) function f and value a, this would also terminate:

foldr (\x t -> if x > 5 then f x else t) a $ [1..]

This is perfectly equivalent to the plain recursion

foo [] = a
foo (x:xs) = if x > 5 then f x else foo xs

when called as foo [1..]. Eventually, x becomes 6, f 6 is returned, and no more recursive calls are made.


问:
Back navigation button not showing up
I cloned the code using

ionic start myProjectName tutorial

and changed the project according to ionic 3 , now , there is a file list.html , it has a button at header which opens side menu. i wanted to have a back button over there ,and removed the code for side menu opening. Expected that back button would automatically show up , but it did not happen, instead it shows header without any button with just title written.

in this project , you will find list.html , and i have altered it as follows:

```<code>  <ion-header>
  <ion-navbar>
    <ion-title>My First List</ion-title>
  </ion-navbar>
</ion-header>
<ion-content>
  <ion-list>
    <button ion-item *ngFor="let item of items" (click)="itemTapped($event, item)">
      <ion-icon name="{{item.icon}}" item-left></ion-icon>
      {{item.title}}
      <div class="item-note" item-right>
        {{item.note}}
      </div>
    </button>
  </ion-list>
</ion-content>
</code>```

It just have a title , no back navigation button which could take me to root page

答:
Here some code for header in ionic.

```<code><ion-view>
<ion-nav-bar>
    <ion-nav-buttons side="left">
        <button class="button button-clear  ion-arrow-left-c  " ng-click="backButton()"></button>
    </ion-nav-buttons>
    <ion-nav-buttons side="right">
        <button class="button button-clear btn-white ion-android-settings header-icon-size " ng-click="openDrawer()"></button>
    </ion-nav-buttons>
</ion-nav-bar>
<ion-content>
    <!-- here content -->
</ion-content>
</ion-view>
</code>```

Let me know if it works for you ??

Title: Back navigation button not showing up

Body:
I cloned the code using

ionic start myProjectName tutorial

and changed the project according to ionic 3 , now , there is a file list.html , it has a button at header which opens side menu. i wanted to have a back button over there ,and removed the code for side menu opening. Expected that back button would automatically show up , but it did not happen, instead it shows header without any button with just title written.

in this project , you will find list.html , and i have altered it as follows:

  <ion-header>
  <ion-navbar>
    <ion-title>My First List</ion-title>
  </ion-navbar>
</ion-header>
<ion-content>
  <ion-list>
    <button ion-item *ngFor="let item of items" (click)="itemTapped($event, item)">
      <ion-icon name="{{item.icon}}" item-left></ion-icon>
      {{item.title}}

        {{item.note}}

    </button>
  </ion-list>
</ion-content>

It just have a title , no back navigation button which could take me to root page

Body:
Here some code for header in ionic.

<ion-view>
<ion-nav-bar>
    <ion-nav-buttons side="left">
        <button class="button button-clear  ion-arrow-left-c  " ng-click="backButton()"></button>
    </ion-nav-buttons>
    <ion-nav-buttons side="right">
        <button class="button button-clear btn-white ion-android-settings header-icon-size " ng-click="openDrawer()"></button>
    </ion-nav-buttons>
</ion-nav-bar>
<ion-content>
    <!-- here content -->
</ion-content>
</ion-view>

Let me know if it works for you ??


问:
Python: Regex help
```<code>str = "a\b\c\dsdf\matchthis\erwe.txt"
</code>```

The last folder name.

Match "matchthis"

答:
Without using regex, just do:</p>

```<code>>>> import os
>>> my_str = "a/b/c/dsdf/matchthis/erwe.txt"
>>> my_dir_path = os.path.dirname(my_str)
>>> my_dir_path
'a/b/c/dsdf/matchthis'
>>> my_dir_name = os.path.basename(my_dir_path)
>>> my_dir_name
'matchthis'
</code>```

Title: Python: Regex help

Body:
str = "a\b\c\dsdf\matchthis\erwe.txt"

The last folder name.

Match "matchthis"

Body:
Without using regex, just do:

>>> import os
>>> my_str = "a/b/c/dsdf/matchthis/erwe.txt"
>>> my_dir_path = os.path.dirname(my_str)
>>> my_dir_path
'a/b/c/dsdf/matchthis'
>>> my_dir_name = os.path.basename(my_dir_path)
>>> my_dir_name
'matchthis'


问:
use Inner Join in SQL
I want to join two tables and then I want to join this result with another table
but it doesn't work

```<code>select * from
        (
            (select SeId,FLName,Company from Sellers) s
                inner join
            (select SeId,BIId from BuyInvoices) b
                on s.SeId=b.SeId
            ) Y
            inner join
         (select * from BuyPayments) X
            on Y.BIId=X.BIId
</code>```

thanks

答:
In most databases, your syntax isn't going to work.  Although parentheses are allowed in the FROM clause, they don't get their own table aliases.

You can simplify the JOIN.  This is a simpler way to write the logic:

```<code>select s.SeId, s.FLName, s.Company, bp.*
from Sellers s inner join
     BuyInvoices b
     on s.SeId = b.SeId inner join
     BuyPayments bp
     on bp.BIId = b.BIId;
</code>```

Title: use Inner Join in SQL

Body:
I want to join two tables and then I want to join this result with another table
but it doesn't work

select * from
        (
            (select SeId,FLName,Company from Sellers) s
                inner join
            (select SeId,BIId from BuyInvoices) b
                on s.SeId=b.SeId
            ) Y
            inner join
         (select * from BuyPayments) X
            on Y.BIId=X.BIId

thanks

Body:
In most databases, your syntax isn't going to work.  Although parentheses are allowed in the FROM clause, they don't get their own table aliases.

You can simplify the JOIN.  This is a simpler way to write the logic:

select s.SeId, s.FLName, s.Company, bp.*
from Sellers s inner join
     BuyInvoices b
     on s.SeId = b.SeId inner join
     BuyPayments bp
     on bp.BIId = b.BIId;


问:
let keyword in the for loop
ECMAScript 6's let is supposed to provide block scope without hoisting headaches. Can some explain why in the code below i in the function resolves to the last value from the loop (just like with var) instead of the value from the current iteration?

```<code>"use strict";
var things = {};
for (let i = 0; i < 3; i++) {
    things["fun" + i] = function() {
        console.log(i);
    };
}

things["fun0"](); // prints 3
things["fun1"](); // prints 3
things["fun2"](); // prints 3
</code>```

According to MDN using let in the for loop like that should bind the variable in the scope of the loop's body. Things work as I'd expect them when I use a temporary variable inside the block. Why is that necessary?

```<code>"use strict";
var things = {};
for (let i = 0; i < 3; i++) {
    let index = i;
    things["fun" + i] = function() {
        console.log(index);
    };
}

things["fun0"](); // prints 0
things["fun1"](); // prints 1
things["fun2"](); // prints 2
</code>```

I tested the script with Traceur and node --harmony.

答:
I passed this code through Babel so we can understand the behaviour in terms of familiar ES5:

```<code>for (let i = 0; i < 3; i++) {
    i++;
    things["fun" + i] = function() {
        console.log(i);
    };
    i--;
}
</code>```

Here is the code transpiled to ES5:

```<code>var _loop = function _loop(_i) {
    _i++;
    things["fun" + _i] = function () {
        console.log(_i);
    };
    _i--;
    i = _i;
};

for (var i = 0; i < 3; i++) {
    _loop(i);
}
</code>```

We can see that two variables are used.

In the outer scope i is the variable that changes as we iterate.

In the inner scope _i is a unique variable for each iteration. There will eventually be three separate instances of _i.

Each callback function can see its corresponding _i, and could even manipulate it if it wanted to, independently of the _is in other scopes.

(You can confirm that there are three different _is by doing console.log(i++) inside the callback. Changing _i in an earlier callback does not affect the output from later callbacks.)

At the end of each iteration, the value of _i is copied into i.  Therefore changing the unique inner variable during the iteration will affect the outer iterated variable.

It is good to see that ES6 has continued the long-standing tradition of WTFJS.

Title: let keyword in the for loop

Body:
ECMAScript 6's let is supposed to provide block scope without hoisting headaches. Can some explain why in the code below i in the function resolves to the last value from the loop (just like with var) instead of the value from the current iteration?

"use strict";
var things = {};
for (let i = 0; i < 3; i++) {
    things["fun" + i] = function() {
        console.log(i);
    };
}

things["fun0"](); // prints 3
things["fun1"](); // prints 3
things["fun2"](); // prints 3

According to MDN using let in the for loop like that should bind the variable in the scope of the loop's body. Things work as I'd expect them when I use a temporary variable inside the block. Why is that necessary?

"use strict";
var things = {};
for (let i = 0; i < 3; i++) {
    let index = i;
    things["fun" + i] = function() {
        console.log(index);
    };
}

things["fun0"](); // prints 0
things["fun1"](); // prints 1
things["fun2"](); // prints 2

I tested the script with Traceur and node --harmony.

Body:
I passed this code through Babel so we can understand the behaviour in terms of familiar ES5:

for (let i = 0; i < 3; i++) {
    i++;
    things["fun" + i] = function() {
        console.log(i);
    };
    i--;
}

Here is the code transpiled to ES5:

var _loop = function _loop(_i) {
    _i++;
    things["fun" + _i] = function () {
        console.log(_i);
    };
    _i--;
    i = _i;
};

for (var i = 0; i < 3; i++) {
    _loop(i);
}

We can see that two variables are used.

In the outer scope i is the variable that changes as we iterate.

In the inner scope _i is a unique variable for each iteration. There will eventually be three separate instances of _i.

Each callback function can see its corresponding _i, and could even manipulate it if it wanted to, independently of the _is in other scopes.

(You can confirm that there are three different _is by doing console.log(i++) inside the callback. Changing _i in an earlier callback does not affect the output from later callbacks.)

At the end of each iteration, the value of _i is copied into i.  Therefore changing the unique inner variable during the iteration will affect the outer iterated variable.

It is good to see that ES6 has continued the long-standing tradition of WTFJS.


问:
Will long-lasting readOnly transaction slow down other request?
For example, I want to iterate over 5000k rows via without holder cursor inside a readOnly transaction, it will definitely run for a long period.

Will such kind transaction slow down other requests on the same table ?

答:
No, it won't, unless concurrent transaction require an ACCESS EXCLUSIVE lock on the table (they are running something like DROP TABLE, ALTER TABLE or CREATE INDEX). Such transactons would hang until the read-only transaction is done.

The problem with long transactions is that they keep autovacuum from doing its work, and if there is a lot of concurrent data modifying activity, you could end up with bloated tables and indexes.


问:
how to work delete query in wordpress 4.7
Im trying to work delete query in wordpress.
im list all values from table(test)and create delete link to all view values.id;?>">Delete

and Im create anew page delete.php.
Code is :
<?php global $wpdb;
$id=$_POST['id'];
$r=$wpdb->query($wpdb->prepare("DELETE FROM test WHERE id=$id"));?>

after running page not found error message is display??

答:
if you have created a template file called delete and assign that template to one of the wp pages. then in the href you should pass:

```<code><a href="<?php echo get_permalink(get_page_by_title('your wp page  name'));?>?id=<?php echo $user->id;?>">Delete</a>"
</code>```

and use GET insted of POST.

Body:
Im trying to work delete query in wordpress.
im list all values from table(test)and create delete link to all view values.<a href="http://localhost/wordpress/delete?id=<?php echo $user->id;?>">Delete

and Im create anew page delete.php.
Code is :
<?php global $wpdb;
$id=$_POST['id'];
$r=$wpdb->query($wpdb->prepare("DELETE FROM test WHERE id=$id"));?>

after running page not found error message is display??

Body:
if you have created a template file called delete and assign that template to one of the wp pages. then in the href you should pass:

<a href="<?php echo get_permalink(get_page_by_title('your wp page  name'));?>?id=<?php echo $user->id;?>">Delete</a>"

and use GET insted of POST.


问:
PHP - Do (and echo) operation only when remainder from is 0 - Going into infinite loop
Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!

I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.

First I generate the random numbers, easy:

```<code>$x = mt_rand(1,10);
$y = mt_rand(1,10);
</code>```

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

```<code><?php

function hello(){
      echo "Hello!";
}

hello();
?>
</code>```

Why not up the ante as I said before and use it, so I mix the up:

```<code><?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);

function foo(){

if($x % $y == 0){

echo $x . "/" . $y;

}else{

foo();

}

}

?>
</code>```

It doesn't work, I get a blank screen.

What was I expecting from this script:

Create a function with an if() statement on it

If the remainder is 0, great, echo.

else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?

To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!

Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)

答:
Paxdiablo is on the right track but this is what you probably want:

```<code><?php
    function foo() {
        do
        {
            $x = mt_rand(1,10);
            $y = mt_rand(1,10);
        }
        while ($x % $y != 0);

        echo $x . "/" . $y;
    }
?>
</code>```

This will loop executing the code inside the do { } while until the while condition to false. The difference between a while and a do while is that the code is executed before the condition is checked.

Body:
Let me start by the end and the actual question:

I'm trying to write a PHP script that from two random numbers $x and $y will only we outputted and resolved when modulo == 0 (it should always echo a valid function)

What do I mean:

The script echos:

4 / 2 => GOOD!

The script echos:

4 / 3 => BAD!

NOTHING => BAD!

I'll try to guide you through my reasoning but be warned:

I'm a newbie so: I learn something, up the ante, and try to apply it conveniently.

First I generate the random numbers, easy:

$x = mt_rand(1,10);
$y = mt_rand(1,10);

Now I say, I have two possibilities after division, remainder 0 or not 0, so an if() statement looks like a good idea, so I do:

if($x % $y == 0){

echo $x . "/" . $y;

}else{

echo "The remainder is not 0";

}

This works as expected except of course, I always want to generate this remainder is not 0 divisions.

So my approach was the following, why not use user generated functions (never used the before but could come in handy) so, if I know this works just fine:

<?php

function hello(){
      echo "Hello!";
}

hello();
?>

Why not up the ante as I said before and use it, so I mix the up:

<?php
$x = mt_rand(1,10);
$y = mt_rand(1,10);

function foo(){

if($x % $y == 0){

echo $x . "/" . $y;

}else{

foo();

}

}

?>

It doesn't work, I get a blank screen.

What was I expecting from this script:

Create a function with an if() statement on it

If the remainder is 0, great, echo.

else, start all over, again and again, till you get a division with no remainder.

This does't work.

So I basically ask, what I am doing wrong? What is wrong with the line of though behind this?

Can this work with a subtle change?

To experienced coders, I know you could all make a script that does this (but has nothing to do with mine) using MS PAINT as an IDE, BUT:

I have no interest in the code itself since this is ONLY for learning purposes.

This is not the first time it has happened to me, I keep hitting the wall with infinite loops VERY often, so the slighter the change (and the bigger the explanation) the better, and will be very much appreciated.

Thanks in advance!

Now that finish I've just realized the problem might not even be a infinite loop, even if it's not the question still stands, what do you think think of my approach? (of course I will also edit and remove the infinite loop from the question)

Body:
Paxdiablo is on the right track but this is what you probably want:

<?php
    function foo() {
        do
        {
            $x = mt_rand(1,10);
            $y = mt_rand(1,10);
        }
        while ($x % $y != 0);

        echo $x . "/" . $y;
    }
?>

This will loop executing the code inside the do { } while until the while condition to false. The difference between a while and a do while is that the code is executed before the condition is checked.


问:
Horizontal UIScrollView using auto layout
I have been trying this for quite sometime now and went through a lot of posts on SO and some video tutorials. What I want to create is a horizontal scroll view with some buttons in it, like this:

My view hierarchy is as follows:

View Controller

View

Scroll View

View

Buttons

I have set top, leading, trailing, bottom constraints to the scroll view. I have set it's width equal to it's superview, and have set it's height to 200. So far so good, for the view inside the scroll view, I have set it's constraints leading, trailing, top and bottom to zero with respect to it's superview i.e. scroll view. I have made it's width equals to the View controllers view, since that was the solution here on SO to the ambiguous width issue. It solved the issue. Now I added all the buttons and set up their constraints to their parent view. Now when I run the app, a screen like the above added screenshot appears, however I cant scroll to the last element.Any help is greatly appretiated.

答:
```<code>@IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var btnBack: UIButton!
    @IBOutlet weak var btnForward: UIButton!

let headerView = UIView()
        headerView.backgroundColor = UIColor.white

        for i in 0..<selectedRestaurant.multipleImages.count {
            let url = selectedRestaurant.multipleImages[i]

            let imgView = UIImageView()
            imgView.frame = CGRect(x: CGFloat(i) * self.view.frame.size.width, y: 0, width: self.view.frame.size.width, height: scrollView.frame.size.height)

            let task = URLSession.shared.dataTask(with: URL(string: url as! String)!, completionHandler: { (data, response, error) in

                if error == nil {
                    if data != nil {
                        imgView.contentMode = UIViewContentMode.scaleAspectFill
                        imgView.image = UIImage(data: data!)
                    }
                }

        })
                scrollView.addSubview(imgView)
scrollView.contentSize = CGSize(width: self.view.frame.size.width * CGFloat(selectedRestaurant.multipleImages.count), height: scrollView.frame.size.height)
</code>```

write code in btn back clicked <<<<

```<code>let index = Int(scrollView.contentOffset.x/self.view.frame.size.width) - 1
        print("\(index)")
        if index >= 0 {
            scrollView.setContentOffset(CGPoint(x: CGFloat(index) * self.view.frame.size.width, y: 0), animated: true)
        }
</code>```

write code in btn next clicked >>>>>

```<code>let index = Int(scrollView.contentOffset.x/self.view.frame.size.width) + 1
        print("\(index)")
        if index < (selectedRestaurant.multipleImages.count)  {
            scrollView.setContentOffset(CGPoint(x: CGFloat(index) * self.view.frame.size.width, y: 0), animated: true)
        }
</code>```

Body:
@IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var btnBack: UIButton!
    @IBOutlet weak var btnForward: UIButton!

let headerView = UIView()
        headerView.backgroundColor = UIColor.white

        for i in 0..<selectedRestaurant.multipleImages.count {
            let url = selectedRestaurant.multipleImages[i]

            let imgView = UIImageView()
            imgView.frame = CGRect(x: CGFloat(i) * self.view.frame.size.width, y: 0, width: self.view.frame.size.width, height: scrollView.frame.size.height)

            let task = URLSession.shared.dataTask(with: URL(string: url as! String)!, completionHandler: { (data, response, error) in

                if error == nil {
                    if data != nil {
                        imgView.contentMode = UIViewContentMode.scaleAspectFill
                        imgView.image = UIImage(data: data!)
                    }
                }

        })
                scrollView.addSubview(imgView)
scrollView.contentSize = CGSize(width: self.view.frame.size.width * CGFloat(selectedRestaurant.multipleImages.count), height: scrollView.frame.size.height)

write code in btn back clicked <<<<

let index = Int(scrollView.contentOffset.x/self.view.frame.size.width) - 1
        print("\(index)")
        if index >= 0 {
            scrollView.setContentOffset(CGPoint(x: CGFloat(index) * self.view.frame.size.width, y: 0), animated: true)
        }

write code in btn next clicked >>>>>

let index = Int(scrollView.contentOffset.x/self.view.frame.size.width) + 1
        print("\(index)")
        if index < (selectedRestaurant.multipleImages.count)  {
            scrollView.setContentOffset(CGPoint(x: CGFloat(index) * self.view.frame.size.width, y: 0), animated: true)
        }


问:
RxJs Observable<string> vs Observable<string[]>
I'm having a hard time getting my head around RxJS Observables, though I've used the observable pattern in a number of different situations throughout my life. Here's some code:

```<code>    const observable: Observable<Response> = createdElswhere();
    let test1: Observable<string>;
    let test2: Observable<string[]>;

    test1 = observable.map(r => r.json());
    test2 = observable.map(r => r.json());
</code>```

Response.json() returns an array of data - usually objects that will be mapped to a typescript object, but they're just strings in this case:

```<code>[
    "test1",
    "test2",
    "test3",
    "test4"
]
</code>```

When I subscribe to the test1 or test2 properties (in an angular view template, or manually in code using .subscribe() for example), the observable generic type doesn't seem to make any difference to the framework. The items are displayed exactly the same, even though the 'data' inside the observable is different (one is an array, the other is an array of observable strings).

Can anyone explain the difference between Observable<string> and Observable<string[]>, and give me an example of how they should be used?

答:
Observable<string>
meansthat you are creating a observer for type string

Observable<string[]>
means that you are creating a observer for array of string

since you are coding in typescript it just a typecheck which helps your compiler when you will wrongly try to assign the variable. since type script are compiled to javascript which doesnt have type check so it dosent matter what you assign the value with

eg:
**In typescript **

let k:int;

k=r.json().val;

In javascript compiled code is equal to

var k;

k=r.json().val;

so if r.json().val return int then k will become int and k is string it will become string

Body:
I'm having a hard time getting my head around RxJS Observables, though I've used the observable pattern in a number of different situations throughout my life. Here's some code:

    const observable: Observable<Response> = createdElswhere();
    let test1: Observable<string>;
    let test2: Observable<string[]>;

    test1 = observable.map(r => r.json());
    test2 = observable.map(r => r.json());

Response.json() returns an array of data - usually objects that will be mapped to a typescript object, but they're just strings in this case:

[
    "test1",
    "test2",
    "test3",
    "test4"
]

When I subscribe to the test1 or test2 properties (in an angular view template, or manually in code using .subscribe() for example), the observable generic type doesn't seem to make any difference to the framework. The items are displayed exactly the same, even though the 'data' inside the observable is different (one is an array, the other is an array of observable strings).

Can anyone explain the difference between Observable<string> and Observable<string[]>, and give me an example of how they should be used?


问:
Error when trying to RSA-decrypt a parameter string with libcrypto
I am a beginner with the libcrypto library. I am trying to give an encrypted string to a function, decrypt it and return it decrypted. The string is encoded with my public key which which is 4096-bit sized.

```<code>char* decodeStr(const char* str, const size_t sizeStr)
{
    puts("Starting");
    FILE* file = fopen(PRIVATE_KEY_PATH, "r");
    if (file == NULL)
    {
        perror("Error while trying to access to Presto's private key.\n");
        return NULL;
    }

    RSA *privateKey = RSA_new();
    privateKey = PEM_read_RSAPrivateKey(file, &privateKey, NULL, NULL);
    if (privateKey == NULL)
    {
        fprintf(stderr, "Error loading RSA private key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    char* res = malloc(sizeStr);
    if (res == NULL)
    {
        perror("Memory allocating error ");
        return NULL;
    }
    const int sizeDecoded = RSA_private_decrypt(sizeStr, str, res, privateKey, RSA_PKCS1_PADDING);
    if (sizeDecoded == -1)
    {
        fprintf(stderr, "Error while decoding RSA-encoded wrapping key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    if ((res = realloc(res, (size_t)sizeDecoded)) == NULL)
    {
        perror("Memory allocating error ");
        return NULL;
    }
    return res;

}
</code>```

The following code outputs :

```<code>Starting
Error while decoding RSA-encoded wrapping key.
6928:error;04069506C:lib<4>:func<101>:reason<108>:.\crypto\rsa\rsa_eay.c:518:
</code>```

Since the error is unknown and I haven't been able to find any information about it on the net, and moreover I am a beginner with libcrypto, does strneed to be in a certain format ?

Obivously it is this which breaks the program but I can't be sure of it, neither do I know how to fix this.

```<code>const int sizeDecoded = RSA_private_decrypt(sizeStr, str, res, privateKey, RSA_PKCS1_PADDING);
</code>```

EDIT : I have been working with a client  which provides me those encoded dat for me to decrypt them. I don't know how they are processed exactly. Unfortunately, the encoded strings are even more sensitive than the private key itself, so I can't share it. It looks like 0c79cc00deb89a614db6ebe42be748219089fb5356 but with 1024 characters.

答:
I solved part of the issue. I added :

```<code>/* Load the human readable error strings for libcrypto */
    ERR_load_crypto_strings();
</code>```

At the beginning of the function. The output turned into :

```<code>Starting
Error while decoding RSA-encoded wrapping key.
1124:errir:0406506C:rsa routines: RSA_EAY_PRIVATE_DECRYPT:data greater than mod len:.\crypto\rsa\rsa_eay.c:518:
</code>```

Which I guess means that the length of the key is too small for the provided data. Still left to know if the data is wrong, the key is wrong and how to fix it.

Also, to avoid making such mistakes later, I added :

```<code>const size_t sizeRSA = RSA_size(prestoPrivateKey);
if (sizeRSA < sizeWrappingKey)
{
    fprintf(stderr, "Size of key : %d\n Size of data : %d\n The size of the key should higher than data length.\n", sizeRSA, sizeWrappingKey);
    return NULL;
}
</code>```

Body:
I am a beginner with the libcrypto library. I am trying to give an encrypted string to a function, decrypt it and return it decrypted. The string is encoded with my public key which which is 4096-bit sized.

char* decodeStr(const char* str, const size_t sizeStr)
{
    puts("Starting");
    FILE* file = fopen(PRIVATE_KEY_PATH, "r");
    if (file == NULL)
    {
        perror("Error while trying to access to Presto's private key.\n");
        return NULL;
    }

    RSA *privateKey = RSA_new();
    privateKey = PEM_read_RSAPrivateKey(file, &privateKey, NULL, NULL);
    if (privateKey == NULL)
    {
        fprintf(stderr, "Error loading RSA private key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    char* res = malloc(sizeStr);
    if (res == NULL)
    {
        perror("Memory allocating error ");
        return NULL;
    }
    const int sizeDecoded = RSA_private_decrypt(sizeStr, str, res, privateKey, RSA_PKCS1_PADDING);
    if (sizeDecoded == -1)
    {
        fprintf(stderr, "Error while decoding RSA-encoded wrapping key.\n");
        ERR_print_errors_fp(stderr);
        return NULL;
    }
    if ((res = realloc(res, (size_t)sizeDecoded)) == NULL)
    {
        perror("Memory allocating error ");
        return NULL;
    }
    return res;

}

The following code outputs :

Starting
Error while decoding RSA-encoded wrapping key.
6928:error;04069506C:lib<4>:func<101>:reason<108>:.\crypto\rsa\rsa_eay.c:518:

Since the error is unknown and I haven't been able to find any information about it on the net, and moreover I am a beginner with libcrypto, does strneed to be in a certain format ?

Obivously it is this which breaks the program but I can't be sure of it, neither do I know how to fix this.

const int sizeDecoded = RSA_private_decrypt(sizeStr, str, res, privateKey, RSA_PKCS1_PADDING);

EDIT : I have been working with a client  which provides me those encoded dat for me to decrypt them. I don't know how they are processed exactly. Unfortunately, the encoded strings are even more sensitive than the private key itself, so I can't share it. It looks like 0c79cc00deb89a614db6ebe42be748219089fb5356 but with 1024 characters.

Body:
I solved part of the issue. I added :

/* Load the human readable error strings for libcrypto */
    ERR_load_crypto_strings();

At the beginning of the function. The output turned into :

Starting
Error while decoding RSA-encoded wrapping key.
1124:errir:0406506C:rsa routines: RSA_EAY_PRIVATE_DECRYPT:data greater than mod len:.\crypto\rsa\rsa_eay.c:518:

Which I guess means that the length of the key is too small for the provided data. Still left to know if the data is wrong, the key is wrong and how to fix it.

Also, to avoid making such mistakes later, I added :

const size_t sizeRSA = RSA_size(prestoPrivateKey);
if (sizeRSA < sizeWrappingKey)
{
    fprintf(stderr, "Size of key : %d\n Size of data : %d\n The size of the key should higher than data length.\n", sizeRSA, sizeWrappingKey);
    return NULL;
}