问:
I dont know what is wrong with my django
I dont know what is wrong, and I am desperates with no sleep int two days because of this error. I dont know where does it come from, and it wouldn let me know what did i do wrong. for your information I am learning using django with python, my version of django is 1.11 and my version of python is 2.7 . Please help me, this is what i got from my code

```<code>Traceback (most recent call last):
  File "./manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/commands/check.py", line 68, in handle
    fail_level=getattr(checks, options['fail_level']),
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 28, in check_resolver
    warnings.extend(check_resolver(pattern))
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 30, in check_resolver
    warnings.extend(check_pattern_name(pattern))
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 120, in check_pattern_name
    if pattern.name is not None and ":" in pattern.name:
TypeError: argument of type 'function' is not iterable
</code>```

See? it would not let me know where is my fault is.

答:
The error suggests that you have forgotten quotes when naming a URL pattern.

For example you have name=my_view,

```<code>url('^my-url/$', my_view, name=my_view)
</code>```

when you should use a string name='my_view':

```<code>url('^my-url/$', my_view, name='my_view')
</code>```

Body:
I dont know what is wrong, and I am desperates with no sleep int two days because of this error. I dont know where does it come from, and it wouldn let me know what did i do wrong. for your information I am learning using django with python, my version of django is 1.11 and my version of python is 2.7 . Please help me, this is what i got from my code

Traceback (most recent call last):
  File "./manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute
    output = self.handle(*args, **options)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/commands/check.py", line 68, in handle
    fail_level=getattr(checks, options['fail_level']),
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 374, in check
    include_deployment_checks=include_deployment_checks,
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/management/base.py", line 361, in _run_checks
    return checks.run_checks(**kwargs)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/registry.py", line 81, in run_checks
    new_errors = check(app_configs=app_configs)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 14, in check_url_config
    return check_resolver(resolver)
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 28, in check_resolver
    warnings.extend(check_resolver(pattern))
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 30, in check_resolver
    warnings.extend(check_pattern_name(pattern))
  File "/home/juunnn/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 120, in check_pattern_name
    if pattern.name is not None and ":" in pattern.name:
TypeError: argument of type 'function' is not iterable

See? it would not let me know where is my fault is.

Body:
The error suggests that you have forgotten quotes when naming a URL pattern.

For example you have name=my_view,

url('^my-url/$', my_view, name=my_view)

when you should use a string name='my_view':

url('^my-url/$', my_view, name='my_view')


来源: stackexchange

问:
Using xpath containing whitespace
```<code>List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id=\"tabela\"]/tbody/tr/td[5][contains(text(),"+situacao+")]"));
</code>```

<p>how to use normalize-space in my case? "situacao" has white spaces </p>

答:
There's no need to handle this with XPath. You can just .trim() the string.

```<code>List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id='tabela']/tbody/tr/td[5][contains(text(),'" + situacao.trim() + "')]"));
</code>```

I would also use ' inside the XPath instead of escaping the double quotes \". I think it makes it easier to read.

ContentLicense: CC BY-SA 3.0

Title: Using xpath containing whitespace

Body:
List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id=\"tabela\"]/tbody/tr/td[5][contains(text(),"+situacao+")]"));

how to use normalize-space in my case? "situacao" has white spaces

Body:
There's no need to handle this with XPath. You can just .trim() the string.

List <WebElement> tableSituacao = driver.findElements(By.xpath("//*[@id='tabela']/tbody/tr/td[5][contains(text(),'" + situacao.trim() + "')]"));

I would also use ' inside the XPath instead of escaping the double quotes \". I think it makes it easier to read.


问:
SQL Server developing Random Points inside of a Zip code off of a center point
I am trying to get SQL Server to generate random points for each Zip code, for each LocationID. So I have added the center point for each Zip code, and would like to distribute these points around the center point. For each locationID I would like a point. Here is what my table looks like currently.

Table name= Location

```<code>LocationName; varchar
locationID; int
ZIP: int
CentroidLat;float
CentroidLng;float
</code>```

Sample data:

```<code>LocationName         LocationID      Zip      CentriodLat    CentroidLNG
-------------------------------------------------------------------------
    JV                    1         99999      38.999999      - 93.999999
    JV                    2         99999      38.999999      - 93.999999
    AA                    1         11111      37.999999      - 94.999999
    AA                    2         11111      37.999999      - 94.999999
    AA                    3         11111      37.999999      - 94.999999
    BB                    1         22222      36.999999      - 95.999999
    BB                    2         22222      36.999999      - 95.999999
</code>```

So for each zip's LocationId I would like a random lat long within the Zip Code. I could get this in a square or circle that would work fine. It does not need to be too exact. Also each Zip Code is going to be a different size so if there could be a variable that i could change manually in the code that would be great!

This is what I would like it to look like

```<code>`LocationName    LocationID    Zip    CentroidLat      Centroid      RandLat   RandLNG`

    JV              1        99999      38.999999    - 93.999999    -93.7436  -94.0124
    JV              2        99999      38.999999    - 93.999999    -93.9653  -94.0052
    AA              1        11111      37.999999    - 94.999999    110.9636  -95.7219
    AA              2        11111      37.999999    - 94.999999    102.6538  -95.7489
    AA              3        11111      37.999999    - 94.999999    101.9887  -96.0089
    BB              1        22222      36.999999    - 95.999999    137.5311  -97.9698
    BB              2        22222      36.999999    - 95.999999    46.7497   -96.9266
</code>```

Is this possible?

I found this... SQL Server generating random spatial geography around point?
but cannot get it to work.

I keep getting this error:

Msg 116, Level 16, State 1, Line 18

  Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

Errors happen when I try and insert my table name and column into the top of the code.

Thank you in advance!

答:
The error you are getting is a generic SQL error which has nothing to do with spatial/geographic objects. In the code referenced by your link, I've created a table variable to hold some sample values and set it up so that multiple values will be returned for the zip code 98765. Running the code, you will get the error you describe:

```<code>DECLARE @geo      AS GEOGRAPHY
        , @newgeo AS GEOGRAPHY
DECLARE @ZipCodes AS TABLE
  (
       [ZipGeo]    GEOGRAPHY
       , [ZipCode] SYSNAME
  );

INSERT INTO @ZipCodes
            ([ZipGeo]
             , [ZipCode])
VALUES      (geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656 )', 4326),N'98765'),
            (geography::STGeomFromText('POLYGON((-122.358 47.653 , -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326),N'98765');

SET @geo = (SELECT [ZipGeo]
            FROM   @ZipCodes
            WHERE  [ZipCode] = '98765')
</code>```

The way to address this is either to "SELECT TOP(1) .... ORDER BY ..." as below, but the ORDER BY is really not used here and you can't sort by the GEOGRAPHY type.

```<code>DECLARE @geo      AS GEOGRAPHY
        , @newgeo AS GEOGRAPHY
DECLARE @ZipCodes AS TABLE
  (
       [ZipGeo]    GEOGRAPHY
       , [ZipCode] SYSNAME
  );

INSERT INTO @ZipCodes
            ([ZipGeo]
             , [ZipCode])
VALUES      (geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656 )', 4326),N'98765'),
            (geography::STGeomFromText('POLYGON((-122.358 47.653 , -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326),N'98765');

SET @geo = (SELECT TOP(1) [ZipGeo]
            FROM   @ZipCodes
            WHERE  [ZipCode] = '98765'
            ORDER  BY [ZipCode])
</code>```

Alternately you can do this, but this is really bad practice.

```<code>DECLARE @geo      AS GEOGRAPHY
        , @newgeo AS GEOGRAPHY
DECLARE @ZipCodes AS TABLE
  (
       [ZipGeo]    GEOGRAPHY
       , [ZipCode] SYSNAME
  );

INSERT INTO @ZipCodes
            ([ZipGeo]
             , [ZipCode])
VALUES      (geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656 )', 4326),N'98765'),
            (geography::STGeomFromText('POLYGON((-122.358 47.653 , -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326),N'98765');

SELECT @geo = [ZipGeo]
FROM   @ZipCodes
WHERE  [ZipCode] = '98765';
</code>```

It is preferable to have a column you can order by and return just the top(1) for the set. That way your SQL statement is deterministic. Since SQL does NOT guarantee an order, you have to order your results to guarantee a return.

Regardless, this is the cause of the error you are seeing. There are several ways to address it. This is a common error I see in production code where people assume the data will always be "good" and will return only one value. Then, when the data returns multiple values (as in your case or my example) the code fails and people wonder why.

The best practice is to write the code defensively and decoratively such that you state exactly what you desire to get.

Body:
I am trying to get SQL Server to generate random points for each Zip code, for each LocationID. So I have added the center point for each Zip code, and would like to distribute these points around the center point. For each locationID I would like a point. Here is what my table looks like currently.

Table name= Location

LocationName; varchar
locationID; int
ZIP: int
CentroidLat;float
CentroidLng;float

Sample data:

LocationName         LocationID      Zip      CentriodLat    CentroidLNG
-------------------------------------------------------------------------
    JV                    1         99999      38.999999      - 93.999999
    JV                    2         99999      38.999999      - 93.999999
    AA                    1         11111      37.999999      - 94.999999
    AA                    2         11111      37.999999      - 94.999999
    AA                    3         11111      37.999999      - 94.999999
    BB                    1         22222      36.999999      - 95.999999
    BB                    2         22222      36.999999      - 95.999999

So for each zip's LocationId I would like a random lat long within the Zip Code. I could get this in a square or circle that would work fine. It does not need to be too exact. Also each Zip Code is going to be a different size so if there could be a variable that i could change manually in the code that would be great!

This is what I would like it to look like

`LocationName    LocationID    Zip    CentroidLat      Centroid      RandLat   RandLNG`

    JV              1        99999      38.999999    - 93.999999    -93.7436  -94.0124
    JV              2        99999      38.999999    - 93.999999    -93.9653  -94.0052
    AA              1        11111      37.999999    - 94.999999    110.9636  -95.7219
    AA              2        11111      37.999999    - 94.999999    102.6538  -95.7489
    AA              3        11111      37.999999    - 94.999999    101.9887  -96.0089
    BB              1        22222      36.999999    - 95.999999    137.5311  -97.9698
    BB              2        22222      36.999999    - 95.999999    46.7497   -96.9266

Is this possible?

I found this... SQL Server generating random spatial geography around point?
but cannot get it to work.

I keep getting this error:

Msg 116, Level 16, State 1, Line 18

  Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

Errors happen when I try and insert my table name and column into the top of the code.

Thank you in advance!

Body:
The error you are getting is a generic SQL error which has nothing to do with spatial/geographic objects. In the code referenced by your link, I've created a table variable to hold some sample values and set it up so that multiple values will be returned for the zip code 98765. Running the code, you will get the error you describe:

DECLARE @geo      AS GEOGRAPHY
        , @newgeo AS GEOGRAPHY
DECLARE @ZipCodes AS TABLE
  (
       [ZipGeo]    GEOGRAPHY
       , [ZipCode] SYSNAME
  );

INSERT INTO @ZipCodes
            ([ZipGeo]
             , [ZipCode])
VALUES      (geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656 )', 4326),N'98765'),
            (geography::STGeomFromText('POLYGON((-122.358 47.653 , -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326),N'98765');

SET @geo = (SELECT [ZipGeo]
            FROM   @ZipCodes
            WHERE  [ZipCode] = '98765')

The way to address this is either to "SELECT TOP(1) .... ORDER BY ..." as below, but the ORDER BY is really not used here and you can't sort by the GEOGRAPHY type.

DECLARE @geo      AS GEOGRAPHY
        , @newgeo AS GEOGRAPHY
DECLARE @ZipCodes AS TABLE
  (
       [ZipGeo]    GEOGRAPHY
       , [ZipCode] SYSNAME
  );

INSERT INTO @ZipCodes
            ([ZipGeo]
             , [ZipCode])
VALUES      (geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656 )', 4326),N'98765'),
            (geography::STGeomFromText('POLYGON((-122.358 47.653 , -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326),N'98765');

SET @geo = (SELECT TOP(1) [ZipGeo]
            FROM   @ZipCodes
            WHERE  [ZipCode] = '98765'
            ORDER  BY [ZipCode])

Alternately you can do this, but this is really bad practice.

DECLARE @geo      AS GEOGRAPHY
        , @newgeo AS GEOGRAPHY
DECLARE @ZipCodes AS TABLE
  (
       [ZipGeo]    GEOGRAPHY
       , [ZipCode] SYSNAME
  );

INSERT INTO @ZipCodes
            ([ZipGeo]
             , [ZipCode])
VALUES      (geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656 )', 4326),N'98765'),
            (geography::STGeomFromText('POLYGON((-122.358 47.653 , -122.348 47.649, -122.348 47.658, -122.358 47.658, -122.358 47.653))', 4326),N'98765');

SELECT @geo = [ZipGeo]
FROM   @ZipCodes
WHERE  [ZipCode] = '98765';

It is preferable to have a column you can order by and return just the top(1) for the set. That way your SQL statement is deterministic. Since SQL does NOT guarantee an order, you have to order your results to guarantee a return.

Regardless, this is the cause of the error you are seeing. There are several ways to address it. This is a common error I see in production code where people assume the data will always be "good" and will return only one value. Then, when the data returns multiple values (as in your case or my example) the code fails and people wonder why.

The best practice is to write the code defensively and decoratively such that you state exactly what you desire to get.


问:
React: How to pass width as a prop from the component
I am trying to create a component, whose width can be specified wherever the component can be used

Like:

```<code><Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
`;

var React = require('react');

var Button = React.createClass({

render: function () {

return (
  <TestButton>{this.props.label}</TestButton>
);
}
});

module.exports = Button;
</code>```

how can I achieve this?

答:
If you're using styled-components you can pass the width prop to the component and set its width:

```<code><Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
  width: ${(props) => props.width}
`;

var React = require('react');

var Button = React.createClass({

  render: function () {

    return (
      <TestButton width={this.props.width}>{this.props.label}</TestButton>
     );
    }
  });

module.exports = Button;
</code>```

Body:
I am trying to create a component, whose width can be specified wherever the component can be used

Like:

<Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
`;

var React = require('react');

var Button = React.createClass({

render: function () {

return (
  <TestButton>{this.props.label}</TestButton>
);
}
});

module.exports = Button;

how can I achieve this?

Body:
If you're using styled-components you can pass the width prop to the component and set its width:

<Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
  width: ${(props) => props.width}
`;

var React = require('react');

var Button = React.createClass({

  render: function () {

    return (
      <TestButton width={this.props.width}>{this.props.label}</TestButton>
     );
    }
  });

module.exports = Button;


问:
Limit access to web api 2 controller in dotnet core mvc project
what is the best way to limit access to a webapi 2 controller within a MVC project to only the hosted App Service?

I have created a endpoint which my MVC client is accessing. The entire application is published to azure through an app service. How can I now protect the endpoint from being called outside of the application context?

答:
Based on your comments you should consider restructuring your solution.

Consider moving your Web API to an independent project. This way your API is decoupled from your MVC app and you can deploy and scale it,if required, independently.

Move the MVC client app in it's own independent project

For authentication I would consider implementing an authorization server (again in an independent project) that issues tokens to the client (in your case the MVC app) and the client would then access the API using this token. For implementing an auth server you have a couple of options

Use the ClientCredentials grant using IdentityServer4

Use the OWIN OAuth middleware to implement your auth server with ClientCredentials grant

There are other Oauth implementations that you could use too.

Having a dedicated authorization server clearly separates out the identity responsibility allowing you to control access for other future clients and possibly restrict access to only certain endpoints (aka scopes).


问:
VBA/SQL: Nested Query, Baffling Data Mismatch
The basic idea: I want a list of all of the processes that exist within a certain division. Processes are related to OperationalUnits, which are related to Divisions.

The query I want:

SELECT ID, ProcessName FROM Processes WHERE Unit IN (SELECT ID FROM OperationalUnits WHERE Division='1');

This always throws me a "type mismatch in expression" error.

I've tested by breaking the query down into the two component queries:

SELECT ID FROM OperationalUnits WHERE Division='1';

This returns a single ID, 2, which is what I expect from my test data.

SELECT ID, ProcessName FROM Processes WHERE Unit IN ('2');

This returns a single process, which is again exactly what I expect.

But if I combine them back together into the main query? Nope. It appears that the issue is that the inside query returns [2], while the outside query only works if it returns ['2'], but that doesn't seem like it can be right to me. Any help is appreciated!

答:
Access doesn't automatically cast types, unless in specific situations. As discussed in the comments, since your fields have different types, you can do two things: cast using a function, or change the type.

To cast, you can use the following:

```<code>SELECT ID, ProcessName FROM Processes WHERE Unit IN (SELECT CStr(ID) FROM OperationalUnits WHERE Division='1');
</code>```

Body:
Access doesn't automatically cast types, unless in specific situations. As discussed in the comments, since your fields have different types, you can do two things: cast using a function, or change the type.

To cast, you can use the following:

SELECT ID, ProcessName FROM Processes WHERE Unit IN (SELECT CStr(ID) FROM OperationalUnits WHERE Division='1');


问:
how to parse json to get lodash score from a url?
I'm trying to find out how to parse the url and put the names in an array and then to parse the json to get the lodash score and convert the score to a whole number. any help would be nice. </p>

<p>
    </p>

```<code><head>
    <title> final</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
</head>

<body>
    <h3>The window.location object</h3>

<input type="button" value="Load new document" onclick="newDoc()">

<script>
function newDoc() {
    window.location.assign("https://api.npms.io/v2/package/lodash");
}

</script>
    <!--// JSON.parse(");-->
    <!--// displayfromJSON(lodash);-->
    <!--//     window.substring(0.9200443085079093);-->
    <!--// split(92)-->
</body>

</html>
</code>```

答:
When you change the location to that url your page no longer exists...and neither does any of your script

Use fetch() to get the data and then do what you want with it.

fetch('https://api.npms.io/v2/package/lodash')
    .then(res => res.json())
    .then(data => console.log(data.score))```

Body:
I'm trying to find out how to parse the url and put the names in an array and then to parse the json to get the lodash score and convert the score to a whole number. any help would be nice.

    <title> final</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

The window.location object

<input type="button" value="Load new document" onclick="newDoc()">


问:
consuming webservice with asp.net and C#
I am learning asp.net, and trying to understand in consuming a webservice. I am using the following wsdl file

http://www.webservicex.net/uszip.asmx?WSDL

I am using a textbox to enter the zipcode, added the wsdl in the web reference , and am using C# to retrieve data. The structure of the data is as follows:

http://www.webservicex.net/uszip.asmx/GetInfoByZIP

I am not able to understand on how to display the results  on a webpage. The following code is what I have until now..

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    USZip s1 = new USZip();
    var input = zipcode.Text.ToString();
    String result = s1.GetInfoByZIP(input);

}
</code>```

It would be great if anyone can give me helpful pointers

Thanks a lot

答:
Hover over the call to GetInfoByZIP and you should see that it returns an XmlNode. Since there is no implicit conversion from an XmlNode to a string, then you should not be able to assign the result directly to a string. To get the string value, call the XmlNode property OuterXml, like so (make sure you have a multi-line text control):

```<code>XmlNode result = s1.GetInfoByZIP(input);
YourTextControl.Text = result.OuterXml;
</code>```

Per the WSDL, the call returns a GetInfoByZipResult, which can contain any XML (with no further specification in the WSDL). The XML I get looks like the XML below. So, if you want to get to the name of the City, State, etc., you will need to parse the XML.

```<code><NewDataSet xmlns="">
  <Table>
    <CITY>Glendale</CITY>
    <STATE>CA</STATE>
    <ZIP>91210</ZIP>
    <AREA_CODE>818</AREA_CODE>
    <TIME_ZONE>P</TIME_ZONE>
  </Table>
</NewDataSet>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am learning asp.net, and trying to understand in consuming a webservice. I am using the following wsdl file

http://www.webservicex.net/uszip.asmx?WSDL

I am using a textbox to enter the zipcode, added the wsdl in the web reference , and am using C# to retrieve data. The structure of the data is as follows:

http://www.webservicex.net/uszip.asmx/GetInfoByZIP

I am not able to understand on how to display the results  on a webpage. The following code is what I have until now..

protected void Button1_Click(object sender, EventArgs e)
{
    USZip s1 = new USZip();
    var input = zipcode.Text.ToString();
    String result = s1.GetInfoByZIP(input);

}

It would be great if anyone can give me helpful pointers

Thanks a lot

Body:
Hover over the call to GetInfoByZIP and you should see that it returns an XmlNode. Since there is no implicit conversion from an XmlNode to a string, then you should not be able to assign the result directly to a string. To get the string value, call the XmlNode property OuterXml, like so (make sure you have a multi-line text control):

XmlNode result = s1.GetInfoByZIP(input);
YourTextControl.Text = result.OuterXml;

Per the WSDL, the call returns a GetInfoByZipResult, which can contain any XML (with no further specification in the WSDL). The XML I get looks like the XML below. So, if you want to get to the name of the City, State, etc., you will need to parse the XML.

<NewDataSet xmlns="">
  <Table>
    <CITY>Glendale</CITY>
    <STATE>CA</STATE>
    <ZIP>91210</ZIP>
    <AREA_CODE>818</AREA_CODE>
    <TIME_ZONE>P</TIME_ZONE>
  </Table>
</NewDataSet>


问:
AWS ECS tasks keep starting and stopping
I am trying to use ECS for deployment with travis.
At one point everything was working but now it stopped.

I am following this tutorial https://testdriven.io/part-five-ec2-container-service/

There are 2 tasks that keep stopping and starting.

These are the messages I see in tasks:

```<code>STOPPED (CannotStartContainerError: API error (500): oci ru)

STOPPED (Essential container in task exited)
</code>```

These are the messages I see in the logs:

```<code>FATAL: could not write to file "pg_wal/xlogtemp.28": No space left on device

container_linux.go:262: starting container process caused "exec: \"./entrypoint.sh\": permission denied"
</code>```

Why is ECS stopping and starting so many new tasks? This was not happening before.

This is my docker_deploy.sh from my main microservice which I am calling via travis.

```<code>#!/bin/sh

if [ -z "$TRAVIS_PULL_REQUEST" ] || [ "$TRAVIS_PULL_REQUEST" == "false" ];
then

    if [ "$TRAVIS_BRANCH" == "staging" ];
    then
        JQ="jq --raw-output --exit-status"

        configure_aws_cli() {
            aws --version
            aws configure set default.region us-east-1
            aws configure set default.output json
            echo "AWS Configured!"
        }

        make_task_def() {
            task_template=$(cat ecs_taskdefinition.json)
            task_def=$(printf "$task_template" $AWS_ACCOUNT_ID $AWS_ACCOUNT_ID)
            echo "$task_def"
        }

        register_definition() {
            if revision=$(aws ecs register-task-definition --cli-input-json "$task_def" --family $family | $JQ '.taskDefinition.taskDefinitionArn');
            then
                echo "Revision: $revision"
            else
                echo "Failed to register task definition"
                return 1
            fi
        }

        deploy_cluster() {

            family="testdriven-staging"
            cluster="ezasdf-staging"
            service="ezasdf-staging"

            make_task_def
            register_definition

            if [[ $(aws ecs update-service --cluster $cluster --service $service --task-definition $revision | $JQ '.service.taskDefinition') != $revision ]];
            then
                echo "Error updating service."
                return 1
            fi

        }

        configure_aws_cli
        deploy_cluster

    fi
fi
</code>```

This is my Dockerfile from my users microservice:

```<code>FROM python:3.6.2

# install environment dependencies
RUN apt-get update -yqq \
    && apt-get install -yqq --no-install-recommends \
        netcat \
    && apt-get -q clean

# set working directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# add requirements (to leverage Docker cache)
ADD ./requirements.txt /usr/src/app/requirements.txt

# install requirements
RUN pip install -r requirements.txt

# add entrypoint.sh
ADD ./entrypoint.sh /usr/src/app/entrypoint.sh
RUN chmod +x /usr/src/app/entrypoint.sh

# add app
ADD . /usr/src/app

# run server
CMD ["./entrypoint.sh"]
</code>```

entrypoint.sh:

```<code>#!/bin/sh

echo "Waiting for postgres..."

while ! nc -z users-db 5432;
do
    sleep 0.1
done

echo "PostgreSQL started"

python manage.py recreate_db
python manage.py seed_db
gunicorn -b 0.0.0.0:5000 manage:app
</code>```

I tried deleting my cluster and deregistering my tasks and restarting but ECS still continuously stops and starts new tasks now.

When it was working fine: the difference was that instead of the CMD ["./entrypoint.sh"] in my Dockerfile, I had

```<code>RUN python manage.py recreate_db
RUN python manage.py seed_db
CMD gunicorn -b 0.0.0.0:5000 manage:app
</code>```

travis is passing.

答:
If it's too many tasks running and they have consumed the space then you will need to shell in to the host and do the following. Don't use -f on the docker rm as that will remove the running ECS agent container

```<code>docker rm $(docker ps -aq)
</code>```

Body:
I am trying to use ECS for deployment with travis.
At one point everything was working but now it stopped.

I am following this tutorial https://testdriven.io/part-five-ec2-container-service/

There are 2 tasks that keep stopping and starting.

These are the messages I see in tasks:

STOPPED (CannotStartContainerError: API error (500): oci ru)

STOPPED (Essential container in task exited)

These are the messages I see in the logs:

FATAL: could not write to file "pg_wal/xlogtemp.28": No space left on device

container_linux.go:262: starting container process caused "exec: \"./entrypoint.sh\": permission denied"

Why is ECS stopping and starting so many new tasks? This was not happening before.

This is my docker_deploy.sh from my main microservice which I am calling via travis.

#!/bin/sh

if [ -z "$TRAVIS_PULL_REQUEST" ] || [ "$TRAVIS_PULL_REQUEST" == "false" ];
then

    if [ "$TRAVIS_BRANCH" == "staging" ];
    then
        JQ="jq --raw-output --exit-status"

        configure_aws_cli() {
            aws --version
            aws configure set default.region us-east-1
            aws configure set default.output json
            echo "AWS Configured!"
        }

        make_task_def() {
            task_template=$(cat ecs_taskdefinition.json)
            task_def=$(printf "$task_template" $AWS_ACCOUNT_ID $AWS_ACCOUNT_ID)
            echo "$task_def"
        }

        register_definition() {
            if revision=$(aws ecs register-task-definition --cli-input-json "$task_def" --family $family | $JQ '.taskDefinition.taskDefinitionArn');
            then
                echo "Revision: $revision"
            else
                echo "Failed to register task definition"
                return 1
            fi
        }

        deploy_cluster() {

            family="testdriven-staging"
            cluster="ezasdf-staging"
            service="ezasdf-staging"

            make_task_def
            register_definition

            if [[ $(aws ecs update-service --cluster $cluster --service $service --task-definition $revision | $JQ '.service.taskDefinition') != $revision ]];
            then
                echo "Error updating service."
                return 1
            fi

        }

        configure_aws_cli
        deploy_cluster

    fi
fi

This is my Dockerfile from my users microservice:

FROM python:3.6.2

# install environment dependencies
RUN apt-get update -yqq \
    && apt-get install -yqq --no-install-recommends \
        netcat \
    && apt-get -q clean

# set working directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# add requirements (to leverage Docker cache)
ADD ./requirements.txt /usr/src/app/requirements.txt

# install requirements
RUN pip install -r requirements.txt

# add entrypoint.sh
ADD ./entrypoint.sh /usr/src/app/entrypoint.sh
RUN chmod +x /usr/src/app/entrypoint.sh

# add app
ADD . /usr/src/app

# run server
CMD ["./entrypoint.sh"]

entrypoint.sh:

#!/bin/sh

echo "Waiting for postgres..."

while ! nc -z users-db 5432;
do
    sleep 0.1
done

echo "PostgreSQL started"

python manage.py recreate_db
python manage.py seed_db
gunicorn -b 0.0.0.0:5000 manage:app

I tried deleting my cluster and deregistering my tasks and restarting but ECS still continuously stops and starts new tasks now.

When it was working fine: the difference was that instead of the CMD ["./entrypoint.sh"] in my Dockerfile, I had

RUN python manage.py recreate_db
RUN python manage.py seed_db
CMD gunicorn -b 0.0.0.0:5000 manage:app

travis is passing.

Body:
If it's too many tasks running and they have consumed the space then you will need to shell in to the host and do the following. Don't use -f on the docker rm as that will remove the running ECS agent container

docker rm $(docker ps -aq)


问:
Rails 5 upgrade Halt callback config issue
I have recently upgraded from Rails 4.2 to 5.0. I know about the change in callback halting using throw(:abort) instead of returning false. My problem is that I can't make the deprecation warnings go away.

DEPRECATION WARNING: Returning false in Active Record and Active Model callbacks will not implicitly halt a callback chain in Rails 5.1. To explicitly halt the callback chain, please use throw :abort instead.

I have made config/initializers/callback_terminator.rb file with following code

```<code>ActiveSupport.halt_callback_chains_on_return_false = false
</code>```

but I am not still not able to get rid of the warning. Nor am I getting the expected behaviour. It seems that this configuration is not being applied.

Is there something I am missing?

答:
Put the config in after config.after_initialize block in application.rb file like this.</p>

```<code>config.after_initialize do
  ActiveSupport.halt_callback_chains_on_return_false = false
end
</code>```

Body:
I have recently upgraded from Rails 4.2 to 5.0. I know about the change in callback halting using throw(:abort) instead of returning false. My problem is that I can't make the deprecation warnings go away.

DEPRECATION WARNING: Returning false in Active Record and Active Model callbacks will not implicitly halt a callback chain in Rails 5.1. To explicitly halt the callback chain, please use throw :abort instead.

I have made config/initializers/callback_terminator.rb file with following code

ActiveSupport.halt_callback_chains_on_return_false = false

but I am not still not able to get rid of the warning. Nor am I getting the expected behaviour. It seems that this configuration is not being applied.

Is there something I am missing?

Body:
Put the config in after config.after_initialize block in application.rb file like this.

config.after_initialize do
  ActiveSupport.halt_callback_chains_on_return_false = false
end


问:
mounted method is fired before data loaded - VueJS
I'm using Vue Resource to retrieve an images collection from a REST API. The request is sent in the created hook of my Vue component.

The problem is, I'm trying to access the retrieved data in the mounted hook, but the data isn't loaded.

I get this error in the console:

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'forEach' of undefined"

Here is my component:

```<code><script>
export default {
  data() {
    return { imgs : '' };
  },
  created() {
    // the full url is declare in my main.js
    this.imgs = this.$resource('acf/v3/pages/4');

    this.imgs.query().then((response) => {
      console.log('success', response);
      this.imgs = response.data.acf.gallery;
    }, (response) => {
      console.log('erreur', response);
    });
  },
  mounted() {
    // get the ref="image" in my dom template
    let imgs = this.$refs.image;

    imgs.forEach((img) => {
      // I do some stuff with imgs
    });
  }
}
</script>
</code>```

If I wrap a setTimeout around the content of mounted, everything works fine.

So, I don't understand how I can wait for my data to load before the mounted hook is executed. Isn't this the role of the Vue lifecycle hooks?

答:
Since the this.imgs.query() call is async, your mounted hook is being called before the then handler is setting this.imgs (which I'm assuming is being bound with v-for to an element in your template with an attribute ref="image"). So, even though the component has been mounted to the DOM, the $refs have not been set up yet.

I would make a method to "do some stuff with imgs" and then call that method in a $nextTick callback in the then handler of the async call. The callback passed to $nextTick will be "executed after the next DOM update cycle", meaning the $refs will be set up at that point.

```<code><script>
export default {
  data() {
    return { imgs: '' };
  },
  created() {
    // the full url is declare in my main.js
    this.imgs = this.$resource('acf/v3/pages/4');

    this.imgs.query().then((response) => {
      console.log('success', response);
      this.imgs = response.data.acf.gallery;
      this.$nextTick(() => this.doStuffWithImgs());
    }, (response) => {
      console.log('erreur', response);
    });
  },
  methods: {
    doStuffWithImgs() {
      // get the ref="image" in my dom template
      let imgs = this.$refs.image;

      imgs.forEach((img) => {
        // I do some stuff with imgs
      });
    }
  }
}
</script>
</code>```

Body:
I'm using Vue Resource to retrieve an images collection from a REST API. The request is sent in the created hook of my Vue component.

The problem is, I'm trying to access the retrieved data in the mounted hook, but the data isn't loaded.

I get this error in the console:

[Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'forEach' of undefined"

Here is my component:

If I wrap a setTimeout around the content of mounted, everything works fine.

So, I don't understand how I can wait for my data to load before the mounted hook is executed. Isn't this the role of the Vue lifecycle hooks?

Body:
Since the this.imgs.query() call is async, your mounted hook is being called before the then handler is setting this.imgs (which I'm assuming is being bound with v-for to an element in your template with an attribute ref="image"). So, even though the component has been mounted to the DOM, the $refs have not been set up yet.

I would make a method to "do some stuff with imgs" and then call that method in a $nextTick callback in the then handler of the async call. The callback passed to $nextTick will be "executed after the next DOM update cycle", meaning the $refs will be set up at that point.

<script>
export default {
  data() {
    return { imgs: '' };
  },
  created() {
    // the full url is declare in my main.js
    this.imgs = this.$resource('acf/v3/pages/4');

    this.imgs.query().then((response) => {
      console.log('success', response);
      this.imgs = response.data.acf.gallery;
      this.$nextTick(() => this.doStuffWithImgs());
    }, (response) => {
      console.log('erreur', response);
    });
  },
  methods: {
    doStuffWithImgs() {
      // get the ref="image" in my dom template
      let imgs = this.$refs.image;

      imgs.forEach((img) => {
        // I do some stuff with imgs
      });
    }
  }
}
</script>

ContentLicense: CC BY-SA 4.0


问:
How to wildcard include JAR files when compiling?
I have the following in a java file (MyRtmpClient.java):

```<code>import org.apache.mina.common.ByteBuffer;
</code>```

and ByteBuffer is inside a JAR file (with the proper directory structure of course).
That jar file and others I need are in the same directory as the .java file.

Then I compile with the line:

```<code>javac -cp ".;*.jar" MyRtmpClient.java
</code>```

But I get the error:

MyRtmpClient.java:3: package org.apache.mina.common does not exist

  import org.apache.mina.common.ByteBuffer;

How can I include jar files in my project?

答:
In Java 8, the option ".;*" etc. which are mentioned above did not seem to work. I tried and found that :
javac -cp '<location of jars>/*' MyRtmpClient.java

works:

<location of jar> can be /usr/local/classes/* or /home/developer/MyProject/*

OwnerDisplayName: javanewbie

Body:
I have the following in a java file (MyRtmpClient.java):

import org.apache.mina.common.ByteBuffer;

and ByteBuffer is inside a JAR file (with the proper directory structure of course).
That jar file and others I need are in the same directory as the .java file.

Then I compile with the line:

javac -cp ".;*.jar" MyRtmpClient.java

But I get the error:

MyRtmpClient.java:3: package org.apache.mina.common does not exist

  import org.apache.mina.common.ByteBuffer;

How can I include jar files in my project?


问:
Ruby on Rails5: Filtering users by City / Country
what is the best way to structure Location information for users? I need to be able filter hundreds of users by City/Country.

Currently I have created a free-text string for location as I could not find any gem for whole cities grouped under countries. Btw this is a custom scaffold, not devise.

Should I just enter as free-text as in city, country and then filter based on that string with alike?

Thank you

答:
If you have structured data (i.e., address, city, state, country) for your users, you can filter on those. For example:

```<code>WHERE city || ', ' || country ILIKE ?
</code>```

If you don't, you can still try that assuming freeform location information on your users table (you weren't clear on the database schema):

```<code>WHERE location ILIKE ?
</code>```

Ideally you'd split up the city and country and filter separately:

```<code>WHERE city ILIKE ? AND country ILIKE ?
</code>```

Hundreds shouldn't be much of a performance issue but you can definitely build indexes for either of those:

```<code>CREATE INDEX city_country_on_users ON users(city || ', ' || country);
CREATE INDEX city_country_on_users ON users(location);
CREATE INDEX city_country_on_users ON users(city, country);
</code>```

respectively

Body:
If you have structured data (i.e., address, city, state, country) for your users, you can filter on those. For example:

WHERE city || ', ' || country ILIKE ?

If you don't, you can still try that assuming freeform location information on your users table (you weren't clear on the database schema):

WHERE location ILIKE ?

Ideally you'd split up the city and country and filter separately:

WHERE city ILIKE ? AND country ILIKE ?

Hundreds shouldn't be much of a performance issue but you can definitely build indexes for either of those:

CREATE INDEX city_country_on_users ON users(city || ', ' || country);
CREATE INDEX city_country_on_users ON users(location);
CREATE INDEX city_country_on_users ON users(city, country);

respectively


问:
cannot get the correct date and time in php
I dont know why I'm not getting the correct date and time in my region.
Here's the code

```<code><?php
//date_default_timezone_set('Asia/Manila');
echo date('YYYY-mm-dd H:i:s'); ?>
</code>```

Even if I comment out or change the time zone the date and time that I'm getting is still the same.
The date today is 23. But its outputting 22. And the time doesn't change even if I change the time zones.
Does it have something to do with my computer?
Because I sometimes notice that the clock on the lower right corner of the screen is not displaying the correct time.

Heres the current time, but its displaying this:

```<code>01-22-2011 05:38:31-PM
</code>```

答: It could be that time set up on server (where PHP script is being executed) is not correct.</p>

Body:
I dont know why I'm not getting the correct date and time in my region.
Here's the code

<?php
//date_default_timezone_set('Asia/Manila');
echo date('YYYY-mm-dd H:i:s'); ?>

Even if I comment out or change the time zone the date and time that I'm getting is still the same.
The date today is 23. But its outputting 22. And the time doesn't change even if I change the time zones.
Does it have something to do with my computer?
Because I sometimes notice that the clock on the lower right corner of the screen is not displaying the correct time.

Heres the current time, but its displaying this:

01-22-2011 05:38:31-PM


问:
Why do the types in `(fmap . fmap) sum Just [1, 2, 3]` work?
I'm having the time of my life reading the wonderful Haskell Programming from first principles and I came by the following example that I'm just not able to take apart (Page 1286 e-reader):

```<code>Prelude> (fmap . fmap) sum Just [1, 2, 3]
Just 6
</code>```

It is obvious to me how the following works:

```<code>Prelude> fmap sum $ Just [1,2,3]
Just 6
</code>```

And I already manually deconstructed (fmap . fmap) to understand how the types work. But when thinking about this as "lifting twice" it doesn't make sense, since I'm lifting over both the Just and List data constructors.

I typed out the following in ghci:

```<code>Prelude> :t (fmap . fmap)
(fmap . fmap)
  :: (Functor f, Functor f1) => (a -> b) -> f1 (f a) -> f1 (f b)

Prelude> :t (fmap . fmap) sum
(fmap . fmap) sum
  :: (Num b, Foldable t, Functor f, Functor f1) =>
     f1 (f (t b)) -> f1 (f b)

Prelude> :t (fmap . fmap) sum Just
(fmap . fmap) sum Just :: (Num b, Foldable t) => t b -> Maybe b
</code>```

I don't understand how to derive the last output. When feeding (fmap . fmap) sum the Just data constructor, How does the compiler know to replace both f1 and f for Maybe? After I'll get a good answer here, how could I have figured it out myself?

答:
If you don't understand how a particular answer works, line up the argument you are supplying with the type from the previous step.

```<code>Prelude> :t (fmap . fmap) sum
(fmap . fmap) sum
  :: (Functor f, Functor f1, Num b) => f (f1 [b]) -> f (f1 b)
</code>```

So in order for this work, Just has to have type f (f1 [b]), and then (fmap . fmap) sum Just has to have type f (f1 b).

```<code>Just :: (Functor f, Functor f1, Num b) => f (f1 [b])
</code>```

It's not obvious what f or f1 should be here, so let's try the RHS instead. We can cheat and ask GHCi to check what the actual value of (fmap . fmap) sum Just should be:

```<code>Prelude> :t (fmap . fmap) sum Just
(fmap . fmap) sum Just :: Num b => [b] -> Maybe b
</code>```

But this should match:

```<code>(Functor f, Functor f1, Num b) => f (f1 b)
</code>```

We're trying to figure out what f and f1 are here. So we have to rewrite it a little bit so it has the same structure (remember that -> is syntactic sugar and gets in the way sometimes):

```<code>(fmap . fmap) sum Just :: Num b => [b] -> Maybe b
-- Same as...
(fmap . fmap) sum Just :: Num b => (->) [b] (Maybe b)
-- Or...
(fmap . fmap) sum Just :: Num b => ((->) [b]) (Maybe b)
--                     Functor f = ((->) [b])
--                                Functor f1 = Maybe
</code>```

So we can figure out that in order for the types to match, the Functor f  has to be (->) [b]… remember that functions are functors too! And the Functor f1 is Maybe, which is a bit more obvious.

We can test this out:

```<code>Prelude> :t (fmap . fmap) sum :: Num b => ([b] -> Maybe [b]) -> ([b] -> Maybe b)
(fmap . fmap) sum :: Num b => ([b] -> Maybe [b]) -> ([b] -> Maybe b)
  :: Num b => ([b] -> Maybe [b]) -> [b] -> Maybe b
</code>```

And GHCi thinks it type checks just fine.

The only part here that's easy to forget is just that (->) [b] is a valid functor!

Body:
I'm having the time of my life reading the wonderful Haskell Programming from first principles and I came by the following example that I'm just not able to take apart (Page 1286 e-reader):

Prelude> (fmap . fmap) sum Just [1, 2, 3]
Just 6

It is obvious to me how the following works:

Prelude> fmap sum $ Just [1,2,3]
Just 6

And I already manually deconstructed (fmap . fmap) to understand how the types work. But when thinking about this as "lifting twice" it doesn't make sense, since I'm lifting over both the Just and List data constructors.

I typed out the following in ghci:

Prelude> :t (fmap . fmap)
(fmap . fmap)
  :: (Functor f, Functor f1) => (a -> b) -> f1 (f a) -> f1 (f b)

Prelude> :t (fmap . fmap) sum
(fmap . fmap) sum
  :: (Num b, Foldable t, Functor f, Functor f1) =>
     f1 (f (t b)) -> f1 (f b)

Prelude> :t (fmap . fmap) sum Just
(fmap . fmap) sum Just :: (Num b, Foldable t) => t b -> Maybe b

I don't understand how to derive the last output. When feeding (fmap . fmap) sum the Just data constructor, How does the compiler know to replace both f1 and f for Maybe? After I'll get a good answer here, how could I have figured it out myself?

Body:
If you don't understand how a particular answer works, line up the argument you are supplying with the type from the previous step.

Prelude> :t (fmap . fmap) sum
(fmap . fmap) sum
  :: (Functor f, Functor f1, Num b) => f (f1 [b]) -> f (f1 b)

So in order for this work, Just has to have type f (f1 [b]), and then (fmap . fmap) sum Just has to have type f (f1 b).

Just :: (Functor f, Functor f1, Num b) => f (f1 [b])

It's not obvious what f or f1 should be here, so let's try the RHS instead. We can cheat and ask GHCi to check what the actual value of (fmap . fmap) sum Just should be:

Prelude> :t (fmap . fmap) sum Just
(fmap . fmap) sum Just :: Num b => [b] -> Maybe b

But this should match:

(Functor f, Functor f1, Num b) => f (f1 b)

We're trying to figure out what f and f1 are here. So we have to rewrite it a little bit so it has the same structure (remember that -> is syntactic sugar and gets in the way sometimes):

(fmap . fmap) sum Just :: Num b => [b] -> Maybe b
-- Same as...
(fmap . fmap) sum Just :: Num b => (->) [b] (Maybe b)
-- Or...
(fmap . fmap) sum Just :: Num b => ((->) [b]) (Maybe b)
--                     Functor f = ((->) [b])
--                                Functor f1 = Maybe

So we can figure out that in order for the types to match, the Functor f  has to be (->) [b]… remember that functions are functors too! And the Functor f1 is Maybe, which is a bit more obvious.

We can test this out:

Prelude> :t (fmap . fmap) sum :: Num b => ([b] -> Maybe [b]) -> ([b] -> Maybe b)
(fmap . fmap) sum :: Num b => ([b] -> Maybe [b]) -> ([b] -> Maybe b)
  :: Num b => ([b] -> Maybe [b]) -> [b] -> Maybe b

And GHCi thinks it type checks just fine.

The only part here that's easy to forget is just that (->) [b] is a valid functor!


问:
Pass gridview template field text box id to a javascript function
I have a ASP GridView in my webpage.

I have two template fields 1 textbox and 1 hyperlink.

If i click the hyperlink on that particular row I need to pass the corresponding textbox id in that particular row of gridview.

```<code><asp:TemplateField HeaderText="Input">
    <ItemTemplate>
        <asp:TextBox ID="txtInput" Text='<%# Eval("Input") %>' Width="200px" Height="70px" runat="server" TextMode="MultiLine"></asp:TextBox>
    </ItemTemplate>
    <ItemStyle Width="20px" Height="30px" BorderStyle="Solid" Font-Size="12px" HorizontalAlign="Left"
    VerticalAlign="Middle" />
</asp:TemplateField>

<asp:TemplateField HeaderText="Verify">
    <ItemTemplate>
        <a href="#" id="lnkView" onclick="GetResults('#<%= txtInput.ClientID %>')">
        <%#Eval("Verify")%>
        </a>
    </ItemTemplate>
    <ItemStyle Width="203px" Height="15px" BorderStyle="Solid" BorderWidth="1px" Font-Size="12px" HorizontalAlign="Left"
    VerticalAlign="Middle" />
</asp:TemplateField>
</code>```

I tried the below code but am getting error as name 'txtInput' does not exist in current context.

Javascript function

```<code>function GetResults(id) {

//My code using this textbox id

}
</code>```

Please help on how to pass the text box id to javascript function on click of the hyperlink

答:
Something like this might work (untested).

Following line, remove the # sign.

```<code><a href="#" id="lnkView" onclick="GetResults('<%= txtInput.ClientID %>')">
</code>```

Then your javascript:

```<code>function GetResults(id) {

var ctrlId = "[id$=" + id + "]"
var inputVal = $(ctrlId).val()

// do work

}
</code>```

Body:
I have a ASP GridView in my webpage.

I have two template fields 1 textbox and 1 hyperlink.

If i click the hyperlink on that particular row I need to pass the corresponding textbox id in that particular row of gridview.

<asp:TemplateField HeaderText="Input">
    <ItemTemplate>
        <asp:TextBox ID="txtInput" Text='<%# Eval("Input") %>' Width="200px" Height="70px" runat="server" TextMode="MultiLine"></asp:TextBox>
    </ItemTemplate>
    <ItemStyle Width="20px" Height="30px" BorderStyle="Solid" Font-Size="12px" HorizontalAlign="Left"
    VerticalAlign="Middle" />
</asp:TemplateField>

<asp:TemplateField HeaderText="Verify">
    <ItemTemplate>
        <a href="#" id="lnkView" onclick="GetResults('#<%= txtInput.ClientID %>')">
        <%#Eval("Verify")%>

    </ItemTemplate>
    <ItemStyle Width="203px" Height="15px" BorderStyle="Solid" BorderWidth="1px" Font-Size="12px" HorizontalAlign="Left"
    VerticalAlign="Middle" />
</asp:TemplateField>

I tried the below code but am getting error as name 'txtInput' does not exist in current context.

Javascript function

function GetResults(id) {

//My code using this textbox id

}

Please help on how to pass the text box id to javascript function on click of the hyperlink

Body:
Something like this might work (untested).

Following line, remove the # sign.

<a href="#" id="lnkView" onclick="GetResults('<%= txtInput.ClientID %>')">

Then your javascript:

function GetResults(id) {

var ctrlId = "[id$=" + id + "]"
var inputVal = $(ctrlId).val()

// do work

}


问:
Multitouch two imageviews at the same position
I am using two image views in my activity, and the moment i double tap/pinch zoom i am zooming only the image which i have touched.
how can i zoom the other image also exactly at same time & same position.

I am only achieving multi-touch/pinch zoom only on one image view.

PS: I searched before posting, but to no avail.

Because of code lenth i cant paste it. Here's the link for the same which i have used: TouchImageView.java

答:
Maybe you want something like this:

```<code>onYourOnTouchImplementation(MotionEvent e) {
    //your implementation
    ...
    long downTime = e.getDownTime();
    long eventTime = e.getEventTime();
    int action = e.getAction();
    int x = e.getX() + (otherView.getX() - firstView.getX());
    int y = e.getY() + (otherView.getY() - firstView.getY());
    int metaState = e.getMetaState();

    MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, x, y, metaState);
    otherView.dispatchTouchEvent(event);
}
</code>```

So you can pass touches on the second view.

Body:
Maybe you want something like this:

onYourOnTouchImplementation(MotionEvent e) {
    //your implementation
    ...
    long downTime = e.getDownTime();
    long eventTime = e.getEventTime();
    int action = e.getAction();
    int x = e.getX() + (otherView.getX() - firstView.getX());
    int y = e.getY() + (otherView.getY() - firstView.getY());
    int metaState = e.getMetaState();

    MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, x, y, metaState);
    otherView.dispatchTouchEvent(event);
}

So you can pass touches on the second view.


问:
NHibernate elt field
Does anyone know why NHibernate generates a field named 'elt' of type int for a many to many mapping?
I'm wondering why I need it.
Thanks</p>

答: The "elt" field is the foreign key to the element in the many-to-many mapping.  In the join table, you should see two foreign key columns, id (for the parent) and elt (for the element).  You can use different names if you like; these are defaults.</p>

Title: NHibernate elt field

LastEditorDisplayName: Cade Roux

OwnerDisplayName: David Crow


问:
When to remove event listeners?
How do you know when you should remove event listeners?

For example, I know that if I have a TimerEvent listener, I can safely remove that event when I have stopped and / or deleted my timer.

Or, if I have a display object on the stage, and I remove it, I can safely remove any event listeners associated with the display object.

Any other examples?

答:
There are two reasons to remove event listeners:

You no longer want to receive events for whatever reason.  This is pretty straight-forward.  Your code is done listening and turns it off.

You are done with the object and you want it to be garbage collected.  This is a more subtle one, but if not done properly can lead to real memory leaks.  You see, when an observer adds an event listener to an observable, the observable keeps a reference to the observer.  Because of this, you can release your reference to the observer, think it will get garbage collected, but it won't if the observable is still alive.  Since the observable can't know when to release the listener, you have effectively created a memory leak!  Your code doesn't have an explicit reference to it, so you can't unhook it, and the observable won't do it eiher.  So, if you want an object to be completely de-referenced and therefore properly garbage collected, you need to remove the event listener.

Title: When to remove event listeners?


问:
Is there proper way to concatenate a base path name with a new path name?

Is there a way where you can update the char arrays of a base path with an updated path?

```<code>struct dirent *dp;
DIR *dir;
struct stat buf;
dir = opendir("./statdir/");
int x;
char base_path[11] = "./statdir/";
char* full_path;

int main(int argc, char* argv[]){
  while((dp = readdir(dir)) != NULL) {
     full_path = strcat(base_path, dp->d_name);

     if((x = lstat(full_path, &buf)) == -1) {
         perror("stat failed");
         exit(1);
       }
       printf("Debug: %s\n", full_path);

     }
     closedir(dir);
     return(0);
  }
}
</code>```

My goal is to update full_path after each loop to the base_path + whatever argument is passed to argv[] and in my directory i have two files name file1 and file2....

i.e if I ran my code and wrote ./Stat, I expected full_path to be "./statdir/file1" and then "./statdir/file2"

The results I am getting however is :

Debug: ./statdir/.

Debug: ./statdir/...

stat failed: No such file or directory

答:
You could build the full filename using snprintf like this...

```<code>snprintf(full_path, PATH_MAX, "%s/%s",base_path, dp->d_name);
</code>```

...but you'll first need to ensure that full_path has the space to contain the filename so replace

```<code>char *full_path;
</code>```

with

```<code>char full_path[PATH_MAX];
</code>```

Body:
Is there a way where you can update the char arrays of a base path with an updated path?

struct dirent *dp;
DIR *dir;
struct stat buf;
dir = opendir("./statdir/");
int x;
char base_path[11] = "./statdir/";
char* full_path;

int main(int argc, char* argv[]){
  while((dp = readdir(dir)) != NULL) {
     full_path = strcat(base_path, dp->d_name);

     if((x = lstat(full_path, &buf)) == -1) {
         perror("stat failed");
         exit(1);
       }
       printf("Debug: %s\n", full_path);

     }
     closedir(dir);
     return(0);
  }
}

My goal is to update full_path after each loop to the base_path + whatever argument is passed to argv[] and in my directory i have two files name file1 and file2....

i.e if I ran my code and wrote ./Stat, I expected full_path to be "./statdir/file1" and then "./statdir/file2"

The results I am getting however is :

Debug: ./statdir/.

Debug: ./statdir/...

stat failed: No such file or directory

Body:
You could build the full filename using snprintf like this...

snprintf(full_path, PATH_MAX, "%s/%s",base_path, dp->d_name);

...but you'll first need to ensure that full_path has the space to contain the filename so replace

char *full_path;

with

char full_path[PATH_MAX];


问:
TransformationError Reasons get_serving_url / Images API
I'm running into the following error using get_serving_url in order to serve images from my bucket.

```<code>Traceback (most recent call last):
 File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
   return method(*args, **kwargs)
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 1087, in synctasklet_wrapper
   return taskletfunc(*args, **kwds).get_result()
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 1057, in tasklet_wrapper
   result = func(*args, **kwds)
 File "/base/data/home/apps/e~tileserve20171207t210519.406056180994857717/blob_upload.py", line 70, in post
   bf.put_async()
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3473, in _put_async
   self._pre_put_hook()
 File "/base/data/home/apps/e~tileserve/20171207t210519.406056180994857717/blob_files.py", line 124, in _pre_put_hook
   print images.get_serving_url(None, filename='/gs' + '/tileserve.appspot.com/user2test4test4RGB20170927.tif')
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/images/__init__.py", line 1868, in get_serving_url
   return rpc.get_result()
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result
   return self.__get_result_hook(self)
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/images/__init__.py", line 1972, in get_serving_url_hook
   raise _ToImagesError(e, readable_blob_key)
 TransformationError
</code>```

When I upload an image to my bucket then it works but when I create an image through processing which should be exposed through get_serving_url I get TransformationError.

I tried two variants for serving images:

```<code>test = blobstore.create_gs_key('/gs' + '/path2object')
images.get_serving_url(test, secure_url=True)

images.get_serving_url(None, filename='/gs' + '/' + <bucket name>+  '/'+ <object name>)
</code>```

I also set the bucket object ACM permissions and the IAM App Engine app default service account permissions (storage admin). Both variants changed nothing but are important in order to access objects of a bucket.

Did somebody experience this issue ? What could be the error? I do not understand why it works when I upload an image but not for images which are generated through processing.

答:
The traceback suggests you may be trying to call images.get_serving_url() while an async operation may still be in progress.

If that op is actually saving the transformed image in GCS then it could explain the failure: get_serving_url() includes a check of the file being a valid image, which would fail with TransformationError if the file is not yet saved.

If so - you can fix the problem by either:

switching to the sync version of saving the image

waiting until saving the image completes (in case you have some other stuff to do in the meantime) - get the result of the sync call before invoking get_serving_url()

repeatedly trying get_serving_url() while catching TransformationError until it no longer fails that way. This is a bit risky as it can end up in an infinite loop if TransformationError is raised for reasons other than simply saving the image being incomplete.

Body:
I'm running into the following error using get_serving_url in order to serve images from my bucket.

Traceback (most recent call last):
 File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
   return method(*args, **kwargs)
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 1087, in synctasklet_wrapper
   return taskletfunc(*args, **kwds).get_result()
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 1057, in tasklet_wrapper
   result = func(*args, **kwds)
 File "/base/data/home/apps/e~tileserve20171207t210519.406056180994857717/blob_upload.py", line 70, in post
   bf.put_async()
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3473, in _put_async
   self._pre_put_hook()
 File "/base/data/home/apps/e~tileserve/20171207t210519.406056180994857717/blob_files.py", line 124, in _pre_put_hook
   print images.get_serving_url(None, filename='/gs' + '/tileserve.appspot.com/user2test4test4RGB20170927.tif')
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/images/__init__.py", line 1868, in get_serving_url
   return rpc.get_result()
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result
   return self.__get_result_hook(self)
 File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/images/__init__.py", line 1972, in get_serving_url_hook
   raise _ToImagesError(e, readable_blob_key)
 TransformationError

When I upload an image to my bucket then it works but when I create an image through processing which should be exposed through get_serving_url I get TransformationError.

I tried two variants for serving images:

test = blobstore.create_gs_key('/gs' + '/path2object')
images.get_serving_url(test, secure_url=True)

images.get_serving_url(None, filename='/gs' + '/' + <bucket name>+  '/'+ <object name>)

I also set the bucket object ACM permissions and the IAM App Engine app default service account permissions (storage admin). Both variants changed nothing but are important in order to access objects of a bucket.

Did somebody experience this issue ? What could be the error? I do not understand why it works when I upload an image but not for images which are generated through processing.


问:
Regroup javascript array
I would like to format:

```<code>[
    {
        "id": 1,
        "location": {
            "id": 1,
            "title": "location 1"
        },
    },
    {
        "id": 2,
        "location": {
            "id": 1,
            "title": "location 1"
        },
    },
    {
        "id": 3,
        "location": {
            "id": 2,
            "title": "location 2"
        },
    }
]
</code>```

To:

```<code>[
    {
        "id": 1,
        "title": "location 1",
        "items": [
            {
                "id": 1
            },
            {
                "id": 2
            }
        ]
    },
    {
        "id": 2,
        "title": "location 2",
        "items": [
            {
                "id": 3
            }
        ]
    }
]
</code>```

Update:
From your responses I derived:

```<code>const result = _(items)
    .groupBy(x => x.location.id)
    .map((value, key) => ({location: key, items: value}))
    .value();
</code>```

Which works, but the item objects still contain the location attribute and the location only maintains its id attribute. Is it neccessary to add all attributes to the groupBy?

The reason I am doing this is because I would like to filter on item attributes, but display the items grouped by location.

答:
Collect the items using _.groupBy() on the location.title, then map them. To create an object, use the key (2nd param) for the location, take the id from the 1st item using _.get(), and map the other items to take just the location object without the title using _.omit():

const data = [{"id":1,"location":{"id":1,"title":"location 1"}},{"id":2,"location":{"id":1,"title":"location 1"}},{"id":3,"location":{"id":2,"title":"location 2"}}];

const result = _(data)
  .groupBy('location.title')
  .map((items, location) => ({
    location,
    id: _.get(items, '[0].id'), // get the 1st item (if any) id
    items: items.map(({ location }) => _.omit(location, 'title')) // map the objects and take the inner item without the title
  }))
  .value();

console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script></code>```

Title: Regroup javascript array

Body:
I would like to format:

[
    {
        "id": 1,
        "location": {
            "id": 1,
            "title": "location 1"
        },
    },
    {
        "id": 2,
        "location": {
            "id": 1,
            "title": "location 1"
        },
    },
    {
        "id": 3,
        "location": {
            "id": 2,
            "title": "location 2"
        },
    }
]

To:

[
    {
        "id": 1,
        "title": "location 1",
        "items": [
            {
                "id": 1
            },
            {
                "id": 2
            }
        ]
    },
    {
        "id": 2,
        "title": "location 2",
        "items": [
            {
                "id": 3
            }
        ]
    }
]

Update:
From your responses I derived:

const result = _(items)
    .groupBy(x => x.location.id)
    .map((value, key) => ({location: key, items: value}))
    .value();

Which works, but the item objects still contain the location attribute and the location only maintains its id attribute. Is it neccessary to add all attributes to the groupBy?

The reason I am doing this is because I would like to filter on item attributes, but display the items grouped by location.

Body:
Collect the items using _.groupBy() on the location.title, then map them. To create an object, use the key (2nd param) for the location, take the id from the 1st item using _.get(), and map the other items to take just the location object without the title using _.omit():

const data = [{"id":1,"location":{"id":1,"title":"location 1"}},{"id":2,"location":{"id":1,"title":"location 1"}},{"id":3,"location":{"id":2,"title":"location 2"}}];

const result = _(data)
  .groupBy('location.title')
  .map((items, location) => ({
    location,
    id: _.get(items, '[0].id'), // get the 1st item (if any) id
    items: items.map(({ location }) => _.omit(location, 'title')) // map the objects and take the inner item without the title
  }))
  .value();

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>


问:
Ionic 3 - Want to convert array of object to array of strings in controller
In Ionic 3, I am fetching an array of objects in the controller. But it is not useful for me. So I want to convert array of objects to array of strings.. I am getting following data in controller.

```<code>   this.users = [{"id":1,"name":"US"},{"id":2,"name":"UK"}]
</code>```

But I want the result below:

```<code>    this.users = ["US", "UK"];
</code>```

答:
You can do that in a single line like this:</p>

```<code>this.users = this.users.map(user => user.name);
</code>```

Body:
In Ionic 3, I am fetching an array of objects in the controller. But it is not useful for me. So I want to convert array of objects to array of strings.. I am getting following data in controller.

   this.users = [{"id":1,"name":"US"},{"id":2,"name":"UK"}]

But I want the result below:

    this.users = ["US", "UK"];

Body:
You can do that in a single line like this:

this.users = this.users.map(user => user.name);


问:
JavaScript override class method conditionally
I have a class that I have defined that I use all over my application.  I have one page where I would like to change override some of the methods on all instances of the class.  Here is some code to illustrate.

myclass-script.js

```<code>var MyClass = new Class({
    foo: function() {
        return 1;
    },

    bar: function() {
        return this.foo() + 9;
    },
});
</code>```

change-myclass-script.js

```<code>MyClass.implement({
    foo: function() {
        return this.parent() * -1;
    },
});
</code>```

If I include on a page myclass-script.js I should see:

```<code>var test = new MyClass();
test.bar() === 10; //true
</code>```

If I include myclass-script.js and then change-myclass-script.js I should see:

```<code>var test = new MyClass();
test.bar() === 8; //true
</code>```

The issue I am having is that MyClass.implement applies to all instances of MyClass but it doesn't "override" the method, it replaces it.  So the this.parent() call fails because there is no parent for that method.  If I do MyClass.extend it does not apply like I want and I do not see the instances of MyClass calling the overridden method.

答:
Try doing the following:</p>

```<code>MyClass.prototype.implement({
</code>```

Body:
I have a class that I have defined that I use all over my application.  I have one page where I would like to change override some of the methods on all instances of the class.  Here is some code to illustrate.

myclass-script.js

var MyClass = new Class({
    foo: function() {
        return 1;
    },

    bar: function() {
        return this.foo() + 9;
    },
});

change-myclass-script.js

MyClass.implement({
    foo: function() {
        return this.parent() * -1;
    },
});

If I include on a page myclass-script.js I should see:

var test = new MyClass();
test.bar() === 10; //true

If I include myclass-script.js and then change-myclass-script.js I should see:

var test = new MyClass();
test.bar() === 8; //true

The issue I am having is that MyClass.implement applies to all instances of MyClass but it doesn't "override" the method, it replaces it.  So the this.parent() call fails because there is no parent for that method.  If I do MyClass.extend it does not apply like I want and I do not see the instances of MyClass calling the overridden method.

Body:
Try doing the following:

MyClass.prototype.implement({


问:
Adding custom link buttons to ASP GridView
I have the following GridView in which I have a select button in the first column that selects the row.

I want to put another similar (custom/user defined) button in a new column right next to select button called "Compute". How can I do that?

```<code><asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server" OnRowCommand="GridViewSavingsTracker_RowCommand">
    <Columns>
        <asp:CommandField ShowSelectButton="true" />
        <asp:BoundField DataField="creditorName" HeaderText="Creditor Name" />
        <asp:BoundField DataField="amount" HeaderText="Principal Amount" />
        <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
    </Columns>
</asp:GridView>
</code>```

答:
```<code><asp:ButtonField Text="Text_on_the_Button" CommandName="Command1" ButtonType="Link" />
</code>```

Command_Name = Gets or Sets a string that represents the action to perform when a button in a ButtonField object is clicked.

And on server side:

```<code>protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName=="Command1")
    {
        // What you want to do when the button is clicked.
    }
}
</code>```

Source: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.buttonfield(v=vs.110).aspx

Body:
I have the following GridView in which I have a select button in the first column that selects the row.

I want to put another similar (custom/user defined) button in a new column right next to select button called "Compute". How can I do that?

<asp:GridView ID="GridViewSavingsTracker" AutoGenerateColumns="false" runat="server" OnRowCommand="GridViewSavingsTracker_RowCommand">
    <Columns>
        <asp:CommandField ShowSelectButton="true" />
        <asp:BoundField DataField="creditorName" HeaderText="Creditor Name" />
        <asp:BoundField DataField="amount" HeaderText="Principal Amount" />
        <asp:BoundField DataField="interestRate" HeaderText="Interest Rate" />
    </Columns>
</asp:GridView>

Body:
<asp:ButtonField Text="Text_on_the_Button" CommandName="Command1" ButtonType="Link" />

Command_Name = Gets or Sets a string that represents the action to perform when a button in a ButtonField object is clicked.

And on server side:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if(e.CommandName=="Command1")
    {
        // What you want to do when the button is clicked.
    }
}

Source: https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.buttonfield(v=vs.110).aspx


问:
Adjust Elements after Manipulating String into AttributedString - Swift 4
I have the following which allows me to create a bullet list which works really well, however, after the bullet list is created I need to manipulate the outputted Attributed string to have certain elements either in bold or in italics or both.

The function I have is:

```<code>@IBOutlet var label: UILabel!
let bulletString = ["String 1","String 2","String 3"]

label.attributedText = label.bulletPoints(stringList: bulletString, font: UIFont.stdFontMediumSeventeen, bullet: "•", lineSpacing: 4, paragraphSpacing: 4, textColor: UIColor.darkGreyColor, bulletColor: UIColor.darkGreyColor)

func bulletPoints(stringList: [String],font: UIFont,bullet: String = "\u{2022}",indentation: CGFloat = 20,lineSpacing: CGFloat = 2,paragraphSpacing: CGFloat = 12,textColor: UIColor = .gray,bulletColor: UIColor = .red) -> NSAttributedString{
    let textAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor]
    let bulletAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: bulletColor]

    let paragraphStyle = NSMutableParagraphStyle()
    let nonOptions = [NSTextTab.OptionKey: Any]()
    paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
    paragraphStyle.defaultTabInterval = indentation
    paragraphStyle.lineSpacing = lineSpacing
    paragraphStyle.paragraphSpacing = paragraphSpacing
    paragraphStyle.headIndent = indentation

    let bulletList = NSMutableAttributedString()
    for string in stringList {
        let formattedString = "\(bullet)\t\(string)\n"
        let attributedString = NSMutableAttributedString(string: formattedString)

        attributedString.addAttributes(
            [NSAttributedStringKey.paragraphStyle : paragraphStyle],
            range: NSMakeRange(0, attributedString.length))

        attributedString.addAttributes(
            textAttributes,
            range: NSMakeRange(0, attributedString.length))

        let string:NSString = NSString(string: formattedString)
        let rangeForBullet:NSRange = string.range(of: bullet)
        attributedString.addAttributes(bulletAttributes, range: rangeForBullet)
        bulletList.append(attributedString)
    }
    return bulletList
}
</code>```

What I am looking for is a way to pass in a boolean to state if the bullet string requires either bold or italic text and if so what the elements of the intital string are that need this treatment.

The bulletPoints function sits in an extension file and works as expected.

答:
Using a model to link the bold/italic to the strings in question, as Neil suggests, helps you in this case. Here's a version which links font traits to the strings for each bullet, then uses those when building up the string.

I've refactored your bulletPoints function as well, to remove the use of ranges and simplify it a little. It could stay in an extension (I assume you have it on UILabel?) but there's no reason for it to, since it returns the string anyway. I've written it as a function which could be used in any class

```<code>class ViewController: UIViewController {

    @IBOutlet var label: UILabel!

    override func viewWillAppear(_ animated: Bool) {
        let bulletStrings = [BulletString(string: "String 1", traits: []),
                             BulletString(string: "String 2", traits: [.traitBold]),
                             BulletString(string: "String 3", traits: [.traitItalic]),
                             BulletString(string: "String 4", traits: [.traitBold, .traitItalic])]
        label.attributedText = bulletPoints(stringList: bulletStrings, font: UIFont.systemFont(ofSize: 15.0), bullet: "•", lineSpacing: 4, paragraphSpacing: 4, textColor: UIColor.darkGray, bulletColor: UIColor.darkGray)

    }

    func bulletPoints(stringList: [BulletString],
                      font: UIFont,
                      bullet: String = "\u{2022}",
                      indentation: CGFloat = 20,
                      lineSpacing: CGFloat = 2,
                      paragraphSpacing: CGFloat = 12,
                      textColor: UIColor = .gray,
                      bulletColor: UIColor = .red) -> NSAttributedString {

        let bulletList = NSMutableAttributedString()
        for bulletString in stringList {
            let attributedString = NSMutableAttributedString(string: "")
            let bulletAttributes: [NSAttributedStringKey: Any] = [
                .foregroundColor: bulletColor,
                .font: font]
            attributedString.append(NSAttributedString(string: bullet, attributes: bulletAttributes))

            let textAttributes: [NSAttributedStringKey: Any] = [
                .font: font.withTraits(traits: bulletString.traits),
                .foregroundColor: textColor,
                .paragraphStyle : paragraphStyle(indentation: indentation, lineSpacing: lineSpacing, paragraphSpacing: paragraphSpacing)
            ]
            attributedString.append(NSAttributedString(string:"\t\(bulletString.string)\n", attributes: textAttributes))

            bulletList.append(attributedString)
        }
        return bulletList
    }

    private func paragraphStyle(indentation: CGFloat, lineSpacing: CGFloat, paragraphSpacing: CGFloat) -> NSParagraphStyle {
        let style = NSMutableParagraphStyle()
        let nonOptions = [NSTextTab.OptionKey: Any]()
        style.tabStops = [NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
        style.defaultTabInterval = indentation
        style.lineSpacing = lineSpacing
        style.paragraphSpacing = paragraphSpacing
        style.headIndent = indentation
        return style
    }
}

struct BulletString {
    let string: String
    let traits: UIFontDescriptorSymbolicTraits
}

extension UIFont {

    func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont {
        let descriptor = self.fontDescriptor
            .withSymbolicTraits(UIFontDescriptorSymbolicTraits(traits))!
        return UIFont(descriptor: descriptor, size: 0)
    }

}
</code>```

If you wanted to have the bullets match the style of their strings, i.e. be bolded or italicised, you could just add the attributes in a single pass for each bullet

Body:
I have the following which allows me to create a bullet list which works really well, however, after the bullet list is created I need to manipulate the outputted Attributed string to have certain elements either in bold or in italics or both.

The function I have is:

@IBOutlet var label: UILabel!
let bulletString = ["String 1","String 2","String 3"]

label.attributedText = label.bulletPoints(stringList: bulletString, font: UIFont.stdFontMediumSeventeen, bullet: "•", lineSpacing: 4, paragraphSpacing: 4, textColor: UIColor.darkGreyColor, bulletColor: UIColor.darkGreyColor)

func bulletPoints(stringList: [String],font: UIFont,bullet: String = "\u{2022}",indentation: CGFloat = 20,lineSpacing: CGFloat = 2,paragraphSpacing: CGFloat = 12,textColor: UIColor = .gray,bulletColor: UIColor = .red) -> NSAttributedString{
    let textAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: textColor]
    let bulletAttributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: bulletColor]

    let paragraphStyle = NSMutableParagraphStyle()
    let nonOptions = [NSTextTab.OptionKey: Any]()
    paragraphStyle.tabStops = [NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
    paragraphStyle.defaultTabInterval = indentation
    paragraphStyle.lineSpacing = lineSpacing
    paragraphStyle.paragraphSpacing = paragraphSpacing
    paragraphStyle.headIndent = indentation

    let bulletList = NSMutableAttributedString()
    for string in stringList {
        let formattedString = "\(bullet)\t\(string)\n"
        let attributedString = NSMutableAttributedString(string: formattedString)

        attributedString.addAttributes(
            [NSAttributedStringKey.paragraphStyle : paragraphStyle],
            range: NSMakeRange(0, attributedString.length))

        attributedString.addAttributes(
            textAttributes,
            range: NSMakeRange(0, attributedString.length))

        let string:NSString = NSString(string: formattedString)
        let rangeForBullet:NSRange = string.range(of: bullet)
        attributedString.addAttributes(bulletAttributes, range: rangeForBullet)
        bulletList.append(attributedString)
    }
    return bulletList
}

What I am looking for is a way to pass in a boolean to state if the bullet string requires either bold or italic text and if so what the elements of the intital string are that need this treatment.

The bulletPoints function sits in an extension file and works as expected.

Body:
Using a model to link the bold/italic to the strings in question, as Neil suggests, helps you in this case. Here's a version which links font traits to the strings for each bullet, then uses those when building up the string.

I've refactored your bulletPoints function as well, to remove the use of ranges and simplify it a little. It could stay in an extension (I assume you have it on UILabel?) but there's no reason for it to, since it returns the string anyway. I've written it as a function which could be used in any class

class ViewController: UIViewController {

    @IBOutlet var label: UILabel!

    override func viewWillAppear(_ animated: Bool) {
        let bulletStrings = [BulletString(string: "String 1", traits: []),
                             BulletString(string: "String 2", traits: [.traitBold]),
                             BulletString(string: "String 3", traits: [.traitItalic]),
                             BulletString(string: "String 4", traits: [.traitBold, .traitItalic])]
        label.attributedText = bulletPoints(stringList: bulletStrings, font: UIFont.systemFont(ofSize: 15.0), bullet: "•", lineSpacing: 4, paragraphSpacing: 4, textColor: UIColor.darkGray, bulletColor: UIColor.darkGray)

    }

    func bulletPoints(stringList: [BulletString],
                      font: UIFont,
                      bullet: String = "\u{2022}",
                      indentation: CGFloat = 20,
                      lineSpacing: CGFloat = 2,
                      paragraphSpacing: CGFloat = 12,
                      textColor: UIColor = .gray,
                      bulletColor: UIColor = .red) -> NSAttributedString {

        let bulletList = NSMutableAttributedString()
        for bulletString in stringList {
            let attributedString = NSMutableAttributedString(string: "")
            let bulletAttributes: [NSAttributedStringKey: Any] = [
                .foregroundColor: bulletColor,
                .font: font]
            attributedString.append(NSAttributedString(string: bullet, attributes: bulletAttributes))

            let textAttributes: [NSAttributedStringKey: Any] = [
                .font: font.withTraits(traits: bulletString.traits),
                .foregroundColor: textColor,
                .paragraphStyle : paragraphStyle(indentation: indentation, lineSpacing: lineSpacing, paragraphSpacing: paragraphSpacing)
            ]
            attributedString.append(NSAttributedString(string:"\t\(bulletString.string)\n", attributes: textAttributes))

            bulletList.append(attributedString)
        }
        return bulletList
    }

    private func paragraphStyle(indentation: CGFloat, lineSpacing: CGFloat, paragraphSpacing: CGFloat) -> NSParagraphStyle {
        let style = NSMutableParagraphStyle()
        let nonOptions = [NSTextTab.OptionKey: Any]()
        style.tabStops = [NSTextTab(textAlignment: .left, location: indentation, options: nonOptions)]
        style.defaultTabInterval = indentation
        style.lineSpacing = lineSpacing
        style.paragraphSpacing = paragraphSpacing
        style.headIndent = indentation
        return style
    }
}

struct BulletString {
    let string: String
    let traits: UIFontDescriptorSymbolicTraits
}

extension UIFont {

    func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont {
        let descriptor = self.fontDescriptor
            .withSymbolicTraits(UIFontDescriptorSymbolicTraits(traits))!
        return UIFont(descriptor: descriptor, size: 0)
    }

}

If you wanted to have the bullets match the style of their strings, i.e. be bolded or italicised, you could just add the attributes in a single pass for each bullet