问:
App crashes because of "context" issue
I'm fairly new to android and having an issue grasping the concept of Contexts and all.

I have a small app that consists of 3 activities:

1- Main Activity

2- Login Activity

3- Splash Activity

I've created a number of classes that are part of MainActivity and run as part of it. One of the classes is a database helper. Database helper needs a context to use and what I do is, in MainActivity:

```<code>public static Context context;
</code>```

and in onResume I do:

```<code>@Override
public void onResume() {
    super.onResume();

    this.context = this;
}
</code>```

All activities work just fine, spalsh works, login works, everything works fine. I've defined everything in Manifest.

But randomly when I leave my app running in background for a while and do other stuff with my phone and open it up, sometimes it just crashes pointing to a function that gets "context" as an argument.

Is there anything I can do to fix this?

Thanks

答:
This is happening because the activity who called that background task is not alive at the time of crash. So you need to use Application Context there.

Easy way to do that is

```<code>@Override
public void onResume() {
    super.onResume();

    this.context = this.getApplicationContext();
}
</code>```

And yes Context as you defined (public static Context context;) should not be static. (Although this is not causing problem to you, Best practice is to not to make Context as static.)

You should read about What is 'Context' on Android? and App crashes because of "context" issue.

Title: App crashes because of "context" issue

Body:
I'm fairly new to android and having an issue grasping the concept of Contexts and all.

I have a small app that consists of 3 activities:

1- Main Activity

2- Login Activity

3- Splash Activity

I've created a number of classes that are part of MainActivity and run as part of it. One of the classes is a database helper. Database helper needs a context to use and what I do is, in MainActivity:

public static Context context;

and in onResume I do:

@Override
public void onResume() {
    super.onResume();

    this.context = this;
}

All activities work just fine, spalsh works, login works, everything works fine. I've defined everything in Manifest.

But randomly when I leave my app running in background for a while and do other stuff with my phone and open it up, sometimes it just crashes pointing to a function that gets "context" as an argument.

Is there anything I can do to fix this?

Thanks

Body:
This is happening because the activity who called that background task is not alive at the time of crash. So you need to use Application Context there.

Easy way to do that is

@Override
public void onResume() {
    super.onResume();

    this.context = this.getApplicationContext();
}

And yes Context as you defined (public static Context context;) should not be static. (Although this is not causing problem to you, Best practice is to not to make Context as static.)

You should read about What is 'Context' on Android? and App crashes because of "context" issue.


来源: stackexchange

问:
How to drop a unique constraint from table column?
I have a table 'users' with 'login' column defined as:

```<code>[login] VARCHAR(50) UNIQUE NOT NULL
</code>```

Now I want to remove this unique constraint/index using SQL script. I found its name UQ_users_7D78A4E7 in my local database but I suppose it has a different name on another database.

What is the best way to drop this unique constraint? Or at least any...

Thanks.

答:
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

```<code>DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command
</code>```

It will drop your default constraint. However if you want to create it again you can simply try this

```<code>ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
</code>```

Finally, just simply run a DROP command to drop the column.

ContentLicense: CC BY-SA 2.5

Body:
I have a table 'users' with 'login' column defined as:

[login] VARCHAR(50) UNIQUE NOT NULL

Now I want to remove this unique constraint/index using SQL script. I found its name UQ_users_7D78A4E7 in my local database but I suppose it has a different name on another database.

What is the best way to drop this unique constraint? Or at least any...

Thanks.

Body:
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash value in it's name. So problem is this HASH is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4 here 6AB17FE4 is the hash value(8 bit). So I am referring a single script which will be fruitful to all

DECLARE @Command NVARCHAR(MAX)
     declare @table_name nvarchar(256)
     declare @col_name nvarchar(256)
     set @table_name = N'ProcedureAlerts'
     set @col_name = N'EmailSent'

     select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
     from
         sys.tables t
         join sys.default_constraints d on d.parent_object_id = t.object_id
         join sys.columns c on c.object_id = t.object_id
                               and c.column_id = d.parent_column_id
     where
         t.name = @table_name
         and c.name = @col_name) + ']'

    --print @Command
    exec sp_executesql @Command

It will drop your default constraint. However if you want to create it again you can simply try this

ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]

Finally, just simply run a DROP command to drop the column.

ContentLicense: CC BY-SA 3.0


问:
Find probability of skewed distribution
I have a variable X with summary given below.  Looking at distribution it seems like skewed normal distribution. I wonder how can I find p-value associated with each value of variable X in R?

```<code>Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
1.5   318.3   399.9   367.1   447.4   500.0
</code>```

答:
Judging by your plot, I assume you have some sequence of numbers called averageRank, for which you tried to fit a kernel density estimator using density.default().

Essentially you have an estimate of your probability density function (output of density.default()). Your question states:

I wonder how can I find p-value associated with each value of variable X in R?

Which is what density.default() gives to you indirectly, except only for 512 equidistant points, instead of something continuous. You could find, for a specific value x the closest value outputted by density.default() and the corresponding y:

```<code># Create some random data:
set.seed(123)
averageRank <- rnorm(100, mean = 300, sd = 75)
x           <- 250

kde       <- density.default(averageRank)
closeness <- abs(kde$x - x)
kde$y[which(closeness == min(closeness))]
# [1] 0.004370022    # is P(X = 250)
</code>```

However, from the way you posed your question I get the feeling you are searching for the cumulative distribution function:

```<code>sum(kde$y[1:which(closeness == min(closeness))]/sum(kde$y)
# [1] 0.2138626     # is P(X < 250)
</code>```

Title: Find probability of skewed distribution

Body:
I have a variable X with summary given below.  Looking at distribution it seems like skewed normal distribution. I wonder how can I find p-value associated with each value of variable X in R?

Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
1.5   318.3   399.9   367.1   447.4   500.0

Body:
Judging by your plot, I assume you have some sequence of numbers called averageRank, for which you tried to fit a kernel density estimator using density.default().

Essentially you have an estimate of your probability density function (output of density.default()). Your question states:

I wonder how can I find p-value associated with each value of variable X in R?

Which is what density.default() gives to you indirectly, except only for 512 equidistant points, instead of something continuous. You could find, for a specific value x the closest value outputted by density.default() and the corresponding y:

# Create some random data:
set.seed(123)
averageRank <- rnorm(100, mean = 300, sd = 75)
x           <- 250

kde       <- density.default(averageRank)
closeness <- abs(kde$x - x)
kde$y[which(closeness == min(closeness))]
# [1] 0.004370022    # is P(X = 250)

However, from the way you posed your question I get the feeling you are searching for the cumulative distribution function:

sum(kde$y[1:which(closeness == min(closeness))]/sum(kde$y)
# [1] 0.2138626     # is P(X < 250)


问:
Google Map or login working fine in signed apk but same apk published on google play then map or login not working
I have generated Sh1 key from release keystore file then create api key from sh1 key for release mode then paste the key release folder also have generated debug mode key also in debug folder.Map is working fine in release apk but not after download same apk on google Play.

keytool -list -v -keystore F:\Sanjeev\Location\abc.jks -alias abc

i have generated sh1 from above keytool

Please suggest me what am i doing wrong.

答:
I understand you're not able to use your app’s original keystore.

Unless you are enrolled in Google Play app signing, the only solution to this issue is to publish a new app with a new package name and a new key. In order to transition existing users to the new app, you’ll need to update the original app’s description with a link to the new app and unpublish the original app.

I absolutely understand this is a significant inconvenience, however, due to security concerns Google does not keep a copy of your keystore and at this time we do not support the deletion of apps or the re-use of package names.

You can read through this article in the Android Studio Help Center for more information about keystores.


问:
SQL 2005 nvarchar(max) problem
I have the following in a stored procedure:

```<code>DECLARE @TSQL NVARCHAR(MAX)

SET @TSQL = N'.....' Which contains about 33000 characters of text
</code>```

When I do a PRINT LEN(@TSQL) 7968 is returned. Why is the rest of @TSQL cut off?

答:
Make sure that when you concatenate everything is a nvarchar(max)

take a look at this

```<code>DECLARE @n NVARCHAR(MAX)
SELECT @n = REPLICATE(convert(varchar(max),'A'),300000)

select LEN(@n), DATALENGTH(@n)
GO
</code>```

--300000    600000

```<code>DECLARE @n NVARCHAR(MAX)
SELECT @n = REPLICATE('A',300000)

select LEN(@n), DATALENGTH(@n)
</code>```

--8000  16000

Title: SQL 2005 nvarchar(max) problem

Body:
I have the following in a stored procedure:

DECLARE @TSQL NVARCHAR(MAX)

SET @TSQL = N'.....' Which contains about 33000 characters of text

When I do a PRINT LEN(@TSQL) 7968 is returned. Why is the rest of @TSQL cut off?

Body:
Make sure that when you concatenate everything is a nvarchar(max)

take a look at this

DECLARE @n NVARCHAR(MAX)
SELECT @n = REPLICATE(convert(varchar(max),'A'),300000)

select LEN(@n), DATALENGTH(@n)
GO

--300000    600000

DECLARE @n NVARCHAR(MAX)
SELECT @n = REPLICATE('A',300000)

select LEN(@n), DATALENGTH(@n)

--8000  16000


问:
Bootstrap select input area bigger than parent
So my bootstrap select's area is bigger than I'd like when it's on small screens (mobile). So I was wondering if there was some way to force the selection area to not be bigger than the parent.

My problem via image below as well as recreated issue in snippet. The black bar represents edge of screen.

$.ajax({
  url: "https://restcountries.eu/rest/v2/all",
  success: (data) =>
  {
    let select = $("#select-country");
    for (let country of data)
    {
      select.append(`
          <option>
            ${country.name}
          </option>
        `);
    }
    $(select).prop('disabled', false);
    $(select).selectpicker('refresh');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css" rel="stylesheet"/>

<div style="width: 300px;">
    <select id='select-country' disabled="true" className="selectpicker" data-live-search="true" title="Choose a country">
    </select>
</div>
<div style="width: 50px; position: absolute; top: 0; left: 300px; height: 200px; background-color: black; z-index: 200">
</div></code>```

答:
try this

```<code>.dropdown-menu
{
max-width:100%;
}
</code>```

hope this helps..

Body:
So my bootstrap select's area is bigger than I'd like when it's on small screens (mobile). So I was wondering if there was some way to force the selection area to not be bigger than the parent.

My problem via image below as well as recreated issue in snippet. The black bar represents edge of screen.

$.ajax({
  url: "https://restcountries.eu/rest/v2/all",
  success: (data) =>
  {
    let select = $("#select-country");
    for (let country of data)
    {
      select.append(`
          <option>
            ${country.name}
          </option>
        `);
    }
    $(select).prop('disabled', false);
    $(select).selectpicker('refresh');
  }
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css" rel="stylesheet"/>

    <select id='select-country' disabled="true" className="selectpicker" data-live-search="true" title="Choose a country">
    </select>

Body:
try this

.dropdown-menu
{
max-width:100%;
}

hope this helps..


问:
JavaFx close window on pressing esc not working on table view?
I've used the following function to close the Stage when pressing escape key. It works fine but it doesn't work when my table has the keyboard focus.

```<code>scene.setOnKeyPressed(new EventHandler<KeyEvent>()
{
  @Override
  public void handle(KeyEvent evt)
  {
     if(evt.getCode().equals(KeyCode.ESCAPE))
     {
        dialogStage.close();
     }
  }
});
</code>```

答:
I had the same problem but found the target of KeyEvent is the TableView, not parent stage, that is why the parent doesn't get Esc event.

My variant based on EventHandler (bubbling phase):

```<code>myTable.setOnKeyReleased(event -> {
    if (event.getCode() == KeyCode.ESCAPE) {
        stage.close();
    }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've used the following function to close the Stage when pressing escape key. It works fine but it doesn't work when my table has the keyboard focus.

scene.setOnKeyPressed(new EventHandler<KeyEvent>()
{
  @Override
  public void handle(KeyEvent evt)
  {
     if(evt.getCode().equals(KeyCode.ESCAPE))
     {
        dialogStage.close();
     }
  }
});

Body:
I had the same problem but found the target of KeyEvent is the TableView, not parent stage, that is why the parent doesn't get Esc event.

My variant based on EventHandler (bubbling phase):

myTable.setOnKeyReleased(event -> {
    if (event.getCode() == KeyCode.ESCAPE) {
        stage.close();
    }
});


问:
Trying to call callback after S3.putobject
kinda new to aws and javascript and i am trying to achieve the following, uploading a photo using binary support and on my return value adding status paramater to be later used in API Gateway

```<code>var params = {
  Key: key,
  Body: image,
};
this.s3.putObject(params, function(err, data) {
  if (!err) {
    callback(null,{newValue: "This is my test value"});
  }
});
</code>```

the code works fine if I comment out the callback line, but crashes otherwise.
 Any tips on how to fix it will be greatly appreciated

答:
Rajana is correct. To add on this: this is a core functionality of JS (or functional programming). The putObject function accepts two parameters: params, an object containing parameters and callback which is a function that is executed inside the putObject function when completed. So you don't call callback, putObject calls callback.

So you create a function, and it as a function argument of the putObject function. So this would also work:

```<code>const params = { some: 'params'};
const fn = function(err) { console.log(err); }
this.s3.putObject(params, fn);
</code>```

But you can also define the function in the argument (making it an anonymous function), what you did in your example.

Body:
kinda new to aws and javascript and i am trying to achieve the following, uploading a photo using binary support and on my return value adding status paramater to be later used in API Gateway

var params = {
  Key: key,
  Body: image,
};
this.s3.putObject(params, function(err, data) {
  if (!err) {
    callback(null,{newValue: "This is my test value"});
  }
});

the code works fine if I comment out the callback line, but crashes otherwise.
 Any tips on how to fix it will be greatly appreciated

Body:
Rajana is correct. To add on this: this is a core functionality of JS (or functional programming). The putObject function accepts two parameters: params, an object containing parameters and callback which is a function that is executed inside the putObject function when completed. So you don't call callback, putObject calls callback.

So you create a function, and it as a function argument of the putObject function. So this would also work:

const params = { some: 'params'};
const fn = function(err) { console.log(err); }
this.s3.putObject(params, fn);

But you can also define the function in the argument (making it an anonymous function), what you did in your example.


问:
Can I set ng-model to two values?
I have an input

```<code><input type="text" ng-model="choice.text">
</code>```

Where choice.text creates a new text property in the object choice. This allows me to send the contents of the input to different page. While this feature works, I would also like to add another feature where the content of the input is displayed and updated in real time on the page. Something to this effect.

Unfortunately, ng-model is already set to choice.text. Is there a way I can have set two values to one ng-model? It would perhaps look like this:

```<code><input type="text" ng-model="choice.text name"></p>
<p ng-bind="name"></p>
</code>```

If not, is there another way to achieve this effect?

EDIT: For those wondering, when I try

it doesnt work for some reason.

EDIT 2: I simplified the code for the sake of the question. Here is the actual code for more detail:

```<code><div class ="ask-container">
    <div ng-switch="cbstate">
      <div ng-switch-when="not-pressed">
        <h1>Choose between... </h1> <!-- I would like to add the dynamic element here -->
      </div>
      <div ng-switch-when="pressed">
        <h1>Hi</h1>
      </div>
    </div>
    <form role="form" ng-submit="submitChoice()">
      <div class="input" ng-repeat="choice in poll.options">
        <input type="text"  ng-model="choice.text" placeholder="Choice {{$index+1}}"><br>
      </div>
      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>
</div>
</code>```

EDIT 3: Same code, but with the ng-bind:

```<code><div class ="ask-container">
    <div ng-switch="cbstate">
      <div ng-switch-when="not-pressed">
        <h1>Choose between... </h1>
      </div>
      <div ng-switch-when="pressed">
        <h1>Hi</h1>
      </div>
    </div>
    <form role="form" ng-submit="submitChoice()">
      <div class="input" ng-repeat="choice in poll.options">
        <input type="text"  ng-model="choice.text" ng-change="temp=choice.text" placeholder="Choice {{$index+1}}"><br>
      </div>
      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>
    <p ng-bind="temp"></p>
    <p ng-bind="choice.text"></p>
</div>
</code>```

Note: Somebody said that the ng-repeat may be messing with my scope. Maybe keep that in mind as you try and fix my problem.

答:
For now, just list[0]. Eventually I will want them all to appear in a list but I can do that myself. For now I just want the first input to display in the bind.

To have the first of the list appear in the bind:

```<code><div class="input" ng-repeat="choice in poll.options">
  <input type="text"  ng-model="choice.text" placeholder="Choice {{$index+1}}" />
  <br>
</div>

<p ng-bind="poll.options[0].text"></p>
</code>```

Each
 in the ng-repeat has its own child scope with the choice property set to poll.options[0], poll.options[1], poll.options[2], etc. Simply use those values in the parent scope.

Title: Can I set ng-model to two values?

Body:
I have an input

<input type="text" ng-model="choice.text">

Where choice.text creates a new text property in the object choice. This allows me to send the contents of the input to different page. While this feature works, I would also like to add another feature where the content of the input is displayed and updated in real time on the page. Something to this effect.

Unfortunately, ng-model is already set to choice.text. Is there a way I can have set two values to one ng-model? It would perhaps look like this:

<input type="text" ng-model="choice.text name">

If not, is there another way to achieve this effect?

EDIT: For those wondering, when I try

it doesnt work for some reason.

EDIT 2: I simplified the code for the sake of the question. Here is the actual code for more detail:

Choose between...

Hi

    <form role="form" ng-submit="submitChoice()">

        <input type="text"  ng-model="choice.text" placeholder="Choice {{$index+1}}">

      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>

EDIT 3: Same code, but with the ng-bind:

Choose between...

Hi

    <form role="form" ng-submit="submitChoice()">

        <input type="text"  ng-model="choice.text" ng-change="temp=choice.text" placeholder="Choice {{$index+1}}">

      <button class="add" type="button" ng-click="addChoice()">+</button>
      <button class="create" type="submit">Create</button>
    </form>

Note: Somebody said that the ng-repeat may be messing with my scope. Maybe keep that in mind as you try and fix my problem.

Body:
For now, just list[0]. Eventually I will want them all to appear in a list but I can do that myself. For now I just want the first input to display in the bind.

To have the first of the list appear in the bind:

<div class="input" ng-repeat="choice in poll.options">
  <input type="text"  ng-model="choice.text" placeholder="Choice {{$index+1}}" />
  <br>
</div>

<p ng-bind="poll.options[0].text"></p>

Each <div> in the ng-repeat has its own child scope with the choice property set to poll.options[0], poll.options[1], poll.options[2], etc. Simply use those values in the parent scope.


问:
Dateformat dd/MM/yyyy HH:mm z is crashing while converting string to Date Swift 3.0
I am parsing this DateString 01/06/2017 14:31 GMT+10:00 into Date using date format dd/MM/yyyy HH:mm z but some times it gives nil values. and some times it works correctly.

Can you suggest correct Date format for this date string.

I am using swift 3.0 and Xcode 8.3.

My codes are :

```<code>static func getTimestampFromDateString(dateString:String) -> Int64{
    let separated = dateString.components(separatedBy: " ")
    let currentUser = User.getLoggedInUserDataModel()
    let finalDateStr = "\(String.getString(separated[0])) \(String.getString(separated[1])) \(String.getString(currentUser.timeZoneOffset))"

    let date = convertStringToDate(dateString: finalDateStr, dateFormat: "dd/MM/yyyy HH:mm z")
    let timestamp = Int64(date.timeIntervalSince1970)
    return timestamp
}
static func convertStringToDate(dateString:String,dateFormat:String)->Date{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    let date:Date = dateFormatter.date(from: dateString)!
    return date
}
</code>```

答:
The date format "dd/MM/yyyy HH:mm z" works good for me .
By the way , I am using this code below

```<code>extension String
{
     func  toDate( dateFormat format  : String) -> Date
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        if let date = dateFormatter.date(from: self)
        {
            return date
        }
        print("Invalid arguments ! Returning Current Date . ")
        return Date()
    }
}
</code>```

and here is how i called . .

```<code>print("01/06/2017 14:31 GMT+10:00".toDate(dateFormat: "dd/MM/yyyy HH:mm z"))
</code>```

Body:
I am parsing this DateString 01/06/2017 14:31 GMT+10:00 into Date using date format dd/MM/yyyy HH:mm z but some times it gives nil values. and some times it works correctly.

Can you suggest correct Date format for this date string.

I am using swift 3.0 and Xcode 8.3.

My codes are :

static func getTimestampFromDateString(dateString:String) -> Int64{
    let separated = dateString.components(separatedBy: " ")
    let currentUser = User.getLoggedInUserDataModel()
    let finalDateStr = "\(String.getString(separated[0])) \(String.getString(separated[1])) \(String.getString(currentUser.timeZoneOffset))"

    let date = convertStringToDate(dateString: finalDateStr, dateFormat: "dd/MM/yyyy HH:mm z")
    let timestamp = Int64(date.timeIntervalSince1970)
    return timestamp
}
static func convertStringToDate(dateString:String,dateFormat:String)->Date{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateFormat
    let date:Date = dateFormatter.date(from: dateString)!
    return date
}

Body:
The date format "dd/MM/yyyy HH:mm z" works good for me .
By the way , I am using this code below

extension String
{
     func  toDate( dateFormat format  : String) -> Date
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        if let date = dateFormatter.date(from: self)
        {
            return date
        }
        print("Invalid arguments ! Returning Current Date . ")
        return Date()
    }
}

and here is how i called . .

print("01/06/2017 14:31 GMT+10:00".toDate(dateFormat: "dd/MM/yyyy HH:mm z"))


问:
Java: How can I read and store them in array by a new line in ArrayList?
Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):

```<code>-0.89094    -0.86099    -0.82438    -0.78214    -0.73573    -0.68691    -0.63754
-0.42469    -0.3924     -0.36389    -0.33906    -0.31795    -0.30056    -0.28692
</code>```

What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).

Here is my code:

```<code>public class ReadStore {
    public static void main(String[] args) throws IOException {

    Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
    ArrayList<Float> temps = new ArrayList<Float>();

    while (inFile.hasNextFloat()) {
      // find next line
      float token = inFile.nextFloat();
      temps.add(token);

    }

    inFile1.close();

    Float [] tempsArray = temps.toArray(new Float[0]);
    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }
</code>```

Any suggestion for making this works?

答:
Read the file once with Files.readAllLines method. And split it by spaces</p>

```<code>import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        String readFileContent = readFileContent(new File("Test.txt"));
        ArrayList<Float> temps = new ArrayList<Float>();
        String[] split = readFileContent.split("\\s+");
        for (String num : split) {
             float token = Float.parseFloat(num.trim());
             temps.add(token);
        }

        Float [] tempsArray = temps.toArray(new Float[0]);
        for (Float s : tempsArray) {
            System.out.println(s);
        }
    }

    private static String readFileContent(File file) {
        try {
            return Files.readAllLines(file.toPath()).stream().collect(Collectors.joining("\n"));
        } catch (IOException e) {
            System.out.println("Error while reading file " + file.getAbsolutePath());
        }
        return "";
    }
}
</code>```

Body:
Here is what my .txt file looks like (but more than 100 elements per line and more than 100 lines):

-0.89094    -0.86099    -0.82438    -0.78214    -0.73573    -0.68691    -0.63754
-0.42469    -0.3924     -0.36389    -0.33906    -0.31795    -0.30056    -0.28692

What I want to do is read this .txt file and store them in Arryalist. The problem is when I read and store this data, they put all of this in the same array (I want them to store in 2 arrays split by a line).

Here is my code:

public class ReadStore {
    public static void main(String[] args) throws IOException {

    Scanner inFile = new Scanner(new File("Untitled.txt")).useDelimiter("\\s");
    ArrayList<Float> temps = new ArrayList<Float>();

    while (inFile.hasNextFloat()) {
      // find next line
      float token = inFile.nextFloat();
      temps.add(token);

    }

    inFile1.close();

    Float [] tempsArray = temps.toArray(new Float[0]);
    for (Float s : tempsArray) {
      System.out.println(s);
    }
  }

Any suggestion for making this works?

Body:
Read the file once with Files.readAllLines method. And split it by spaces

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        String readFileContent = readFileContent(new File("Test.txt"));
        ArrayList<Float> temps = new ArrayList<Float>();
        String[] split = readFileContent.split("\\s+");
        for (String num : split) {
             float token = Float.parseFloat(num.trim());
             temps.add(token);
        }

        Float [] tempsArray = temps.toArray(new Float[0]);
        for (Float s : tempsArray) {
            System.out.println(s);
        }
    }

    private static String readFileContent(File file) {
        try {
            return Files.readAllLines(file.toPath()).stream().collect(Collectors.joining("\n"));
        } catch (IOException e) {
            System.out.println("Error while reading file " + file.getAbsolutePath());
        }
        return "";
    }
}


问:
What is the ms-vscode.cpptools extension?
I am using Microsoft Visual Studio Code (it is basically a glorified command prompt), it keeps recommending that I download the ms-vscode.cpptools extension. Has anyone download it already and know what it is?</p>

答:
It is an extension for C/C++ in Visual Studio Code.

This preview release of the extension adds language support for C/C++ to Visual Studio Code

You can find it and its Details easily in Markt.

I guess it keeps recommending you to download it because you are editing c/c++ files.


问:
@Transactional in REST layer or in Service layer? Which is better?
In my case, I want to create multiple tags by invoking the method "createTags()". For testing convenience, I just use @GET and no params in this method, please don't mind it. And I want all the operations rollback if one of them throw an exception, e.g. if t3's tagValue is empty, t1, t2 shouldn't exist in my database. Obviously, I should use @Transactional here, so my question is that can I use @Transactional this way? I mean to use it in my REST layer. Here is the code:

TestREST.class

```<code>@Path("tag/create")
@GET
@Transactional(rollbackOn = {NoTagException.class, TagAlreadyExistedException.class}))
public void createTags() throws NoTagException, TagAlreadyExistedException {
    // create all categories
    Tag t1 = new Tag(TagType.CATEGORY);
    t1.setTagValue("Edu");
    tagService.createTag(t1);
    Tag t2 = new Tag(TagType.CATEGORY);
    t2.setTagValue("ZJNU");
    tagService.createTag(t2);
    Tag t3 = new Tag(TagType.CATEGORY);
    // the value is empty here so I hope all previous operations rollback
    t3.setTagValue("");
    tagService.createTag(t3);
}
</code>```

TagService.class

```<code>public void createTag(Tag tag) throws NoTagException, TagAlreadyExistedException {
    if (tag.getType() == null || !(tag.getType() instanceof TagType)) {
        throw new NoTagException("tag's type must be set");
    } else if (tag.getTagValue() == null || tag.getTagValue().equals("")) {
        throw new NoTagException("tag's value must be set!");
    } else {
        Optional<Tag> existedTag = retrieveTagByTypeAndValue(tag.getType(), tag.getTagValue());
        if (existedTag.isPresent()) {
            throw new TagAlreadyExistedException("one or more tags are already existed!");
        } else {
            tagDAO.create(tag);
        }
    }
}
</code>```

Or should I always use @Transactional in my Service layer? I change the above methods to this:

TestREST.class

```<code>@Path("tag/create")
@GET
public void createTags() throws NoTagException, TagAlreadyExistedException {
    // create all categories
    Set<Tag> tags = new HashSet<>();
    Tag t1 = new Tag(TagType.CATEGORY);
    t1.setTagValue("Edu");
    Tag t2 = new Tag(TagType.CATEGORY);
    t2.setTagValue("ZJNU");
    Tag t3 = new Tag(TagType.CATEGORY);
    t3.setTagValue("");
    tags.add(t1);
    tags.add(t2);
    tags.add(t3);
    tagService.createTags(tags);
}
</code>```

TagService.class

```<code>@Transactional(rollbackOn = {NoTagException.class, TagAlreadyExistedException.class}))
public void createTag(Tag tag) throws NoTagException, TagAlreadyExistedException {
    // just the same as above
}

public void createTags(Set<Tag> tags) throws NoTagException, TagAlreadyExistedException {
    if (tags.isEmpty()) {
        throw new NoTagException("tag must be set");
    } else {
        for (Tag tag : tags) {
            createTag(tag);
        }
    }
}
</code>```

They can all achieve what I expected. So, which approach should I choose? Why? And any suggestions that I can improve these methods? BTW, I use CDI @RequestScoped in TestREST.class and TagService.class Thanks for your help!

答:
When designing transaction for an application below one of transaction design pattern can be used based on architecture/type of an application

Client Owner Transaction Design Pattern
Domain Service Owner Transaction Design Pattern
Sever Delegate Owner Transaction Design Pattern

For most java enterprise application Domain Service Owner Transaction Design Pattern is used in which Domain component of an application manage transaction

When we want to move transaction responsibility to presentation layer Client Owner Transaction Design Pattern is used

Sever Delegate Owner Transaction Design Pattern is used when we want to leverage Command Pattern in an application

Client Owner is used when an application does not have aggregate service and several client to remote call is require to fulfill one business action. In your code you are calling same service multiple time to create tags in REST layer so there is not reason to place transaction responsibility in presentation layer. For your business requirement it is better to move transaction responsibility on middle layer using Domain Service owner pattern
Also using Client owner patter put too much infrastructure responsibility in client side which increase server chatting. Presentation layer should only responsible for presenting data but Client Owner patter force presentation layer to maintain server side responsibility also it is not good .

Domain Service owner is commonly used pattern for most java based enterprise an application. In this pattern Domain component of your application  i.e. Item, Order, Inventory and in your case Tag own the transaction responsibility. So for business requirement this is pattern which should be used

Sever Delegate Owner Transaction Design Pattern is used when using Command Pattern in application and it solves regards to Client Owner pattern. In command Pattern functionality is put in Command and sent to server for execution. Command Processor component in server side manage transaction.

One simple rule to manage an exception an efficiently in transaction is the layer/Component which is managing transaction should handle exception and do business operation for that an exception. Managing transaction includes starting transaction, committing transaction,  and roll back transaction so all these three an operation should be put in component which owns transaction responsibility

I suggest to go through pdf version Java Transaction Design Strategies which i have uploaded in mine below git repo to learn in depth about transaction design pattern.

https://github.com/anurag1986/Transaction-Material

Body:
In my case, I want to create multiple tags by invoking the method "createTags()". For testing convenience, I just use @GET and no params in this method, please don't mind it. And I want all the operations rollback if one of them throw an exception, e.g. if t3's tagValue is empty, t1, t2 shouldn't exist in my database. Obviously, I should use @Transactional here, so my question is that can I use @Transactional this way? I mean to use it in my REST layer. Here is the code:

TestREST.class

@Path("tag/create")
@GET
@Transactional(rollbackOn = {NoTagException.class, TagAlreadyExistedException.class}))
public void createTags() throws NoTagException, TagAlreadyExistedException {
    // create all categories
    Tag t1 = new Tag(TagType.CATEGORY);
    t1.setTagValue("Edu");
    tagService.createTag(t1);
    Tag t2 = new Tag(TagType.CATEGORY);
    t2.setTagValue("ZJNU");
    tagService.createTag(t2);
    Tag t3 = new Tag(TagType.CATEGORY);
    // the value is empty here so I hope all previous operations rollback
    t3.setTagValue("");
    tagService.createTag(t3);
}

TagService.class

public void createTag(Tag tag) throws NoTagException, TagAlreadyExistedException {
    if (tag.getType() == null || !(tag.getType() instanceof TagType)) {
        throw new NoTagException("tag's type must be set");
    } else if (tag.getTagValue() == null || tag.getTagValue().equals("")) {
        throw new NoTagException("tag's value must be set!");
    } else {
        Optional<Tag> existedTag = retrieveTagByTypeAndValue(tag.getType(), tag.getTagValue());
        if (existedTag.isPresent()) {
            throw new TagAlreadyExistedException("one or more tags are already existed!");
        } else {
            tagDAO.create(tag);
        }
    }
}

Or should I always use @Transactional in my Service layer? I change the above methods to this:

TestREST.class

@Path("tag/create")
@GET
public void createTags() throws NoTagException, TagAlreadyExistedException {
    // create all categories
    Set<Tag> tags = new HashSet<>();
    Tag t1 = new Tag(TagType.CATEGORY);
    t1.setTagValue("Edu");
    Tag t2 = new Tag(TagType.CATEGORY);
    t2.setTagValue("ZJNU");
    Tag t3 = new Tag(TagType.CATEGORY);
    t3.setTagValue("");
    tags.add(t1);
    tags.add(t2);
    tags.add(t3);
    tagService.createTags(tags);
}

TagService.class

@Transactional(rollbackOn = {NoTagException.class, TagAlreadyExistedException.class}))
public void createTag(Tag tag) throws NoTagException, TagAlreadyExistedException {
    // just the same as above
}

public void createTags(Set<Tag> tags) throws NoTagException, TagAlreadyExistedException {
    if (tags.isEmpty()) {
        throw new NoTagException("tag must be set");
    } else {
        for (Tag tag : tags) {
            createTag(tag);
        }
    }
}

They can all achieve what I expected. So, which approach should I choose? Why? And any suggestions that I can improve these methods? BTW, I use CDI @RequestScoped in TestREST.class and TagService.class Thanks for your help!


问:
ThinkingSphinx: dynamic indices on the SQL-backed indices?
I am trying to use ThinkingSphinx (with SQL-backed indices) in my Rails 5 project.

I need some dynamic run-time indices to search over.

I have a Message model:

```<code>class Message < ApplicationRecord
    belongs_to :sender, class_name: 'User', :inverse_of => :messages
    belongs_to :recipient, class_name: 'User', :inverse_of => :messages
end
</code>```

and its indexer:

```<code>ThinkingSphinx::Index.define :message, :with => :active_record, :delta => true do
    indexes text

    indexes sender.email, :as => :sender_email, :sortable => true

    indexes recipient.email, :as => :recipient_email, :sortable => true

    indexes [sender.email, recipient.email], :as => :messager_email, :sortable => true

    has sender_id, created_at, updated_at

    has recipient_id

end
</code>```

schema.rb:

```<code>  create_table "messages", force: :cascade do |t|
    t.integer  "sender_id"
    t.integer  "recipient_id"
    t.text     "text"
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
    t.boolean  "read",         default: false
    t.boolean  "spam",         default: false
    t.boolean  "delta",        default: true,  null: false
    t.index ["recipient_id"], name: "index_messages_on_recipient_id", using: :btree
    t.index ["sender_id"], name: "index_messages_on_sender_id", using: :btree
  end
</code>```

The problem is about so-called "dialogs". They don't exist in the database - they are determined at run-time. A dialog - that's a set of messages between 2 users, where each user may be either a sender or a receiver.

The task is to search through my dialogs and to find the dialog (dialog's messages) by the piece of the correspondent email. So complicated!

Here's my effort:

```<code>  conditions = {messager_email: search_email}

  with_current_user_dialogs =

  "*, IF(sender_id = #{current_user.id} OR recipient_id = #{current_user.id}, 1, 0) AS current_user_dialogs"

  messages = Message.search search_email, conditions: conditions,

    select: with_current_user_dialogs,
    with: {'current_user_dialogs' => 1}
</code>```

This is almost fine - but still not. This query correctly searches only within my dialog (within the messages I sent or received) and only within :sender and :recipient fields simultaneously (which is not best).

Say my email is "client1@example.com". Other emails are like "client2@example.com", "client3@example.com", "manager1@example.com".

The trouble is that when I search for "client1" - I get all the messages where I was either a sender or a receiver. But I should get nothing in response - I need to search only across my correspondents emails - not mine.

Even worse stuff happens also while querying "client" - I get back the correct correspondents with "client2@example.com", "client3@example.com" - but the result is spoiled with wrong "client1@example.com".

I need a way to choose at run-time - which index subset to search within.

I mean this condition is not enough for me:

```<code>indexes [sender.email, recipient.email], :as => :messager_email, :sortable => true
</code>```

It searches (for "client") within all the sender.email and all the recipient.email at once.

But I need to dynamically choose like: "search only within sender.email values conforming to if sender.id != current_user.id" OR "search only within recipient.email conforming to if recipient.id != current_user.id" (because I can be as a sender as a receiver).

That's what I call a "dynamic index".

How to do that? Such "dynamic index" surely would depend on the current current_user value - so it will be different for the different users - even on the same total messages set.

It is clear that I can't apply whatever post-search cut-offs (what to cut off?) - I need to somehow limitate the search itself.

I tried to search over some scope - but got the error that "searching is impossible over scopes" - something like that.

Maybe I should use the real-time indexing instead of the SQL-backed indexing?

Sorry for the complexity of my question.

答:
Would the following work?

```<code>other = User.find_by :email => search_email
with_current_user_dialogs = "*, IF((sender_id = #{current_user.id} AND recipient_id = #{other.id}) OR (recipient_id = #{current_user.id} AND sender_id = #{other.id}), 1, 0) AS current_user_dialogs"
</code>```

Or do you need partial matches on the searched email address?

[EDIT]

Okay, from the discussion in the comments below, it's clear that the field data is critical. While you can construct a search query that uses both fields and attributes, you can't have logic in the query that combines the two. That is, you can't say: "Search field 'x' when attribute 'i' is 1, otherwise search field 'y'."

The only way I can possibly see this working is if you're using fields for both parts of the logic. Perhaps something like the following:

```<code>current_user_email = "\"" + current_user.email + "\""

Message.search(
  "(@sender_email #{current_user_email} @recipient_email #{search_email}) | (@sender_email #{search_email} @recipient_email #{current_user_email})"
)
</code>```

Body:
I am trying to use ThinkingSphinx (with SQL-backed indices) in my Rails 5 project.

I need some dynamic run-time indices to search over.

I have a Message model:

class Message < ApplicationRecord
    belongs_to :sender, class_name: 'User', :inverse_of => :messages
    belongs_to :recipient, class_name: 'User', :inverse_of => :messages
end

and its indexer:

ThinkingSphinx::Index.define :message, :with => :active_record, :delta => true do
    indexes text

    indexes sender.email, :as => :sender_email, :sortable => true

    indexes recipient.email, :as => :recipient_email, :sortable => true

    indexes [sender.email, recipient.email], :as => :messager_email, :sortable => true

    has sender_id, created_at, updated_at

    has recipient_id

end

schema.rb:

  create_table "messages", force: :cascade do |t|
    t.integer  "sender_id"
    t.integer  "recipient_id"
    t.text     "text"
    t.datetime "created_at",                   null: false
    t.datetime "updated_at",                   null: false
    t.boolean  "read",         default: false
    t.boolean  "spam",         default: false
    t.boolean  "delta",        default: true,  null: false
    t.index ["recipient_id"], name: "index_messages_on_recipient_id", using: :btree
    t.index ["sender_id"], name: "index_messages_on_sender_id", using: :btree
  end

The problem is about so-called "dialogs". They don't exist in the database - they are determined at run-time. A dialog - that's a set of messages between 2 users, where each user may be either a sender or a receiver.

The task is to search through my dialogs and to find the dialog (dialog's messages) by the piece of the correspondent email. So complicated!

Here's my effort:

  conditions = {messager_email: search_email}

  with_current_user_dialogs =

  "*, IF(sender_id = #{current_user.id} OR recipient_id = #{current_user.id}, 1, 0) AS current_user_dialogs"

  messages = Message.search search_email, conditions: conditions,

    select: with_current_user_dialogs,
    with: {'current_user_dialogs' => 1}

This is almost fine - but still not. This query correctly searches only within my dialog (within the messages I sent or received) and only within :sender and :recipient fields simultaneously (which is not best).

Say my email is "client1@example.com". Other emails are like "client2@example.com", "client3@example.com", "manager1@example.com".

The trouble is that when I search for "client1" - I get all the messages where I was either a sender or a receiver. But I should get nothing in response - I need to search only across my correspondents emails - not mine.

Even worse stuff happens also while querying "client" - I get back the correct correspondents with "client2@example.com", "client3@example.com" - but the result is spoiled with wrong "client1@example.com".

I need a way to choose at run-time - which index subset to search within.

I mean this condition is not enough for me:

indexes [sender.email, recipient.email], :as => :messager_email, :sortable => true

It searches (for "client") within all the sender.email and all the recipient.email at once.

But I need to dynamically choose like: "search only within sender.email values conforming to if sender.id != current_user.id" OR "search only within recipient.email conforming to if recipient.id != current_user.id" (because I can be as a sender as a receiver).

That's what I call a "dynamic index".

How to do that? Such "dynamic index" surely would depend on the current current_user value - so it will be different for the different users - even on the same total messages set.

It is clear that I can't apply whatever post-search cut-offs (what to cut off?) - I need to somehow limitate the search itself.

I tried to search over some scope - but got the error that "searching is impossible over scopes" - something like that.

Maybe I should use the real-time indexing instead of the SQL-backed indexing?

Sorry for the complexity of my question.

Body:
Would the following work?

other = User.find_by :email => search_email
with_current_user_dialogs = "*, IF((sender_id = #{current_user.id} AND recipient_id = #{other.id}) OR (recipient_id = #{current_user.id} AND sender_id = #{other.id}), 1, 0) AS current_user_dialogs"

Or do you need partial matches on the searched email address?

[EDIT]

Okay, from the discussion in the comments below, it's clear that the field data is critical. While you can construct a search query that uses both fields and attributes, you can't have logic in the query that combines the two. That is, you can't say: "Search field 'x' when attribute 'i' is 1, otherwise search field 'y'."

The only way I can possibly see this working is if you're using fields for both parts of the logic. Perhaps something like the following:

current_user_email = "\"" + current_user.email + "\""

Message.search(
  "(@sender_email #{current_user_email} @recipient_email #{search_email}) | (@sender_email #{search_email} @recipient_email #{current_user_email})"
)


问:
Copy only specific extension blobs using Azure Data Factory
I am trying to copy a Blob Container from one Azure Storage account to another. I am using Azure Data Factory Copy Activity to do this. It is simple to copy all the blobs. But i want to copy specific extension blobs only.

I do not see any option to specify wildcard or regex while creating input dataset.

Is there any way i can achieve this with ADF. I also tried  Azure Data Movement Library. Even it doesn't have such feature. Only prefix based filtering is available in DML.

答:
Base on my understanding, there is no file extension concept for blob. Where the file extension will be handy is when our download these files on our local computer. Based on the file extension, our local computer could decide which  application to use to open these files.

Is there any way i can achieve this with ADF

We can could use Azure Data Factory Custom activities to do that. We could implement our logic by ourselves. More info about how to use custom activites, please refer to this tutorials.

We also could use Azure WebJob with time trigger to do that.

If Azure Data Factory is the only choice, we could implement copy blob with our logic. The following is my demo code. I tested it on my side, it works correctly

```<code>         CloudStorageAccount storageAccountSource = CloudStorageAccount.Parse("connection string");
         CloudStorageAccount storageAccountDest = CloudStorageAccount.Parse("connection string");
         // Create the blob client.
         CloudBlobClient blobClientSource = storageAccountSource.CreateCloudBlobClient();
         CloudBlobClient blobClientDest = storageAccountDest.CreateCloudBlobClient();
         CloudBlobContainer containerSource = blobClientSource.GetContainerReference("test");
         CloudBlobContainer containerDest = blobClientDest.GetContainerReference("test");
         containerDest.CreateIfNotExists();

        SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
        {

            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
            Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List |
            SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Delete
        };

        // Get the container's existing permissions.
        BlobContainerPermissions permissions = containerSource.GetPermissions();
        permissions.SharedAccessPolicies.Add("policy", sharedPolicy);
        containerSource.SetPermissionsAsync(permissions);
        var blobToken = containerSource.GetSharedAccessSignature(sharedPolicy);

        foreach (IListBlobItem item in containerSource.ListBlobs())
        {
            CloudBlob destBlob;
            CloudBlob srcBlob;
            if (item.GetType() == typeof(CloudBlockBlob))
            {
                srcBlob = (CloudBlockBlob)item;
                destBlob = containerDest.GetBlockBlobReference(srcBlob.Name);

            }
            else
            {
                srcBlob = (CloudPageBlob)item;
                destBlob = containerDest.GetPageBlobReference(srcBlob.Name);

            }
            if (srcBlob.Name.Contains("format"))
            {
                destBlob.StartCopy(new Uri(srcBlob.Uri.AbsoluteUri + blobToken));
            }
       }
</code>```

Body:
Base on my understanding, there is no file extension concept for blob. Where the file extension will be handy is when our download these files on our local computer. Based on the file extension, our local computer could decide which  application to use to open these files.

Is there any way i can achieve this with ADF

We can could use Azure Data Factory Custom activities to do that. We could implement our logic by ourselves. More info about how to use custom activites, please refer to this tutorials.

We also could use Azure WebJob with time trigger to do that.

If Azure Data Factory is the only choice, we could implement copy blob with our logic. The following is my demo code. I tested it on my side, it works correctly

         CloudStorageAccount storageAccountSource = CloudStorageAccount.Parse("connection string");
         CloudStorageAccount storageAccountDest = CloudStorageAccount.Parse("connection string");
         // Create the blob client.
         CloudBlobClient blobClientSource = storageAccountSource.CreateCloudBlobClient();
         CloudBlobClient blobClientDest = storageAccountDest.CreateCloudBlobClient();
         CloudBlobContainer containerSource = blobClientSource.GetContainerReference("test");
         CloudBlobContainer containerDest = blobClientDest.GetContainerReference("test");
         containerDest.CreateIfNotExists();

        SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
        {

            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
            Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List |
            SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Delete
        };

        // Get the container's existing permissions.
        BlobContainerPermissions permissions = containerSource.GetPermissions();
        permissions.SharedAccessPolicies.Add("policy", sharedPolicy);
        containerSource.SetPermissionsAsync(permissions);
        var blobToken = containerSource.GetSharedAccessSignature(sharedPolicy);

        foreach (IListBlobItem item in containerSource.ListBlobs())
        {
            CloudBlob destBlob;
            CloudBlob srcBlob;
            if (item.GetType() == typeof(CloudBlockBlob))
            {
                srcBlob = (CloudBlockBlob)item;
                destBlob = containerDest.GetBlockBlobReference(srcBlob.Name);

            }
            else
            {
                srcBlob = (CloudPageBlob)item;
                destBlob = containerDest.GetPageBlobReference(srcBlob.Name);

            }
            if (srcBlob.Name.Contains("format"))
            {
                destBlob.StartCopy(new Uri(srcBlob.Uri.AbsoluteUri + blobToken));
            }
       }


问:
Create async methods to load data from database using EF
how does one write an async method that gets data from database, using DbContext and .NET 4.0?

```<code>public Task<List<Product>> GetProductsAsync()
{
    // Context.Set<Product>().ToList();
}
</code>```

so we can await somewhere for result of this method

```<code>// somewhere
List<Product> products = await repository.GetProductsAsync();
</code>```

What is important is that I do not want to use thread pool thread for this task, since this is an IO task, and I need to support framework 4.0, and EF6 had added support for async methods only in 4.5, if I am not mistaken.

答:
Not possible, SaveAsync is wrapped with:

```<code>#if !NET40
</code>```

Source: https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/DbContext.cs#L335

Body:
how does one write an async method that gets data from database, using DbContext and .NET 4.0?

public Task<List<Product>> GetProductsAsync()
{
    // Context.Set<Product>().ToList();
}

so we can await somewhere for result of this method

// somewhere
List<Product> products = await repository.GetProductsAsync();

What is important is that I do not want to use thread pool thread for this task, since this is an IO task, and I need to support framework 4.0, and EF6 had added support for async methods only in 4.5, if I am not mistaken.

Body:
Not possible, SaveAsync is wrapped with:

#if !NET40

Source: https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/DbContext.cs#L335


问:
Classes & Activities in Android
Another Java/Android newbie...

My Activity contains a delcaration for a variable of a class that I've defined...
    public Teams theTeams = null;
Within the onCreate method of this Activity, I create an object of that class...
    Teams theTeams = new Teams();
I've been able to make some changes to this object...
    theTeams.setName("A", "Jets");
... which assigns "Jets" to a string in the class.
However, from within a private method of the Activity, attempts to refer to "theTeams" give me a null pointer error.  I guess there's something about object visibility that I'm not understanding.  Can someone clarify?

答:
You declared first public Teams theTeams = null;
Then in the onCreate method, you have this

```<code>Teams theTeams = new Teams();
</code>```

So you are initializing a new  theTeams object of type Team inside the onCreate, which you can see only in the scope of onCreate.

So when you call a method on theTeams in your private method, the method is called in the object you have declared first outside the onCreate (which is still null)

So inside, your onCreate, you have to use:

```<code>theTeams = new Teams();
</code>```

Something like the following should work (untested):

```<code>private Teams theTeams = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    theTeams = new Teams();
}

private void myMethod() {
    theTeams.getName();
}
</code>```

Title: Classes & Activities in Android

Body:
You declared first public Teams theTeams = null;
Then in the onCreate method, you have this

Teams theTeams = new Teams();

So you are initializing a new  theTeams object of type Team inside the onCreate, which you can see only in the scope of onCreate.

So when you call a method on theTeams in your private method, the method is called in the object you have declared first outside the onCreate (which is still null)

So inside, your onCreate, you have to use:

theTeams = new Teams();

Something like the following should work (untested):

private Teams theTeams = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    theTeams = new Teams();
}

private void myMethod() {
    theTeams.getName();
}


问:
Get specific value from XBRL document
I've been using Gepsio to try and churn my way through standard SEC XBRL filings through their EDGAR system, and despite my numerous attempts to figure this out, it seems I'm at a loss.

When you extract the facts from any document, and you're interested in retrieving "revenues," per the specific US-GAAP standards, there might be as many as 200 facts with the revenues tag associated with it. While the ID of each one is unique, figuring out which ID equates to the particular type of revenue you want doesn't seem to be very straightforward. The Revenue I'm interested in getting is the same one that appears in the consolidated statement of operations--i.e. Net Revenue, and not some obscure other type of revenue in the document. However, XBRL viewers like Arelle get it right every time, and despite trolling through the source code of Arelle I can't figure out the logic they are using either.

Anyone who can throw me in the right direction to understanding this would be greatly appreciated.

答:
You need to find the fact that has the right concept, period and entity.

Finding the concept is not as trivial as it sounds. While in theory it should be us-gaap:Revenues, many filers do not use that concept and either "abuse" another US GAAP concept or (in the worst case) make up their own concept in their own namespace. Charles Hoffman has spent considerable time investing this and designed report frames to solve this issue and allow comparison across filers. Report frames include mappings, such as this one where you can see that there are no less than 77 different concepts (us-gaap:Revenues, us-gaap:SalesRevenueNet, ...) used to report revenues. Charlie's approach is to pick the first one in the list that gets reported. For some concepts (I think it doesn't happen with revenues), facts may not even get explicitly reported, so that calculations are needed. Some XBRL vendors have worked with Charlie and integrated this report frame feature in their products.

The entity is the easiest, because in the vast majority of the cases (it may even be mandatory, but I couldn't find instructions on this), all facts within a filing share the same entity. For SEC filings, it is the CIK of the company (with the CIK scheme). Having said that, in SEC filings, there is an additional dimension (dei:LegalEntityAxis) that you must check is absent or set to its default value to filter out any subsidiaries.

The period is a bit more complicated. For this, you need to find another fact reported on dei:DocumentPeriodEndDate that gives you the period on which the report ends, which is the balance sheet date. With this date, you can filter the candidate facts and pick the ones that end on that date, and that have one year, or one or several quarters of duration.

Revenues may also be reported for specific scenarios or branches. In this case, simply filter out facts that have any further dimensions.

Normally, if you filter facts based on all the above (concept, entity, period, extra dimensions), you should only have one left, because collisions are very rare and are often mistakes.

Another, different approach for finding the concept is to look at the networks in each filing to programmatically find the statement of consolidated operations that you mention, but this is also not trivial as labels may vary. Then you may be able to infer the revenues concept, and the (absence of) definition network will make sure the dimensions (if any) are right. This may be the way Arelle finds it.

Title: Get specific value from XBRL document


问:
bash scripting - how to loop through results called within a function
I have a function that gives me a list of IPs and for each IP in my list, I want to run a query. The problem I'm having is its only looping through (1) of the results and not the rest.

```<code>getPartition ()
{
    _knife=$(which knife);
    _grep=$(which grep);
    _awk=$(which awk);
    cd ~/home/foo/.chef
    local result=$(${_knife} search "chef_environment:dev AND role:myapp AND ec2_region:us-east-1" | ${_grep} IP | ${_awk} '{ print $2 }');
   read -a servers <<< $result;
   echo "Checking ${#servers[@]} servers";
   for i in ${servers[@]};
   do
       local host='10.1.2.123'
       local db='mystate'
       _mongo=$(which mongo);
       echo -n "$i";
       local exp="db.foobarcluster_servers.find(
       {\"node_host\":\"${i}\",\"node_type\":\"PROCESS\",\"region\":\"us-east-1\",\"status\":\"ACTIVE\"},{\"partition_range_start\":1,\"partition_range_end\":1, _id:0}).pretty();";
       ${_mongo} ${host}/${db} --eval "$exp" | grep -o -e "{[^}]*}";
  done
}
</code>```

So, I tried using for, but its only running the query for (1) of the (5) hosts listed.

I can see in my output for result that the list of IPs look like this:

```<code>+ local 'result=10.8.3.34
10.8.2.161
10.8.3.514
10.8.4.130
10.8.2.173'
</code>```

So, I'm just returning results for (1) of the IPs it should be (5) of them because I have 5 IPs:

```<code>+ read -a servers
+ echo 'Checking 1 servers'
Checking 1 servers
+ for i in ${servers[@]}
+ local host=10.1.2.130
+ local db=mystate
++ which mongo
+ _mongo=/usr/local/bin/mongo
+ echo -n 10.8.3.34
10.8.3.34+ local 'exp=db.foobarcluster_servers.find(
       {"node_host":"10.8.3.34","node_type":"PROCESS","region":"us-east-1","status":"ACTIVE"},{"partition_range_start":1,"partition_range_end":1, _id:0}).pretty();'
+ /usr/local/bin/mongo 10.8.3.34/mystate --eval 'db.foobarcluster_servers.find(
       {"node_host":"10.8.3.34","node_type":"PROCESS","region":"us-east-1","status":"ACTIVE"},{"partition_range_start":1,"partition_range_end":1, _id:0}).pretty();'
+ grep -o -e '{[^}]*}'
{ "partition_range_start" : 31, "partition_range_end" : 31 }
+ set +x
</code>```

Results:

```<code>{ "partition_range_start" : 31, "partition_range_end" : 31 }
</code>```

I'm expecting:

```<code>{ "partition_range_start" : 31, "partition_range_end" : 31 }
{ "partition_range_start" : 32, "partition_range_end" : 32 }
{ "partition_range_start" : 33, "partition_range_end" : 33 }
{ "partition_range_start" : 34, "partition_range_end" : 34 }
{ "partition_range_start" : 35, "partition_range_end" : 35 }
</code>```

How do I effectively loop through my IPs? Did I set up result properly as a variable to hold that list of IPs?

答:
it's because read reads only until first input line delimiter "\n"
adding option -d '', reads until end of input

```<code>result=serv1$'\n'serv2$'\n'serv3

read -a servers <<< $result
printf "<%s>\n" "${servers[@]}"

read -d '' -a servers <<< $result
printf "<%s>\n" "${servers[@]}"
</code>```

There's also readarray builtin which can be used to read an array

```<code>readarray -t servers <<< $result
printf "<%s>\n" "${servers[@]}"
</code>```

-t to remove the newlines for each element of the array

Body:
I have a function that gives me a list of IPs and for each IP in my list, I want to run a query. The problem I'm having is its only looping through (1) of the results and not the rest.

getPartition ()
{
    _knife=$(which knife);
    _grep=$(which grep);
    _awk=$(which awk);
    cd ~/home/foo/.chef
    local result=$(${_knife} search "chef_environment:dev AND role:myapp AND ec2_region:us-east-1" | ${_grep} IP | ${_awk} '{ print $2 }');
   read -a servers <<< $result;
   echo "Checking ${#servers[@]} servers";
   for i in ${servers[@]};
   do
       local host='10.1.2.123'
       local db='mystate'
       _mongo=$(which mongo);
       echo -n "$i";
       local exp="db.foobarcluster_servers.find(
       {\"node_host\":\"${i}\",\"node_type\":\"PROCESS\",\"region\":\"us-east-1\",\"status\":\"ACTIVE\"},{\"partition_range_start\":1,\"partition_range_end\":1, _id:0}).pretty();";
       ${_mongo} ${host}/${db} --eval "$exp" | grep -o -e "{[^}]*}";
  done
}

So, I tried using for, but its only running the query for (1) of the (5) hosts listed.

I can see in my output for result that the list of IPs look like this:

+ local 'result=10.8.3.34
10.8.2.161
10.8.3.514
10.8.4.130
10.8.2.173'

So, I'm just returning results for (1) of the IPs it should be (5) of them because I have 5 IPs:

+ read -a servers
+ echo 'Checking 1 servers'
Checking 1 servers
+ for i in ${servers[@]}
+ local host=10.1.2.130
+ local db=mystate
++ which mongo
+ _mongo=/usr/local/bin/mongo
+ echo -n 10.8.3.34
10.8.3.34+ local 'exp=db.foobarcluster_servers.find(
       {"node_host":"10.8.3.34","node_type":"PROCESS","region":"us-east-1","status":"ACTIVE"},{"partition_range_start":1,"partition_range_end":1, _id:0}).pretty();'
+ /usr/local/bin/mongo 10.8.3.34/mystate --eval 'db.foobarcluster_servers.find(
       {"node_host":"10.8.3.34","node_type":"PROCESS","region":"us-east-1","status":"ACTIVE"},{"partition_range_start":1,"partition_range_end":1, _id:0}).pretty();'
+ grep -o -e '{[^}]*}'
{ "partition_range_start" : 31, "partition_range_end" : 31 }
+ set +x

Results:

{ "partition_range_start" : 31, "partition_range_end" : 31 }

I'm expecting:

{ "partition_range_start" : 31, "partition_range_end" : 31 }
{ "partition_range_start" : 32, "partition_range_end" : 32 }
{ "partition_range_start" : 33, "partition_range_end" : 33 }
{ "partition_range_start" : 34, "partition_range_end" : 34 }
{ "partition_range_start" : 35, "partition_range_end" : 35 }

How do I effectively loop through my IPs? Did I set up result properly as a variable to hold that list of IPs?

Body:
it's because read reads only until first input line delimiter "\n"
adding option -d '', reads until end of input

result=serv1$'\n'serv2$'\n'serv3

read -a servers <<< $result
printf "<%s>\n" "${servers[@]}"

read -d '' -a servers <<< $result
printf "<%s>\n" "${servers[@]}"

There's also readarray builtin which can be used to read an array

readarray -t servers <<< $result
printf "<%s>\n" "${servers[@]}"

-t to remove the newlines for each element of the array


问:
UILabel rounding corners cuts-off text
I am using custom TableCell which has a label with numberofLines = 0

I wanted the label like this.

That is rounded only in three corners.For this to achieve i've written code like this in cell's swift file.I've extended the UIView basically.

```<code>extension UIView {
    func roundCorners(corners:UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}
</code>```

And i've used this like this to round my corners.

```<code>self.chatLabel.roundCorners(corners: [.topLeft,.bottomLeft,.bottomRight], radius: 7.0)
</code>```

But the problem is when label's content is bigger than the cell's row height it's not showing the content

Please just see the second cell's label in first picture .It's content is not showing.
But when i remove the rounded corner's code everything is working fine but lost my corner radius.

Any suggestion is highly appreciated.Thanks.

Edited:

My cell is like this.

And i am achieving chat UI using the code below.

```<code>var cellTypeToDraw:cellType {
        get {
            return self.cellTypeToDraw
        }
        set(newValue) {
            switch newValue {
            case .cellTypeReceiver:
                self.leftImage.isHidden = true
                 self.rightImage.isHidden = false
                self.chatLabel.textAlignment = .right
                self.chatLabel.roundCorners(corners: [.topLeft,.bottomLeft,.bottomRight], radius: 7.0)
            case .cellTypeSender:
                self.rightImage.isHidden = true
                self.leftImage.isHidden = false
                self.chatLabel.textAlignment = .left
                self.chatLabel.roundCorners(corners: [.topRight,.bottomLeft,.bottomRight], radius: 7.0)
            }
            self.leftImage.layer.cornerRadius = self.leftImage.bounds.size.width/2
            self.rightImage.layer.cornerRadius = self.rightImage.bounds.size.width/2
           // self.chatLabel.sizeToFit()
           // self.chatLabel.autoresizingMask = .flexibleHeight
        }
    }
</code>```

and accessing this variable in cellForRowAtIndexPath like this.

```<code> if indexPath.row % 2 != 0 {
            cell.cellTypeToDraw = .cellTypeReceiver
        }
        else {
            cell.cellTypeToDraw = .cellTypeSender
        }
</code>```

答: Add a view insert your label and add some space between your label and that view. </p>

Title: UILabel rounding corners cuts-off text

Body:
I am using custom TableCell which has a label with numberofLines = 0

I wanted the label like this.

That is rounded only in three corners.For this to achieve i've written code like this in cell's swift file.I've extended the UIView basically.

extension UIView {
    func roundCorners(corners:UIRectCorner, radius: CGFloat) {
        let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
    }
}

And i've used this like this to round my corners.

self.chatLabel.roundCorners(corners: [.topLeft,.bottomLeft,.bottomRight], radius: 7.0)

But the problem is when label's content is bigger than the cell's row height it's not showing the content

Please just see the second cell's label in first picture .It's content is not showing.
But when i remove the rounded corner's code everything is working fine but lost my corner radius.

Any suggestion is highly appreciated.Thanks.

Edited:

My cell is like this.

And i am achieving chat UI using the code below.

var cellTypeToDraw:cellType {
        get {
            return self.cellTypeToDraw
        }
        set(newValue) {
            switch newValue {
            case .cellTypeReceiver:
                self.leftImage.isHidden = true
                 self.rightImage.isHidden = false
                self.chatLabel.textAlignment = .right
                self.chatLabel.roundCorners(corners: [.topLeft,.bottomLeft,.bottomRight], radius: 7.0)
            case .cellTypeSender:
                self.rightImage.isHidden = true
                self.leftImage.isHidden = false
                self.chatLabel.textAlignment = .left
                self.chatLabel.roundCorners(corners: [.topRight,.bottomLeft,.bottomRight], radius: 7.0)
            }
            self.leftImage.layer.cornerRadius = self.leftImage.bounds.size.width/2
            self.rightImage.layer.cornerRadius = self.rightImage.bounds.size.width/2
           // self.chatLabel.sizeToFit()
           // self.chatLabel.autoresizingMask = .flexibleHeight
        }
    }

and accessing this variable in cellForRowAtIndexPath like this.

 if indexPath.row % 2 != 0 {
            cell.cellTypeToDraw = .cellTypeReceiver
        }
        else {
            cell.cellTypeToDraw = .cellTypeSender
        }


问:
Shell script to remove backups that are older than 2 Weeks
I have a shell script that takes the backup of the Mongo DB on a daily basis. It's working as expected. Now I need to remove the backups that are older than 2 weeks. Would that be achievable with the current naming convention. Can anyone shed some light? I'm fairly new to shell scripting</p>

```<code>#!/bin/sh
DIR=`date +%m%d%y`
DEST=/dbBackups/$DIR
mkdir $DEST
mongodump --authenticationDatabase admin -h 127.0.0.1 -d pipe -u <username> -p <password>
</code>```

答:
Finally got it with the below script

```<code>#!/bin/sh
DIR=`date +%m%d%y`
DEST=/dbBackups/$DIR
mkdir $DEST
mongodump --authenticationDatabase admin -h 127.0.0.1 -d pipe -u <username> -p <password>
find /dbBackups/* -type d -ctime +14 -exec rm -rf {} +
</code>```

Thanks to Shell script to delete directories older than n days

Body:
I have a shell script that takes the backup of the Mongo DB on a daily basis. It's working as expected. Now I need to remove the backups that are older than 2 weeks. Would that be achievable with the current naming convention. Can anyone shed some light? I'm fairly new to shell scripting

#!/bin/sh
DIR=`date +%m%d%y`
DEST=/dbBackups/$DIR
mkdir $DEST
mongodump --authenticationDatabase admin -h 127.0.0.1 -d pipe -u <username> -p <password>

Body:
Finally got it with the below script

#!/bin/sh
DIR=`date +%m%d%y`
DEST=/dbBackups/$DIR
mkdir $DEST
mongodump --authenticationDatabase admin -h 127.0.0.1 -d pipe -u <username> -p <password>
find /dbBackups/* -type d -ctime +14 -exec rm -rf {} +

Thanks to Shell script to delete directories older than n days


问:
Kotlin on android: Cannot find main merged manifest. What is causing this error?
I wanted to give Kotlin a shot. I converted my java classes to Kotlin and corrected some errors. If I try to build, the following error comes up:

Error:Execution failed for task ':app:generateDebugInstantRunAppInfo'. Cannot find main merged manifest.

This is the manifest file:

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustPan">

        </activity>
        <activity android:name=".Setup_Activity"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
</code>```

Thanks for your help!

答:
I tried both cleaning the project and close-opening it, but they don't work in my case.
After editing the manifest (not a functional change) now project runs. </p>

Body:
I wanted to give Kotlin a shot. I converted my java classes to Kotlin and corrected some errors. If I try to build, the following error comes up:

Error:Execution failed for task ':app:generateDebugInstantRunAppInfo'. Cannot find main merged manifest.

This is the manifest file:

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:windowSoftInputMode="adjustPan">

        </activity>
        <activity android:name=".Setup_Activity"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Thanks for your help!


问:
PHP sum two different minutes
i have two different break time

default break time

extra break time

here i want to sum of two times and display 12 hrs format

EX :

```<code>$default_time = "00:30";
 $extra_time   = "00:25";
</code>```

my expected output : 00:55

but now display 01:00

this is my code

```<code>$default_time = $work_data->break_time;
$break_time =  $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));
</code>```

答:
You could try the following code fragment:</p>

```<code>$time1 = explode(":", $default_time);
$time2 = explode(":", $break_time);
$fulltime = ($time1[0] + $time2[0]) * 60 + $time1[1] + $time2[1];
echo (int)($fulltime / 60) . ":" . ($fulltime % 60);
</code>```

Title: PHP sum two different minutes

Body:
i have two different break time

default break time

extra break time

here i want to sum of two times and display 12 hrs format

EX :

$default_time = "00:30";
 $extra_time   = "00:25";

my expected output : 00:55

but now display 01:00

this is my code

$default_time = $work_data->break_time;
$break_time =  $work_data->extra_time;
$total_break = strtotime($default_time)+strtotime($break_time);
echo date("h:i",strtotime($total_break));

Body:
You could try the following code fragment:

$time1 = explode(":", $default_time);
$time2 = explode(":", $break_time);
$fulltime = ($time1[0] + $time2[0]) * 60 + $time1[1] + $time2[1];
echo (int)($fulltime / 60) . ":" . ($fulltime % 60);


问:
Addressing instance name string in __init__(self) in Python
I am doing something like this:

```<code>class Class(object):
    def __init__(self):
        self.var=#new instance name string#
</code>```

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

```<code>c=Class()
</code>```

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

```<code>c=Class()
</code>```

Then, suppose:

```<code>del c
</code>```

Later on:

```<code>c=Class()
</code>```

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

```<code>c=Class()
</code>```

Then, suppose:

```<code>del c
</code>```

Later on:

```<code>c=Class()
</code>```

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

答:
That isn't possible. You seem to be confusing variables and objects.

In any case there may well not be a variable:

e.g.

```<code>foo(Class())

Class().arbitraryMethod()
</code>```

Or multiple:

```<code>a = b = Class()
</code>```

OwnerDisplayName: xktybot

Body:
I am doing something like this:

class Class(object):
    def __init__(self):
        self.var=#new instance name string#

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

c=Class()

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

LastEditorDisplayName: xktybot

Body:
That isn't possible. You seem to be confusing variables and objects.

In any case there may well not be a variable:

e.g.

foo(Class())

Class().arbitraryMethod()

Or multiple:

a = b = Class()

OwnerDisplayName: Douglas Leeder


问:
SwipeRefreshLayout with Webview not working
This is my webview app code with SwipeRefreshLayout. But SwipeRefresh not working please check it. But all other things are working correctly. Like webview, menu button.

Below is my activity_main.xml file

```<code> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:id="@+id/webView"
        />
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>
</code>```

And this is my MainActivity.java file

```<code>    public class MainActivity extends AppCompatActivity {

    WebView webView;
    SwipeRefreshLayout swipe;

    @Override
    public boolean onCreateOptionsMenu (Menu manu){
        getMenuInflater().inflate(R.menu.main, manu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item){
        int id=item.getItemId();
        if(id==R.id.id_about){
            Intent intentabout=new Intent(MainActivity.this, About.class);
            startActivity(intentabout);

            return true;
        }
        if(id==R.id.id_terms){

            return true;
        }
        if(id==R.id.id_privacy){

            return true;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                LoadWeb();
            }
        });

        LoadWeb();

    }

    public void LoadWeb(){
        webView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webView.loadUrl("https://google.com");
        swipe.setRefreshing(true);
        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/error.html");

            }

            public void onPagefinished(WebView view, String url){
                swipe.setRefreshing(false);
            }
        });
    }

}
</code>```

答:
You should add  </p>

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            LoadWeb();
        }
    });
    swipe.setRefreshing(true); //add
    LoadWeb();

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

Body:
This is my webview app code with SwipeRefreshLayout. But SwipeRefresh not working please check it. But all other things are working correctly. Like webview, menu button.

Below is my activity_main.xml file

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:id="@+id/webView"
        />
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

And this is my MainActivity.java file

    public class MainActivity extends AppCompatActivity {

    WebView webView;
    SwipeRefreshLayout swipe;

    @Override
    public boolean onCreateOptionsMenu (Menu manu){
        getMenuInflater().inflate(R.menu.main, manu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected (MenuItem item){
        int id=item.getItemId();
        if(id==R.id.id_about){
            Intent intentabout=new Intent(MainActivity.this, About.class);
            startActivity(intentabout);

            return true;
        }
        if(id==R.id.id_terms){

            return true;
        }
        if(id==R.id.id_privacy){

            return true;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                LoadWeb();
            }
        });

        LoadWeb();

    }

    public void LoadWeb(){
        webView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAppCacheEnabled(true);
        webView.loadUrl("https://google.com");
        swipe.setRefreshing(true);
        webView.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                webView.loadUrl("file:///android_asset/error.html");

            }

            public void onPagefinished(WebView view, String url){
                swipe.setRefreshing(false);
            }
        });
    }

}

Body:
You should add

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            LoadWeb();
        }
    });
    swipe.setRefreshing(true); //add
    LoadWeb();

}
LoadWeb();


答:
Good idea using set -x - another good debugging tactic (that also makes reading set -x easier) would be to comment out parts that aren't relevant to the issue (e.g. make the for loop simply print its iterations, hard-code the value of result, etc.) to try to narrow down the issue.

If I try to replicate what you're doing myself:

```<code>demo() {
  local result='10.8.3.34
10.8.2.161
10.8.3.514
10.8.4.130
10.8.2.173'
  read -a servers <<< $result
  echo "Checking ${#servers[@]} servers"
  for i in ${servers[@]}; do
    echo "$i"
  done
}
</code>```

Which outputs (with set -x):

```<code>$ demo
+ demo
+ local 'result=10.8.3.34
10.8.2.161
10.8.3.514
10.8.4.130
10.8.2.173'
+ read -a servers
+ echo 'Checking 5 servers'
Checking 5 servers
+ for i in '${servers[@]}'
+ echo 10.8.3.34
10.8.3.34
+ for i in '${servers[@]}'
+ echo 10.8.2.161
10.8.2.161
+ for i in '${servers[@]}'
+ echo 10.8.3.514
10.8.3.514
+ for i in '${servers[@]}'
+ echo 10.8.4.130
10.8.4.130
+ for i in '${servers[@]}'
+ echo 10.8.2.173
10.8.2.173
</code>```

In other words, the code you shared appears to be working as expected. Perhaps there's a typo you corrected while transcribing?

A key thing to note (per help read) is that read "Reads a single line from the standard input ... the line is split into fields as with word splitting". In other words, a multi-line input does not all get read by a call to read, only the first line does. We can test this by tweaking the demo function above to use:

```<code>read -a servers <<< "$result"
</code>```

Which causes the output you describe:

```<code>$ demo
+ demo
+ local 'result=10.8.3.34
    10.8.2.161
    10.8.3.514
    10.8.4.130
    10.8.2.173'
+ read -a servers
+ echo 'Checking 1 servers'
Checking 1 servers
+ for i in '${servers[@]}'
+ echo 10.8.3.34
10.8.3.34
</code>```

So that's likely the source of your issue - by quoting $result (which generally is a good idea) read respects the newlines separating the elements, and stops reading after it sees the first one.

Instead use the readarray command, which has more sane behavior for tasks like this. It will "read lines from a file into an array variable", rather than stopping after the first line.

You can then skip the indirection of writing to result, as well, and just pipe directly into readarray:

```<code>readarray -t servers < <(
  ${_knife} search "chef_environment:dev AND role:myapp AND ec2_region:us-east-1"
    | ${_grep} IP | ${_awk} '{ print $2 }')
</code>```

Title: bash scripting - how to loop through results called within a function

Body:
Good idea using set -x - another good debugging tactic (that also makes reading set -x easier) would be to comment out parts that aren't relevant to the issue (e.g. make the for loop simply print its iterations, hard-code the value of result, etc.) to try to narrow down the issue.

If I try to replicate what you're doing myself:

demo() {
  local result='10.8.3.34
10.8.2.161
10.8.3.514
10.8.4.130
10.8.2.173'
  read -a servers <<< $result
  echo "Checking ${#servers[@]} servers"
  for i in ${servers[@]}; do
    echo "$i"
  done
}

Which outputs (with set -x):

$ demo
+ demo
+ local 'result=10.8.3.34
10.8.2.161
10.8.3.514
10.8.4.130
10.8.2.173'
+ read -a servers
+ echo 'Checking 5 servers'
Checking 5 servers
+ for i in '${servers[@]}'
+ echo 10.8.3.34
10.8.3.34
+ for i in '${servers[@]}'
+ echo 10.8.2.161
10.8.2.161
+ for i in '${servers[@]}'
+ echo 10.8.3.514
10.8.3.514
+ for i in '${servers[@]}'
+ echo 10.8.4.130
10.8.4.130
+ for i in '${servers[@]}'
+ echo 10.8.2.173
10.8.2.173

In other words, the code you shared appears to be working as expected. Perhaps there's a typo you corrected while transcribing?

A key thing to note (per help read) is that read "Reads a single line from the standard input ... the line is split into fields as with word splitting". In other words, a multi-line input does not all get read by a call to read, only the first line does. We can test this by tweaking the demo function above to use:

read -a servers <<< "$result"

Which causes the output you describe:

$ demo
+ demo
+ local 'result=10.8.3.34
    10.8.2.161
    10.8.3.514
    10.8.4.130
    10.8.2.173'
+ read -a servers
+ echo 'Checking 1 servers'
Checking 1 servers
+ for i in '${servers[@]}'
+ echo 10.8.3.34
10.8.3.34

So that's likely the source of your issue - by quoting $result (which generally is a good idea) read respects the newlines separating the elements, and stops reading after it sees the first one.

Instead use the readarray command, which has more sane behavior for tasks like this. It will "read lines from a file into an array variable", rather than stopping after the first line.

You can then skip the indirection of writing to result, as well, and just pipe directly into readarray:

readarray -t servers < <(
  ${_knife} search "chef_environment:dev AND role:myapp AND ec2_region:us-east-1"
    | ${_grep} IP | ${_awk} '{ print $2 }')