问:
Rselenium scraping loop and list
I'm trying to use this code:

```<code>require(RSelenium)
checkForServer()
startServer()
remDr<-remoteDriver()
remDr$open()

appURL <- 'http://www.mtmis.excise-punjab.gov.pk'
remDr$navigate(appURL)
remDr$findElement("name", "vhlno")$sendKeysToElement(list("ria-07-777"))
</code>```

Can't figure out css selector

```<code>remDr$findElements("class", "ent-button-div")[[1]]$clickElement()
</code>```

after searching query

```<code>elem <- remDr$findElement(using="class", value="result-div")
elemtxt <- elem$getElementAttribute("outerHTML")[[1]]
elemxml <- htmlTreeParse(elemtxt, useInternalNodes=T)
final <- readHTMLTable(elemxml)

remDr$close()
rD[["server"]]$stop()
</code>```

What I want is to create an automated "for loop" with different vehicles from list and merge all into one final table with unique identifier, e.g., "ria-07-777".

```<code>list <- c("ria-07-776", "ria-07-777", "ria-07-778")
</code>```

答:
Why do you need Selenium?

```<code>library(httr)
library(rvest)

clean_cols <- function(x) {
  x <- tolower(x)
  x <- gsub("[[:punct:][:space:]]+", "_", x)
  x <- gsub("_+", "_", x)
  x <- gsub("(^_|_$)", "", x)
  make.unique(x, sep = "_")
}

get_vehicle_info <- function(vhlno) {

  POST(
    url = 'http://www.mtmis.excise-punjab.gov.pk/',
    set_cookies(has_js=1),
    body = list(vhlno=vhlno)
  ) -> res

  stop_for_status(res)

  pg <- content(res)
  rows <- html_nodes(pg, xpath=".//div[contains(@class, 'result-div')]/table/tr[td[not(@colspan)]]")

  cbind.data.frame(
    as.list(
      setNames(
        html_text(html_nodes(rows, xpath=".//td[2]")),
        clean_cols(html_text(html_nodes(rows, xpath=".//td[1]")))
      )
    ),
    stringsAsFactors=FALSE
  )

}
</code>```

Now use ^^:

```<code>vehicles <- c("ria-07-776", "ria-07-777", "ria-07-778")

Reduce(
  rbind.data.frame,
  lapply(vehicles, function(v) {
    Sys.sleep(5) # your desire to steal a bunch of vehicle info to make a sketch database does not give you the right to hammer the server, and you'll very likely remove this line anyway, but I had to try
    get_vehicle_info(v)
  })
) -> vehicle_df

str(vehicle_df)
## 'data.frame': 3 obs. of  12 variables:
##  $ registration_number: chr  "ria-07-776" "ria-07-777" "ria-07-778"
##  $ chassis_number     : chr  "KZJ95-0019869" "NFBFD15746R101101" "NZE1206066278"
##  $ engine_number      : chr  "1KZ-0375851" "R18A11981105" "X583994"
##  $ make_name          : chr  "LAND - CRUISER" "HONDA - CIVIC" "TOYOTA - COROLLA"
##  $ registration_date  : chr  "17-Dec-2007 12:00 AM" "01-Aug-2007 12:00 AM" "01-Jan-1970 12:00 AM"
##  $ model              : chr  "1997" "2006" "2007"
##  $ vehicle_price      : chr  "1,396,400" "1,465,500" "0"
##  $ color              : chr  "MULTI" "GRENDA B.P" "SILVER"
##  $ token_tax_paid_upto: chr  "June 2015" "June 2011" "June 2016"
##  $ owner_name         : chr  "FATEH DIN AWAN" "M BILAL YASIN" "MUHAMMAD ALTAF"
##  $ father_name        : chr  "HAFIZ ABDUL HAKEEM AWAN" "CH M. YASIN" "NAZAR MUHAMMAD"
##  $ owner_city         : chr  "RAWALPINDI" "ISLAMABAD" "SARGODHA"
</code>```

You'll need to handle network and scraping errors on your own. I can't justify any more time for this likely unethical endeavour (the answer was more to help others with similar q's).

Title: Rselenium scraping loop and list

Body:
I'm trying to use this code:

require(RSelenium)
checkForServer()
startServer()
remDr<-remoteDriver()
remDr$open()

appURL <- 'http://www.mtmis.excise-punjab.gov.pk'
remDr$navigate(appURL)
remDr$findElement("name", "vhlno")$sendKeysToElement(list("ria-07-777"))

Can't figure out css selector

remDr$findElements("class", "ent-button-div")[[1]]$clickElement()

after searching query

elem <- remDr$findElement(using="class", value="result-div")
elemtxt <- elem$getElementAttribute("outerHTML")[[1]]
elemxml <- htmlTreeParse(elemtxt, useInternalNodes=T)
final <- readHTMLTable(elemxml)

remDr$close()
rD[["server"]]$stop()

What I want is to create an automated "for loop" with different vehicles from list and merge all into one final table with unique identifier, e.g., "ria-07-777".

list <- c("ria-07-776", "ria-07-777", "ria-07-778")

Body:
Why do you need Selenium?

library(httr)
library(rvest)

clean_cols <- function(x) {
  x <- tolower(x)
  x <- gsub("[[:punct:][:space:]]+", "_", x)
  x <- gsub("_+", "_", x)
  x <- gsub("(^_|_$)", "", x)
  make.unique(x, sep = "_")
}

get_vehicle_info <- function(vhlno) {

  POST(
    url = 'http://www.mtmis.excise-punjab.gov.pk/',
    set_cookies(has_js=1),
    body = list(vhlno=vhlno)
  ) -> res

  stop_for_status(res)

  pg <- content(res)
  rows <- html_nodes(pg, xpath=".//div[contains(@class, 'result-div')]/table/tr[td[not(@colspan)]]")

  cbind.data.frame(
    as.list(
      setNames(
        html_text(html_nodes(rows, xpath=".//td[2]")),
        clean_cols(html_text(html_nodes(rows, xpath=".//td[1]")))
      )
    ),
    stringsAsFactors=FALSE
  )

}

Now use ^^:

vehicles <- c("ria-07-776", "ria-07-777", "ria-07-778")

Reduce(
  rbind.data.frame,
  lapply(vehicles, function(v) {
    Sys.sleep(5) # your desire to steal a bunch of vehicle info to make a sketch database does not give you the right to hammer the server, and you'll very likely remove this line anyway, but I had to try
    get_vehicle_info(v)
  })
) -> vehicle_df

str(vehicle_df)
## 'data.frame': 3 obs. of  12 variables:
##  $ registration_number: chr  "ria-07-776" "ria-07-777" "ria-07-778"
##  $ chassis_number     : chr  "KZJ95-0019869" "NFBFD15746R101101" "NZE1206066278"
##  $ engine_number      : chr  "1KZ-0375851" "R18A11981105" "X583994"
##  $ make_name          : chr  "LAND - CRUISER" "HONDA - CIVIC" "TOYOTA - COROLLA"
##  $ registration_date  : chr  "17-Dec-2007 12:00 AM" "01-Aug-2007 12:00 AM" "01-Jan-1970 12:00 AM"
##  $ model              : chr  "1997" "2006" "2007"
##  $ vehicle_price      : chr  "1,396,400" "1,465,500" "0"
##  $ color              : chr  "MULTI" "GRENDA B.P" "SILVER"
##  $ token_tax_paid_upto: chr  "June 2015" "June 2011" "June 2016"
##  $ owner_name         : chr  "FATEH DIN AWAN" "M BILAL YASIN" "MUHAMMAD ALTAF"
##  $ father_name        : chr  "HAFIZ ABDUL HAKEEM AWAN" "CH M. YASIN" "NAZAR MUHAMMAD"
##  $ owner_city         : chr  "RAWALPINDI" "ISLAMABAD" "SARGODHA"

You'll need to handle network and scraping errors on your own. I can't justify any more time for this likely unethical endeavour (the answer was more to help others with similar q's).


来源: stackexchange

问:
how to make element check code simpler or one-liner in python?
I wanna make simple condition to check whether element 'a' in A and element 'b' in B has a some characteristic.

the below code operates well, it looks dirty, so, I wanna make it simpler, or one-liner. are there any way to do that?

```<code>    def check_direction(A, B):
        for a in A:
            for b in B:
                if c_matrix.loc()[a][b]!="->":
                    return False
        return True
</code>```

答:
Ignoring the possible pandas or numpy angles that c_matrix.loc() suggests might be available, you can use all() to get the exact same functionality:

```<code>return all(c_matrix.loc()[a][b] == "->" for a in A for b in B)
</code>```

all() short-circuits; as soon as a c_matrix.loc()[a][b] == "->" fails, False is returned. True is only produced if all tests pass.

ContentLicense: CC BY-SA 3.0

Body:
I wanna make simple condition to check whether element 'a' in A and element 'b' in B has a some characteristic.

the below code operates well, it looks dirty, so, I wanna make it simpler, or one-liner. are there any way to do that?

    def check_direction(A, B):
        for a in A:
            for b in B:
                if c_matrix.loc()[a][b]!="->":
                    return False
        return True

Body:
Ignoring the possible pandas or numpy angles that c_matrix.loc() suggests might be available, you can use all() to get the exact same functionality:

return all(c_matrix.loc()[a][b] == "->" for a in A for b in B)

all() short-circuits; as soon as a c_matrix.loc()[a][b] == "->" fails, False is returned. True is only produced if all tests pass.


问:
How can I use an if statement in a JavaScript array
How can I use an if statement in a JavaScript array. Below is the code I have tried but it's not working yet.

```<code>var today = new Date();

var dd = today.getDate();

var mm = today.getMonth() + 1;

var yyyy = today.getFullYear();

var today = yyyy + '-' + mm + '-' + dd;

//--------------------- Begin Of Calendar Event ---------------------------//

var calendarEvents = [

  if (today == today) {

    {
      title: 'Nigeria Independence',
      url: 'http://google.com/',
      start: today
    }

  }

];

//--------------------- End Of Calendar Event ----------------------------//
</code>```

答:
First off, your condition is always true. So change it like this:

```<code>if ((new Date()) == today) {
</code>```

Also, the above condition might not work, because new Date() is not today. You need to format it right.

Secondly, to have a conditional inside an array, use a ternary operator:

var today = new Date();
var calendarEvents = [
  (today == today) ? {
    title: 'Nigeria Independence',
    url: 'http://google.com/',
    start: today
  } :
  "Not Today"
];

console.log(calendarEvents);```

Body:
How can I use an if statement in a JavaScript array. Below is the code I have tried but it's not working yet.

var today = new Date();

var dd = today.getDate();

var mm = today.getMonth() + 1;

var yyyy = today.getFullYear();

var today = yyyy + '-' + mm + '-' + dd;

//--------------------- Begin Of Calendar Event ---------------------------//

var calendarEvents = [

  if (today == today) {

    {
      title: 'Nigeria Independence',
      url: 'http://google.com/',
      start: today
    }

  }

];

//--------------------- End Of Calendar Event ----------------------------//

Body:
First off, your condition is always true. So change it like this:

if ((new Date()) == today) {

Also, the above condition might not work, because new Date() is not today. You need to format it right.

Secondly, to have a conditional inside an array, use a ternary operator:

var today = new Date();
var calendarEvents = [
  (today == today) ? {
    title: 'Nigeria Independence',
    url: 'http://google.com/',
    start: today
  } :
  "Not Today"
];

console.log(calendarEvents);


答:
Do it like this so that if today does = today, then create the array

```<code>var today = new Date();

var dd = today.getDate();

var mm = today.getMonth() + 1;

var yyyy = today.getFullYear();

var today = yyyy + '-' + mm + '-' + dd;

//--------------------- Begin Of Calendar Event ---------------------------//

  if (today == today) {

   var calendarEvents = [
      {
        title: 'Nigeria Independence',
        url: 'http://google.com/',
        start: today
      }
   ];

  }

//--------------------- End Of Calendar Event ----------------------------//
</code>```

Title: How can I use an if statement in a JavaScript array

Body:
Do it like this so that if today does = today, then create the array

var today = new Date();

var dd = today.getDate();

var mm = today.getMonth() + 1;

var yyyy = today.getFullYear();

var today = yyyy + '-' + mm + '-' + dd;

//--------------------- Begin Of Calendar Event ---------------------------//

  if (today == today) {

   var calendarEvents = [
      {
        title: 'Nigeria Independence',
        url: 'http://google.com/',
        start: today
      }
   ];

  }

//--------------------- End Of Calendar Event ----------------------------//


问:
How to access model attribute in html page in Spring MVC?
I have Spring MVC project where the views are html pages. I am setting model attribute in my Controller method but unable to access it on html view page.

Here is my Controller method.

```<code>@RequestMapping(value = "/", method = RequestMethod.GET)
 public ModelAndView getData() {

  ModelAndView model =new ModelAndView();
  model.addObject("name", "Jack");
  model.setViewName("html/firstLayer.html");
  return model;

 }
</code>```

This is how i am accessing it in my html page

```<code><script type="text/javascript">
    var name1 ='${name}' ;
    console.log(name1);
 </script>
</code>```

But on console it is printing ${name}, it should print Jack.
Any help will be appreciated , Thanks.

答:
You cannot do that directly through Javascript. You either need to use a JSP file to retrieve the server side ModelAndView variable that you have set.

Or you can go with a better solution.

```<code>@RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getData() throws JsonProcessingException {
    Map<String, Object> myData = new LinkedHashMap<>();
    myData.put("name", "Jacky");
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.writeValueAsString(myData);
}
</code>```

Basically when you do a get, you will return a string to the client side, then you can take the string from the request via a ajax call and manipulate the data with javascript as you want.

Spoiler: this is a very rough implementation. I would recommend changing the Map into an object, like a separate class MyDataClas with the fields that you want and if you are using spring web, you can add jackson in your classpath and instead of converting your object into string, you can return directly your class (spring will deal with serialization of the object to json):

```<code> @RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody MyDataClass getData() {
    final MyDataClass myDataClass = new MyDataClass();
    myDataClass.setName("Jacky");
    return myDataClass;
}
</code>```

This would look much better than the first and cleaner.

You can look over a few tutorials regarding this to better understand how this works here

Body:
I have Spring MVC project where the views are html pages. I am setting model attribute in my Controller method but unable to access it on html view page.

Here is my Controller method.

@RequestMapping(value = "/", method = RequestMethod.GET)
 public ModelAndView getData() {

  ModelAndView model =new ModelAndView();
  model.addObject("name", "Jack");
  model.setViewName("html/firstLayer.html");
  return model;

 }

This is how i am accessing it in my html page

But on console it is printing ${name}, it should print Jack.
Any help will be appreciated , Thanks.

Body:
You cannot do that directly through Javascript. You either need to use a JSP file to retrieve the server side ModelAndView variable that you have set.

Or you can go with a better solution.

@RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getData() throws JsonProcessingException {
    Map<String, Object> myData = new LinkedHashMap<>();
    myData.put("name", "Jacky");
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.writeValueAsString(myData);
}

Basically when you do a get, you will return a string to the client side, then you can take the string from the request via a ajax call and manipulate the data with javascript as you want.

Spoiler: this is a very rough implementation. I would recommend changing the Map into an object, like a separate class MyDataClas with the fields that you want and if you are using spring web, you can add jackson in your classpath and instead of converting your object into string, you can return directly your class (spring will deal with serialization of the object to json):

 @RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody MyDataClass getData() {
    final MyDataClass myDataClass = new MyDataClass();
    myDataClass.setName("Jacky");
    return myDataClass;
}

This would look much better than the first and cleaner.

You can look over a few tutorials regarding this to better understand how this works here


问:
Kafka partition Lag increasing
I have an application which uses Kafka 1.0 as a queue. The Kafka topic has 80 partitions and 80 consumers running. (Kafka-python consumers).

By running the command :

```<code>./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group mygroup  --describe
</code>```

I see that one of the partitions is stuck at an offset, and the lag continuously increases as new records are added to it.

The output of the above command looks something like this:

```<code>TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG        CONSUMER-ID                                       HOST

118 mytopic                       37         1924            2782            858        kafka-python-1.3.4-3da99d4d-63e8-4e72-967e-xxxxxxxxxxx/localhost
119 mytopic                       38         2741            2742            1          kafka-python-1.3.4-40b44482-39fc-42d0-8f55-xxxxxxxxxxx/localhost
120 mytopic                       39         2713            2713            0          kafka-python-1.3.4-4121d080-1d7c-4d6b-ac58-xxxxxxxxxxx/localhost
121 mytopic                       40         2687            2688            1          kafka-python-1.3.4-43441f6e-fd35-448e-b791-xxxxxxxxxxx/localhost
</code>```

What causes this? Also resetting offset using reset-offsets command is not desirable as this server might not be manually monitored on a regular basis.

Clients run in background as parallel processes in a Linux m/c:

```<code>consumer = KafkaConsumer('mytopic', group_id='mygroup', bootstrap_servers='localhost:9092',
                     session_timeout_ms=120000, heartbeat_interval_ms=100000, max_poll_records=1,
                     auto_commit_interval_ms=100000, request_timeout_ms=350000, max_partition_fetch_bytes=3*1024*1024,
                     value_deserializer=lambda m: json.loads(m.decode('ascii')))

for message in consumer:
    msg = json.loads(message.value)
    process_message(msg)
</code>```

答:
If consumer offset is not moving after some time, then consumer is
  likely to have stopped. If consumer offset is moving, but consumer lag
  (difference between the end of the log and the consumer offset) is
  increasing, the consumer is slower than the producer. If the consumer
  is slow, the typical solution is to increase the degree of parallelism
  in the consumer. This may require increasing the number of partitions
  of a topic.

Read more at the Kafka docs.

To put it simply; you're producing more than you're consuming. You need to increase the rate of consumption to reduce the lag. You need to add more consumers. If you're just testing, then your consumer is slow.

Title: Kafka partition Lag increasing

Body:
I have an application which uses Kafka 1.0 as a queue. The Kafka topic has 80 partitions and 80 consumers running. (Kafka-python consumers).

By running the command :

./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group mygroup  --describe

I see that one of the partitions is stuck at an offset, and the lag continuously increases as new records are added to it.

The output of the above command looks something like this:

TOPIC                          PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG        CONSUMER-ID                                       HOST

118 mytopic                       37         1924            2782            858        kafka-python-1.3.4-3da99d4d-63e8-4e72-967e-xxxxxxxxxxx/localhost
119 mytopic                       38         2741            2742            1          kafka-python-1.3.4-40b44482-39fc-42d0-8f55-xxxxxxxxxxx/localhost
120 mytopic                       39         2713            2713            0          kafka-python-1.3.4-4121d080-1d7c-4d6b-ac58-xxxxxxxxxxx/localhost
121 mytopic                       40         2687            2688            1          kafka-python-1.3.4-43441f6e-fd35-448e-b791-xxxxxxxxxxx/localhost

What causes this? Also resetting offset using reset-offsets command is not desirable as this server might not be manually monitored on a regular basis.

Clients run in background as parallel processes in a Linux m/c:

consumer = KafkaConsumer('mytopic', group_id='mygroup', bootstrap_servers='localhost:9092',
                     session_timeout_ms=120000, heartbeat_interval_ms=100000, max_poll_records=1,
                     auto_commit_interval_ms=100000, request_timeout_ms=350000, max_partition_fetch_bytes=3*1024*1024,
                     value_deserializer=lambda m: json.loads(m.decode('ascii')))

for message in consumer:
    msg = json.loads(message.value)
    process_message(msg)


答:
Use the Push method to add to an array.    </p>

```<code>var today = new Date();

    var dd = today.getDate();

    var mm = today.getMonth() + 1;

    var yyyy = today.getFullYear();

    var today = yyyy + '-' + mm + '-' + dd;

    //--------------------- Begin Of Calendar Event ---------------------------//

    var calendarEvents = [];

      if (today == today) {

        var data = {
               title: 'Nigeria Independence',
               url: 'http://google.com/',
               start: today
               }

    //add to array
    calendarEvents.push(data);
      }

    //--------------------- End Of Calendar Event ----------------------------//
</code>```

Body:
Use the Push method to add to an array.

var today = new Date();

    var dd = today.getDate();

    var mm = today.getMonth() + 1;

    var yyyy = today.getFullYear();

    var today = yyyy + '-' + mm + '-' + dd;

    //--------------------- Begin Of Calendar Event ---------------------------//

    var calendarEvents = [];

      if (today == today) {

        var data = {
               title: 'Nigeria Independence',
               url: 'http://google.com/',
               start: today
               }

    //add to array
    calendarEvents.push(data);
      }

    //--------------------- End Of Calendar Event ----------------------------//


问:
Calculating list cumulative sum in Haskell
Write a function that returns the running sum of list. e.g. running [1,2,3,5] is [1,3,6,11]. I write this function below which just can return the final sum of all the values among the list.So how can i separate them one by one?</p>

```<code>sumlist' xx=aux xx 0
    where aux [] a=a
          aux (x:xs) a=aux xs (a+x)
</code>```

答:
While scanl1 is clearly the "canonical" solution, it is still instructive to see how you could do it with foldl:

```<code>sumList xs = tail.reverse $ foldl acc [0] xs where
  acc (y:ys) x = (x+y):y:ys
</code>```

Or pointfree:

```<code>sumList = tail.reverse.foldl acc [0] where
  acc (y:ys) x = (x+y):y:ys
</code>```

Here is an ugly brute force approach:

```<code>sumList xs = reverse $ acc $ reverse xs where
  acc [] = []
  acc (x:xs) = (x + sum xs) : acc xs
</code>```

There is a cute (but not very performant) solution using inits:

```<code>sumList xs = tail $ map sum $ inits xs
</code>```

Again pointfree:

```<code>sumList = tail.map sum.inits
</code>```

Body:
Write a function that returns the running sum of list. e.g. running [1,2,3,5] is [1,3,6,11]. I write this function below which just can return the final sum of all the values among the list.So how can i separate them one by one?

sumlist' xx=aux xx 0
    where aux [] a=a
          aux (x:xs) a=aux xs (a+x)

Body:
While scanl1 is clearly the "canonical" solution, it is still instructive to see how you could do it with foldl:

sumList xs = tail.reverse $ foldl acc [0] xs where
  acc (y:ys) x = (x+y):y:ys

Or pointfree:

sumList = tail.reverse.foldl acc [0] where
  acc (y:ys) x = (x+y):y:ys

Here is an ugly brute force approach:

sumList xs = reverse $ acc $ reverse xs where
  acc [] = []
  acc (x:xs) = (x + sum xs) : acc xs

There is a cute (but not very performant) solution using inits:

sumList xs = tail $ map sum $ inits xs

Again pointfree:

sumList = tail.map sum.inits

ContentLicense: CC BY-SA 2.5


问:
Make status bar opaque programmatically
There are 2 Fragments of the Activity. When the first Fragment is visible, I want the status bar to be translucent (no Toolbar here). That works as expected.

But when I switch over to the second Fragment, I want the status bar to be opaque. And the Toolbar should be drawn below the status bar. I want these changes to be done programmatically because I can't do it in the Activity XML.

So far I've tried the following code. But this doesn't work.

```<code>if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    {
        Window window = getActivity().getWindow();
        view.setFitsSystemWindows(true);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_LAYOUT_FLAGS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.TYPE_STATUS_BAR);
        window.setStatusBarColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
    }
</code>```

This is the screen I'm getting:

But I want the status bar to have primaryDark colour and the Toolbar to appear below it.

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.blogspot.smarphy.pierecipe">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true">
        <activity
            android:name=".SplashActivity"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".HomeyActivity"
            android:label="@string/title_activity_homey"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
        </activity>

        <activity
            android:name=".RecipesCardsActivity"
            android:label="@string/title_activity_recipes_cards"
            android:parentActivityName=".HomeyActivity"
            android:theme="@style/AppTheme.OpaqueStatus" />

        <service android:name=".Services.HomeCardsNetworkService" />
        <service android:name=".Services.SearchCardsNetworkService" />

    </application>

</manifest>
</code>```

答:
As I understand you correctly.

You want to switch from fullscreen to normal when you switch from fragment 1 to 2.

You probably have this on your activity if not use this

```<code>android:theme="@style/FullscreenTheme"
</code>```

In fragment 2 you can use this to setup non-fullscreen mode.
@Nullable

```<code>    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        ....
    }
    @Override
    public void onDestroyView() {
        getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        ....
    }
</code>```

You should clear fullscreen flag when adding non-fullscreen.

Info:
The translucent status bar was introduced in API level 19.

ContentLicense: CC BY-SA 4.0

Title: Make status bar opaque programmatically

Body:
There are 2 Fragments of the Activity. When the first Fragment is visible, I want the status bar to be translucent (no Toolbar here). That works as expected.

But when I switch over to the second Fragment, I want the status bar to be opaque. And the Toolbar should be drawn below the status bar. I want these changes to be done programmatically because I can't do it in the Activity XML.

So far I've tried the following code. But this doesn't work.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
    {
        Window window = getActivity().getWindow();
        view.setFitsSystemWindows(true);
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_LAYOUT_FLAGS);
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.TYPE_STATUS_BAR);
        window.setStatusBarColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));
    }

This is the screen I'm getting:

But I want the status bar to have primaryDark colour and the Toolbar to appear below it.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.blogspot.smarphy.pierecipe">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true">
        <activity
            android:name=".SplashActivity"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".HomeyActivity"
            android:label="@string/title_activity_homey"
            android:theme="@style/AppTheme">
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>
        </activity>

        <activity
            android:name=".RecipesCardsActivity"
            android:label="@string/title_activity_recipes_cards"
            android:parentActivityName=".HomeyActivity"
            android:theme="@style/AppTheme.OpaqueStatus" />

        <service android:name=".Services.HomeCardsNetworkService" />
        <service android:name=".Services.SearchCardsNetworkService" />

    </application>

</manifest>

Body:
As I understand you correctly.

You want to switch from fullscreen to normal when you switch from fragment 1 to 2.

You probably have this on your activity if not use this

android:theme="@style/FullscreenTheme"

In fragment 2 you can use this to setup non-fullscreen mode.
@Nullable

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        ....
    }
    @Override
    public void onDestroyView() {
        getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        ....
    }

You should clear fullscreen flag when adding non-fullscreen.

Info:
The translucent status bar was introduced in API level 19.


问:
Array to string conversion - Laravel
I am trying to store the id of the selected item in my drop down but I get an error array to string conversion.

HTML

    Age

        <select class="form-control" id="age" name="age[]" mulitple>
            @foreach($ages as $age)
                <option value="{!! $age->id !!}" @if(in_array($age->id, $selectedAges)) selected="selected" @endif >
                    {!! $age->id !!}
                </option>
            @endforeach
        </select>

```

<p><strong>Controller</strong></p>

<pre class="lang-php prettyprint-override"><code>$user = new User(array(
    'name' => $request->get('name'),
    'age' => $request->get('age'),
));

$user->save();
</code>```

答: Because name="age[]" sends an array. change it to name="age"

Title: Array to string conversion - Laravel

Body:
I am trying to store the id of the selected item in my drop down but I get an error array to string conversion.

HTML

    Age

        <select class="form-control" id="age" name="age[]" mulitple>
            @foreach($ages as $age)
                <option value="{!! $age->id !!}" @if(in_array($age->id, $selectedAges)) selected="selected" @endif >
                    {!! $age->id !!}
                </option>
            @endforeach
        </select>

Controller

$user = new User(array(
    'name' => $request->get('name'),
    'age' => $request->get('age'),
));

$user->save();


问:
How can you check if SQL command is still running? Or is it frozen/dead...?
I created an index for my ginormous (250 million+ records) SQL table and it has been several hours. How can I tell if it's still going? Or if the process is frozen/dead?

If you have an answer about how to check if SQL (SQLite3) is still running in general, that'd be super. However, if you have an approach for my specific case, that's good as well. This is what I did.

CREATE INDEX index_name ON table_name(column_name);

答: You have to use some monitoring mechanism of your OS (top, Task Manager, etc.) to check whether the process is using CPU or disk I/O.


问:
Merge and edit multiple legends when facets and geom_line are plotted separately
Following this guide I have plotted the following graph  using the following code. I did split my dataset into one that contains the data that goes in all plots 'control', and the rest 'dfnocontrol'.

```<code>ggplot(dfnocontrol,aes(y=value,x=year)) + geom_line(data=dfnocontrol,
  aes(color=survivorship),size=1.5) + facet_wrap(~density,nrow=2) +
  geom_line(data=dfcontrol,aes(linetype=simulname),color='grey',size=1.5)
</code>```

I have tried many ways to have only one legend, or to edit the existing two legend but nothing seems to work. scale_fill_manual() seems to be ignored, even though I don't get any error message. I was forced to use linetype to make the 'control' appear in the legend. How can I merge these two legends?

edit: these are the data for control

```<code>structure(list(year = 1:2, psize = structure(c(6L, 6L), .Label = c("all plants",
"all plants no-seedl", "seedlings", "SmallerT10", "SmallerT10 no-seedl",
"LargerT10", "10-30", "30-50", "50+"), class = "factor"), value = c(392.884450281975,
392.76842677951), simulname = structure(c(1L, 1L), .Label = c("control",
"d02s70", "d02s80", "d02s90", "d05s70", "d05s80", "d05s90", "d07s70",
"d07s80", "d07s90", "d1s70", "d1s80", "d1s90", "d2s70", "d2s80",
"d2s90", "d3s70", "d3s80", "d3s90", "d4s70", "d4s80", "d4s90",
"d5s70", "d5s80", "d5s90"), class = "factor"), survivorship = structure(c(1L,
1L), .Label = c("control", "s70", "s80", "s90"), class = "factor")), .Names = c("year",
"psize", "value", "simulname", "survivorship"), row.names = 2501:2502, class = "data.frame")
</code>```

and data for the rest

```<code>structure(list(year = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    1L, 2L, 1L, 2L, 1L, 2L), psize = structure(c(6L, 6L, 6L, 6L,
    6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
    6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
    6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L), .Label = c("all plants",
    "all plants no-seedl", "seedlings", "SmallerT10", "SmallerT10 no-seedl",
    "LargerT10", "10-30", "30-50", "50+"), class = "factor"), value = c(391.933827876557,
    390.784233661738, 391.931768654094, 390.777949423224, 391.930831801103,
    390.775125884957, 391.904131913644, 390.671681105517, 391.903377880798,
    390.669377819171, 391.902842713777, 390.667498067697, 391.874743014214,
    390.557893743236, 391.874006362415, 390.555639401299, 391.8735511448,
    390.554149478021, 391.84367266143, 390.443618794749, 391.843064602404,
    390.442149462261, 391.842594963982, 390.440725187945, 391.72267802326,
    388.998242801555, 391.722309813432, 388.996838950063, 391.721745089041,
    388.995715149179, 384.967818982887, 383.215849576989, 384.967407490871,
    383.214728664341, 384.96689031843, 383.213390281481, 391.897592532656,
    389.445606459513, 391.897234485415, 389.444632515097, 391.89681267375,
    389.443358475326, 391.402389493961, 388.987279260992, 391.401979078947,
    388.985920091544, 391.401583421483, 388.984891027315), simulname = structure(c(2L,
    2L, 3L, 3L, 4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 10L,
    10L, 11L, 11L, 12L, 12L, 13L, 13L, 14L, 14L, 15L, 15L, 16L, 16L,
    17L, 17L, 18L, 18L, 19L, 19L, 20L, 20L, 21L, 21L, 22L, 22L, 23L,
    23L, 24L, 24L, 25L, 25L), .Label = c("control", "d02s70", "d02s80",
    "d02s90", "d05s70", "d05s80", "d05s90", "d07s70", "d07s80", "d07s90",
    "d1s70", "d1s80", "d1s90", "d2s70", "d2s80", "d2s90", "d3s70",
    "d3s80", "d3s90", "d4s70", "d4s80", "d4s90", "d5s70", "d5s80",
    "d5s90"), class = "factor"), density = structure(c(2L, 2L, 2L,
    2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L,
    5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L,
    7L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L), .Label = c("control",
    "d02", "d05", "d07", "d1", "d2", "d3", "d4", "d5"), class = "factor"),
        survivorship = structure(c(2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L,
        3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L,
        4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L,
        3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L), .Label = c("control",
        "s70", "s80", "s90"), class = "factor")), .Names = c("year",
    "psize", "value", "simulname", "density", "survivorship"), row.names = c(6081L,
    6082L, 9845L, 9846L, 14345L, 14346L, 17985L, 17986L, 21797L,
    21798L, 26297L, 26298L, 30567L, 30568L, 34528L, 34529L, 38744L,
    38745L, 43144L, 43145L, 47519L, 47520L, 51983L, 51984L, 56483L,
    56484L, 60983L, 60984L, 65483L, 65484L, 69983L, 69984L, 74483L,
    74484L, 78983L, 78984L, 83483L, 83484L, 87983L, 87984L, 92483L,
    92484L, 96983L, 96984L, 101483L, 101484L, 105983L, 105984L), class = "data.frame")
</code>```

答:
Since you provided no data, I will give you an example using the economics data set.

```<code>library(wesanderson) # for the colours
library(tidyverse)
data("economics")
</code>```

We will need two data sets for this task. Variable unemploy will serve as our 'control' (6th column). All variables will be scaled.

First data set:

```<code>economics_gathered <- economics[, 1:5] %>% # exclude unemploy
modify_if(is.numeric, scale) %>%
gather(key, value, -date)
</code>```

Second data set:

```<code>economics_control <- economics[, c(1, 6)] %>%
dplyr::rename(control = unemploy) %>%
gather(some_other_key, value, 2) %>%
mutate(value = scale(value))
</code>```

Now we can plot:

```<code>ggplot() +
geom_line(data = economics_control, aes(x = date, y = value, col = some_other_key)) +
geom_line(data = economics_gathered, aes(date, value, col = key)) +
scale_colour_manual(values = c("grey", wes_palette("GrandBudapest"))) +
facet_wrap(~key, scales = "free_y")
</code>```

To which the result is the plot below.

EDIT

With the data provided by the OP the following code

```<code>ggplot() +
geom_line(data = dfcontrol, aes(year, value, col = survivorship), size = 1.5) +
geom_line(data = dfnocontrol, aes(year, value, col = survivorship), size = 1.5) +
facet_wrap( ~ density, nrow = 2) +
scale_colour_manual(values = c("grey", "forestgreen", "red", "blue"))
</code>```

gives this plot:

DATA

1)

```<code>dfcontrol <- structure(list(year = 1:2, psize = structure(c(6L, 6L), .Label = c("all plants",
"all plants no-seedl", "seedlings", "SmallerT10", "SmallerT10 no-seedl",
"LargerT10", "10-30", "30-50", "50+"), class = "factor"), value = c(392.884450281975,
392.76842677951), simulname = structure(c(1L, 1L), .Label = c("control",
"d02s70", "d02s80", "d02s90", "d05s70", "d05s80", "d05s90", "d07s70",
"d07s80", "d07s90", "d1s70", "d1s80", "d1s90", "d2s70", "d2s80",
"d2s90", "d3s70", "d3s80", "d3s90", "d4s70", "d4s80", "d4s90",
"d5s70", "d5s80", "d5s90"), class = "factor"), survivorship = structure(c(1L,
1L), .Label = c("control", "s70", "s80", "s90"), class = "factor")), .Names = c("year",
"psize", "value", "simulname", "survivorship"), row.names = 2501:2502, class = "data.frame")
</code>```

2)

```<code>dfnocontrol <- structure(list(year = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L), psize = structure(c(6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L), .Label = c("all plants",
"all plants no-seedl", "seedlings", "SmallerT10", "SmallerT10 no-seedl",
"LargerT10", "10-30", "30-50", "50+"), class = "factor"), value = c(391.933827876557,
390.784233661738, 391.931768654094, 390.777949423224, 391.930831801103,
390.775125884957, 391.904131913644, 390.671681105517, 391.903377880798,
390.669377819171, 391.902842713777, 390.667498067697, 391.874743014214,
390.557893743236, 391.874006362415, 390.555639401299, 391.8735511448,
390.554149478021, 391.84367266143, 390.443618794749, 391.843064602404,
390.442149462261, 391.842594963982, 390.440725187945, 391.72267802326,
388.998242801555, 391.722309813432, 388.996838950063, 391.721745089041,
388.995715149179, 384.967818982887, 383.215849576989, 384.967407490871,
383.214728664341, 384.96689031843, 383.213390281481, 391.897592532656,
389.445606459513, 391.897234485415, 389.444632515097, 391.89681267375,
389.443358475326, 391.402389493961, 388.987279260992, 391.401979078947,
388.985920091544, 391.401583421483, 388.984891027315), simulname = structure(c(2L,
2L, 3L, 3L, 4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 10L,
10L, 11L, 11L, 12L, 12L, 13L, 13L, 14L, 14L, 15L, 15L, 16L, 16L,
17L, 17L, 18L, 18L, 19L, 19L, 20L, 20L, 21L, 21L, 22L, 22L, 23L,
23L, 24L, 24L, 25L, 25L), .Label = c("control", "d02s70", "d02s80",
"d02s90", "d05s70", "d05s80", "d05s90", "d07s70", "d07s80", "d07s90",
"d1s70", "d1s80", "d1s90", "d2s70", "d2s80", "d2s90", "d3s70",
"d3s80", "d3s90", "d4s70", "d4s80", "d4s90", "d5s70", "d5s80",
"d5s90"), class = "factor"), density = structure(c(2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L,
7L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L), .Label = c("control",
"d02", "d05", "d07", "d1", "d2", "d3", "d4", "d5"), class = "factor"),
    survivorship = structure(c(2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L,
    3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L,
    4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L,
    3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L), .Label = c("control",
    "s70", "s80", "s90"), class = "factor")), .Names = c("year",
"psize", "value", "simulname", "density", "survivorship"), row.names = c(6081L,
6082L, 9845L, 9846L, 14345L, 14346L, 17985L, 17986L, 21797L,
21798L, 26297L, 26298L, 30567L, 30568L, 34528L, 34529L, 38744L,
38745L, 43144L, 43145L, 47519L, 47520L, 51983L, 51984L, 56483L,
56484L, 60983L, 60984L, 65483L, 65484L, 69983L, 69984L, 74483L,
74484L, 78983L, 78984L, 83483L, 83484L, 87983L, 87984L, 92483L,
92484L, 96983L, 96984L, 101483L, 101484L, 105983L, 105984L), class = "data.frame")
</code>```

Body:
Following this guide I have plotted the following graph  using the following code. I did split my dataset into one that contains the data that goes in all plots 'control', and the rest 'dfnocontrol'.

ggplot(dfnocontrol,aes(y=value,x=year)) + geom_line(data=dfnocontrol,
  aes(color=survivorship),size=1.5) + facet_wrap(~density,nrow=2) +
  geom_line(data=dfcontrol,aes(linetype=simulname),color='grey',size=1.5)

I have tried many ways to have only one legend, or to edit the existing two legend but nothing seems to work. scale_fill_manual() seems to be ignored, even though I don't get any error message. I was forced to use linetype to make the 'control' appear in the legend. How can I merge these two legends?

edit: these are the data for control

structure(list(year = 1:2, psize = structure(c(6L, 6L), .Label = c("all plants",
"all plants no-seedl", "seedlings", "SmallerT10", "SmallerT10 no-seedl",
"LargerT10", "10-30", "30-50", "50+"), class = "factor"), value = c(392.884450281975,
392.76842677951), simulname = structure(c(1L, 1L), .Label = c("control",
"d02s70", "d02s80", "d02s90", "d05s70", "d05s80", "d05s90", "d07s70",
"d07s80", "d07s90", "d1s70", "d1s80", "d1s90", "d2s70", "d2s80",
"d2s90", "d3s70", "d3s80", "d3s90", "d4s70", "d4s80", "d4s90",
"d5s70", "d5s80", "d5s90"), class = "factor"), survivorship = structure(c(1L,
1L), .Label = c("control", "s70", "s80", "s90"), class = "factor")), .Names = c("year",
"psize", "value", "simulname", "survivorship"), row.names = 2501:2502, class = "data.frame")

and data for the rest

structure(list(year = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
    1L, 2L, 1L, 2L, 1L, 2L), psize = structure(c(6L, 6L, 6L, 6L,
    6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
    6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
    6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L), .Label = c("all plants",
    "all plants no-seedl", "seedlings", "SmallerT10", "SmallerT10 no-seedl",
    "LargerT10", "10-30", "30-50", "50+"), class = "factor"), value = c(391.933827876557,
    390.784233661738, 391.931768654094, 390.777949423224, 391.930831801103,
    390.775125884957, 391.904131913644, 390.671681105517, 391.903377880798,
    390.669377819171, 391.902842713777, 390.667498067697, 391.874743014214,
    390.557893743236, 391.874006362415, 390.555639401299, 391.8735511448,
    390.554149478021, 391.84367266143, 390.443618794749, 391.843064602404,
    390.442149462261, 391.842594963982, 390.440725187945, 391.72267802326,
    388.998242801555, 391.722309813432, 388.996838950063, 391.721745089041,
    388.995715149179, 384.967818982887, 383.215849576989, 384.967407490871,
    383.214728664341, 384.96689031843, 383.213390281481, 391.897592532656,
    389.445606459513, 391.897234485415, 389.444632515097, 391.89681267375,
    389.443358475326, 391.402389493961, 388.987279260992, 391.401979078947,
    388.985920091544, 391.401583421483, 388.984891027315), simulname = structure(c(2L,
    2L, 3L, 3L, 4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 10L,
    10L, 11L, 11L, 12L, 12L, 13L, 13L, 14L, 14L, 15L, 15L, 16L, 16L,
    17L, 17L, 18L, 18L, 19L, 19L, 20L, 20L, 21L, 21L, 22L, 22L, 23L,
    23L, 24L, 24L, 25L, 25L), .Label = c("control", "d02s70", "d02s80",
    "d02s90", "d05s70", "d05s80", "d05s90", "d07s70", "d07s80", "d07s90",
    "d1s70", "d1s80", "d1s90", "d2s70", "d2s80", "d2s90", "d3s70",
    "d3s80", "d3s90", "d4s70", "d4s80", "d4s90", "d5s70", "d5s80",
    "d5s90"), class = "factor"), density = structure(c(2L, 2L, 2L,
    2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L,
    5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L,
    7L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L), .Label = c("control",
    "d02", "d05", "d07", "d1", "d2", "d3", "d4", "d5"), class = "factor"),
        survivorship = structure(c(2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L,
        3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L,
        4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L,
        3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L), .Label = c("control",
        "s70", "s80", "s90"), class = "factor")), .Names = c("year",
    "psize", "value", "simulname", "density", "survivorship"), row.names = c(6081L,
    6082L, 9845L, 9846L, 14345L, 14346L, 17985L, 17986L, 21797L,
    21798L, 26297L, 26298L, 30567L, 30568L, 34528L, 34529L, 38744L,
    38745L, 43144L, 43145L, 47519L, 47520L, 51983L, 51984L, 56483L,
    56484L, 60983L, 60984L, 65483L, 65484L, 69983L, 69984L, 74483L,
    74484L, 78983L, 78984L, 83483L, 83484L, 87983L, 87984L, 92483L,
    92484L, 96983L, 96984L, 101483L, 101484L, 105983L, 105984L), class = "data.frame")

Body:
Since you provided no data, I will give you an example using the economics data set.

library(wesanderson) # for the colours
library(tidyverse)
data("economics")

We will need two data sets for this task. Variable unemploy will serve as our 'control' (6th column). All variables will be scaled.

First data set:

economics_gathered <- economics[, 1:5] %>% # exclude unemploy
modify_if(is.numeric, scale) %>%
gather(key, value, -date)

Second data set:

economics_control <- economics[, c(1, 6)] %>%
dplyr::rename(control = unemploy) %>%
gather(some_other_key, value, 2) %>%
mutate(value = scale(value))

Now we can plot:

ggplot() +
geom_line(data = economics_control, aes(x = date, y = value, col = some_other_key)) +
geom_line(data = economics_gathered, aes(date, value, col = key)) +
scale_colour_manual(values = c("grey", wes_palette("GrandBudapest"))) +
facet_wrap(~key, scales = "free_y")

To which the result is the plot below.

EDIT

With the data provided by the OP the following code

ggplot() +
geom_line(data = dfcontrol, aes(year, value, col = survivorship), size = 1.5) +
geom_line(data = dfnocontrol, aes(year, value, col = survivorship), size = 1.5) +
facet_wrap( ~ density, nrow = 2) +
scale_colour_manual(values = c("grey", "forestgreen", "red", "blue"))

gives this plot:

DATA

1)

dfcontrol <- structure(list(year = 1:2, psize = structure(c(6L, 6L), .Label = c("all plants",
"all plants no-seedl", "seedlings", "SmallerT10", "SmallerT10 no-seedl",
"LargerT10", "10-30", "30-50", "50+"), class = "factor"), value = c(392.884450281975,
392.76842677951), simulname = structure(c(1L, 1L), .Label = c("control",
"d02s70", "d02s80", "d02s90", "d05s70", "d05s80", "d05s90", "d07s70",
"d07s80", "d07s90", "d1s70", "d1s80", "d1s90", "d2s70", "d2s80",
"d2s90", "d3s70", "d3s80", "d3s90", "d4s70", "d4s80", "d4s90",
"d5s70", "d5s80", "d5s90"), class = "factor"), survivorship = structure(c(1L,
1L), .Label = c("control", "s70", "s80", "s90"), class = "factor")), .Names = c("year",
"psize", "value", "simulname", "survivorship"), row.names = 2501:2502, class = "data.frame")

2)

dfnocontrol <- structure(list(year = c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L,
1L, 2L, 1L, 2L, 1L, 2L), psize = structure(c(6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L), .Label = c("all plants",
"all plants no-seedl", "seedlings", "SmallerT10", "SmallerT10 no-seedl",
"LargerT10", "10-30", "30-50", "50+"), class = "factor"), value = c(391.933827876557,
390.784233661738, 391.931768654094, 390.777949423224, 391.930831801103,
390.775125884957, 391.904131913644, 390.671681105517, 391.903377880798,
390.669377819171, 391.902842713777, 390.667498067697, 391.874743014214,
390.557893743236, 391.874006362415, 390.555639401299, 391.8735511448,
390.554149478021, 391.84367266143, 390.443618794749, 391.843064602404,
390.442149462261, 391.842594963982, 390.440725187945, 391.72267802326,
388.998242801555, 391.722309813432, 388.996838950063, 391.721745089041,
388.995715149179, 384.967818982887, 383.215849576989, 384.967407490871,
383.214728664341, 384.96689031843, 383.213390281481, 391.897592532656,
389.445606459513, 391.897234485415, 389.444632515097, 391.89681267375,
389.443358475326, 391.402389493961, 388.987279260992, 391.401979078947,
388.985920091544, 391.401583421483, 388.984891027315), simulname = structure(c(2L,
2L, 3L, 3L, 4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 10L,
10L, 11L, 11L, 12L, 12L, 13L, 13L, 14L, 14L, 15L, 15L, 16L, 16L,
17L, 17L, 18L, 18L, 19L, 19L, 20L, 20L, 21L, 21L, 22L, 22L, 23L,
23L, 24L, 24L, 25L, 25L), .Label = c("control", "d02s70", "d02s80",
"d02s90", "d05s70", "d05s80", "d05s90", "d07s70", "d07s80", "d07s90",
"d1s70", "d1s80", "d1s90", "d2s70", "d2s80", "d2s90", "d3s70",
"d3s80", "d3s90", "d4s70", "d4s80", "d4s90", "d5s70", "d5s80",
"d5s90"), class = "factor"), density = structure(c(2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L,
7L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L), .Label = c("control",
"d02", "d05", "d07", "d1", "d2", "d3", "d4", "d5"), class = "factor"),
    survivorship = structure(c(2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L,
    3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L,
    4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L, 2L, 2L,
    3L, 3L, 4L, 4L, 2L, 2L, 3L, 3L, 4L, 4L), .Label = c("control",
    "s70", "s80", "s90"), class = "factor")), .Names = c("year",
"psize", "value", "simulname", "density", "survivorship"), row.names = c(6081L,
6082L, 9845L, 9846L, 14345L, 14346L, 17985L, 17986L, 21797L,
21798L, 26297L, 26298L, 30567L, 30568L, 34528L, 34529L, 38744L,
38745L, 43144L, 43145L, 47519L, 47520L, 51983L, 51984L, 56483L,
56484L, 60983L, 60984L, 65483L, 65484L, 69983L, 69984L, 74483L,
74484L, 78983L, 78984L, 83483L, 83484L, 87983L, 87984L, 92483L,
92484L, 96983L, 96984L, 101483L, 101484L, 105983L, 105984L), class = "data.frame")


问:
Django query table to find Item that only exist in Parent field
I been struggling with doing a query to get the rows where a Item only exsist in Parnet field and not Child field.

This is the models.

```<code>class Item(models.Model):
    text = models.CharField()

class ItemRelations(models.Model):
    child = models.ForeignKey('Item', related_name='itemchild')
    parent = models.ForeignKey('Item', related_name='itemparent')
</code>```

So I only want to filter out the Items that are not a child, but is a Parent. I call it the firstParent.

I tried so many different ways. I want to accomplish something like this.

```<code>firstParent = Item.objects.filter(ItemRelations_parent__is=self).exclude(ItemRelations_child__is=self)
</code>```

Is it possible. Or does one have to make several queries and loops to manage this?

答:
It is possible.

```<code>firstParent = Item.objects.exclude(child=self).filter(parent=self)
</code>```

write exclude before filter.

Body:
I been struggling with doing a query to get the rows where a Item only exsist in Parnet field and not Child field.

This is the models.

class Item(models.Model):
    text = models.CharField()

class ItemRelations(models.Model):
    child = models.ForeignKey('Item', related_name='itemchild')
    parent = models.ForeignKey('Item', related_name='itemparent')

So I only want to filter out the Items that are not a child, but is a Parent. I call it the firstParent.

I tried so many different ways. I want to accomplish something like this.

firstParent = Item.objects.filter(ItemRelations_parent__is=self).exclude(ItemRelations_child__is=self)

Is it possible. Or does one have to make several queries and loops to manage this?

Body:
It is possible.

firstParent = Item.objects.exclude(child=self).filter(parent=self)

write exclude before filter.


问:
Android services and Intent filters
When we declare something like this in the manifest, is it guaranteed that the service will be executed (if it is not already running) on receiving an intent of that type? Does this work the same way on Android Oreo 8.0?</p>

```<code>    <service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
</code>```

答:
is it guaranteed that the service will be executed (if it is not already running) on receiving an intent of that type?

"Guaranteed" is a strong term. Generally your statement is true. Scenarios where it will not be include:

If somebody tries starting the service using an implicit Intent, one with just that action string. Most likely a device will have several services with that <intent-filter>, in which case Android will just pick one of those services to start. Note that binding using an implicit Intent is banned on Android 5.0+, to avoid this sort of situation.

If you disabled the component at runtime using PackageManager and setComponentEnabledSetting().

Does this work the same way on Android Oreo 8.0?

I am not aware of any changes in the behavior of <intent-filter> on <service> in Android 8.0. There are changes to services in Android 8.0 (e.g., cannot start a service from the background), but those changes do not depend on the existence of an <intent-filter>.

Title: Android services and Intent filters

Body:
When we declare something like this in the manifest, is it guaranteed that the service will be executed (if it is not already running) on receiving an intent of that type? Does this work the same way on Android Oreo 8.0?

    <service
        android:name=".MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>


问:
output buffering ob_get_clean not working
I have the code below code that works correctly as what i want. It does not send any output on browser that is what i exactly want.

```<code>ob_start();
echo "test";
echo "test";
$output = ob_get_clean( );
</code>```

But problem is in my below code. below code start sending the output on the browser even i have $output = ob_get_clean( ); at the end

```<code>ob_start();
for($i=0;$i<=10000000;$i++){
    echo $i."<br/>";
}
$output = ob_get_clean( );
</code>```

I am unable to understand the concept of output buffering. everyone say you can control the output and send the output when you want but my above script start sending output to the browser.

答:
There's a limit to how much there can be buffered which by default is 4KB so you are hitting the maximum with your script. If you want to use it for a larger buffer you have to edit your php.ini settings to reflect that. To quote from the PHP docs

You can enable output buffering for all files by setting this directive to ‘On’. If you wish to limit the size of the buffer to a certain size – you can use a maximum number of bytes instead of ‘On’, as a value for this directive (e.g., output_buffering=4096). As of PHP 4.3.5, this directive is always Off in PHP-CLI. source

The PHP doc is quite technical on the subject so I found this blog post which explains the bits and tricks to output buffering:

Streaming and Output Buffering

Body:
I have the code below code that works correctly as what i want. It does not send any output on browser that is what i exactly want.

ob_start();
echo "test";
echo "test";
$output = ob_get_clean( );

But problem is in my below code. below code start sending the output on the browser even i have $output = ob_get_clean( ); at the end

ob_start();
for($i=0;$i<=10000000;$i++){
    echo $i."
";
}
$output = ob_get_clean( );

I am unable to understand the concept of output buffering. everyone say you can control the output and send the output when you want but my above script start sending output to the browser.


问:
Android: SQLite part or full word search not working using SELECT query
I have 10 movie names in SQLite database. I am searching in the database using SearchView and storing result data into ArrayList and then displaying in custom ListView.
The problem is, it works sometimes only. For example, when I search for "the god" or "god" it returns "The Godfather" but when I search for "the shaw" or "shaw" it doesn't return "The Shawshank Redemption". Also, when searching "the" it returns all the movie names starting with "the" like The Godfather, The good, bad and the ugly, the Shawshank redemption etc. I have the below code. Also "Not found" toast is never getting triggered.

SearchActivity.java

```<code>            searchView = findViewById(R.id.searchBar);
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                    myDB = new DatabaseHelper(SearchActivity.this);

                    data = myDB.searchRecord(query);//Sends search term to database helper which returns all data found according to the search term

                    if (data==null){
                        Toasty.error(SearchActivity.this, "Not found", Toast.LENGTH_SHORT, true);
                    }else {
                        searchResultMethod();//Calling method which stores curser data in arraylist
                    }
            return false;
            }

        private void searchResultMethod() {
            if(data == null)
            {
                Toast toastem = Toasty.warning(SearchActivity.this, "Database is empty", Toast.LENGTH_SHORT, true);
                toastem.show();
             }else{
                while(data.moveToNext())
                {
                    arrayListTitle.add(data.getString(1));
                    arrayListYear.add(data.getString(2));
                    arrayListRating.add(data.getString(3));
                    arrayListThumb.add(data.getString(4));
                    arrayListUrl.add(data.getString(5));
                 }
        }
         CustomSearchListAdapter customSearchListAdapter = new CustomSearchListAdapter(SearchActivity.this,arrayListTitle, arrayListYear, arrayListRating, arrayListThumb, arrayListUrl);

    searchListView.setAdapter(customSearchListAdapter);
    searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent webActivityIntent = new Intent(SearchActivity.this, WebViewActivity.class);
                                            webActivityIntent.putExtra("url_list",arrayListUrl);//Sending imdb url to web view activity
                                            webActivityIntent.putExtra("position",i);
                                            startActivity(webActivityIntent);

   }
 });

}
</code>```

searchRecord() method in DatabaseHelper.java

```<code>public Cursor searchRecord(String searchTerm)
{
    db = this.getReadableDatabase();
    String query ="SELECT  *  FROM " + TABLE_NAME + " WHERE title LIKE '%" + searchTerm + "%' OR '" + searchTerm + "%' OR '%" + searchTerm + "'";

    Cursor c = db.rawQuery(query, null);

    if (c == null) {
        return null;
    } else if (!c.moveToFirst()) {
        c.close();
        return null;
    }

    return c;
}
</code>```

I can not figure out what I am doing wrong. Any help is appreciated.

答:
Have you tried to make you query case insensitive? Like this</p>

```<code>String query ="SELECT  *  FROM " + TABLE_NAME + " WHERE title LIKE '%" + searchTerm + "%' COLLATE NOCASE;
</code>```

Body:
I have 10 movie names in SQLite database. I am searching in the database using SearchView and storing result data into ArrayList and then displaying in custom ListView.
The problem is, it works sometimes only. For example, when I search for "the god" or "god" it returns "The Godfather" but when I search for "the shaw" or "shaw" it doesn't return "The Shawshank Redemption". Also, when searching "the" it returns all the movie names starting with "the" like The Godfather, The good, bad and the ugly, the Shawshank redemption etc. I have the below code. Also "Not found" toast is never getting triggered.

SearchActivity.java

            searchView = findViewById(R.id.searchBar);
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                    myDB = new DatabaseHelper(SearchActivity.this);

                    data = myDB.searchRecord(query);//Sends search term to database helper which returns all data found according to the search term

                    if (data==null){
                        Toasty.error(SearchActivity.this, "Not found", Toast.LENGTH_SHORT, true);
                    }else {
                        searchResultMethod();//Calling method which stores curser data in arraylist
                    }
            return false;
            }

        private void searchResultMethod() {
            if(data == null)
            {
                Toast toastem = Toasty.warning(SearchActivity.this, "Database is empty", Toast.LENGTH_SHORT, true);
                toastem.show();
             }else{
                while(data.moveToNext())
                {
                    arrayListTitle.add(data.getString(1));
                    arrayListYear.add(data.getString(2));
                    arrayListRating.add(data.getString(3));
                    arrayListThumb.add(data.getString(4));
                    arrayListUrl.add(data.getString(5));
                 }
        }
         CustomSearchListAdapter customSearchListAdapter = new CustomSearchListAdapter(SearchActivity.this,arrayListTitle, arrayListYear, arrayListRating, arrayListThumb, arrayListUrl);

    searchListView.setAdapter(customSearchListAdapter);
    searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent webActivityIntent = new Intent(SearchActivity.this, WebViewActivity.class);
                                            webActivityIntent.putExtra("url_list",arrayListUrl);//Sending imdb url to web view activity
                                            webActivityIntent.putExtra("position",i);
                                            startActivity(webActivityIntent);

   }
 });

}

searchRecord() method in DatabaseHelper.java

public Cursor searchRecord(String searchTerm)
{
    db = this.getReadableDatabase();
    String query ="SELECT  *  FROM " + TABLE_NAME + " WHERE title LIKE '%" + searchTerm + "%' OR '" + searchTerm + "%' OR '%" + searchTerm + "'";

    Cursor c = db.rawQuery(query, null);

    if (c == null) {
        return null;
    } else if (!c.moveToFirst()) {
        c.close();
        return null;
    }

    return c;
}

I can not figure out what I am doing wrong. Any help is appreciated.

Body:
Have you tried to make you query case insensitive? Like this

String query ="SELECT  *  FROM " + TABLE_NAME + " WHERE title LIKE '%" + searchTerm + "%' COLLATE NOCASE;


问:
TYPO3 fe_user how login user via php code?
I have TYPO3 7.6.18 and extension femanager.

```<code>$GLOBALS['TSFE']->fe_user->checkPid = '';
$info = $GLOBALS['TSFE']->fe_user->getAuthInfoArray();
$user = $GLOBALS['TSFE']->fe_user->fetchUserRecord($info['db_user'], $username);
$loginData = array('uname' => $username, 'uident' => $password, 'status' => 'login');

$GLOBALS['TSFE']->fe_user->forceSetCookie = TRUE;
$GLOBALS['TSFE']->fe_user->createUserSession($user);
$GLOBALS['TSFE']->fe_user->user = $GLOBALS['TSFE']->fe_user->fetchUserSession();

$loginSuccess = $GLOBALS['TSFE']->fe_user->compareUident($user, $loginData);
</code>```

this code does't work. error:

```<code>PHP Catchable Fatal Error: Argument 2 passed to In2code\Femanager\Utility\LogUtility::log() must be an instance of In2code\Femanager\Domain\Model\User, boolean given, called in /home/abenteuer/public_html/typo3conf/ext/feusersplus/Classes/Controller/NewController.php on line 91 and defined in /home/abenteuer/public_html/typo3conf/ext/femanager/Classes/Utility/LogUtility.php line 48
</code>```

Is it hard code? May be exists better way ?

Do you know how login user via php code ?

答:
Call it with username as a parameter

```<code>function loginUser($username)
{
    $GLOBALS['TSFE']->fe_user->checkPid = '';
    $info = $GLOBALS['TSFE']->fe_user->getAuthInfoArray();
    $user = $GLOBALS['TSFE']->fe_user->fetchUserRecord($info['db_user'], $username);
    $loginData = array('uname' => $username, 'uident' => $user['password'], 'status' => 'login');

    $GLOBALS['TSFE']->fe_user->forceSetCookie = TRUE;
    $GLOBALS['TSFE']->fe_user->createUserSession($user);

    $reflection = new \ReflectionClass($GLOBALS['TSFE']->fe_user);
    $setSessionCookieMethod = $reflection->getMethod('setSessionCookie');
    $setSessionCookieMethod->setAccessible(TRUE);
    $setSessionCookieMethod->invoke($GLOBALS['TSFE']->fe_user);

    $GLOBALS['TSFE']->fe_user->user = $GLOBALS['TSFE']->fe_user->fetchUserSession();
    $session_data = $GLOBALS['TSFE']->fe_user->fetchUserSession();
    $loginSuccess = $GLOBALS['TSFE']->fe_user->compareUident($user, $loginData);

    setcookie('fe_typo_user', $session_data['ses_id'], time() + (86400 * 30), "/");
    setcookie('nc_staticfilecache', 'fe_typo_user_logged_in', time() + (86400 * 30), "/");
}
</code>```

Body:
I have TYPO3 7.6.18 and extension femanager.

$GLOBALS['TSFE']->fe_user->checkPid = '';
$info = $GLOBALS['TSFE']->fe_user->getAuthInfoArray();
$user = $GLOBALS['TSFE']->fe_user->fetchUserRecord($info['db_user'], $username);
$loginData = array('uname' => $username, 'uident' => $password, 'status' => 'login');

$GLOBALS['TSFE']->fe_user->forceSetCookie = TRUE;
$GLOBALS['TSFE']->fe_user->createUserSession($user);
$GLOBALS['TSFE']->fe_user->user = $GLOBALS['TSFE']->fe_user->fetchUserSession();

$loginSuccess = $GLOBALS['TSFE']->fe_user->compareUident($user, $loginData);

this code does't work. error:

PHP Catchable Fatal Error: Argument 2 passed to In2code\Femanager\Utility\LogUtility::log() must be an instance of In2code\Femanager\Domain\Model\User, boolean given, called in /home/abenteuer/public_html/typo3conf/ext/feusersplus/Classes/Controller/NewController.php on line 91 and defined in /home/abenteuer/public_html/typo3conf/ext/femanager/Classes/Utility/LogUtility.php line 48

Is it hard code? May be exists better way ?

Do you know how login user via php code ?

Body:
Call it with username as a parameter

function loginUser($username)
{
    $GLOBALS['TSFE']->fe_user->checkPid = '';
    $info = $GLOBALS['TSFE']->fe_user->getAuthInfoArray();
    $user = $GLOBALS['TSFE']->fe_user->fetchUserRecord($info['db_user'], $username);
    $loginData = array('uname' => $username, 'uident' => $user['password'], 'status' => 'login');

    $GLOBALS['TSFE']->fe_user->forceSetCookie = TRUE;
    $GLOBALS['TSFE']->fe_user->createUserSession($user);

    $reflection = new \ReflectionClass($GLOBALS['TSFE']->fe_user);
    $setSessionCookieMethod = $reflection->getMethod('setSessionCookie');
    $setSessionCookieMethod->setAccessible(TRUE);
    $setSessionCookieMethod->invoke($GLOBALS['TSFE']->fe_user);

    $GLOBALS['TSFE']->fe_user->user = $GLOBALS['TSFE']->fe_user->fetchUserSession();
    $session_data = $GLOBALS['TSFE']->fe_user->fetchUserSession();
    $loginSuccess = $GLOBALS['TSFE']->fe_user->compareUident($user, $loginData);

    setcookie('fe_typo_user', $session_data['ses_id'], time() + (86400 * 30), "/");
    setcookie('nc_staticfilecache', 'fe_typo_user_logged_in', time() + (86400 * 30), "/");
}


问:
Convert JSON array in MySQL to rows
UPDATE: This is now possible in MySQL 8 via the JSON_TABLE function: https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html

I'm loving the new JSON functions in MySQL 5.7, but running into a block trying to merge values from JSON into a normal table structure.

Grabbing JSON, manipulating and extracting arrays from it etc. is simple. JSON_EXTRACT all the way. But what about the inverse, going from a JSON array to rows? Perhaps I am dense on the existing MySQL JSON functionality, but I haven't been able to figure that one out.

For example, say I have a JSON array and want to insert a row for each element in the array with its value? The only way I have found is to write a bunch of JSON_EXTRACT(... '$[0]') JSON_EXTRACT(... '$[1]') etc and union them together.

Or, say I have a JSON array and want to GROUP_CONCAT() it to a single comma separated string?

In other words, I know I can do this:

```<code>SET @j = '[1, 2, 3]';
SELECT GROUP_CONCAT(JSON_EXTRACT(@j, CONCAT('$[', x.n, ']'))) AS val
  FROM
  (
    SELECT 0 AS n
    UNION
    SELECT 1 AS n
    UNION
    SELECT 2 AS n
    UNION
    SELECT 3 AS n
    UNION
    SELECT 4 AS n
    UNION
    SELECT 5 AS n
  ) x
WHERE x.n < JSON_LENGTH(@j);
</code>```

But that hurts my eyes. And my heart.

How can I do something like:

```<code>SET @j = '[1, 2, 3]';
SELECT GROUP_CONCAT(JSON_EXTRACT(@j, '$[ * ]'))
</code>```

... and have it concatenate together the values in the array vs. the JSON array itself?

I guess what I'm looking for here is some sort of JSON_SPLIT along the lines of:

```<code>SET @j = '[1, 2, 3]';

SELECT GROUP_CONCAT(val)
FROM
  JSON_SPLIT(JSON_EXTRACT(@j, '$[ * ]'), '$')
</code>```

If MySQL had a proper STRING_SPLIT(val, 'separator') table returning function, I could hack it (escaping be damned), but that's not available either.

答:
In My Case, JSON Function was not available so I used a hack.
As mentioned by Chris MYSQL do not have STRING_SPLIT but it does have substring_index.

For the input

```<code>{
    "requestId":"BARBH17319901529",
    "van":"0xxxxx91317508",
    "source":"AxxxS",
    "txnTime":"15-11-2017 14:08:22"
}
</code>```

You can use:

```<code>trim(
    replace(
        substring_index(
            substring(input,
                locate('requestid',input)
                    + length('requestid')
                    + 2), ',', 1), '"', '')
) as Requestid`
</code>```

The output will be:

```<code>BARBH17319901529
</code>```

You can modify according to your requirement.

Title: Convert JSON array in MySQL to rows

Body:
UPDATE: This is now possible in MySQL 8 via the JSON_TABLE function: https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html

I'm loving the new JSON functions in MySQL 5.7, but running into a block trying to merge values from JSON into a normal table structure.

Grabbing JSON, manipulating and extracting arrays from it etc. is simple. JSON_EXTRACT all the way. But what about the inverse, going from a JSON array to rows? Perhaps I am dense on the existing MySQL JSON functionality, but I haven't been able to figure that one out.

For example, say I have a JSON array and want to insert a row for each element in the array with its value? The only way I have found is to write a bunch of JSON_EXTRACT(... '$[0]') JSON_EXTRACT(... '$[1]') etc and union them together.

Or, say I have a JSON array and want to GROUP_CONCAT() it to a single comma separated string?

In other words, I know I can do this:

SET @j = '[1, 2, 3]';
SELECT GROUP_CONCAT(JSON_EXTRACT(@j, CONCAT('$[', x.n, ']'))) AS val
  FROM
  (
    SELECT 0 AS n
    UNION
    SELECT 1 AS n
    UNION
    SELECT 2 AS n
    UNION
    SELECT 3 AS n
    UNION
    SELECT 4 AS n
    UNION
    SELECT 5 AS n
  ) x
WHERE x.n < JSON_LENGTH(@j);

But that hurts my eyes. And my heart.

How can I do something like:

SET @j = '[1, 2, 3]';
SELECT GROUP_CONCAT(JSON_EXTRACT(@j, '$[ * ]'))

... and have it concatenate together the values in the array vs. the JSON array itself?

I guess what I'm looking for here is some sort of JSON_SPLIT along the lines of:

SET @j = '[1, 2, 3]';

SELECT GROUP_CONCAT(val)
FROM
  JSON_SPLIT(JSON_EXTRACT(@j, '$[ * ]'), '$')

If MySQL had a proper STRING_SPLIT(val, 'separator') table returning function, I could hack it (escaping be damned), but that's not available either.

Body:
In My Case, JSON Function was not available so I used a hack.
As mentioned by Chris MYSQL do not have STRING_SPLIT but it does have substring_index.

For the input

{
    "requestId":"BARBH17319901529",
    "van":"0xxxxx91317508",
    "source":"AxxxS",
    "txnTime":"15-11-2017 14:08:22"
}

You can use:

trim(
    replace(
        substring_index(
            substring(input,
                locate('requestid',input)
                    + length('requestid')
                    + 2), ',', 1), '"', '')
) as Requestid`

The output will be:

BARBH17319901529

You can modify according to your requirement.


问:
Detect closed pipe in redirected console output in .NET applications
The .NET Console class and its default TextWriter implementation (available as Console.Out and implicitly in e.g. Console.WriteLine()) does not signal any error when the application is having its output piped to another program, and the other program terminates or closes the pipe before the application has finished. This means that the application may run for longer than necessary, writing output into a black hole.

How can I detect the closing of the other end of the redirection pipe?

A more detailed explanation follows:

Here are a pair of example programs that demonstrate the problem. Produce prints lots of integers fairly slowly, to simulate the effect of computation:

```<code>using System;
class Produce
{
    static void Main()
    {
        for (int i = 0; i < 10000; ++i)
        {
            System.Threading.Thread.Sleep(100); // added for effect
            Console.WriteLine(i);
        }
    }
}
</code>```

Consume only reads the first 10 lines of input and then exits:

```<code>using System;
class Consume
{
    static void Main()
    {
        for (int i = 0; i < 10; ++i)
            Console.ReadLine();
    }
}
</code>```

If these two programs are compiled, and the output of the first piped to the second, like so:

```<code>Produce | Consume
</code>```

... it can be observed that Produce keeps on running long after Consume has terminated.

In reality, my Consume program is Unix-style head, and my Produce program prints data which is costly to calculate. I'd like to terminate output when the other end of the pipe has closed the connection.

How can I do this in .NET?

(I know that an obvious alternative is to pass a command-line argument to limit output, and indeed that's what I'm currently doing, but I'd still like to know how to do this since I want to be able to make more configurable judgements about when to terminate reading; e.g. piping through grep before head.)

UPDATE: It looks horribly like the System.IO.__ConsoleStream implementation in .NET is hard-coded to ignore errors 0x6D (ERROR_BROKEN_PIPE) and 0xE8 (ERROR_NO_DATA). That probably means I need to reimplement the console stream. Sigh...)

答:
To solve this one, I had to write my own basic stream implementation over Win32 file handles. This wasn't terribly difficult, as I didn't need to implement asynchronous support, buffering or seeking.

Unfortunately, unsafe code needs to be used, but that generally isn't a problem for console applications that will be run locally and with full trust.

Here's the core stream:

```<code>class HandleStream : Stream
{
    SafeHandle _handle;
    FileAccess _access;
    bool _eof;

    public HandleStream(SafeHandle handle, FileAccess access)
    {
        _handle = handle;
        _access = access;
    }

    public override bool CanRead
    {
        get { return (_access & FileAccess.Read) != 0; }
    }

    public override bool CanSeek
    {
        get { return false; }
    }

    public override bool CanWrite
    {
        get { return (_access & FileAccess.Write) != 0; }
    }

    public override void Flush()
    {
        // use external buffering if you need it.
    }

    public override long Length
    {
        get { throw new NotSupportedException(); }
    }

    public override long Position
    {
        get { throw new NotSupportedException(); }
        set { throw new NotSupportedException(); }
    }

    static void CheckRange(byte[] buffer, int offset, int count)
    {
        if (offset < 0 || count < 0 || (offset + count) < 0
            || (offset + count) > buffer.Length)
            throw new ArgumentOutOfRangeException();
    }

    public bool EndOfStream
    {
        get { return _eof; }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        CheckRange(buffer, offset, count);
        int result = ReadFileNative(_handle, buffer, offset, count);
        _eof |= result == 0;
        return result;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        int notUsed;
        Write(buffer, offset, count, out notUsed);
    }

    public void Write(byte[] buffer, int offset, int count, out int written)
    {
        CheckRange(buffer, offset, count);
        int result = WriteFileNative(_handle, buffer, offset, count);
        _eof |= result == 0;
        written = result;
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        throw new NotSupportedException();
    }

    public override void SetLength(long value)
    {
        throw new NotSupportedException();
    }

    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("kernel32", SetLastError=true)]
    static extern unsafe bool ReadFile(
        SafeHandle hFile, byte* lpBuffer, int nNumberOfBytesToRead,
        out int lpNumberOfBytesRead, IntPtr lpOverlapped);

    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("kernel32.dll", SetLastError=true)]
    static extern unsafe bool WriteFile(
        SafeHandle hFile, byte* lpBuffer, int nNumberOfBytesToWrite,
        out int lpNumberOfBytesWritten, IntPtr lpOverlapped);

    unsafe static int WriteFileNative(SafeHandle hFile, byte[] buffer, int offset, int count)
    {
        if (buffer.Length == 0)
            return 0;

        fixed (byte* bufAddr = &buffer[0])
        {
            int result;
            if (!WriteFile(hFile, bufAddr + offset, count, out result, IntPtr.Zero))
            {
                // Using Win32Exception just to get message resource from OS.
                Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
                int hr = ex.NativeErrorCode | unchecked((int) 0x80000000);
                throw new IOException(ex.Message, hr);
            }

            return result;
        }
    }

    unsafe static int ReadFileNative(SafeHandle hFile, byte[] buffer, int offset, int count)
    {
        if (buffer.Length == 0)
            return 0;

        fixed (byte* bufAddr = &buffer[0])
        {
            int result;
            if (!ReadFile(hFile, bufAddr + offset, count, out result, IntPtr.Zero))
            {
                Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
                int hr = ex.NativeErrorCode | unchecked((int) 0x80000000);
                throw new IOException(ex.Message, hr);
            }
            return result;
        }
    }
}
</code>```

BufferedStream can be wrapped around it for buffering if needed, but for console output, the TextWriter will be doing character-level buffering anyway, and only flushing on newlines.

The stream abuses Win32Exception to extract an error message, rather than calling FormatMessage itself.

Building on this stream, I was able to write a simple wrapper for console I/O:

```<code>static class ConsoleStreams
{
    enum StdHandle
    {
        Input = -10,
        Output = -11,
        Error = -12,
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr GetStdHandle(int nStdHandle);

    static SafeHandle GetStdHandle(StdHandle h)
    {
        return new SafeFileHandle(GetStdHandle((int) h), true);
    }

    public static HandleStream OpenStandardInput()
    {
        return new HandleStream(GetStdHandle(StdHandle.Input), FileAccess.Read);
    }

    public static HandleStream OpenStandardOutput()
    {
        return new HandleStream(GetStdHandle(StdHandle.Output), FileAccess.Write);
    }

    public static HandleStream OpenStandardError()
    {
        return new HandleStream(GetStdHandle(StdHandle.Error), FileAccess.Write);
    }

    static TextReader _in;
    static StreamWriter _out;
    static StreamWriter _error;

    public static TextWriter Out
    {
        get
        {
            if (_out == null)
            {
                _out = new StreamWriter(OpenStandardOutput());
                _out.AutoFlush = true;
            }
            return _out;
        }
    }

    public static TextWriter Error
    {
        get
        {
            if (_error == null)
            {
                _error = new StreamWriter(OpenStandardError());
                _error.AutoFlush = true;
            }
            return _error;
        }
    }

    public static TextReader In
    {
        get
        {
            if (_in == null)
                _in = new StreamReader(OpenStandardInput());
            return _in;
        }
    }
}
</code>```

The final result is that writing to the console output after the other end of the pipe has terminated the connection, results in a nice exception with the message:

The pipe is being closed

By catching and ignoring the IOException at the outermost level, it looks like I'm good to go.

OwnerDisplayName: Barry Kelly

Body:
The .NET Console class and its default TextWriter implementation (available as Console.Out and implicitly in e.g. Console.WriteLine()) does not signal any error when the application is having its output piped to another program, and the other program terminates or closes the pipe before the application has finished. This means that the application may run for longer than necessary, writing output into a black hole.

How can I detect the closing of the other end of the redirection pipe?

A more detailed explanation follows:

Here are a pair of example programs that demonstrate the problem. Produce prints lots of integers fairly slowly, to simulate the effect of computation:

using System;
class Produce
{
    static void Main()
    {
        for (int i = 0; i < 10000; ++i)
        {
            System.Threading.Thread.Sleep(100); // added for effect
            Console.WriteLine(i);
        }
    }
}

Consume only reads the first 10 lines of input and then exits:

using System;
class Consume
{
    static void Main()
    {
        for (int i = 0; i < 10; ++i)
            Console.ReadLine();
    }
}

If these two programs are compiled, and the output of the first piped to the second, like so:

Produce | Consume

... it can be observed that Produce keeps on running long after Consume has terminated.

In reality, my Consume program is Unix-style head, and my Produce program prints data which is costly to calculate. I'd like to terminate output when the other end of the pipe has closed the connection.

How can I do this in .NET?

(I know that an obvious alternative is to pass a command-line argument to limit output, and indeed that's what I'm currently doing, but I'd still like to know how to do this since I want to be able to make more configurable judgements about when to terminate reading; e.g. piping through grep before head.)

UPDATE: It looks horribly like the System.IO.__ConsoleStream implementation in .NET is hard-coded to ignore errors 0x6D (ERROR_BROKEN_PIPE) and 0xE8 (ERROR_NO_DATA). That probably means I need to reimplement the console stream. Sigh...)

LastEditorDisplayName: Barry Kelly

Body:
To solve this one, I had to write my own basic stream implementation over Win32 file handles. This wasn't terribly difficult, as I didn't need to implement asynchronous support, buffering or seeking.

Unfortunately, unsafe code needs to be used, but that generally isn't a problem for console applications that will be run locally and with full trust.

Here's the core stream:

class HandleStream : Stream
{
    SafeHandle _handle;
    FileAccess _access;
    bool _eof;

    public HandleStream(SafeHandle handle, FileAccess access)
    {
        _handle = handle;
        _access = access;
    }

    public override bool CanRead
    {
        get { return (_access & FileAccess.Read) != 0; }
    }

    public override bool CanSeek
    {
        get { return false; }
    }

    public override bool CanWrite
    {
        get { return (_access & FileAccess.Write) != 0; }
    }

    public override void Flush()
    {
        // use external buffering if you need it.
    }

    public override long Length
    {
        get { throw new NotSupportedException(); }
    }

    public override long Position
    {
        get { throw new NotSupportedException(); }
        set { throw new NotSupportedException(); }
    }

    static void CheckRange(byte[] buffer, int offset, int count)
    {
        if (offset < 0 || count < 0 || (offset + count) < 0
            || (offset + count) > buffer.Length)
            throw new ArgumentOutOfRangeException();
    }

    public bool EndOfStream
    {
        get { return _eof; }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        CheckRange(buffer, offset, count);
        int result = ReadFileNative(_handle, buffer, offset, count);
        _eof |= result == 0;
        return result;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        int notUsed;
        Write(buffer, offset, count, out notUsed);
    }

    public void Write(byte[] buffer, int offset, int count, out int written)
    {
        CheckRange(buffer, offset, count);
        int result = WriteFileNative(_handle, buffer, offset, count);
        _eof |= result == 0;
        written = result;
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        throw new NotSupportedException();
    }

    public override void SetLength(long value)
    {
        throw new NotSupportedException();
    }

    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("kernel32", SetLastError=true)]
    static extern unsafe bool ReadFile(
        SafeHandle hFile, byte* lpBuffer, int nNumberOfBytesToRead,
        out int lpNumberOfBytesRead, IntPtr lpOverlapped);

    [return: MarshalAs(UnmanagedType.Bool)]
    [DllImport("kernel32.dll", SetLastError=true)]
    static extern unsafe bool WriteFile(
        SafeHandle hFile, byte* lpBuffer, int nNumberOfBytesToWrite,
        out int lpNumberOfBytesWritten, IntPtr lpOverlapped);

    unsafe static int WriteFileNative(SafeHandle hFile, byte[] buffer, int offset, int count)
    {
        if (buffer.Length == 0)
            return 0;

        fixed (byte* bufAddr = &buffer[0])
        {
            int result;
            if (!WriteFile(hFile, bufAddr + offset, count, out result, IntPtr.Zero))
            {
                // Using Win32Exception just to get message resource from OS.
                Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
                int hr = ex.NativeErrorCode | unchecked((int) 0x80000000);
                throw new IOException(ex.Message, hr);
            }

            return result;
        }
    }

    unsafe static int ReadFileNative(SafeHandle hFile, byte[] buffer, int offset, int count)
    {
        if (buffer.Length == 0)
            return 0;

        fixed (byte* bufAddr = &buffer[0])
        {
            int result;
            if (!ReadFile(hFile, bufAddr + offset, count, out result, IntPtr.Zero))
            {
                Win32Exception ex = new Win32Exception(Marshal.GetLastWin32Error());
                int hr = ex.NativeErrorCode | unchecked((int) 0x80000000);
                throw new IOException(ex.Message, hr);
            }
            return result;
        }
    }
}

BufferedStream can be wrapped around it for buffering if needed, but for console output, the TextWriter will be doing character-level buffering anyway, and only flushing on newlines.

The stream abuses Win32Exception to extract an error message, rather than calling FormatMessage itself.

Building on this stream, I was able to write a simple wrapper for console I/O:

static class ConsoleStreams
{
    enum StdHandle
    {
        Input = -10,
        Output = -11,
        Error = -12,
    }

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr GetStdHandle(int nStdHandle);

    static SafeHandle GetStdHandle(StdHandle h)
    {
        return new SafeFileHandle(GetStdHandle((int) h), true);
    }

    public static HandleStream OpenStandardInput()
    {
        return new HandleStream(GetStdHandle(StdHandle.Input), FileAccess.Read);
    }

    public static HandleStream OpenStandardOutput()
    {
        return new HandleStream(GetStdHandle(StdHandle.Output), FileAccess.Write);
    }

    public static HandleStream OpenStandardError()
    {
        return new HandleStream(GetStdHandle(StdHandle.Error), FileAccess.Write);
    }

    static TextReader _in;
    static StreamWriter _out;
    static StreamWriter _error;

    public static TextWriter Out
    {
        get
        {
            if (_out == null)
            {
                _out = new StreamWriter(OpenStandardOutput());
                _out.AutoFlush = true;
            }
            return _out;
        }
    }

    public static TextWriter Error
    {
        get
        {
            if (_error == null)
            {
                _error = new StreamWriter(OpenStandardError());
                _error.AutoFlush = true;
            }
            return _error;
        }
    }

    public static TextReader In
    {
        get
        {
            if (_in == null)
                _in = new StreamReader(OpenStandardInput());
            return _in;
        }
    }
}

The final result is that writing to the console output after the other end of the pipe has terminated the connection, results in a nice exception with the message:

The pipe is being closed

By catching and ignoring the IOException at the outermost level, it looks like I'm good to go.


问:
Controller repeatedly calling itself in Spring-MVC
I was trying to just output my request with just a direct write to the response object. This works great with servlets but with Spring-MVC I ended up creating an infinite loop for some reason I don't understand. Basically the controller just gets called repeatedly. I don't even know how that is possible.

```<code>public ModelAndView handleRequest(
        HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException
{
    System.out.println("I will get called infinitely");
    response.getWriter().print( "Hello World!");
    response.getWriter().close();
    return new ModelAndView();

}
</code>```

So the question is, does anyone know why it would cause an infinite amount of re-requests to this page? It seems to only occur when I am creating a ModelAndView() with nothing in it. But in this case I don't want anything in it, just a blank page. So secondly then is there a way to accomplish that?

答:
Probably an empty viewName of the ModelAndView class will cause that the view from the current request will be used.

You can use void or @ResponseBody String as return type.

Body:
I was trying to just output my request with just a direct write to the response object. This works great with servlets but with Spring-MVC I ended up creating an infinite loop for some reason I don't understand. Basically the controller just gets called repeatedly. I don't even know how that is possible.

public ModelAndView handleRequest(
        HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException
{
    System.out.println("I will get called infinitely");
    response.getWriter().print( "Hello World!");
    response.getWriter().close();
    return new ModelAndView();

}

So the question is, does anyone know why it would cause an infinite amount of re-requests to this page? It seems to only occur when I am creating a ModelAndView() with nothing in it. But in this case I don't want anything in it, just a blank page. So secondly then is there a way to accomplish that?


问:
Serving StyleSheet and JS with Sails
I am a newbie at working with nodeJS and especially with the framework Sails.

I did my research and found that with sails you just need to put CSS-files under the the folder "assets" and call them directly with the URL, e.g. if I put the file custom.css in the folder "assets/foo" I should be able to access it via the URL "localhost:1337/foo/custom.css".

The problem is that my local server throws a 404 Error not being able to find the files, but strangely when I deployed the app to Heroku it works perfectly and I am able to access the css files.

Why is this not working locally?

答:
Welcome to Sails! CSS is served automatically if you put it in your assets/styles folder. Your JS should be in assets/js folder as well. This way you can access it like localhost:1337/assets/js/myjs.js.

In your view - if you don't want to serve it everywhere with a layout - just put your tag like this: <link rel="stylesheet" href="/styles/myawesomestyle.css"> or .
Remember, everything in assets will be made publicly available.
I really recommend that you read the docs HERE.

Title: Serving StyleSheet and JS with Sails

Body:
Welcome to Sails! CSS is served automatically if you put it in your assets/styles folder. Your JS should be in assets/js folder as well. This way you can access it like localhost:1337/assets/js/myjs.js.

In your view - if you don't want to serve it everywhere with a layout - just put your tag like this: <link rel="stylesheet" href="/styles/myawesomestyle.css"> or <script src="/js/mypowerfuljs.js"></script>.
Remember, everything in assets will be made publicly available.
I really recommend that you read the docs HERE.