答:
There is a function in laravel Auth::loginUsingId():

```<code>if(Auth::loginUsingId($userId))
{
    return redirect('/dashboard');
}
</code>```

by which user can login by using its id in user table only. In this there is no need to pass email, password etc

Title: Faking logins with Laravel Auth

Body:
On our service there's admins and other users. I'm using the basic Laravel Auth package for handling registrations, logins etc.

What would be the best way to implement a feature, where an admin user could "fake login" as a regular user, without knowing the actual user's password?

Body:
There is a function in laravel Auth::loginUsingId():

if(Auth::loginUsingId($userId))
{
    return redirect('/dashboard');
}

by which user can login by using its id in user table only. In this there is no need to pass email, password etc


来源: stackexchange

问:
Multiple LIKE matches with Arel & MetaWhere
I'm transitioning an application written in Rails-2.3 with SearchLogic to Rails-3.0 with Arel and MetaWhere, and I'm running into an operation that I don't know how the write.

The old code was:

```<code>if params[:city] && params[:city].respond_to?(:each)
  users = users.person_address_city_like_any(params[:city])
end
</code>```

what this did was run a LIKE match against each item in the params[:city] array.

This is easy enough in MetaWhere when there's only one search term:

```<code>users = users.where(:person => { :address => { :city.matches => '%city1%' } })
</code>```

but how would I write this with an arbitrary number of cities?

答:
Try:

users = users.where(:person => { :address => { :city.matches_any => ['%city1%','%city2%'] } })

ContentLicense: CC BY-SA 2.5

Body:
I'm transitioning an application written in Rails-2.3 with SearchLogic to Rails-3.0 with Arel and MetaWhere, and I'm running into an operation that I don't know how the write.

The old code was:

if params[:city] && params[:city].respond_to?(:each)
  users = users.person_address_city_like_any(params[:city])
end

what this did was run a LIKE match against each item in the params[:city] array.

This is easy enough in MetaWhere when there's only one search term:

users = users.where(:person => { :address => { :city.matches => '%city1%' } })

but how would I write this with an arbitrary number of cities?


问:
how to make controller detect link down or host down in the following topology
I am trying to detect the traffic going to host(server) that is down.So as to redirect it to a working server.I am planning to implement the redirection part in click(nfv)
I run the controller using the following command  ./pox.py openflow.discovery forwarding.l2_learning.
How to make controller detect the host down/link down.

答:
i am able to detect host down with the following code

```<code>from pox.core import core
import pox
import pox.lib.packet as pkt
from pox.lib.revent import *
from pox.openflow.discovery import Discovery
from pox.host_tracker import host_tracker
import pox.openflow.libopenflow_01 as of

class kj_host(EventMixin):
  def __init__ (self):
    def startup ():
      core.openflow.addListeners(self, priority=0)
      core.openflow_discovery.addListeners(self)
      core.host_tracker.addListeners(self)
      """ Here is the place where is created the listener"""
    core.call_when_ready(startup, ('openflow','openflow_discovery', 'host_tracker'))

  def _handle_HostEvent (self, event):
    """ Here is the place where is used the listener"""
    print "Host, switchport and switch...", event.entry

  def _handle_PacketIn(self, event):
    """ Packet processing """
def launch():
  from host_tracker import launch
  launch()
  core.registerNew(kj_host)
</code>```

I saved this code in kj_host.py and placed inside /home/pox/pox/misc and i run the controller with following command ./pox.py openflow.discovery forwarding.l2_learning misc.kj_host
Reference:
1)answer from github
2)stackoverflow answer

ContentLicense: CC BY-SA 3.0

Body:
i am able to detect host down with the following code

from pox.core import core
import pox
import pox.lib.packet as pkt
from pox.lib.revent import *
from pox.openflow.discovery import Discovery
from pox.host_tracker import host_tracker
import pox.openflow.libopenflow_01 as of

class kj_host(EventMixin):
  def __init__ (self):
    def startup ():
      core.openflow.addListeners(self, priority=0)
      core.openflow_discovery.addListeners(self)
      core.host_tracker.addListeners(self)
      """ Here is the place where is created the listener"""
    core.call_when_ready(startup, ('openflow','openflow_discovery', 'host_tracker'))

  def _handle_HostEvent (self, event):
    """ Here is the place where is used the listener"""
    print "Host, switchport and switch...", event.entry

  def _handle_PacketIn(self, event):
    """ Packet processing """
def launch():
  from host_tracker import launch
  launch()
  core.registerNew(kj_host)

I saved this code in kj_host.py and placed inside /home/pox/pox/misc and i run the controller with following command ./pox.py openflow.discovery forwarding.l2_learning misc.kj_host
Reference:
1)answer from github
2)stackoverflow answer


问:
Skips zero's, but display label value as Zero
Since I do not have 50 reputations, I was unable to ask my question on the same post here (Remove Duplicate and Count only one in a y:axis).

I am working on a similar project, everything on the post (Remove Duplicate and Count only one in a y:axis) looks good. The output is also perfect however, I need one extra thing added to the output.

The Present Input:

```<code>var list = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:1,label:'Computers'},
  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:1,label:'Math'},
]
</code>```

What I am already getting is:

```<code>[{y: 1, label: "Computers"}, {y: 2, label: "Math"}]
</code>```

This is perfect to me, this solution on the URL I mentioned, skips zero's, removes duplicates .. I need all of this, I do not need any change in these, however, if all the values of one subject are zero's then I want the output to display  a single output for zero. To make it clear below is my input and

New Input:
If all the values of 'Computers' are y: is Zero, then I want the output at least to inform me that it is all Zero.

```<code>var list = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'}, //here all the values are zero for computers

  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:1,label:'Math'},
]
</code>```

Present Output:

```<code>[{y: 2, label: "Math"}] //this is perfect but, with skip of zeros, I need an output like the below expected output
</code>```

Expected Output:

```<code>[{y: 0, label: "Computers"}, {y: 2, label: "Math"}]
</code>```

答:
My vanilla js answer is:

EDIT: Didn't notice that the question is 1 year old :D

var list = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:1,label:'Computers'},
  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:1,label:'Math'},
];

var out = [];

var filt = {};
for (var entry of list) {
  if (!filt[entry.label]) {
    filt[entry.label] = {y: 0, label: entry.label}
  }

  filt[entry.label].y += entry.y;
}

for (var key in filt) {
  out.push(filt[key]);
}

// out is the list you need

document.body.innerHTML = JSON.stringify(out);```

Body:
Since I do not have 50 reputations, I was unable to ask my question on the same post here (Remove Duplicate and Count only one in a y:axis).

I am working on a similar project, everything on the post (Remove Duplicate and Count only one in a y:axis) looks good. The output is also perfect however, I need one extra thing added to the output.

The Present Input:

var list = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:1,label:'Computers'},
  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:1,label:'Math'},
]

What I am already getting is:

[{y: 1, label: "Computers"}, {y: 2, label: "Math"}]

This is perfect to me, this solution on the URL I mentioned, skips zero's, removes duplicates .. I need all of this, I do not need any change in these, however, if all the values of one subject are zero's then I want the output to display  a single output for zero. To make it clear below is my input and

New Input:
If all the values of 'Computers' are y: is Zero, then I want the output at least to inform me that it is all Zero.

var list = [
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'},
  {y:0,label:'Computers'}, //here all the values are zero for computers

  {y:0,label:'Math'},
  {y:0,label:'Math'},
  {y:1,label:'Math'},
  {y:1,label:'Math'},
]

Present Output:

[{y: 2, label: "Math"}] //this is perfect but, with skip of zeros, I need an output like the below expected output

Expected Output:

[{y: 0, label: "Computers"}, {y: 2, label: "Math"}]


问:
jQuery hasClass Uncaught SyntaxError: Unexpected token )
I got this error in console log but can't determine what's wrong. I would like to hide an element when the button is collapsed </p>

```<code>$(".navbar-toggle").click(function() {
if(".navbar-toggle").hasClass("collapsed")
    $(".country-flags-container").hide();
else
    $(".country-flags-container").show();
)}
</code>```

<p>I appreciate your help for my learnings. </p>

答:
Try this one :

```<code>   $(".navbar-toggle").click(function() {
    if((".navbar-toggle").hasClass("collapsed")) // missing () for if statement
        $(".country-flags-container").hide();
    else
        $(".country-flags-container").show();
    });// this was the issue
</code>```

Good luck

Body:
I got this error in console log but can't determine what's wrong. I would like to hide an element when the button is collapsed

$(".navbar-toggle").click(function() {
if(".navbar-toggle").hasClass("collapsed")
    $(".country-flags-container").hide();
else
    $(".country-flags-container").show();
)}

I appreciate your help for my learnings.

Body:
Try this one :

   $(".navbar-toggle").click(function() {
    if((".navbar-toggle").hasClass("collapsed")) // missing () for if statement
        $(".country-flags-container").hide();
    else
        $(".country-flags-container").show();
    });// this was the issue

Good luck


问:
How to switch layouts in Angular2
What is the best practices way of using two entirely different layouts in the same Angular2 application? For example in my /login route I want to have a very simple box horizontally and vertically centered, for every other route I want my full template with header, content and footer.</p>

答:
In Angular 4 (and probably also in Angular 2) you can do:

```<code>const routes: Route[] = [
  {path: 'admin', redirectTo: 'admin/dashboard', pathMatch: 'full'},
  {
    path: 'admin',
    children: [
      {
        path: '', component: DefaultLayoutComponent,
        children: [
          {path: 'dashboard', component: DashboardComponent}
        ]
      },
      {
        path: '',
        children: [
          {path: 'login', component: LoginComponent}
        ]
      }
    ]
  }
]
</code>```

By using path: '' you won't have to invent different url namespaces in order to use a simple layout. This is what the views look like:

index.html:

```<code><router-outlet>
</code>```

default-layout.html:

```<code><div class="sidebar"></div>
<div class="content">
  <router-outlet></router-outlet>
</div>
</code>```

Title: How to switch layouts in Angular2

Body:
In Angular 4 (and probably also in Angular 2) you can do:

const routes: Route[] = [
  {path: 'admin', redirectTo: 'admin/dashboard', pathMatch: 'full'},
  {
    path: 'admin',
    children: [
      {
        path: '', component: DefaultLayoutComponent,
        children: [
          {path: 'dashboard', component: DashboardComponent}
        ]
      },
      {
        path: '',
        children: [
          {path: 'login', component: LoginComponent}
        ]
      }
    ]
  }
]

By using path: '' you won't have to invent different url namespaces in order to use a simple layout. This is what the views look like:

index.html:

<router-outlet>

default-layout.html:

<div class="sidebar"></div>
<div class="content">
  <router-outlet></router-outlet>
</div>


问:
Use vs Include in PHP
I'm trying to get my head around PHP namespaces and testing with PHPUnit.

These tests from Codewars pass when I run phpunit test.php in the command line on Windows:

```<code><?php
require 'solution.php';
use PHPUnit\Framework\TestCase;

class myTests extends TestCase {
  public function testExamples() {
        $this->assertEquals(pair_sum([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10),6);
        $this->assertEquals(pair_sum([1,2,3,1],3),1);
        $this->assertEquals(pair_sum([1,3,2,2],4),2);
        $this->assertEquals(pair_sum([1],4),false);
        $this->assertEquals(pair_sum([2,3,10,-5],5),2);
  }
}
</code>```

However, when I comment out use PHPUnit\Framework\TestCase; I get Class 'TestCase' not found which makes sense since there is no reference to the needed classes/functions.

What's confusing me though is that lots of answers here on SO about namespacing claim that the use keyword is NOT a substitute for include/require and that the classes still need to be included/autoloaded(?).

I'm not using any autoloading here - just a solution.php file and the tests above in a test.php file.

Can someone please explain what I'm missing here? How come the tests work without  any explicit including of the PHPunit functionality?

I should mention that I have PHPUnit installed globally via Composer.

答:
use doesn't include anything. It just imports the specified namespace (or class) to the current scope, you need to have an autoloader set up in order to include the file in which the namespace is defined.
Read more about autoloading here:http://php.net/manual/en/language.oop5.autoload.php

The include statement includes and evaluates the specified file.

Example:

```<code><?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>
</code>```

Title: Use vs Include in PHP

Body:
I'm trying to get my head around PHP namespaces and testing with PHPUnit.

These tests from Codewars pass when I run phpunit test.php in the command line on Windows:

<?php
require 'solution.php';
use PHPUnit\Framework\TestCase;

class myTests extends TestCase {
  public function testExamples() {
        $this->assertEquals(pair_sum([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10),6);
        $this->assertEquals(pair_sum([1,2,3,1],3),1);
        $this->assertEquals(pair_sum([1,3,2,2],4),2);
        $this->assertEquals(pair_sum([1],4),false);
        $this->assertEquals(pair_sum([2,3,10,-5],5),2);
  }
}

However, when I comment out use PHPUnit\Framework\TestCase; I get Class 'TestCase' not found which makes sense since there is no reference to the needed classes/functions.

What's confusing me though is that lots of answers here on SO about namespacing claim that the use keyword is NOT a substitute for include/require and that the classes still need to be included/autoloaded(?).

I'm not using any autoloading here - just a solution.php file and the tests above in a test.php file.

Can someone please explain what I'm missing here? How come the tests work without  any explicit including of the PHPunit functionality?

I should mention that I have PHPUnit installed globally via Composer.

Body:
use doesn't include anything. It just imports the specified namespace (or class) to the current scope, you need to have an autoloader set up in order to include the file in which the namespace is defined.
Read more about autoloading here:http://php.net/manual/en/language.oop5.autoload.php

The include statement includes and evaluates the specified file.

Example:

<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>


问:
Java: Hibernate does not see changes in DataBase
I have two different applications that share the same database. The problem is that when I have an application change something in the database, the other does not update.

I tried to make a session.flush() but it didn't work. The only way is to close the entire session and recreate it, but of course, that takes too long.

答:
If I understand correctly this is what happens in your scenario:

app1 starts a transaction

app2 (starts and) commits another transaction

app1 expects to be able to read the changes done by app2

If this is the case you need to check out your database Isolation levels.

Or you could of course start a new transaction when you want to read updated data. Check out the Hibernate transactions documentation


问:
Mongoose - filter and sort results on user input
I want to implement a search feature in my website, which allows the user to search the database and then filter or sort the search results as needed. Something like this. </p>

<p>Is there an "efficient" way that I can search using a Schema.find() and store the result in an array of Mongoose objects, and then filter or sort this array according to user input? Or do I have to make a new query every time the user adds a new filter? </p>

答:
This answer depends a lot on your architecture.  At first blush, the direct answer to your question would be to use the query builder interface. That would let you chain together where clauses and sort and limit options via chaining, eg.

```<code>Person.find({ occupation: /host/ }).
  where('name.last').equals('Ghost').
  where('age').gt(17).lt(66).
  where('likes').in(['vaporizing', 'talking']).
  limit(10).
  sort('-occupation').
  select('name occupation').
  exec(callback);
</code>```

But if you're doing a web app, one might presume that you want to respond with the first find, and then let users filter and sort from there.

In that case, you'll either need to sort and filter on the client (which isn't too hard if you're using ES6 via babel or lodash), or if your initial find returns a lot of records, you'll still need to make trips to the server and re-query the db.

Body:
I want to implement a search feature in my website, which allows the user to search the database and then filter or sort the search results as needed. Something like this.

Is there an "efficient" way that I can search using a Schema.find() and store the result in an array of Mongoose objects, and then filter or sort this array according to user input? Or do I have to make a new query every time the user adds a new filter?

Body:
This answer depends a lot on your architecture.  At first blush, the direct answer to your question would be to use the query builder interface. That would let you chain together where clauses and sort and limit options via chaining, eg.

Person.find({ occupation: /host/ }).
  where('name.last').equals('Ghost').
  where('age').gt(17).lt(66).
  where('likes').in(['vaporizing', 'talking']).
  limit(10).
  sort('-occupation').
  select('name occupation').
  exec(callback);

But if you're doing a web app, one might presume that you want to respond with the first find, and then let users filter and sort from there.

In that case, you'll either need to sort and filter on the client (which isn't too hard if you're using ES6 via babel or lodash), or if your initial find returns a lot of records, you'll still need to make trips to the server and re-query the db.


答:
```<code> $(".navbar-toggle").click(function() {
   if(".navbar-toggle").hasClass("collapsed"))
    $(".country-flags-container").hide();
  else
    $(".country-flags-container").show();
  )}
</code>```

Try this You miss the ) for if condition

Title: jQuery hasClass Uncaught SyntaxError: Unexpected token )

Body:
 $(".navbar-toggle").click(function() {
   if(".navbar-toggle").hasClass("collapsed"))
    $(".country-flags-container").hide();
  else
    $(".country-flags-container").show();
  )}

Try this You miss the ) for if condition


问:
scalac: Error: object CharRef in intelliJ 14
I can successfully compile code from terminal with mvn compile command. But when I compile code with intellij 14 I got following error:

```<code>Error:scalac: Error: object CharRef does not have a member create
scala.reflect.internal.FatalError: object CharRef does not have a member create
    at scala.reflect.internal.Definitions$DefinitionsClass.scala$reflect$internal$Definitions$DefinitionsClass$$fatalMissingSymbol(Definitions.scala:1179)
    at ...
</code>```

What could be a reason?

答: My version is IntelliJ IDEA 2016.1.3 and has same issue. My solution is the scala-sdk 2.12.1 change to use version 2.10.4 , It can fixed. Help it can help guys. </p>

Body:
I can successfully compile code from terminal with mvn compile command. But when I compile code with intellij 14 I got following error:

Error:scalac: Error: object CharRef does not have a member create
scala.reflect.internal.FatalError: object CharRef does not have a member create
    at scala.reflect.internal.Definitions$DefinitionsClass.scala$reflect$internal$Definitions$DefinitionsClass$$fatalMissingSymbol(Definitions.scala:1179)
    at ...

What could be a reason?


问:
How to hide div when click on anywhere on the display
Here My Div #PopupDiv by dafault its in hiding when i click on #Btn1 its display #PopupDiv but whenevere user click anywhere on the display it should be hide

       $(document).ready(function () {
          $('#PopupDiv').hide();
          $('#Btn1').click(function () {
             alert()
             $('#PopupDiv').show();
          })
          $(document).click(function () {
             alert('o')
             if ($('#PopupDiv').is(':visible')) {
                alert('vis');
             }
          })
       })

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="button" id="Btn1" value="BtnClick" />
</div>
<div id="PopupDiv">
  <p>Hello Popup Grid</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </code>```

答:
you can simply do like this way, you can use .stopPropagation() for this

jQuery(function($) {
    $('#PopupDiv').hide();
    $('#Btn1').click(function (e) {
       e.stopPropagation();
       $('#PopupDiv').show();
    });

    $(document).click(function (e) {
      e.stopPropagation();
      $('#PopupDiv').hide();
   });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="button" id="Btn1" value="BtnClick" />
</div>

<div id="PopupDiv">
  <p>Hello Popup Grid</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </code>```

Body:
Here My Div #PopupDiv by dafault its in hiding when i click on #Btn1 its display #PopupDiv but whenevere user click anywhere on the display it should be hide

       $(document).ready(function () {
          $('#PopupDiv').hide();
          $('#Btn1').click(function () {
             alert()
             $('#PopupDiv').show();
          })
          $(document).click(function () {
             alert('o')
             if ($('#PopupDiv').is(':visible')) {
                alert('vis');
             }
          })
       })

  <input type="button" id="Btn1" value="BtnClick" />

Hello Popup Grid

Body:
you can simply do like this way, you can use .stopPropagation() for this

jQuery(function($) {
    $('#PopupDiv').hide();
    $('#Btn1').click(function (e) {
       e.stopPropagation();
       $('#PopupDiv').show();
    });

    $(document).click(function (e) {
      e.stopPropagation();
      $('#PopupDiv').hide();
   });
});

<div>
  <input type="button" id="Btn1" value="BtnClick" />
</div>

<div id="PopupDiv">
  <p>Hello Popup Grid</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


问:
Is there any way to add constraint between a view and the top layout guide in a xib file?
In iOS 7, we can now add a constraint between a view and the top layout guide, which I think is very useful to solve the status bar offset issue in iOS7(especially when there is no navigation bar in the view).

In a storyboard file, I can add this kind of constraints easily. Just hold the control key then drag the view to the container, it will show the "Top Space to Top Layout Guide" option.

But when I do the same operation in a xib file, this option disappears.

So, is there any way to add this kind of constraints in xib files? Or do I have to add them with code?

答:
From iOS 9 you can also do it more simple with topLayoutGuide's anchors:

Swift 3

view.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true

ObjC

[controller.view.topAnchor constraintEqualToAnchor:controller.topLayoutGuide.bottomAnchor].active = YES;


问:
endPosTable already set when adding sourceSet
I am using a custom annotation processor and have a new problem.
I am using Gradle (3.1.1) and when I add the path of the file that will be generated, by my processor, to the sourceSet I get weird problems.

I perform a gradle clean build then a gradle build afterwards and the build get's destroyed.
The stacktrace I get is a pretty common one to my surprise.

```<code>An exception has occurred in the compiler (1.8.0_91). Please file a bug against the Java compiler via the Java bug reporting page (http://bugreport.java.com) after checking the Bug Database (http://bugs.java.com) for duplicates. Include your program and the following diagnostic in your report. Thank you.
java.lang.IllegalStateException: endPosTable already set
    at com.sun.tools.javac.util.DiagnosticSource.setEndPosTable(DiagnosticSource.java:136)
    at com.sun.tools.javac.util.Log.setEndPosTable(Log.java:350)
    at com.sun.tools.javac.main.JavaCompiler.parse(JavaCompiler.java:667)
    at com.sun.tools.javac.main.JavaCompiler.parseFiles(JavaCompiler.java:950)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.<init>(JavacProcessingEnvironment.java:892)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.next(JavacProcessingEnvironment.java:921)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1187)
    at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
    at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:856)
    at com.sun.tools.javac.main.Main.compile(Main.java:523)
    at com.sun.tools.javac.main.Main.compile(Main.java:381)
    at com.sun.tools.javac.main.Main.compile(Main.java:370)
    at com.sun.tools.javac.main.Main.compile(Main.java:361)
    at com.sun.tools.javac.Main.compile(Main.java:56)
    at com.sun.tools.javac.Main.main(Main.java:42)
</code>```

If I always clean before building I don't have a problem, alsothe build is always successfull when I don't add the sourceSet.
I even tried deleting the file right before creating the new generated file in my annotation processor but that didn't do the trick either.

While researching I also found this interesting link:
JDK Bug report

But thinking about that I either have to always clean first or to leave it out of my sourceSet is not really good. Since Eclipse doesn't like not finding a file that should be there by convention.

Do you have any suggestions on how to solve this?

答:
I'm trying to use generated Dagger* files in the testing source set of my Android application. I changed a couple of things in @Nico's workaround, now everything is working great for me.

/build.gradle:

```<code>ext {
    generatedSourcesDir = 'build/generated/source/apt/test/debug'
}
</code>```

/app/build.gradle

```<code>android {
    sourceSets {
        test.java.srcDirs += generatedSourcesDir
    }
}

tasks.withType(JavaCompile) {
   if (file(generatedSourcesDir).exists()) {
       FileCollection collection = files { file(generatedSourcesDir).listFiles() }
       collection.each { delete it }
   }
}

dependencies {
    ...
}
</code>```

Body:
I am using a custom annotation processor and have a new problem.
I am using Gradle (3.1.1) and when I add the path of the file that will be generated, by my processor, to the sourceSet I get weird problems.

I perform a gradle clean build then a gradle build afterwards and the build get's destroyed.
The stacktrace I get is a pretty common one to my surprise.

An exception has occurred in the compiler (1.8.0_91). Please file a bug against the Java compiler via the Java bug reporting page (http://bugreport.java.com) after checking the Bug Database (http://bugs.java.com) for duplicates. Include your program and the following diagnostic in your report. Thank you.
java.lang.IllegalStateException: endPosTable already set
    at com.sun.tools.javac.util.DiagnosticSource.setEndPosTable(DiagnosticSource.java:136)
    at com.sun.tools.javac.util.Log.setEndPosTable(Log.java:350)
    at com.sun.tools.javac.main.JavaCompiler.parse(JavaCompiler.java:667)
    at com.sun.tools.javac.main.JavaCompiler.parseFiles(JavaCompiler.java:950)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.<init>(JavacProcessingEnvironment.java:892)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.next(JavacProcessingEnvironment.java:921)
    at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1187)
    at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1170)
    at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:856)
    at com.sun.tools.javac.main.Main.compile(Main.java:523)
    at com.sun.tools.javac.main.Main.compile(Main.java:381)
    at com.sun.tools.javac.main.Main.compile(Main.java:370)
    at com.sun.tools.javac.main.Main.compile(Main.java:361)
    at com.sun.tools.javac.Main.compile(Main.java:56)
    at com.sun.tools.javac.Main.main(Main.java:42)

If I always clean before building I don't have a problem, alsothe build is always successfull when I don't add the sourceSet.
I even tried deleting the file right before creating the new generated file in my annotation processor but that didn't do the trick either.

While researching I also found this interesting link:
JDK Bug report

But thinking about that I either have to always clean first or to leave it out of my sourceSet is not really good. Since Eclipse doesn't like not finding a file that should be there by convention.

Do you have any suggestions on how to solve this?

Body:
I'm trying to use generated Dagger* files in the testing source set of my Android application. I changed a couple of things in @Nico's workaround, now everything is working great for me.

/build.gradle:

ext {
    generatedSourcesDir = 'build/generated/source/apt/test/debug'
}

/app/build.gradle

android {
    sourceSets {
        test.java.srcDirs += generatedSourcesDir
    }
}

tasks.withType(JavaCompile) {
   if (file(generatedSourcesDir).exists()) {
       FileCollection collection = files { file(generatedSourcesDir).listFiles() }
       collection.each { delete it }
   }
}

dependencies {
    ...
}


问:
No video, only sound with VideoView
When I play a video file using a VideoView on Android, I can hear the sound fine, but the video does not show.

So, when I use :

```<code>myVideoView.setZOrderOnTop(true);
</code>```

then the video shows fine, however, then my TextView is behind the VideoView and I need it to be in front.

Therefore, I either need a solution so that the video is played without using setZOrderOnTop, or I need a way to get the text in front of the video while using setZOrderOnTop.

Title: No video, only sound with VideoView

Body:
When I play a video file using a VideoView on Android, I can hear the sound fine, but the video does not show.

So, when I use :

myVideoView.setZOrderOnTop(true);

then the video shows fine, however, then my TextView is behind the VideoView and I need it to be in front.

Therefore, I either need a solution so that the video is played without using setZOrderOnTop, or I need a way to get the text in front of the video while using setZOrderOnTop.

Body: videoView.setBackgroundColor(Color.TRANSPARENT);


问:
In Javascript console.log I am not getting the result
I want console.log to print only firstname if lastname was undefined, instead I get firstname + undefined on the console. What could I change in the code so it only gives me firstname or lastname if one of them is undefined without printing the word 'undefined' in the console, and if both are defined to print them both. This is the code I am trying:

```<code>    document.getElementById("runButton").onclick = function run() {
        var lastName = "arm";
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName = 'undefined') {
                console.log("Hello, " + firstName + "!");
            } else if (firstName = 'undefiend') {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName + " " + lastName);
    };
</code>```

答:
Check your conditions, it has typo. Also </p>

```<code>function Greeting(firstName, lastName) {
            if (lastName == undefined) {
                console.log("Hello, " + firstName + "!");
            } else if (firstName == undefined) {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
</code>```

Body:
I want console.log to print only firstname if lastname was undefined, instead I get firstname + undefined on the console. What could I change in the code so it only gives me firstname or lastname if one of them is undefined without printing the word 'undefined' in the console, and if both are defined to print them both. This is the code I am trying:

    document.getElementById("runButton").onclick = function run() {
        var lastName = "arm";
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName = 'undefined') {
                console.log("Hello, " + firstName + "!");
            } else if (firstName = 'undefiend') {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName + " " + lastName);
    };

Body:
Check your conditions, it has typo. Also

function Greeting(firstName, lastName) {
            if (lastName == undefined) {
                console.log("Hello, " + firstName + "!");
            } else if (firstName == undefined) {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }


问:
How are these quoted strings replaced with the values in perl .pm file?
Below is the Perl code in .pm file which is supposed to replace the specified strings (that are in "quotes") with some values. But its not happening. Can anyone explain what is happening in this code?</p>

```<code>package SomePackage;

require Exporter;

@ISA    = qw(Exporter);
@EXPORT = qw(send_request, create_mmd_and_transfer, update_mmd_file);

sub send_request {
    my ( $service, $action, $torole ) = @_;

    my ( $seller_request_mmd );

    my $replace_contents = ();
    $replace_contents{"REPLACE_Service"}        = $service;
    $replace_contents{"REPLACE_RequestAction"}  = $action;
    $replace_contents{"REPLACE_TradingPartner"} = $torole;
    $replace_contents{"REPLACE_Requestxml"}     = "Request.xml";

    create_mmd_and_transfer( \%replace_contents, $seller_request_mmd, "/MMD.xml" );
}

sub create_mmd_and_transfer {

    my $local_replace_contents = shift;
    my $input_mmd              = shift;
    my $local_output_mmd       = shift;
    my $output_mmd             = shift;

    update_mmd_file( "$input_mmd", "temp_mmd_file.xml", $local_replace_contents );
}

sub update_mmd_file {

    my $input_file  = shift;
    my $output_file = shift;
    my $contents    = shift;

    open( MMD_FILE, "<$input_file" )
            or main::error_exit(" Cannot open MMD file template $input_file \n $input_file not found int the Templates folder \n Please place the same and then run the script ");

    open( TEMP_MMD_FILE, ">$output_file" );

    while ( <MMD_FILE> ) {

        s/^M//g;    # Getrid of the ^Ms

        foreach my $content ( keys( %$contents ) ) {

            my $exact_value = ${%$contents}{$content};

            if ( $main::test_scenario =~ /^Invalid Request Action \a\n\d Service/
                and ( $content =~ /REPLACE_Service|REPLACE_RequestAction/i ) ) {
            }
            else {

                if ( $exact_value ne "" ) {
                    s/$content/$exact_value/g;
                }
            }
        }

        print TEMP_MMD_FILE;
    }

    close MMD_FILE;
    close TEMP_MMD_FILE;
}
</code>```

答:
The following will not make your script work, just create the better base for some future questions.

Before you even thinking about posting a perl question here:

1.) add to the top of your script:

```<code>use strict;
use warnings;
</code>```

Posting a code here without these two lines, nobody will bother even trying to read the code.

2.) use perl -c SomePackage.pm for the check. If it will tell you: SomePackage.pm syntax OK - you can start thinking about posting a question here. ;)

Some basic problems with your script:

```<code>package SomePackage;
use strict;   # see the above
use warnings;

require Exporter;

# these variables are defined outside of this package, so, tell perl this fact. use the `our`
our @ISA    = qw(Exporter);
#the use warnings will warn you about the following line
# @EXPORT = qw(send_request, create_mmd_and_transfer, update_mmd_file);
#the correct one is without commas
our @EXPORT = qw(send_request create_mmd_and_transfer update_mmd_file); #not saying anything about the @EXPORT rudeness. :)

#my $replace_contents = ();
#the $replace_contents is a scalar. Bellow you using a hash. So,
my %replace_contents;
#or use the scalar but the lines bellow should use the hashref notation, e.g.
# $replace_contents->{"REPLACE_Service"} = $service;
# you decide. :)

# the seller_request_mmd contains undef here.
create_mmd_and_transfer( \%replace_contents, $seller_request_mmd, "/MMD.xml");
# also bellow, in the subroutine definition it wants 4 arguments.
# indicates a problem...

# using 2-arg open is not the best practice.
# Also, you should to use lexical filehandles
# open (MMD_FILE, "<$input_file")
# better
open (my $mmd_file, '<', $input_file)
# of course, you need change every MMD_FILE to $mmd_file
# check the result of the open and die if not successful
# or you can use the
use autodie;

# instead of $exact_value = ${%$contents}{$content};
# you probably want
my $exact_value = $contents->{$content};
</code>```

Indent your code!

All the above are just about the syntactic problems and not solving anything about the "logic" of your code.

Ps: And me is still an beginner, so, others sure will find much more problems with the above code.

Body:
Below is the Perl code in .pm file which is supposed to replace the specified strings (that are in "quotes") with some values. But its not happening. Can anyone explain what is happening in this code?

package SomePackage;

require Exporter;

@ISA    = qw(Exporter);
@EXPORT = qw(send_request, create_mmd_and_transfer, update_mmd_file);

sub send_request {
    my ( $service, $action, $torole ) = @_;

    my ( $seller_request_mmd );

    my $replace_contents = ();
    $replace_contents{"REPLACE_Service"}        = $service;
    $replace_contents{"REPLACE_RequestAction"}  = $action;
    $replace_contents{"REPLACE_TradingPartner"} = $torole;
    $replace_contents{"REPLACE_Requestxml"}     = "Request.xml";

    create_mmd_and_transfer( \%replace_contents, $seller_request_mmd, "/MMD.xml" );
}

sub create_mmd_and_transfer {

    my $local_replace_contents = shift;
    my $input_mmd              = shift;
    my $local_output_mmd       = shift;
    my $output_mmd             = shift;

    update_mmd_file( "$input_mmd", "temp_mmd_file.xml", $local_replace_contents );
}

sub update_mmd_file {

    my $input_file  = shift;
    my $output_file = shift;
    my $contents    = shift;

    open( MMD_FILE, "<$input_file" )
            or main::error_exit(" Cannot open MMD file template $input_file \n $input_file not found int the Templates folder \n Please place the same and then run the script ");

    open( TEMP_MMD_FILE, ">$output_file" );

    while ( <MMD_FILE> ) {

        s/^M//g;    # Getrid of the ^Ms

        foreach my $content ( keys( %$contents ) ) {

            my $exact_value = ${%$contents}{$content};

            if ( $main::test_scenario =~ /^Invalid Request Action \a\n\d Service/
                and ( $content =~ /REPLACE_Service|REPLACE_RequestAction/i ) ) {
            }
            else {

                if ( $exact_value ne "" ) {
                    s/$content/$exact_value/g;
                }
            }
        }

        print TEMP_MMD_FILE;
    }

    close MMD_FILE;
    close TEMP_MMD_FILE;
}

Body:
The following will not make your script work, just create the better base for some future questions.

Before you even thinking about posting a perl question here:

1.) add to the top of your script:

use strict;
use warnings;

Posting a code here without these two lines, nobody will bother even trying to read the code.

2.) use perl -c SomePackage.pm for the check. If it will tell you: SomePackage.pm syntax OK - you can start thinking about posting a question here. ;)

Some basic problems with your script:

package SomePackage;
use strict;   # see the above
use warnings;

require Exporter;

# these variables are defined outside of this package, so, tell perl this fact. use the `our`
our @ISA    = qw(Exporter);
#the use warnings will warn you about the following line
# @EXPORT = qw(send_request, create_mmd_and_transfer, update_mmd_file);
#the correct one is without commas
our @EXPORT = qw(send_request create_mmd_and_transfer update_mmd_file); #not saying anything about the @EXPORT rudeness. :)

#my $replace_contents = ();
#the $replace_contents is a scalar. Bellow you using a hash. So,
my %replace_contents;
#or use the scalar but the lines bellow should use the hashref notation, e.g.
# $replace_contents->{"REPLACE_Service"} = $service;
# you decide. :)

# the seller_request_mmd contains undef here.
create_mmd_and_transfer( \%replace_contents, $seller_request_mmd, "/MMD.xml");
# also bellow, in the subroutine definition it wants 4 arguments.
# indicates a problem...

# using 2-arg open is not the best practice.
# Also, you should to use lexical filehandles
# open (MMD_FILE, "<$input_file")
# better
open (my $mmd_file, '<', $input_file)
# of course, you need change every MMD_FILE to $mmd_file
# check the result of the open and die if not successful
# or you can use the
use autodie;

# instead of $exact_value = ${%$contents}{$content};
# you probably want
my $exact_value = $contents->{$content};

Indent your code!

All the above are just about the syntactic problems and not solving anything about the "logic" of your code.

Ps: And me is still an beginner, so, others sure will find much more problems with the above code.


问:
Sort DataAdapter Alphabetically - VB.Net
This should be a fairly simple one. I am creating a dataset which will contain a description field which I would like to sort by. The reason I want to sort the dataadapter and not in my SQL is that I am already ordering by the results that have a particular value.

My SQL looks like this:

```<code>SELECT pif_desc, pif_fund, psf_end, (CASE WHEN SUM(pmi_units) IS Null THEN 0 ELSE SUM(pmi_units) END) As fundunits
    FROM tbl_mem INNER JOIN tbl_sfunds
    ON pm_scheme = psf_scheme
    INNER JOIN tbl_invfun
    ON tbl_fund = tbl_fund
    LEFT JOIN pe_minv
    ON pmi_fund = pif_fund AND pm_member = pmi_member
    WHERE pm_member = @pm_member
    GROUP BY pif_desc, pif_fund, psf_end
    ORDER BY fundunits DESC
</code>```

My VB looks like this:

```<code>Dim cmd As New SqlCommand("getMembersFundsDCGENST", conn)
        cmd.CommandType = CommandType.StoredProcedure

        Dim p_pm_member As New SqlParameter("@pm_member", SqlDbType.Int)
        p_pm_member.Value = pm_member
        cmd.Parameters.Add(p_pm_member)

        Dim p_period_closing_date As New SqlParameter("@closingdate", SqlDbType.DateTime)
        p_period_closing_date.Value = period_closing_date
        cmd.Parameters.Add(p_closing_date)

        Dim da As New SqlDataAdapter(cmd)
        da.Fill(ds)
</code>```

I want to sort the datarows is ds.tables(0) by pif_desc but still have the rows with fundunits > 0 listed first.

I am also open to other suggestions on how I can achieve the correct ordering.

答: DataView should be used whenever sorting or filtering is to be applied in code. Take a look.

Body:
This should be a fairly simple one. I am creating a dataset which will contain a description field which I would like to sort by. The reason I want to sort the dataadapter and not in my SQL is that I am already ordering by the results that have a particular value.

My SQL looks like this:

SELECT pif_desc, pif_fund, psf_end, (CASE WHEN SUM(pmi_units) IS Null THEN 0 ELSE SUM(pmi_units) END) As fundunits
    FROM tbl_mem INNER JOIN tbl_sfunds
    ON pm_scheme = psf_scheme
    INNER JOIN tbl_invfun
    ON tbl_fund = tbl_fund
    LEFT JOIN pe_minv
    ON pmi_fund = pif_fund AND pm_member = pmi_member
    WHERE pm_member = @pm_member
    GROUP BY pif_desc, pif_fund, psf_end
    ORDER BY fundunits DESC

My VB looks like this:

Dim cmd As New SqlCommand("getMembersFundsDCGENST", conn)
        cmd.CommandType = CommandType.StoredProcedure

        Dim p_pm_member As New SqlParameter("@pm_member", SqlDbType.Int)
        p_pm_member.Value = pm_member
        cmd.Parameters.Add(p_pm_member)

        Dim p_period_closing_date As New SqlParameter("@closingdate", SqlDbType.DateTime)
        p_period_closing_date.Value = period_closing_date
        cmd.Parameters.Add(p_closing_date)

        Dim da As New SqlDataAdapter(cmd)
        da.Fill(ds)

I want to sort the datarows is ds.tables(0) by pif_desc but still have the rows with fundunits > 0 listed first.

I am also open to other suggestions on how I can achieve the correct ordering.


问:
UI Bootstrap Datepicker - Call function when date selected from keyboard or popup
I'm using the UI Bootstrap Datepicker Popup elsewhere in my apps successfully. I now have the requirement to call a function (which makes a fairly expensive API call after translating the date to the next Sunday if it isn't a Sunday) when the user has either selected a date from the popup or FINISHED entering a date from the keyboard.

I currently have a search button that calls the function, but the new requirement is to remove the search button and search when a new date has been selected.

My logical design is to call my function on a popup date selection OR a return/enter key keypress to indicate keyboard input is complete.

Here's the HTML I have for the datepicker

```<code><div class="input-group">
  <input type="text" name="datePicker" id="datePicker"
    class="form-control"
    ng-model="$ctrl.dateValue"
    ng-change="$ctrl.onChange($ctrl.dateValue)"
    uib-datepicker-popup="{{$ctrl.config.format}}"
    datepicker-options="$ctrl.config.options"
    is-open="$ctrl.config.opened"
    close-text="Close">

  <span class="input-group-btn">
    <button type="button" id="datePickerButton"
      class="btn btn-primary"
      ng-click="$ctrl.openDatePicker()">
      <i class="glyphicon glyphicon-calendar"></i>
    </button>
  </span>
</div>
</code>```

This correctly calls my $ctrl.onChange() function when the date has changed from the date picker popup. However it also triggers as the user is performing keypress events.

For example if the date displayed is 8/15/16 and the user wants to change it from Aug 15 to Aug 23. The user may want to select the '15' and type '23'. Unfortunately the ng-change will be triggered with the '2' keypress and not give them the chance to enter the '3'.

How do I wait on keyboard input until the user signals they are complete by pressing the enter key?

答:
I solved it like this :

in the controller :

```<code>$scope.change = function(search) {

        if(event) {
            if (event.type==="click") {
                if (search==="yourControl") {
                    dosomething()
                }
            }
        }

 };
</code>```

in the view :

```<code>ng-change="ctrl.change('yourControl')"
</code>```

Body:
I'm using the UI Bootstrap Datepicker Popup elsewhere in my apps successfully. I now have the requirement to call a function (which makes a fairly expensive API call after translating the date to the next Sunday if it isn't a Sunday) when the user has either selected a date from the popup or FINISHED entering a date from the keyboard.

I currently have a search button that calls the function, but the new requirement is to remove the search button and search when a new date has been selected.

My logical design is to call my function on a popup date selection OR a return/enter key keypress to indicate keyboard input is complete.

Here's the HTML I have for the datepicker

  <input type="text" name="datePicker" id="datePicker"
    class="form-control"
    ng-model="$ctrl.dateValue"
    ng-change="$ctrl.onChange($ctrl.dateValue)"
    uib-datepicker-popup="{{$ctrl.config.format}}"
    datepicker-options="$ctrl.config.options"
    is-open="$ctrl.config.opened"
    close-text="Close">

    <button type="button" id="datePickerButton"
      class="btn btn-primary"
      ng-click="$ctrl.openDatePicker()">

    </button>

This correctly calls my $ctrl.onChange() function when the date has changed from the date picker popup. However it also triggers as the user is performing keypress events.

For example if the date displayed is 8/15/16 and the user wants to change it from Aug 15 to Aug 23. The user may want to select the '15' and type '23'. Unfortunately the ng-change will be triggered with the '2' keypress and not give them the chance to enter the '3'.

How do I wait on keyboard input until the user signals they are complete by pressing the enter key?

Body:
I solved it like this :

in the controller :

$scope.change = function(search) {

        if(event) {
            if (event.type==="click") {
                if (search==="yourControl") {
                    dosomething()
                }
            }
        }

 };

in the view :

ng-change="ctrl.change('yourControl')"


问:
How can I decode a JSON into array using jQuery
Hi to all i have a problem with a JSON in Phonegap, i´m trying to do a login using facebook sdk and get some info for the profile but i get a JSON this is the JSON
using JSON.stringify():

```<code> {
   "id":"facebookId",
   "first_name":"Joseluis",
   "last_name":"Fernandezmateo",
   "email":"myemail@hotmail.com",
   "gender":"male",
   "birthday":"09/30/1998"
 }
</code>```

And what i want is to create an array that contains all data (first name, last name, id, and the other stuff) and returns the value of the data i mean
data['gender'] and this return his gender in this case male sorry if i could not explain me better but in my head all make sense, Thanks for the help

答: Thanks for the answers i use luschn answer i just use data.email in order to get the email, sorry if look as a noob but I´m noob in web developing i´m learning web developing and in the meantime i develop and app anyways thanks for all answers</p>

Body:
Hi to all i have a problem with a JSON in Phonegap, i´m trying to do a login using facebook sdk and get some info for the profile but i get a JSON this is the JSON
using JSON.stringify():

 {
   "id":"facebookId",
   "first_name":"Joseluis",
   "last_name":"Fernandezmateo",
   "email":"myemail@hotmail.com",
   "gender":"male",
   "birthday":"09/30/1998"
 }

And what i want is to create an array that contains all data (first name, last name, id, and the other stuff) and returns the value of the data i mean
data['gender'] and this return his gender in this case male sorry if i could not explain me better but in my head all make sense, Thanks for the help


问:
How to concatenate variable name AngularJS?
Concatenate variable name in HTML code like:

app.controller code

```<code>  $scope.name ='abc';
  $scope.abc123 = response.data;
</code>```

HTML code

```<code>   <h1>{{name}}</h1>
   <h1>{{{{name}}123}}</h1> <!-- here i need value of abc123 -->
</code>```

答:
Double times curly braces wouldn't work since it tries to interpret 123 as number but you can do so using combination of ng-bind and {{..}}. Like this:

```<code><pre ng-bind="{{name}}123">```
```

<p>Here's working example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>angular.module('myApp', []);

function myCtrl($scope) {
  $scope.model = {};
  $scope.name = 'abc'
  $scope.abc123 = "test"
}</code>```

```
  </div>
</body></code>```

Body:
Concatenate variable name in HTML code like:

app.controller code

  $scope.name ='abc';
  $scope.abc123 = response.data;

HTML code

{{name}}

{{{{name}}123}}

Body:
Double times curly braces wouldn't work since it tries to interpret 123 as number but you can do so using combination of ng-bind and {{..}}. Like this:

<pre ng-bind="{{name}}123"></pre>

Here's working example:

angular.module('myApp', []);

function myCtrl($scope) {
  $scope.model = {};
  $scope.name = 'abc'
  $scope.abc123 = "test"
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
  <div ng-controller="myCtrl">
    <pre ng-bind="{{name}}123"></pre>
  </div>
</body>


问:
Apps Script to automate Bigquery runs but doesn't do anything
I'm posting this as a new question as it's slightly different to my original questions on this matter.

I have an apps script to run a query in BigQuery. The script is running and communicating with BigQuery but the job isn't working as expected. I currently get the following error in BigQuery:

Already Exists: Table fiery-cabinet-111****:***.Test4 (error code: duplicate)

Here is the script:

```<code>function saveQueryToTable() {
  var projectId = 'fiery-cabinet-*****';
  var datasetId = '11****101';
  var tableId = 'Test4';
  var job = {
    configuration: {
      query: {
        query: 'SELECT * ' +
               'FROM [fiery-cabinet-****:*****.Test2];',
        destinationTable: {
          projectId: projectId,
          datasetId: datasetId,
          tableId: tableId
        }
      }
    }
  };

var queryResults = BigQuery.Jobs.insert(job, projectId);
  Logger.log(queryResults.status);
}
</code>```

答:
The table you are writing the query results to already exists. You need to set the WRITE_DISPOSITION to either:

WRITE_TRUNCATE: If the table already exists, BigQuery overwrites the table data.

WRITE_APPEND: If the table already exists, BigQuery appends the data to the table.

WRITE_EMPTY: If the table already exists and contains data, a 'duplicate' error is returned in the job result.

The default value is WRITE_EMPTY.

https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.query

configuration.query.writeDisposition

Body:
I'm posting this as a new question as it's slightly different to my original questions on this matter.

I have an apps script to run a query in BigQuery. The script is running and communicating with BigQuery but the job isn't working as expected. I currently get the following error in BigQuery:

Already Exists: Table fiery-cabinet-111****:***.Test4 (error code: duplicate)

Here is the script:

function saveQueryToTable() {
  var projectId = 'fiery-cabinet-*****';
  var datasetId = '11****101';
  var tableId = 'Test4';
  var job = {
    configuration: {
      query: {
        query: 'SELECT * ' +
               'FROM [fiery-cabinet-****:*****.Test2];',
        destinationTable: {
          projectId: projectId,
          datasetId: datasetId,
          tableId: tableId
        }
      }
    }
  };

var queryResults = BigQuery.Jobs.insert(job, projectId);
  Logger.log(queryResults.status);
}


问:
Sort descending based on part of a title in Wordpress?
I'm having an issue how to sort a title in Wordpress. If I just know how I would solve this in MySQL it would be great. (If someone has an answer specific for wordpress that would be a lot easier for me though)

I have a database where the title (one field in the database-table) is called post_title. The title stores name AND year with a space between

eg.

```<code>Sweden 2017
Sweden 2016
Norway 2018
Norway 2019
</code>```

I want to sort above like this: (descending by year and ascending by name)

```<code>Norway 2019
Norway 2018
Sweden 2017
Sweden 2016
</code>```

UPDATE:
I've tried with Wordpress-builtin sorting with WP_Query:

```<code>$module_args = array(
                'posts_per_page' => -1,
                'post_type' => 'project',
                'include_children' => false,
                'orderby' => 'title',
                'order' => 'DESC',
                'no_found_rows' => true          //No pagination needed
            );

//Do the filtering and retrieve all projects with current service
$projects = get_posts( $module_args );
</code>```

but then I get this result:

```<code>Yacht 2011
Vasastan 2008
Ulrikagatan 2008
Thailand 2010 (?)
Strandvägen 2007
</code>```

but it should be:

```<code>Yacht 2011
Thailand 2010
Ulrikagatan 2008
Vasastan 2008
Strandvägen 2007
</code>```

答:
In Mysql

You could use  a conversion in int for the last four char   and after this for title

```<code>Order by  CONVERT(right(post_title, 4),UNSIGNED INTEGER) , post_title
</code>```

Body:
I'm having an issue how to sort a title in Wordpress. If I just know how I would solve this in MySQL it would be great. (If someone has an answer specific for wordpress that would be a lot easier for me though)

I have a database where the title (one field in the database-table) is called post_title. The title stores name AND year with a space between

eg.

Sweden 2017
Sweden 2016
Norway 2018
Norway 2019

I want to sort above like this: (descending by year and ascending by name)

Norway 2019
Norway 2018
Sweden 2017
Sweden 2016

UPDATE:
I've tried with Wordpress-builtin sorting with WP_Query:

$module_args = array(
                'posts_per_page' => -1,
                'post_type' => 'project',
                'include_children' => false,
                'orderby' => 'title',
                'order' => 'DESC',
                'no_found_rows' => true          //No pagination needed
            );

//Do the filtering and retrieve all projects with current service
$projects = get_posts( $module_args );

but then I get this result:

Yacht 2011
Vasastan 2008
Ulrikagatan 2008
Thailand 2010 (?)
Strandvägen 2007

but it should be:

Yacht 2011
Thailand 2010
Ulrikagatan 2008
Vasastan 2008
Strandvägen 2007

Body:
In Mysql

You could use  a conversion in int for the last four char   and after this for title

Order by  CONVERT(right(post_title, 4),UNSIGNED INTEGER) , post_title


问:
How to use ApprovalTests for approving logs
I want to use Approval Tests to verify log output. What is the preferred way to deal with dynamic content of the log text, e.g. time stamps? The included FileApprover always compares the files for exact equality.

答:
There are a couple solutions to this. Here they are in order of preference:

Don't log dynamic content during the test.

Fake dynamic content during the test so the output is consistent.

Scrub the log file before comparing. This usually looks like:

```<code>ScrubFile("log.txt", "log_scrubbed.txt", new DateScrubber(), new GuidScrubber())
</code>```

Body:
There are a couple solutions to this. Here they are in order of preference:

Don't log dynamic content during the test.

Fake dynamic content during the test so the output is consistent.

Scrub the log file before comparing. This usually looks like:

ScrubFile("log.txt", "log_scrubbed.txt", new DateScrubber(), new GuidScrubber())


问:
python 'x days ago' to datetime
I have strings that show a date in the following format:

```<code>x minutes/hours/days/months/years ago
</code>```

I need to parse that to a datetime using python.

It seems dateutil can't do it.

Is there a way to do it?

答:
Since your arguments are something like 2 days ago, 3 months ago, 2 years ago. The function below could be of help in getting the exact date for the arguments. You first need to import the following date utils

```<code>import datetime
from dateutil.relativedelta import relativedelta
</code>```

Then implement the function below

```<code>def get_past_date(str_days_ago):
    TODAY = datetime.date.today()
    splitted = str_days_ago.split()
    if len(splitted) == 1 and splitted[0].lower() == 'today':
        return str(TODAY.isoformat())
    elif len(splitted) == 1 and splitted[0].lower() == 'yesterday':
        date = TODAY - relativedelta(days=1)
        return str(date.isoformat())
    elif splitted[1].lower() in ['hour', 'hours', 'hr', 'hrs', 'h']:
        date = datetime.datetime.now() - relativedelta(hours=int(splitted[0]))
        return str(date.date().isoformat())
    elif splitted[1].lower() in ['day', 'days', 'd']:
        date = TODAY - relativedelta(days=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['wk', 'wks', 'week', 'weeks', 'w']:
        date = TODAY - relativedelta(weeks=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['mon', 'mons', 'month', 'months', 'm']:
        date = TODAY - relativedelta(months=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['yrs', 'yr', 'years', 'year', 'y']:
        date = TODAY - relativedelta(years=int(splitted[0]))
        return str(date.isoformat())
    else:
        return "Wrong Argument format"
</code>```

You can then call the function like this:

```<code>print get_past_date('5 hours ago')
print get_past_date('yesterday')
print get_past_date('3 days ago')
print get_past_date('4 months ago')
print get_past_date('2 years ago')
print get_past_date('today')
</code>```

Title: python 'x days ago' to datetime

Body:
I have strings that show a date in the following format:

x minutes/hours/days/months/years ago

I need to parse that to a datetime using python.

It seems dateutil can't do it.

Is there a way to do it?

Body:
Since your arguments are something like 2 days ago, 3 months ago, 2 years ago. The function below could be of help in getting the exact date for the arguments. You first need to import the following date utils

import datetime
from dateutil.relativedelta import relativedelta

Then implement the function below

def get_past_date(str_days_ago):
    TODAY = datetime.date.today()
    splitted = str_days_ago.split()
    if len(splitted) == 1 and splitted[0].lower() == 'today':
        return str(TODAY.isoformat())
    elif len(splitted) == 1 and splitted[0].lower() == 'yesterday':
        date = TODAY - relativedelta(days=1)
        return str(date.isoformat())
    elif splitted[1].lower() in ['hour', 'hours', 'hr', 'hrs', 'h']:
        date = datetime.datetime.now() - relativedelta(hours=int(splitted[0]))
        return str(date.date().isoformat())
    elif splitted[1].lower() in ['day', 'days', 'd']:
        date = TODAY - relativedelta(days=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['wk', 'wks', 'week', 'weeks', 'w']:
        date = TODAY - relativedelta(weeks=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['mon', 'mons', 'month', 'months', 'm']:
        date = TODAY - relativedelta(months=int(splitted[0]))
        return str(date.isoformat())
    elif splitted[1].lower() in ['yrs', 'yr', 'years', 'year', 'y']:
        date = TODAY - relativedelta(years=int(splitted[0]))
        return str(date.isoformat())
    else:
        return "Wrong Argument format"

You can then call the function like this:

print get_past_date('5 hours ago')
print get_past_date('yesterday')
print get_past_date('3 days ago')
print get_past_date('4 months ago')
print get_past_date('2 years ago')
print get_past_date('today')


问:
Android custom camera photos not shown in gallery
I'm creating custom android camera layout.

I've used information from http://developer.android.com/guide/topics/media/camera.html#basics. Everithing works fine except one thing.

The photo is not shown in the phone's gallery. The metod is:

```<code>private Camera.PictureCallback cameraCallback = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFile = getOutputMediaFile();
        if (pictureFile == null){
            Log.d(Values.APPLICATION_TAG + ACTIVITY_TAG, "Error creating media file, check storage permissions: ");
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.flush();
            fos.close();
            createPhotoAndShowPreview(Uri.fromFile(pictureFile));
        } catch (FileNotFoundException e) {
            Log.d(Values.APPLICATION_TAG + ACTIVITY_TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(Values.APPLICATION_TAG + ACTIVITY_TAG, "Error accessing file: " + e.getMessage());
        }
    }
};

private static File getOutputMediaFile(){

    File galleryDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "MyCameraApp");
    if (!galleryDir.exists()) {
        if (!galleryDir.mkdir())
        {
            Log.d(Values.APPLICATION_TAG, "failed to create directory");
            return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    mediaFile = new File(galleryDir.getPath() + File.separator +
            "gfranq_"+ timeStamp + ".jpg");

    return mediaFile;
}
</code>```

Method createPhotoAndShowPreview(Uri.fromFile(pictureFile)); works fine, the file exists during runtime and I can use it, but when I exit the app there is no file in the gallery. I used a file manager to check if the file is deleted, but its not deleted, it exists after exiting the application, but the system doesn't recognize that it is an image.

Update: The photos appered in the gallery after I connected my phone to my pc. But new photos still don't appear in the gallery untill I connect and disconnect my phone to pc. rebooting the phone has the same effect.

答:
```<code>MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                    Log.i("ExternalStorage", "Scanned " + path + ":");
                    Log.i("ExternalStorage", "-> uri=" + uri);
                }
            });
</code>```

Body:
I'm creating custom android camera layout.

I've used information from http://developer.android.com/guide/topics/media/camera.html#basics. Everithing works fine except one thing.

The photo is not shown in the phone's gallery. The metod is:

private Camera.PictureCallback cameraCallback = new Camera.PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {

        File pictureFile = getOutputMediaFile();
        if (pictureFile == null){
            Log.d(Values.APPLICATION_TAG + ACTIVITY_TAG, "Error creating media file, check storage permissions: ");
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.flush();
            fos.close();
            createPhotoAndShowPreview(Uri.fromFile(pictureFile));
        } catch (FileNotFoundException e) {
            Log.d(Values.APPLICATION_TAG + ACTIVITY_TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(Values.APPLICATION_TAG + ACTIVITY_TAG, "Error accessing file: " + e.getMessage());
        }
    }
};

private static File getOutputMediaFile(){

    File galleryDir = new File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "MyCameraApp");
    if (!galleryDir.exists()) {
        if (!galleryDir.mkdir())
        {
            Log.d(Values.APPLICATION_TAG, "failed to create directory");
            return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    mediaFile = new File(galleryDir.getPath() + File.separator +
            "gfranq_"+ timeStamp + ".jpg");

    return mediaFile;
}

Method createPhotoAndShowPreview(Uri.fromFile(pictureFile)); works fine, the file exists during runtime and I can use it, but when I exit the app there is no file in the gallery. I used a file manager to check if the file is deleted, but its not deleted, it exists after exiting the application, but the system doesn't recognize that it is an image.

Update: The photos appered in the gallery after I connected my phone to my pc. But new photos still don't appear in the gallery untill I connect and disconnect my phone to pc. rebooting the phone has the same effect.


问:
Iterator function for IDisposable items
Suppose I want to create an iterator function that yields IDisposable items.

```<code>IEnumerable<Disposable> GetItems()
{
    yield return new Disposable();
    yield return new Disposable();
}
</code>```

This does not seem ideal for the client code:

```<code>foreach (var item in source.GetItems())
{
    using (item)
    {
        // ...
    }
}
</code>```

Intuitively, the using comes too late. Things could get moved around. One could accidentally insert code between the foreach and the using. Not ideal.

I am looking for a better alternative!

One approach that comes to mind is creating the following API instead of an iterator function:

```<code>// Client
while (source.HasItem)
{
    using (var item = source.GetNextItem())
    {
        // ...
    }
}

// Source
private IEnumerator<Disposable> Enumerator { get; }
private bool? _hasItem;
bool HasItem
{
    get
    {
        if (this._hasItem == null) this._hasItem = this.Enumerator.MoveNext();
        return this._hasItem;
    }
}
Disposable GetNextItem()
{
    if (!this.HasItem) throw new IndexOutOfBoundsException();
    this._hasItem = null;
    return this.Enumerator.Current;
}
</code>```

But now it seems that the source has to become IDisposable! How else would it know when to dispose Enumerator? That can be an unpleasant side-effect.

I am looking for an alternative that feels solid in the client, but that keeps the source from becoming IDisposable too.

Edit - Clarification: I forgot to mention that some of the content that we need comes from an iterator. Concretely, imagine that we are returning IDbCommand instances, which are IDisposable. Before returning each command, we need to populate it with some query data, which in turn comes from a simple iterator method.

答:
The iterator function itself can take responsibility for placing a using (i.e. disposing the current item when the next is requested).

```<code>IEnumerable<Disposable> GetItems()
{
    // Assumming CreateItems() is an iterator as well
    foreach (var item in this.CreateItems())
        using (item) yield return item;
}
</code>```

As a result, we will essentially have a streaming-only iterator. Methods like ToList() become meaningless, because only one item is usable at a time.

Unfortunately, this does create room for error.

Title: Iterator function for IDisposable items

Body:
Suppose I want to create an iterator function that yields IDisposable items.

IEnumerable<Disposable> GetItems()
{
    yield return new Disposable();
    yield return new Disposable();
}

This does not seem ideal for the client code:

foreach (var item in source.GetItems())
{
    using (item)
    {
        // ...
    }
}

Intuitively, the using comes too late. Things could get moved around. One could accidentally insert code between the foreach and the using. Not ideal.

I am looking for a better alternative!

One approach that comes to mind is creating the following API instead of an iterator function:

// Client
while (source.HasItem)
{
    using (var item = source.GetNextItem())
    {
        // ...
    }
}

// Source
private IEnumerator<Disposable> Enumerator { get; }
private bool? _hasItem;
bool HasItem
{
    get
    {
        if (this._hasItem == null) this._hasItem = this.Enumerator.MoveNext();
        return this._hasItem;
    }
}
Disposable GetNextItem()
{
    if (!this.HasItem) throw new IndexOutOfBoundsException();
    this._hasItem = null;
    return this.Enumerator.Current;
}

But now it seems that the source has to become IDisposable! How else would it know when to dispose Enumerator? That can be an unpleasant side-effect.

I am looking for an alternative that feels solid in the client, but that keeps the source from becoming IDisposable too.

Edit - Clarification: I forgot to mention that some of the content that we need comes from an iterator. Concretely, imagine that we are returning IDbCommand instances, which are IDisposable. Before returning each command, we need to populate it with some query data, which in turn comes from a simple iterator method.

Body:
The iterator function itself can take responsibility for placing a using (i.e. disposing the current item when the next is requested).

IEnumerable<Disposable> GetItems()
{
    // Assumming CreateItems() is an iterator as well
    foreach (var item in this.CreateItems())
        using (item) yield return item;
}

As a result, we will essentially have a streaming-only iterator. Methods like ToList() become meaningless, because only one item is usable at a time.

Unfortunately, this does create room for error.


问:
QT configure with xp support error
I want to build(with MinGW 5.3.0 32bit) my QT(qt-everywhere-opensource-src-5.8.0) with Xp support

```<code>configure -target xp -static -qmake -opensource -nomake examples -no-opengl -platform win32-g++ -openssl-linked -I C:\OpenSSL-Win32\include -L C:\OpenSSL-Win32\lib OPENSSL_LIBS="-llibeay32 -lssleay32 -lgdi32"
</code>```

The error is:

```<code>ERROR: Unknown command line option '-target'.
Qmake failed, return code 3
</code>```

答: Qt 5.6 LTS supports Windows XP until March 2019. Since Qt 5.7 release Qt supports Windows 7 and upwards.

Title: QT configure with xp support error

Body:
I want to build(with MinGW 5.3.0 32bit) my QT(qt-everywhere-opensource-src-5.8.0) with Xp support

configure -target xp -static -qmake -opensource -nomake examples -no-opengl -platform win32-g++ -openssl-linked -I C:\OpenSSL-Win32\include -L C:\OpenSSL-Win32\lib OPENSSL_LIBS="-llibeay32 -lssleay32 -lgdi32"

The error is:

ERROR: Unknown command line option '-target'.
Qmake failed, return code 3


问:
Use vs Include in PHP
I'm trying to get my head around PHP namespaces and testing with PHPUnit.

These tests from Codewars pass when I run phpunit test.php in the command line on Windows:

```<code><?php
require 'solution.php';
use PHPUnit\Framework\TestCase;

class myTests extends TestCase {
  public function testExamples() {
        $this->assertEquals(pair_sum([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10),6);
        $this->assertEquals(pair_sum([1,2,3,1],3),1);
        $this->assertEquals(pair_sum([1,3,2,2],4),2);
        $this->assertEquals(pair_sum([1],4),false);
        $this->assertEquals(pair_sum([2,3,10,-5],5),2);
  }
}
</code>```

However, when I comment out use PHPUnit\Framework\TestCase; I get Class 'TestCase' not found which makes sense since there is no reference to the needed classes/functions.

What's confusing me though is that lots of answers here on SO about namespacing claim that the use keyword is NOT a substitute for include/require and that the classes still need to be included/autoloaded(?).

I'm not using any autoloading here - just a solution.php file and the tests above in a test.php file.

Can someone please explain what I'm missing here? How come the tests work without  any explicit including of the PHPunit functionality?

I should mention that I have PHPUnit installed globally via Composer.

答:
To make namespaces clear (ignore load of the class file here)

So in one php-file:

```<code>namespace xyz {
  class a {}
  class b {}
}
namespace abc {
  use xyz\a;
  new a();
  new \xyz\b();
  class b extends a {}
}
namespace {
 use abc\b as aa;
 use xyz\b as bb;
 new bb;
 new aa;
}
</code>```

Namespace are for preventing name-conflicts!

Title: Use vs Include in PHP

Body:
I'm trying to get my head around PHP namespaces and testing with PHPUnit.

These tests from Codewars pass when I run phpunit test.php in the command line on Windows:

<?php
require 'solution.php';
use PHPUnit\Framework\TestCase;

class myTests extends TestCase {
  public function testExamples() {
        $this->assertEquals(pair_sum([1,9,2,8,3,7,4,6,5,5,13,14,11,13,-1],10),6);
        $this->assertEquals(pair_sum([1,2,3,1],3),1);
        $this->assertEquals(pair_sum([1,3,2,2],4),2);
        $this->assertEquals(pair_sum([1],4),false);
        $this->assertEquals(pair_sum([2,3,10,-5],5),2);
  }
}

However, when I comment out use PHPUnit\Framework\TestCase; I get Class 'TestCase' not found which makes sense since there is no reference to the needed classes/functions.

What's confusing me though is that lots of answers here on SO about namespacing claim that the use keyword is NOT a substitute for include/require and that the classes still need to be included/autoloaded(?).

I'm not using any autoloading here - just a solution.php file and the tests above in a test.php file.

Can someone please explain what I'm missing here? How come the tests work without  any explicit including of the PHPunit functionality?

I should mention that I have PHPUnit installed globally via Composer.

Body:
To make namespaces clear (ignore load of the class file here)

So in one php-file:

namespace xyz {
  class a {}
  class b {}
}
namespace abc {
  use xyz\a;
  new a();
  new \xyz\b();
  class b extends a {}
}
namespace {
 use abc\b as aa;
 use xyz\b as bb;
 new bb;
 new aa;
}

Namespace are for preventing name-conflicts!


问:
MvcContrib.Castle Meduim Trust & Signed Assemblies
I have a class library which references MvcContrib.Castle. My Assembly is signed, but will not compile

error

Error  129 Assembly generation failed -- Referenced assembly 'MvcContrib.Castle' does not have a strong name

I have tried added to the AssemblyInfo.cs

```<code>using System.Security;
[assembly: AllowPartiallyTrustedCallers]
</code>```

the issue persists.

I have tried the following too: http://paulwideman.com/softwareartist/tag/medium-trust/

Anyone know what todo?

if it helps im using .net 4

many thanks in advance

答: You can sing MvcContrib dlls without rebuilding them, for example with this tool: http://signer.codeplex.com/</p>

Body:
I have a class library which references MvcContrib.Castle. My Assembly is signed, but will not compile

error

Error  129 Assembly generation failed -- Referenced assembly 'MvcContrib.Castle' does not have a strong name

I have tried added to the AssemblyInfo.cs

using System.Security;
[assembly: AllowPartiallyTrustedCallers]

the issue persists.

I have tried the following too: http://paulwideman.com/softwareartist/tag/medium-trust/

Anyone know what todo?

if it helps im using .net 4

many thanks in advance


答:
You could do this with PHP:

```<code>$titles = [
  'Sweden 2017',
  'Sweden 2016',
  'Norway 2018',
  'Norway 2019',
];

usort($titles, function($a, $b) {
  $asplit = preg_split('/\s/', $a);
  $bsplit = preg_split('/\s/', $b);

  $strcmp = strcmp($asplit[0], $bsplit[0]);

  if ( $strcmp ) {
    return $strcmp;
  }
  else {
    return $bsplit[1] - $asplit[1];
  }
});

// print_r($titles) yields:
//
// Array
// (
//     [0] => Norway 2019
//     [1] => Norway 2018
//     [2] => Sweden 2017
//     [3] => Sweden 2016
// )
</code>```

Edit: fixed typos, now it works

Title: Sort descending based on part of a title in Wordpress?

Body:
You could do this with PHP:

$titles = [
  'Sweden 2017',
  'Sweden 2016',
  'Norway 2018',
  'Norway 2019',
];

usort($titles, function($a, $b) {
  $asplit = preg_split('/\s/', $a);
  $bsplit = preg_split('/\s/', $b);

  $strcmp = strcmp($asplit[0], $bsplit[0]);

  if ( $strcmp ) {
    return $strcmp;
  }
  else {
    return $bsplit[1] - $asplit[1];
  }
});

// print_r($titles) yields:
//
// Array
// (
//     [0] => Norway 2019
//     [1] => Norway 2018
//     [2] => Sweden 2017
//     [3] => Sweden 2016
// )

Edit: fixed typos, now it works


答: Instead of using a single = use a double ==. Currently you set the lastName equal to undefined, by using two equal signs you are comparing. So change to this. Also undefined doesn't need to be in apostrophes.

Title: In Javascript console.log I am not getting the result

Body:
I want console.log to print only firstname if lastname was undefined, instead I get firstname + undefined on the console. What could I change in the code so it only gives me firstname or lastname if one of them is undefined without printing the word 'undefined' in the console, and if both are defined to print them both. This is the code I am trying:

    document.getElementById("runButton").onclick = function run() {
        var lastName = "arm";
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName = 'undefined') {
                console.log("Hello, " + firstName + "!");
            } else if (firstName = 'undefiend') {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName + " " + lastName);
    };


问:
Adobe Brackets extension that enables code-folding for Ruby/Chef dev?
I love Adobe Brackets and use it for everything except my Chef dev. The main reason being that I can't find anything that enables code folding for Ruby. Does anyone know of a good extension? Cheers.</p>

答:
did you try Atom.io?
It's very powerfull editor with planty of plugins and it has code folding by default for each language.</p>


问:
woocommerce get_woocommerce_currency_symbol()
I am developing an extension for woocommerce WordPress plugin.

I would like to display the currency symbol outside of the loop in a custom function

I have the following:

```<code>function my_function( ) {
   global  $woocommerce;
   echo get_woocommerce_currency_symbol();
}
</code>```

I am not sure why but this doesn't output the symbol? Am I missing something?

答:
```<code>get_option('woocommerce_currency')
</code>```

will help you lot.

Body:
I am developing an extension for woocommerce WordPress plugin.

I would like to display the currency symbol outside of the loop in a custom function

I have the following:

function my_function( ) {
   global  $woocommerce;
   echo get_woocommerce_currency_symbol();
}

I am not sure why but this doesn't output the symbol? Am I missing something?

Body:
get_option('woocommerce_currency')

will help you lot.


问:
how to cast up to super class when there is an override function in the sub class
A super-class Car and a sub-class Jaguar was created. The function info() -> Void in the sub-class overrided the super-class' function. A instance named theAuto of type Jaguar had been created.

Problem:

Seems I cannot up casts the theAuto to the type of Car, please see the code snippet and its comments

```<code>class Car {
        func info() {
                print("You've got a car")
        }
}

class Jaguar : Car {
       override func info() {
               print("You've got a Jaguar")
       }
}

let theAuto = Jaguar()
theAuto.info() // --> You've got a Jaguar
let auto = theAuto as Car // casting but seems not working
auto.info() // --> You've got a Jaguar
print(type(of: auto)) // fail to casting
</code>```

Question:

I think I didn't fully understand the concept of casting together with override scenario. Why I cannot make the up casting? Is the override action limited my upper casting?

many thanks for your help and time

答:
Because you're overriding the method in a subclass, you're getting dynamic dispatch. The method implementation to call will be based on the dynamic type of the instance that it's called on. Upcasting a Jaguar to a Car only changes the static type of the instance – the dynamic type is still a Jaguar, for that's the type of instance you created.

Therefore upcasting has no bearing whatsoever on the dynamic dispatch of a method – nor should it, as the whole point of dynamic dispatch is to ensure that the correct method implementation for the given instance is called no matter what it's statically typed as.

The kind of behaviour you're expecting is static dispatch – the compiler chooses the implementation to call based on the static type of the instance. This is commonly achieved by overloading (rather than overriding) functions.

For example, an overloaded static method:

```<code>class Car {
    static func info(for car: Car) {
        print("You've got a Car")
    }
}

class Jaguar : Car {
    static func info(for jaguar: Jaguar) {
        print("You've got a Jaguar")
    }
}

let jaguar = Jaguar()
Jaguar.info(for: jaguar) // You've got a Jaguar
Car.info(for: jaguar)    // You've got a Car

let car = jaguar as Car
Jaguar.info(for: car)    // You've got a Car
</code>```

Here, the compiler resolves which implementation of info(for:) to call based on the static types of what it's being called on and the arguments being passed. If it's either called on Car, or the argument passed is statically typed as a Car, only Car's overload can possibly be statically dispatched to.

Another example of static dispatch is with a protocol extension, where the method isn't a protocol requirement (as making it a requirement gives it dynamic dispatch).

```<code>protocol Car {}

extension Car {
    func info() {
        print("You've got a Car")
    }
}

class Jaguar : Car {
    func info() {
        print("You've got a Jaguar")
    }
}

let jaguar = Jaguar()
jaguar.info() // You've got a Jaguar

let car = jaguar as Car
car.info()    // You've got a Car
</code>```

Here, the compiler resolves which implementation of info() to call solely based on the static type of the instance that it's called on.

Body:
A super-class Car and a sub-class Jaguar was created. The function info() -> Void in the sub-class overrided the super-class' function. A instance named theAuto of type Jaguar had been created.

Problem:

Seems I cannot up casts the theAuto to the type of Car, please see the code snippet and its comments

class Car {
        func info() {
                print("You've got a car")
        }
}

class Jaguar : Car {
       override func info() {
               print("You've got a Jaguar")
       }
}

let theAuto = Jaguar()
theAuto.info() // --> You've got a Jaguar
let auto = theAuto as Car // casting but seems not working
auto.info() // --> You've got a Jaguar
print(type(of: auto)) // fail to casting

Question:

I think I didn't fully understand the concept of casting together with override scenario. Why I cannot make the up casting? Is the override action limited my upper casting?

many thanks for your help and time

Body:
Because you're overriding the method in a subclass, you're getting dynamic dispatch. The method implementation to call will be based on the dynamic type of the instance that it's called on. Upcasting a Jaguar to a Car only changes the static type of the instance – the dynamic type is still a Jaguar, for that's the type of instance you created.

Therefore upcasting has no bearing whatsoever on the dynamic dispatch of a method – nor should it, as the whole point of dynamic dispatch is to ensure that the correct method implementation for the given instance is called no matter what it's statically typed as.

The kind of behaviour you're expecting is static dispatch – the compiler chooses the implementation to call based on the static type of the instance. This is commonly achieved by overloading (rather than overriding) functions.

For example, an overloaded static method:

class Car {
    static func info(for car: Car) {
        print("You've got a Car")
    }
}

class Jaguar : Car {
    static func info(for jaguar: Jaguar) {
        print("You've got a Jaguar")
    }
}

let jaguar = Jaguar()
Jaguar.info(for: jaguar) // You've got a Jaguar
Car.info(for: jaguar)    // You've got a Car

let car = jaguar as Car
Jaguar.info(for: car)    // You've got a Car

Here, the compiler resolves which implementation of info(for:) to call based on the static types of what it's being called on and the arguments being passed. If it's either called on Car, or the argument passed is statically typed as a Car, only Car's overload can possibly be statically dispatched to.

Another example of static dispatch is with a protocol extension, where the method isn't a protocol requirement (as making it a requirement gives it dynamic dispatch).

protocol Car {}

extension Car {
    func info() {
        print("You've got a Car")
    }
}

class Jaguar : Car {
    func info() {
        print("You've got a Jaguar")
    }
}

let jaguar = Jaguar()
jaguar.info() // You've got a Jaguar

let car = jaguar as Car
car.info()    // You've got a Car

Here, the compiler resolves which implementation of info() to call solely based on the static type of the instance that it's called on.


问:
Why this url pattern is not working?
```<code>from views import login
from django.conf.urls.defaults import *

urlpatterns = patterns('',
  ***  (r'([a-zA-Z0-9]+)/login/$', login, name='login'),

)
</code>```

showing me the syntax error in line ***.

http://localhost:8000/{{ slug }}/login/ is the action url in form. I want to make it using Django { % url slug login % } tag. But it also not working.

答:
You need to use the url() function if you're using the name keyword:

```<code>url(r'([a-zA-Z0-9]+)/login/$', login, name='login'),
</code>```

And the order of parameters to the {% url %} tag has the url name first. So it should be:

```<code>{% url login slug %}
</code>```

Title: Why this url pattern is not working?

Body:
from views import login
from django.conf.urls.defaults import *

urlpatterns = patterns('',
  ***  (r'([a-zA-Z0-9]+)/login/$', login, name='login'),

)

showing me the syntax error in line ***.

http://localhost:8000/{{ slug }}/login/ is the action url in form. I want to make it using Django { % url slug login % } tag. But it also not working.

Body:
You need to use the url() function if you're using the name keyword:

url(r'([a-zA-Z0-9]+)/login/$', login, name='login'),

And the order of parameters to the {% url %} tag has the url name first. So it should be:

{% url login slug %}


问:
Wordpress updated from 4.1->4.7, got phpmailerException when resetting password
We updated Wordpress from 4.1.something to 4.7.3. Everything works, except the mail that contains the new password when a user resets the password. The password is still reset, but no mail is obtained with the reset password, making it impossible to log in. As far as I know, this is the only mail that fails, registration mails and such still works.

There shouldn't be anything wrong with the code, it has worked for years. But something was clearly messed up when updating. When trying to send the mail, the following error occurs.

```<code>PHP Fatal error:  Uncaught exception 'phpmailerException' with message 'Invalid address:  (setFrom) service' in /var/www/site-adress/public_html/wp/wp-includes/class-phpmailer.php:1023
Stack trace:
#0 /var/www/site-adress/public_html/wp/wp-includes/pluggable.php(352): PHPMailer->setFrom('service', 'WordPress', false)
#1 /var/www/site-adress/public_html/wp-content/themes/site/functions.php(320): wp_mail('dummy.mail...', 'Site: passwor...', 'Your new passwo...', 'From: service')
#2 [internal function]: {closure}('')
#3 /var/www/site-adress/public_html/wp/wp-includes/class-wp-hook.php(298): call_user_func_array(Object(Closure), Array)
#4 /var/www/site-adress/public_html/wp/wp-includes/class-wp-hook.php(323): WP_Hook->apply_filters('', Array)
 #5 /var/www/site-adress/public_html/wp/wp-includes/plugin.php(453): WP_Hook->do_action(Array)
#6 /var/www/site-adress/public_html/wp/wp-admin/admin-ajax.php(101): do_action in /var/www/site-adress/public_html/wp/wp-includes/class-phpmailer.php on line 1023
</code>```

Does anyone know how this should be solved? What does this information mean? Where does the problem lie?

Thank you, ahead of time.

答: I had to disable plugins for it to work</p>

Body:
We updated Wordpress from 4.1.something to 4.7.3. Everything works, except the mail that contains the new password when a user resets the password. The password is still reset, but no mail is obtained with the reset password, making it impossible to log in. As far as I know, this is the only mail that fails, registration mails and such still works.

There shouldn't be anything wrong with the code, it has worked for years. But something was clearly messed up when updating. When trying to send the mail, the following error occurs.

PHP Fatal error:  Uncaught exception 'phpmailerException' with message 'Invalid address:  (setFrom) service' in /var/www/site-adress/public_html/wp/wp-includes/class-phpmailer.php:1023
Stack trace:
#0 /var/www/site-adress/public_html/wp/wp-includes/pluggable.php(352): PHPMailer->setFrom('service', 'WordPress', false)
#1 /var/www/site-adress/public_html/wp-content/themes/site/functions.php(320): wp_mail('dummy.mail...', 'Site: passwor...', 'Your new passwo...', 'From: service')
#2 [internal function]: {closure}('')
#3 /var/www/site-adress/public_html/wp/wp-includes/class-wp-hook.php(298): call_user_func_array(Object(Closure), Array)
#4 /var/www/site-adress/public_html/wp/wp-includes/class-wp-hook.php(323): WP_Hook->apply_filters('', Array)
 #5 /var/www/site-adress/public_html/wp/wp-includes/plugin.php(453): WP_Hook->do_action(Array)
#6 /var/www/site-adress/public_html/wp/wp-admin/admin-ajax.php(101): do_action in /var/www/site-adress/public_html/wp/wp-includes/class-phpmailer.php on line 1023

Does anyone know how this should be solved? What does this information mean? Where does the problem lie?

Thank you, ahead of time.

Body: I had to disable plugins for it to work