问:
if condition for checking a tortoiseSVN update into a linux bash
I am working with a SVN server into a linux computer.I am trying to develop bash code for making the compilation automatically. The thing is that I do not want to compile the files if there have not been an update into my SVN server. so the first thing I do is checking for updates.

this way:

if svn update; then

...

fi

the problem is that even if there are not updates it enters into the if condition as it has to check for updates. I would like to Know if there is a way of checking if an update had occurred or not.

thank you.

答:
I suggest to use svn hooks rather that ad-hoc scripts but you need to place them on the server side.

This said, if you still need to build your own script you need to notice that the svn update command will evaluate to true if no error has happened. This has nothing to do with the command really updating files or not. Consequently, you need to check your current svn version and the svn version of the remote repository. If they are different, then you can perform the svn update and any other command needed.

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

REMOTE_REPO="svn://path/to/remote/repo"
LOCAL_REPO="/path/to/local/repo"

REMOTE_REV=$(svn info $REMOTE_REPO | grep '^Revision:' | awk {' print $2 '})
LOCAL_REV=$(svn info $LOCAL_REPO | grep '^Revision:' | awk {' print $2 '})

if [ $REMOTE_REV -ne $LOCAL_REV ]; then
    cd $LOCAL_REPO
    svn up

    # Add any other command here
fi
</code>```

Body:
I suggest to use svn hooks rather that ad-hoc scripts but you need to place them on the server side.

This said, if you still need to build your own script you need to notice that the svn update command will evaluate to true if no error has happened. This has nothing to do with the command really updating files or not. Consequently, you need to check your current svn version and the svn version of the remote repository. If they are different, then you can perform the svn update and any other command needed.

#!/bin/bash

REMOTE_REPO="svn://path/to/remote/repo"
LOCAL_REPO="/path/to/local/repo"

REMOTE_REV=$(svn info $REMOTE_REPO | grep '^Revision:' | awk {' print $2 '})
LOCAL_REV=$(svn info $LOCAL_REPO | grep '^Revision:' | awk {' print $2 '})

if [ $REMOTE_REV -ne $LOCAL_REV ]; then
    cd $LOCAL_REPO
    svn up

    # Add any other command here
fi


来源: stackexchange

问:
Masked Input Using EditText Widget in Android
Is there a way I can specify an input mask to the EditText control in Android?

I want be able to specify something like ### - ## - #### for a Social Security Number. This will cause any invalid input to be rejected automatically (example, I type alphabetical characters instead of numeric digits).

I realize that I can add an OnKeyListener and manually check for validity. But this is tedious and I will have to handle various edge cases.

答:
```<code>String phoneNumber = "1234567890";

String text = String.valueOf( android.telephony.PhoneNumberUtils.formatNumber(phoneNumber) ); //formatted: 123-456-7890

editTextMobile.setText(text); //set editText text equal to new formatted number

editTextMobile.setSelection(text.length()); //move cursor to end of editText view
</code>```

Use this in an onKey function for delicious on-the-fly bunny sex with formatted phone numbers.

ContentLicense: CC BY-SA 4.0

Body:
String phoneNumber = "1234567890";

String text = String.valueOf( android.telephony.PhoneNumberUtils.formatNumber(phoneNumber) ); //formatted: 123-456-7890

editTextMobile.setText(text); //set editText text equal to new formatted number

editTextMobile.setSelection(text.length()); //move cursor to end of editText view

Use this in an onKey function for delicious on-the-fly bunny sex with formatted phone numbers.

ContentLicense: CC BY-SA 3.0


问:
What is the simplest way to remove a trailing slash from each parameter?
What is the simplest way to remove a trailing slash from each parameter in the '$@' array, so that rsync copies  the directories by name?

```<code>rsync -a --exclude='*~' "$@" "$dir"
</code>```

The title has been changed for clarification. To understand the comments and answer about multiple trailing slashes see the edit history.

答:
realpath resolves given path. Among other things it also removes trailing slashes. Use -s to prevent following simlinks

```<code>DIR=/tmp/a///
echo $(realpath -s $DIR)
# output: /tmp/a
</code>```

Body:
What is the simplest way to remove a trailing slash from each parameter in the '$@' array, so that rsync copies  the directories by name?

rsync -a --exclude='*~' "$@" "$dir"

The title has been changed for clarification. To understand the comments and answer about multiple trailing slashes see the edit history.

Body:
realpath resolves given path. Among other things it also removes trailing slashes. Use -s to prevent following simlinks

DIR=/tmp/a///
echo $(realpath -s $DIR)
# output: /tmp/a


问:
Best practices with saving datetime & timezone info in database when data is dependant on datetime
There were quite a few questions about saving datetime & timezones info in DB but more on the overall level. Here I'd like to address a specific case.

System specs

We have an Orders system database

It is a multi-tenant system where tenants can use arbitrary timezone (it is arbitrary but single timezone per tenant, saved in Tenants table once and never changes)

Business rule needed to be covered in DB

When tenant places an Order into the system, order number gets computed based on their local datetime (its not literally a number but some kind of an identifier like ORDR-13432-Year-Month-Day). Precise calculation is not important for the moment, it's just important that it's dependant on tenants local datetime

We also do want to be able to select all Orders, on the system level, placed between some UTC datetimes regardless of the tenant (for general system statistics/reporting)

Our initial idea

Our initial idea was to save UTC datetime across whole DB and, of course, keep tenants timezone offset relative to UTC and have application that consumes DB always convert datetimes to UTC so that DB itself always operate with UTC.

Approach 1

Saving local tenants datetime would be nice per tenant but then we have problem with queries like:

```<code>SELECT * FROM ORDERS WHERE OrderDateTime BETWEEN UTCDateTime1 AND UTCDateTime2
</code>```

It's problematic because OrderDateTime in this query means different moment in time, based on tenant. Of course, this query might include join to Tenants table to get local datetime offset which would then calculate OrderDateTime on the fly to make adjustments. It's possible, but not sure if it's a good way to do it?

Approach 2

On the other hand, when saving UTC datetime, then when we do calculation of OrderNumber since the day/month/year in UTC might differ from the one in local datetime

Let's take extreme example; let's say tenant is 6 hours ahead of UTC and his local datetime is 2017-01-01 02:00.
UTC would be 2016-12-31 20:00. Order placed at that moment should get OrderNumber 'ORDR-13432-2017-1-1' but if saving UTC it would get ORDR-13432-2016-12-31.

In this case, at the moment of creating Order in DB, we should get UTC datetime, tenants offset and compile OrderNumber based on recalculated tenants localtime but still save DateTime column in UTC.

Questions

What is the preferred way of handling this kind of situation?

Is there a nice solution with saving UTC datetimes because that one would be pretty nice for us because of the system-level reporting?

If going with saving UTC, is Approach 2) good way to handle those cases or is there some better/recommended way?

[UPDATE]

Based on comments from Gerard Ashton and Hugo:

Initial question was not clear with respect to the detail if tenant can change timezone or not and what happens if political authority changes the timezone properties or some terirory's timezone.
Of course that is of an extreme importance, but it is not in the center of this question . We might address that in a separate question.

For the sake of this question, lets assume tenant will not change location. Timezone properties or timezone itself for that location might change and those changes will be handled in the system separately from this question.

答:
I'd recommend to always use UTC internally, and convert to a timezone only when displaying the date to the user. So I tend to prefer approach 2.

If there's a business rule saying that the tenant's local date/time must be part of the identifier, so be it. But internally, you keep the order date in UTC.

Using your example: a tenant whose timezone is in UTC+06:00, so the tenant's local time is 2017-01-01 02:00, which is equivalent to 2016-12-31 20:00 in UTC.

The order identifier would be ORDR-13432-2017-1-1 and the order date would be UTC 2016-12-31 20:00Z.

To get all orders between 2 dates, this query is straighforward:

SELECT * FROM ORDERS WHERE OrderDateTime BETWEEN UTCDateTime1 AND UTCDateTime2
```

<p>Because <code>OrderDateTime</code> is in UTC.</p>

<p>If looking for a specific tenant, then you can get the corresponding timezone, convert the date accordingly and search for it. Using the same example above (tenant's timezone is in <code>UTC+06:00</code>), to get all orders made in <code>2017-01-01</code> (in tenant's local time):</p>

<pre class="lang-sql prettyprint-override"><code>--get tenant timezone
--startUTC=tenant's local 2017-01-01 00:00 converted to UTC (2016-12-31T18:00Z)
--endUTC=tenant's local 2017-01-01 23:59:59.999 converted to UTC (2017-01-01T17:59:59.999)
SELECT * FROM ORDERS WHERE OrderDateTime between startUTC and endUTC
</code>```

This will get ORDR-13432-2017-1-1 correctly.

To make queries for multiple tenants in different timezones, both approaches require a join, so none are "better" for this case.

Unless you create an extra column with the tenant's local date/time (the UTC OrderDateTime converted to tenant's timezone). It'll be redundant, but it can help you with queries that searches in more than one timezone. If that's a reasonable trade-off it will depend on how frequent those queries will be made.

Body:
There were quite a few questions about saving datetime & timezones info in DB but more on the overall level. Here I'd like to address a specific case.

System specs

We have an Orders system database

It is a multi-tenant system where tenants can use arbitrary timezone (it is arbitrary but single timezone per tenant, saved in Tenants table once and never changes)

Business rule needed to be covered in DB

When tenant places an Order into the system, order number gets computed based on their local datetime (its not literally a number but some kind of an identifier like ORDR-13432-Year-Month-Day). Precise calculation is not important for the moment, it's just important that it's dependant on tenants local datetime

We also do want to be able to select all Orders, on the system level, placed between some UTC datetimes regardless of the tenant (for general system statistics/reporting)

Our initial idea

Our initial idea was to save UTC datetime across whole DB and, of course, keep tenants timezone offset relative to UTC and have application that consumes DB always convert datetimes to UTC so that DB itself always operate with UTC.

Approach 1

Saving local tenants datetime would be nice per tenant but then we have problem with queries like:

SELECT * FROM ORDERS WHERE OrderDateTime BETWEEN UTCDateTime1 AND UTCDateTime2

It's problematic because OrderDateTime in this query means different moment in time, based on tenant. Of course, this query might include join to Tenants table to get local datetime offset which would then calculate OrderDateTime on the fly to make adjustments. It's possible, but not sure if it's a good way to do it?

Approach 2

On the other hand, when saving UTC datetime, then when we do calculation of OrderNumber since the day/month/year in UTC might differ from the one in local datetime

Let's take extreme example; let's say tenant is 6 hours ahead of UTC and his local datetime is 2017-01-01 02:00.
UTC would be 2016-12-31 20:00. Order placed at that moment should get OrderNumber 'ORDR-13432-2017-1-1' but if saving UTC it would get ORDR-13432-2016-12-31.

In this case, at the moment of creating Order in DB, we should get UTC datetime, tenants offset and compile OrderNumber based on recalculated tenants localtime but still save DateTime column in UTC.

Questions

What is the preferred way of handling this kind of situation?

Is there a nice solution with saving UTC datetimes because that one would be pretty nice for us because of the system-level reporting?

If going with saving UTC, is Approach 2) good way to handle those cases or is there some better/recommended way?

[UPDATE]

Based on comments from Gerard Ashton and Hugo:

Initial question was not clear with respect to the detail if tenant can change timezone or not and what happens if political authority changes the timezone properties or some terirory's timezone.
Of course that is of an extreme importance, but it is not in the center of this question . We might address that in a separate question.

For the sake of this question, lets assume tenant will not change location. Timezone properties or timezone itself for that location might change and those changes will be handled in the system separately from this question.

Body:
I'd recommend to always use UTC internally, and convert to a timezone only when displaying the date to the user. So I tend to prefer approach 2.

If there's a business rule saying that the tenant's local date/time must be part of the identifier, so be it. But internally, you keep the order date in UTC.

Using your example: a tenant whose timezone is in UTC+06:00, so the tenant's local time is 2017-01-01 02:00, which is equivalent to 2016-12-31 20:00 in UTC.

The order identifier would be ORDR-13432-2017-1-1 and the order date would be UTC 2016-12-31 20:00Z.

To get all orders between 2 dates, this query is straighforward:

SELECT * FROM ORDERS WHERE OrderDateTime BETWEEN UTCDateTime1 AND UTCDateTime2

Because OrderDateTime is in UTC.

If looking for a specific tenant, then you can get the corresponding timezone, convert the date accordingly and search for it. Using the same example above (tenant's timezone is in UTC+06:00), to get all orders made in 2017-01-01 (in tenant's local time):

--get tenant timezone
--startUTC=tenant's local 2017-01-01 00:00 converted to UTC (2016-12-31T18:00Z)
--endUTC=tenant's local 2017-01-01 23:59:59.999 converted to UTC (2017-01-01T17:59:59.999)
SELECT * FROM ORDERS WHERE OrderDateTime between startUTC and endUTC

This will get ORDR-13432-2017-1-1 correctly.

To make queries for multiple tenants in different timezones, both approaches require a join, so none are "better" for this case.

Unless you create an extra column with the tenant's local date/time (the UTC OrderDateTime converted to tenant's timezone). It'll be redundant, but it can help you with queries that searches in more than one timezone. If that's a reasonable trade-off it will depend on how frequent those queries will be made.


问:
numberDisplay - filter by max key
I have a dc.js dashboard that has historical Headcount, Sickness etc information that is grouped by Month / Period. The users of the Dashboards want to see the most recent Month's data in number displays across the top (e.g Headcount, Sickness rate etc).

My data:

```<code>var data= [
{ "Month": "01/02/2014","Period": 201402,"Heads": 15123,"SchedHours":146000,"Sickness": 0,},
{ "Month": "01/03/2014","Period": 201403,"Heads": 15100,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/04/2014","Period": 201404,"Heads": 14900,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/05/2014","Period": 201405,"Heads": 14800,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/06/2014","Period": 201406,"Heads": 14750,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/07/2014","Period": 201407,"Heads": 14720,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/08/2014","Period": 201408,"Heads": 14000,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/09/2014","Period": 201409,"Heads": 13750,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/10/2014","Period": 201410,"Heads": 13500,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/11/2014","Period": 201411,"Heads": 13200,"SchedHours": 146000,"Sickness": 0,},
....]
</code>```

I can work out how to do this by default when the dashboard first loads using a variable:

```<code>maxPeriod = dimPeriod.top(1)[0].Period;
</code>```

But I'm struggling to work out how to update the variable above to update the numberDisplay to always filter it to show the Heads by the max Period or Month.

I'm currently showing the latest number of "Heads" using a function Gordon kindly provided in another question:

```<code>function choose_bin(group, key) {
return {
value: function() {
  return group.all().filter(kv => kv.key === key)[0].value;
    }
  }
}
</code>```

My group is then:

```<code>var latestMonth = choose_bin(groupHeads3, maxPeriod);
</code>```

and the numberDisplay:

```<code>numberChart
.group(latestMonth)
.valueAccessor(x => (x))
.formatNumber(d3.format(".0f"));
</code>```

I have a basic jsfiddle that shows the problem (as soon as a filter is applied, the value is 0): https://jsfiddle.net/kevinelphick/mzpoe555/2/

What I'm aiming to do, is for the Heads value to update based on the highest period that's filtered in the line chart. I'm also looking to include the month prior to the highest period value, and provide a comparison of the two to show a trend.

Thank you in advance.

答:
You're just not calculating quite enough stuff at runtime. You need to calculate maxPeriod and everything subsequent to that every time the group is queried. You'll probably want to do something like this (which works if you drop it into your JSFiddle:

```<code>var latestMonth = {
  all: function() {
    maxPeriod = dimPeriod.top(1)[0].Period;
    return [choose_bin(groupHeads3, maxPeriod).value()]
  }
}
</code>```

Title: numberDisplay - filter by max key

Body:
I have a dc.js dashboard that has historical Headcount, Sickness etc information that is grouped by Month / Period. The users of the Dashboards want to see the most recent Month's data in number displays across the top (e.g Headcount, Sickness rate etc).

My data:

var data= [
{ "Month": "01/02/2014","Period": 201402,"Heads": 15123,"SchedHours":146000,"Sickness": 0,},
{ "Month": "01/03/2014","Period": 201403,"Heads": 15100,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/04/2014","Period": 201404,"Heads": 14900,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/05/2014","Period": 201405,"Heads": 14800,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/06/2014","Period": 201406,"Heads": 14750,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/07/2014","Period": 201407,"Heads": 14720,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/08/2014","Period": 201408,"Heads": 14000,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/09/2014","Period": 201409,"Heads": 13750,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/10/2014","Period": 201410,"Heads": 13500,"SchedHours": 146000,"Sickness": 0,},
{ "Month": "01/11/2014","Period": 201411,"Heads": 13200,"SchedHours": 146000,"Sickness": 0,},
....]

I can work out how to do this by default when the dashboard first loads using a variable:

maxPeriod = dimPeriod.top(1)[0].Period;

But I'm struggling to work out how to update the variable above to update the numberDisplay to always filter it to show the Heads by the max Period or Month.

I'm currently showing the latest number of "Heads" using a function Gordon kindly provided in another question:

function choose_bin(group, key) {
return {
value: function() {
  return group.all().filter(kv => kv.key === key)[0].value;
    }
  }
}

My group is then:

var latestMonth = choose_bin(groupHeads3, maxPeriod);

and the numberDisplay:

numberChart
.group(latestMonth)
.valueAccessor(x => (x))
.formatNumber(d3.format(".0f"));

I have a basic jsfiddle that shows the problem (as soon as a filter is applied, the value is 0): https://jsfiddle.net/kevinelphick/mzpoe555/2/

What I'm aiming to do, is for the Heads value to update based on the highest period that's filtered in the line chart. I'm also looking to include the month prior to the highest period value, and provide a comparison of the two to show a trend.

Thank you in advance.

Body:
You're just not calculating quite enough stuff at runtime. You need to calculate maxPeriod and everything subsequent to that every time the group is queried. You'll probably want to do something like this (which works if you drop it into your JSFiddle:

var latestMonth = {
  all: function() {
    maxPeriod = dimPeriod.top(1)[0].Period;
    return [choose_bin(groupHeads3, maxPeriod).value()]
  }
}


问:
Find an exact text inside an string with MySQL
I have a database table with two columns, one for the ID and another one for Colors. Imagine that I have 3 lines in this table with the following data:

```<code>ID: 1 => Colors: Blue; Yellow; Red;
ID: 2 => Colors: Green; GreenYellow; Yellowgreen; Blue;
ID: 3 => Colors: Yellow; Blue;
</code>```

If I want to make a SQL call to know if there is a register with yellow color (just Yellow, no GreenYellow or Yellowgreen). How can I do it? I´m trying with:

```<code>$statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
$statement->execute(array(":suscritos" => "%Yellow%"));
$todos_mis_mensajes = $statement->fetchAll();
</code>```

IDs results: 1, 2 and 3

```<code> $statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
 $statement->execute(array(":suscritos" => "%Yellow_"));
 $todos_mis_mensajes = $statement->fetchAll();
</code>```

IDs results: No result

```<code>$statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
$statement->execute(array(":suscritos" => "_Yellow%"));
$todos_mis_mensajes = $statement->fetchAll();
</code>```

IDs results: 3

答:
Just put the exact "Yellow" word with no wildcards.

% indicates 0 or more characters.

"%Yellow%" indicates all strings with Yellow word.

"%Yellow" indicates all string that ends in Yellow.

"Yellow%" indicates all string that starts with Yellow.

_ indicates must have exactly 1 character.
"_Yellow" all strings that have a character before the Yellow word.
ie: aYellow, bYellow

unacceptable: abYellow, Yellow

Body:
I have a database table with two columns, one for the ID and another one for Colors. Imagine that I have 3 lines in this table with the following data:

ID: 1 => Colors: Blue; Yellow; Red;
ID: 2 => Colors: Green; GreenYellow; Yellowgreen; Blue;
ID: 3 => Colors: Yellow; Blue;

If I want to make a SQL call to know if there is a register with yellow color (just Yellow, no GreenYellow or Yellowgreen). How can I do it? I´m trying with:

$statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
$statement->execute(array(":suscritos" => "%Yellow%"));
$todos_mis_mensajes = $statement->fetchAll();

IDs results: 1, 2 and 3

 $statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
 $statement->execute(array(":suscritos" => "%Yellow_"));
 $todos_mis_mensajes = $statement->fetchAll();

IDs results: No result

$statement = $conexion->prepare("SELECT * FROM comentarios  WHERE suscritos LIKE :suscritos");
$statement->execute(array(":suscritos" => "_Yellow%"));
$todos_mis_mensajes = $statement->fetchAll();

IDs results: 3


问:
AngularJS using XAMPP doesn't find the page
I have the following folder structure:

```<code>C:\xampp\htdocs\project
</code>```

Inside project folder, I have an index.html file and other folders which contain js files and minified versions of angular and angular-route.

I installed XAMPP and I started all the modules(MySQL, FileZilla, Mercury, Tomcat), only Apache doesn't start, throwind these messages:

```<code>5:14:15 PM  [Apache]    Status change detected: stopped
5:14:15 PM  [Apache]    Error: Apache shutdown unexpectedly.
5:14:15 PM  [Apache]    This may be due to a blocked port, missing dependencies,
5:14:15 PM  [Apache]    improper privileges, a crash, or a shutdown by another method.
5:14:15 PM  [Apache]    Press the Logs button to view error logs and check
5:14:15 PM  [Apache]    the Windows Event Viewer for more clues
5:14:15 PM  [Apache]    If you need more help, copy and post this
5:14:15 PM  [Apache]    entire log window on the forums
</code>```

I'm trying to see the index.html file in a browser, I use this URL: http://localhost/xampp/htdocs/project/index.html but I get an empty page, in console showing this message:

GET http://localhost/xampp/htdocs/project/index.html 404 (Not Found)

Any ideas how to solve this?

答:
The URL you are trying to navigate to is not correct. It should be localhost/project/index.html#/. Basically, xampp sets up a server (apache and others) in your system. And your file for a project such as index.html should reside in the xampp\htdocs\YourFolderName.

The browser locates the server in localhost and will search through the above folder for any resources available in there. So the url will for above case will be localhost/YourFolderName/index.html#/

Body:
I have the following folder structure:

C:\xampp\htdocs\project

Inside project folder, I have an index.html file and other folders which contain js files and minified versions of angular and angular-route.

I installed XAMPP and I started all the modules(MySQL, FileZilla, Mercury, Tomcat), only Apache doesn't start, throwind these messages:

5:14:15 PM  [Apache]    Status change detected: stopped
5:14:15 PM  [Apache]    Error: Apache shutdown unexpectedly.
5:14:15 PM  [Apache]    This may be due to a blocked port, missing dependencies,
5:14:15 PM  [Apache]    improper privileges, a crash, or a shutdown by another method.
5:14:15 PM  [Apache]    Press the Logs button to view error logs and check
5:14:15 PM  [Apache]    the Windows Event Viewer for more clues
5:14:15 PM  [Apache]    If you need more help, copy and post this
5:14:15 PM  [Apache]    entire log window on the forums

I'm trying to see the index.html file in a browser, I use this URL: http://localhost/xampp/htdocs/project/index.html but I get an empty page, in console showing this message:

GET http://localhost/xampp/htdocs/project/index.html 404 (Not Found)

Any ideas how to solve this?


问:
Exposing different view of Class
Is it possible to give different view of a Class . For example , i have Account class , i want expose this data using WCF. For different method call i want expose different property of Account class.Suppose for particular call i want expose only UserName and Password, for
another call i want expose Email and Address. Should i have to write different class or
i can expose needed property to client</p>

答: You could use a DataContract with DataMember attributes, but that allows you to produce only one serialised view of a class. You would probably want to create smaller ViewModel classes, possibly using AutoMapper to handle all the mapping code for you.</p>

ContentLicense: CC BY-SA 2.5

Title: Exposing different view of Class


问:
The reference assemblies for framework “.NETFramework,Version=v4.5.1” were not found in RHPL
we have install dotnet sdk in our RHPL version 7. when we try to build our project we getting some build error. my dotnet version on Linux is 1.0.4. we are getting error like this </p>

```<code>    error MSB3644: The reference assemblies for framework ".NETFramework,Version=v4.5.1" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed.
Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend.
</code>```

答:
Your project targets .net 4.5.1, in the csproj there should be something that looks like this

<TargetFramework>net451</TargetFramework>

That line would target the windows desktop based .net which will not compile on linux.

You need to have your project target netstandard or netcoreapp depending on your usecase.

If you have a TargetFrameworks attribute (note the s at the end) with a semicolon seperated list of framworks then it is likely multi targeted. You could probably call dotnet build /p:TargetFramework=<FrameworkHere> where the framework is in the list of frameworks and it starts with netstandard or netcoreapp.

You will not be able to compile netX code on linux, only netstandard, netcoreapp, and a few other obscure monikers.

Body:
we have install dotnet sdk in our RHPL version 7. when we try to build our project we getting some build error. my dotnet version on Linux is 1.0.4. we are getting error like this

    error MSB3644: The reference assemblies for framework ".NETFramework,Version=v4.5.1" were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed.
Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend.


问:
How to put sign on marked places in document pages
Based on docusignapi functionality need to put sign on marked places in document pages,</p>

答:
Using the auto-place feature (also called anchor-tagging) you can specify the location of your tabs based on content or "markers" contained within your documents.

See Documentation here.

Api Documentation here


答:
Map projections

Difficult problem

The problem with the earth is that is is not flat, and most of what we humans use to draw and render to tends to be flat. To fix the problem we accept some deformation of what the map represents by applying a projection from the round Earth to the flat map. There are many many different types of projections, a common one is the mercator projection (see google maps), it distorts area the further south and north of the equator you are. But it does this to maintain direction. You can put a compass on a mercator projected map and get an accurate bearing, but you can't take a ruler and measure the distance.

But size matters, easy solution

But there is one saving grace in all this. We humans are tiny compared to the Earth and for local maps the distortion caused by the curvature of the Earth is so small to be irrelevant.

If you have a set of coordinates in a small area (eg a city and suburbs) you can just use a square projection. Where lat and long are x and y on the grid of rendering surface.

Step by step

How to take some mapping data and fit it to a canvas maintaining the aspect.

So you have a set of points and a canvas context

```<code><canvas id="canvas" width =300 height = 200></canvas>
ctx = canvas.getContext("2d");

 var myPoints = [[2.809510437833253,49.408625488749216],[2.8095461924850422,49.40864172401838],[2.8095226856172806,49.40866595550704],[2.809565304449213,49.40868849340382],[2.8097185865450465,49.40858536874469],[2.809677338568488,49.40856463072128],[2.8096442193374154,49.408580757620854],[2.809609885351463,49.40855283978645],[2.809510437833253,49.408625488749216]]
</code>```

Then find the extent of those points (the min and max coordinates)

```<code>var minX,minY,maxX,maxY;
myPoints.forEach((p,i) => {
   if(i === 0){ // if first point
      minX = maxX = p[0];
      minY = maxY = p[1];
   }else{
      minX = Math.min(p[0],minX);
      minY = Math.min(p[1],minY);
      maxX = Math.max(p[0],maxX);
      maxY = Math.max(p[1],maxY);
   }
 });
 // now get the map width and heigth in its local coords
 const mapWidth = maxX-minX;
 const mapHeight = maxY-minY;
 const mapCenterX = (maxX + minX) /2;
 const mapCenterY = (maxY + minY) /2;
</code>```

Now you have the map extent you can scale it to the canvas by finding the smallest scale to fit both width and height.

```<code> const scale = Math.min(canvas.width / mapWidth,canvas.height / mapHeight);
</code>```

Now you can draw the map first subtracting the map center, then scaling it up, then moving ot to the canvas center.

```<code> ctx.beginPath();
 myPoints.forEach(p => {
      ctx.lineTo(
          (p[0] - mapCenterX) * scale + canvas.width /2 ,
          (p[1] - mapCenterY) * scale + canvas.height / 2
      );
 });
 ctx.stroke();
</code>```

And a working example.

 ctx = canvas.getContext("2d");

 var myPoints = [[2.809510437833253,49.408625488749216],[2.8095461924850422,49.40864172401838],[2.8095226856172806,49.40866595550704],[2.809565304449213,49.40868849340382],[2.8097185865450465,49.40858536874469],[2.809677338568488,49.40856463072128],[2.8096442193374154,49.408580757620854],[2.809609885351463,49.40855283978645],[2.809510437833253,49.408625488749216]]

var minX,minY,maxX,maxY;
myPoints.forEach((p,i) => {
   if(i === 0){ // if first point
      minX = maxX = p[0];
      minY = maxY = p[1];
   }else{
      minX = Math.min(p[0],minX);
      minY = Math.min(p[1],minY);
      maxX = Math.max(p[0],maxX);
      maxY = Math.max(p[1],maxY);
   }
 });
 // now get the map width and heigth in its local coords
 const mapWidth = maxX-minX;
 const mapHeight = maxY-minY;
 const mapCenterX = (maxX + minX) /2;
 const mapCenterY = (maxY + minY) /2;

 // to find the scale that will fit the canvas get the min scale to fit height or width
 const scale = Math.min(canvas.width / mapWidth,canvas.height / mapHeight);

 // Now you can draw the map centered on the cavas
 ctx.beginPath();
 myPoints.forEach(p => {
      ctx.lineTo(
          (p[0] - mapCenterX) * scale + canvas.width /2 ,
          (p[1] - mapCenterY) * scale + canvas.height / 2
      );
 });
 ctx.stroke();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { border : 2px solid black; }</code>```

<canvas id="canvas" width =300 height = 200></canvas>```

Title: Draw polygon canvas from coordinates map

Body:
How to transform coordinates map to point canvas?

I have a map leaflet Map leaflet
 and when i select polygon, i want to draw the polygon with canvas html5

I have coordinates like this :

[[2.809510437833253,49.408625488749216],[2.8095461924850422,49.40864172401838],[2.8095226856172806,49.40866595550704],[2.809565304449213,49.40868849340382],[2.8097185865450465,49.40858536874469],[2.809677338568488,49.40856463072128],[2.8096442193374154,49.408580757620854],[2.809609885351463,49.40855283978645],[2.809510437833253,49.408625488749216]]

The difficulty is how to get points from map coordinates

This example to display polygon canvas :

<!DOCTYPE html>

<svg height="110" width="200">
<polygon points="130,0 0,160 0,485 270,645 560,485 560,160"/>
</svg>

Thanks for your help.

Body:
Map projections

Difficult problem

The problem with the earth is that is is not flat, and most of what we humans use to draw and render to tends to be flat. To fix the problem we accept some deformation of what the map represents by applying a projection from the round Earth to the flat map. There are many many different types of projections, a common one is the mercator projection (see google maps), it distorts area the further south and north of the equator you are. But it does this to maintain direction. You can put a compass on a mercator projected map and get an accurate bearing, but you can't take a ruler and measure the distance.

But size matters, easy solution

But there is one saving grace in all this. We humans are tiny compared to the Earth and for local maps the distortion caused by the curvature of the Earth is so small to be irrelevant.

If you have a set of coordinates in a small area (eg a city and suburbs) you can just use a square projection. Where lat and long are x and y on the grid of rendering surface.

Step by step

How to take some mapping data and fit it to a canvas maintaining the aspect.

So you have a set of points and a canvas context

<canvas id="canvas" width =300 height = 200></canvas>
ctx = canvas.getContext("2d");

 var myPoints = [[2.809510437833253,49.408625488749216],[2.8095461924850422,49.40864172401838],[2.8095226856172806,49.40866595550704],[2.809565304449213,49.40868849340382],[2.8097185865450465,49.40858536874469],[2.809677338568488,49.40856463072128],[2.8096442193374154,49.408580757620854],[2.809609885351463,49.40855283978645],[2.809510437833253,49.408625488749216]]

Then find the extent of those points (the min and max coordinates)

var minX,minY,maxX,maxY;
myPoints.forEach((p,i) => {
   if(i === 0){ // if first point
      minX = maxX = p[0];
      minY = maxY = p[1];
   }else{
      minX = Math.min(p[0],minX);
      minY = Math.min(p[1],minY);
      maxX = Math.max(p[0],maxX);
      maxY = Math.max(p[1],maxY);
   }
 });
 // now get the map width and heigth in its local coords
 const mapWidth = maxX-minX;
 const mapHeight = maxY-minY;
 const mapCenterX = (maxX + minX) /2;
 const mapCenterY = (maxY + minY) /2;

Now you have the map extent you can scale it to the canvas by finding the smallest scale to fit both width and height.

 const scale = Math.min(canvas.width / mapWidth,canvas.height / mapHeight);

Now you can draw the map first subtracting the map center, then scaling it up, then moving ot to the canvas center.

 ctx.beginPath();
 myPoints.forEach(p => {
      ctx.lineTo(
          (p[0] - mapCenterX) * scale + canvas.width /2 ,
          (p[1] - mapCenterY) * scale + canvas.height / 2
      );
 });
 ctx.stroke();

And a working example.

 ctx = canvas.getContext("2d");

 var myPoints = [[2.809510437833253,49.408625488749216],[2.8095461924850422,49.40864172401838],[2.8095226856172806,49.40866595550704],[2.809565304449213,49.40868849340382],[2.8097185865450465,49.40858536874469],[2.809677338568488,49.40856463072128],[2.8096442193374154,49.408580757620854],[2.809609885351463,49.40855283978645],[2.809510437833253,49.408625488749216]]

var minX,minY,maxX,maxY;
myPoints.forEach((p,i) => {
   if(i === 0){ // if first point
      minX = maxX = p[0];
      minY = maxY = p[1];
   }else{
      minX = Math.min(p[0],minX);
      minY = Math.min(p[1],minY);
      maxX = Math.max(p[0],maxX);
      maxY = Math.max(p[1],maxY);
   }
 });
 // now get the map width and heigth in its local coords
 const mapWidth = maxX-minX;
 const mapHeight = maxY-minY;
 const mapCenterX = (maxX + minX) /2;
 const mapCenterY = (maxY + minY) /2;

 // to find the scale that will fit the canvas get the min scale to fit height or width
 const scale = Math.min(canvas.width / mapWidth,canvas.height / mapHeight);

 // Now you can draw the map centered on the cavas
 ctx.beginPath();
 myPoints.forEach(p => {
      ctx.lineTo(
          (p[0] - mapCenterX) * scale + canvas.width /2 ,
          (p[1] - mapCenterY) * scale + canvas.height / 2
      );
 });
 ctx.stroke();

canvas { border : 2px solid black; }

<canvas id="canvas" width =300 height = 200></canvas>


问:
std::ptr_fun replacement for c++17
I am using std::ptr_fun as follows:

```<code>static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}
</code>```

as presented in this answer.

However this does not compile with C++17 (using Microsoft Visual Studio 2017), with the error:

```<code>error C2039: 'ptr_fun': is not a member of 'std'
</code>```

How can this be fixed?

答:
You use a lambda:

```<code>static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c) {return !std::isspace(c);}));
    return s;
}
</code>```

The answer you cited is from 2008, well before C++11 and lambdas existed.

Title: std::ptr_fun replacement for c++17

Body:
I am using std::ptr_fun as follows:

static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
    return s;
}

as presented in this answer.

However this does not compile with C++17 (using Microsoft Visual Studio 2017), with the error:

error C2039: 'ptr_fun': is not a member of 'std'

How can this be fixed?

Body:
You use a lambda:

static inline std::string &ltrim(std::string &s) {
    s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int c) {return !std::isspace(c);}));
    return s;
}

The answer you cited is from 2008, well before C++11 and lambdas existed.


问:
Design patterns to avoid
A lot of people seem to agree, that the Singleton pattern has a number of drawbacks and some even suggest avoiding the pattern entirely. There's an excellent discussion here. Please direct any comments about the Singleton pattern to that question.

My question: Are there other design patterns, that should be avoided or used with great care?

答: I believe the observer pattern has a lot to answer for, it works in very general cases, but as systems become more complex it becomes a nightmare, needing OnBefore(), OnAfter() notifications, and often posting of asynchronous tasks to avoid re-entrancy.  A much better solution is to develop a system of automatic dependency analysis that instruments all object accesses (with read-barriers) during calculations and automatically creates an edge in a dependency graph.</p>

OwnerDisplayName: Brian Rasmussen

Title: Design patterns to avoid

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: Jesse Pepper


答:
If one usage is WCF and another usage is internal to your app, then you can annotate the class appropriately with [DataMember] such that only the desired properties are exposed. If you have two different WCF scenarios, then I would introduce a new class (or classes) to represent each set of return data, probably adding an implicit conversion operator (from the entity to the DTO), so that you can do:

```<code>public CustomerLite GetCustomer(int id) {
    Customer cust = SomeTier.GetCustomer(id);
    return cust; // note cust is Customer but we are returning CustomerLite
}
</code>```

Title: Exposing different view of Class

Body:
Is it possible to give different view of a Class . For example , i have Account class , i want expose this data using WCF. For different method call i want expose different property of Account class.Suppose for particular call i want expose only UserName and Password, for
another call i want expose Email and Address. Should i have to write different class or
i can expose needed property to client

Body:
If one usage is WCF and another usage is internal to your app, then you can annotate the class appropriately with [DataMember] such that only the desired properties are exposed. If you have two different WCF scenarios, then I would introduce a new class (or classes) to represent each set of return data, probably adding an implicit conversion operator (from the entity to the DTO), so that you can do:

public CustomerLite GetCustomer(int id) {
    Customer cust = SomeTier.GetCustomer(id);
    return cust; // note cust is Customer but we are returning CustomerLite
}


问:
Why is my css showing ���?

System details:

  Server: Apache, Ubuntu 16.02

  Client: Windows 10, Chrome

My apache config file looks as follows:

```<code><VirtualHost *:80>
       ServerName mycoolsiteA.mydomain.com
       ServerAlias mycoolsiteB.mydomain.com

       Alias /static /var/www/python/mysite/static
       Alias /templates /var/www/python/mysite/templates

       WSGIDaemonProcess my_app user=www-data group=www-data threads=5
       WSGIScriptAlias / /var/www/python/mysite/start.py
       WSGIScriptReloading On

       <Directory /var/www/python/mysite>
               WSGIProcessGroup my_app
               WSGIApplicationGroup %{GLOBAL}
               order deny,allow
               Allow from all
       </Directory>
</VirtualHost>
</code>```

When I load the css in a browser it is showing the following. However, this is quite random. It "sometimes" works, and sometimes does not.

My example url is this:
https://mycoolsiteA.mydomain.com/static/css/bs/bootstrap.min.css

We do have a Firewall appliance which auto-redirects http to https, but I'm loading the css directly with https.

And the result looks like this:

Yet, if I refresh several times, or add a r=number on the end, it will clear the cache and load. But, it will do it again randomly until I clear the cache again.

Here it is loaded and working:

Any thoughts, direction on where to look to fix this?

答:
Welcome to the fun world of UTF-8!

I've seen this dozens of times in PHP (see UTF-8 all the way through). What you're experiencing is almost certainly a UTF-8 file being delivered as some other character encoding (or vice-versa). I downloaded Bootstrap and Notepad++ identifies them as ANSI encoded. Your web server might be forcing that to use UTF-8. Look at the response headers for something like this

```<code>Content-Type: text/css; charset=UTF-8
</code>```

So your web server is saying it's UTF-8 but it's really not. At which point your browser starts vomiting out �, meaning it doesn't recognize the character.

There's a couple of ways to deal with this if that's the case.

Re-encode the file as UTF-8 (Notepad++ can do this for you)

Stop passing a default UTF-8. Your browser will try to identify the encoding

Just for kicks, try loading the CSS directly from the MaxCDN servers

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

They do not pass a UTF-8 header

Title: Why is my css showing ���?

Body:
System details:

  Server: Apache, Ubuntu 16.02

  Client: Windows 10, Chrome

My apache config file looks as follows:

<VirtualHost *:80>
       ServerName mycoolsiteA.mydomain.com
       ServerAlias mycoolsiteB.mydomain.com

       Alias /static /var/www/python/mysite/static
       Alias /templates /var/www/python/mysite/templates

       WSGIDaemonProcess my_app user=www-data group=www-data threads=5
       WSGIScriptAlias / /var/www/python/mysite/start.py
       WSGIScriptReloading On

       <Directory /var/www/python/mysite>
               WSGIProcessGroup my_app
               WSGIApplicationGroup %{GLOBAL}
               order deny,allow
               Allow from all
       </Directory>
</VirtualHost>

When I load the css in a browser it is showing the following. However, this is quite random. It "sometimes" works, and sometimes does not.

My example url is this:
https://mycoolsiteA.mydomain.com/static/css/bs/bootstrap.min.css

We do have a Firewall appliance which auto-redirects http to https, but I'm loading the css directly with https.

And the result looks like this:

Yet, if I refresh several times, or add a r=number on the end, it will clear the cache and load. But, it will do it again randomly until I clear the cache again.

Here it is loaded and working:

Any thoughts, direction on where to look to fix this?

Body:
Welcome to the fun world of UTF-8!

I've seen this dozens of times in PHP (see UTF-8 all the way through). What you're experiencing is almost certainly a UTF-8 file being delivered as some other character encoding (or vice-versa). I downloaded Bootstrap and Notepad++ identifies them as ANSI encoded. Your web server might be forcing that to use UTF-8. Look at the response headers for something like this

Content-Type: text/css; charset=UTF-8

So your web server is saying it's UTF-8 but it's really not. At which point your browser starts vomiting out �, meaning it doesn't recognize the character.

There's a couple of ways to deal with this if that's the case.

Re-encode the file as UTF-8 (Notepad++ can do this for you)

Stop passing a default UTF-8. Your browser will try to identify the encoding

Just for kicks, try loading the CSS directly from the MaxCDN servers

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

They do not pass a UTF-8 header


问:
Export-Csv multiple forloop results
I have multiple forloops running with different variables pulling from .txt files. I want to export this all into a single csv file while having it look just like it does in powershell. Attached is what I get for powershell output and I would like to see the first write-host as a header in excel, followed by server name in column 1 and UP or DOWN in column 2 beneath it.
Powershell

```<code>Write-Host "Starting SVR2000MS" -ForegroundColor Yellow
$servers = Get-Content C:\Users\username\Desktop\subfolder\SVR2000.txt
foreach($server in $servers){
    if (Test-Connection -ComputerName $server -Count 1 -ErrorAction SilentlyContinue) {
    Write-Host "$server, UP" -ForegroundColor Green
}
    else{
    Write-Host "$server, DOWN" -ForegroundColor Red
    }
}

Write-Host "Starting SVR2003DC" -ForegroundColor Yellow
$servers = Get-Content C:\Users\username\Desktop\subfolder\SVR2003.txt
foreach($server in $servers){
    if (Test-Connection -ComputerName $server -Count 1 -ErrorAction SilentlyContinue) {
    Write-Host "$server, UP" -ForegroundColor Green
}
    else{
    Write-Host "$server, DOWN" -ForegroundColor Red
    }
}
</code>```

答:
Simple way:

You just print it and put it in a file

Instead of Write-Host ..., do:

```<code> "$server,UP" | Out-File test.csv -append
</code>```

You can have more elaborate options by using objects, but it may be overkill for your needs.

If you want a clean file, you need to delete it at the beginning, because of -append.

BTW, no space after comma in a CSV :)

Edit:

Write-Host writes specifically ... to the host, i.e. the console, so you cannot redirect it elsewhere.

Title: Export-Csv multiple forloop results

Body:
I have multiple forloops running with different variables pulling from .txt files. I want to export this all into a single csv file while having it look just like it does in powershell. Attached is what I get for powershell output and I would like to see the first write-host as a header in excel, followed by server name in column 1 and UP or DOWN in column 2 beneath it.
Powershell

Write-Host "Starting SVR2000MS" -ForegroundColor Yellow
$servers = Get-Content C:\Users\username\Desktop\subfolder\SVR2000.txt
foreach($server in $servers){
    if (Test-Connection -ComputerName $server -Count 1 -ErrorAction SilentlyContinue) {
    Write-Host "$server, UP" -ForegroundColor Green
}
    else{
    Write-Host "$server, DOWN" -ForegroundColor Red
    }
}

Write-Host "Starting SVR2003DC" -ForegroundColor Yellow
$servers = Get-Content C:\Users\username\Desktop\subfolder\SVR2003.txt
foreach($server in $servers){
    if (Test-Connection -ComputerName $server -Count 1 -ErrorAction SilentlyContinue) {
    Write-Host "$server, UP" -ForegroundColor Green
}
    else{
    Write-Host "$server, DOWN" -ForegroundColor Red
    }
}

Body:
Simple way:

You just print it and put it in a file

Instead of Write-Host ..., do:

 "$server,UP" | Out-File test.csv -append

You can have more elaborate options by using objects, but it may be overkill for your needs.

If you want a clean file, you need to delete it at the beginning, because of -append.

BTW, no space after comma in a CSV :)

Edit:

Write-Host writes specifically ... to the host, i.e. the console, so you cannot redirect it elsewhere.


问:
Proper way to return private object in Python
I'm new to Python (and liking it so far) but have many years experience with OO languages like C++ and C# and consider myself a strong OO designer.

My understanding is that Python does not strictly enforce private object properties, but that by convention people expect that if you name a property with an underscore that they will know not to access it outside the class. OK, fair enough.

My question: if an object contains "private" object and I return it to a caller, should I make a copy so they can't mess it up? Or does Python automatically make a copy?

```<code># My Channel class has a dictionary of capabilities
class Channel(object):
    def __init__(self):
        self._capabilities = dict()
</code>```

If I do the following can the caller mess with my capabilities by messing with the returned dictionary?

```<code>@property
def capabilities(self):
    return self._capabilities
</code>```

Or should I do this and return a copy to protect myself?

```<code>@property
def capabilities(self):
    # I'm assuming that this creates a new copy of the dictionary
    return dict(self._capabilities)
</code>```

I am guessing that Python returns a reference so that the caller can indeed mess with my private dictionary (or list, or whatever) so I better make a copy first.

答:
I slept on it and realized I could just write a test and figure out my own answer. When I return an object (a dictionary in my test) then I get a reference to the actual private object. If I add an entry to what gets returned then it adds an entry to the original object's dictionary.

So if I want to protect against that then I need to create a copy and return.

```<code>    @property
    def capabilities(self):
        # I'm assuming that this creates a new copy of the dictionary
        return dict(self._capabilities)
</code>```

I think part of my original question was whether this approach was the common pattern for Python. It is in C# and I intend to do this as a general practice.

Body:
I'm new to Python (and liking it so far) but have many years experience with OO languages like C++ and C# and consider myself a strong OO designer.

My understanding is that Python does not strictly enforce private object properties, but that by convention people expect that if you name a property with an underscore that they will know not to access it outside the class. OK, fair enough.

My question: if an object contains "private" object and I return it to a caller, should I make a copy so they can't mess it up? Or does Python automatically make a copy?

# My Channel class has a dictionary of capabilities
class Channel(object):
    def __init__(self):
        self._capabilities = dict()

If I do the following can the caller mess with my capabilities by messing with the returned dictionary?

@property
def capabilities(self):
    return self._capabilities

Or should I do this and return a copy to protect myself?

@property
def capabilities(self):
    # I'm assuming that this creates a new copy of the dictionary
    return dict(self._capabilities)

I am guessing that Python returns a reference so that the caller can indeed mess with my private dictionary (or list, or whatever) so I better make a copy first.

Body:
I slept on it and realized I could just write a test and figure out my own answer. When I return an object (a dictionary in my test) then I get a reference to the actual private object. If I add an entry to what gets returned then it adds an entry to the original object's dictionary.

So if I want to protect against that then I need to create a copy and return.

    @property
    def capabilities(self):
        # I'm assuming that this creates a new copy of the dictionary
        return dict(self._capabilities)

I think part of my original question was whether this approach was the common pattern for Python. It is in C# and I intend to do this as a general practice.


问:
Testing vuex action that contains an async
[This is a Vue app, using Vuex, created with vue-cli, using mocha, chai, karma, sinon]

I'm trying to create tests for my vuex state and I DON'T want to use a mock -- one of my big goals for these tests is to also test the API that data is coming from.

I am trying to follow the docs for chai-as-promised.

This is a simplification of the vuex action I'm trying to test:

```<code>const actions = {
  login: (context, payload) => {
    context.commit('setFlashMessage', "");
    axios.get("https://first-api-call")
      .then((response) => {
        axios.post("https://second-api-call")
          .then((response) => {
            router.push({ name: "Home"});
            context.commit('setFlashMessage', "Logged in successfully");
            context.commit('setLogin', response.data);
        });
    },
</code>```

Notice that the login action has two promises and doesn't return anything. The login action does two things: it sets some state and it changes the route.

The example that I've seen that using chai-as-promised expects that the promise is returned. That is:

```<code>var result = systemUnderTest();
return expect(result).to.eventually.equal(blah);
</code>```

But in my case, login() doesn't return anything, and I'm not sure what I would return if it did.

This is what I have so far:

```<code>import store from '@/src/store/store'
describe('login', () => {
  it('bad input', () => {
    store.login({ username: "abcd", password: ""});
    // What is the test I should use?
  }
}
</code>```

答: I would return the login response message and make two tests. One to make sure that invalid credentials return a failure message and one to make sure that valid credentials login successfully</p>

Body:
[This is a Vue app, using Vuex, created with vue-cli, using mocha, chai, karma, sinon]

I'm trying to create tests for my vuex state and I DON'T want to use a mock -- one of my big goals for these tests is to also test the API that data is coming from.

I am trying to follow the docs for chai-as-promised.

This is a simplification of the vuex action I'm trying to test:

const actions = {
  login: (context, payload) => {
    context.commit('setFlashMessage', "");
    axios.get("https://first-api-call")
      .then((response) => {
        axios.post("https://second-api-call")
          .then((response) => {
            router.push({ name: "Home"});
            context.commit('setFlashMessage', "Logged in successfully");
            context.commit('setLogin', response.data);
        });
    },

Notice that the login action has two promises and doesn't return anything. The login action does two things: it sets some state and it changes the route.

The example that I've seen that using chai-as-promised expects that the promise is returned. That is:

var result = systemUnderTest();
return expect(result).to.eventually.equal(blah);

But in my case, login() doesn't return anything, and I'm not sure what I would return if it did.

This is what I have so far:

import store from '@/src/store/store'
describe('login', () => {
  it('bad input', () => {
    store.login({ username: "abcd", password: ""});
    // What is the test I should use?
  }
}


问:
Entity Framework 6 Mapping classes to a table based on a value in a column
A table has similar but unrelated data records

```<code>+------------+------------+-----------+-------------+----------------------+
| RecordType |    Name    |  Surname  | DateOfBirth | DateOfIncorporation  |
+------------+------------+-----------+-------------+----------------------+
| Person     | Luke       | SkyWalker | 1/1/1017    |                      |
| Company    | Jedi Order |           |             | 1/1/101              |
+------------+------------+-----------+-------------+----------------------+
</code>```

I would like to use two classes to handle this rather than having to always look at the RecordType (Person or Company).

This is an existing table and there is not an option to split the table in to two (ironically, this table was created using code first entity framework, but the table now cannot be modified)

Is there a way I can do this in entity framework ?

That is, when I use Person class (context.Persons) I only get records with RecordType "Person" and when I use Company class (context.Companies) I only get records with RecordType "Comapany" -

```<code>class Person
{
string RecordType {get;set;} //This will only have "Person"
string Name {get;set;}
string Surname {get;set;}
DateTime DateOfBirth {get;set;}
}

class Company
{
string RecordType {get;set;} //This will only have Company
string Name {get;set;}
DateTime DateOfIncorporation {get;set;}
}
</code>```

答:
Yes, this is definitely possible with entity framework. The best guides to this I have found are at this link.

EDIT

You're currently using Table-Per-Hierarchy, but if you follow that guide then you can do it in such a way as to be able to query efficiently over either Persons or Companies with strong types. For example,

```<code>var allRecords = myDbContext.RecordsTable;
var personRecords = allRecords.OfType<Person>();
var companyRecords = allRecords.OfType<Company>();
</code>```

One nice perk of using this method is that calling OfType() does not force execution, so you can use it on an IQueryable<T> without fetching records too early. If your classes share all or almost all of the same properties, this is usually a good strategy. Otherwise, you'll want to use one of the other inheritance strategies.

Body:
A table has similar but unrelated data records

+------------+------------+-----------+-------------+----------------------+
| RecordType |    Name    |  Surname  | DateOfBirth | DateOfIncorporation  |
+------------+------------+-----------+-------------+----------------------+
| Person     | Luke       | SkyWalker | 1/1/1017    |                      |
| Company    | Jedi Order |           |             | 1/1/101              |
+------------+------------+-----------+-------------+----------------------+

I would like to use two classes to handle this rather than having to always look at the RecordType (Person or Company).

This is an existing table and there is not an option to split the table in to two (ironically, this table was created using code first entity framework, but the table now cannot be modified)

Is there a way I can do this in entity framework ?

That is, when I use Person class (context.Persons) I only get records with RecordType "Person" and when I use Company class (context.Companies) I only get records with RecordType "Comapany" -

class Person
{
string RecordType {get;set;} //This will only have "Person"
string Name {get;set;}
string Surname {get;set;}
DateTime DateOfBirth {get;set;}
}

class Company
{
string RecordType {get;set;} //This will only have Company
string Name {get;set;}
DateTime DateOfIncorporation {get;set;}
}

Body:
Yes, this is definitely possible with entity framework. The best guides to this I have found are at this link.

EDIT

You're currently using Table-Per-Hierarchy, but if you follow that guide then you can do it in such a way as to be able to query efficiently over either Persons or Companies with strong types. For example,

var allRecords = myDbContext.RecordsTable;
var personRecords = allRecords.OfType<Person>();
var companyRecords = allRecords.OfType<Company>();

One nice perk of using this method is that calling OfType() does not force execution, so you can use it on an IQueryable<T> without fetching records too early. If your classes share all or almost all of the same properties, this is usually a good strategy. Otherwise, you'll want to use one of the other inheritance strategies.


问:
Building 64bit Qt on 32bit Xp computer
I'm trying to build Qt in a shared 64 bit mode on my 32bit XP system.

I can configure the QMake and start the 64bit build.  The problem is that when the build starts, the first thing that happens in that the process builds ui, moc and rcc utility compilers in 64 bit mode, then tries to run them on my 32bit machine.

Does anyone know how to configure the build so that it does not build those compilers first?

答:
I don't think Qt support cross-compilation on Windows.

I suggest doing it the other way around, by using a 64bit machine (and a 64 bit version of Windows) to build the 64bit and 32bit versions.

Title: Building 64bit Qt on 32bit Xp computer


问:
Filename of the excel file upon downloading in Codeigniter
Is it possible to set the filename of a excel to a name from database upon downloading  ?</p>

答:
Your question is not precise, but I guess, probably you want to set the name of an Excell's file possible to download from your page to the name saved in the database.

In CodeIgniter it's possible to use Download Helper.

First select from the DataBase the name you want to show for users and save it to a variable. For example:

$name.

Load Download Helper:

$this->load->helper('download');

Use function force_download() to serve your Excel file for user with your name from DB:

$data = file_get_contents($excell_file_path); // Read the file's contents

force_download($name, $data);


答:
Just use a lambda:

```<code>[](unsigned char c){ return !std::isspace(c); }
</code>```

Note that I changed the argument type to unsigned char, see the notes for std::isspace for why.

std::ptr_fun was deprecated in C++11, and will be removed completely in C++17.

Title: std::ptr_fun replacement for c++17

Body:
Just use a lambda:

[](unsigned char c){ return !std::isspace(c); }

Note that I changed the argument type to unsigned char, see the notes for std::isspace for why.

std::ptr_fun was deprecated in C++11, and will be removed completely in C++17.


问:
How to route an array of params in Rails
So I want to pass through an array of params to a "testers" route in Rails. My table for testers currently looks like this:

```<code>class CreateTesters < ActiveRecord::Migration[5.1]
  def change
    create_table :testers do |t|
      t.integer :testerID
      t.string :firstName
      t.string :lastName
      t.string :country
      t.datetime :lastLogin

      t.timestamps
    end
  end
end
</code>```

The url I want to make a request to looks like this: http://localhost:3000/testers?tester_id[]=1&tester_id[]=2&country[]=US

My server is correctly identifying that I've passed an array of params, but my issue is that it's hitting the index route and simply returning all the testers in my database.

How do I either get Rails to recognize this as a 'show` request, or create a custom route for this type of url?

答:
As per your comments, ideal of doing it is using your index action itself..

```<code>def index
  @testers = Tester.data(params[:tester_ids])
end
</code>```

In your testers.rb model

```<code>scope :data, ->(ids) { ids.present? ? where(id: params[:tester_ids].split(',')) : all }
</code>```

and your url will look like

http://localhost:3000/testers for all and

http://localhost:3000/testers?tester_ids=1,2,3 for filtered testers

Body:
So I want to pass through an array of params to a "testers" route in Rails. My table for testers currently looks like this:

class CreateTesters < ActiveRecord::Migration[5.1]
  def change
    create_table :testers do |t|
      t.integer :testerID
      t.string :firstName
      t.string :lastName
      t.string :country
      t.datetime :lastLogin

      t.timestamps
    end
  end
end

The url I want to make a request to looks like this: http://localhost:3000/testers?tester_id[]=1&tester_id[]=2&country[]=US

My server is correctly identifying that I've passed an array of params, but my issue is that it's hitting the index route and simply returning all the testers in my database.

How do I either get Rails to recognize this as a 'show` request, or create a custom route for this type of url?

Body:
As per your comments, ideal of doing it is using your index action itself..

def index
  @testers = Tester.data(params[:tester_ids])
end

In your testers.rb model

scope :data, ->(ids) { ids.present? ? where(id: params[:tester_ids].split(',')) : all }

and your url will look like

http://localhost:3000/testers for all and

http://localhost:3000/testers?tester_ids=1,2,3 for filtered testers


问:
Download a pdf using ajax and spring mvc doesn't work
I'm trying to implement an ajax download. This is my code for the ajax request:

```<code>$('#download').click(function(){
                    $.ajax({
                        url: '${downloadPath}',
                        type: 'GET',
                        data: {${_csrf.parameterName}:'${_csrf.token}'},
                        success: function (res) {
                        }
                    });
                });
</code>```

And this is my controller's method:

```<code>    @Secured("IS_AUTHENTICATED")
    @RequestMapping(value="download/{id}", method=RequestMethod.GET, produces="application/pdf")
    @ResponseBody
    public void download(@PathVariable(value="id") final Long id, HttpServletResponse response) throws IOException {

        CheckList checkList = checkListService.findById(id);
//      byte[] byteItem  = checkListService.getFileByIdDocument(id);

        File f = new File(VariabiliGlobali.PATH_CHECKLIST+checkList.getPratica().getId()+"/"+id);
        ServletOutputStream out = response.getOutputStream();

        response.setContentType("application/pdf");
        response.setContentLength((int)f.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + f.getName() + "\"");

        FileInputStream in = new FileInputStream(f);
        byte[] buffer = new byte[4096];

        int length;
        while( (length = in.read(buffer) ) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }
</code>```

I can see the pdf inside the response:

But my browser (Chrome) doens't do anything.

Where am I wrong? How can I dowload it?

答:
Set your content type in header. So browsers handles the pdf.

```<code>headers.setContentType(MediaType.parseMediaType("application/pdf"));
</code>```

Below is the sample code.

```<code>@Secured("IS_AUTHENTICATED")
@RequestMapping(value="download/{id}", method=RequestMethod.GET, produces="application/pdf")
public ResponseEntity<?> download(@PathVariable(value="id") final Long id, HttpServletResponse response) throws IOException {
    List<SampleDto> reportData = new ArrayList<SampleDto>();

    HttpHeaders headers = new HttpHeaders();

    if (null == reportData || reportData.size() == 0) {
        return new ResponseEntity<byte[]>(null, headers, HttpStatus.NO_CONTENT);
    }

    byte[] contents = writePdfContentToBytes();//Here you should your code to get content in bytes.

    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.setContentDispositionFormData("inline", "Report.pdf");
    return new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
}
</code>```

Body:
I'm trying to implement an ajax download. This is my code for the ajax request:

$('#download').click(function(){
                    $.ajax({
                        url: '${downloadPath}',
                        type: 'GET',
                        data: {${_csrf.parameterName}:'${_csrf.token}'},
                        success: function (res) {
                        }
                    });
                });

And this is my controller's method:

    @Secured("IS_AUTHENTICATED")
    @RequestMapping(value="download/{id}", method=RequestMethod.GET, produces="application/pdf")
    @ResponseBody
    public void download(@PathVariable(value="id") final Long id, HttpServletResponse response) throws IOException {

        CheckList checkList = checkListService.findById(id);
//      byte[] byteItem  = checkListService.getFileByIdDocument(id);

        File f = new File(VariabiliGlobali.PATH_CHECKLIST+checkList.getPratica().getId()+"/"+id);
        ServletOutputStream out = response.getOutputStream();

        response.setContentType("application/pdf");
        response.setContentLength((int)f.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + f.getName() + "\"");

        FileInputStream in = new FileInputStream(f);
        byte[] buffer = new byte[4096];

        int length;
        while( (length = in.read(buffer) ) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();
    }

I can see the pdf inside the response:

But my browser (Chrome) doens't do anything.

Where am I wrong? How can I dowload it?

Body:
Set your content type in header. So browsers handles the pdf.

headers.setContentType(MediaType.parseMediaType("application/pdf"));

Below is the sample code.

@Secured("IS_AUTHENTICATED")
@RequestMapping(value="download/{id}", method=RequestMethod.GET, produces="application/pdf")
public ResponseEntity<?> download(@PathVariable(value="id") final Long id, HttpServletResponse response) throws IOException {
    List<SampleDto> reportData = new ArrayList<SampleDto>();

    HttpHeaders headers = new HttpHeaders();

    if (null == reportData || reportData.size() == 0) {
        return new ResponseEntity<byte[]>(null, headers, HttpStatus.NO_CONTENT);
    }

    byte[] contents = writePdfContentToBytes();//Here you should your code to get content in bytes.

    headers.setContentType(MediaType.parseMediaType("application/pdf"));
    headers.setContentDispositionFormData("inline", "Report.pdf");
    return new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
}


问:
How to find the entries in one table not like those in another
I have a table called whitelist_email which looks like this

```<code>+----+---------------------+-------------+
| id | email_suffix        | create_date |
+----+---------------------+-------------+
|  1 | stackoverflow.com   | 2017-07-07  |
|  2 | example.com         | 2017-07-07  |
</code>```

and a table called user_info with a field called verified_email. I would like to write a command to find all the rows in user_info whose verified_email field does not end with any entry in whitelist_email to give me a list of new users who need to be vetted. The best I can do with my limited knowledge is

```<code>SELECT verified_email
FROM user_info
WHERE verified_email IN (
    SELECT email_suffix
    FROM whitelist_email
);
</code>```

答:
One approach is to LEFT JOIN the user_info table to the whitelist_email table on the condition that the verified email address ends in a whitelisted suffix, and then retain only emails which did not match to any known whitelisted email suffix.

```<code>SELECT t1.*
FROM user_info t1
LEFT JOIN whitelist_email t2
    ON t1.verified_email LIKE CONCAT('%', t2.email_suffix)
WHERE t2.id IS NULL
</code>```

Body:
I have a table called whitelist_email which looks like this

+----+---------------------+-------------+
| id | email_suffix        | create_date |
+----+---------------------+-------------+
|  1 | stackoverflow.com   | 2017-07-07  |
|  2 | example.com         | 2017-07-07  |

and a table called user_info with a field called verified_email. I would like to write a command to find all the rows in user_info whose verified_email field does not end with any entry in whitelist_email to give me a list of new users who need to be vetted. The best I can do with my limited knowledge is

SELECT verified_email
FROM user_info
WHERE verified_email IN (
    SELECT email_suffix
    FROM whitelist_email
);

Body:
One approach is to LEFT JOIN the user_info table to the whitelist_email table on the condition that the verified email address ends in a whitelisted suffix, and then retain only emails which did not match to any known whitelisted email suffix.

SELECT t1.*
FROM user_info t1
LEFT JOIN whitelist_email t2
    ON t1.verified_email LIKE CONCAT('%', t2.email_suffix)
WHERE t2.id IS NULL


问:
How can hide the textbox on basis on checkbox in JSP
In my JSP page two fields one is textbox and one is checkbox, I tried with     j query and java script also for hiding the textbox on checked of checkbox but it is not reflecting. Below I am mentioning code here

```<code><p class="contact"> <input id="check" name="check" value="check" style="margin-right: 10px" type="checkbox" tabindex="11">
        <label for="name"> Not Yet Registered</label> </p>

        <p class= "reg"><label for="reg">Register No.</label></p><br>
        <input id = "reg" maxlength="15"  name= "reg" placeholder="Reg No." type ="text" tabindex="12"><br><br>
</code>```

J query

```<code>$('#check').click(function() {
  $('.reg')[this.checked ? "hide" : "show"]();
});
</code>```

Kindly Help me out

答:
Use change event

```<code>$('#check').change(function() {
       $(this).is(":checked")?$('.reg').hide():$('.reg').show()
 });
</code>```

Body:
In my JSP page two fields one is textbox and one is checkbox, I tried with     j query and java script also for hiding the textbox on checked of checkbox but it is not reflecting. Below I am mentioning code here

 <input id="check" name="check" value="check" style="margin-right: 10px" type="checkbox" tabindex="11">
         Not Yet Registered

Register No.

        <input id = "reg" maxlength="15"  name= "reg" placeholder="Reg No." type ="text" tabindex="12">

J query

$('#check').click(function() {
  $('.reg')[this.checked ? "hide" : "show"]();
});

Kindly Help me out

Body:
Use change event

$('#check').change(function() {
       $(this).is(":checked")?$('.reg').hide():$('.reg').show()
 });


问:
Plot a graph using python2.7 for a program starting and ending at various timestamps
I have a program that is starting and ending at various times and I have captured the timings.

Example:

```<code>[('05:43:44', '05:43:51'), ('05:59:32', '05:59:39'), ('06:14:46', '06:41:03'), ('06:41:16', '06:42:57')]
</code>```

The start and end times are paired together for an instance in a tuple as shown below.

```<code>{ Example [(1st start time, 1st end time), (2nd start time, 2nd end time) ..and so on }
</code>```

I want to plot the curve for the start, end times for the program and a meaningful graph. Please provide me ideas how to do plot this in Python 2.7.

I tried to run this, but get Value Error

Test Data:

  [('05:43:44', '05:59:32', '06:14:46', '06:41:16'),('05:43:51', '05:59:39', '06:41:03', '06:42:57')]*

```<code>import matplotlib.pyplot as plt
plt.scatter(*zip(*zipped_files))
plt.show()
</code>```

Error:

```<code>ValueErrorTraceback (most recent call last)
<ipython-input-84-713cb20ee252> in <module>()
1 import matplotlib.pyplot as plt
2
----> 3 plt.scatter(*zip(*zipped_files))
4 plt.show()
ValueError: invalid literal for float(): 05:43:44
</code>```

答:
You need to convert your data to datetime objects using the datetime module. Below is a complete example for the data you provided:

```<code>import matplotlib.pyplot as plt
import datetime

data = [('05:43:44', '05:59:32', '06:14:46', '06:41:16'),('05:43:51', '05:59:39', '06:41:03', '06:42:57')]

x = [i[0] for i in data]
y = [i[1] for i in data]

new_x = [datetime.datetime.strptime(i, "%H:%M:%S") for i in x]
new_y = [datetime.datetime.strptime(i, "%H:%M:%S") for i in y]

plt.plot(new_x,new_y)
plt.show()
</code>```

This produces the following graph:

You can better format the x axis by using autofmt_xdate():

```<code>fig, ax = plt.subplots()

ax.plot(new_x,new_y)
fig.autofmt_xdate()

plt.show()
</code>```

which gives:

Body:
I have a program that is starting and ending at various times and I have captured the timings.

Example:

[('05:43:44', '05:43:51'), ('05:59:32', '05:59:39'), ('06:14:46', '06:41:03'), ('06:41:16', '06:42:57')]

The start and end times are paired together for an instance in a tuple as shown below.

{ Example [(1st start time, 1st end time), (2nd start time, 2nd end time) ..and so on }

I want to plot the curve for the start, end times for the program and a meaningful graph. Please provide me ideas how to do plot this in Python 2.7.

I tried to run this, but get Value Error

Test Data:

  [('05:43:44', '05:59:32', '06:14:46', '06:41:16'),('05:43:51', '05:59:39', '06:41:03', '06:42:57')]*

import matplotlib.pyplot as plt
plt.scatter(*zip(*zipped_files))
plt.show()

Error:

ValueErrorTraceback (most recent call last)
<ipython-input-84-713cb20ee252> in <module>()
1 import matplotlib.pyplot as plt
2
----> 3 plt.scatter(*zip(*zipped_files))
4 plt.show()
ValueError: invalid literal for float(): 05:43:44

Body:
You need to convert your data to datetime objects using the datetime module. Below is a complete example for the data you provided:

import matplotlib.pyplot as plt
import datetime

data = [('05:43:44', '05:59:32', '06:14:46', '06:41:16'),('05:43:51', '05:59:39', '06:41:03', '06:42:57')]

x = [i[0] for i in data]
y = [i[1] for i in data]

new_x = [datetime.datetime.strptime(i, "%H:%M:%S") for i in x]
new_y = [datetime.datetime.strptime(i, "%H:%M:%S") for i in y]

plt.plot(new_x,new_y)
plt.show()

This produces the following graph:

You can better format the x axis by using autofmt_xdate():

fig, ax = plt.subplots()

ax.plot(new_x,new_y)
fig.autofmt_xdate()

plt.show()

which gives:


问:
How to get the values of ion-checkboxes in ionic?
I have 4 checkboxes. How do i get the values of those that are checked? What should i type in my typescript folder? I am trying to get the values so that i can save it into firebase. Here is my .html code.</p>

```<code><ion-content padding>
<ion-list>
<ion-item>
  <ion-label>Bedrooms</ion-label>
  <ion-checkbox [(ngModel)]="bedrooms" (ionChange)="updateBedrooms()"></ion-checkbox>
</ion-item>
<ion-item>
  <ion-label>Toilet</ion-label>
  <ion-checkbox [(ngModel)]="toilets" (ionChange)="updateToilets()">
</ion-checkbox>
</ion-item>
<ion-item>
  <ion-label>Living Room</ion-label>
  <ion-checkbox [(ngModel)]="livingroom" (ionChange)="updateLivingRoom()"></ion-checkbox>
</ion-item>
<ion-item>
  <ion-label>Kitchen</ion-label>
  <ion-checkbox [(ngModel)]="kitchen" (ionChange)="updateKitchen()">
</ion-checkbox>
</ion-item>
</ion-list>

<button (click)="onLoadTasks()" ion-button block>Choose Tasks<ion-
 icon name="arrow-dropright"></ion-icon></button>
</code>```

答:
try this for the 4 ones</p>

```<code>kitchen: boolean;

updateKitchen() {
  console.log('new state:' + this.kitchen);
}
</code>```

Body:
I have 4 checkboxes. How do i get the values of those that are checked? What should i type in my typescript folder? I am trying to get the values so that i can save it into firebase. Here is my .html code.

<ion-content padding>
<ion-list>
<ion-item>
  <ion-label>Bedrooms</ion-label>
  <ion-checkbox [(ngModel)]="bedrooms" (ionChange)="updateBedrooms()"></ion-checkbox>
</ion-item>
<ion-item>
  <ion-label>Toilet</ion-label>
  <ion-checkbox [(ngModel)]="toilets" (ionChange)="updateToilets()">
</ion-checkbox>
</ion-item>
<ion-item>
  <ion-label>Living Room</ion-label>
  <ion-checkbox [(ngModel)]="livingroom" (ionChange)="updateLivingRoom()"></ion-checkbox>
</ion-item>
<ion-item>
  <ion-label>Kitchen</ion-label>
  <ion-checkbox [(ngModel)]="kitchen" (ionChange)="updateKitchen()">
</ion-checkbox>
</ion-item>
</ion-list>

<button (click)="onLoadTasks()" ion-button block>Choose Tasks<ion-
 icon name="arrow-dropright"></ion-icon></button>

Body:
try this for the 4 ones

kitchen: boolean;

updateKitchen() {
  console.log('new state:' + this.kitchen);
}


问:
Exposing different view of Class
Is it possible to give different view of a Class . For example , i have Account class , i want expose this data using WCF. For different method call i want expose different property of Account class.Suppose for particular call i want expose only UserName and Password, for
another call i want expose Email and Address. Should i have to write different class or
i can expose needed property to client</p>

答:
If you want to expose multiple views of the same Account class, the answer is no (that I'm aware of).  Using the default DataContractSerializer, you can control which members are presented to the user only in a declarative manner.  This would allow you to customize the user's view in one way, but not multiples.

Instead, you can create one individual data contract class (which might take an Account as a constructor argument) for each "view" you wish to expose.

Title: Exposing different view of Class


问:
Error printing a vector with names
I have a vector named "list" and I want to print the names that are in the list but it says

operator "<<" matches these operand

operand types are: std::ostream << std::string

Why do I have this error and how cand I fix it?

```<code>#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;
vector<string> list;

vector<string> getAll() {     //I tried to use this function instread of "list"(list is used below) but it's the same result.
    return list;
}

int main() {

    list.push_back("Ion");
    list.push_back("Gabi");
    list.push_back("Sabrina");

    for (string i : list)
        std::cout << i;           //HERE

    }
</code>```

答:
You did not #include <string>. It is important.

Yes, I know you were able to instantiate the vector without it. No, that doesn't make a difference. It's pure chance, down to how your standard library implementation is laid out.

The function responsible for making << work on strings is inside that header.

Title: Error printing a vector with names

Body:
I have a vector named "list" and I want to print the names that are in the list but it says

operator "<<" matches these operand

operand types are: std::ostream << std::string

Why do I have this error and how cand I fix it?

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;
vector<string> list;

vector<string> getAll() {     //I tried to use this function instread of "list"(list is used below) but it's the same result.
    return list;
}

int main() {

    list.push_back("Ion");
    list.push_back("Gabi");
    list.push_back("Sabrina");

    for (string i : list)
        std::cout << i;           //HERE

    }


问:
Can workbooks uploaded to Tableau Public have filters?
I'm working with a Tableau workbook that contains a list of checkboxes the user can choose among. When I view the workbook in Tableau Desktop, I can enable filters to allow me to search by keyword, rather than scrolling down the long list of checkboxes:

However, when I upload the workbook to Tableau Public, there is no filter that appears above the checkboxes:

I checked the settings in Tableau Public, and I don't see an option to enable/disable filters:

Is this feature available in Tableau Public?

答:
I found the answer, and want to share it with folks who may come across this post.

The solution can be found in the "Edit Filter" menu, which you can access by clicking the arrow icon at the top of your list of items:

The workbook I had been using had the option "Use all" checked. When I switched to "Select from list" and republished the workbook to Tableau Public, I discovered that the filter option became available:

Again, hope this will be helpful for a future reader.


问:
How to change constraint in ms sql if other bit column is true
I'm building a codebook in database.
There I have three columns:

[IDReal] int identity (1,1), [IsReal] bit not null, [Code] nvarchar (20) null

Now I have somehow get that when user change [IsReal] to 1, that my column [Code] change to not null and unique and vice versa.

I was trying something like

```<code>CREATE TABLE [dbo].[sReal](
[IDReal] [int] IDENTITY(1,1) NOT NULL,
[Code] [nvarchar](20) NULL,
[IsReal] [bit] NOT NULL,

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [DEF_IsReal]  DEFAULT ((0)) FOR [IsReal]
    GO

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [CHNG_IsReal] IF [IsReal]=1 THEN (ALTER TABLE [dbo].[sReal] ALTER COLUMN [Code] [nvarchar](20) not null unique)
ELSE END IF
GO`
</code>```

This, of course, is not working and I can't use triggers or functions or procedures to solve that.

Is there any other solution for accomplishing what I'm trying to do.

答:
This may helps you Try once Else Try in another way</p>

```<code>IF EXISTS(

SELECT 1 From INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='sReal'
AND COLUMN_NAME='IsReal' AND DATA_TYPE='bit'
)
Begin
DECLARE @Real BIT
SELECT TOP 1@Real=[IsReal] From [sReal] WHERE  [IsReal]=1

IF (@Real=1 )
Begin

ALTER TABLE [dbo].[sReal] ALTER COLUMN [Code] [nvarchar](20) NOT NULL

ALTER TABLE [dbo].[sReal] ADD CONSTRAINT UC_Code UNIQUE ([Code]);
END
END
</code>```

Body:
I'm building a codebook in database.
There I have three columns:

[IDReal] int identity (1,1), [IsReal] bit not null, [Code] nvarchar (20) null

Now I have somehow get that when user change [IsReal] to 1, that my column [Code] change to not null and unique and vice versa.

I was trying something like

CREATE TABLE [dbo].[sReal](
[IDReal] [int] IDENTITY(1,1) NOT NULL,
[Code] [nvarchar](20) NULL,
[IsReal] [bit] NOT NULL,

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [DEF_IsReal]  DEFAULT ((0)) FOR [IsReal]
    GO

ALTER TABLE [dbo].[sReal] ADD  CONSTRAINT [CHNG_IsReal] IF [IsReal]=1 THEN (ALTER TABLE [dbo].[sReal] ALTER COLUMN [Code] [nvarchar](20) not null unique)
ELSE END IF
GO`

This, of course, is not working and I can't use triggers or functions or procedures to solve that.

Is there any other solution for accomplishing what I'm trying to do.

Body:
This may helps you Try once Else Try in another way

IF EXISTS(

SELECT 1 From INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME='sReal'
AND COLUMN_NAME='IsReal' AND DATA_TYPE='bit'
)
Begin
DECLARE @Real BIT
SELECT TOP 1@Real=[IsReal] From [sReal] WHERE  [IsReal]=1

IF (@Real=1 )
Begin

ALTER TABLE [dbo].[sReal] ALTER COLUMN [Code] [nvarchar](20) NOT NULL

ALTER TABLE [dbo].[sReal] ADD CONSTRAINT UC_Code UNIQUE ([Code]);
END
END


问:
Giving AWS federated user access to s3 bucket
Mobile phones can upload their content to our s3 bucket under an IAM user correctly using the below bucket policy

```<code>{
    "Version": "2008-10-17",
    "Id": "redacted",
    "Statement": [
        {
            "Sid": "redacted",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::redacted:user/iam_user"
            },
            "Action": "s3:ListBucketMultipartUploads",
            "Resource": "arn:aws:s3:::bucket_name"
        },
        {
            "Sid": "redacted",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::202695660434:user/iam_user"
            },
            "Action": [
                "s3:AbortMultipartUpload",
                "s3:GetObject",
                "s3:ListMultipartUploadParts",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::bucket_name/uploads/*"
        }
    ]
}
</code>```

I would like to follow best practises and allow federated users to upload from mobile to this bucket. How would I adjust the policy? I can currently create the federated user creds, but cant get it to upload correctly. This policy failed to save

```<code>{
    "Version": "2008-10-17",
    "Id": "redacted",
    "Statement": [
        {
            "Action": [
                "sts:GetFederationToken"
            ],
            "Sid": "redacted",
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        },
        {
            "Sid": "redacted",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::redacted:user/iam_user"
            },
            "Action": "s3:ListBucketMultipartUploads",
            "Resource": "arn:aws:s3:::bucket_name"
        },
        {
            "Sid": "redacted",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::202695660434:user/iam_user"
            },
            "Action": [
                "s3:AbortMultipartUpload",
                "s3:GetObject",
                "s3:ListMultipartUploadParts",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::bucket_name/uploads/*"
        }
    ]
}
</code>```

答:
I am having the same situation; Where I need some users to upload files at a particular bucket and some users to be download data from some buckets;

I am planning to have a lambda function which will request access on behalf of the user to read/write from specific buckets and provide the files to them locally. I am not sure if this is one of the best practices;

I will provide security around how the lambda function will be called.

Body:
Mobile phones can upload their content to our s3 bucket under an IAM user correctly using the below bucket policy

{
    "Version": "2008-10-17",
    "Id": "redacted",
    "Statement": [
        {
            "Sid": "redacted",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::redacted:user/iam_user"
            },
            "Action": "s3:ListBucketMultipartUploads",
            "Resource": "arn:aws:s3:::bucket_name"
        },
        {
            "Sid": "redacted",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::202695660434:user/iam_user"
            },
            "Action": [
                "s3:AbortMultipartUpload",
                "s3:GetObject",
                "s3:ListMultipartUploadParts",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::bucket_name/uploads/*"
        }
    ]
}

I would like to follow best practises and allow federated users to upload from mobile to this bucket. How would I adjust the policy? I can currently create the federated user creds, but cant get it to upload correctly. This policy failed to save

{
    "Version": "2008-10-17",
    "Id": "redacted",
    "Statement": [
        {
            "Action": [
                "sts:GetFederationToken"
            ],
            "Sid": "redacted",
            "Resource": [
                "*"
            ],
            "Effect": "Allow"
        },
        {
            "Sid": "redacted",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::redacted:user/iam_user"
            },
            "Action": "s3:ListBucketMultipartUploads",
            "Resource": "arn:aws:s3:::bucket_name"
        },
        {
            "Sid": "redacted",
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::202695660434:user/iam_user"
            },
            "Action": [
                "s3:AbortMultipartUpload",
                "s3:GetObject",
                "s3:ListMultipartUploadParts",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::bucket_name/uploads/*"
        }
    ]
}