问:
How to make a python list from a .csv list?
I want to know how to make a .csv list into a python list which I can do plotting and calculating:

I used:

```<code>    fpath = r'C:112017\temp\tT.csv'
    with open(fpath,'r') as csvfile:
         reader = csv.reader(csvfile, delimiter=',')
         for row in reader:
             print(list(reader))
</code>```

it gives me lists like this (which I dont' want):

```<code>    [['2014-12-30', '18.34244791666665'], ['2014-12-31', '18.540224913494818'], ['2015-01-01', '18.15729166666666'],......
</code>```

If I use

```<code>    print(row)
</code>```

it gives me lists like this (looks better but I still can not use it for calculating):

```<code>    ...
    ['2016-07-27', '20.434809022479584']
    ['2016-07-28', '21.395138886239796']
    ['2016-07-29', '20.81571181284057']
    ['2016-07-30', '20.565711801250778']
    ...
</code>```

How can I use panda to make a list? Or is there any easier way to achieve this? Is that possible to use something like:

```<code>    date = row[0]
    temp = row[1]
    lis = pd.DataFrame(date,temp)
</code>```

I guess there are some basic mistakes, but I can't fix it by myself.
Thank you for your time to help.

答:
in my opinion if you want to perform calculations with data from a .csv file you should consider using pandas and numpy.</p>

```<code>import pandas as pd
import numpy as np

# importing dataframe
df = pd.read_csv('filename.csv', delimiter=',')
# check the dataframe
print (df)
</code>```

Body:
I want to know how to make a .csv list into a python list which I can do plotting and calculating:

I used:

    fpath = r'C:112017\temp\tT.csv'
    with open(fpath,'r') as csvfile:
         reader = csv.reader(csvfile, delimiter=',')
         for row in reader:
             print(list(reader))

it gives me lists like this (which I dont' want):

    [['2014-12-30', '18.34244791666665'], ['2014-12-31', '18.540224913494818'], ['2015-01-01', '18.15729166666666'],......

If I use

    print(row)

it gives me lists like this (looks better but I still can not use it for calculating):

    ...
    ['2016-07-27', '20.434809022479584']
    ['2016-07-28', '21.395138886239796']
    ['2016-07-29', '20.81571181284057']
    ['2016-07-30', '20.565711801250778']
    ...

How can I use panda to make a list? Or is there any easier way to achieve this? Is that possible to use something like:

    date = row[0]
    temp = row[1]
    lis = pd.DataFrame(date,temp)

I guess there are some basic mistakes, but I can't fix it by myself.
Thank you for your time to help.

Body:
in my opinion if you want to perform calculations with data from a .csv file you should consider using pandas and numpy.

import pandas as pd
import numpy as np

# importing dataframe
df = pd.read_csv('filename.csv', delimiter=',')
# check the dataframe
print (df)


来源: stackexchange

问:
Modify certain values in a data frame by indirect reference to the columns
I'm wrangling some data where we sort fails into bins and compute limited yields for each sort bin by lot.

I have a meta table that describes the sort bins. The rows are arranged in ascending test order and some of the sort labels come in with non-syntactic names.

```<code>sort_tbl <- tibble::tribble(~weight,   ~label,
                                  0, "fail A",
                                  0, "fail B",
                                  0, "fail C",
                                100,   "pass")
> sort_tbl
# A tibble: 4 x 2
  weight  label
   <dbl>  <chr>
1      0 fail A
2      0 fail B
3      0 fail C
4    100   pass
</code>```

I have a data table of limited yield by sort bin with one row per lot and one col for each sort bin. Because this table was constructed from a transposition we get instances where a particular sort never occurred for a lot and the resulting value is NA. Note that the columns in this table are arranged in descending test order.

```<code>yld_tbl <- tibble::tribble(  ~lot, ~pass, ~`fail C`, ~`fail B`, ~`fail A`,
                           "lot1",    NA,        NA,      0.00,        NA,
                           "lot2",    NA,      0.00,      0.80,        NA,
                           "lot3",  0.49,        NA,      0.50,      0.98,
                           "lot4",  0.70,      0.95,      0.74,      0.99)
> yld_tbl
# A tibble: 4 x 5
    lot  pass `fail C` `fail B` `fail A`
  <chr> <dbl>    <dbl>    <dbl>    <dbl>
1  lot1    NA       NA     0.00       NA
2  lot2    NA     0.00     0.80       NA
3  lot3  0.49       NA     0.50     0.98
4  lot4  0.70     0.95     0.74     0.99
</code>```

Some of the missing values imply a limited yield of 100% while others reflect an undefined value because we are zero yield earlier in the flow. My task is to replace the former group of NA's with 1.00 as appropriate.

One algorithm to accomplish this works left to right (descending test order) replacing NA with 1.00 if the subsequent limited yield is not NA. In the first row of the example data set, we don't change fail C since pass is missing. But we do replace fail A with 1.00 since fail B is not missing.

The correct example output would be:

```<code>> fill_ones(yld_tbl, sort_tbl)
# A tibble: 4 x 5
    lot  pass `fail C` `fail B` `fail A`
  <chr> <dbl>    <dbl>    <dbl>    <dbl>
1  lot1    NA       NA     0.00     1.00
2  lot2    NA     0.00     0.80     1.00
3  lot3  0.49     1.00     0.50     0.98
4  lot4  0.70     0.95     0.74     0.99
</code>```

答:
This problem becomes a bit easier if you think of it as "first replace all the NAs with 1, then replace all 1s after the first 0 with NA."

Here are two approaches, one using matrix operations and one using dplyr.

In the matrix approach, you'd extract the values as a numeric matrix, use apply to find the positions that need to be replaced with NA, and return them.

```<code># extract as a matrix, with left-to-right bins
m <- as.matrix(yld_tbl[, sort_tbl$label])

# replace NAs with 1
m[is.na(m)] <- 1

# find 1s happening after a zero in each row
after_zero <- t(apply(m == 0, 1, cumsum)) & (m == 1)

# replace them with NA
m[after_zero] <- NA

# return them in the table
yld_tbl[, sort_tbl$label] <- m
</code>```

Using dplyr/tidyr, you'd first gather() the columns (using arrange() to put them in the desired order), replace the NAs (the group_by/mutate is accomplishing the same thing as apply above), and spread them back into a wide format.

```<code>library(dplyr)
library(tidyr)

yld_tbl %>%
  gather(label, value, -lot) %>%
  arrange(lot, match(label, sort_tbl$label)) %>%
  replace_na(list(value = 1)) %>%
  group_by(lot) %>%
  mutate(value = ifelse(cumsum(value == 0) > 0 & value == 1, NA, value)) %>%
  spread(label, value)
</code>```

Note that unlike the matrix-based approach, this does not preserve the ordering of the columns.

ContentLicense: CC BY-SA 3.0

Body:
I'm wrangling some data where we sort fails into bins and compute limited yields for each sort bin by lot.

I have a meta table that describes the sort bins. The rows are arranged in ascending test order and some of the sort labels come in with non-syntactic names.

sort_tbl <- tibble::tribble(~weight,   ~label,
                                  0, "fail A",
                                  0, "fail B",
                                  0, "fail C",
                                100,   "pass")
> sort_tbl
# A tibble: 4 x 2
  weight  label
   <dbl>  <chr>
1      0 fail A
2      0 fail B
3      0 fail C
4    100   pass

I have a data table of limited yield by sort bin with one row per lot and one col for each sort bin. Because this table was constructed from a transposition we get instances where a particular sort never occurred for a lot and the resulting value is NA. Note that the columns in this table are arranged in descending test order.

yld_tbl <- tibble::tribble(  ~lot, ~pass, ~`fail C`, ~`fail B`, ~`fail A`,
                           "lot1",    NA,        NA,      0.00,        NA,
                           "lot2",    NA,      0.00,      0.80,        NA,
                           "lot3",  0.49,        NA,      0.50,      0.98,
                           "lot4",  0.70,      0.95,      0.74,      0.99)
> yld_tbl
# A tibble: 4 x 5
    lot  pass `fail C` `fail B` `fail A`
  <chr> <dbl>    <dbl>    <dbl>    <dbl>
1  lot1    NA       NA     0.00       NA
2  lot2    NA     0.00     0.80       NA
3  lot3  0.49       NA     0.50     0.98
4  lot4  0.70     0.95     0.74     0.99

Some of the missing values imply a limited yield of 100% while others reflect an undefined value because we are zero yield earlier in the flow. My task is to replace the former group of NA's with 1.00 as appropriate.

One algorithm to accomplish this works left to right (descending test order) replacing NA with 1.00 if the subsequent limited yield is not NA. In the first row of the example data set, we don't change fail C since pass is missing. But we do replace fail A with 1.00 since fail B is not missing.

The correct example output would be:

> fill_ones(yld_tbl, sort_tbl)
# A tibble: 4 x 5
    lot  pass `fail C` `fail B` `fail A`
  <chr> <dbl>    <dbl>    <dbl>    <dbl>
1  lot1    NA       NA     0.00     1.00
2  lot2    NA     0.00     0.80     1.00
3  lot3  0.49     1.00     0.50     0.98
4  lot4  0.70     0.95     0.74     0.99

Body:
This problem becomes a bit easier if you think of it as "first replace all the NAs with 1, then replace all 1s after the first 0 with NA."

Here are two approaches, one using matrix operations and one using dplyr.

In the matrix approach, you'd extract the values as a numeric matrix, use apply to find the positions that need to be replaced with NA, and return them.

# extract as a matrix, with left-to-right bins
m <- as.matrix(yld_tbl[, sort_tbl$label])

# replace NAs with 1
m[is.na(m)] <- 1

# find 1s happening after a zero in each row
after_zero <- t(apply(m == 0, 1, cumsum)) & (m == 1)

# replace them with NA
m[after_zero] <- NA

# return them in the table
yld_tbl[, sort_tbl$label] <- m

Using dplyr/tidyr, you'd first gather() the columns (using arrange() to put them in the desired order), replace the NAs (the group_by/mutate is accomplishing the same thing as apply above), and spread them back into a wide format.

library(dplyr)
library(tidyr)

yld_tbl %>%
  gather(label, value, -lot) %>%
  arrange(lot, match(label, sort_tbl$label)) %>%
  replace_na(list(value = 1)) %>%
  group_by(lot) %>%
  mutate(value = ifelse(cumsum(value == 0) > 0 & value == 1, NA, value)) %>%
  spread(label, value)

Note that unlike the matrix-based approach, this does not preserve the ordering of the columns.


问:
Can't change width and height values of a shape in AS3
This is my Entity class.

```<code>package  {
    import flash.display.Shape;
    public class Entity extends Shape{
        public var color:int;
        public function
        Entity(xA:Number,yA:Number,widthA:Number,heightA:Number,c:int) {
            this.x=xA;
            this.y=yA;
            this.width=widthA;
            this.height=heightA;
            color=c;
            graphics.beginFill(color);
            graphics.drawRect(x,y,width,height);
            graphics.endFill();
        }
    }
}
</code>```

And this is my main code.

```<code>var rectangle:Entity = new Entity(10,10,100,100,0xFF0000);
addChild(rectangle);
trace(rectangle.x+" "+rectangle.y+" "+rectangle.width+" "+rectangle.height+" "+rectangle.color);
</code>```

And what I'm expecting is for widthA and heightA to change the width and height of the shape, but when I run the code I get this

```<code>10 10 0 0 16711680
</code>```

From the trace, which indicates the x and y position are changing but not the height. Why is this?

答:
The problem is that you're setting the width and height of a display object with no graphics. Since its width and height at that point are zero, you're asking Flash to set the scale values to infinity. There's no way an empty display object can have width and height other than zero.

Try this:

```<code>        this.x=xA;
        this.y=yA;
        color=c;
        graphics.beginFill(color);
        graphics.drawRect(0,0,widthA,heightA); // I suspect you don't want x and y here.
        graphics.endFill();
</code>```

The width and height will be set automatically.

Body:
This is my Entity class.

package  {
    import flash.display.Shape;
    public class Entity extends Shape{
        public var color:int;
        public function
        Entity(xA:Number,yA:Number,widthA:Number,heightA:Number,c:int) {
            this.x=xA;
            this.y=yA;
            this.width=widthA;
            this.height=heightA;
            color=c;
            graphics.beginFill(color);
            graphics.drawRect(x,y,width,height);
            graphics.endFill();
        }
    }
}

And this is my main code.

var rectangle:Entity = new Entity(10,10,100,100,0xFF0000);
addChild(rectangle);
trace(rectangle.x+" "+rectangle.y+" "+rectangle.width+" "+rectangle.height+" "+rectangle.color);

And what I'm expecting is for widthA and heightA to change the width and height of the shape, but when I run the code I get this

10 10 0 0 16711680

From the trace, which indicates the x and y position are changing but not the height. Why is this?

Body:
The problem is that you're setting the width and height of a display object with no graphics. Since its width and height at that point are zero, you're asking Flash to set the scale values to infinity. There's no way an empty display object can have width and height other than zero.

Try this:

        this.x=xA;
        this.y=yA;
        color=c;
        graphics.beginFill(color);
        graphics.drawRect(0,0,widthA,heightA); // I suspect you don't want x and y here.
        graphics.endFill();

The width and height will be set automatically.


问:
Show another element if current input was changed
I want to show one element if current input was changed.

```<code>$('.type_number').change(function() {
  $(this)
  $('.check-update').css('display', 'block')
})
</code>```

<input class="type_number" type="number" name="amount" value="{{ product.amount }}">
<input type="hidden" name="product" value="{{ product.product.id }}">
<button type="submit" class="btn btn-link check-update">

</button>
```

How to say jquery if current was changed show another element

This creates a difficulty for me and besides I can not figure out how to do it. Please explain me if someone knows about it

答:
Maybe you're searching this:

$('.type_number').change(function () {

         if($(this).val() < 1 ) {
          $('.check-update i').addClass('fa-remove');
          $('.check-update i').removeClass('fa-check');
         } else {
            $('.check-update i').addClass('fa-check');
             $('.check-update i').removeClass('fa-remove');
        }
     });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="type_number" type="number" name="amount" value="{{ product.amount }}">
        <input type="hidden" name="product" value="{{ product.product.id }}">
        <button type="submit" class="btn btn-link check-update"><i class="fa fa-remove"></i></button></code>```

Body:
I want to show one element if current input was changed.

$('.type_number').change(function() {
  $(this)
  $('.check-update').css('display', 'block')
})

<input class="type_number" type="number" name="amount" value="{{ product.amount }}">
<input type="hidden" name="product" value="{{ product.product.id }}">
<button type="submit" class="btn btn-link check-update">

</button>

How to say jquery if current was changed show another element

This creates a difficulty for me and besides I can not figure out how to do it. Please explain me if someone knows about it

Body:
Maybe you're searching this:

$('.type_number').change(function () {

         if($(this).val() < 1 ) {
          $('.check-update i').addClass('fa-remove');
          $('.check-update i').removeClass('fa-check');
         } else {
            $('.check-update i').addClass('fa-check');
             $('.check-update i').removeClass('fa-remove');
        }
     });

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="type_number" type="number" name="amount" value="{{ product.amount }}">
        <input type="hidden" name="product" value="{{ product.product.id }}">
        <button type="submit" class="btn btn-link check-update"><i class="fa fa-remove"></i></button>


问:
How to search with couchdb nano
I am trying to search couchdb with nano, as described here:

https://github.com/dscape/nano#dbsearchdesignname-searchname-params-callback

But I get 'document is missing attachment'.

```<code>var config = require('./config.js');
var nano = require('nano')(config.dbhost);

var couch = nano.db.use('my-database');

couch.search('object-views', 'by-content', {q: 'hello'}, function(err, data) {
    if(err) {
        console.log('ERROR ', err);
    } else {
        console.log(data);
    }
})
</code>```

EDIT this is my view code:

```<code>function (doc) {
  if(doc.type && doc.type==='message') {
    emit(doc.text.toLowerCase(), 1);
  }
}
</code>```

答:
So I looked inside nano code and found that the search is designed for Cloudant only. It calls a view of type "search".

So instead of calling _designdoc/name/_view/something, it calls:

_designdoc/name/_search/something

So basically, use db.view

Title: How to search with couchdb nano

Body:
I am trying to search couchdb with nano, as described here:

https://github.com/dscape/nano#dbsearchdesignname-searchname-params-callback

But I get 'document is missing attachment'.

var config = require('./config.js');
var nano = require('nano')(config.dbhost);

var couch = nano.db.use('my-database');

couch.search('object-views', 'by-content', {q: 'hello'}, function(err, data) {
    if(err) {
        console.log('ERROR ', err);
    } else {
        console.log(data);
    }
})

EDIT this is my view code:

function (doc) {
  if(doc.type && doc.type==='message') {
    emit(doc.text.toLowerCase(), 1);
  }
}


问:
Expand Multi-level Powershell nested hash tables from JSON api call
I am having an issue with a JSON API call using Powershell, that returns a multi-level nested array. Using the standard convertfrom-json & convertto-json doesn't give me the full results. I just get a ...

I have done a lot of research on this and found the following link  on stack for expanding the nested hash tables, and this is about the best format that I have gotten. For reference, I am trying to insert employee records into SQL Server. I have a JSON function for doing so, and need to get the JSON response in the expanded format. There are some security aspects, that won't allow me to post the actual detail so I am trying to provide an example of some issues that I am having. Keep in mind the response is for 1 employee record out of hundreds overall, and in SQL will be one table with a row per employee.

```<code>$json1 = Invoke-webRequest -Uri $Workeruri -Certificate $cert -Headers $WorkerHeader | convertfrom-json

$workers = $json1.workers | select -property *

$workers | format-table Name, @{n='Value'; e={
    if ($_.Value -is [Hashtable]) {
        $ht = $_.Value
        $a = $ht.keys | sort | % { '{0}={1}' -f $_, $ht[$_] }
        '{{{0}}}' -f ($a -join ', ')
    } else {
        $_.Value
    }
}}

$workers
</code>```

I have also tried:

```<code>$workers | convertto-json
</code>```

and

```<code>$workers = json1.workers | foreach-object {$_}
</code>```

The data returned comes back like this:

```<code>associateOID          : XXXXXXXXXXXXXX
workerID              : @{idValue=XXXXXXX}
person                : @{governmentIDs=System.Object[]; legalName=; birthDate=0000-00-00; legalAddress=; genderCode=; maritalStatusCode=; socialInsurancePrograms=System.Object[]; tobaccoUserIndicator=False; raceCode=; customFieldGroup=}
workerDates           : @{originalHireDate=2015-03-09; terminationDate=2016-03-18}
workerStatus          : @{statusCode=}
businessCommunication : @{emails=System.object[]}
workAssignments       : {@{itemID=xxxxxx; occupationalclassification=System.Object[]; etc}}
</code>```

I need it to come back with all of the columns on the left side, utilizing the "AssociateOID" as the key identifier for the individual. I have previously gotten the JSON response to come back completely expanded using this format but it wasn't working with the import into SQL Server or looking very nice like the Google Postman response:

```<code>$json1 = Invoke-webRequest -Uri $Workeruri -Certificate $cert -Headers $WorkerHeader | format-list -property *
</code>```

答:
You mean you want to get a JSON file that all objects/properties are expanded, right? Use the -Depth option of ConvertTo-Json to write a JSON file properly. Default value of -Depth option is 2.

$workers | ConvertTo-Json -Depth 100
```

Specify the appropriate depth according to your JSON files.

Body:
I am having an issue with a JSON API call using Powershell, that returns a multi-level nested array. Using the standard convertfrom-json & convertto-json doesn't give me the full results. I just get a ...

I have done a lot of research on this and found the following link  on stack for expanding the nested hash tables, and this is about the best format that I have gotten. For reference, I am trying to insert employee records into SQL Server. I have a JSON function for doing so, and need to get the JSON response in the expanded format. There are some security aspects, that won't allow me to post the actual detail so I am trying to provide an example of some issues that I am having. Keep in mind the response is for 1 employee record out of hundreds overall, and in SQL will be one table with a row per employee.

$json1 = Invoke-webRequest -Uri $Workeruri -Certificate $cert -Headers $WorkerHeader | convertfrom-json

$workers = $json1.workers | select -property *

$workers | format-table Name, @{n='Value'; e={
    if ($_.Value -is [Hashtable]) {
        $ht = $_.Value
        $a = $ht.keys | sort | % { '{0}={1}' -f $_, $ht[$_] }
        '{{{0}}}' -f ($a -join ', ')
    } else {
        $_.Value
    }
}}

$workers

I have also tried:

$workers | convertto-json

and

$workers = json1.workers | foreach-object {$_}

The data returned comes back like this:

associateOID          : XXXXXXXXXXXXXX
workerID              : @{idValue=XXXXXXX}
person                : @{governmentIDs=System.Object[]; legalName=; birthDate=0000-00-00; legalAddress=; genderCode=; maritalStatusCode=; socialInsurancePrograms=System.Object[]; tobaccoUserIndicator=False; raceCode=; customFieldGroup=}
workerDates           : @{originalHireDate=2015-03-09; terminationDate=2016-03-18}
workerStatus          : @{statusCode=}
businessCommunication : @{emails=System.object[]}
workAssignments       : {@{itemID=xxxxxx; occupationalclassification=System.Object[]; etc}}

I need it to come back with all of the columns on the left side, utilizing the "AssociateOID" as the key identifier for the individual. I have previously gotten the JSON response to come back completely expanded using this format but it wasn't working with the import into SQL Server or looking very nice like the Google Postman response:

$json1 = Invoke-webRequest -Uri $Workeruri -Certificate $cert -Headers $WorkerHeader | format-list -property *

Body:
You mean you want to get a JSON file that all objects/properties are expanded, right? Use the -Depth option of ConvertTo-Json to write a JSON file properly. Default value of -Depth option is 2.

$workers | ConvertTo-Json -Depth 100

Specify the appropriate depth according to your JSON files.


问:
How to represent a dependency relationship between node and artifact in UML Deployment Diagram?
I have a web application that reads from a file. My application is represented as a node and file as an artifact. Can I use dashed arrow to represent their relationship ?

答: That's perfectly ok. You could optionally stereotype the dependency with <<create>>.


问:
UrlHelper returning Url that executes another method
Im doing a tutorial about Web APIs, I have 2 controllers, one repo and one factory that returns the models, the response is in json and returns the data and the url.

This is my modelFactory:

```<code>public class ModelFactory : IModelFactory
{
    private UrlHelper _UrlHelper;

    public ModelFactory(HttpRequestMessage request)
    {
        _UrlHelper = new UrlHelper(request);
    }

    public FoodModel Create(Food food)
    {
        return new FoodModel()
        {
            Url = _UrlHelper.Link("Food", new { foodid = food.Id }),
            Description = food.Description,
            Measures = food.Measures.Select(m => Create(m))
        };
    }

    public MeasureModel Create(Measure measure)
    {
        MeasureModel measureModel  = new MeasureModel
        {
            Url = _UrlHelper.Link("Food", new { foodid = measure.Food.Id, measures = measure.Id }),
            Description = measure.Description,
            Calories = Math.Round(measure.Calories)
        };

        return measureModel;
    }
}
</code>```

These are my routes in my WebApiConfig:

```<code>public static void Register(HttpConfiguration config)
{
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
    .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept",
                                  "text/html",
                                  StringComparison.InvariantCultureIgnoreCase,
                                  true,
                                  "application/json"));

    config.Formatters.Remove(config.Formatters.XmlFormatter);

    config.Routes.MapHttpRoute(
        name: "Food",
        routeTemplate: "api/nutrition/foods/{foodid}",
        defaults: new { controller = "foods", foodid = RouteParameter.Optional });

    config.Routes.MapHttpRoute(
        name: "Measures",
        routeTemplate: "api/nutrition/foods/{foodid}/measures/{id}",
        defaults: new { controller = "measures", id = RouteParameter.Optional });
}
</code>```

And this is my MeasuresController:

```<code>public class MeasuresController : BaseApiController
{
    public MeasuresController(ICountingKsRepository repo) : base(repo) { }

    public IEnumerable<MeasureModel> Get(int foodid)
    {
        var results = TheRepository.GetMeasuresForFood(foodid)
            .ToList()
            .Select(m => TheModelFactory.Create(m));

        return results;
    }

    public MeasureModel Get(int foodid,int id)
    {

        var results = TheRepository.GetMeasure(id);

        if(results.Food.Id == foodid)
        {
            return TheModelFactory.Create(results);
        }

        return new MeasureModel
        {
            Description = "No Food id associated with this Measure",
            Calories = 0,
            Url = ""
        };
    }

}
</code>```

now, Im using fiddler with the JSONview plugin for Chrome and this is the structure of my json when I call Get(int foodid)

I go to: http://localhost:8901/api/nutrition/foods/1/measures

```<code>[
   {
      Url: "http://localhost:8901/api/nutrition/foods/1?measures=1",
      Description: "1 Cup",
      Calories: 1628
   },
   {
      Url: "http://localhost:8901/api/nutrition/foods/1?measures=2",
      Description: "1 Tbsp",
      Calories: 102
   }
]
</code>```

If I want to go, lets say http://localhost:8901/api/nutrition/foods/1?measures=2 It executes the Get(int foodid) instead of Get(int foodid, int id) but if I change the Url to http://localhost:8901/api/nutrition/foods/1/measures/2

It goes to the correct method.

What is the cause of this?

答:
Well, I found the problem

In my method:

```<code>public MeasureModel Create(Measure measure)
{
    MeasureModel measureModel  = new MeasureModel
    {
        Url = _UrlHelper.Link("Food", new { foodid = measure.Food.Id, measures = measure.Id }),
        Description = measure.Description,
        Calories = Math.Round(measure.Calories)
    };

    return measureModel;
}
</code>```

The Url was routing to Food instead of Measures, so I needed to change the Url property with this:

```<code>Url = _UrlHelper.Link("Measures", new { foodid = measure.Food.Id, measures = measure.Id })
</code>```

Body:
Im doing a tutorial about Web APIs, I have 2 controllers, one repo and one factory that returns the models, the response is in json and returns the data and the url.

This is my modelFactory:

public class ModelFactory : IModelFactory
{
    private UrlHelper _UrlHelper;

    public ModelFactory(HttpRequestMessage request)
    {
        _UrlHelper = new UrlHelper(request);
    }

    public FoodModel Create(Food food)
    {
        return new FoodModel()
        {
            Url = _UrlHelper.Link("Food", new { foodid = food.Id }),
            Description = food.Description,
            Measures = food.Measures.Select(m => Create(m))
        };
    }

    public MeasureModel Create(Measure measure)
    {
        MeasureModel measureModel  = new MeasureModel
        {
            Url = _UrlHelper.Link("Food", new { foodid = measure.Food.Id, measures = measure.Id }),
            Description = measure.Description,
            Calories = Math.Round(measure.Calories)
        };

        return measureModel;
    }
}

These are my routes in my WebApiConfig:

public static void Register(HttpConfiguration config)
{
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.MediaTypeMappings
    .Add(new System.Net.Http.Formatting.RequestHeaderMapping("Accept",
                                  "text/html",
                                  StringComparison.InvariantCultureIgnoreCase,
                                  true,
                                  "application/json"));

    config.Formatters.Remove(config.Formatters.XmlFormatter);

    config.Routes.MapHttpRoute(
        name: "Food",
        routeTemplate: "api/nutrition/foods/{foodid}",
        defaults: new { controller = "foods", foodid = RouteParameter.Optional });

    config.Routes.MapHttpRoute(
        name: "Measures",
        routeTemplate: "api/nutrition/foods/{foodid}/measures/{id}",
        defaults: new { controller = "measures", id = RouteParameter.Optional });
}

And this is my MeasuresController:

public class MeasuresController : BaseApiController
{
    public MeasuresController(ICountingKsRepository repo) : base(repo) { }

    public IEnumerable<MeasureModel> Get(int foodid)
    {
        var results = TheRepository.GetMeasuresForFood(foodid)
            .ToList()
            .Select(m => TheModelFactory.Create(m));

        return results;
    }

    public MeasureModel Get(int foodid,int id)
    {

        var results = TheRepository.GetMeasure(id);

        if(results.Food.Id == foodid)
        {
            return TheModelFactory.Create(results);
        }

        return new MeasureModel
        {
            Description = "No Food id associated with this Measure",
            Calories = 0,
            Url = ""
        };
    }

}

now, Im using fiddler with the JSONview plugin for Chrome and this is the structure of my json when I call Get(int foodid)

I go to: http://localhost:8901/api/nutrition/foods/1/measures

[
   {
      Url: "http://localhost:8901/api/nutrition/foods/1?measures=1",
      Description: "1 Cup",
      Calories: 1628
   },
   {
      Url: "http://localhost:8901/api/nutrition/foods/1?measures=2",
      Description: "1 Tbsp",
      Calories: 102
   }
]

If I want to go, lets say http://localhost:8901/api/nutrition/foods/1?measures=2 It executes the Get(int foodid) instead of Get(int foodid, int id) but if I change the Url to http://localhost:8901/api/nutrition/foods/1/measures/2

It goes to the correct method.

What is the cause of this?

Body:
Well, I found the problem

In my method:

public MeasureModel Create(Measure measure)
{
    MeasureModel measureModel  = new MeasureModel
    {
        Url = _UrlHelper.Link("Food", new { foodid = measure.Food.Id, measures = measure.Id }),
        Description = measure.Description,
        Calories = Math.Round(measure.Calories)
    };

    return measureModel;
}

The Url was routing to Food instead of Measures, so I needed to change the Url property with this:

Url = _UrlHelper.Link("Measures", new { foodid = measure.Food.Id, measures = measure.Id })


问:
Trying to export multiple variables in vuejs
I started creating a web app with the firebase database.  The firebase config is in a separate file that gets imported into the application.

Now I want to add firebase storage, but I can't seem to export both db and st.  I get an error message saying that vuejs doesn't support named exports.  I would export app instead and get rid of the db and st references, however my application already has tons of references to db.  Is there a simple way to export db and st?

```<code>const app = Firebase.initializeApp(config);
const db = app.database();
const st = app.storage();  //this was recently added

export default db;  //How do I add 'st' to the export in vuejs?
</code>```

答:
In order to achieve what you want,

you can export an object with db and st as properties, or export different variables.

this syntax is called ES6, which use modules. you can read more about them here (2ality blog) and here (MDN).

You can try:

```<code>export { db, st };
</code>```

or

```<code>export const db = app.database();
export const st = app.storage();
</code>```

Then, import them wherever you want.

```<code>import { db, st } from 'path/to/file'
</code>```

Body:
I started creating a web app with the firebase database.  The firebase config is in a separate file that gets imported into the application.

Now I want to add firebase storage, but I can't seem to export both db and st.  I get an error message saying that vuejs doesn't support named exports.  I would export app instead and get rid of the db and st references, however my application already has tons of references to db.  Is there a simple way to export db and st?

const app = Firebase.initializeApp(config);
const db = app.database();
const st = app.storage();  //this was recently added

export default db;  //How do I add 'st' to the export in vuejs?

Body:
In order to achieve what you want,

you can export an object with db and st as properties, or export different variables.

this syntax is called ES6, which use modules. you can read more about them here (2ality blog) and here (MDN).

You can try:

export { db, st };

or

export const db = app.database();
export const st = app.storage();

Then, import them wherever you want.

import { db, st } from 'path/to/file'


问:
Swashbuckle 5 can't find my ApiControllers
I'm at a point where I really need API documentation for my WebAPI 2 project, and I used the Swashbuckle 5 NuGet package. Out of the box, I can hit {myrooturl}/swagger and a UI pops up, but there are no controllers, methods, or anything in there. Just my title: [ base url: /EM.Services , api version: v1 ]

I took a look at the Swashbuckle docs, and since I'm using OWIN which is hosted by IIS, I modified the SwaggerConfig with:

```<code>c.RootUrl(req => req.RequestUri.GetLeftPart(UriPartial.Authority) + req.GetRequestContext().VirtualPathRoot.TrimEnd('/'));
</code>```

as per this doc: https://github.com/domaindrivendev/Swashbuckle/blob/1326e753ce9b3a823b3c156b0b601134692ffc58/README.md#transitioning-to-swashbuckle-50

I also setup the build of the project to generate the XML docs and pointed my SwaggerConfig to it with:

```<code>    private static string GetXmlCommentsPath()
    {
        // tried with an without the \bin
        return String.Format(@"{0}\bin\EM.Services.XML", AppDomain.CurrentDomain.BaseDirectory);
    }
</code>```

I'm not sure if the XML docs working/not-working has anything to do with it though, as I get absolutely no controllers on the swagger-ui page.

For what it's worth, all of my controller inherit from a BaseController, which in turn inherits from ApiController.

Is there something screwy with my WebApiConfig?

```<code>    public static void Register(HttpConfiguration config)
    {

        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        config.Filters.Add(new ValidateModelAttribute());

        config.Filters.Add(new BaseAuthenticationAttribute());

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
</code>```

My concrete controllers all look like this (I've tried subbing out BaseController for ApiController and there is no change):

```<code>[RoutePrefix("api/whatever")]
public class FooController : BaseController
</code>```

and my Base controller doesn't do much (yet), just has an attribute:

```<code>[BuildClaims]
public abstract class BaseController : ApiController
</code>```

The empty page persists across using IIS Express or full blown IIS.

Update:
Example of a contrived controller I made that is really basic. It also does not show up, as I still have the boiler plate swagger ui with nothing in it.

```<code>/// <summary>
/// I am a test
/// </summary>
[RoutePrefix("api/dummy")]
public class DummyController : ApiController
{
    [HttpGet]
    [Route("foo")]
    public int Foo()
    {
        return 42;
    }
}
</code>```

答:
I just had the same issue myself and none of these helped me.

After some messing around I figured out that the routes that I'd labeled as [System.Web.Mvc.Route("visit")] were not being discovered by swagger.

```<code>    [HttpGet]
    // ROUTE ATTRIBUTE NOT FOUND BY SWAGGER
    [System.Web.Mvc.Route("visit")]
    public string Visit()
    {
</code>```

but [System.Web.Http.Route("visit")] is

```<code>    [HttpGet]
    // ROUTE ATTRIBUTE *IS* FOUND BY SWAGGER
    [System.Web.Http.Route("visit")]
    public string Visit()
    {
</code>```

I'm not 100% sure, but if it matters, I also switched from

```<code> public class MyAPIController : Controller
</code>```

to:

```<code> public class MyAPIController : System.Web.Http.ApiController
</code>```

More accurately I removed the "using" statement for System.Web.Mvc, but the code is listed for illustrative purposes.

Hope this helps someone else in future :) Good luck!

Body:
I'm at a point where I really need API documentation for my WebAPI 2 project, and I used the Swashbuckle 5 NuGet package. Out of the box, I can hit {myrooturl}/swagger and a UI pops up, but there are no controllers, methods, or anything in there. Just my title: [ base url: /EM.Services , api version: v1 ]

I took a look at the Swashbuckle docs, and since I'm using OWIN which is hosted by IIS, I modified the SwaggerConfig with:

c.RootUrl(req => req.RequestUri.GetLeftPart(UriPartial.Authority) + req.GetRequestContext().VirtualPathRoot.TrimEnd('/'));

as per this doc: https://github.com/domaindrivendev/Swashbuckle/blob/1326e753ce9b3a823b3c156b0b601134692ffc58/README.md#transitioning-to-swashbuckle-50

I also setup the build of the project to generate the XML docs and pointed my SwaggerConfig to it with:

    private static string GetXmlCommentsPath()
    {
        // tried with an without the \bin
        return String.Format(@"{0}\bin\EM.Services.XML", AppDomain.CurrentDomain.BaseDirectory);
    }

I'm not sure if the XML docs working/not-working has anything to do with it though, as I get absolutely no controllers on the swagger-ui page.

For what it's worth, all of my controller inherit from a BaseController, which in turn inherits from ApiController.

Is there something screwy with my WebApiConfig?

    public static void Register(HttpConfiguration config)
    {

        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        config.Filters.Add(new ValidateModelAttribute());

        config.Filters.Add(new BaseAuthenticationAttribute());

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

My concrete controllers all look like this (I've tried subbing out BaseController for ApiController and there is no change):

[RoutePrefix("api/whatever")]
public class FooController : BaseController

and my Base controller doesn't do much (yet), just has an attribute:

[BuildClaims]
public abstract class BaseController : ApiController

The empty page persists across using IIS Express or full blown IIS.

Update:
Example of a contrived controller I made that is really basic. It also does not show up, as I still have the boiler plate swagger ui with nothing in it.

///
/// I am a test
///
[RoutePrefix("api/dummy")]
public class DummyController : ApiController
{
    [HttpGet]
    [Route("foo")]
    public int Foo()
    {
        return 42;
    }
}

Body:
I just had the same issue myself and none of these helped me.

After some messing around I figured out that the routes that I'd labeled as [System.Web.Mvc.Route("visit")] were not being discovered by swagger.

    [HttpGet]
    // ROUTE ATTRIBUTE NOT FOUND BY SWAGGER
    [System.Web.Mvc.Route("visit")]
    public string Visit()
    {

but [System.Web.Http.Route("visit")] is

    [HttpGet]
    // ROUTE ATTRIBUTE *IS* FOUND BY SWAGGER
    [System.Web.Http.Route("visit")]
    public string Visit()
    {

I'm not 100% sure, but if it matters, I also switched from

 public class MyAPIController : Controller

to:

 public class MyAPIController : System.Web.Http.ApiController

More accurately I removed the "using" statement for System.Web.Mvc, but the code is listed for illustrative purposes.

Hope this helps someone else in future :) Good luck!


问:
what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?
what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q'] (which is used in Drupal)?

答:
In the context of Drupal, the difference will depend whether clean URLs are on or not.

With them off, $_SERVER['REQUEST_URI'] will have the full path of the page as called w/ /index.php, while $_GET["q"] will just have what is assigned to q.

With them on, they will be nearly identical w/o other arguments, but $_GET["q"] will be missing the leading /.  Take a look towards the end of the default .htaccess to see what is going on.  They will also differ if additional arguments are passed into the page, eg when a pager is active.

ContentLicense: CC BY-SA 2.5


问:
Python: How combine returned value from 2 functions and appending them into a list using thread?
I am new to thread, I had encountered abnormal result while printing the value inside a list using thread to allow 2 functions to working at the same time and appending the result to a list. Below my code:

```<code>import threading
def func1():

  return "HTML"

def func2():

  return "IS FUN"

threadslist = []

thread1 = threading.Thread(target=func1)
thread2 = threading.Thread(target=func2)

x = thread1
y = thread2

x.start()
y.start()

threadslist.append(x)
threadslist.append(y)

print(threadslist)
</code>```

And here is the result for the list:

```<code>[<Thread(Thread-1, stopped 1076)>, <Thread(Thread-2, stopped 7948)>]
</code>```

Why it storing the Threads object instead of storing ['HTML', 'IS FUN'] ?

答:
```<code>import threading
threading_list = []
def func1():
   threading_list.append("HTML")

def func2():
   threading_list.append("IS FUN")

thread1 = threading.Thread(target=func1)
thread2 = threading.Thread(target=func2)

x = thread1
y = thread2

x.start()
y.start()

print(threading_list)
</code>```

Body:
I am new to thread, I had encountered abnormal result while printing the value inside a list using thread to allow 2 functions to working at the same time and appending the result to a list. Below my code:

import threading
def func1():

  return "HTML"

def func2():

  return "IS FUN"

threadslist = []

thread1 = threading.Thread(target=func1)
thread2 = threading.Thread(target=func2)

x = thread1
y = thread2

x.start()
y.start()

threadslist.append(x)
threadslist.append(y)

print(threadslist)

And here is the result for the list:

[<Thread(Thread-1, stopped 1076)>, <Thread(Thread-2, stopped 7948)>]

Why it storing the Threads object instead of storing ['HTML', 'IS FUN'] ?


问:
makefile use variable defined in target
How can one use the variable defined inside a make target

```<code>.PHONY: foo

VAR_GLOBAL=$(shell cat /tmp/global)

foo:
    echo "local" > /tmp/local
    VAR_LOCAL=$(shell cat /tmp/local)
    echo ${VAR_GLOBAL}
    echo ${VAR_LOCAL}
</code>```

here is the execution output:

```<code>$ echo global > /tmp/global
$ make foo
echo "local" > /tmp/local
VAR_LOCAL=local
echo global
global
echo
</code>```

答:
You probably want to use the override directive in a target-specific variable assignment, so try:

```<code>foo: override LS_LOCAL=$(shell ls /var | tail -1)
    echo ${LS_GLOBAL}
    echo ${LS_LOCAL}
</code>```

If LS_LOCAL is never defined (even by builtin-rules) you might not need the override keyword.

BTW, you might avoid $(shell ls /var | tail -1) by using the wildcard  function combined with the lastword function (perhaps combined with notdir function), so you might code $(lastword $(wildcard /var/*)) or $(notdir $(lastword $(wildcard /var/*))) instead . However, beware of the order of expansion, and of filenames with spaces. At last the shell function probably uses your $PATH variable (so strange things could happen if some weird ls program appears there before /bin/ls). Perhaps using $(shell /bin/ls /var | /usr/bin/tail -1) might be better.

Look also into Guile-extended make; consider perhaps some other build-automation tool like ninja and/or generating your Makefile (or other build configuration) with something like a configure script generated via autoconf or cmake.

Notice also that a command in recipe can be made of several physical backslashed lines (hence executed in the same shell). Maybe you might consider something like

```<code>  export MY_VAR=$$(ls /var | tail); \
  dosomething; \
  use $$MY_VAR
</code>```

inside some recipe.

Title: makefile use variable defined in target

Body:
How can one use the variable defined inside a make target

.PHONY: foo

VAR_GLOBAL=$(shell cat /tmp/global)

foo:
    echo "local" > /tmp/local
    VAR_LOCAL=$(shell cat /tmp/local)
    echo ${VAR_GLOBAL}
    echo ${VAR_LOCAL}

here is the execution output:

$ echo global > /tmp/global
$ make foo
echo "local" > /tmp/local
VAR_LOCAL=local
echo global
global
echo

Body:
You probably want to use the override directive in a target-specific variable assignment, so try:

foo: override LS_LOCAL=$(shell ls /var | tail -1)
    echo ${LS_GLOBAL}
    echo ${LS_LOCAL}

If LS_LOCAL is never defined (even by builtin-rules) you might not need the override keyword.

BTW, you might avoid $(shell ls /var | tail -1) by using the wildcard  function combined with the lastword function (perhaps combined with notdir function), so you might code $(lastword $(wildcard /var/*)) or $(notdir $(lastword $(wildcard /var/*))) instead . However, beware of the order of expansion, and of filenames with spaces. At last the shell function probably uses your $PATH variable (so strange things could happen if some weird ls program appears there before /bin/ls). Perhaps using $(shell /bin/ls /var | /usr/bin/tail -1) might be better.

Look also into Guile-extended make; consider perhaps some other build-automation tool like ninja and/or generating your Makefile (or other build configuration) with something like a configure script generated via autoconf or cmake.

Notice also that a command in recipe can be made of several physical backslashed lines (hence executed in the same shell). Maybe you might consider something like

  export MY_VAR=$$(ls /var | tail); \
  dosomething; \
  use $$MY_VAR

inside some recipe.


问:
React-virtualized infinite scroll not rendering correctly
I have a component in which i want to list numbers from an array.
I tried to implement the react virtualized infinite scroll like in this example :
https://github.com/bvaughn/react-virtualized/blob/master/docs/InfiniteLoader.md#user-content-infiniteloader-and-list

I think i am close from the solution but can't figure out why the code is not working. Can you help me ? Here is my actual component (I tried to clean it as much as possible)

import * as React from 'react';

const dataTest = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];

export class EventsViewController extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            threshold: 10,
            actualData: []
        };

        this.rowRenderer = this.rowRenderer.bind(this);
        this.isRowLoaded = this.isRowLoaded.bind(this);
        this.loadMoreRows = this.loadMoreRows.bind(this);
    }

    public isRowLoaded(param: any) {
        return !!this.state.actualData[param.index];
    }

    public loadMoreRows(param: any) {
        const startIndex = param.startIndex;
        const stopIndex = param.stopIndex;

        const dataLoaded = [];
        for (let i = startIndex; i < stopIndex; i++) {
            dataLoaded[i] = dataTest[i];
        }

        this.setState({
            actualData: dataLoaded
        });
    }

    public componentWillMount() {
        const dataLoaded] = [];
        for (let i = 0; i < this.state.threshold; i++) {
            dataLoaded[i] = dataTest[i];
        }
        this.setState({
            actualData: dataLoaded
        });
    }

    public rowRenderer(param: any) {
        const list = this.state.actualData;
        const index = param.index;

        return (

                {list[index]}

        );
    }

    public render() {
        return (
            <InfiniteLoader
                isRowLoaded={this.isRowLoaded}
                loadMoreRows={this.loadMoreRows}
                rowCount={this.state.actualData.length}
                >
            {({ onRowsRendered, registerChild }) => (
                <List
                    height={250}
                    onRowsRendered={onRowsRendered}
                    ref={registerChild}
                    rowCount={this.state.actualData.length}
                    rowHeight={50}
                    rowRenderer={this.rowRenderer}
                    width={300}
                />
            )}
            </InfiniteLoader>
        );
    }
}```

When i scroll, loadMoreRows function is called indefinitely and the display "blinks" (the scrollbar moves fast by itself from vertically).

Thanks for your help...

答:
You need to set

```<code>rowCount={dataTest.length}
</code>```

in the List component.

Body:
I have a component in which i want to list numbers from an array.
I tried to implement the react virtualized infinite scroll like in this example :
https://github.com/bvaughn/react-virtualized/blob/master/docs/InfiniteLoader.md#user-content-infiniteloader-and-list

I think i am close from the solution but can't figure out why the code is not working. Can you help me ? Here is my actual component (I tried to clean it as much as possible)

import * as React from 'react';

const dataTest = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30];

export class EventsViewController extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            threshold: 10,
            actualData: []
        };

        this.rowRenderer = this.rowRenderer.bind(this);
        this.isRowLoaded = this.isRowLoaded.bind(this);
        this.loadMoreRows = this.loadMoreRows.bind(this);
    }

    public isRowLoaded(param: any) {
        return !!this.state.actualData[param.index];
    }

    public loadMoreRows(param: any) {
        const startIndex = param.startIndex;
        const stopIndex = param.stopIndex;

        const dataLoaded = [];
        for (let i = startIndex; i < stopIndex; i++) {
            dataLoaded[i] = dataTest[i];
        }

        this.setState({
            actualData: dataLoaded
        });
    }

    public componentWillMount() {
        const dataLoaded] = [];
        for (let i = 0; i < this.state.threshold; i++) {
            dataLoaded[i] = dataTest[i];
        }
        this.setState({
            actualData: dataLoaded
        });
    }

    public rowRenderer(param: any) {
        const list = this.state.actualData;
        const index = param.index;

        return (

                {list[index]}

        );
    }

    public render() {
        return (
            <InfiniteLoader
                isRowLoaded={this.isRowLoaded}
                loadMoreRows={this.loadMoreRows}
                rowCount={this.state.actualData.length}
                >
            {({ onRowsRendered, registerChild }) => (
                <List
                    height={250}
                    onRowsRendered={onRowsRendered}
                    ref={registerChild}
                    rowCount={this.state.actualData.length}
                    rowHeight={50}
                    rowRenderer={this.rowRenderer}
                    width={300}
                />
            )}
            </InfiniteLoader>
        );
    }
}

When i scroll, loadMoreRows function is called indefinitely and the display "blinks" (the scrollbar moves fast by itself from vertically).

Thanks for your help...

Body:
You need to set

rowCount={dataTest.length}

in the List component.


问:
Executable script in R package `inst/`
I am writing an R package (for internal use, will never be on CRAN). One of my functions calls a shell script containing node.js commands. I've put the file in inst/node_script.sh, so that when the package is installed I can call the script with

```<code>system(system.file("./node_script.sh", package = "mypackage"))
</code>```

This works great on my development machine. But when I install the package on a test machine, node_script.sh is in the proper place, but it drops the executable mode, so I can't run the script without first chmod +x .... Three questions:

How can I keep the file permissions on my script file through install?

Is there a clean way to set them afterwards? I'm using devtools::install_github

Is this even the best way to go about this?

答:
This best one could apparently do is to use cleanup script https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Configure-and-cleanup

and call the installation with --clean argument, such as devtools::install_github("foo/bar",args=c("--clean"))

If your /tmp has noexec flag like me, then you are out of luck.

Here is a related question R package that delivers executables residing in /inst

Title: Executable script in R package `inst/`

Body:
I am writing an R package (for internal use, will never be on CRAN). One of my functions calls a shell script containing node.js commands. I've put the file in inst/node_script.sh, so that when the package is installed I can call the script with

system(system.file("./node_script.sh", package = "mypackage"))

This works great on my development machine. But when I install the package on a test machine, node_script.sh is in the proper place, but it drops the executable mode, so I can't run the script without first chmod +x .... Three questions:

How can I keep the file permissions on my script file through install?

Is there a clean way to set them afterwards? I'm using devtools::install_github

Is this even the best way to go about this?


问:
Counting the number of occurrences of a value in R
If I have a vector of numbers in R.

```<code>numbers <- c(1,1, 2,2,2, 3,3, 4,4,4,4, 1)
</code>```

I want to return a vector that provides the number of times that value has occurred cumulatively along the vector. I.e.

```<code>results <- c(1,2, 1,2,3, 1,2, 1,2,3,4, 3)
</code>```

答:
We can use ave and apply the seq_along by grouping with the 'numbers' vector

```<code>ave(numbers, numbers, FUN = seq_along)
#[1] 1 2 1 2 3 1 2 1 2 3 4 3
</code>```

Body:
If I have a vector of numbers in R.

numbers <- c(1,1, 2,2,2, 3,3, 4,4,4,4, 1)

I want to return a vector that provides the number of times that value has occurred cumulatively along the vector. I.e.

results <- c(1,2, 1,2,3, 1,2, 1,2,3,4, 3)

Body:
We can use ave and apply the seq_along by grouping with the 'numbers' vector

ave(numbers, numbers, FUN = seq_along)
#[1] 1 2 1 2 3 1 2 1 2 3 4 3


问:
ROS python Error "The manifest (with format version 2) must not contain the following tags: run_depend"
I have been following the book "Programming Robots with ROS: A Practical Introduction to the Robot Operating System"

In the "Defining a New Message" part of the book we create a new message definition

```<code>Example 3-3. Complex.msg
float32 real
float32 imaginary
</code>```

so we require to modify the package.xml and add the following lines:

```<code><build_depend>message_generation</build_depend>
<run_depend>message_runtime</run_depend>
</code>```

but when I run the catkin_make in the catkin_ws directory I get the following error

```<code>Error(s) in /home/gtkratosman-lap/catkin_ws/src/basic/package.xml:
- The manifest (with format version 2) must not contain the following tags: run_depend
</code>```

My version:

```<code>ii  python-rospkg                                         1.1.4-100                                           all          ROS package library
ii  python-rospkg-modules                                 1.1.4-1                                             all          ROS package library
</code>```

Here is the full package.xml file

```<code><?xml version="1.0"?>
<package format="2">
  <name>basic</name>
  <version>0.0.0</version>
  <description>The basic package</description>

  <maintainer email="gtkratosman-lap@todo.todo">gtkratosman-
  lap</maintainer>

  <license>TODO</license>

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>rospy</build_depend>

  <run_depend>message_generation</run_depend>
  <run_depend>message_runtime</run_depend>

  <build_export_depend>rospy</build_export_depend>
  <exec_depend>rospy</exec_depend>

  <export>
  </export>
</package>
</code>```

答:
Just omit the format. It is not necessary and breaks your code.
Use this template for your package.xml.

```<code><?xml version="1.0"?>
<package>

    <name>basic</name>
    <version>0.0.0</version>
    <description>The basic package</description>

    <maintainer email="gtkratosman-lap@todo.todo">gtkratosman-lap</maintainer>

    <license>TODO</license>

    <buildtool_depend>catkin</buildtool_depend>
    <build_depend>rospy</build_depend>
    <build_depend>message_generation</build_depend>

    <run_depend>message_runtime</run_depend>

    <export>
    <!-- Other tools can request additional information be placed here -->
    </export>
</code>```

Body:
I have been following the book "Programming Robots with ROS: A Practical Introduction to the Robot Operating System"

In the "Defining a New Message" part of the book we create a new message definition

Example 3-3. Complex.msg
float32 real
float32 imaginary

so we require to modify the package.xml and add the following lines:

<build_depend>message_generation</build_depend>
<run_depend>message_runtime</run_depend>

but when I run the catkin_make in the catkin_ws directory I get the following error

Error(s) in /home/gtkratosman-lap/catkin_ws/src/basic/package.xml:
- The manifest (with format version 2) must not contain the following tags: run_depend

My version:

ii  python-rospkg                                         1.1.4-100                                           all          ROS package library
ii  python-rospkg-modules                                 1.1.4-1                                             all          ROS package library

Here is the full package.xml file

<?xml version="1.0"?>
<package format="2">
  <name>basic</name>
  <version>0.0.0</version>
  <description>The basic package</description>

  <maintainer email="gtkratosman-lap@todo.todo">gtkratosman-
  lap</maintainer>

  <license>TODO</license>

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>rospy</build_depend>

  <run_depend>message_generation</run_depend>
  <run_depend>message_runtime</run_depend>

  <build_export_depend>rospy</build_export_depend>
  <exec_depend>rospy</exec_depend>

  <export>
  </export>
</package>

Body:
Just omit the format. It is not necessary and breaks your code.
Use this template for your package.xml.

<?xml version="1.0"?>
<package>

    <name>basic</name>
    <version>0.0.0</version>
    <description>The basic package</description>

    <maintainer email="gtkratosman-lap@todo.todo">gtkratosman-lap</maintainer>

    <license>TODO</license>

    <buildtool_depend>catkin</buildtool_depend>
    <build_depend>rospy</build_depend>
    <build_depend>message_generation</build_depend>

    <run_depend>message_runtime</run_depend>

    <export>
    <!-- Other tools can request additional information be placed here -->
    </export>


问:
Bind data to parent
I have angular 5 project with the following structure:

app.component.html

```<code><app-header></app-header>
<app-list-view></app-list-view>
<app-footer></app-footer>
</code>```

In my <app-header> component I have a <app-search></app-search> component:

```<code><div id="headerContent">
    <div id="logo">
        <img src="../../../assets/images/logo.png"/>
    </div>

    <app-search></app-search>
</div>
</code>```

In this search.component.html I have:

```<code><div id="searchContent">
  <input [(ngModel)]="queryString" type="text" placeholder="Bijv. PHP developer, AngularJs"/>
  <button>Zoeken</button>
</div>
</code>```

I would like to pass the data from the input field from the app-search component to the app-list-view component.

What would be the best way to do this?

答: The easiest way to achieve communication between components that are not nested (aka parent-child) it to use a service. A useful example is the on in Angular docs. </p>

Title: Bind data to parent

Body:
I have angular 5 project with the following structure:

app.component.html

<app-header></app-header>
<app-list-view></app-list-view>
<app-footer></app-footer>

In my <app-header> component I have a <app-search></app-search> component:

    <app-search></app-search>

In this search.component.html I have:

  <input [(ngModel)]="queryString" type="text" placeholder="Bijv. PHP developer, AngularJs"/>
  <button>Zoeken</button>

I would like to pass the data from the input field from the app-search component to the app-list-view component.

What would be the best way to do this?


问:
Private IBOutlets Swift
I know that our IBOutlets should be private, but for example if I have IBOutlets in TableViewCell, how should I access them from another ViewController? Here is the example why I'm asking this kind of question:

```<code>class BookTableViewCell: UITableViewCell {

    @IBOutlet weak private var bookTitle: UILabel!

}
</code>```

if I assign to the IBOutlet that it should be private, I got an error in another ViewController while I'm accessing the cell property: 'bookTitle' is inaccessible due to 'private' protection level

答:
You should expose only what you need.

For example you can set and get only the text property in the cell.

```<code>class BookTableViewCell: UITableViewCell {
    @IBOutlet weak private var bookTitleLabel: UILabel!

    var bookTitle: String? {
        set {
            bookTitleLabel.text = newValue
        }
        get {
            return bookTitleLabel.text
        }
    }
}
</code>```

And then, wherever you need:

```<code>cell.bookTitle = "It"
</code>```

Now outer objects do not have access to bookTitleLabel but are able to change it's text content.

What i usually do is configure method which receives data object and privately sets all it's outlets features.

Title: Private IBOutlets Swift

Body:
I know that our IBOutlets should be private, but for example if I have IBOutlets in TableViewCell, how should I access them from another ViewController? Here is the example why I'm asking this kind of question:

class BookTableViewCell: UITableViewCell {

    @IBOutlet weak private var bookTitle: UILabel!

}

if I assign to the IBOutlet that it should be private, I got an error in another ViewController while I'm accessing the cell property: 'bookTitle' is inaccessible due to 'private' protection level

Body:
You should expose only what you need.

For example you can set and get only the text property in the cell.

class BookTableViewCell: UITableViewCell {
    @IBOutlet weak private var bookTitleLabel: UILabel!

    var bookTitle: String? {
        set {
            bookTitleLabel.text = newValue
        }
        get {
            return bookTitleLabel.text
        }
    }
}

And then, wherever you need:

cell.bookTitle = "It"

Now outer objects do not have access to bookTitleLabel but are able to change it's text content.

What i usually do is configure method which receives data object and privately sets all it's outlets features.


问:
Generic type bounded by another generic
Suppose I have this:

```<code>interface Shape {}
interface Square extends Shape {}
interface Circle extends Shape {}

interface ShapeBuilder<S extends Shape> {}
</code>```

I want something like this:

```<code>class ShapeBuilderFactory<SB extends ShapeBuilder> {
    SB<Square> getSquareBuilder(){...}
    SB<Circle> getCircleBuilder(){...}
}
</code>```

This code doesn't compile (because ShapeBuilder is a raw type), but I hope you understand the idea.
Is it possible to do something like this in java? How?

(the real problem isn't with shapes builders and factories, I used this example for simplicity)

Edit (more context)

I have different kind of builders:

```<code>interface RegularShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}
interface FunnyShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}

class RegularSquareBuilder extends RegularShapeBuilder<Square> {}
class FunnySquareBuilder extends FunnyShapeBuilder<Square> {}
class RegularCircleBuilder extends RegularShapeBuilder<Circle> {}
class FunnyCircleBuilder extends FunnyShapeBuilder<Circle> {}
</code>```

And I want the factory to do things like this:

```<code>ShapeBuilderFactory<FunnyShapeBuilder> funnyShapeBuilderFactory = ...;
FunnyShapeBuilder<Square> funnySquareBuilder = funnyShapeBuilderFactory.getSquareBuilder();
</code>```

答:
I'm not sure why you wouldn't just have:

```<code>class ShapeBuilderFactory {
    ShapeBuilder<Square> getSquareBuilder(){...}
    ShapeBuilder<Circle> getCircleBuilder(){...}
}
</code>```

Edit

So if you really must have the ShapeBuilder subtype in your factory, you'll need to declare each one of them:

```<code>class ShapeBuilderFactory<SqB extends ShapeBuilder<Square>,
                          CiB extends ShapeBuilder<Circle>> {
    SqB getSquareBuilder(){...}
    CiB getCircleBuilder(){...}
}
</code>```

So you'll have to declare that as:

```<code>ShapeBuilderFactory<FunnySquareBuilder, FunnyCircleBuilder> funnyShapeBuilder = ...
</code>```

But you will be able to say

```<code>FunnyShapeBuilder<Square> funnySquareBuilder = funnyShapeBuilderFactory.getSquareBuilder();
</code>```

The problem you've got is that an implementation of ShapeBuilder can only create one type of shape.  That's how you've declared it.

If this were my code I would use the ShapeBuilderFactory definition I initially wrote and instantiate it with funny or regular builders.  Isn't the point of having these interfaces actually using them?

Title: Generic type bounded by another generic

Body:
Suppose I have this:

interface Shape {}
interface Square extends Shape {}
interface Circle extends Shape {}

interface ShapeBuilder<S extends Shape> {}

I want something like this:

class ShapeBuilderFactory<SB extends ShapeBuilder> {
    SB<Square> getSquareBuilder(){...}
    SB<Circle> getCircleBuilder(){...}
}

This code doesn't compile (because ShapeBuilder is a raw type), but I hope you understand the idea.
Is it possible to do something like this in java? How?

(the real problem isn't with shapes builders and factories, I used this example for simplicity)

Edit (more context)

I have different kind of builders:

interface RegularShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}
interface FunnyShapeBuilder<S extends Shape> extends ShapeBuilder<S> {}

class RegularSquareBuilder extends RegularShapeBuilder<Square> {}
class FunnySquareBuilder extends FunnyShapeBuilder<Square> {}
class RegularCircleBuilder extends RegularShapeBuilder<Circle> {}
class FunnyCircleBuilder extends FunnyShapeBuilder<Circle> {}

And I want the factory to do things like this:

ShapeBuilderFactory<FunnyShapeBuilder> funnyShapeBuilderFactory = ...;
FunnyShapeBuilder<Square> funnySquareBuilder = funnyShapeBuilderFactory.getSquareBuilder();

Body:
I'm not sure why you wouldn't just have:

class ShapeBuilderFactory {
    ShapeBuilder<Square> getSquareBuilder(){...}
    ShapeBuilder<Circle> getCircleBuilder(){...}
}

Edit

So if you really must have the ShapeBuilder subtype in your factory, you'll need to declare each one of them:

class ShapeBuilderFactory<SqB extends ShapeBuilder<Square>,
                          CiB extends ShapeBuilder<Circle>> {
    SqB getSquareBuilder(){...}
    CiB getCircleBuilder(){...}
}

So you'll have to declare that as:

ShapeBuilderFactory<FunnySquareBuilder, FunnyCircleBuilder> funnyShapeBuilder = ...

But you will be able to say

FunnyShapeBuilder<Square> funnySquareBuilder = funnyShapeBuilderFactory.getSquareBuilder();

The problem you've got is that an implementation of ShapeBuilder can only create one type of shape.  That's how you've declared it.

If this were my code I would use the ShapeBuilderFactory definition I initially wrote and instantiate it with funny or regular builders.  Isn't the point of having these interfaces actually using them?


问:
How to print horizontally instead of vertically?
I wrote a script that is supposed to print an answer to a specific input horizontally.

For example if the input is:

```<code>TTACTGGCAT
</code>```

It should print:

```<code>TTACTGGCAT
AATGACCGTA
</code>```

My code:

```<code>x = 0
n = input("Insert DNA seqence: ")
print(n.upper())
while x < len(n):
  if 'T' in n[x]:
    print('A')
  if 'G' in n[x]:
    print('C')
  if 'C' in n[x]:
    print('G')
  if 'A' in n[x]:
    print('T')
  x = x + 1
</code>```

答:
I assume you want to do something like this:

```<code>nucl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}

n = input("Insert DNA seqence: ").upper()
print(n)
print(''.join(nucl_dict.get(nucl, nucl) for nucl in n))
</code>```

nucl_dict defines which nucleotides are complementary.

This joins the characters for the corresponding nucleotides into a string and prints the result.

If the character is not a valid nucleotide, the character is simply added without a change to the complementary string. get tries to find the value given the first argument as a key (in this case each character in n) and if the key does not exist uses the second argument (in this case the same character).

Body:
I wrote a script that is supposed to print an answer to a specific input horizontally.

For example if the input is:

TTACTGGCAT

It should print:

TTACTGGCAT
AATGACCGTA

My code:

x = 0
n = input("Insert DNA seqence: ")
print(n.upper())
while x < len(n):
  if 'T' in n[x]:
    print('A')
  if 'G' in n[x]:
    print('C')
  if 'C' in n[x]:
    print('G')
  if 'A' in n[x]:
    print('T')
  x = x + 1

Body:
I assume you want to do something like this:

nucl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}

n = input("Insert DNA seqence: ").upper()
print(n)
print(''.join(nucl_dict.get(nucl, nucl) for nucl in n))

nucl_dict defines which nucleotides are complementary.

This joins the characters for the corresponding nucleotides into a string and prints the result.

If the character is not a valid nucleotide, the character is simply added without a change to the complementary string. get tries to find the value given the first argument as a key (in this case each character in n) and if the key does not exist uses the second argument (in this case the same character).


问:
Check if means break certain limits R
I have a 100x2 dataset, where the first column identifies the sample, and the second column represents the measurement. Each sample is of size 4, so the dataset looks like:

```<code>V1  V2
1   125.8
1   128.4
1   129.0
1   121.0
2   125.2
2   127.0
2   130.4
2   124.6
3   121.8
3   126.8
..  ..
</code>```

I have calculated the mean for each sample using:

```<code>df2 = subset(data, select = c(2))
means =  t(sapply(split(df2,rep(seq(1,nrow(df2),4),each=4)),colMeans))
</code>```

So I now have a vector of 25 means. I want to check if each of these means falls outside certain limits (defined below), and then return an object containing the sample ID, the mean value for the sample, and information on which limit it broke, setting the output to be of class "shewart":

```<code>warning_upper: 130.4
action_upper: 132.1
warning_lower: 123.6
action_lower: 121.9
</code>```

答:
I've slightly changed the values you provided to make sure the process can spot correctly the pattern you want.</p>

```<code>library(dplyr)

# example dataset
df = read.table(text = "
V1  V2
1   195.8
1   128.4
1   129.0
1   121.0
2   125.2
2   127.0
2   125.4
2   114.6
", header=T)

# function to return info based on a value
f = function(x) {
  ifelse(x < 121.9, "below action",
         ifelse(x < 123.6, "below warning",
                ifelse(x > 132.1, "above action",
                       ifelse(x > 130.4, "above warning", "normal"))))
  }

df %>%
  group_by(V1) %>%                      # for each V1
  summarise(MeanValue = mean(V2)) %>%   # calculate means
  mutate(info = f(MeanValue))           # use the function to get relevant info

# # A tibble: 2 x 3
#      V1 MeanValue          info
#   <int>     <dbl>         <chr>
# 1     1    143.55  above action
# 2     2    123.05 below warning
</code>```

Title: Check if means break certain limits R

Body:
I have a 100x2 dataset, where the first column identifies the sample, and the second column represents the measurement. Each sample is of size 4, so the dataset looks like:

V1  V2
1   125.8
1   128.4
1   129.0
1   121.0
2   125.2
2   127.0
2   130.4
2   124.6
3   121.8
3   126.8
..  ..

I have calculated the mean for each sample using:

df2 = subset(data, select = c(2))
means =  t(sapply(split(df2,rep(seq(1,nrow(df2),4),each=4)),colMeans))

So I now have a vector of 25 means. I want to check if each of these means falls outside certain limits (defined below), and then return an object containing the sample ID, the mean value for the sample, and information on which limit it broke, setting the output to be of class "shewart":

warning_upper: 130.4
action_upper: 132.1
warning_lower: 123.6
action_lower: 121.9

Body:
I've slightly changed the values you provided to make sure the process can spot correctly the pattern you want.

library(dplyr)

# example dataset
df = read.table(text = "
V1  V2
1   195.8
1   128.4
1   129.0
1   121.0
2   125.2
2   127.0
2   125.4
2   114.6
", header=T)

# function to return info based on a value
f = function(x) {
  ifelse(x < 121.9, "below action",
         ifelse(x < 123.6, "below warning",
                ifelse(x > 132.1, "above action",
                       ifelse(x > 130.4, "above warning", "normal"))))
  }

df %>%
  group_by(V1) %>%                      # for each V1
  summarise(MeanValue = mean(V2)) %>%   # calculate means
  mutate(info = f(MeanValue))           # use the function to get relevant info

# # A tibble: 2 x 3
#      V1 MeanValue          info
#   <int>     <dbl>         <chr>
# 1     1    143.55  above action
# 2     2    123.05 below warning


问:
Looping through worksheets and check cell value
I am trying to loop through all sheets and check them one by one and do the following: If in the checked cell the value of E18 = N/A then on the first sheet (named Summary) I'd change the value of G23 to N/A as well (and then do that for each cell, and on Summary change G23 then G24 then G25 and so forth) I wrote the following loop, it runs but it doesn't do anything whatsoever

```<code>Sub MyTestSub()

Dim ws As Worksheet

LastRow = Cells(Rows.Count, "G").End(xlUp).Row
For X = 22 To LastRow
    For Each ws In Worksheets
        If ws.Range("E18").Value="N/A" then ThisWorkbook.Sheets("Summary").Range("G"&x).Value="N/A"
    Next ws
Next x

End Sub
</code>```

Any help would be appreciated!

答:
It needs to be a 2-Step procedure:

Check if IsError in the cell.

Check if the type of error is #N/A, with If .Range("E18").Value = CVErr(xlErrNA) Then.

Otherwise, if you have a regular String, like "Pass" you will get an error.

Code

```<code>Dim lRow As Long

LastRow = Sheets("Summary").Cells(Sheets("Summary").Rows.Count, "G").End(xlUp).Row
lRow = 23 ' start from row 23

For Each ws In Worksheets
    With ws
        If .Name <> "Summary" Then
            If IsError(.Range("E18").Value) Then
                If .Range("E18").Value = CVErr(xlErrNA) Then
                    Sheets("Summary").Range("G" & lRow).Value = CVErr(xlErrNA)
                End If
            End If
        End If
    End With
    lRow = lRow + 1
Next ws
</code>```

Body:
I am trying to loop through all sheets and check them one by one and do the following: If in the checked cell the value of E18 = N/A then on the first sheet (named Summary) I'd change the value of G23 to N/A as well (and then do that for each cell, and on Summary change G23 then G24 then G25 and so forth) I wrote the following loop, it runs but it doesn't do anything whatsoever

Sub MyTestSub()

Dim ws As Worksheet

LastRow = Cells(Rows.Count, "G").End(xlUp).Row
For X = 22 To LastRow
    For Each ws In Worksheets
        If ws.Range("E18").Value="N/A" then ThisWorkbook.Sheets("Summary").Range("G"&x).Value="N/A"
    Next ws
Next x

End Sub

Any help would be appreciated!

Body:
It needs to be a 2-Step procedure:

Check if IsError in the cell.

Check if the type of error is #N/A, with If .Range("E18").Value = CVErr(xlErrNA) Then.

Otherwise, if you have a regular String, like "Pass" you will get an error.

Code

Dim lRow As Long

LastRow = Sheets("Summary").Cells(Sheets("Summary").Rows.Count, "G").End(xlUp).Row
lRow = 23 ' start from row 23

For Each ws In Worksheets
    With ws
        If .Name <> "Summary" Then
            If IsError(.Range("E18").Value) Then
                If .Range("E18").Value = CVErr(xlErrNA) Then
                    Sheets("Summary").Range("G" & lRow).Value = CVErr(xlErrNA)
                End If
            End If
        End If
    End With
    lRow = lRow + 1
Next ws


问:
Is it possible to make this image in CSS?
I was working on something in photoshop. You can see the picture here:

The three triangles in the background refer to 3 different pages on my website. I was wondering if it was possible to put the images like this in CSS because I want them to work like links and put some simple zoom animation on it when you hover on it. I'm actually pretty noob and new to CSS in overall so this will be hard to make without doing a lot of research but I hope you guys can help me out and give me a way to start. Any help is appreciated, thanks a lot!

just to be clear, the 3 triangles should become 3 individual pictures. I'm forced to work with flexbox on school if that matters. Thanks again.

答:
You can play with gradient, shadow and mix-blend-mode , but the best and most efficient is SVG.
example to start with if you feel like spending hours drawing your shapes .

.img {
  float:left;
  background:
    radial-gradient(circle at bottom center, transparent 20%, black 90%),
    linear-gradient( 50deg, rgba(125, 60, 213, 0.7) 32%, transparent 32.5% ),
    linear-gradient(-50deg, rgba(0, 108, 179, 0.7) 32%, transparent 32.5%) #000;
  min-width:400px;
}
.img:before {/* to keep ratio*/
  content:'';
  float:left;
  padding-top:66.66%;
}
.img:after {/* to draw stars spots */
  content:'';
  display:block;
  height:2px;
  width:2px;
  border-radius:50%;
  box-shadow: 50px 10px 1px  white, 55px 11px 1px  white, 45px 12px 1px  white, 40px 25px 1px  white;
}
.moon {
  float:left;
  margin:10% 1%;
  width:9%;
  padding-top:9%;
  box-shadow:0.30em 0.30em 0 0.25em gold ;
  border-radius:50%;
}
.star {
  position:relative;
  float:left;
  width: 2.5%;
  padding-top:1.25%;
  margin:3em;
  transform:rotate(-20deg);
}
.star:before , .star:after{
  content:'';
  position:absolute;
  top:0;
  left:0;
  background:linear-gradient(45deg, rgb(247, 237, 135),gold);
  height:100%;
  width:100%;
  transform:skew(50deg) rotate(10deg)
}
.star:after {
  transform:skew(-50deg) rotate(50deg)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="img">
  <b class="moon"></b>
  <b class="star"></b>
</div></code>```

Body:
You can play with gradient, shadow and mix-blend-mode , but the best and most efficient is SVG.
example to start with if you feel like spending hours drawing your shapes .

.img {
  float:left;
  background:
    radial-gradient(circle at bottom center, transparent 20%, black 90%),
    linear-gradient( 50deg, rgba(125, 60, 213, 0.7) 32%, transparent 32.5% ),
    linear-gradient(-50deg, rgba(0, 108, 179, 0.7) 32%, transparent 32.5%) #000;
  min-width:400px;
}
.img:before {/* to keep ratio*/
  content:'';
  float:left;
  padding-top:66.66%;
}
.img:after {/* to draw stars spots */
  content:'';
  display:block;
  height:2px;
  width:2px;
  border-radius:50%;
  box-shadow: 50px 10px 1px  white, 55px 11px 1px  white, 45px 12px 1px  white, 40px 25px 1px  white;
}
.moon {
  float:left;
  margin:10% 1%;
  width:9%;
  padding-top:9%;
  box-shadow:0.30em 0.30em 0 0.25em gold ;
  border-radius:50%;
}
.star {
  position:relative;
  float:left;
  width: 2.5%;
  padding-top:1.25%;
  margin:3em;
  transform:rotate(-20deg);
}
.star:before , .star:after{
  content:'';
  position:absolute;
  top:0;
  left:0;
  background:linear-gradient(45deg, rgb(247, 237, 135),gold);
  height:100%;
  width:100%;
  transform:skew(50deg) rotate(10deg)
}
.star:after {
  transform:skew(-50deg) rotate(50deg)
}

<div class="img">
  <b class="moon"></b>
  <b class="star"></b>
</div>


问:
Update $scope in an $interval function
I have a login page designed using angular-material. Along with this I also have a password manager chrome extension which works well on many other websites.

What I am trying to achieve is to make the login page compatible with my password manager extension. The extension is provided with the id of the fields, next it fetches the data to be inserted into it and in the last it fills the input with the fetched value. This is done using pure JS like below:

```<code>var inputBox = document.getElementById(fieldId);
if (typeof inputBox !== "undefined" && inputBox !== null) {
    inputBox.click();
    inputBox.focus();
    inputBox.value = fetchedValue;
}
</code>```

However, on the login page, I have a dialog that displays the form fields. The extension is able to find the fields using the id and also able to insert the value. But even after that the form validation error for required condition is shown.

I tried to replicate the behaviour in angular using the below code:

```<code>$scope.user = {
    username: '',
    password: ''
};

$interval(function() {
    var inputBox = document.getElementById("username");
    console.log(inputBox);
    if (typeof inputBox !== "undefined" && inputBox !== null) {
        inputBox.click();
        inputBox.focus();
        inputBox.value = "test";
    }
}, 2000, 1);
</code>```

The username field is bound to $scope.user.username but still upon insertion, the scope is not modified.

Here's the JSFiddle where the issue is replicated: https://jsfiddle.net/prerak6962/fxwmda5w/2/

答:
Why not just:

```<code>$interval(function() {
            var inputBox = document.getElementById("username");
            console.log(inputBox);
            if (typeof inputBox !== "undefined" && inputBox !== null) {
                inputBox.focus();
                $scope.user.username = "test";
            }
        }, 2000, 1);
</code>```

Angular do not watch values in inputs, instead it listen to DOM-events to track changes, when you change element content manually - angular will never know that something changed.

P.S. Angular is PLAIN JS. There is no 'magic'. For example, this strange code will work:

```<code>var user = {
            username: '',
            password: ''
        };
var rootScope;

(function() {
    'use strict';
    angular.module('chipsDemo', [])
        .controller('BasicDemoCtrl', DemoCtrl);

    function DemoCtrl($scope, $rootScope) {
        $scope.user = user;
        rootScope = $rootScope;
    }
})();

setInterval(function() {
  user.password = new Date().getTime();
  rootScope.$apply();
}, 1000);
</code>```

Title: Update $scope in an $interval function

Body:
I have a login page designed using angular-material. Along with this I also have a password manager chrome extension which works well on many other websites.

What I am trying to achieve is to make the login page compatible with my password manager extension. The extension is provided with the id of the fields, next it fetches the data to be inserted into it and in the last it fills the input with the fetched value. This is done using pure JS like below:

var inputBox = document.getElementById(fieldId);
if (typeof inputBox !== "undefined" && inputBox !== null) {
    inputBox.click();
    inputBox.focus();
    inputBox.value = fetchedValue;
}

However, on the login page, I have a dialog that displays the form fields. The extension is able to find the fields using the id and also able to insert the value. But even after that the form validation error for required condition is shown.

I tried to replicate the behaviour in angular using the below code:

$scope.user = {
    username: '',
    password: ''
};

$interval(function() {
    var inputBox = document.getElementById("username");
    console.log(inputBox);
    if (typeof inputBox !== "undefined" && inputBox !== null) {
        inputBox.click();
        inputBox.focus();
        inputBox.value = "test";
    }
}, 2000, 1);

The username field is bound to $scope.user.username but still upon insertion, the scope is not modified.

Here's the JSFiddle where the issue is replicated: https://jsfiddle.net/prerak6962/fxwmda5w/2/

Body:
Why not just:

$interval(function() {
            var inputBox = document.getElementById("username");
            console.log(inputBox);
            if (typeof inputBox !== "undefined" && inputBox !== null) {
                inputBox.focus();
                $scope.user.username = "test";
            }
        }, 2000, 1);

Angular do not watch values in inputs, instead it listen to DOM-events to track changes, when you change element content manually - angular will never know that something changed.

P.S. Angular is PLAIN JS. There is no 'magic'. For example, this strange code will work:

var user = {
            username: '',
            password: ''
        };
var rootScope;

(function() {
    'use strict';
    angular.module('chipsDemo', [])
        .controller('BasicDemoCtrl', DemoCtrl);

    function DemoCtrl($scope, $rootScope) {
        $scope.user = user;
        rootScope = $rootScope;
    }
})();

setInterval(function() {
  user.password = new Date().getTime();
  rootScope.$apply();
}, 1000);


问:
How can I set the focus of a ListBox in XAML?
I have this ListBox:

```<code><ListBox Name="lbColor">
    <ListBoxItem Content="Blue"/>
    <ListBoxItem Content="Red"/>
    <ListBoxItem Content="Orange"/>
</ListBox>
</code>```

This code pre-selects the choice alright, but doesn't set the focus, how can I do that?

```<code>public Window1()
{
    InitializeComponent();

    lbColor.SelectedIndex = 1;
    lbColor.Focus = 1;
}
</code>```

答:
You can use the Focus method:</p>

```<code>public Window1()
{
    InitializeComponent();
    lbColor.SelectedIndex = 1;
    lbColor.Focus();
}
</code>```

OwnerDisplayName: Edward Tanguay

Body:
I have this ListBox:

<ListBox Name="lbColor">
    <ListBoxItem Content="Blue"/>
    <ListBoxItem Content="Red"/>
    <ListBoxItem Content="Orange"/>
</ListBox>

This code pre-selects the choice alright, but doesn't set the focus, how can I do that?

public Window1()
{
    InitializeComponent();

    lbColor.SelectedIndex = 1;
    lbColor.Focus = 1;
}

Body:
You can use the Focus method:

public Window1()
{
    InitializeComponent();
    lbColor.SelectedIndex = 1;
    lbColor.Focus();
}

OwnerDisplayName: darin


问:
SELECTing Related Rows Based on a Single Row Match
I have the following table running on Postgres SQL 9.5:

```<code>+---+------------+-------------+
|ID |  trans_id  |   message   |
+---+------------+-------------+
| 1 | 1234567    | abc123-ef   |
| 2 | 1234567    | def234-gh   |
| 3 | 1234567    | ghi567-ij   |
| 4 | 8902345    | ced123-ef   |
| 5 | 8902345    | def234-bz   |
| 6 | 8902345    | ghi567-ij   |
| 7 | 6789012    | abc123-ab   |
| 8 | 6789012    | def234-cd   |
| 9 | 6789012    | ghi567-ef   |
|10 | 4567890    | abc123-ab   |
|11 | 4567890    | gex890-aj   |
|12 | 4567890    | ghi567-ef   |
+---+------------+-------------+
</code>```

I am looking for the rows for each trans_id based on a LIKE query, like this:

```<code>SELECT * FROM table
WHERE message LIKE '%def-234%'
</code>```

This, of course, returns just three rows, the three that match my pattern in the message column. What I am looking for, instead, is all the rows matching that trans_id in groups of messages that match. That is, if a single row matches the pattern, get all the rows with the trans_id of that matching row.

That is, the results would be:

```<code>+---+------------+-------------+
|ID |  trans_id  |   message   |
+---+------------+-------------+
| 1 | 1234567    | abc123-ef   |
| 2 | 1234567    | def234-gh   |
| 3 | 1234567    | ghi567-ij   |
| 4 | 8902345    | ced123-ef   |
| 5 | 8902345    | def234-bz   |
| 6 | 8902345    | ghi567-ij   |
| 7 | 6789012    | abc123-ab   |
| 8 | 6789012    | def234-cd   |
| 9 | 6789012    | ghi567-ef   |
+---+------------+-------------+
</code>```

Notice rows 10, 11, and 12 were not SELECTed because there was not one of them that matched the %def-234% pattern.

I have tried (and failed) to write a sub-query to get the all the related rows when a single message matches a pattern:

```<code>SELECT sub.*
    FROM (
        SELECT DISTINCT trans_id FROM table WHERE message LIKE '%def-234%'
    ) sub
WHERE table.trans_id = sub.trans_id
</code>```

I could easily do this with two queries, but the first query to get a list of matching trans_ids to include in a WHERE trans_id IN (<huge list of trans_ids>) clause would be very large, and would not be a very inefficient way of doing this, and I believe there exists a way to do it with a single query.

Thank you!

答:
You can do this.

```<code>WITH trans
AS
(SELECT DISTINCT trans_id
   FROM t1
  WHERE message LIKE '%def234%')
SELECT t1.*
 FROM t1,
      trans
WHERE t1.trans_id = trans.trans_id;
</code>```

I think this will perform better. If you have enough data, you can do an explain on both Sub query and CTE and compare the output.

Body:
I have the following table running on Postgres SQL 9.5:

+---+------------+-------------+
|ID |  trans_id  |   message   |
+---+------------+-------------+
| 1 | 1234567    | abc123-ef   |
| 2 | 1234567    | def234-gh   |
| 3 | 1234567    | ghi567-ij   |
| 4 | 8902345    | ced123-ef   |
| 5 | 8902345    | def234-bz   |
| 6 | 8902345    | ghi567-ij   |
| 7 | 6789012    | abc123-ab   |
| 8 | 6789012    | def234-cd   |
| 9 | 6789012    | ghi567-ef   |
|10 | 4567890    | abc123-ab   |
|11 | 4567890    | gex890-aj   |
|12 | 4567890    | ghi567-ef   |
+---+------------+-------------+

I am looking for the rows for each trans_id based on a LIKE query, like this:

SELECT * FROM table
WHERE message LIKE '%def-234%'

This, of course, returns just three rows, the three that match my pattern in the message column. What I am looking for, instead, is all the rows matching that trans_id in groups of messages that match. That is, if a single row matches the pattern, get all the rows with the trans_id of that matching row.

That is, the results would be:

+---+------------+-------------+
|ID |  trans_id  |   message   |
+---+------------+-------------+
| 1 | 1234567    | abc123-ef   |
| 2 | 1234567    | def234-gh   |
| 3 | 1234567    | ghi567-ij   |
| 4 | 8902345    | ced123-ef   |
| 5 | 8902345    | def234-bz   |
| 6 | 8902345    | ghi567-ij   |
| 7 | 6789012    | abc123-ab   |
| 8 | 6789012    | def234-cd   |
| 9 | 6789012    | ghi567-ef   |
+---+------------+-------------+

Notice rows 10, 11, and 12 were not SELECTed because there was not one of them that matched the %def-234% pattern.

I have tried (and failed) to write a sub-query to get the all the related rows when a single message matches a pattern:

SELECT sub.*
    FROM (
        SELECT DISTINCT trans_id FROM table WHERE message LIKE '%def-234%'
    ) sub
WHERE table.trans_id = sub.trans_id

I could easily do this with two queries, but the first query to get a list of matching trans_ids to include in a WHERE trans_id IN (<huge list of trans_ids>) clause would be very large, and would not be a very inefficient way of doing this, and I believe there exists a way to do it with a single query.

Thank you!

Body:
You can do this.

WITH trans
AS
(SELECT DISTINCT trans_id
   FROM t1
  WHERE message LIKE '%def234%')
SELECT t1.*
 FROM t1,
      trans
WHERE t1.trans_id = trans.trans_id;

I think this will perform better. If you have enough data, you can do an explain on both Sub query and CTE and compare the output.


问:
ReferenceError : By is not defined - webdriverIO
Code :

```<code>var assert = require('assert');
describe('webdriver.io api page', function() {
    it('should open login page', function () {
        browser.url('/login');
        browser.pause(10000);
})

it('Should enter login details and submit', function() {

    browser.pause(10000);
    browser.element(By.xpath("//input[@type='text' and @aria-label='user name']")).sendKeys("mikestr");

})
});
</code>```

I am new to webdriverIO and trying to locate username textbox using xpath but it throws me error. I look around many webdriverIO material but did not get solution for this yet.

答:
The locator has to be a string

For setting value , you can use setValue

```<code>browser.setValue("//input[@type='text' and @aria-label='user name']", 'mikestr');
</code>```

Body:
Code :

var assert = require('assert');
describe('webdriver.io api page', function() {
    it('should open login page', function () {
        browser.url('/login');
        browser.pause(10000);
})

it('Should enter login details and submit', function() {

    browser.pause(10000);
    browser.element(By.xpath("//input[@type='text' and @aria-label='user name']")).sendKeys("mikestr");

})
});

I am new to webdriverIO and trying to locate username textbox using xpath but it throws me error. I look around many webdriverIO material but did not get solution for this yet.

Body:
The locator has to be a string

For setting value , you can use setValue

browser.setValue("//input[@type='text' and @aria-label='user name']", 'mikestr');


问:
How to move an object similar to sinusoidal wave movement?-LibGdx
I want to move my object vertically in zig-zag motion,similar to sisnusoidal motion;

I am moving my object like this:

```<code>public void moveLeavesDown(float delta) {

    setY(getY() - (getSpeed()* delta));

}
</code>```

How can I get this kind of movement?

答:
You can add a timer and use the math.sin function to add an offset to your leaves.

This demo below shows how it can be done:

```<code>import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;

public class Test extends ApplicationAdapter{

    float time =0; // timer to store current elapsed time
    Vector2 leaf = new Vector2(150,150); // holds the leaf x,y pos
    float sinOffset = 0; // the offset for adding to the image
    private SpriteBatch sb; // spritebatch for rendering
    TextureRegion tx;  // a texture region(the leaf)

    @Override
    public void create() {
        sb = new SpriteBatch(); // make spritebatch
        tx = DFUtils.makeTextureRegion(10, 10, "FFFFFF"); // makes a textureRegion of 10x10 of pure white

    }

    @Override
    public void render() {
        // clear screen
        Gdx.gl.glClearColor(0f, 0f, 0f, 0f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        leaf.y = leaf.y-0.2f; // move downwards
        time+= Gdx.graphics.getDeltaTime(); // update sin timer
        sinOffset =(float)Math.sin(time)*10; // calculate offset

        // draw leaf with offset
        sb.begin();
        sb.draw(tx, leaf.x+sinOffset, leaf.y);
        sb.end();

    }
}
</code>```

Body:
I want to move my object vertically in zig-zag motion,similar to sisnusoidal motion;

I am moving my object like this:

public void moveLeavesDown(float delta) {

    setY(getY() - (getSpeed()* delta));

}

How can I get this kind of movement?

Body:
You can add a timer and use the math.sin function to add an offset to your leaves.

This demo below shows how it can be done:

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;

public class Test extends ApplicationAdapter{

    float time =0; // timer to store current elapsed time
    Vector2 leaf = new Vector2(150,150); // holds the leaf x,y pos
    float sinOffset = 0; // the offset for adding to the image
    private SpriteBatch sb; // spritebatch for rendering
    TextureRegion tx;  // a texture region(the leaf)

    @Override
    public void create() {
        sb = new SpriteBatch(); // make spritebatch
        tx = DFUtils.makeTextureRegion(10, 10, "FFFFFF"); // makes a textureRegion of 10x10 of pure white

    }

    @Override
    public void render() {
        // clear screen
        Gdx.gl.glClearColor(0f, 0f, 0f, 0f);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        leaf.y = leaf.y-0.2f; // move downwards
        time+= Gdx.graphics.getDeltaTime(); // update sin timer
        sinOffset =(float)Math.sin(time)*10; // calculate offset

        // draw leaf with offset
        sb.begin();
        sb.draw(tx, leaf.x+sinOffset, leaf.y);
        sb.end();

    }
}