问:
MySQL | Selecting data from another table
I am trying to use a foreign key in order to setup a system where I can refer to this table to get a friendly name, rather than using the id in the api.

Currently, I have it set up like this...

```<code>| id | friendly_name
| 1  | starters
| 2  | desserts
</code>```

And I have another table like this...

```<code>| id | type | price | desc
| 1  | 1    | 3.99  | This is the desc
</code>```

I want to use the type to refer to in the api so i have /api/menu/{id}/{type} but I want it to be written like /api/menu/1/starters.

I am currently trying this code but it is returning every item in the database

```<code>SELECT
   m.item,
   m.description,
   m.price
FROM
   menu m,
   types t
WHERE
    m.restaurant_id = :restaurant_id
AND
    t.id = :type
</code>```

答:
You need to add a ON clause to your join and you need to select by type.friendly_namenot type.id.

```<code>SELECT
   m.item,
   m.description,
   m.price
FROM
   menu m INNER JOIN types t ON m.type = t.id
WHERE
   m.restaurant_id = :restaurant_id
   AND
   t.friendly_name= :type
</code>```

Body:
I am trying to use a foreign key in order to setup a system where I can refer to this table to get a friendly name, rather than using the id in the api.

Currently, I have it set up like this...

| id | friendly_name
| 1  | starters
| 2  | desserts

And I have another table like this...

| id | type | price | desc
| 1  | 1    | 3.99  | This is the desc

I want to use the type to refer to in the api so i have /api/menu/{id}/{type} but I want it to be written like /api/menu/1/starters.

I am currently trying this code but it is returning every item in the database

SELECT
   m.item,
   m.description,
   m.price
FROM
   menu m,
   types t
WHERE
    m.restaurant_id = :restaurant_id
AND
    t.id = :type

Body:
You need to add a ON clause to your join and you need to select by type.friendly_namenot type.id.

SELECT
   m.item,
   m.description,
   m.price
FROM
   menu m INNER JOIN types t ON m.type = t.id
WHERE
   m.restaurant_id = :restaurant_id
   AND
   t.friendly_name= :type


来源: stackexchange

问:
FactoyGirl: before(:create) actions not being recognized
I am attempting to create my FactoryGirl factories such that when I call FactoryGirl.create(:model_a), any dependency for model_a are created and assigned to that model_a factory. However, for some reason my method is not working and I can't quite figure out why.

In my factory file this is what I have:

```<code>FactoryGirl.define do
    factory :model_a do
        before(:create) do
            FactoryGirl.create(:model_b)
        end

        model_b {ModelB.first}
    end
end
</code>```

Now when I run FactoryGirl.create(:model_a) I would expect this to first create the factory model_b (because of the before(:create) call) and then go back to creating the factory model_a and assigning the factory model_b to the model_b relationshionship for model_a

But instead, I am getting the error model_b must exist, model_b cannot be blank.

Why is the factory model_b not being created so that I can use it?

答:
You need to set the association between model_a and model_b inside your before(:create) block. For example:

```<code>FactoryGirl.define do
  factory :model_a do
    # add model_a attributes as needed

    before(:create) do |model_a|
      model_a.model_b = ModelB.first || FactoryGirl.create(:model_b)
    end
  end
end
</code>```

Or, per OP's comment:

```<code>factory :model_a do
  # add model_a attributes as needed
  model_b { ModelB.first || FactoryGirl.create(:model_b) }
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to create my FactoryGirl factories such that when I call FactoryGirl.create(:model_a), any dependency for model_a are created and assigned to that model_a factory. However, for some reason my method is not working and I can't quite figure out why.

In my factory file this is what I have:

FactoryGirl.define do
    factory :model_a do
        before(:create) do
            FactoryGirl.create(:model_b)
        end

        model_b {ModelB.first}
    end
end

Now when I run FactoryGirl.create(:model_a) I would expect this to first create the factory model_b (because of the before(:create) call) and then go back to creating the factory model_a and assigning the factory model_b to the model_b relationshionship for model_a

But instead, I am getting the error model_b must exist, model_b cannot be blank.

Why is the factory model_b not being created so that I can use it?

Body:
You need to set the association between model_a and model_b inside your before(:create) block. For example:

FactoryGirl.define do
  factory :model_a do
    # add model_a attributes as needed

    before(:create) do |model_a|
      model_a.model_b = ModelB.first || FactoryGirl.create(:model_b)
    end
  end
end

Or, per OP's comment:

factory :model_a do
  # add model_a attributes as needed
  model_b { ModelB.first || FactoryGirl.create(:model_b) }
end


问:
Problem while hosting codeigniter project
After hosting the codeigniter project, while I run it I shows me 404 number error.
 please tell me what change I should do?</p>

答:
edit your config file </p>

```<code>$config['base_url'] = "http://mysite.com/";
</code>```

ContentLicense: CC BY-SA 2.5

Body:
edit your config file

$config['base_url'] = "http://mysite.com/";


问:
Filter foreach array based on value inside this array
Hello I have the following array:

$tourcontent

and the following foreach:

```<code>foreach($tourcontent as $set)
</code>```

How I can limit the result of the output of this foreach to be limited to only where in the sub array categories[] contains value of 5 where $tourcontent[]['info']['categories'][] = 5 ?

答:
You could use in_array.

```<code>foreach($tourcontent as $set) {
    if (in_array(5, $set['info']['categories'])) {
        // do stuff
    }
}
</code>```

This will only "do stuff" to the $sets that contain 5 in their ['info']['categories'] arrays.

Body:
Hello I have the following array:

$tourcontent

and the following foreach:

foreach($tourcontent as $set)

How I can limit the result of the output of this foreach to be limited to only where in the sub array categories[] contains value of 5 where $tourcontent[]['info']['categories'][] = 5 ?

Body:
You could use in_array.

foreach($tourcontent as $set) {
    if (in_array(5, $set['info']['categories'])) {
        // do stuff
    }
}

This will only "do stuff" to the $sets that contain 5 in their ['info']['categories'] arrays.


问:
Unable to click on a link after switching to other browser window in Selenium Webdriver java
I am try to click on a link on a newly opened browser window after clicking on a link on main window But webdriver is unable to find the element on the new opened window.

Below is my code which I am using to switch on the other window and then performing an action on it.

```<code>public void test() throws Exception{
    driver.findElement(By.xpath("//img[@alt='Calender']")).click();
    String Parent_Window =driver.getWindowHandle();

    for (String Child_Window : driver.getWindowHandles()) {
      driver.switchTo().window(Child_Window);
      driver.findElement(By.xpath("//div[@class='pbBody']//table[@class='list']//tr[@class='dataRow even first']//a")).click();
      // Webdriver is not able to click on the above link and it fails at this step
    }
    driver.switchTo().window(Parent_Window);
}
</code>```

Please help me on this why wedrivber is unable to find the element on the new browser window after switching.Thanks!

答:
try this, i was having serious issue with windowhandles, but this one seems better.</p>

```<code>String parentWindowHandler = driver.getWindowHandle();
        String subWindowHandler = null;

        Set<String> handles = driver.getWindowHandles();
        Iterator<String> iterator = handles.iterator();
        while (iterator.hasNext()){
            subWindowHandler = iterator.next();
        }
        driver.switchTo().window(subWindowHandler);

        driver.findElement(By.xpath("")); //do something

        driver.switchTo().window(parentWindowHandler);
</code>```

Body:
I am try to click on a link on a newly opened browser window after clicking on a link on main window But webdriver is unable to find the element on the new opened window.

Below is my code which I am using to switch on the other window and then performing an action on it.

public void test() throws Exception{
    driver.findElement(By.xpath("//img[@alt='Calender']")).click();
    String Parent_Window =driver.getWindowHandle();

    for (String Child_Window : driver.getWindowHandles()) {
      driver.switchTo().window(Child_Window);
      driver.findElement(By.xpath("//div[@class='pbBody']//table[@class='list']//tr[@class='dataRow even first']//a")).click();
      // Webdriver is not able to click on the above link and it fails at this step
    }
    driver.switchTo().window(Parent_Window);
}

Please help me on this why wedrivber is unable to find the element on the new browser window after switching.Thanks!

Body:
try this, i was having serious issue with windowhandles, but this one seems better.

String parentWindowHandler = driver.getWindowHandle();
        String subWindowHandler = null;

        Set<String> handles = driver.getWindowHandles();
        Iterator<String> iterator = handles.iterator();
        while (iterator.hasNext()){
            subWindowHandler = iterator.next();
        }
        driver.switchTo().window(subWindowHandler);

        driver.findElement(By.xpath("")); //do something

        driver.switchTo().window(parentWindowHandler);


问:
Returning string in Ajax success function
I'm trying to return a string back after my Ajax is executed, however; I'm getting the word undefined instead of the string. I understand that the code is being executed asynchronously, but I don't understand how I can make a solution for my problem.

JS

```<code>function aggregator(field){
    var query = '{"aggs": { "group_by_date": { "terms": { "field": "' + field + '" } } } }';

     $.ajax({
        url: 'index.php',
        type: 'post',
        data: {
            qSet: query
        },
        success: function(message){
            return message;
        }
    });

}

   var results = aggregator("transactionDate");
   document.getElementById("results").innerHTML = results;
</code>```

How do I make it so that my element in HTML has the returned value?

答:
welcome to asynchronous programming. You must either process your return value inside the callback of the ajax function, or use some kind of deferred queue based on promises for example.

For a quick solution of your problem, try the first technique:

```<code>function aggregator(field,element){
    var query = '{"aggs": { "group_by_date": { "terms": { "field": "' + field + '" } } } }';

     $.ajax({
        url: 'index.php',
        type: 'post',
        data: {
            qSet: query
        },
        success: function(message){
            document.getElementById(element).innerHTML=message;
        }
    });

}

aggregator("transactionDate","results");
</code>```

Body:
I'm trying to return a string back after my Ajax is executed, however; I'm getting the word undefined instead of the string. I understand that the code is being executed asynchronously, but I don't understand how I can make a solution for my problem.

JS

function aggregator(field){
    var query = '{"aggs": { "group_by_date": { "terms": { "field": "' + field + '" } } } }';

     $.ajax({
        url: 'index.php',
        type: 'post',
        data: {
            qSet: query
        },
        success: function(message){
            return message;
        }
    });

}

   var results = aggregator("transactionDate");
   document.getElementById("results").innerHTML = results;

How do I make it so that my element in HTML has the returned value?

Body:
welcome to asynchronous programming. You must either process your return value inside the callback of the ajax function, or use some kind of deferred queue based on promises for example.

For a quick solution of your problem, try the first technique:

function aggregator(field,element){
    var query = '{"aggs": { "group_by_date": { "terms": { "field": "' + field + '" } } } }';

     $.ajax({
        url: 'index.php',
        type: 'post',
        data: {
            qSet: query
        },
        success: function(message){
            document.getElementById(element).innerHTML=message;
        }
    });

}

aggregator("transactionDate","results");


问:
MVC Application - Use your local DB in order to login/register
I'm new into MVC applications and I'm trying to learn how to connect to my local DB. I have watched lots of tutorials and I could figure it out how to change my connection string in order for the MVC to access my database. But, if I register on my MVC Application, Visual Studio creates automatically four new tables, besides my TEST database and the new user is inserted in those tables, not in the table I have set/used in connection string. What am I doing wrong? Thanks

Here is my connection string:

<connectionStrings>
    <add name="DefaultConnection" connectionString="Server=DESKTOP-K6CIG9A;Database=TEST;Trusted_Connection=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

Here is how it looks my Server Explorer:
Printscreen

答: You're going to want to change your connection string to use (LocalDb)\v11.0. You can find more information in this article.


问:
Scala: short form of pattern matching that returns Boolean
I found myself writing something like this quite often:

```<code>a match {
  case `b` => // do stuff
  case _ => // do nothing
}
</code>```

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

```<code>if (a matches b) // do stuff
</code>```

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

答:
Kim's answer can be “improved” to better match your requirement:

```<code>class AnyWrapper[A](wrapped: A) {
  def matches(f: PartialFunction[A, Unit]) = f.isDefinedAt(wrapped)
}
implicit def any2wrapper[A](wrapped: A) = new AnyWrapper(wrapped)
</code>```

then:

```<code>val a = "a" :: Nil
if (a matches { case "a" :: Nil => }) {
  println("match")
}
</code>```

I wouldn't do it, however. The => }) { sequence is really ugly here, and the whole code looks much less clear than a normal match. Plus, you get the compile-time overhead of looking up the implicit conversion, and the run-time overhead of wrapping the match in a PartialFunction (not counting the conflicts you could get with other, already defined matches methods, like the one in String).

To look a little bit better (and be less verbose), you could add this def to AnyWrapper:

```<code>def ifMatch(f: PartialFunction[A, Unit]): Unit = if (f.isDefinedAt(wrapped)) f(wrapped)
</code>```

and use it like this:

```<code>a ifMatch { case "a" :: Nil => println("match") }
</code>```

which saves you your case _ => line, but requires double braces if you want a block instead of a single statement... Not so nice.

Note that this construct is not really in the spirit of functional programming, as it can only be used to execute something that has side effects. We can't easily use it to return a value (therefore the Unit return value), as the function is partial — we'd need a default value, or we could return an Option instance. But here again, we would probably unwrap it with a match, so we'd gain nothing.

Frankly, you're better off getting used to seeing and using those match frequently, and moving away from this kind of imperative-style constructs (following Madoc's nice explanation).

Body:
I found myself writing something like this quite often:

a match {
  case `b` => // do stuff
  case _ => // do nothing
}

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

if (a matches b) // do stuff

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

Body:
Kim's answer can be “improved” to better match your requirement:

class AnyWrapper[A](wrapped: A) {
  def matches(f: PartialFunction[A, Unit]) = f.isDefinedAt(wrapped)
}
implicit def any2wrapper[A](wrapped: A) = new AnyWrapper(wrapped)

then:

val a = "a" :: Nil
if (a matches { case "a" :: Nil => }) {
  println("match")
}

I wouldn't do it, however. The => }) { sequence is really ugly here, and the whole code looks much less clear than a normal match. Plus, you get the compile-time overhead of looking up the implicit conversion, and the run-time overhead of wrapping the match in a PartialFunction (not counting the conflicts you could get with other, already defined matches methods, like the one in String).

To look a little bit better (and be less verbose), you could add this def to AnyWrapper:

def ifMatch(f: PartialFunction[A, Unit]): Unit = if (f.isDefinedAt(wrapped)) f(wrapped)

and use it like this:

a ifMatch { case "a" :: Nil => println("match") }

which saves you your case _ => line, but requires double braces if you want a block instead of a single statement... Not so nice.

Note that this construct is not really in the spirit of functional programming, as it can only be used to execute something that has side effects. We can't easily use it to return a value (therefore the Unit return value), as the function is partial — we'd need a default value, or we could return an Option instance. But here again, we would probably unwrap it with a match, so we'd gain nothing.

Frankly, you're better off getting used to seeing and using those match frequently, and moving away from this kind of imperative-style constructs (following Madoc's nice explanation).


问:
Eiffel: Do expanded types conform to ANY?

Assume that foo: ANY is an assignable entity.

What happens when I do foo := create {BOOLEAN}?

It would fail always, because BOOLEAN (an expanded type) does not conform to ANY (a reference type), correct?

答:
Expanded types conform to reference ones (provided that other conformance requirements are satisfied). So, the example you mention works just fine. Moreover, it is ok to write foo := True.

The key difference after such reattachments is that copy semantics of expanded types is preserved, i.e. if there is an entity bar of type ANY, the assignment bar := foo will attach a copy of the boolean object to bar, not the same reference. So, if a value of the object attached to foo is changed afterwards, bar remains unchanged.

Answering your original question, BOOLEAN conforms to ANY.


问:
How to call a Restfull web service that have basic authentication using Spring RestTemplate
I am using Tomcat7, Sprng framework for restfull web services. I am trying to call an http web service that have basic authentication using Spring RestTemplate.

I couldn't get it to work. Can anybody please tell me based on the code below what do I need to change to make it able to call the http restfull web service that have basic authentication.. Also can anybody tell me or provide me with the pom.xml file which java libraries would I need?

```<code>import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.journaldev.spring.controller.EmpRestURIConstants;
import com.journaldev.spring.model.CostControlPost;
import com.journaldev.spring.model.Employee;
import com.journaldev.spring.model.RfxForUpdate;

import static org.junit.Assert.*;
import org.apache.commons.codec.binary.Base64;

import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class TestExample2 {

    public static final String SERVER_LIST="http://abc/sourcing/testServices";

    @Test
    public void testGetListOfServiceNames()
    {
        try
        {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.exchange(SERVER_LIST,HttpMethod.GET,null,String.class);
            assertNotNull(response);
        }
        catch(Exception e)
        {
            System.out.println("e:"+e.getMessage());
        }
    }
 }
</code>```

答:
In simplest form:

```<code>    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicCredentialsProvider credentialsProvider =  new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password);
    httpClient.setCredentialsProvider(credentialsProvider);
    ClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(httpClient);

    template = new RestTemplate(rf);
</code>```

Spring Automatic Management:

Create HTTP context for RestTemplate:

```<code> private HttpContext createHttpContext() {
        AuthCache authCache = new BasicAuthCache();

        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        return localcontext;
    }
</code>```

Add the interceptors:

```<code>restTemplate.getInterceptors().add(
  new BasicAuthorizationInterceptor("username", "password"));
</code>```

Call:

```<code>restTemplate.exchange(
  "http://abc/sourcing/testServices",
  HttpMethod.GET, null, String.class);
</code>```

Refer this post.

Body:
I am using Tomcat7, Sprng framework for restfull web services. I am trying to call an http web service that have basic authentication using Spring RestTemplate.

I couldn't get it to work. Can anybody please tell me based on the code below what do I need to change to make it able to call the http restfull web service that have basic authentication.. Also can anybody tell me or provide me with the pom.xml file which java libraries would I need?

import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.journaldev.spring.controller.EmpRestURIConstants;
import com.journaldev.spring.model.CostControlPost;
import com.journaldev.spring.model.Employee;
import com.journaldev.spring.model.RfxForUpdate;

import static org.junit.Assert.*;
import org.apache.commons.codec.binary.Base64;

import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class TestExample2 {

    public static final String SERVER_LIST="http://abc/sourcing/testServices";

    @Test
    public void testGetListOfServiceNames()
    {
        try
        {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.exchange(SERVER_LIST,HttpMethod.GET,null,String.class);
            assertNotNull(response);
        }
        catch(Exception e)
        {
            System.out.println("e:"+e.getMessage());
        }
    }
 }

Body:
In simplest form:

    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicCredentialsProvider credentialsProvider =  new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password);
    httpClient.setCredentialsProvider(credentialsProvider);
    ClientHttpRequestFactory rf = new HttpComponentsClientHttpRequestFactory(httpClient);

    template = new RestTemplate(rf);

Spring Automatic Management:

Create HTTP context for RestTemplate:

 private HttpContext createHttpContext() {
        AuthCache authCache = new BasicAuthCache();

        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        return localcontext;
    }

Add the interceptors:

restTemplate.getInterceptors().add(
  new BasicAuthorizationInterceptor("username", "password"));

Call:

restTemplate.exchange(
  "http://abc/sourcing/testServices",
  HttpMethod.GET, null, String.class);

Refer this post.


问:
Drupal SAML login redirect not working
I'm configuring SSO by SAML for Drupal, I tested the SP login through SimpleSAMLphp's panel and it works. I installed simplesamlphp_auth for drupal and enabled authentication via SimpleSAMLphp.

When I go to https://mydrupal.com/saml_login, the browser starts to redirect (some long URL with disco.php) then stops with a 404. The SP simply logs, and rightly so:

session not valid because we are not authenticated.

I'm certain this is a drupal or a module config (not the SP or IdP as those are tested and work), what am I doing wrong ?

Should my SP absolutely use Memcache as a store ?

Update:

Recent log entries mention SimpleSAMLphp can't find disco.php

page not found 2016-01-18 16:33    simplesamlphp/module.php/saml/disco.php

Should the ServerName in my VirtualHost config for the SP match the drupal url or is that irrelevant ?

答:
You could be getting these issues for multiple different reasons. This is why one answer is about VirtualHost entries, and another is about your session handling method (memcache or sql).

You didn't mention which version of Drupal core you are running. This is also important with the simplesamlphp_auth module.

If you are running Drupal 8 and you installed the simplesamlphp_auth module via composer, it will have installed the simplesamlphp library in your vendor directory. And it won't matter that you've pointed to another directory for that library in your VirtualHost entries, or even that you've specified another directory in settings.php config. The simplesamlphp_auth will use the library in your vendor directory anyway. This was the issue that I ran into. I had to copy all my config into the files in the simplesamlphp library in the vendor directory before it worked.

Title: Drupal SAML login redirect not working


问:
Can a controller influence the _layout.cshtml file?
I'm stuck! I'm under the impression that the _layout.cshtml file is used for MasterPage-like content. Everything there is rendered on every page. Naturally, I want to write the code for rendering my sidebar menu in that file.

I want to dynamically display a list of Categories from my DB, but I'm having a problem with passing the actual model of categories to Layout.cshtml since it seems no controller actually touches it.

Any suggestions?

Otherwise please tell me how to approach this problem. I've been wracking my brain for the past three days and still no elegant solution.

I need to:

Dynamically fetch a list of Categories from the DB.

Display this list of Categories on every single view. (Hence the use of _layout.cshtml)

Elegantly handle each different categories click.

I'm at my wits end. :P How would you solve this?

答:
Any viewmodel that you pass to your view is automatically available within your master page. If you do not use RenderAction/Action which is the best approach, then you must create the necessary master page data in every action and add it to viewdata - either by having a common base class for your strongly typed viewmodel that contains all master page data or by using the viewdata dictionary.

I would strongly recommend that you go down the html.action approach though. In this way, you have a totally separate controller action for dealing with your list of categories. This action can retrieve the neccesary category data and return the categorylist usercontrol as a partialview and you will not have to worry about polluting all your other actions with this data.

OwnerDisplayName: delete


问:
ExpressJS: Why does this output [] on the first GET, and then the next GET returns the data from the previous?
I am experimenting with Express and MongoDB, and have a functional API server that can add, update, delete, and retrieve a single post. The issue I have run into is returning all of the documents from Mongo.

I have a GET route that outputs the results, except it does not behave as I imagined it would. When you run this, the first GET request to /notes returns and empty array, i.e. []

```<code>let notes =[];
app.get('/notes', (req, res) => {
    async function getNotes() {
      try {
        await db.collection('notes').find().forEach(function (myDoc) {
          notes.push(myDoc);
        })
      } catch(err) {
        console.log(err)
      }
      console.log(notes);
      res.send((notes));
    }
    getNotes();
  });
</code>```

On the second GET to /notes, however, the data that was pushed into notes[] is returned, and it is then overwritten by the newly pushed data.

Can anyone help me fill in the blank spot in my understanding of this? I imagine there is something that I just didn't understand along the way.

Edit***

I have experimented with this a bit, and am still running into the same issues.

```<code>let array= [];
async function getNotes() {
try {
  await db.collection('notes').find().toArray(function (err, notesArray) {
    array = notesArray;
  })
} catch (err) {
  console.log(err)
}
console.log(array);
return array;
}
app.get('/notes', (req, res) => {
  getNotes();
  res.send(array);
});
</code>```

答:
MongoDB's .toArray() won't both invoke a callback and return a Promise.

Returns:

Promise if no callback passed

And, await depends on the Promise, so you won't be able to use the callback as well.

Though, one isn't really necessary. When the promise resolves, await will return the array of documents, allowing you to assign that to array or any other variable.

```<code>try {
  array = await db.collection('notes').find().toArray();
}
</code>```

Body:
I am experimenting with Express and MongoDB, and have a functional API server that can add, update, delete, and retrieve a single post. The issue I have run into is returning all of the documents from Mongo.

I have a GET route that outputs the results, except it does not behave as I imagined it would. When you run this, the first GET request to /notes returns and empty array, i.e. []

let notes =[];
app.get('/notes', (req, res) => {
    async function getNotes() {
      try {
        await db.collection('notes').find().forEach(function (myDoc) {
          notes.push(myDoc);
        })
      } catch(err) {
        console.log(err)
      }
      console.log(notes);
      res.send((notes));
    }
    getNotes();
  });

On the second GET to /notes, however, the data that was pushed into notes[] is returned, and it is then overwritten by the newly pushed data.

Can anyone help me fill in the blank spot in my understanding of this? I imagine there is something that I just didn't understand along the way.

Edit***

I have experimented with this a bit, and am still running into the same issues.

let array= [];
async function getNotes() {
try {
  await db.collection('notes').find().toArray(function (err, notesArray) {
    array = notesArray;
  })
} catch (err) {
  console.log(err)
}
console.log(array);
return array;
}
app.get('/notes', (req, res) => {
  getNotes();
  res.send(array);
});

Body:
MongoDB's .toArray() won't both invoke a callback and return a Promise.

Returns:

Promise if no callback passed

And, await depends on the Promise, so you won't be able to use the callback as well.

Though, one isn't really necessary. When the promise resolves, await will return the array of documents, allowing you to assign that to array or any other variable.

try {
  array = await db.collection('notes').find().toArray();
}


问:
Using TouchAFPosition with Sony a6500 Camera
I am trying to use setTouchAFPosition with Sony Camera Remote API version 2.40 and a a6500 Camera.

I am able to get the Liveview and actTakePicture to work but any time I call "setTouchAFPosition" I keep getting "Not Available Now".

Has anyone been able to use this function with the a6500 camera or similar?

答: It could have something to do with the a6500 not supporting "Tracking Focus". Try running the "getSupportedCameraFunction" and "getAvailableCameraFunction" commands to see if the "setTouchAFPosition" commands is returned in the list.</p>


问:
How to Copy data from one sheet to another based on cell value
I have a master dataset in one sheet something like this

In another sheet I want to extract Data from this Master Data set based on a cell value which will have Department as Criteria.

So ,For example if in sheet 2 I type my my Department criteria as Sales, All the rows with Department as Sales should get populated in Sheet 2.

Can this be done by excel functions/Macros/VBA ?
Thanks in advance.
Pardon me if you find this query absurd .

答:
Yes it can be done.  Add this code to a module in your workbook.  You can run it right from the debugger, or go to macros and assign it a hotkey, or you can create a button on the sheet and put this code inside the button click event.  There are probably more efficient ways to do this but it shouldn't matter unless you have a lot of data.  I've been explicit so you can see whats going on.  I've used the sheet names "Data" and "View" you will have to change the names in the code to match your workbook.

EDIT:  I'm also assuming that the top left cell in your screenshot is A1, if not you will have to adjust the code.

```<code>Sub GetDepartments()

Dim LastRow As Long
Dim MyRange As Range
Dim SourceRow As Long
Dim DeptValue As String
Dim OutputRow As Long
Dim ColCounter As Long

'get size of current view sheet and clear
LastRow = ThisWorkbook.Worksheets("View").Cells(ThisWorkbook.Worksheets("View").Rows.Count, "A").End(xlUp).Row
If LastRow > 7 Then
  Set MyRange = ThisWorkbook.Worksheets("View").Range("A7:C" & LastRow)
  MyRange.ClearContents
End If

'get size of data sheet
LastRow = ThisWorkbook.Worksheets("Data").Cells(ThisWorkbook.Worksheets("Data").Rows.Count, "A").End(xlUp).Row
'get value to match
DeptValue = ThisWorkbook.Worksheets("View").Cells(3, 2).Value

'track outputrow
OutputRow = 7

'loop through all rows in data
For SourceRow = 2 To LastRow
  'if match found
  If ThisWorkbook.Worksheets("Data").Cells(SourceRow, 2).Value = DeptValue Then
    'copy 3 cols
    For ColCounter = 1 To 3
      ThisWorkbook.Worksheets("View").Cells(OutputRow, ColCounter).Value = _
        ThisWorkbook.Worksheets("Data").Cells(SourceRow, ColCounter).Value
    Next ColCounter
    'increment outputrow
    OutputRow = OutputRow + 1
  End If
Next SourceRow
End Sub
</code>```

Body:
Yes it can be done.  Add this code to a module in your workbook.  You can run it right from the debugger, or go to macros and assign it a hotkey, or you can create a button on the sheet and put this code inside the button click event.  There are probably more efficient ways to do this but it shouldn't matter unless you have a lot of data.  I've been explicit so you can see whats going on.  I've used the sheet names "Data" and "View" you will have to change the names in the code to match your workbook.

EDIT:  I'm also assuming that the top left cell in your screenshot is A1, if not you will have to adjust the code.

Sub GetDepartments()

Dim LastRow As Long
Dim MyRange As Range
Dim SourceRow As Long
Dim DeptValue As String
Dim OutputRow As Long
Dim ColCounter As Long

'get size of current view sheet and clear
LastRow = ThisWorkbook.Worksheets("View").Cells(ThisWorkbook.Worksheets("View").Rows.Count, "A").End(xlUp).Row
If LastRow > 7 Then
  Set MyRange = ThisWorkbook.Worksheets("View").Range("A7:C" & LastRow)
  MyRange.ClearContents
End If

'get size of data sheet
LastRow = ThisWorkbook.Worksheets("Data").Cells(ThisWorkbook.Worksheets("Data").Rows.Count, "A").End(xlUp).Row
'get value to match
DeptValue = ThisWorkbook.Worksheets("View").Cells(3, 2).Value

'track outputrow
OutputRow = 7

'loop through all rows in data
For SourceRow = 2 To LastRow
  'if match found
  If ThisWorkbook.Worksheets("Data").Cells(SourceRow, 2).Value = DeptValue Then
    'copy 3 cols
    For ColCounter = 1 To 3
      ThisWorkbook.Worksheets("View").Cells(OutputRow, ColCounter).Value = _
        ThisWorkbook.Worksheets("Data").Cells(SourceRow, ColCounter).Value
    Next ColCounter
    'increment outputrow
    OutputRow = OutputRow + 1
  End If
Next SourceRow
End Sub


问:
Python function equivalent to R's `pretty()`?
I'm replicating some R code in Python.

I've tripped up on R's pretty().

All I need is pretty(x), where x is some numeric.

Roughly, the function "computes pretty breakpoints" as a sequence of several "round" values. I'm not sure there is a Python equivalent and I'm not having much luck with Google.

Edit: More specifically, this is the Description entry in he help page for pretty:

Description: Compute a sequence of about n+1 equally spaced ‘round’ values which cover the range of the values in x. The values are chosen so that they are 1, 2 or 5 times a power of 10.

I looked into R's pretty.default() to see what exactly R is doing with the function but it eventually uses .Internal() -- which usually leads to dark R magic. I thought I'd ask around before diving in.

Does anyone know if Python has something equivalent to R's pretty()?

答:
What about numpy.arange?

```<code>import numpy as np

print np.arange(0,16,3)
</code>```

$ [ 0  3  6  9 12 15]

Body:
What about numpy.arange?

import numpy as np

print np.arange(0,16,3)

$ [ 0  3  6  9 12 15]


问:
NSCollectionView performBatchUpdates doesn't animate changes
When I do the animations individually everything works fine, but inside of a performBatchUpdates block the change is instant, almost like I called reloadData(). Am I using it correctly?

Working method:

```<code>NSAnimationContext.currentContext().duration = 0.25

indexPathChanges.map({collectionView.animator().moveItemAtIndexPath($0.0, toIndexPath: $0.1)})
</code>```

performBatchUpdates version (instant change - no animation):

```<code>NSAnimationContext.currentContext().duration = 0.25

collectionView.performBatchUpdates(  {
    indexPathChanges.map({self.collectionView.moveItemAtIndexPath($0.0, toIndexPath: $0.1)})

    // tried this as well - no luck
    // indexPathChanges.map({self.collectionView.animator().moveItemAtIndexPath($0.0, toIndexPath: $0.1)})

}, completionHandler: {(finished) in print("Finished: \(finished)")
</code>```

答:
Try to put it this way:

```<code>collectionView.animator().performBatchUpdates({<your animations>}, completionHandler:{finished in <your completion handler>})
</code>```

In other words, pass it through animator() proxy.

Body:
When I do the animations individually everything works fine, but inside of a performBatchUpdates block the change is instant, almost like I called reloadData(). Am I using it correctly?

Working method:

NSAnimationContext.currentContext().duration = 0.25

indexPathChanges.map({collectionView.animator().moveItemAtIndexPath($0.0, toIndexPath: $0.1)})

performBatchUpdates version (instant change - no animation):

NSAnimationContext.currentContext().duration = 0.25

collectionView.performBatchUpdates(  {
    indexPathChanges.map({self.collectionView.moveItemAtIndexPath($0.0, toIndexPath: $0.1)})

    // tried this as well - no luck
    // indexPathChanges.map({self.collectionView.animator().moveItemAtIndexPath($0.0, toIndexPath: $0.1)})

}, completionHandler: {(finished) in print("Finished: \(finished)")

Body:
Try to put it this way:

collectionView.animator().performBatchUpdates({<your animations>}, completionHandler:{finished in <your completion handler>})

In other words, pass it through animator() proxy.

ContentLicense: CC BY-SA 4.0


问:
Flash video player for AVI files (free for commercial use)
Are there any Flash video players, free for commercial use, that are able to playback AVI files? JW Player is out of the question because in the readme it states that use by a corporation is considered commercial use and needs a different license.</p>

答: Strobe Media Playback. Bsd license. Directly from adobe. .... docs suck at this point though.... player is pretty good though...  http://sourceforge.net/adobe/smp/wiki/Home/</p>


问:
click the bottom part of an element?
I have a link that I need to click on that is halfway underneath another element.  Something like this:

```<code>______________________
| A  ____________    | <-- on top
|____|B_________|____|
     |__________| < - on bottom (need to click this one)
</code>```

When I try to click on the bottom link, I get

```<code>(B) is not clickable at point (254, 5). Other element would receive the click: (A).
</code>```

Here is an image (I need to click on the PO Box link).  I don't know exactly what to do here.  Thanks!

Here is the HTML in question.  Selenium is sending the click action to the span labelFieldWrapper:

```<code><div class='clr type_address formFieldContainer'>
    <span class="labelFieldWrapper">
        <label class="placeholder" for="address1">
            <span class="labelText">Address 1</span>
        </label>
        <input id="address1" name="address1" type="text" value="" autofillparam="ON" size="20" maxlength="60"/><span class="asterisk">*</span>
    </span>
    <p class="helpLink">
        <a href="javascript: void(0)"
           onclick="window.open('/checkout/canadian_province_support.jsp',
          'pobox',
          'width=450, \
           height=200, \
           directories=no, \
           location=no, \
           menubar=no, \
           resizable=no, \
           scrollbars=1, \
           status=no, \
           toolbar=no');
          return false;">PO Box?</a>  <-- Trying to click on this link
        </p>
    </div><!-- /formFieldContainer -->
</code>```

答:
if this case you can make some workaround, like click on the bottom of element</p>

```<code>WebElement element = driver.findElement(By.xpath("someXpath"));
int halfOfHeight = element.getSize().getHeight()/2;
// moveToElement* method moves to the middle of element, so we'll also move on half of element and click on the 3rd pix from the bottom
int offset = halfOfHeight - 3;

Actions actions = new Actions(driver);
actions
       .moveToElement(element)
       .moveByOffset(0, offset)
       .click()
       .build()
       .perform();
</code>```

Title: click the bottom part of an element?

Body:
I have a link that I need to click on that is halfway underneath another element.  Something like this:

______________________
| A  ____________    | <-- on top
|____|B_________|____|
     |__________| < - on bottom (need to click this one)

When I try to click on the bottom link, I get

(B) is not clickable at point (254, 5). Other element would receive the click: (A).

Here is an image (I need to click on the PO Box link).  I don't know exactly what to do here.  Thanks!

Here is the HTML in question.  Selenium is sending the click action to the span labelFieldWrapper:

            Address 1

        <input id="address1" name="address1" type="text" value="" autofillparam="ON" size="20" maxlength="60"/>*

        PO Box?  <-- Trying to click on this link

Body:
if this case you can make some workaround, like click on the bottom of element

WebElement element = driver.findElement(By.xpath("someXpath"));
int halfOfHeight = element.getSize().getHeight()/2;
// moveToElement* method moves to the middle of element, so we'll also move on half of element and click on the 3rd pix from the bottom
int offset = halfOfHeight - 3;

Actions actions = new Actions(driver);
actions
       .moveToElement(element)
       .moveByOffset(0, offset)
       .click()
       .build()
       .perform();


问:
How to make smaller a background circle in a font awesome icon?
I need to produce the following warning sign using Font Awesome:

However, I am not able to make it exactly as it is because I have like an extra border:

This is my HTML:

```<code><div role="alert" class="alert alert-dismissible">
  <i id="exclamation-mark" class="fa fa-exclamation-circle extraClass" aria-hidden="true"></i>
  <p style="display: inline;vertical-align: middle">
    <span>Oops! Something went horribly wrong. </span> We’re really sorry. Please try that again.
  </p>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    ×
  </button>
</div>
</code>```

This is my CSS (SCSS):

```<code>$color-secondary-1: #db2b4b;

p > span {
  font-weight: bold;
}

div {
  color: white;
  text-align: center;
  background-color: $color-secondary-1;

  i {
    font-size: 100px;
    color: #ff91a5;
    background: white;
    border-radius: 50%;
    height: 1em;
    width: 1em;
  }
}

.extraClass{
     font-size:3em;
}
</code>```

This is my CodePen link.

答:
Fix is pretty simple. Use the version of the icon without the circle, and then just add the circle manually.

Fixed: codepen.io/anon/pen/JJoZVo?editors=1100

HTML

```<code><div role="alert" class="alert alert-dismissible">
  <i id="exclamation-mark" class="fa fa-exclamation extraClass" aria-hidden="true"></i>
  <p style="display: inline;vertical-align: middle">
    <span>Oops! Something went horribly wrong. </span> We’re really sorry. Please try that again.
  </p>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    ×
  </button>
</div>
</code>```

CSS

```<code>$color-secondary-1: #db2b4b;

p > span {
  font-weight: bold;
}

div {
  color: white;
  text-align: center;
  background-color: $color-secondary-1;

  i {
    color: white;
    background: #ff91a5;
    border-radius: 50%;
    padding:10px;
    height: 1em;
    width: 1em;
  }
}

.extraClass{
     font-size: 2em;
}
</code>```

Body:
I need to produce the following warning sign using Font Awesome:

However, I am not able to make it exactly as it is because I have like an extra border:

This is my HTML:

    Oops! Something went horribly wrong.  We’re really sorry. Please try that again.

  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    ×
  </button>

This is my CSS (SCSS):

$color-secondary-1: #db2b4b;

p > span {
  font-weight: bold;
}

div {
  color: white;
  text-align: center;
  background-color: $color-secondary-1;

  i {
    font-size: 100px;
    color: #ff91a5;
    background: white;
    border-radius: 50%;
    height: 1em;
    width: 1em;
  }
}

.extraClass{
     font-size:3em;
}

This is my CodePen link.

Body:
Fix is pretty simple. Use the version of the icon without the circle, and then just add the circle manually.

Fixed: codepen.io/anon/pen/JJoZVo?editors=1100

HTML

<div role="alert" class="alert alert-dismissible">
  <i id="exclamation-mark" class="fa fa-exclamation extraClass" aria-hidden="true"></i>
  <p style="display: inline;vertical-align: middle">
    <span>Oops! Something went horribly wrong. </span> We’re really sorry. Please try that again.
  </p>
  <button type="button" class="close" data-dismiss="alert" aria-label="Close">
    ×
  </button>
</div>

CSS

$color-secondary-1: #db2b4b;

p > span {
  font-weight: bold;
}

div {
  color: white;
  text-align: center;
  background-color: $color-secondary-1;

  i {
    color: white;
    background: #ff91a5;
    border-radius: 50%;
    padding:10px;
    height: 1em;
    width: 1em;
  }
}

.extraClass{
     font-size: 2em;
}


问:
Keep list open unless clicked or hovered off
I have a JQuery/JS function that shows a list when you hover over a button. However, when you hover off the button, the list does not show. I need the list to keep showing when you hover over it, and close when you hover off or click a link on the list.

How can I achieve this?
Fiddle: https://jsfiddle.net/wj6pguf2/

JQ

```<code>$(document).ready(function(){
var recent = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana", "Druif"]
    $("#recent").hover(function() {
        $("#recentcomplete").empty();
        document.getElementById("recentcomplete").style.display = "block";
        recent.forEach(function(item) {
            $("#recentcomplete").append('<li><a href="#">' + item + '</a></li>');
        });
            }, function() {
        document.getElementById("recentcomplete").style.display = "none";
    });
});
</code>```

HTML

```<code>        <button type="submit" name="recent" id="recent" style="max-width:150px;">snelkiezer</button>

        <ul id="recentcomplete" >
        </ul>
</code>```

答:
You can add the ID of the list to your hover call:

```<code>$("#recent, #recentcomplete").hover(function() {
</code>```

jsFiddle example

To close the list upon clicking a link, use:

```<code>$(document).on('click', '#recentcomplete a', function() {
    $('#recentcomplete').hide()
})
</code>```

Body:
I have a JQuery/JS function that shows a list when you hover over a button. However, when you hover off the button, the list does not show. I need the list to keep showing when you hover over it, and close when you hover off or click a link on the list.

How can I achieve this?
Fiddle: https://jsfiddle.net/wj6pguf2/

JQ

$(document).ready(function(){
var recent = ["Appel", "Aardbei", "Aardappelen", "Banaan", "Bananen", "Banana", "Druif"]
    $("#recent").hover(function() {
        $("#recentcomplete").empty();
        document.getElementById("recentcomplete").style.display = "block";
        recent.forEach(function(item) {
            $("#recentcomplete").append('
' + item + '
');
        });
            }, function() {
        document.getElementById("recentcomplete").style.display = "none";
    });
});

HTML

        <button type="submit" name="recent" id="recent" style="max-width:150px;">snelkiezer</button>

Body:
You can add the ID of the list to your hover call:

$("#recent, #recentcomplete").hover(function() {

jsFiddle example

To close the list upon clicking a link, use:

$(document).on('click', '#recentcomplete a', function() {
    $('#recentcomplete').hide()
})


问:
Oracle SQL with Join and count
I would like to join two tables, A and B, with a count function.

Table A has the followings:

```<code>SQL> select a.book_id, count(a.book_id)
   from
   a
   group by a.book_id ;

BOOK_ID COUNT(A.BOOK_ID)
--------- ----------------
    1                2
    2                2
    3                2
    4                2
    5                2
    6                3
</code>```

and table B has the followings:

```<code> SQL> select b.book_id, count(b.book_id)
from
b
group by b.book_id ;

 BOOK_ID COUNT(B.BOOK_ID)
--------- ----------------
     6                2
</code>```

So I would like to have a query which gives me the following result:

```<code> BOOK_ID COUNT(A.BOOK_ID)    COUNT(B.BOOK_ID)
--------- ----------------   ----------------
    1                2                   0
    2                2                   0
    3                2                   0
    4                2                   0
    5                2                   0
    6                3                   2
</code>```

I tried this :

```<code>  SQL> select b.book_id, count(b.book_id),a.book_id, count(a.book_id)
  from
  b , a
  where
  b.book_id(+) = a.book_id
 group by b.book_id, a.book_id ;
</code>```

but the results were like this :

```<code>   BOOK_ID COUNT(B.BOOK_ID)   BOOK_ID COUNT(A.BOOK_ID)
 --------- ---------------- --------- ----------------
                     0         1                2
                     0         2                2
                     0         3                2
                     0         4                2
                     0         5                2
    6                6         6                6
</code>```

答:
Something like this perhaps:</p>

```<code>select  a.book_id as id_a,
        (select count(1) from a a2 where a2.book_id = a.book_id) as count_a,
        b.book_id as id_b,
        (select count(1) from b b2 where b2.book_id = a.book_id) as count_b
from a
left join b on b.book_id  = a.book_id
group by a.book_id;
</code>```

Title: Oracle SQL with Join and count

Body:
I would like to join two tables, A and B, with a count function.

Table A has the followings:

SQL> select a.book_id, count(a.book_id)
   from
   a
   group by a.book_id ;

BOOK_ID COUNT(A.BOOK_ID)
--------- ----------------
    1                2
    2                2
    3                2
    4                2
    5                2
    6                3

and table B has the followings:

 SQL> select b.book_id, count(b.book_id)
from
b
group by b.book_id ;

 BOOK_ID COUNT(B.BOOK_ID)
--------- ----------------
     6                2

So I would like to have a query which gives me the following result:

 BOOK_ID COUNT(A.BOOK_ID)    COUNT(B.BOOK_ID)
--------- ----------------   ----------------
    1                2                   0
    2                2                   0
    3                2                   0
    4                2                   0
    5                2                   0
    6                3                   2

I tried this :

  SQL> select b.book_id, count(b.book_id),a.book_id, count(a.book_id)
  from
  b , a
  where
  b.book_id(+) = a.book_id
 group by b.book_id, a.book_id ;

but the results were like this :

   BOOK_ID COUNT(B.BOOK_ID)   BOOK_ID COUNT(A.BOOK_ID)
 --------- ---------------- --------- ----------------
                     0         1                2
                     0         2                2
                     0         3                2
                     0         4                2
                     0         5                2
    6                6         6                6

Body:
Something like this perhaps:

select  a.book_id as id_a,
        (select count(1) from a a2 where a2.book_id = a.book_id) as count_a,
        b.book_id as id_b,
        (select count(1) from b b2 where b2.book_id = a.book_id) as count_b
from a
left join b on b.book_id  = a.book_id
group by a.book_id;


问:
I want a right arrow to change variable, but it will not work
When I hit the right arrow, it does not change the variable. Here's my code:</p>

```<code>var squareX = 10;
document.addEventListener("keypress", function(e) {
  if (e.keyCode === 39) {
    squareX += 10;
  }
});
</code>```

答:
Use keydown instead of keypress:

```<code>document.addEventListener("keydown", function(e) {
    if (e.keyCode === 39) {
       squareX += 10;
    }
});
</code>```

That did the trick for me!

Body:
When I hit the right arrow, it does not change the variable. Here's my code:

var squareX = 10;
document.addEventListener("keypress", function(e) {
  if (e.keyCode === 39) {
    squareX += 10;
  }
});

Body:
Use keydown instead of keypress:

document.addEventListener("keydown", function(e) {
    if (e.keyCode === 39) {
       squareX += 10;
    }
});

That did the trick for me!


问:
Filter foreach array based on value inside this array
Hello I have the following array:

$tourcontent

and the following foreach:

```<code>foreach($tourcontent as $set)
</code>```

How I can limit the result of the output of this foreach to be limited to only where in the sub array categories[] contains value of 5 where $tourcontent[]['info']['categories'][] = 5 ?

答:
Or maybe if you don't need to foreach all the array, you could try something like:</p>

```<code>foreach($tourcontent['info']['categories'] as $category)
{
  if($category == 5)
  {
    echo "found!"
  }
}
</code>```

Body:
Hello I have the following array:

$tourcontent

and the following foreach:

foreach($tourcontent as $set)

How I can limit the result of the output of this foreach to be limited to only where in the sub array categories[] contains value of 5 where $tourcontent[]['info']['categories'][] = 5 ?

Body:
Or maybe if you don't need to foreach all the array, you could try something like:

foreach($tourcontent['info']['categories'] as $category)
{
  if($category == 5)
  {
    echo "found!"
  }
}


问:
How do I get the value of the first occurrence of array_walk_recursive in php
I have a deep multidimensional array that I am needing to extract the value of a specific key. I have found that the array_walk_recursive function will be my best option. I only need the first occurrence.

My array looks like this - (except much more complicated)

```<code>Array (
    [vehicle info] => Array (
        [one] => Array (
            [submodel] => LX
            [engine] => 2.3
        )
        [two] => Array (
            [color] => blue
            [year] => 2007
            [wheels] => 4
        )
        [three] => Array (
            [submodel] => LX
            [make] => Ford
            [model] => F-150
            [offroad] => No
        )
    )
)
</code>```

The issue here is, submodel is in both one and three. Additionally, the array is not consistent, so I must use array_walk_recursive to search through it for the matching key, then return the value for that key.

Here is my current code -

```<code>array_walk_recursive ($array, (function ($item, $key) {
    $wanted = "submodel";
    if ($key === $wanted) {
        echo ("$key is $item");
    }
}));
</code>```

The above returns submodel is LXsubmodel is LX.

Bonus Question!!
How can I search for multiple keys and return the first corresponding value for each of those? I was thinking putting all wanted keys in an array, then do a foreach loop, but don't quite know how to structure this. I am new to php.

答:
As far as there is no way to return early from array_walk_recursive(), I'd suggest to create a function to find the first occurrence of $wanted:

```<code>$arr = [
  'vehicle info' => [
     'one' => ['submodel' => 'LX', 'engine' => '2.3'],
     'two' => ['color' => 'blue', 'year' => '2007', 'wheels' => '4'],
     'three' => ['submodel' => 'LX', 'make' => 'Ford', 'model' => 'F-150', 'offroad' => 'No'],
    ],
];

function find($needle, $haystack, $found = '')
{
    foreach ($haystack as $key => $value) {
        if ($found) {
            break;
        }
        if ($key === $needle) {
            $found = "{$needle} is {$value}";
            break;
        }
        if (is_array($value)) {
            $found = find($needle, $value, $found);
        }
    }
    return $found;
}

$wanted = 'submodel';
$result = find($wanted, $arr);

var_dump($result); // string(14) "submodel is LX"
</code>```

Live demo

Update: to search for multiple keys you'll need to do it in a loop:

```<code>$multiple_keys = array('submodel', 'year');

foreach ($multiple_keys as $wanted) {
    var_dump(find($wanted, $arr));
}

// Output:
//    string(14) "submodel is LX"
//    string(12) "year is 2007"
</code>```

Live demo

Body:
I have a deep multidimensional array that I am needing to extract the value of a specific key. I have found that the array_walk_recursive function will be my best option. I only need the first occurrence.

My array looks like this - (except much more complicated)

Array (
    [vehicle info] => Array (
        [one] => Array (
            [submodel] => LX
            [engine] => 2.3
        )
        [two] => Array (
            [color] => blue
            [year] => 2007
            [wheels] => 4
        )
        [three] => Array (
            [submodel] => LX
            [make] => Ford
            [model] => F-150
            [offroad] => No
        )
    )
)

The issue here is, submodel is in both one and three. Additionally, the array is not consistent, so I must use array_walk_recursive to search through it for the matching key, then return the value for that key.

Here is my current code -

array_walk_recursive ($array, (function ($item, $key) {
    $wanted = "submodel";
    if ($key === $wanted) {
        echo ("$key is $item");
    }
}));

The above returns submodel is LXsubmodel is LX.

Bonus Question!!
How can I search for multiple keys and return the first corresponding value for each of those? I was thinking putting all wanted keys in an array, then do a foreach loop, but don't quite know how to structure this. I am new to php.

Body:
As far as there is no way to return early from array_walk_recursive(), I'd suggest to create a function to find the first occurrence of $wanted:

$arr = [
  'vehicle info' => [
     'one' => ['submodel' => 'LX', 'engine' => '2.3'],
     'two' => ['color' => 'blue', 'year' => '2007', 'wheels' => '4'],
     'three' => ['submodel' => 'LX', 'make' => 'Ford', 'model' => 'F-150', 'offroad' => 'No'],
    ],
];

function find($needle, $haystack, $found = '')
{
    foreach ($haystack as $key => $value) {
        if ($found) {
            break;
        }
        if ($key === $needle) {
            $found = "{$needle} is {$value}";
            break;
        }
        if (is_array($value)) {
            $found = find($needle, $value, $found);
        }
    }
    return $found;
}

$wanted = 'submodel';
$result = find($wanted, $arr);

var_dump($result); // string(14) "submodel is LX"

Live demo

Update: to search for multiple keys you'll need to do it in a loop:

$multiple_keys = array('submodel', 'year');

foreach ($multiple_keys as $wanted) {
    var_dump(find($wanted, $arr));
}

// Output:
//    string(14) "submodel is LX"
//    string(12) "year is 2007"

Live demo


问:
Creating a password in Bash
I currently have a password that is being generated, that is a hash of the date. I'd like to increase this generated password's security, by adding in some uppercase, lower case, numeric, and special characters, all to a minimum length of 10 characters.

What I currently have is below. As you can see, it assigns the output to my PASSWORD variable.

```<code>PASSWORD=$(date +%s | sha256sum | base64 | head -c 15)
</code>```

I'm unsure if I can do this inline, or, if I need to create a function within my bash script to suit? Is that even possible?

Many thanks in advance.

答:
With tr and head:

```<code>password=$(tr -dc 'A-Za-z0-9!?%=' < /dev/urandom | head -c 10)

echo "$password"
</code>```

Output (example):

```
k?lmyif6aE
```

tr reads bytes via stdin from Linux‘ special random device /dev/urandom and removes all bytes/characters but A to Z, a to z, 0 to 9 and !?%=. tr sends its output via stdout to head‘s stdin. head cuts output after 10 bytes.

Title: Creating a password in Bash

Body:
I currently have a password that is being generated, that is a hash of the date. I'd like to increase this generated password's security, by adding in some uppercase, lower case, numeric, and special characters, all to a minimum length of 10 characters.

What I currently have is below. As you can see, it assigns the output to my PASSWORD variable.

PASSWORD=$(date +%s | sha256sum | base64 | head -c 15)

I'm unsure if I can do this inline, or, if I need to create a function within my bash script to suit? Is that even possible?

Many thanks in advance.

Body:
With tr and head:

password=$(tr -dc 'A-Za-z0-9!?%=' < /dev/urandom | head -c 10)

echo "$password"

Output (example):

k?lmyif6aE

tr reads bytes via stdin from Linux‘ special random device /dev/urandom and removes all bytes/characters but A to Z, a to z, 0 to 9 and !?%=. tr sends its output via stdout to head‘s stdin. head cuts output after 10 bytes.


问:
Merging two columns with different information, python
I have a dataframe with one column of last names, and one column of first names. How do I merge these columns so that I have one column with first and last names?

Here is what I have:
First Name (Column 1)

John

Lisa

Jim

Last Name (Column 2)

Smith

Brown

Dandy

This is what I want:

Full Name

John Smith

Lisa Brown

Jim Dandy.

Thank you!

答:
Try

```<code>df.assign(name = df.apply(' '.join, axis = 1)).drop(['first name', 'last name'], axis = 1)
</code>```

You get

```<code>    name
0   bob smith
1   john smith
2   bill smith
</code>```

Body:
Try

df.assign(name = df.apply(' '.join, axis = 1)).drop(['first name', 'last name'], axis = 1)

You get

    name
0   bob smith
1   john smith
2   bill smith


答:
array_walk_recursive() is the appropriate native function to call for this task.  Keep track of which keys have already been declared in the result array and ensure that they are never overwritten.

Code: (Demo)

```<code>$needles = ['submodel', 'offroad'];
$result = [];
array_walk_recursive(
    $array,
    function($value, $key) use ($needles, &$result) {
        if (
            in_array($key, $needles)
            && !isset($result[$key])
        ) {
            $result[$key] = "$key is $value";
        }
    }
);
var_export($result);
</code>```

Output:

```<code>array (
  'submodel' => 'submodel is LX',
  'offroad' => 'offroad is No',
)
</code>```

If your application has performance concerns, then the native function becomes less attractive because it will always iterate the entire input array's structure -- even after all sought keys are encountered.  If you want to "break early" (short circuit), then you will need to design your own recursive function which will return when all sought keys are found.

Code: (Demo)

```<code>$soughtKeys = array_flip(['submodel', 'offroad']);

function earlyReturningRecursion(array $array, array $soughtKeys, array &$result = []): array
{
    foreach ($array as $key => $value) {
        if (!array_diff_key($soughtKeys, $result)) {  // check if result is complete
            return $result;
        } elseif (is_array($value)) {
            earlyReturningRecursion($value, $soughtKeys, $result);
        } elseif (isset($soughtKeys[$key]) && !isset($result[$key])) {
            $result[$key] = "$key is $value";
        }
    }
    return $result;
}
var_export(earlyReturningRecursion($array, $soughtKeys));
// same output as the first snippet
</code>```

Title: How do I get the value of the first occurrence of array_walk_recursive in php

Body:
array_walk_recursive() is the appropriate native function to call for this task.  Keep track of which keys have already been declared in the result array and ensure that they are never overwritten.

Code: (Demo)

$needles = ['submodel', 'offroad'];
$result = [];
array_walk_recursive(
    $array,
    function($value, $key) use ($needles, &$result) {
        if (
            in_array($key, $needles)
            && !isset($result[$key])
        ) {
            $result[$key] = "$key is $value";
        }
    }
);
var_export($result);

Output:

array (
  'submodel' => 'submodel is LX',
  'offroad' => 'offroad is No',
)

If your application has performance concerns, then the native function becomes less attractive because it will always iterate the entire input array's structure -- even after all sought keys are encountered.  If you want to "break early" (short circuit), then you will need to design your own recursive function which will return when all sought keys are found.

Code: (Demo)

$soughtKeys = array_flip(['submodel', 'offroad']);

function earlyReturningRecursion(array $array, array $soughtKeys, array &$result = []): array
{
    foreach ($array as $key => $value) {
        if (!array_diff_key($soughtKeys, $result)) {  // check if result is complete
            return $result;
        } elseif (is_array($value)) {
            earlyReturningRecursion($value, $soughtKeys, $result);
        } elseif (isset($soughtKeys[$key]) && !isset($result[$key])) {
            $result[$key] = "$key is $value";
        }
    }
    return $result;
}
var_export(earlyReturningRecursion($array, $soughtKeys));
// same output as the first snippet


问:
Website background transparent scale. How to Fix?
I complie my website via google chrome, It's transparent scale background

This Screen Image:
https://www.img.in.th/image/fyPY

How to Fix?
thank you in advance

答: You're going to want to add a background-color property to your website using CSS. You can find more information in this article.


问:
What is the right way to include Qt headers?
So far I know several ways to #include Qt classes:

#include <QtModule>

This brings all classes of a specific module, for example QDomDocument, QDomElement, QDomNode and numerous others from #include <QtXml>.

#include <QClassName>

This adds declaration of a specific class one may want to use, e.g. QEvent, QStringList, QFile.

#include <qcstyleheader.h>

This has effect of the previous method, except for differently looking header name.

So I wonder, are there any other ways to #include Qt classes? Are they equivalent, or are some of them preferred to others because of some reasons? Does this depend on #include-ing inside a .cpp or a .h file? Does this influence compilation speed and size of the executable?

In short, what is the best way to go?

答:
As a rule, the more header files there are, the longer it takes the compiler to parse each module.  (Obviously precompiled headers render some of this moot.)  So you generally want to include the fewest header files necessary to build your app correctly.

If you are only using a few classes in a given compilation unit, then just include the classes by name, in the modern style:

```<code>#include <QEvent>
#include <QPainter>
#include <QFont>
</code>```

If you use a large number of classes from a given module, it is probably just as easy to include the module-level header, such as:

```<code>#include <QtGui>
</code>```

You generally only use the older .h style if a newer style header doesn't exist.

Now precompiled headers mitigate many of these issues by compiling once into a binary form. But there is still a cost to loading the precompiled symbols into memory and searching through them at compilation time.  So the less you put in, the more efficient the build will be.

Body:
As a rule, the more header files there are, the longer it takes the compiler to parse each module.  (Obviously precompiled headers render some of this moot.)  So you generally want to include the fewest header files necessary to build your app correctly.

If you are only using a few classes in a given compilation unit, then just include the classes by name, in the modern style:

#include <QEvent>
#include <QPainter>
#include <QFont>

If you use a large number of classes from a given module, it is probably just as easy to include the module-level header, such as:

#include <QtGui>

You generally only use the older .h style if a newer style header doesn't exist.

Now precompiled headers mitigate many of these issues by compiling once into a binary form. But there is still a cost to loading the precompiled symbols into memory and searching through them at compilation time.  So the less you put in, the more efficient the build will be.


问:
php query in database doesn't work
Hello guys i tried to add into database some values and it's not working.I tried everything but no.
What should i do? the name of the table is "credit".
Can you help me to rezolv this problem?</p>

```<code><tr>
    <td><input class="form-control" placeholder="nr" name="nr" type="text" autofocus></td>
    <td><input class="form-control" placeholder="suma" name="suma" type="text" autofocus></td>
    <td><input class="form-control" placeholder="rate" name="rate" type="text" autofocus></td>
    <td><input class="form-control" placeholder="dobanda" name="dobanda" type="text" autofocus></td>
    <td><button class="btn btn-success" value="adaugare">Adaugare credit</button></a></td>
</tr>
</table>
</div>
</div>

<?php if(isset($_POST['adaugare']))
    {
        $nr=$_POST['nr'];
        $suma=$_POST['suma'];
        $rate=$_POST['rate'];
        $dobanda=$_POST['dobanda'];

        if($nr=='')
        {

            echo"<script>alert('Introdu numar')</script>";
            exit();
        }

        if($suma=='')
        {

            echo"<script>alert('Introdu suma')</script>";
            exit();
        }
        if($rate=='')
        {
            echo"<script>alert('Introdu rate')</script>";
            exit();
        }
        if($dobanda=='')
        {
            echo"<script>alert('Introdu dobanda')</script>";
            exit();
        }
        $id=$_SESSION['id'];
        $insert_credit="insert into credit VALUE ('$nr','$id','$suma','$rate','$dobanda')";
        mysqli_query($dbcon,$insert_credit);

    }
</code>```

答:
Your problem exist on line 43 becuase you defined the table names but ignores column names

Instead of this

```<code>$insert_credit="insert into credit VALUE ('$nr','$id','$suma','$rate','$dobanda')";
</code>```

Use the following code

```<code>$insert_credit="insert into credit (col_name1, col_name2, col_name3, col_name4, col_name5) VALUES ('$nr','$id','$suma','$rate','$dobanda')";
</code>```

and replace col_name* with your actual column names it will resolve your issue or if you're inserting into all columns then you can use this

```<code>$insert_credit="insert into credit VALUES ('$nr','$id','$suma','$rate','$dobanda')";
</code>```

Title: php query in database doesn't work

Body:
Hello guys i tried to add into database some values and it's not working.I tried everything but no.
What should i do? the name of the table is "credit".
Can you help me to rezolv this problem?

    <input class="form-control" placeholder="nr" name="nr" type="text" autofocus>
    <input class="form-control" placeholder="suma" name="suma" type="text" autofocus>
    <input class="form-control" placeholder="rate" name="rate" type="text" autofocus>
    <input class="form-control" placeholder="dobanda" name="dobanda" type="text" autofocus>
    <button class="btn btn-success" value="adaugare">Adaugare credit</button>

<?php if(isset($_POST['adaugare']))
    {
        $nr=$_POST['nr'];
        $suma=$_POST['suma'];
        $rate=$_POST['rate'];
        $dobanda=$_POST['dobanda'];

        if($nr=='')
        {

            echo"";
            exit();
        }

        if($suma=='')
        {

            echo"";
            exit();
        }
        if($rate=='')
        {
            echo"";
            exit();
        }
        if($dobanda=='')
        {
            echo"";
            exit();
        }
        $id=$_SESSION['id'];
        $insert_credit="insert into credit VALUE ('$nr','$id','$suma','$rate','$dobanda')";
        mysqli_query($dbcon,$insert_credit);

    }

Body:
Your problem exist on line 43 becuase you defined the table names but ignores column names

Instead of this

$insert_credit="insert into credit VALUE ('$nr','$id','$suma','$rate','$dobanda')";

Use the following code

$insert_credit="insert into credit (col_name1, col_name2, col_name3, col_name4, col_name5) VALUES ('$nr','$id','$suma','$rate','$dobanda')";

and replace col_name* with your actual column names it will resolve your issue or if you're inserting into all columns then you can use this

$insert_credit="insert into credit VALUES ('$nr','$id','$suma','$rate','$dobanda')";


问:
How SELECT different options AS value
I'm trying to populate storage table with sql. There are two two types of storage items, products and cols. Products consist of cols and have table 'prodcols' for linking.

I have:

```<code>Orderlines
- productID
- orderQTY

ProdCols
- productID
- colID
- colQTY

Storage
- itemID (can be productID or colID)
- itemType (Product or Col)
- itemName
- itemQTY
</code>```

Needed result:

```<code>itemType | itemID | itemName | itemQTY | itemOrderQTY | itemFreeQTY
Product  | 1001   | *name*   | 50      | 20           | 30
Col      | C101   | *name*   | 80      | 60           | 20

     SUM of orderQTYs (of each productID) AS itemOrderQTY
     itemQTY - itemOrderQTY AS itemFreeQTY

     itemQTY is maintained by other parts of software
</code>```

I have achieved a way to list either products or cols with needed qtys but don't know how to list them both with single clause. End result includes a few WHERE with variables to quickly narrow the results, itemName for example.

My Attempt for cols, works but is slow:

```<code>    (SELECT ProdCols.ColQTY*(SELECT SUM(OrderQTY)FROM Orderlines WHERE productID
 IN (SELECT ProductID FROM ProdCols WHERE ProdCols.ColID=storage.itemID) AND ..)
 AS itemOrderQTY
FROM Storage, Orderlines, ProdCols
GROUP BY Storage.Itemid, Storage.type, Storage.name, Storage.qty..
</code>```

For products this works ok:

```<code>(SELECT SUM(orderlines.orderQTY) FROM orderlines
    WHERE orderlines.productID=storage.itemID AND ...) AS itemOrderQTY
    FROM storage, orderlines
    GROUP BY storage.itemID,storage.itemType,storage.itemName, storage.ItemQTY
</code>```

Is there a way to UNION these two? Why is the one for cols performing very slow?

I'm running ms sql server express with custom platform.

ps. sorry for bad naming for question, just couldn't come up with better one..

答:
Are you looking something like this?

```<code>Select S.ItemName, S.itemQty, p.ProductId, p1.ColId, p1.ColQty,
    Sum(o.OrderQty) over(partition by p.ProductId) as ItemOrderQty,
    S.ItemQty - Sum(o.OrderQty) over(partition by p.ProductId) as ItemFreeQty
from Storage s
left join ProdCols p
    on s.ItemId = P.ProductID
    and s.itemType = 'Product'
left join ProdCols P1
    on s.ItemId = P.ColId
    and s.itemType = 'Col'
left join OrderLines o
    on p.ProductId = o.ProductId
</code>```

You might required to change to inner join for some of the tables based on your requirement

Title: How SELECT different options AS value

Body:
I'm trying to populate storage table with sql. There are two two types of storage items, products and cols. Products consist of cols and have table 'prodcols' for linking.

I have:

Orderlines
- productID
- orderQTY

ProdCols
- productID
- colID
- colQTY

Storage
- itemID (can be productID or colID)
- itemType (Product or Col)
- itemName
- itemQTY

Needed result:

itemType | itemID | itemName | itemQTY | itemOrderQTY | itemFreeQTY
Product  | 1001   | *name*   | 50      | 20           | 30
Col      | C101   | *name*   | 80      | 60           | 20

     SUM of orderQTYs (of each productID) AS itemOrderQTY
     itemQTY - itemOrderQTY AS itemFreeQTY

     itemQTY is maintained by other parts of software

I have achieved a way to list either products or cols with needed qtys but don't know how to list them both with single clause. End result includes a few WHERE with variables to quickly narrow the results, itemName for example.

My Attempt for cols, works but is slow:

    (SELECT ProdCols.ColQTY*(SELECT SUM(OrderQTY)FROM Orderlines WHERE productID
 IN (SELECT ProductID FROM ProdCols WHERE ProdCols.ColID=storage.itemID) AND ..)
 AS itemOrderQTY
FROM Storage, Orderlines, ProdCols
GROUP BY Storage.Itemid, Storage.type, Storage.name, Storage.qty..

For products this works ok:

(SELECT SUM(orderlines.orderQTY) FROM orderlines
    WHERE orderlines.productID=storage.itemID AND ...) AS itemOrderQTY
    FROM storage, orderlines
    GROUP BY storage.itemID,storage.itemType,storage.itemName, storage.ItemQTY

Is there a way to UNION these two? Why is the one for cols performing very slow?

I'm running ms sql server express with custom platform.

ps. sorry for bad naming for question, just couldn't come up with better one..

Body:
Are you looking something like this?

Select S.ItemName, S.itemQty, p.ProductId, p1.ColId, p1.ColQty,
    Sum(o.OrderQty) over(partition by p.ProductId) as ItemOrderQty,
    S.ItemQty - Sum(o.OrderQty) over(partition by p.ProductId) as ItemFreeQty
from Storage s
left join ProdCols p
    on s.ItemId = P.ProductID
    and s.itemType = 'Product'
left join ProdCols P1
    on s.ItemId = P.ColId
    and s.itemType = 'Col'
left join OrderLines o
    on p.ProductId = o.ProductId

You might required to change to inner join for some of the tables based on your requirement


问:
Django server side caching of uploaded file
I am running a server in django and I want to serve a file. I am storing the file under '/upload/directory/filename' and I return it using

```<code>from django.shortcuts import redirect

file_path = '/upload/directory/filename'
return redirect(file_path)
</code>```

However, the file appears to have been cached to the first version that had been placed locally and is never updated. Even if I remove the file, the file is still served. I checked that if I change the path to 'upload/directory_2/filename then I correctly get my new file. What is going on and how can I fight this ?

This is happening locally and I am making a direct server request (hence there is no possibility of browser caching or anything else).

Additional information:

I understand that maybe I should be using static files, although for instance this answer suggests that it is quite debatable for files that I am uploading myself.

When I say "I want to serve files with django" I just mean that I have associated a file path to a particular entity in my database (using models.FileField) and based on what the user requests I want to return this file. I kind of doubt this is a clear cut for using static files in that case.

There are many workarounds to my issue, like generating unique filenames every time I want to "clear my cache" or explicitly opening the file:

```<code>with open(absolute_file_path) as file:
    response = HttpResponse(file.read(), content_type='application/octet-stream')
</code>```

My question was about understanding why the particular piece of code above does what it does, i.e. leads to data caching, and how to prevent this.

答:
If you must do this using Django itself, I would suggest skipping the redirect and setting up your app according to these directions:

https://docs.djangoproject.com/en/1.11/howto/static-files/#serving-files-uploaded-by-a-user-during-development

Make your MEDIA_URL something like /media/ or if you want it to match your current case /upload/ or something. MEDIA_ROOT could point to os.path.join(BASE_DIR, 'upload') and your FileField(upload_to='directory').

Body:
I am running a server in django and I want to serve a file. I am storing the file under '/upload/directory/filename' and I return it using

from django.shortcuts import redirect

file_path = '/upload/directory/filename'
return redirect(file_path)

However, the file appears to have been cached to the first version that had been placed locally and is never updated. Even if I remove the file, the file is still served. I checked that if I change the path to 'upload/directory_2/filename then I correctly get my new file. What is going on and how can I fight this ?

This is happening locally and I am making a direct server request (hence there is no possibility of browser caching or anything else).

Additional information:

I understand that maybe I should be using static files, although for instance this answer suggests that it is quite debatable for files that I am uploading myself.

When I say "I want to serve files with django" I just mean that I have associated a file path to a particular entity in my database (using models.FileField) and based on what the user requests I want to return this file. I kind of doubt this is a clear cut for using static files in that case.

There are many workarounds to my issue, like generating unique filenames every time I want to "clear my cache" or explicitly opening the file:

with open(absolute_file_path) as file:
    response = HttpResponse(file.read(), content_type='application/octet-stream')

My question was about understanding why the particular piece of code above does what it does, i.e. leads to data caching, and how to prevent this.


问:
How to select tuples that begin with a certain substring in R
I have a data frame that looks as follows

```<code>> df[1:10,c("Uri","Latency")]
                                                                                Uri
1                          /filters/test_group_1/test_datasource%20with%20space/test_application_alias_100
2                                                          /applications?includeDashboards&includeMappings
3                                                                   /applications/test_application_alias_1
4                                                          /applications?includeDashboards&includeMappings
5                                                                 /applications/test_application_alias_200
6                                                                 /applications/test_application_alias_100
7    /filters/00000000-0000-0000-0000-000000000001/test_datasource%20with%20space/test_application_alias_0
8                                             /dashboards?dashboard=test_dashboard_alias_9&includeMappings
9               /filters/00000000-0000-0000-0000-000000000001/test_dataSource_1/test_application_alias_100
10 /filters/00000000-0000-0000-0000-000000000001/test_datasource%20with%20space/test_application_alias_100
   Latency
1      296
2     1388
3       58
4      833
5      239
6       60
7      217
8       36
9       86
10     112
</code>```

I want to select only those rows that start with /applications. Note that the rest of the Uri could be anything, and is not important.

I could've got the exact matches by doing the following,

```<code>df[which(df$Uri == "/applications"),c("Uri","Latency")]
</code>```

However, since, I am looking for a substring, I understand, I may have to do some wildcard processing, which in SQL would look like.

```<code>select * from <table_name> where Uri like '%/applications%'
</code>```

How can I do the same in R

答:
I'd use a regular expression:</p>

```<code>df[ grepl( "^\\/applications" , df[, "Uri"] ) , c("Uri","Latency") ]
</code>```

Body:
I have a data frame that looks as follows

> df[1:10,c("Uri","Latency")]
                                                                                Uri
1                          /filters/test_group_1/test_datasource%20with%20space/test_application_alias_100
2                                                          /applications?includeDashboards&includeMappings
3                                                                   /applications/test_application_alias_1
4                                                          /applications?includeDashboards&includeMappings
5                                                                 /applications/test_application_alias_200
6                                                                 /applications/test_application_alias_100
7    /filters/00000000-0000-0000-0000-000000000001/test_datasource%20with%20space/test_application_alias_0
8                                             /dashboards?dashboard=test_dashboard_alias_9&includeMappings
9               /filters/00000000-0000-0000-0000-000000000001/test_dataSource_1/test_application_alias_100
10 /filters/00000000-0000-0000-0000-000000000001/test_datasource%20with%20space/test_application_alias_100
   Latency
1      296
2     1388
3       58
4      833
5      239
6       60
7      217
8       36
9       86
10     112

I want to select only those rows that start with /applications. Note that the rest of the Uri could be anything, and is not important.

I could've got the exact matches by doing the following,

df[which(df$Uri == "/applications"),c("Uri","Latency")]

However, since, I am looking for a substring, I understand, I may have to do some wildcard processing, which in SQL would look like.

select * from <table_name> where Uri like '%/applications%'

How can I do the same in R

Body:
I'd use a regular expression:

df[ grepl( "^\\/applications" , df[, "Uri"] ) , c("Uri","Latency") ]


问:
UIApplication.shared.isNetworkActivityIndicatorVisible crash when setting to false
I have a huge issue with my app. Whenever I set:

```<code>UIApplication.shared.isNetworkActivityIndicatorVisible = false
</code>```

after I had previously set it to true, I get an NSZombie which shows the following:

"An Objective-C message was sent to a deallocatedUIActivityIndicatorView' object (zombie) at address: 0x102b334d0

Can't add images because I don't have the reputation yet.. :(

but here are the links:

http://imgur.com/3i7TeSV

http://imgur.com/E2oUq4e

I am pretty lost here. My project is both in Swift and Objective-C. I have been doing research for the last 24 hours and couldn't find anything. The app only crashes on device, in the simulator it works perfectly.

Thanks for the help!

答:
Try this</p>

```<code>DispatchQueue.main.async {
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
}
</code>```

Body:
I have a huge issue with my app. Whenever I set:

UIApplication.shared.isNetworkActivityIndicatorVisible = false

after I had previously set it to true, I get an NSZombie which shows the following:

"An Objective-C message was sent to a deallocatedUIActivityIndicatorView' object (zombie) at address: 0x102b334d0

Can't add images because I don't have the reputation yet.. :(

but here are the links:

http://imgur.com/3i7TeSV

http://imgur.com/E2oUq4e

I am pretty lost here. My project is both in Swift and Objective-C. I have been doing research for the last 24 hours and couldn't find anything. The app only crashes on device, in the simulator it works perfectly.

Thanks for the help!

Body:
Try this

DispatchQueue.main.async {
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
}


问:
When and why JPA entities should implement the Serializable interface?
The question is in the title. Below I just described some of my thoughts and findings.

When I had a very simple domain model (3 tables without any relations), all my entities did NOT implement the Serializable interface.

But when the domain model became more complex, I got a RuntimeException, saying that one of my entities didn't implement Serializable.

I use Hibernate as a JPA implementation, and I wonder:

Is it a vendor-specific requirement/behavior?

What happens with my serializable entities? Should they be serializable for storing or for transferring?

At which moment it becomes necessary to make my entity serializable?

答: This is also the error that's thrown when you pass an incorrectly-typed ID as the second param to something like em.find() (i.e. passing the entity itself rather than its ID). I haven't found it yet necessary to actually declare JPA entities serializable--it's not really necessary unless you're using referencedColumnName as described by aman.</p>


问:
Execute an script's Start() after another script's Start() Unity C#
I would like to run the Start() from one script just before the Start() of another Script. Is it possible? Can you choose the order of the executions of the scripts?</p>

答:
What you may be able to do is normally do the script that you are wanting first however you would like it. However lets say your wanting to run the other script at the end of the first script, You may be able to reference a function by using this (Replacing SecondScriptName with the script you want to go after the first one then replacing FunctionFromSecondScript with the Function from that script)

```<code>  <SecondScriptName>().FunctionFromSecondScript();
</code>```

You can then call all of the functions in turn in whatever order you wish.

If i make a mistake, Please forgive me as this is my first comment to help another programmer and I am currently a budding one myself.

Hope this helps :)

Body:
What you may be able to do is normally do the script that you are wanting first however you would like it. However lets say your wanting to run the other script at the end of the first script, You may be able to reference a function by using this (Replacing SecondScriptName with the script you want to go after the first one then replacing FunctionFromSecondScript with the Function from that script)

  <SecondScriptName>().FunctionFromSecondScript();

You can then call all of the functions in turn in whatever order you wish.

If i make a mistake, Please forgive me as this is my first comment to help another programmer and I am currently a budding one myself.

Hope this helps :)


问:
Find if two strings are same in an array?
I have an array of objects. Each object has an property called title , I want to know if two object has the same title. How to do that in swift?</p>

答:
If you want the list of objects which have the same title as another object in the array, you can do this (assuming title is a String):

```<code>var titles     = Set<String>()
let duplicates = array.filter{ !titles.insert($0.title).inserted }

// note: this only lists the second and subsequent element with a given title
</code>```

if you need their indexes, you can do this:

```<code>var titles     = Set<String>()
let dupIndexes = array.enumerated()
                      .filter{ !titles.insert($1.title).inserted }
                      .map{$0.0}
</code>```

If you want all objects where the title is duplicated (including the first one) you can refine the first approach like this:

```<code>var titles     = Set<String>()
let dupTitles  = Set(array.map{$0.title}.filter{!titles.insert($0).inserted})
let dupObjects = array.filter{dupTitles.contains($0.title)}
</code>```

[EDIT] Swift 4 has a new Dictionary initializer that can be used for this:

```<code>let dupObjects = Dictionary(grouping:array){$0.title}
                .filter{$0.value.count > 1}
                .flatMap{$0.value}
</code>```

In all cases, if the .count of duplicates, dupIndexes or dupObjects is > 0 hen you have at least one duplication in the array

Body:
If you want the list of objects which have the same title as another object in the array, you can do this (assuming title is a String):

var titles     = Set<String>()
let duplicates = array.filter{ !titles.insert($0.title).inserted }

// note: this only lists the second and subsequent element with a given title

if you need their indexes, you can do this:

var titles     = Set<String>()
let dupIndexes = array.enumerated()
                      .filter{ !titles.insert($1.title).inserted }
                      .map{$0.0}

If you want all objects where the title is duplicated (including the first one) you can refine the first approach like this:

var titles     = Set<String>()
let dupTitles  = Set(array.map{$0.title}.filter{!titles.insert($0).inserted})
let dupObjects = array.filter{dupTitles.contains($0.title)}

[EDIT] Swift 4 has a new Dictionary initializer that can be used for this:

let dupObjects = Dictionary(grouping:array){$0.title}
                .filter{$0.value.count > 1}
                .flatMap{$0.value}

In all cases, if the .count of duplicates, dupIndexes or dupObjects is > 0 hen you have at least one duplication in the array


问:
Meteor: Programmatically generate password reset token?
In Meteor, how do you programmatically generate / store a reset password token for a user (outside the context of a user asking for it themselves in the UI)?

I am sending a custom email and would like to embed my own "Reset Password" button within it. This requires me to generate a valid reset password token on my own.

Are there any undocumented Accounts functions / helpers that I'm not aware of that can help me achieve this? Thanks!

答:
For most scenarios, I recommend using the in-built Accounts.sendResetPasswordEmail for sending the email and overriding Accounts.emailTemplates.resetPassword to do customizations for the email. For example, you can do a custom reset link like this:

Accounts.emailTemplates.resetPassword.html = (user, url) =>
  `Reset your password`;
```

<p>However, if you need more customizability than this, there is no ready function for creating the reset token, but if you look at the source code for <code>Accounts.sendResetPasswordEmail</code>, you'll see that really you only need to insert an object in the <code>services.password.reset</code> field of the user object like so:</p>

<pre class="lang-js prettyprint-override"><code>var token = Random.secret();
var when = new Date();
var tokenRecord = {
  token: token,
  email: email,
  when: when,
  reason: 'reset'
};
Meteor.users.update(userId, {$set: {
  "services.password.reset": tokenRecord
}});

var resetPasswordUrl = Accounts.urls.resetPassword(token);
</code>```

Now you can send resetPasswordUrl to your user in any way you like, it should work. Be careful with security though - I suppose that the lack of a ready-made function for generating password reset tokens is intentional, and meant to discourage people from carelessly creating password reset methods.

Body:
For most scenarios, I recommend using the in-built Accounts.sendResetPasswordEmail for sending the email and overriding Accounts.emailTemplates.resetPassword to do customizations for the email. For example, you can do a custom reset link like this:

Accounts.emailTemplates.resetPassword.html = (user, url) =>
  `<a href="${url}" style="{ something cool... }">Reset your password</a>`;

However, if you need more customizability than this, there is no ready function for creating the reset token, but if you look at the source code for Accounts.sendResetPasswordEmail, you'll see that really you only need to insert an object in the services.password.reset field of the user object like so:

var token = Random.secret();
var when = new Date();
var tokenRecord = {
  token: token,
  email: email,
  when: when,
  reason: 'reset'
};
Meteor.users.update(userId, {$set: {
  "services.password.reset": tokenRecord
}});

var resetPasswordUrl = Accounts.urls.resetPassword(token);

Now you can send resetPasswordUrl to your user in any way you like, it should work. Be careful with security though - I suppose that the lack of a ready-made function for generating password reset tokens is intentional, and meant to discourage people from carelessly creating password reset methods.