问:
Color a column by searching a particular text in A:A
Assist me with a VBA to color column from A:G, by searching a specific text, say 'UK'in Column A

答:
Try this. Code1 works on every sheet in the workbook but if you like for this to work for the active sheet then try Code2. For Code2 remember to write the correct sheets name. Hope it helps.

Here you can choose an index color: https://stackoverflow.com/a/25000926/7238313

Code1:

```<code>Sub rowhighlight()
Dim sht As Worksheet
Dim nlast As Long

For Each sht In ActiveWorkbook.Worksheets
    sht.Select
    nlast = Cells(Rows.Count, "A").End(xlUp).Row

        For n = nlast To 2 Step -1
            If sht.Cells(n, "A").Value = "UK" Then
                sht.Range("A" & n, "G" & n).Interior.ColorIndex = 37
                'different color number place here----------------^
            End If
        Next n
     Next sht
 End Sub
</code>```

Code2:

```<code>Sub rowhighlight()
Dim nlast As Long

Sheets("sheetname").Activate
Set sht = ActiveWorkbook.ActiveSheet
nlast = Cells(Rows.Count, "A").End(xlUp).Row

    For n = nlast To 2 Step -1
        If sht.Cells(n, "A").Value = "UK" Then
            sht.Range("A" & n, "G" & n).Interior.ColorIndex = 37
            'different color number place here----------------^
        End If
    Next n
End Sub
</code>```

Body:
Try this. Code1 works on every sheet in the workbook but if you like for this to work for the active sheet then try Code2. For Code2 remember to write the correct sheets name. Hope it helps.

Here you can choose an index color: https://stackoverflow.com/a/25000926/7238313

Code1:

Sub rowhighlight()
Dim sht As Worksheet
Dim nlast As Long

For Each sht In ActiveWorkbook.Worksheets
    sht.Select
    nlast = Cells(Rows.Count, "A").End(xlUp).Row

        For n = nlast To 2 Step -1
            If sht.Cells(n, "A").Value = "UK" Then
                sht.Range("A" & n, "G" & n).Interior.ColorIndex = 37
                'different color number place here----------------^
            End If
        Next n
     Next sht
 End Sub

Code2:

Sub rowhighlight()
Dim nlast As Long

Sheets("sheetname").Activate
Set sht = ActiveWorkbook.ActiveSheet
nlast = Cells(Rows.Count, "A").End(xlUp).Row

    For n = nlast To 2 Step -1
        If sht.Cells(n, "A").Value = "UK" Then
            sht.Range("A" & n, "G" & n).Interior.ColorIndex = 37
            'different color number place here----------------^
        End If
    Next n
End Sub


来源: stackexchange

问:
Do we need interfaces for dependency injection?
I have an ASP.NET Core application. The application has few helper classes that does some work. Each class has different signature method. I see lot of .net core examples online that create interface for each class and then register types with DI framework. For example

```<code> public interface IStorage
 {
    Task Download(string file);
 }

 public class Storage
 {
    public Task Download(string file)
    {
    }
 }

 public interface IOcr
 {
     Task Process();
 }

 public class Ocr:IOcr
 {
    public Task Process()
    {

    }
 }
</code>```

Basically for each interface there is only one class. Then i register these types with DI as

```<code> services.AddScoped<IStorage, Storage>();
 services.AddScoped<IOcr,Ocr>();
</code>```

But i can register type without having interfaces so interfaces here look redundant. eg

```<code> services.AddScoped<Storage>();
 services.AddScoped<Ocr>();
</code>```

So do i really need interfaces?

答:
Does it work? Yes. Should you do it? No.

Dependency Injection is a tool for the principle of Dependency Inversion : https://en.wikipedia.org/wiki/Dependency_inversion_principle

Or as it's described in SOLID

one should “depend upon abstractions, [not] concretions."

You can just inject concrete classes all over the place and it will work. But it's not what DI was designed to achieve.

ContentLicense: CC BY-SA 4.0

Body:
I have an ASP.NET Core application. The application has few helper classes that does some work. Each class has different signature method. I see lot of .net core examples online that create interface for each class and then register types with DI framework. For example

 public interface IStorage
 {
    Task Download(string file);
 }

 public class Storage
 {
    public Task Download(string file)
    {
    }
 }

 public interface IOcr
 {
     Task Process();
 }

 public class Ocr:IOcr
 {
    public Task Process()
    {

    }
 }

Basically for each interface there is only one class. Then i register these types with DI as

 services.AddScoped<IStorage, Storage>();
 services.AddScoped<IOcr,Ocr>();

But i can register type without having interfaces so interfaces here look redundant. eg

 services.AddScoped<Storage>();
 services.AddScoped<Ocr>();

So do i really need interfaces?

ContentLicense: CC BY-SA 3.0


问:
Send form data with JWT
Actually i have two websites and the one which is suppose to receive the data is not parametered in https and will not be.
Can I use the JWT technique to send form data from one server two another on a http connnection. I'm thinking of big textarea messages.
The first website receives the data with https connection stores it in a JWT and sends it with curl to the second server with http connection.
I know that it's not the original purpose of JWT but do you think good partice? Do i risk to encounter errors during encoding and decoding en large amounts of text?</p>

答:
I suggest you use rsync. It can work over a SSH connection to protect your data and is smart enough to sync only changed files.

JWT are not designed to send large amount of data between servers. It is in fact a format to transmit claims between servers or between a client and a server. Those claims can be digitally signed (JWS - See RFC7515), encrypted (JWE - See RFC7516) or both (signed then encrypted). They are usually compact as they are mainly used in a web context.

Title: Send form data with JWT


问:
Swagger UI model rendering issue in WSO2
Swagger UI in a WSO2 application renders model schemas in the Model tab incorrectly. Currently it shows the HTML markup as is:

It is supposed to look like this:

I would really appreciate if someone can enlighten me what's wrong and how can I fix that.

答:
This is a known issue in WSO2 2.0.0 version and the fix is located here:
https://github.com/wso2/carbon-apimgt/pull/3271/files</p>


问:
Return from a statement after callback is complete
Basically I'm looking for a smart way to have the function return after the callback within dbInteractionComplete has finished running.

Currently the function returns before the callback has completed, obviously. Maybe there is a smart way of getting the return to wait until the callback has finished?

```<code>private List<Post> toggle() {

    final List<Post> postList = new ArrayList<>();
    final QuestionnaireWrapper mCurrentQuestionnaireWrapper = DatabaseHelper.getCurrentQuestionnaire(teamId);
    if (mCurrentQuestionnaireWrapper != null) {
        if (mCurrentQuestionnaireWrapper.isCompleted()) {
            final QuestionnaireFeedbackDialog mQuestionnaireFeedbackDialog = QuestionnaireFeedbackDialog.newInstance(mCurrentQuestionnaireWrapper.getQuestionnaire().getFeedback());
            mQuestionnaireFeedbackDialog.show(getChildFragmentManager(), "questionnaire_feedback");
            final String uniqueId = teamId + "," + mCurrentQuestionnaireWrapper.getRemoteId();
            DatabaseHelper.deleteQuestionnaire(teamId, uniqueId, new DBCallbackInterface() {
                @Override
                public void dbInteractionComplete() {
                    final QuestionnaireWrapper mNextCurrentQuestionnaire = DatabaseHelper.getCurrentQuestionnaire(teamId);
                    if (mNextCurrentQuestionnaire != null) {
                        mCurrentQuestionnaire = mNextCurrentQuestionnaire.getQuestionnaire();
                        final Post post = new Post();
                        post.setType(Questionnaire.QUESTIONNAIRE_FEED_TYPE);
                        postList.add(post);
                    }
                }
            });
            return postList;
        }
    }
}
</code>```

答:
Create an interface :
public interface SomeInterface { void callback (List<Post>) ;}

Create a class which implements DBCallbackInterface:

```<code>    public static class SomeNewClass implements DBCallbackInterface {

    private List<Post> list;

    private SomeInterface iAmAwsome;
    private int teamId;
    public SomeNewClass(List<Post> list, SomeInterface iAmAwsome, int teamId) {

    this.list = list;

    this.iAmAwsome = iAmAwsome;

    this.teamId = teamId;
    }

    @Override
     public void dbInteractionComplete() {
final QuestionnaireWrapper mNextCurrentQuestionnaire = DatabaseHelper.getCurrentQuestionnaire(teamId);
  if (mNextCurrentQuestionnaire != null) {
                                mCurrentQuestionnaire = mNextCurrentQuestionnaire.getQuestionnaire();
                                final Post post = new Post();
                                post.setType(Questionnaire.QUESTIONNAIRE_FEED_TYPE);              list.add(post);

    if (iAmAwsome! = null)
iAmAwsome.callback(list) ;
    }
    }
</code>```

Usage: inside your toggle method :

```<code>DatabaseHelper.deleteQuestionnaire(teamId, uniqueId,  new SomeNewClass(postList, new SomeInterface() {
@Override
                public void callback(List<Post>yourdata){code here } }, teamId)
</code>```

Body:
Basically I'm looking for a smart way to have the function return after the callback within dbInteractionComplete has finished running.

Currently the function returns before the callback has completed, obviously. Maybe there is a smart way of getting the return to wait until the callback has finished?

private List<Post> toggle() {

    final List<Post> postList = new ArrayList<>();
    final QuestionnaireWrapper mCurrentQuestionnaireWrapper = DatabaseHelper.getCurrentQuestionnaire(teamId);
    if (mCurrentQuestionnaireWrapper != null) {
        if (mCurrentQuestionnaireWrapper.isCompleted()) {
            final QuestionnaireFeedbackDialog mQuestionnaireFeedbackDialog = QuestionnaireFeedbackDialog.newInstance(mCurrentQuestionnaireWrapper.getQuestionnaire().getFeedback());
            mQuestionnaireFeedbackDialog.show(getChildFragmentManager(), "questionnaire_feedback");
            final String uniqueId = teamId + "," + mCurrentQuestionnaireWrapper.getRemoteId();
            DatabaseHelper.deleteQuestionnaire(teamId, uniqueId, new DBCallbackInterface() {
                @Override
                public void dbInteractionComplete() {
                    final QuestionnaireWrapper mNextCurrentQuestionnaire = DatabaseHelper.getCurrentQuestionnaire(teamId);
                    if (mNextCurrentQuestionnaire != null) {
                        mCurrentQuestionnaire = mNextCurrentQuestionnaire.getQuestionnaire();
                        final Post post = new Post();
                        post.setType(Questionnaire.QUESTIONNAIRE_FEED_TYPE);
                        postList.add(post);
                    }
                }
            });
            return postList;
        }
    }
}

Body:
Create an interface :
public interface SomeInterface { void callback (List<Post>) ;}

Create a class which implements DBCallbackInterface:

    public static class SomeNewClass implements DBCallbackInterface {

    private List<Post> list;

    private SomeInterface iAmAwsome;
    private int teamId;
    public SomeNewClass(List<Post> list, SomeInterface iAmAwsome, int teamId) {

    this.list = list;

    this.iAmAwsome = iAmAwsome;

    this.teamId = teamId;
    }

    @Override
     public void dbInteractionComplete() {
final QuestionnaireWrapper mNextCurrentQuestionnaire = DatabaseHelper.getCurrentQuestionnaire(teamId);
  if (mNextCurrentQuestionnaire != null) {
                                mCurrentQuestionnaire = mNextCurrentQuestionnaire.getQuestionnaire();
                                final Post post = new Post();
                                post.setType(Questionnaire.QUESTIONNAIRE_FEED_TYPE);              list.add(post);

    if (iAmAwsome! = null)
iAmAwsome.callback(list) ;
    }
    }

Usage: inside your toggle method :

DatabaseHelper.deleteQuestionnaire(teamId, uniqueId,  new SomeNewClass(postList, new SomeInterface() {
@Override
                public void callback(List<Post>yourdata){code here } }, teamId)


问:
Update attributes unless blank?
I have an existing Project record, and I'm importing a CSV file  to update the associated Project attributes. However, often the CSV will contain blank fields and I don't want to overright exisiting attributes if the related CSV field is blank.

Something like this:

```<code>project.update_attributes(:name => row.field('project_name') unless row.field('project_name').blank?,
                          :owner => row.field('project_owner') unless row.field('project_owner').blank?,
                          :due_date => row.field('project_due_date') unless row.field('project_due_date').blank?)
</code>```

答:
You can do this from the controller if needed:

```<code>def some_params
    params.permit(:foo, :bar).reject { |_, v| v.blank? }
end
</code>```

In this case the attributes won't be saved if they are blank

ContentLicense: CC BY-SA 2.5

Title: Update attributes unless blank?

Body:
I have an existing Project record, and I'm importing a CSV file  to update the associated Project attributes. However, often the CSV will contain blank fields and I don't want to overright exisiting attributes if the related CSV field is blank.

Something like this:

project.update_attributes(:name => row.field('project_name') unless row.field('project_name').blank?,
                          :owner => row.field('project_owner') unless row.field('project_owner').blank?,
                          :due_date => row.field('project_due_date') unless row.field('project_due_date').blank?)

Body:
You can do this from the controller if needed:

def some_params
    params.permit(:foo, :bar).reject { |_, v| v.blank? }
end

In this case the attributes won't be saved if they are blank


问:
Reading a specific sector from a hard drive using C on Linux (GNU/Linux )
I know that a hard drive are system's files (/dev/sdXX) –then treated like files-, I have questions about this:

I tried those following lines of code but nothing positive

-------first attempt----------

```<code>int numSecteur=2;
char secteur [512];
FILE* disqueF=fopen("/dev/sda","r"); //tried "rb" and sda1 ...every thing
fseek(disqueF, numSecteur*512,SEEK_SET);
fread(secteur, 512, 1, disqueF);
fclose(disqueF);
</code>```

-------Second attempt----------

```<code>    int i=open("/dev/sda1",O_RDONLY);
    lseek(i, 0, SEEK_SET);
    read(i,secteur,512);
    close(i);
</code>```

------printing the results----------

```<code>printf("hex : %04x\n",secteur);
printf("string : %s\n",secteur);
</code>```

Why the size is of the file /dev/sda1 is just 8 KBytes ?

How the data is stored (binary or hex….) "for the printing"

Please, I need some clues, and if someone need more details just he ask.

Thanks a lot.

Ps: Running kali 2 64bits ”debian” on VMware and i am RooT.

答:
I tried those following lines of code but nothing positive

That's not a question.

Why the size is of the file /dev/sda1 is just 8 KBytes ?

That isn't the file size, it's the device number. (There are two parts, so the device number of sda1 is 8,1)

How the data is stored (binary or hex….) "for the printing"

Data isn't "stored for the printing". Data is stored (in electrical voltages representing binary, but you don't need to know that), and you can print it any way you want.

Body:
I know that a hard drive are system's files (/dev/sdXX) –then treated like files-, I have questions about this:

I tried those following lines of code but nothing positive

-------first attempt----------

int numSecteur=2;
char secteur [512];
FILE* disqueF=fopen("/dev/sda","r"); //tried "rb" and sda1 ...every thing
fseek(disqueF, numSecteur*512,SEEK_SET);
fread(secteur, 512, 1, disqueF);
fclose(disqueF);

-------Second attempt----------

    int i=open("/dev/sda1",O_RDONLY);
    lseek(i, 0, SEEK_SET);
    read(i,secteur,512);
    close(i);

------printing the results----------

printf("hex : %04x\n",secteur);
printf("string : %s\n",secteur);

Why the size is of the file /dev/sda1 is just 8 KBytes ?

How the data is stored (binary or hex….) "for the printing"

Please, I need some clues, and if someone need more details just he ask.

Thanks a lot.

Ps: Running kali 2 64bits ”debian” on VMware and i am RooT.


问:
The number of characters in each unicode block
Does anyone know any reference showing the number of characters in each Unicode block? (in newer version such as 5.x.x or 6.0.0)

Thanks a lot.

答:
http://www.unicode.org/Public/6.0.0/ucd/UnicodeData.txt contains the data you are interested in.

http://www.unicode.org/Public/6.0.0/ucd/ReadMe.txt contains some instructions and refers to http://unicode.org/reports/tr44/ for interpreting the data. In that document you should read http://unicode.org/reports/tr44/#UnicodeData.txt.


问:
How to combine two dataframes and have unique key column using Pandas?
I have two dataframes with the same columns that I need to combine:

```<code>  first_name last_name
0   Alex    Anderson
1   Amy     Ackerman
2   Allen   Ali
</code>```

and

```<code>  first_name last_name
0    Billy  Bonder
1    Brian  Black
2    Bran   Balwner
</code>```

When I do this:

```<code>df_new = pd.concat([df1, df1])
</code>```

I get this:

```<code>   first_name last_name
0   Alex    Anderson
1   Amy     Ackerman
2   Allen   Ali
0   Billy   Bonder
1   Brian   Black
2   Bran    Balwner
</code>```

Is there a way to have the left column have a unique number like this?

```<code>  first_name last_name
0   Alex    Anderson
1   Amy     Ackerman
2   Allen   Ali
3   Billy   Bonder
4   Brian   Black
5   Bran    Balwner
</code>```

If not, how can I add a new key column with numbers from 1 to whatever the row count is?

答:
As said earlier by @MaxU you can use ignore_index=True.

If you want to keep the index of your first table you can use the parameter ignore_index=True after the [dataframe1, dataframe2].

You can check if the indexes are being repeated with the paremeter verify_integrity=True it will return a boolean (you never know when you'll have to check.
But be careful because this procedure can be a little slow depending on the size of you Dataframe

Body:
I have two dataframes with the same columns that I need to combine:

  first_name last_name
0   Alex    Anderson
1   Amy     Ackerman
2   Allen   Ali

and

  first_name last_name
0    Billy  Bonder
1    Brian  Black
2    Bran   Balwner

When I do this:

df_new = pd.concat([df1, df1])

I get this:

   first_name last_name
0   Alex    Anderson
1   Amy     Ackerman
2   Allen   Ali
0   Billy   Bonder
1   Brian   Black
2   Bran    Balwner

Is there a way to have the left column have a unique number like this?

  first_name last_name
0   Alex    Anderson
1   Amy     Ackerman
2   Allen   Ali
3   Billy   Bonder
4   Brian   Black
5   Bran    Balwner

If not, how can I add a new key column with numbers from 1 to whatever the row count is?


问:
Django Models and Permission Restrictions
Models:

Company

Product

We have a parent company (owner of all) who can create any Company and any Product, as sub-Company or sub-Product.

Now, what I'd like to accomplish, is limiting which Company can CRUD other Companies and Products alike.

Here's are the scenarios:

Company and Sub-Companies (sub-contractors):

```<code>Master (creates) -> Company “A”
Master (creates) -> Company “B” (creates) -> Company “C”
Master (creates) -> Company “D” (creates) -> Company “F” (creates) -> Company “G”
</code>```

Company and Product Assignment:

```<code>Master (Add Product) -> Show all products
Master (assign products to top levels) -> Company “A”, Company “B” and Company ”D”
</code>```

Sub-Company Product Assignment (management):

```<code>Company “B” (assign products only to sub-level) -> Company “C”
Company “D” (assign products only to sub-level) -> Company “F”
Company “F” (assign products only to sub-level) -> Company “G”
</code>```

However, if Company D removes a product from a sub-level, this will also remove from all sub-level products recursively.

Are there any sure ways of doing this with Django core, or perhaps there's a recommended library out there that I'm not finding? I also saw in the Django docs reference to Model Meta options and the Options.permissions method... but I'm not sure that's what I'm needing either.

答:
The best package I can suggest you is DJANGO GUARDIAN. But what you are really looking for Role Based Access Control Logic.

Unfortunately django-guardian doesn't support roles. Linked issue. So I suggest you write your own views for that. But you can look into these below packages:

django-role-permissions

django-rbac

django-group-access

django-teamwork

Body:
Models:

Company

Product

We have a parent company (owner of all) who can create any Company and any Product, as sub-Company or sub-Product.

Now, what I'd like to accomplish, is limiting which Company can CRUD other Companies and Products alike.

Here's are the scenarios:

Company and Sub-Companies (sub-contractors):

Master (creates) -> Company “A”
Master (creates) -> Company “B” (creates) -> Company “C”
Master (creates) -> Company “D” (creates) -> Company “F” (creates) -> Company “G”

Company and Product Assignment:

Master (Add Product) -> Show all products
Master (assign products to top levels) -> Company “A”, Company “B” and Company ”D”

Sub-Company Product Assignment (management):

Company “B” (assign products only to sub-level) -> Company “C”
Company “D” (assign products only to sub-level) -> Company “F”
Company “F” (assign products only to sub-level) -> Company “G”

However, if Company D removes a product from a sub-level, this will also remove from all sub-level products recursively.

Are there any sure ways of doing this with Django core, or perhaps there's a recommended library out there that I'm not finding? I also saw in the Django docs reference to Model Meta options and the Options.permissions method... but I'm not sure that's what I'm needing either.


问:
Using color variables in blueprintjs
Is it necessary to use a css preprocessor like less or sass to be able to access the defined color variables in Blueprint.Colors?
I've looked at the source and those only appear on .scss and .less files. However, the documentation assumes the variables are accessible with the default setup. </p>

答:
Blueprint.Colors is a JS object that can be used in your JS code. It does not require a CSS preprocessor because it's just a plain JS object (source code). Examples: Blueprint.Colors.BLACK, Blueprint.Colors.BLUE3.

The Sass variables all begin with $ and can only be used in Sass files that import the Blueprint variables.scss file. Examples: $black, $blue3. (Less variables have the same names but use an @ prefix: @black.)

(It's also possible, but nontrivial, to use the JS variables in a CSS preprocessor. We do this internally by generating the Sass variables from the JS object.)

Title: Using color variables in blueprintjs


问:
Heroku Console won't boot- cannot load such file -- rack/handler/console
When I run heroku run rails console, my stack trace reads:

```<code>Running rails console on ⬢ canvas-gattaca... up, run.8126 (Standard-1X)
Exiting
/app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:274:in `require': cannot load such file -- rack/handler/console (LoadError)
    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:274:in `block in require'
    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:240:in `load_dependency'
    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:274:in `require'
    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/handler.rb:90:in `try_require'
    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/handler.rb:16:in `get'
    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/server.rb:290:in `server'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/server.rb:125:in `print_boot_information'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/server.rb:75:in `start'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/commands_tasks.rb:80:in `block in server'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/commands_tasks.rb:75:in `tap'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/commands_tasks.rb:75:in `server'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:9:in `require'
    from bin/rails:9:in `<main>'
</code>```

My logs read:

```<code>2017-03-28T19:02:33.583671+00:00 app[api]: Starting process with command `bundle exec rails server console` by user ccromar@instructure.com
2017-03-28T19:02:37.784210+00:00 heroku[run.4264]: Awaiting client
2017-03-28T19:02:37.827306+00:00 heroku[run.4264]: Starting process with command `bundle exec rails server console`
2017-03-28T19:02:38.058988+00:00 heroku[run.4264]: State changed from starting to up
2017-03-28T19:02:45.391746+00:00 heroku[run.4264]: State changed from up to complete
2017-03-28T19:02:45.377045+00:00 heroku[run.4264]: Process exited with status 1
</code>```

My Procfile-

```<code>rails: bundle exec rails server
webpack: ./node_modules/.bin/webpack-dev-server --config config/webpack.config.js
</code>```

Am I missing anything?

答:
You can try this way:

heroku run console

Body:
When I run heroku run rails console, my stack trace reads:

Running rails console on ⬢ canvas-gattaca... up, run.8126 (Standard-1X)
Exiting
/app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:274:in `require': cannot load such file -- rack/handler/console (LoadError)
    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:274:in `block in require'
    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:240:in `load_dependency'
    from /app/vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.2/lib/active_support/dependencies.rb:274:in `require'
    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/handler.rb:90:in `try_require'
    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/handler.rb:16:in `get'
    from /app/vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/server.rb:290:in `server'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/server.rb:125:in `print_boot_information'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/server.rb:75:in `start'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/commands_tasks.rb:80:in `block in server'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/commands_tasks.rb:75:in `tap'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/commands_tasks.rb:75:in `server'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.2/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:9:in `require'
    from bin/rails:9:in `'

My logs read:

2017-03-28T19:02:33.583671+00:00 app[api]: Starting process with command `bundle exec rails server console` by user ccromar@instructure.com
2017-03-28T19:02:37.784210+00:00 heroku[run.4264]: Awaiting client
2017-03-28T19:02:37.827306+00:00 heroku[run.4264]: Starting process with command `bundle exec rails server console`
2017-03-28T19:02:38.058988+00:00 heroku[run.4264]: State changed from starting to up
2017-03-28T19:02:45.391746+00:00 heroku[run.4264]: State changed from up to complete
2017-03-28T19:02:45.377045+00:00 heroku[run.4264]: Process exited with status 1

My Procfile-

rails: bundle exec rails server
webpack: ./node_modules/.bin/webpack-dev-server --config config/webpack.config.js

Am I missing anything?


问:
Spark - how to write files with a given permission
I tried to write some files from spark with 750 permission with the following way
I updated the fs.permissions.umask-mode in the code

```<code>jsc.hadoopConfiguration().set("fs.permissions.umask-mode", "022");
</code>```

It's successfully updated the default umask.

Than I tried to write some RDD on disk, but the file permissions weren't align the the mask I applied. The files didn't have the expected 750 permission.

Code example:

```<code>public class Bla {
    public static void main(String[] args) throws Exception {
    SparkConf sConf = new SparkConf().setAppName("test hadoop config ");
    JavaSparkContext jsc = new JavaSparkContext(sConf);
    JavaRDD<String> stringJavaRDD = jsc.textFile("/path/a.txt");
    stringJavaRDD.saveAsTextFile("/path/def_umask");
    System.out.println("fs.permissions.umask-mode " +
            jsc.hadoopConfiguration().get("fs.permissions.umask-mode"));
    jsc.hadoopConfiguration().set("fs.permissions.umask-mode", "022");
    System.out.println("after mod -- fs.permissions.umask-mode " +
            jsc.hadoopConfiguration().get("fs.permissions.umask-mode"));
    // < this succeed
    stringJavaRDD.saveAsTextFile("/path/updated_umask");
    // < files has the same permission as before the umask change :(

    jsc.stop();
}
</code>```

What do I miss here? How should I do it?
Spark 1.6.3

答:
Actually I get the answer from another source.

```<code>--conf spark.hadoop.fs.permissions.umask-mode=022
</code>```

This setting is coordinating permission in the submitted job (all writes will have this permission).
I tested this and works fine.

OR

It's possible to set the permission for a given path in the code

```<code>FileSystem.get(path, conf).setPermission(...)
</code>```

Body:
I tried to write some files from spark with 750 permission with the following way
I updated the fs.permissions.umask-mode in the code

jsc.hadoopConfiguration().set("fs.permissions.umask-mode", "022");

It's successfully updated the default umask.

Than I tried to write some RDD on disk, but the file permissions weren't align the the mask I applied. The files didn't have the expected 750 permission.

Code example:

public class Bla {
    public static void main(String[] args) throws Exception {
    SparkConf sConf = new SparkConf().setAppName("test hadoop config ");
    JavaSparkContext jsc = new JavaSparkContext(sConf);
    JavaRDD<String> stringJavaRDD = jsc.textFile("/path/a.txt");
    stringJavaRDD.saveAsTextFile("/path/def_umask");
    System.out.println("fs.permissions.umask-mode " +
            jsc.hadoopConfiguration().get("fs.permissions.umask-mode"));
    jsc.hadoopConfiguration().set("fs.permissions.umask-mode", "022");
    System.out.println("after mod -- fs.permissions.umask-mode " +
            jsc.hadoopConfiguration().get("fs.permissions.umask-mode"));
    // < this succeed
    stringJavaRDD.saveAsTextFile("/path/updated_umask");
    // < files has the same permission as before the umask change :(

    jsc.stop();
}

What do I miss here? How should I do it?
Spark 1.6.3

Body:
Actually I get the answer from another source.

--conf spark.hadoop.fs.permissions.umask-mode=022

This setting is coordinating permission in the submitted job (all writes will have this permission).
I tested this and works fine.

OR

It's possible to set the permission for a given path in the code

FileSystem.get(path, conf).setPermission(...)


问:
Is there a way in CSS to calculate line height from em?
Let's say I want an img to be the same height as a line of text.  Is there some way to set this up.  My first thought was something like this:

```
<table>
    <td>
        <img src="pict.png" style="height: 1em"/>
        <img src="pict.png" style="height: 1em"/>
    </td>
    <td>
        The text<br/>
        The second line<br/>
    </td>
</table>
```

However, with that example, the height of the picture is less than the line.   After a few lines the difference becomes very noticeable.  Does anyone have any suggestions?

Also, it looks like for my font 1.15 em is about equal to the line height.  Does this make sense to anyone?

答:
your images are the same height as the line of text in your example.  (see it here).
if it looks differently in your project, you can try setting line-height: 1em in your table, and make sure that font-size: 1em.

as for part two:
i hope this image helps explain the relationship between line-height and font-size:

Body:
Let's say I want an img to be the same height as a line of text.  Is there some way to set this up.  My first thought was something like this:

        The text

        The second line

However, with that example, the height of the picture is less than the line.   After a few lines the difference becomes very noticeable.  Does anyone have any suggestions?

Also, it looks like for my font 1.15 em is about equal to the line height.  Does this make sense to anyone?


问:
Angular 2 Universal - Server-side Rendering
I was reading about Angular 2 Server side rendering with node.

But I cannot find an example or explain how should I do that.
I need to render some pages with angular from server, any advice?

答:
There's another example repo at https://github.com/ng-seed/universal showcasing both Universal and lean Angular on a single project.

This application uses platform-server delivered with Angular 4.0.0, and it could be a good starter/seed project until Angular provides some documentation about the use of platform-server.

Furthermore, it covers most of the features of angular2-webpack-starter by AngularClass such as async/lazy routes, SCSS compilation (both inline and external), dev/prod modes, AoT compilation via @ngtools/webpack, tests, TsLint/Codelyzer, @types and maybe more.

Disclosure: I'm the author too :)


问:
What is the best way to count all instances of a single process running under a particular user logon?
I understand how to use Mutex to limit an application to run only a single instance at one time.  However, in my application I allow multiple instances to run simultaneously, but I need a way to count and/or list all of the running instances for a given user, regardless of whether or not the executable file has been renamed.  Can Mutex be used here or is the process class able to do this?  I know how to use the process class to list processes by name, but what if the exe has been renamed by the user? How is this best handled?

EDIT: For my purposes it turned out to be sufficient to merely be able to count other instances of the same application rather than list them out.  To count them I used a named semaphore.

```<code>//Initialize the semaphore with an initial value of 10000 and a maximum value of 10000.  The 'Global\' prefix will be system wide.  Remove it to limit the semaphore to the current logon session
Semaphore mySemaphore = new Semaphore(10000, 10000, @"Global\mySemaphoreUniqueNameGoesHere");
//Call .WaitOne() to enter the semaphore and decrement the semaphore count
mySemaphore.WaitOne();
</code>```

Since each running instance of the application will decrement the count by 1, then any time I need to check how many instances of the application are running I can use:

```<code>//.Release() will exit the semaphore and increment the semaphore count, but it will also return the value of the count just before .Release() was called, which is what we really need here.
int numberOfRunningInstances = 10000 - mySemaphore.Release();
//Then we can simply use .WaitOne() to re-enter the semaphore and decrement the count back to what it was before calling .Release()
mySemaphore.WaitOne();
</code>```

Then when the application exits:

```<code>//call .Release() to exit the semaphore and increment the count
mySemaphore.Release()
</code>```

答:
This is not an exact duplicate but very close to this existing question about listing all processes for all users.

From the management object you can invoke the GetOwner method like this :

```<code> string[] o = new String[2];
 queryObj.InvokeMethod("GetOwner", (object[])o);
</code>```

EDIT:

Several possible solutions, depending on what you want to achieve and what kind of complexity you can handle / need.

1- You can retrieve the path of each running binary, calculate a checksum for the executable file and compare it to the others. This might not be the solution you are looking for.

2- If you control the source for those applications, you could have them register something system wide at startup. It seems to be possible to register global semaphores and then retrieve the current count.

3- Implement some kind of shared memory between all instances, with memory mapped files for example and share all interesting information between them. This brings more complications, like cleaning up that memory properly when your process exits and probably locking as well.

4- You can implement some kind of system wide event broadcaster / receiver through named events. When the process starts, it writes its pid in a new file in a hardcoded folder. When your process is notified of a new startup, it reads every file in the folder and gets the pids.

Body:
I understand how to use Mutex to limit an application to run only a single instance at one time.  However, in my application I allow multiple instances to run simultaneously, but I need a way to count and/or list all of the running instances for a given user, regardless of whether or not the executable file has been renamed.  Can Mutex be used here or is the process class able to do this?  I know how to use the process class to list processes by name, but what if the exe has been renamed by the user? How is this best handled?

EDIT: For my purposes it turned out to be sufficient to merely be able to count other instances of the same application rather than list them out.  To count them I used a named semaphore.

//Initialize the semaphore with an initial value of 10000 and a maximum value of 10000.  The 'Global\' prefix will be system wide.  Remove it to limit the semaphore to the current logon session
Semaphore mySemaphore = new Semaphore(10000, 10000, @"Global\mySemaphoreUniqueNameGoesHere");
//Call .WaitOne() to enter the semaphore and decrement the semaphore count
mySemaphore.WaitOne();

Since each running instance of the application will decrement the count by 1, then any time I need to check how many instances of the application are running I can use:

//.Release() will exit the semaphore and increment the semaphore count, but it will also return the value of the count just before .Release() was called, which is what we really need here.
int numberOfRunningInstances = 10000 - mySemaphore.Release();
//Then we can simply use .WaitOne() to re-enter the semaphore and decrement the count back to what it was before calling .Release()
mySemaphore.WaitOne();

Then when the application exits:

//call .Release() to exit the semaphore and increment the count
mySemaphore.Release()

Body:
This is not an exact duplicate but very close to this existing question about listing all processes for all users.

From the management object you can invoke the GetOwner method like this :

 string[] o = new String[2];
 queryObj.InvokeMethod("GetOwner", (object[])o);

EDIT:

Several possible solutions, depending on what you want to achieve and what kind of complexity you can handle / need.

1- You can retrieve the path of each running binary, calculate a checksum for the executable file and compare it to the others. This might not be the solution you are looking for.

2- If you control the source for those applications, you could have them register something system wide at startup. It seems to be possible to register global semaphores and then retrieve the current count.

3- Implement some kind of shared memory between all instances, with memory mapped files for example and share all interesting information between them. This brings more complications, like cleaning up that memory properly when your process exits and probably locking as well.

4- You can implement some kind of system wide event broadcaster / receiver through named events. When the process starts, it writes its pid in a new file in a hardcoded folder. When your process is notified of a new startup, it reads every file in the folder and gets the pids.


问:
Dashed line animations in Mapbox GL JS
Is there a way I can do something like this in Mapbox with a LineString?

答:
Here's my initial attempt at a dashed line animation using Map#setPaintProperty(xx, 'line-dasharray', yy) within a setInterval function.

Some rendering artifacts could be eliminated with some creativity and data preprocessing.

<!DOCTYPE html>

    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />

    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.34.0/mapbox-gl.css' rel='stylesheet' />

```

Title: Dashed line animations in Mapbox GL JS

Body:
Here's my initial attempt at a dashed line animation using Map#setPaintProperty(xx, 'line-dasharray', yy) within a setInterval function.

Some rendering artifacts could be eliminated with some creativity and data preprocessing.

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title></title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.34.0/mapbox-gl.js'></script>
    <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.34.0/mapbox-gl.css' rel='stylesheet' />
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
</head>
<body>

<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibHVjYXN3b2oiLCJhIjoiY2l5Nmg4cWU1MDA0ejMzcDJtNHJmZzJkcyJ9.WhcEdTYQH6sSw2pm0RSP9Q';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v9',
    center: [-122.486052, 37.830348],
    zoom: 15
});

map.on('load', function () {

    map.addLayer({
        "id": "route",
        "type": "line",
        "source": {
            "type": "geojson",
            "data": {
                "type": "Feature",
                "properties": {},
                "geometry": {
                    "type": "LineString",
                    "coordinates": [
                        [-122.48369693756104, 37.83381888486939],
                        [-122.48348236083984, 37.83317489144141],
                        [-122.48339653015138, 37.83270036637107],
                        [-122.48356819152832, 37.832056363179625],
                        [-122.48404026031496, 37.83114119107971],
                        [-122.48404026031496, 37.83049717427869],
                        [-122.48348236083984, 37.829920943955045],
                        [-122.48356819152832, 37.82954808664175],
                        [-122.48507022857666, 37.82944639795659],
                        [-122.48610019683838, 37.82880236636284],
                        [-122.48695850372314, 37.82931081282506],
                        [-122.48700141906738, 37.83080223556934],
                        [-122.48751640319824, 37.83168351665737],
                        [-122.48803138732912, 37.832158048267786],
                        [-122.48888969421387, 37.83297152392784],
                        [-122.48987674713133, 37.83263257682617],
                        [-122.49043464660643, 37.832937629287755],
                        [-122.49125003814696, 37.832429207817725],
                        [-122.49163627624512, 37.832564787218985],
                        [-122.49223709106445, 37.83337825839438],
                        [-122.49378204345702, 37.83368330777276]
                    ]
                }
            }
        },
        "layout": {
            "line-join": "round",
            "line-cap": "butt"
        },
        "paint": {
            "line-color": "#888",
            "line-width": 8
        }
    });

    var dashLength = 1;
    var gapLength = 3;

    // We divide the animation up into 40 steps to make careful use of the finite space in
    // LineAtlas
    var steps = 40;
    // A # of steps proportional to the dashLength are devoted to manipulating the dash
    var dashSteps = steps * dashLength / (gapLength + dashLength);
    // A # of steps proportional to the gapLength are devoted to manipulating the gap
    var gapSteps = steps - dashSteps;

    // The current step #
    var step = 0;

    setInterval(function() {
        step = step + 1;
        if (step >= steps) step = 0;

        var t, a, b, c, d;
        if (step < dashSteps) {
          t = step / dashSteps;
          a = (1 - t) * dashLength;
          b = gapLength;
          c = t * dashLength;
          d = 0;
        } else {
          t = (step - dashSteps) / (gapSteps);
          a = 0;
          b = (1 - t) * gapLength;
          c = dashLength;
          d = t * gapLength;
        }

        map.setPaintProperty("route", "line-dasharray", [a, b, c, d]);
    }, 25);
});
</script>

</body>
</html>


问:
How to structure content in Ruby (RoR) app?
I am in the process of building a super simple CMS to handle smaller "static" page type projects (e.g. - small sites for friends). I have different "page types" that I would like to add. I built something similar in Coldfusion previously. Looked something like this:

table content_type:

```<code>content_type_code varchar(10)
content_type_name
</code>```

table content:

```<code>content_id
content_type_code varchar(10)
content_name
content_desc
content_url
</code>```

I would create a content type called "blog" or "photo" and each time a content was added, it'd get assigned the content_type_code. Then in /blog/ I'd query for all content that had a content_type_code of "blog".

Now that I'm using Ruby/RoR I am trying to think about things differently. I was thinking a better way might be to use nested pages with awesome_nested_set (https://github.com/collectiveidea/awesome_nested_set). But I'm not sure if that's the best solution.

Then I could create a page called "blog" and add to that many pages. So essentially the top level would take place of the "content_type" from my previous example.

Can someone steer me in the right direction on what the best method would be? I'm a newb looking for a kick in the right direction.

EDIT

I should add that the only real thing that I would change between the different "types" of content would be the layout and where they are displayed ("photo" content at /photos/, "blog" content at /blog/).

答: Instead of using content_type I would rather let the user choose a model on a selection page, like "photo" or "blog" and load an editing page based on that selection. So the user wants a new 'blog'-entry they get redirected to blog/new or 'photo' for photo/new. It's the easiest way to go in terms of usability and your controlling backend and you don't have redundant data (for example an empty photo url which is not necessary in a blog-type) in your database.</p>

Body:
I am in the process of building a super simple CMS to handle smaller "static" page type projects (e.g. - small sites for friends). I have different "page types" that I would like to add. I built something similar in Coldfusion previously. Looked something like this:

table content_type:

content_type_code varchar(10)
content_type_name

table content:

content_id
content_type_code varchar(10)
content_name
content_desc
content_url

I would create a content type called "blog" or "photo" and each time a content was added, it'd get assigned the content_type_code. Then in /blog/ I'd query for all content that had a content_type_code of "blog".

Now that I'm using Ruby/RoR I am trying to think about things differently. I was thinking a better way might be to use nested pages with awesome_nested_set (https://github.com/collectiveidea/awesome_nested_set). But I'm not sure if that's the best solution.

Then I could create a page called "blog" and add to that many pages. So essentially the top level would take place of the "content_type" from my previous example.

Can someone steer me in the right direction on what the best method would be? I'm a newb looking for a kick in the right direction.

EDIT

I should add that the only real thing that I would change between the different "types" of content would be the layout and where they are displayed ("photo" content at /photos/, "blog" content at /blog/).


问:
Manipulating a dataset by separating variables
I have a data set that looks similar to the image shown below. Total, it is over a 1000 observations long. I want to create a new data frame that separates the single variable into 3 variables. Each variable is separated by a "+" in each observation, so it will need to be separated by using that as a factor.

答:
I'll assume that your movieData object is a single column data.frame object.

If you want to split a single element from your data set, use strsplit using the character + (which R wants to see written as "\\+"):

```<code># split the first element of movieData into a vector of strings:
strsplit(as.character(movieData[1,1]), "\\+")
</code>```

Use lapply to apply this to the entire column, then massage the resulting list into a nice, usable data.frame:

```<code># convert to a list of vectors:
step1 = lapply(movieData[,1], function(x) strsplit(as.character(x), "\\+"))

# step1 is a list, so make it into a data.frame:
step2 = as.data.frame(step1)

# step2 is a nice data.frame, but its names are garbage.  Fix it:
movieDataWithColumns = setNames(step2, c("MovieId", "Title", "Genres"))
</code>```

Body:
I'll assume that your movieData object is a single column data.frame object.

If you want to split a single element from your data set, use strsplit using the character + (which R wants to see written as "\\+"):

# split the first element of movieData into a vector of strings:
strsplit(as.character(movieData[1,1]), "\\+")

Use lapply to apply this to the entire column, then massage the resulting list into a nice, usable data.frame:

# convert to a list of vectors:
step1 = lapply(movieData[,1], function(x) strsplit(as.character(x), "\\+"))

# step1 is a list, so make it into a data.frame:
step2 = as.data.frame(step1)

# step2 is a nice data.frame, but its names are garbage.  Fix it:
movieDataWithColumns = setNames(step2, c("MovieId", "Title", "Genres"))


问:
Python list append issue
One of my function appends an item to the list. This appended list is then sent as argument into two recursive function. But when one of the called function updates its own local list, the original list gets modified because of which second recursive function gets modified list as input.
Basically this is a sort of thing that i am trying to do. Here i want
[2]
[2,3]
[2,4] as output but i am getting [2][2,3] as only output as the original list is getting modified. Is there any way that i can send same list in two functions.</p>

```<code>def Growtree(llst, x):
  if len(llst) == 2:
    return

  llst.append(x)
  print(llst)

Growtree(llst,3)
Growtree(llst,4)
</code>```

答:
use copy.deepcopy()

The reason why the original list got modified in your functions, is that generally when you passing an mutable obj in python. It's the reference got passed into.

Title: Python list append issue

Body:
One of my function appends an item to the list. This appended list is then sent as argument into two recursive function. But when one of the called function updates its own local list, the original list gets modified because of which second recursive function gets modified list as input.
Basically this is a sort of thing that i am trying to do. Here i want
[2]
[2,3]
[2,4] as output but i am getting [2][2,3] as only output as the original list is getting modified. Is there any way that i can send same list in two functions.

def Growtree(llst, x):
  if len(llst) == 2:
    return

  llst.append(x)
  print(llst)

Growtree(llst,3)
Growtree(llst,4)


问:
Python multiprocessing with generator
I'm trying to process a file(every line is a json document). The size of the file can go up to 100's of mbs to gb's. So I wrote a generator code to fetch each document line by line from file.

```<code>def jl_file_iterator(file):
    with codecs.open(file, 'r', 'utf-8') as f:
        for line in f:
            document = json.loads(line)
            yield document
</code>```

My system has 4 cores, So I would like to process 4 lines of the file in parallel. Currently I have this code which takes 4 lines at a time and calls the code for parallel processing

```<code>threads = 4
files, i = [], 1
for jl in jl_file_iterator(input_path):
    files.append(jl)
    if i % (threads) == 0:
        # pool.map(processFile, files)
        parallelProcess(files, o)
        files = []
    i += 1

if files:
    parallelProcess(files, o)
    files = []
</code>```

This is my code where actual processing happens

```<code>def parallelProcess(files, outfile):
    processes = []
    for i in range(len(files)):
        p = Process(target=processFile, args=(files[i],))
        processes.append(p)
        p.start()
    for i in range(len(files)):
        processes[i].join()

def processFile(doc):
    extractors = {}
    ... do some processing on doc
    o.write(json.dumps(doc) + '\n')
</code>```

As you can see I wait for all the 4 lines to finish processing before I send the next 4 files to process. But what I would like to do is as soon as one process finish processing file I want to start the next line to be assigned to realeased processor. How do I do that?

PS: The problem is since its an generator I cannot load all the files and use something like map to run the processes.

Thanks for your help

答:
As @pvg said in a comment, a (bounded) queue is the natural way to mediate among a producer and consumers with different speeds, ensuring they all stay as busy as possible but without letting the producer get way ahead.

Here's a self-contained, executable example.  The queue is restricted to a maximum size equal to the number of worker processes.  If the consumers run much faster than the producer, it could make good sense to let the queue get bigger than that.

In your specific case, it would probably make sense to pass lines to the consumers and let them do the document = json.loads(line) part in parallel.

```<code>import multiprocessing as mp

NCORE = 4

def process(q, iolock):
    from time import sleep
    while True:
        stuff = q.get()
        if stuff is None:
            break
        with iolock:
            print("processing", stuff)
        sleep(stuff)

if __name__ == '__main__':
    q = mp.Queue(maxsize=NCORE)
    iolock = mp.Lock()
    pool = mp.Pool(NCORE, initializer=process, initargs=(q, iolock))
    for stuff in range(20):
        q.put(stuff)  # blocks until q below its max size
        with iolock:
            print("queued", stuff)
    for _ in range(NCORE):  # tell workers we're done
        q.put(None)
    pool.close()
    pool.join()
</code>```

Title: Python multiprocessing with generator

Body:
I'm trying to process a file(every line is a json document). The size of the file can go up to 100's of mbs to gb's. So I wrote a generator code to fetch each document line by line from file.

def jl_file_iterator(file):
    with codecs.open(file, 'r', 'utf-8') as f:
        for line in f:
            document = json.loads(line)
            yield document

My system has 4 cores, So I would like to process 4 lines of the file in parallel. Currently I have this code which takes 4 lines at a time and calls the code for parallel processing

threads = 4
files, i = [], 1
for jl in jl_file_iterator(input_path):
    files.append(jl)
    if i % (threads) == 0:
        # pool.map(processFile, files)
        parallelProcess(files, o)
        files = []
    i += 1

if files:
    parallelProcess(files, o)
    files = []

This is my code where actual processing happens

def parallelProcess(files, outfile):
    processes = []
    for i in range(len(files)):
        p = Process(target=processFile, args=(files[i],))
        processes.append(p)
        p.start()
    for i in range(len(files)):
        processes[i].join()

def processFile(doc):
    extractors = {}
    ... do some processing on doc
    o.write(json.dumps(doc) + '\n')

As you can see I wait for all the 4 lines to finish processing before I send the next 4 files to process. But what I would like to do is as soon as one process finish processing file I want to start the next line to be assigned to realeased processor. How do I do that?

PS: The problem is since its an generator I cannot load all the files and use something like map to run the processes.

Thanks for your help

Body:
As @pvg said in a comment, a (bounded) queue is the natural way to mediate among a producer and consumers with different speeds, ensuring they all stay as busy as possible but without letting the producer get way ahead.

Here's a self-contained, executable example.  The queue is restricted to a maximum size equal to the number of worker processes.  If the consumers run much faster than the producer, it could make good sense to let the queue get bigger than that.

In your specific case, it would probably make sense to pass lines to the consumers and let them do the document = json.loads(line) part in parallel.

import multiprocessing as mp

NCORE = 4

def process(q, iolock):
    from time import sleep
    while True:
        stuff = q.get()
        if stuff is None:
            break
        with iolock:
            print("processing", stuff)
        sleep(stuff)

if __name__ == '__main__':
    q = mp.Queue(maxsize=NCORE)
    iolock = mp.Lock()
    pool = mp.Pool(NCORE, initializer=process, initargs=(q, iolock))
    for stuff in range(20):
        q.put(stuff)  # blocks until q below its max size
        with iolock:
            print("queued", stuff)
    for _ in range(NCORE):  # tell workers we're done
        q.put(None)
    pool.close()
    pool.join()


问:
Why is std::inner_product slower than the naive implementation?
This is my naive implementation of dot product:

```<code>float simple_dot(int N, float *A, float *B) {
    float dot = 0;
    for(int i = 0; i < N; ++i) {
    dot += A[i] * B[i];
    }

    return dot;
}
</code>```

And this is using the C++ library:

```<code>float library_dot(int N, float *A, float *B) {
    return std::inner_product(A, A+N, B, 0);
}
</code>```

I ran some benchmark(code is here https://github.com/ijklr/sse), and the library version is a lot slower.
My compiler flag is -Ofast -march=native

答:
Your two functions don't do the same thing. The algorithm uses an accumulator whose type is deduced from the initial value, which in your case (0) is int. Accumulating floats into an int does not just take longer than accumulating into a float, but also produces a different result.

The equivalent of your raw loop code is to use the initial value 0.0f, or equivalently float{}.

(Note that std::accumulate is a very similar in this regard.)

Body:
This is my naive implementation of dot product:

float simple_dot(int N, float *A, float *B) {
    float dot = 0;
    for(int i = 0; i < N; ++i) {
    dot += A[i] * B[i];
    }

    return dot;
}

And this is using the C++ library:

float library_dot(int N, float *A, float *B) {
    return std::inner_product(A, A+N, B, 0);
}

I ran some benchmark(code is here https://github.com/ijklr/sse), and the library version is a lot slower.
My compiler flag is -Ofast -march=native


问:
In this IronPython example what is the @ symbol doing and how is it implemented?
http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6

```<code>   string code = @"
   print 'test = ' + test
   class MyClass:
       def __init__(self):
           pass

       def somemethod(self):
           print 'in some method'

       def isodd(self, n):
           return 1 == n % 2
   ";
</code>```

Is that '@' part of C# or is that something added by IronPython? If the latter, how do you do that in C#, some kind of operator overloading (basically could I then make '@' do whatever I want, etc)? Example implementation would be great. Otherwise, what's going on here?

答:
@"" is a verbatim string literal in C#.  That is, escape characters inside it are not interpreted.

In this case, the python code is being stored in the C# code string variable, and then is compiled into a CompiledCode from a ScriptSource using a ScriptEngine (which is itself created using Python.CreateEngine()).

Body:
http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6

   string code = @"
   print 'test = ' + test
   class MyClass:
       def __init__(self):
           pass

       def somemethod(self):
           print 'in some method'

       def isodd(self, n):
           return 1 == n % 2
   ";

Is that '@' part of C# or is that something added by IronPython? If the latter, how do you do that in C#, some kind of operator overloading (basically could I then make '@' do whatever I want, etc)? Example implementation would be great. Otherwise, what's going on here?


问:
What VBA variable type to use when reading values from a cell in Excel?
According to this answer one should always use Variant when assigning values in a cell to a variable in the code. Is this correct? I seem to recall reading elsewhere that using Variant indiscriminately is not a good practice.

答:
Not strictly answering your question, but thought I'd add this for reference anyway.

With native Excel functions you can usually provide either a range object or a value directly to a function. For example, you can either write =AVERAGE(A1,A2,A3) or =AVERAGE(10,20,30). If you want to do something similar for any user defined functions, you will need to check the type of object passed to your function:

```<code>Function test(input As Variant)

Dim var As Variant
If TypeName(input) = "Range" Then
    var = input.Value
Else
    var = input
End If
</code>```

You may also want to check for other objects if your function can accept them, but doing this will make your functions behave more like users expect them to.

Body:
Not strictly answering your question, but thought I'd add this for reference anyway.

With native Excel functions you can usually provide either a range object or a value directly to a function. For example, you can either write =AVERAGE(A1,A2,A3) or =AVERAGE(10,20,30). If you want to do something similar for any user defined functions, you will need to check the type of object passed to your function:

Function test(input As Variant)

Dim var As Variant
If TypeName(input) = "Range" Then
    var = input.Value
Else
    var = input
End If

You may also want to check for other objects if your function can accept them, but doing this will make your functions behave more like users expect them to.


答:
When Growtree(llst, 4) is called there is already 2 and 3 in the list llst. So it returns without appending a new element because of your if.

What you need is to make a copy of the list (before to call Glowtree of inside, it depends if you want the orignal list to get modified).

To copy a list, see https://stackoverflow.com/a/2612815/3410584

Title: Python list append issue


问:
Parsing HTML Response in jQuery
My page needs to grab a specific div from another page to display within a div on the current page. It's a perfect job for $.load, except that the HTML source I'm pulling from is not necessarily well-formed, and seems to have occasional tag errors, and IE just plain won't use it in that case. So I've changed it to a $.get to grab the HTML source of the page as a string. Passing it to $ to parse it as a DOM has the same problem in IE as $.load, so I can't do that. I need a way to parse the HTML string to find the contents of my div#information, but not the rest of the page after its
. (PS My div#information contains various other div's and elements.)

EDIT: Also if anyone has a fix for jQuery's $.load not being able to parse response HTML in IE, I'd love to hear that too.

答:
If the resource you are trying to load is under your control, your implementation spec is poorly optimized.  You don't want to ask your server for an entire page of content when you only really need a small piece of that content.

What you'll want to do is isolate the content you want, and have the server return only what you need.

As a side note, since you are aware that you have malformed HTML, you should probably bite the bullet and validate your markup.  That will save you some trouble (like this) in the future.

Finally, if you truly cannot optimize this process, my guess is that you are creating an inconsistency because some element in the parsed HTML has the same ID as an element on your current page.  Identical ID's are invalid and lead to many cross-browser JavaScript problems.

Title: Parsing HTML Response in jQuery


问:
Do we need interfaces for dependency injection?
I have an ASP.NET Core application. The application has few helper classes that does some work. Each class has different signature method. I see lot of .net core examples online that create interface for each class and then register types with DI framework. For example

```<code> public interface IStorage
 {
    Task Download(string file);
 }

 public class Storage
 {
    public Task Download(string file)
    {
    }
 }

 public interface IOcr
 {
     Task Process();
 }

 public class Ocr:IOcr
 {
    public Task Process()
    {

    }
 }
</code>```

Basically for each interface there is only one class. Then i register these types with DI as

```<code> services.AddScoped<IStorage, Storage>();
 services.AddScoped<IOcr,Ocr>();
</code>```

But i can register type without having interfaces so interfaces here look redundant. eg

```<code> services.AddScoped<Storage>();
 services.AddScoped<Ocr>();
</code>```

So do i really need interfaces?

答:
No, you don't need interfaces for dependency injection. But dependency injection is much more useful with them!

As you noticed, you can register concrete types with the service collection and ASP.NET Core will inject them into your classes without problems. The benefit you get by injecting them over simply creating instances with new Storage() is service lifetime management (transient vs. scoped vs. singleton).

That's useful, but only part of the power of using DI. As @DavidG pointed out, the big reason why interfaces are so often paired with DI is because of testing. Making your consumer classes depend on interfaces (abstractions) instead of other concrete classes makes them much easier to test.

For example, you could create a MockStorage that implements IStorage for use during testing, and your consumer class shouldn't be able to tell the difference. Or, you can use a mocking framework to easily create a mocked IStorage on the fly. Doing the same thing with concrete classes is much harder. Interfaces make it easy to replace implementations without changing the abstraction.

Body:
I have an ASP.NET Core application. The application has few helper classes that does some work. Each class has different signature method. I see lot of .net core examples online that create interface for each class and then register types with DI framework. For example

 public interface IStorage
 {
    Task Download(string file);
 }

 public class Storage
 {
    public Task Download(string file)
    {
    }
 }

 public interface IOcr
 {
     Task Process();
 }

 public class Ocr:IOcr
 {
    public Task Process()
    {

    }
 }

Basically for each interface there is only one class. Then i register these types with DI as

 services.AddScoped<IStorage, Storage>();
 services.AddScoped<IOcr,Ocr>();

But i can register type without having interfaces so interfaces here look redundant. eg

 services.AddScoped<Storage>();
 services.AddScoped<Ocr>();

So do i really need interfaces?


问:
Unable to run PowerShell from C#: The 'Get-WindowsOptionalFeature' command was found in the module 'Dism', but the module could not be loaded
I tried to execute the following PowerShell command from my c# application.

```<code>$check = Get-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
if ($check.Installed -eq 'False') {
    Enable-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
}
</code>```

But when I run this, the PowerShell raises the following exception:

The 'Get-WindowsOptionalFeature' command was found in the module 'Dism', but the module could not be loaded. For more information, run 'Import-Module Dism'

However, when I run the same script from the PowerShell window, it works just fine. What is the root of my problem? My operating system is Windows 10.

PowerShell version: 5 - 1 - 14393 - 953

C# Code:

```<code>const string psScript = @"$check = Get-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
if ($check.Installed -eq 'False') {
    Enable-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
}";

using (var PowerShellInstance = PowerShell.Create())
{
    PowerShellInstance.AddScript(psScript);
    var PSOutput = PowerShellInstance.Invoke();

    if (PowerShellInstance.Streams.Error.Count > 0)
    {
        foreach (var err in PowerShellInstance.Streams.Error)
            logger.LogError(err.ToString());
    }

    foreach (var outputItem in PSOutput)
    {
        if (outputItem != null)
            logger.LogInfo(outputItem.ToString());
    }
}
</code>```

答:
Try including 'Import-Module Dism' inside your script, like this:</p>

```<code>const string psScript = @"Import-Module Dism; $check = Get-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45 if ($check.Installed -eq 'False') { Enable-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45 };";
</code>```

Body:
I tried to execute the following PowerShell command from my c# application.

$check = Get-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
if ($check.Installed -eq 'False') {
    Enable-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
}

But when I run this, the PowerShell raises the following exception:

The 'Get-WindowsOptionalFeature' command was found in the module 'Dism', but the module could not be loaded. For more information, run 'Import-Module Dism'

However, when I run the same script from the PowerShell window, it works just fine. What is the root of my problem? My operating system is Windows 10.

PowerShell version: 5 - 1 - 14393 - 953

C# Code:

const string psScript = @"$check = Get-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
if ($check.Installed -eq 'False') {
    Enable-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45
}";

using (var PowerShellInstance = PowerShell.Create())
{
    PowerShellInstance.AddScript(psScript);
    var PSOutput = PowerShellInstance.Invoke();

    if (PowerShellInstance.Streams.Error.Count > 0)
    {
        foreach (var err in PowerShellInstance.Streams.Error)
            logger.LogError(err.ToString());
    }

    foreach (var outputItem in PSOutput)
    {
        if (outputItem != null)
            logger.LogInfo(outputItem.ToString());
    }
}

Body:
Try including 'Import-Module Dism' inside your script, like this:

const string psScript = @"Import-Module Dism; $check = Get-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45 if ($check.Installed -eq 'False') { Enable-WindowsOptionalFeature -Online -FeatureName WCF-HTTP-Activation45 };";


问:
How can I hot one encode in Matlab?
Often you are given a vector of integer values representing your labels (aka classes), for example

```<code>[2; 1; 3; 3; 2]
</code>```

and you would like to hot one encode this vector, such that each value is represented by a 1 in the column indicated by the value in each row of the labels vector, for example

```<code>[0 1 0;
 1 0 0;
 0 0 1;
 0 0 1;
 0 1 0]
</code>```

答:
Just in case someone is looking for the 2D case (as I was):

```<code>X = [2 1; ...
     3 3; ...
     2 4]
Y = zeros(3,2,4)
for i = 1:4
    Y(:,:,i) = ind2sub(X,X==i)
end
</code>```

gives a one-hot encoded matrix along the 3rd dimension.

Title: How can I hot one encode in Matlab?

Body:
Often you are given a vector of integer values representing your labels (aka classes), for example

[2; 1; 3; 3; 2]

and you would like to hot one encode this vector, such that each value is represented by a 1 in the column indicated by the value in each row of the labels vector, for example

[0 1 0;
 1 0 0;
 0 0 1;
 0 0 1;
 0 1 0]

Body:
Just in case someone is looking for the 2D case (as I was):

X = [2 1; ...
     3 3; ...
     2 4]
Y = zeros(3,2,4)
for i = 1:4
    Y(:,:,i) = ind2sub(X,X==i)
end

gives a one-hot encoded matrix along the 3rd dimension.


问:
Getting email-ext script templates to work with Jenkins pipeline
I recently converted to Jenkins 2.x and I am experimenting with pipeline flow, but I can't seem to get the email-ext plugin to work with groovy script templates.  Although my standard flow still work fine, if I try the following I get an error with unexpected token SCRIPT

```<code>    emailext mimeType: 'text/html', replyTo: 'xxxx', subject: "${env.JOB_NAME} - Build# ${env.BUILD_NUMBER} - ${env.BUILD_STATUS}", to: 'xxxx', body: "${SCRIPT, template='regressionfailed.groovy'}"
</code>```

I know that there were issues with token expansion early on, but it seems like from the latest wiki updates those have been fixed.  I also still get no token expansion for any tokens.  Is there any good reference to get this working again.  I would like to switch to the pipeline flow but the email template with token expansion is key to may work flow.

答:
Faced the same issue today, apparently having the body defined before the emailext seem to do the trick:

```<code>def emailBody = '${SCRIPT, template="regressionfailed.groovy"}'
def emailSubject = "${env.JOB_NAME} - Build# ${env.BUILD_NUMBER} - ${env.BUILD_STATUS}"
emailext(mimeType: 'text/html', replyTo: 'xxxx', subject: emailSubject, to: 'xxxx', body: emailBody)
</code>```

Remember you might still need to redo parts of your template.

Body:
I recently converted to Jenkins 2.x and I am experimenting with pipeline flow, but I can't seem to get the email-ext plugin to work with groovy script templates.  Although my standard flow still work fine, if I try the following I get an error with unexpected token SCRIPT

    emailext mimeType: 'text/html', replyTo: 'xxxx', subject: "${env.JOB_NAME} - Build# ${env.BUILD_NUMBER} - ${env.BUILD_STATUS}", to: 'xxxx', body: "${SCRIPT, template='regressionfailed.groovy'}"

I know that there were issues with token expansion early on, but it seems like from the latest wiki updates those have been fixed.  I also still get no token expansion for any tokens.  Is there any good reference to get this working again.  I would like to switch to the pipeline flow but the email template with token expansion is key to may work flow.

Body:
Faced the same issue today, apparently having the body defined before the emailext seem to do the trick:

def emailBody = '${SCRIPT, template="regressionfailed.groovy"}'
def emailSubject = "${env.JOB_NAME} - Build# ${env.BUILD_NUMBER} - ${env.BUILD_STATUS}"
emailext(mimeType: 'text/html', replyTo: 'xxxx', subject: emailSubject, to: 'xxxx', body: emailBody)

Remember you might still need to redo parts of your template.


问:
Recursive Fibonacci Function
I have an assignment where I have create a Fibonacci suite using recursion. The code below works in some cases, but not all.

```<code>org 100h
 jmp debut
val dw 0008h
debut:
  push word ptr 0000h
  push word ptr 0001h
  call fibo
  Add  sp,04
  hlt
fibo proc near
  Sub  sp,04
  mov  dx,[sp+6]
  mov  [sp+02],dx
  add  dx,[sp+8]
  mov  [sp],dx
  cmp  dx,val
  jae  Fin
  Call Fibo
Fin:
  ret 04
endp fibo
</code>```

but the problem is when I try to put in VAL a number like 0 or 1 or negative number like -0003h, Will not stop.

Any help would be appreciated thanks.

答:
The main issue was using jae fin , which is a conditional branch for an unsigned compare. I changed this to use jge fin , which is a conditional branch for signed compare.

The code below was modified to work with Microsoft Masm. I'm not sure about using sp as index register in real mode, so I used bp. I changed the two pushes so that the first time through fibo, dx ends up with zero.

I don't think this is what the assignment intended. Normally the input is n, and fibo is supposed to return the nth fibonacci number in ax (for n = {0,1,2,3,4,...} return {0,1,1,2,3, ...}). This would require fibo to call itself twice, based on fib(n) = fib(n-1) + fib(n-2).

```<code>        .286
        .model  tiny,c
        .code
        org     0100h

main    proc    far
        jmp     short debut
val     dw      00008h
debut:
;       note - push immediate requires 80186 or later cpu
        push    word ptr 0ffffh ;fib(-2) == -1
        push    word ptr 00001h ;fib(-1) ==  1
        call    fibo
        add     sp,4
        hlt
main    endp

fibo    proc    near
        push    bp              ;real mode doesn't allow [sp...]
        mov     bp,sp           ; using [bp...] instead
        sub     sp,4
        mov     dx,[bp+4]
        mov     [bp-2],dx
        add     dx,[bp+6]
        mov     [bp-4],dx
        cmp     dx,val
        jge     fin             ;changed this line
        call    fibo
fin:    add     sp,4            ;added this line
        pop     bp              ;added this line
        ret     0               ;changed this line
fibo    endp

        end     main
</code>```

Title: Recursive Fibonacci Function

Body:
I have an assignment where I have create a Fibonacci suite using recursion. The code below works in some cases, but not all.

org 100h
 jmp debut
val dw 0008h
debut:
  push word ptr 0000h
  push word ptr 0001h
  call fibo
  Add  sp,04
  hlt
fibo proc near
  Sub  sp,04
  mov  dx,[sp+6]
  mov  [sp+02],dx
  add  dx,[sp+8]
  mov  [sp],dx
  cmp  dx,val
  jae  Fin
  Call Fibo
Fin:
  ret 04
endp fibo

but the problem is when I try to put in VAL a number like 0 or 1 or negative number like -0003h, Will not stop.

Any help would be appreciated thanks.

Body:
The main issue was using jae fin , which is a conditional branch for an unsigned compare. I changed this to use jge fin , which is a conditional branch for signed compare.

The code below was modified to work with Microsoft Masm. I'm not sure about using sp as index register in real mode, so I used bp. I changed the two pushes so that the first time through fibo, dx ends up with zero.

I don't think this is what the assignment intended. Normally the input is n, and fibo is supposed to return the nth fibonacci number in ax (for n = {0,1,2,3,4,...} return {0,1,1,2,3, ...}). This would require fibo to call itself twice, based on fib(n) = fib(n-1) + fib(n-2).

        .286
        .model  tiny,c
        .code
        org     0100h

main    proc    far
        jmp     short debut
val     dw      00008h
debut:
;       note - push immediate requires 80186 or later cpu
        push    word ptr 0ffffh ;fib(-2) == -1
        push    word ptr 00001h ;fib(-1) ==  1
        call    fibo
        add     sp,4
        hlt
main    endp

fibo    proc    near
        push    bp              ;real mode doesn't allow [sp...]
        mov     bp,sp           ; using [bp...] instead
        sub     sp,4
        mov     dx,[bp+4]
        mov     [bp-2],dx
        add     dx,[bp+6]
        mov     [bp-4],dx
        cmp     dx,val
        jge     fin             ;changed this line
        call    fibo
fin:    add     sp,4            ;added this line
        pop     bp              ;added this line
        ret     0               ;changed this line
fibo    endp

        end     main


问:
can i click on a link that is not visible using webdriver

My test case is to click on any link of a webpage. I am getting all the links and operation is performed successfully, but when i try to click on some of them then it gives following Exception

```<code>Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.28.455520 (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 31 milliseconds
Build info: version: 'unknown', revision: '5234b32', time: '2017-03-10 09:00:17 -0800'
System info: host: 'ADMINPC', ip: '192.168.1.79', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.28.455520 (cc17746adff54984afff480136733114c6b3704b), userDataDir=C:\Users\admin\AppData\Local\Temp\scoped_dir1932_20343}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=56.0.2924.87, platform=WIN8_1, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
Session ID: f622cb046f2dcc4e7ddd5621497cb602
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:274)
    at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:84)
    at newpackage.AllLinks.main(AllLinks.java:32)
</code>```

答: This error means the link you are trying to click is not visible. Try to wait for the links to be displayed before clicking them.</p>

Body:
My test case is to click on any link of a webpage. I am getting all the links and operation is performed successfully, but when i try to click on some of them then it gives following Exception

Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: element not visible
  (Session info: chrome=56.0.2924.87)
  (Driver info: chromedriver=2.28.455520 (cc17746adff54984afff480136733114c6b3704b),platform=Windows NT 6.3.9600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 31 milliseconds
Build info: version: 'unknown', revision: '5234b32', time: '2017-03-10 09:00:17 -0800'
System info: host: 'ADMINPC', ip: '192.168.1.79', os.name: 'Windows 8.1', os.arch: 'amd64', os.version: '6.3', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.28.455520 (cc17746adff54984afff480136733114c6b3704b), userDataDir=C:\Users\admin\AppData\Local\Temp\scoped_dir1932_20343}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=56.0.2924.87, platform=WIN8_1, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
Session ID: f622cb046f2dcc4e7ddd5621497cb602
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:216)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:168)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:638)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:274)
    at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:84)
    at newpackage.AllLinks.main(AllLinks.java:32)


问:
Can't open Playground Book on iPad
I've got a playgroundBook from Apple's website. I uploaded the file to iCloud Drive (unzipped) but iCloud Drive is adding the .zip extension to it and now the iPad sees it as a zip file and won't open it. I don't have airdrop on the mac. </p>

答: Just get the Book direct from ITunes it will add it automatically to your IBooks </p>

Title: Can't open Playground Book on iPad


问:
CouchDB Views: remove duplicates *and* order by time
Based on a great answer to my previous question, I've partially solved a problem I'm having with CouchDB.

This resulted in a new view.

Now, the next thing I need to do is remove duplicates from this view while ordering by date.

For example, here is how I might query that view:

```<code>GET http://scoates-test.couchone.com/follow/_design/asset/_view/by_userid_following?endkey=[%22c988a29740241c7d20fc7974be05ec54%22]&startkey=[%22c988a29740241c7d20fc7974be05ec54%22,{}]&descending=true&limit=3
</code>```

Resulting in this:

```<code>HTTP 200 http://scoates-test.couchone.com/follow/_design/asset/_view/by_userid_following
http://scoates-test.couchone.com > $_.json.rows
[ { id: 'c988a29740241c7d20fc7974be067295'
  , key:
     [ 'c988a29740241c7d20fc7974be05ec54'
     , '2010-11-26T17:00:00.000Z'
     , 'clementine'
     ]
  , value:
     { _id: 'c988a29740241c7d20fc7974be062ee8'
     , owner: 'c988a29740241c7d20fc7974be05f67d'
     }
  }
, { id: 'c988a29740241c7d20fc7974be068278'
  , key:
 [ 'c988a29740241c7d20fc7974be05ec54'
     , '2010-11-26T15:00:00.000Z'
     , 'durian'
     ]
  , value:
     { _id: 'c988a29740241c7d20fc7974be065115'
     , owner: 'c988a29740241c7d20fc7974be060bb4'
     }
  }
, { id: 'c988a29740241c7d20fc7974be068026'
  , key:
     [ 'c988a29740241c7d20fc7974be05ec54'
     , '2010-11-26T14:00:00.000Z'
     , 'clementine'
     ]
  , value:
     { _id: 'c988a29740241c7d20fc7974be063b6d'
     , owner: 'c988a29740241c7d20fc7974be05ff71'
     }
  }
]
</code>```

As you can see, "clementine" shows up twice.

If I change the view to emit the fruit/asset name as the second key (instead of the time), I can change the grouping depth to collapse these, but that doesn't solve my order-by-time requirement. Similarly, with the above setup, I can order by time, but I can't collapse duplicate asset names into single rows (to allow e.g. 10 assets per page).

Unfortunately, this is not a simple question to explain. Maybe this chat transcript will help a little.

Please help. I'm afraid that what I need to do is still not possible.

S

答:
Ordering by one field and uniquing on another isn't something the basic map reduce can do. All it can do is sort your data, and apply reduce rollups to dynamic key-ranges.

To find the latest entry for each type of fruit, you'd need to query once per fruit.

There are some ways to do this that are kinda sane.

You'll want a view with keys like [fruit_type, date], and then you can query like this:

```<code>for fruit in fruits
  GET /db/_design/foo/_view/bar?startkey=["apples"]&limit=1&descending=true
</code>```

This will give you the latest entry for each fruit.

The list operation could be used to do this, it would just echo the first row from each fruit's block. This would be efficient enough as long as each fruit has a small number of entries. Once there are many entries per fruit, you'll be discarding more data than you echo, so the multi-query approach actually scales better than the list approach, when you get to a large data set. Luckily they can both work on the same view index, so when you have to switch it won't be a big deal.

Body:
Based on a great answer to my previous question, I've partially solved a problem I'm having with CouchDB.

This resulted in a new view.

Now, the next thing I need to do is remove duplicates from this view while ordering by date.

For example, here is how I might query that view:

GET http://scoates-test.couchone.com/follow/_design/asset/_view/by_userid_following?endkey=[%22c988a29740241c7d20fc7974be05ec54%22]&startkey=[%22c988a29740241c7d20fc7974be05ec54%22,{}]&descending=true&limit=3

Resulting in this:

HTTP 200 http://scoates-test.couchone.com/follow/_design/asset/_view/by_userid_following
http://scoates-test.couchone.com > $_.json.rows
[ { id: 'c988a29740241c7d20fc7974be067295'
  , key:
     [ 'c988a29740241c7d20fc7974be05ec54'
     , '2010-11-26T17:00:00.000Z'
     , 'clementine'
     ]
  , value:
     { _id: 'c988a29740241c7d20fc7974be062ee8'
     , owner: 'c988a29740241c7d20fc7974be05f67d'
     }
  }
, { id: 'c988a29740241c7d20fc7974be068278'
  , key:
 [ 'c988a29740241c7d20fc7974be05ec54'
     , '2010-11-26T15:00:00.000Z'
     , 'durian'
     ]
  , value:
     { _id: 'c988a29740241c7d20fc7974be065115'
     , owner: 'c988a29740241c7d20fc7974be060bb4'
     }
  }
, { id: 'c988a29740241c7d20fc7974be068026'
  , key:
     [ 'c988a29740241c7d20fc7974be05ec54'
     , '2010-11-26T14:00:00.000Z'
     , 'clementine'
     ]
  , value:
     { _id: 'c988a29740241c7d20fc7974be063b6d'
     , owner: 'c988a29740241c7d20fc7974be05ff71'
     }
  }
]

As you can see, "clementine" shows up twice.

If I change the view to emit the fruit/asset name as the second key (instead of the time), I can change the grouping depth to collapse these, but that doesn't solve my order-by-time requirement. Similarly, with the above setup, I can order by time, but I can't collapse duplicate asset names into single rows (to allow e.g. 10 assets per page).

Unfortunately, this is not a simple question to explain. Maybe this chat transcript will help a little.

Please help. I'm afraid that what I need to do is still not possible.

S

Body:
Ordering by one field and uniquing on another isn't something the basic map reduce can do. All it can do is sort your data, and apply reduce rollups to dynamic key-ranges.

To find the latest entry for each type of fruit, you'd need to query once per fruit.

There are some ways to do this that are kinda sane.

You'll want a view with keys like [fruit_type, date], and then you can query like this:

for fruit in fruits
  GET /db/_design/foo/_view/bar?startkey=["apples"]&limit=1&descending=true

This will give you the latest entry for each fruit.

The list operation could be used to do this, it would just echo the first row from each fruit's block. This would be efficient enough as long as each fruit has a small number of entries. Once there are many entries per fruit, you'll be discarding more data than you echo, so the multi-query approach actually scales better than the list approach, when you get to a large data set. Luckily they can both work on the same view index, so when you have to switch it won't be a big deal.


问:
$state are not populated in resolving promises in Angular routes
I came across this situation where I can see $stateParams gets populated in one place but not in another. I'm kind of newbie to angular-ui-router so any help will be appreciated.Thanks !

In the resolve block of the following state, I injected $stateParams as a dependency in the function for data 'campaign' and the $stateParams is populated.

```<code>.state('campaign', {
          url: "/campaign/{campaignId:int}",
          templateUrl: campaign_template,
          controller: 'CampaignCtrl',
          parent: 'org',
          abstract: true,
          resolve: {
            campaign: function(CampaignService, $stateParams) {

              console.log('$stateParams is populated here!', $stateParams)

              return CampaignService.get($stateParams.campaignId)
                .then(function(campaign) {
                  return campaign;
                });

            }
          }
</code>```

Inside the CampaignService function, however, I require $stateParams but it's
empty. I'm confused because I'm assuming since it's populated when I injected it in the
resolve block, it should be the same no matter where else I get it again.

```<code>  .service('CampaignService', function($injector, $q) {
            this.get = function() {
              var $stateParams = $injector.get('$stateParams');

              console.log('$stateParams is empty here!', $stateParams);

              var deferred = $q.defer();
              setTimeout(function() {
                deferred.resolve({
                  name: 'campaignName'
                });
              }, 1000);

              return deferred.promise;
            }
          })
</code>```

答:
I'm assuming since it's populated when I injected it in the resolve block, it should be the same no matter where else I get it again.

The $stateParams injected into the resolve block is the proposed future state. At that point in time the application is still using the old state. And will remain in the old state if any of the resolve promises are rejected.

Under the hood, the $state service creates a local version of $stateParams that it injects in the resolve function:

```<code>  var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
  var locals = { $stateParams: $stateParams };

  // Resolve 'global' dependencies for the state, i.e. those not specific to a view.
  // We're also including $stateParams in this; that way the parameters are restricted
  // to the set that should be visible to the state, and are independent of when we update
  // the global $state and $stateParams values.
  dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
  var promises = [dst.resolve.then(function (globals) {
    dst.globals = globals;
  })];
</code>```

— https://github.com/angular-ui/ui-router/blob/legacy/src/state.js#L1427-L1437

The solution is to pass the proposed future $stateParams to the service.

Body:
I came across this situation where I can see $stateParams gets populated in one place but not in another. I'm kind of newbie to angular-ui-router so any help will be appreciated.Thanks !

In the resolve block of the following state, I injected $stateParams as a dependency in the function for data 'campaign' and the $stateParams is populated.

.state('campaign', {
          url: "/campaign/{campaignId:int}",
          templateUrl: campaign_template,
          controller: 'CampaignCtrl',
          parent: 'org',
          abstract: true,
          resolve: {
            campaign: function(CampaignService, $stateParams) {

              console.log('$stateParams is populated here!', $stateParams)

              return CampaignService.get($stateParams.campaignId)
                .then(function(campaign) {
                  return campaign;
                });

            }
          }

Inside the CampaignService function, however, I require $stateParams but it's
empty. I'm confused because I'm assuming since it's populated when I injected it in the
resolve block, it should be the same no matter where else I get it again.

  .service('CampaignService', function($injector, $q) {
            this.get = function() {
              var $stateParams = $injector.get('$stateParams');

              console.log('$stateParams is empty here!', $stateParams);

              var deferred = $q.defer();
              setTimeout(function() {
                deferred.resolve({
                  name: 'campaignName'
                });
              }, 1000);

              return deferred.promise;
            }
          })

Body:
I'm assuming since it's populated when I injected it in the resolve block, it should be the same no matter where else I get it again.

The $stateParams injected into the resolve block is the proposed future state. At that point in time the application is still using the old state. And will remain in the old state if any of the resolve promises are rejected.

Under the hood, the $state service creates a local version of $stateParams that it injects in the resolve function:

  var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);
  var locals = { $stateParams: $stateParams };

  // Resolve 'global' dependencies for the state, i.e. those not specific to a view.
  // We're also including $stateParams in this; that way the parameters are restricted
  // to the set that should be visible to the state, and are independent of when we update
  // the global $state and $stateParams values.
  dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);
  var promises = [dst.resolve.then(function (globals) {
    dst.globals = globals;
  })];

— https://github.com/angular-ui/ui-router/blob/legacy/src/state.js#L1427-L1437

The solution is to pass the proposed future $stateParams to the service.