问:
How do I dynamically append html snippets into the web page?
I have the following markup:

```<code><div id="maincontainer">
  <div id="mainMenu">

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

    <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

     <div class="giver">
      <hr class = "giver-hr">
      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>
      <label class = giver-isClient>
        <input type = "radio">
        <span>lorem ipsum</span>
      </label>
    </div>

  </div>
  <div id="legalDocument"></div>
</div>
</code>```

, where the
 element is repeated multiple (9) times.

What is the best way to append such blocks dynamically, through for(){} cycle for example? The innerHtml property is not recommended from what I've heard. and using a special recursive function that I made doesn't seem to be the right way either.

What should I do? I'd like to extend my Web pages with templates kinda like how Javascript classes behave.

答:
you can use createElement and appendChild

see demo - stackblitz

```<code><div id="maincontainer">
    <div id="legalDocument">
    </div>
</div>

var wrapper = document.querySelector("#mainMenu");
for(let i=0; i<9; i++) {
    wrapper.appendChild(createBox());
}

function createBox() {
  const giver  = document.createElement("div");
  giver.className = 'giver'
  const givenHr  = document.createElement("hr");
  givenHr.className = 'giver-hr'
  const giverSubject  = document.createElement("select");
  giverSubject.className = 'giver-subject'
  const giverStatus  = document.createElement("select");
  giverStatus.className = 'giver-status'
  const giverIsClient  = document.createElement("label");
  giverStatus.className = 'giver-isClient'
  const input  = document.createElement("input");
  input.type = 'radio'
  const span  = document.createElement("span");
  const text = document.createTextNode('lorem ipsum');

  span.appendChild(text);
  giverIsClient.appendChild(input);
  giverIsClient.appendChild(span);

  giver.appendChild(givenHr);
  giver.appendChild(giverSubject);
  giver.appendChild(giverStatus);
  giver.appendChild(giverIsClient);

  return giver;
}
</code>```

Body:
I have the following markup:

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

      <select class ="giver-subject"></select>
      <select class ="giver-status"></select>

        <input type = "radio">
        lorem ipsum

, where the
 element is repeated multiple (9) times.

What is the best way to append such blocks dynamically, through for(){} cycle for example? The innerHtml property is not recommended from what I've heard. and using a special recursive function that I made doesn't seem to be the right way either.

What should I do? I'd like to extend my Web pages with templates kinda like how Javascript classes behave.

Body:
you can use createElement and appendChild

see demo - stackblitz

<div id="maincontainer">
    <div id="legalDocument">
    </div>
</div>

var wrapper = document.querySelector("#mainMenu");
for(let i=0; i<9; i++) {
    wrapper.appendChild(createBox());
}

function createBox() {
  const giver  = document.createElement("div");
  giver.className = 'giver'
  const givenHr  = document.createElement("hr");
  givenHr.className = 'giver-hr'
  const giverSubject  = document.createElement("select");
  giverSubject.className = 'giver-subject'
  const giverStatus  = document.createElement("select");
  giverStatus.className = 'giver-status'
  const giverIsClient  = document.createElement("label");
  giverStatus.className = 'giver-isClient'
  const input  = document.createElement("input");
  input.type = 'radio'
  const span  = document.createElement("span");
  const text = document.createTextNode('lorem ipsum');

  span.appendChild(text);
  giverIsClient.appendChild(input);
  giverIsClient.appendChild(span);

  giver.appendChild(givenHr);
  giver.appendChild(giverSubject);
  giver.appendChild(giverStatus);
  giver.appendChild(giverIsClient);

  return giver;
}


来源: stackexchange

问:
How to get the weight of the smallest path between two nodes?
I have a networkx graph in Python, with weighted edges. I want to get the weight of the smallest path between two nodes.

Currently, I am getting the nodes in the shortest path from the nx.shortest_path implementation, and then iterating through each pair and summing over the weights between each pair of node.

```<code>shortest_path = nx.shortest_path(G, source, destination, 'distance')

#function to iterate over each pair

import itertools
def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

weightSum = 0
for adjPair in pairwise(shortest_path):
    weightSum = weightSum + G[adjPair[0]][adjPair[1]]['distance']
</code>```

Is there a better (built-in) alternative to this?

答:
You look for single_source_dijkstra:

```<code>from networkx.algorithms.shortest_paths.weighted import single_source_dijkstra

single_source_dijkstra(G,s,t)
</code>```

example

```<code>import networkx as nx
from networkx.algorithms.shortest_paths.weighted import single_source_dijkstra

G = nx.Graph()

G.add_edge('a', 'b', weight=0.6)
G.add_edge('a', 'c', weight=6)
G.add_edge('c', 'd', weight=0.1)
G.add_edge('c', 'e', weight=0.7)
G.add_edge('c', 'f', weight=0.9)
G.add_edge('a', 'd', weight=0.3)

single_source_dijkstra(G,'b','f')
</code>```

output

```<code>(1.9, ['b', 'a', 'd', 'c', 'f'])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a networkx graph in Python, with weighted edges. I want to get the weight of the smallest path between two nodes.

Currently, I am getting the nodes in the shortest path from the nx.shortest_path implementation, and then iterating through each pair and summing over the weights between each pair of node.

shortest_path = nx.shortest_path(G, source, destination, 'distance')

#function to iterate over each pair

import itertools
def pairwise(iterable):
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

weightSum = 0
for adjPair in pairwise(shortest_path):
    weightSum = weightSum + G[adjPair[0]][adjPair[1]]['distance']

Is there a better (built-in) alternative to this?

Body:
You look for single_source_dijkstra:

from networkx.algorithms.shortest_paths.weighted import single_source_dijkstra

single_source_dijkstra(G,s,t)

example

import networkx as nx
from networkx.algorithms.shortest_paths.weighted import single_source_dijkstra

G = nx.Graph()

G.add_edge('a', 'b', weight=0.6)
G.add_edge('a', 'c', weight=6)
G.add_edge('c', 'd', weight=0.1)
G.add_edge('c', 'e', weight=0.7)
G.add_edge('c', 'f', weight=0.9)
G.add_edge('a', 'd', weight=0.3)

single_source_dijkstra(G,'b','f')

output

(1.9, ['b', 'a', 'd', 'c', 'f'])


问:
C# Unity: Enter the sub values of the class with a "partial name+number"
I retrieved the number from a class.
now I would like to enter the options through the latter:

```<code>float CarLevel = Settings.LevelSelected; // from main get the level

var LevelNumber = Settings.(LevelOfCar+CarLevel); //enter in corret level

float Kmh = LevelNumber.Kmh; //get the par of level
</code>```

obviously it doesn't work like this ... how can I do to avoid a big classic IF LEVEL IS 2 ELSE .... for all levels? tips?

答:
I would suggest a more object oriented approach.

Consider the following

```<code>public class Level : ScriptableObject
{
    public int CarLevel;
    public float Kmh;
    // other variables that are shared across all levels
}
</code>```

And if you need specific code for each level which share the same script, you could use inheritance.

```<code>public class SpecificLevel : Level
{
    public void DoSomething()
    {

    }
}
</code>```

Have a manager class containing all your levels.

```<code>public class LevelManager : MonoBehaviour
{
    // Assign levels here through the inspector
    public List<Level> Levels;

    public void LoadLevel()
    {
        Level level = Levels.First(x => x.CarLevel == Settings.LevelSelected);
        // Do whatever you want with your level
    }
}
</code>```

You will need to add the linq using.

```<code>using System.Linq;
</code>```

If you do not know about scriptable objects, i suggest following this short tutorial. It will help you out greatly in your development.

Body:
I retrieved the number from a class.
now I would like to enter the options through the latter:

float CarLevel = Settings.LevelSelected; // from main get the level

var LevelNumber = Settings.(LevelOfCar+CarLevel); //enter in corret level

float Kmh = LevelNumber.Kmh; //get the par of level

obviously it doesn't work like this ... how can I do to avoid a big classic IF LEVEL IS 2 ELSE .... for all levels? tips?

Body:
I would suggest a more object oriented approach.

Consider the following

public class Level : ScriptableObject
{
    public int CarLevel;
    public float Kmh;
    // other variables that are shared across all levels
}

And if you need specific code for each level which share the same script, you could use inheritance.

public class SpecificLevel : Level
{
    public void DoSomething()
    {

    }
}

Have a manager class containing all your levels.

public class LevelManager : MonoBehaviour
{
    // Assign levels here through the inspector
    public List<Level> Levels;

    public void LoadLevel()
    {
        Level level = Levels.First(x => x.CarLevel == Settings.LevelSelected);
        // Do whatever you want with your level
    }
}

You will need to add the linq using.

using System.Linq;

If you do not know about scriptable objects, i suggest following this short tutorial. It will help you out greatly in your development.


问:
Using the newly created primary key in another column
Using PostgreSQL

in my table I have the column "id" that is an auto incremented primary key. When I create a new row, I would like to use that newly created primary key value in another column of the new row. How would I do so?

答:
You need a trigger for this:

```<code>create or replace function t_update_message_id_trigger()
returns trigger as
$body$
begin
    new.message_id := new.id;
    return new;
end;
$body$ language plpgsql;

create trigger t_update_message_id before insert on t
    for each row execute procedure t_update_message_id_trigger();
</code>```

Here is a db<>fiddle, illustrating how it works.

Body:
You need a trigger for this:

create or replace function t_update_message_id_trigger()
returns trigger as
$body$
begin
    new.message_id := new.id;
    return new;
end;
$body$ language plpgsql;

create trigger t_update_message_id before insert on t
    for each row execute procedure t_update_message_id_trigger();

Here is a db<>fiddle, illustrating how it works.


问:
Can I take a screenshot tough shh connection and open it on other mac?
(Sorry for my bad english)

Ok so i'm connecting from a mac book pro to a stationary mac trough ssh in the Mac Terminal, and I'm wondering if there's any way I can take a screenshot of the mac i'm connecting to and show it on the mac i'm connections from.  Any help would be appreciated.

答:
Disclaimer : This not exactly what’s the OP asked for, but it’s probably close to what he needs.

You should open a ssh tunnel and connect via the built in VNC server.

See ssh tunnel documentation.

See also https://apple.stackexchange.com/questions/16976/whats-a-good-ssh-tunneling-client-for-os-x


问:
Show Result of Query in JSON format in MVC Model
I wanna fetch some data from a database and show them in JSON format. Im using MVC model. I don't know how to do that.

This is my DAO:

```<code>public static List<NewsModel> getAll() {

        Connection con = ConnectionManagment.CreateConnection();
        List<NewsModel> newsList = new ArrayList<>();

        try {

            java.sql.PreparedStatement ps = con
                    .prepareStatement("select j.title,
               j.content, j.displayDate from JournalArticle  j LIMIT 5");

            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                NewsModel news = new NewsModel();
                news.setTitle(rs.getString("title"));
                String date = rs.getString("displayDate");
                SimpleDateFormat smpl = new
                               SimpleDateFormat("yyyy-MM-dd");
                news.setDisplayDate(smpl.parse(date));
                news.setContent(rs.getString("content"));

                newsList.add(news);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return newsList;
}

</code>```

This is my servlet :

```<code>List<NewsModel> news = (List<NewsModel>) new NewsModel();
news = SaipaDAO.getAll();

JSONArray newsArr = new JSONArray();
for (Object n : news) {
    JSONObject newsObj = new JSONObject();
}
</code>```

答:
I found it. I made a mistake in define foreach statment. this code works :</p>

```<code>    List<NewsModel> news = new ArrayList<NewsModel>();
    JSONArray newsArr = new JSONArray();
    news = SaipaDAO.getAll();

    for (NewsModel n : news) {
        JSONObject newsObj = new JSONObject();

        newsObj.put("title", n.getTitle());
        newsObj.put("content", n.getContent());
        newsObj.put("displayDate", n.getDisplayDate());
        newsArr.add(newsObj);

    }
</code>```

Body:
I wanna fetch some data from a database and show them in JSON format. Im using MVC model. I don't know how to do that.

This is my DAO:

public static List<NewsModel> getAll() {

        Connection con = ConnectionManagment.CreateConnection();
        List<NewsModel> newsList = new ArrayList<>();

        try {

            java.sql.PreparedStatement ps = con
                    .prepareStatement("select j.title,
               j.content, j.displayDate from JournalArticle  j LIMIT 5");

            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                NewsModel news = new NewsModel();
                news.setTitle(rs.getString("title"));
                String date = rs.getString("displayDate");
                SimpleDateFormat smpl = new
                               SimpleDateFormat("yyyy-MM-dd");
                news.setDisplayDate(smpl.parse(date));
                news.setContent(rs.getString("content"));

                newsList.add(news);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return newsList;
}

This is my servlet :

List<NewsModel> news = (List<NewsModel>) new NewsModel();
news = SaipaDAO.getAll();

JSONArray newsArr = new JSONArray();
for (Object n : news) {
    JSONObject newsObj = new JSONObject();
}

Body:
I found it. I made a mistake in define foreach statment. this code works :

    List<NewsModel> news = new ArrayList<NewsModel>();
    JSONArray newsArr = new JSONArray();
    news = SaipaDAO.getAll();

    for (NewsModel n : news) {
        JSONObject newsObj = new JSONObject();

        newsObj.put("title", n.getTitle());
        newsObj.put("content", n.getContent());
        newsObj.put("displayDate", n.getDisplayDate());
        newsArr.add(newsObj);

    }


问:
slicing pandas df based on repeated cycle values in a particular column
I have df like below (Example)

```<code>index       y       z
0           118     .
1           118     .
2           118     .
3           116
4           116
5           110
6           110
7           104
8           104
.
.
.
.
.
320         3       .
321         3       .
322         3
323         7
324         7
328         11
329         11
.
.
.
350         25
351         25
</code>```

As you can see in column y the values starts from 118 and it keeps on decreasing till number 3 at index 322. Again it keeps increasing from index 323 of value 7 and it reaches the value of 25 at index 351.

Also you can find the repeated value in column y. (118 repeated thrice, 116 repeated twice and so on....)

My Requirement

I would like to slice the first part of that df.(Value from 118 to 3)
i.e., from index 0 till 322.

how my df should look like

```<code>index       y       z
0           118     .
1           118     .
2           118     .
3           116
4           116
5           110
6           110
7           104
8           104
.
.
.
.
.
320         3       .
321         3       .
322         3
</code>```

I believe that there should be an alternate pythonic way which make it easier. (In-built function or using numpy) Any help would be appreciated.

Body:
I have df like below (Example)

index       y       z
0           118     .
1           118     .
2           118     .
3           116
4           116
5           110
6           110
7           104
8           104
.
.
.
.
.
320         3       .
321         3       .
322         3
323         7
324         7
328         11
329         11
.
.
.
350         25
351         25

As you can see in column y the values starts from 118 and it keeps on decreasing till number 3 at index 322. Again it keeps increasing from index 323 of value 7 and it reaches the value of 25 at index 351.

Also you can find the repeated value in column y. (118 repeated thrice, 116 repeated twice and so on....)

My Requirement

I would like to slice the first part of that df.(Value from 118 to 3)
i.e., from index 0 till 322.

how my df should look like

index       y       z
0           118     .
1           118     .
2           118     .
3           116
4           116
5           110
6           110
7           104
8           104
.
.
.
.
.
320         3       .
321         3       .
322         3

I believe that there should be an alternate pythonic way which make it easier. (In-built function or using numpy) Any help would be appreciated.

Body:
With df as the input dataframe and index in the sequence - 0,1,.., you can do -

df.iloc[:(df.y.shift()<df.y).idxmax()[0]]

For a generic index format, you can do -

df.iloc[:(df.y.shift()<df.y).to_numpy().argmax()]

Sample run -

In [106]: df
Out[106]:
      y         z
7   118  0.149675
8   118  0.386489
9     3  0.449950
10    3  0.902349
11    8  0.969809
12   11  0.170910

In [107]: df.iloc[:(df.y.shift()<df.y).to_numpy().argmax()]
Out[107]:
      y         z
7   118  0.149675
8   118  0.386489
9     3  0.449950
10    3  0.902349

We can also use slicing on the array data -

In [108]: a = df.y.to_numpy().ravel()

In [109]: df.iloc[:(a[:-1] < a[1:]).argmax()+1]
Out[109]:
      y         z
7   118  0.149675
8   118  0.386489
9     3  0.449950
10    3  0.902349

Alternatively, with np.diff to replace shifted comparison -

In [110]: df.iloc[:(np.diff(a)>0).argmax()+1]
Out[110]:
      y         z
7   118  0.149675
8   118  0.386489
9     3  0.449950
10    3  0.902349


问:
'IServiceCollection' does not contain a definition for 'AddSession'
I am getting an error while adding 'AddSession' in ASP.Net Core 1.1 using VS2017.

'IServiceCollection' does not contain a definition for 'AddSession'
and no extension method 'AddSession' accepting a first argument of
type 'IServiceCollection' could be found (are you missing a using
directive or an assembly reference?)

.csproj

The package is already installed in this solution.

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>

<PropertyGroup>
<PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
</PropertyGroup>
 <ItemGroup>
  <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
  <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
 </ItemGroup>
 <ItemGroup>
 <DotNetCliToolReference
 Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
</ItemGroup>

 </Project>
```

Error :

答:
It looks like you missed something. In Package Manager Console, write:

```<code>install-package Microsoft.AspNetCore.Session -version x.x.x
</code>```

x.x.x depends on your project reference

Body:
I am getting an error while adding 'AddSession' in ASP.Net Core 1.1 using VS2017.

'IServiceCollection' does not contain a definition for 'AddSession'
and no extension method 'AddSession' accepting a first argument of
type 'IServiceCollection' could be found (are you missing a using
directive or an assembly reference?)

.csproj

The package is already installed in this solution.

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup>

<PropertyGroup>
<PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
</PropertyGroup>
 <ItemGroup>
  <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
  <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
 </ItemGroup>
 <ItemGroup>
 <DotNetCliToolReference
 Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
</ItemGroup>

 </Project>

Error :

Body:
It looks like you missed something. In Package Manager Console, write:

install-package Microsoft.AspNetCore.Session -version x.x.x

x.x.x depends on your project reference


问:
How can I create website with transferring file to Ubuntu server
I would like to upload two text files via web page, and transfer them to my ubuntu server. Then I want to add them into one file on the server, and receive it from server. So I can download the file on the web page.

I was trying to find some django and flask framework to do what i want, but i couldn't find it.

Could you recommend some reference to my question, or example?

答:
Although it seems to be an overkill, either Django or Flask can do the job.

Taking Django as an example, you can set up you models to include two FileField to store the user uploaded files for future use.

You then need to specify the two FileField in forms as a ModelForm.

As for views you'll need a view to handle upload and a view to handle download of concatenated text (assuming the content is generated when user requests the download).

If you plan to do this using a framework it's recommended that you read through at least the tutorial of the Django documentation.


问:
How to preserve order of attributes when am modifying value in xml configuration file?
When modifying attribute of xml configuration file the order of attributes are changing.

```<code>Before modifying xml: <connection user="testing" intervalInSeconds="50" versionUpdates="10" />

After modifying xml: <connection intervalInSeconds="50" user="testing" versionUpdates="10" />
</code>```

How to preserve order of attributes in python 3?

Code:

```<code>import xml.etree.ElementTree as ET
tree = ET.parse('file path')
root = tree.getroot()

# modifying an attribute
for elem in root.iter('connection'):

    elem.set('versionUpdates', '10')

tree.write('file path', encoding="UTF-8", xml_declaration = True)
</code>```

答:
Doing it the following way, maintains the order  - not sure why doing it your way doesn't:

```<code>mystr = """
<connection user="testing" intervalInSeconds="50" versionUpdates="10" />
"""

from lxml import etree
root = etree.fromstring(mystr)
for elem in root.iter('connection'):
    elem.set('versionUpdates', '20') #note: I changed it to '20', just to check
print(etree.tostring(root, pretty_print=True))
</code>```

Output:

```<code>b'<connection user="testing" intervalInSeconds="50" versionUpdates="20"/>\n'
</code>```

So modification is implemented, but order is maintained. Not sure if it helps your specific situation, but it may be an option.

Body:
When modifying attribute of xml configuration file the order of attributes are changing.

Before modifying xml: <connection user="testing" intervalInSeconds="50" versionUpdates="10" />

After modifying xml: <connection intervalInSeconds="50" user="testing" versionUpdates="10" />

How to preserve order of attributes in python 3?

Code:

import xml.etree.ElementTree as ET
tree = ET.parse('file path')
root = tree.getroot()

# modifying an attribute
for elem in root.iter('connection'):

    elem.set('versionUpdates', '10')

tree.write('file path', encoding="UTF-8", xml_declaration = True)

Body:
Doing it the following way, maintains the order  - not sure why doing it your way doesn't:

mystr = """
<connection user="testing" intervalInSeconds="50" versionUpdates="10" />
"""

from lxml import etree
root = etree.fromstring(mystr)
for elem in root.iter('connection'):
    elem.set('versionUpdates', '20') #note: I changed it to '20', just to check
print(etree.tostring(root, pretty_print=True))

Output:

b'<connection user="testing" intervalInSeconds="50" versionUpdates="20"/>\n'

So modification is implemented, but order is maintained. Not sure if it helps your specific situation, but it may be an option.


问:
Compare and Extract elements of 2 Arrays
I have 2 String Arrays:

let a = ["jan", "feb", "jun"]

let b = ["jan", "may", "feb"]

I need to check which elements of the a array are not in b array and store the results in an array called c.

I tried to achieve that using this extension:

```<code>extension Array where Element : Hashable {
    func difference(from other: [Element]) -> [Element] {
        let thisSet = Set(self)
        let otherSet = Set(other)
        return Array(thisSet.symmetricDifference(otherSet))
    }
}
</code>```

but the result it gives me are the difference between the two arrays (ie "may", "jun") whereas I ONLY need the elements from a array that are NOT in the b array. How can I achieve this?

答:
You need to subtract b from a

```<code>return Array(otherSet.subtracting(thisSet))
</code>```

```<code>let a = ["jan", "feb", "jun"]

let b = ["jan", "may", "feb"]

print(b.difference(from: a)) // jun
</code>```

Body:
I have 2 String Arrays:

let a = ["jan", "feb", "jun"]

let b = ["jan", "may", "feb"]

I need to check which elements of the a array are not in b array and store the results in an array called c.

I tried to achieve that using this extension:

extension Array where Element : Hashable {
    func difference(from other: [Element]) -> [Element] {
        let thisSet = Set(self)
        let otherSet = Set(other)
        return Array(thisSet.symmetricDifference(otherSet))
    }
}

but the result it gives me are the difference between the two arrays (ie "may", "jun") whereas I ONLY need the elements from a array that are NOT in the b array. How can I achieve this?

Body:
You need to subtract b from a

return Array(otherSet.subtracting(thisSet))

let a = ["jan", "feb", "jun"]

let b = ["jan", "may", "feb"]

print(b.difference(from: a)) // jun


答:
You want to subtract b from a

```<code>return Array(thisSet.subtracting(otherSet))
</code>```

Alternatively

```<code>extension Array where Element : Hashable {
    func difference(from other: [Element]) -> [Element] {
        var temp = self
        temp.removeAll{ other.contains($0) }
        return temp
    }
}
</code>```

Title: Compare and Extract elements of 2 Arrays

Body:
You want to subtract b from a

return Array(thisSet.subtracting(otherSet))

Alternatively

extension Array where Element : Hashable {
    func difference(from other: [Element]) -> [Element] {
        var temp = self
        temp.removeAll{ other.contains($0) }
        return temp
    }
}


问:
How can I get images from "assets/resource/mat "?
I have some images in "assets/resource/mat" . I want to get this images and put them to array . But when I try to get this images I'm getting ArrayIndexOutOfBoundsException . I think that there is problem with Resource.LoadAll("mat") method . But I can't fix it . Please help me</p>

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class test : MonoBehaviour
{
    private string t;
    public Sprite[] Icons;

    void Start()
    {
        Object[] loadedIcons = Resources.LoadAll("mat");
        Icons = new Sprite[loadedIcons.Length];

        for (int x = 0; x < loadedIcons.Length; x++)
        {
            Icons[x] = (Sprite)loadedIcons[x];
            Debug.Log("Loading....");
        }

         GameObject sp = new GameObject();
         sp.GetComponent<SpriteRenderer>().sprite = Icons[0];
    }
}
</code>```

答:
Loading all images from a particular folder, with LINQ, would look like this...</p>

```<code>using UnityEngine;
using System.Linq;

public class Four : MonoBehaviour
{
    public Sprite[] icons;

    void Start()
    {
        icons= Resources.LoadAll("met", typeof(Sprite)).Cast<Sprite>().ToArray();
    }
}
</code>```

Body:
I have some images in "assets/resource/mat" . I want to get this images and put them to array . But when I try to get this images I'm getting ArrayIndexOutOfBoundsException . I think that there is problem with Resource.LoadAll("mat") method . But I can't fix it . Please help me

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class test : MonoBehaviour
{
    private string t;
    public Sprite[] Icons;

    void Start()
    {
        Object[] loadedIcons = Resources.LoadAll("mat");
        Icons = new Sprite[loadedIcons.Length];

        for (int x = 0; x < loadedIcons.Length; x++)
        {
            Icons[x] = (Sprite)loadedIcons[x];
            Debug.Log("Loading....");
        }

         GameObject sp = new GameObject();
         sp.GetComponent<SpriteRenderer>().sprite = Icons[0];
    }
}

Body:
Loading all images from a particular folder, with LINQ, would look like this...

using UnityEngine;
using System.Linq;

public class Four : MonoBehaviour
{
    public Sprite[] icons;

    void Start()
    {
        icons= Resources.LoadAll("met", typeof(Sprite)).Cast<Sprite>().ToArray();
    }
}


问:
Navigate to previous Activity
I have two screens, in second screen i have one back button that shows the first screen(using intent). if i click that back button from second screen i navigated to first screen no probs in that.. now i want to navigate back to second screen automatically without clicking any button. Please help me how can i do this. Thanks for ur valuable time .</p>

答:
I would give a try to a ViewFlipper activity, with two screens. This, of course, if you can encapsulate your actions into one activity (which i'm sure is manageable with AsyncTasks / Threads, Services and Handlers).

This way you can use gestures, (soft/hard)buttons, dropdowns, -whatever-, to navigate between your screens.

ContentLicense: CC BY-SA 2.5

Title: Navigate to previous Activity

ContentLicense: CC BY-SA 3.0


问:
python get month of maximum value xarray

How to get the month of maximum runoff

I want to get the month of maximum runoff for each year, and for the time series as a whole. The idea is to characterise global seasonality by looking at the month of max runoff. I then want to try and consider whether each pixel has a unimodal or bimodal regime.

I want to create a map like the one in the Pangeo Examples here.

What this shows is the hour of maximum precipitation. I want to show the MONTH of maximum runoff (as an integer).

Getting the data

Here I download the GRUN runoff data and create an xarray object.
NOTE: The dataset here is >1GB. I am using it to make this example entirely reproducible.

# get the data
import subprocess
command = """
wget -O grun.nc https://www.research-collection.ethz.ch/bitstream/handle/20.500.11850/324386/GRUN_v1_GSWP3_WGS84_05_1902_2014.nc?sequence=1&isAllowed=y
"""
import os
if not os.path.exists('grun.nc'):
  process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
  output, error = process.communicate()

# read the data
import xarray as xr
ds = xr.open_dataset('grun.nc')

# select a subset so we can work with it more quickly
ds = ds.isel(time=slice(-100,-1))
ds

Out[]:
<xarray.Dataset>
Dimensions:  (lat: 360, lon: 720, time: 99)
Coordinates:
  * lon      (lon) float64 -179.8 -179.2 -178.8 -178.2 ... 178.8 179.2 179.8
  * lat      (lat) float64 -89.75 -89.25 -88.75 -88.25 ... 88.75 89.25 89.75
  * time     (time) datetime64[ns] 2006-09-01 2006-10-01 ... 2014-11-01
Data variables:
    Runoff   (time, lat, lon) float32 ...
Attributes:
    title:                   GRUN
    version:                 GRUN 1.0
    meteorological_forcing:  GSWP3
    temporal_resolution:     monthly
    spatial_resolution:      0.5x0.5
    crs:                     WGS84
    proj4:                   +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
    EPSG:                    4326
    references:              Ghiggi et al.,2019. GRUN: An observation-based g...
    authors:                 Gionata Ghiggi; Lukas Gudmundsson
    contacts:                gionata.ghiggi@gmail.com; lukas.gudmundsson@env....
    institution:             Land-Climate Dynamics, Institute for Atmospheric...
    institution_id:          IAC ETHZ

```
<h2>What I have tried</h2>
<p>I have nan values so I can't just apply an <code>argmax()</code> to the dataset. I use the same approach as @jhamman here combined with the Pangeo Examples above. I'm not entirely sure what this is giving me but it seems to be giving me</p>
<pre class="lang-py prettyprint-override"><code># Apply argmax where you have NAN values
def my_func(ds, dim=None):
    return ds.isel(**{dim: ds['Runoff'].argmax(dim)})

mask = ds['Runoff'].isel(time=0).notnull()  # determine where you have valid data
ds2 = ds.fillna(-9999)  # fill nans with a missing flag of some kind
new = ds2.reset_coords(drop=True).groupby('time.month').apply(my_func, dim='time').where(mask)  # do the groupby operation/reduction and reapply the mask
new

Out[]:
<xarray.Dataset>
Dimensions:  (lat: 360, lon: 720, month: 12)
Coordinates:
  * lon      (lon) float64 -179.8 -179.2 -178.8 -178.2 ... 178.8 179.2 179.8
  * lat      (lat) float64 -89.75 -89.25 -88.75 -88.25 ... 88.75 89.25 89.75
  * month    (month) int64 1 2 3 4 5 6 7 8 9 10 11 12
Data variables:
    Runoff   (month, lat, lon) float32 nan nan nan nan nan ... nan nan nan nan
Attributes:
    title:                   GRUN
    version:                 GRUN 1.0
    meteorological_forcing:  GSWP3
    temporal_resolution:     monthly
    spatial_resolution:      0.5x0.5
    crs:                     WGS84
    proj4:                   +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
    EPSG:                    4326
    references:              Ghiggi et al.,2019. GRUN: An observation-based g...
    authors:                 Gionata Ghiggi; Lukas Gudmundsson
    contacts:                gionata.ghiggi@gmail.com; lukas.gudmundsson@env....
    institution:             Land-Climate Dynamics, Institute for Atmospheric...
    institution_id:          IAC ETHZ

</code>```

This gives me

import matplotlib.pyplot as plt
fig,ax = plt.subplots(figsize=(12,8))
new.Runoff.sel(month=10).plot(ax=ax,  cmap='twilight')
```
<p><img src="https://i.stack.imgur.com/X3mlE.png" alt="My output currently" /></p>
<h2> Ideal Output</h2>
<h3>What I want is for the value of each Pixel to be the month of maximum Runoff.</h3>
<p>Happy to convert to <code>pandas</code> if necessary.</p>
<p>So I would end up with a xr.Dataset with the integer for the month of maximum runoff. Ideally, it would be great to also have the month of maximum runoff over time so I can also see the way that this seasonality has changed.</p>
<pre class="lang-py prettyprint-override"><code><xarray.Dataset>
Dimensions:  (lat: 360, lon: 720)
Coordinates:
  * lon      (lon) float64 -179.8 -179.2 -178.8 -178.2 ... 178.8 179.2 179.8
  * lat      (lat) float64 -89.75 -89.25 -88.75 -88.25 ... 88.75 89.25 89.75
Data variables:
    Month_of_max (lat, lon) int32 ...

# OR EVEN BETTER
<xarray.Dataset>
Dimensions:  (lat: 360, lon: 720, Year: 10)
Coordinates:
  * lon      (lon) float64 -179.8 -179.2 -178.8 -178.2 ... 178.8 179.2 179.8
  * lat      (lat) float64 -89.75 -89.25 -88.75 -88.25 ... 88.75 89.25 89.75
  * year     (year) float64 2010 2011 2012 2013 ...
Data variables:
    Month_of_max (lat, lon, year) int32 ...
</code>```

答:
So the best solution I found was to convert to a pandas.Dataframe object and then do the calculations there. I have wrapped the solution into the functions below.

First let's work with a subset of the data (it takes ages otherwise). This is a box around Kenya.

import xarray as xr
ds = xr.open_dataset('grun.nc')
ds = ds.isel(time=slice(-20,-1))
ds = ds.sel(lat=slice(-5.202,6.002),lon=slice(33.501,42.283))

ds.attrs = ''
ds

Out[]:
<xarray.Dataset>
Dimensions:  (lat: 22, lon: 18, time: 19)
Coordinates:
  * lon      (lon) float64 33.75 34.25 34.75 35.25 ... 40.75 41.25 41.75 42.25
  * lat      (lat) float64 -4.75 -4.25 -3.75 -3.25 -2.75 ... 4.25 4.75 5.25 5.75
  * time     (time) datetime64[ns] 2013-05-01 2013-06-01 ... 2014-11-01
Data variables:
    Runoff   (time, lat, lon) float32 ...
```

<p>The work is all done and tied together in: <code>calculate_annual_month_of_max()</code>. Basically what it does is convert the <code>xr.Dataset</code> to a <code>pd.Dataframe</code> object then it extracts the timestep of maximum Runoff for each <code>lat-lon-year</code>. The beauty of this approach is that it returns both the <code>Runoff</code> value and the <code>month</code> integer.</p>

<pre class="lang-py prettyprint-override"><code>import pandas as pd

def convert_to_df(ds):
    """
    Returns:
    -------
    xr.Dataset
    """
    df = ds.to_dataframe()
    df.reset_index(inplace=True)
    return df

def calculate_year_month_cols(df):
    """"""
    assert 'time' in df.columns, f"time should be in df.columns. Currently: {[c for c in df.columns]}"
    df['year'] = df.time.map(lambda x: x.year)
    df['month'] = df.time.map(lambda x: x.month)

    return df

def calculate_month_of_max_value(df, value_col):
    """
    Arguments
    ---------
    df : pd.DataFrame
        dataframe converted from xarray with ['lat','lon', 'year', value_col] columns

    value_col : str
        column that you want to find the month of maximum for
        e.g. Which month (int) in each pixel (lat,lon) has the highest runoff
    """
    max_months = df.loc[df.groupby(["lat","lon","year"])[value_col].idxmax()]
    return max_months

def convert_dataframe_to_xarray(df, index_cols=['lat','lon']):
    """
    Arguments
    ---------
    df: pd.DataFrame
        the dataframe to convert to xr.dataset

    index_cols: List[str]
        the columns that will become the coordinates
        of the output xr.Dataset

    Returns
    -------
    xr.Dataset
    """
    out = df.set_index(index_cols).dropna()
    ds = out.to_xarray()
    return ds

def calculate_annual_month_of_max(ds, variable):
    """for the `variable` in the `ds` calculate the
    month of maximum for a given pixel-year.

    Returns:
    -------
    xr.Dataset
    """
    # convert to a dataframe
    df = convert_to_df(ds)
    df = calculate_year_month_cols(df)
    # calculate the month of maximum
    df = calculate_month_of_max_value(df, value_col=variable)
    # reconstitute the dataframe object
    ds_out = convert_dataframe_to_xarray(df, index_cols=['lat','lon','year'])

    return ds_out

mon_of_max = calculate_annual_month_of_max(ds, variable='Runoff')
mon_of_max

Out[]:
<xarray.Dataset>
Dimensions:  (lat: 22, lon: 18, year: 2)
Coordinates:
  * lat      (lat) float64 -4.75 -4.25 -3.75 -3.25 -2.75 ... 4.25 4.75 5.25 5.75
  * lon      (lon) float64 33.75 34.25 34.75 35.25 ... 40.75 41.25 41.75 42.25
  * year     (year) float64 2.013e+03 2.014e+03
Data variables:
    time     (lat, lon, year) datetime64[ns] 2013-12-01 ... 2014-10-01
    Runoff   (lat, lon, year) float32 0.5894838 0.9081207 ... 0.2789653
    month    (lat, lon, year) float64 12.0 1.0 12.0 1.0 ... 11.0 10.0 11.0 10.0

</code>```

Which looks like:

Body:
How to get the month of maximum runoff

I want to get the month of maximum runoff for each year, and for the time series as a whole. The idea is to characterise global seasonality by looking at the month of max runoff. I then want to try and consider whether each pixel has a unimodal or bimodal regime.

I want to create a map like the one in the Pangeo Examples here.

What this shows is the hour of maximum precipitation. I want to show the MONTH of maximum runoff (as an integer).

Getting the data

Here I download the GRUN runoff data and create an xarray object.
NOTE: The dataset here is >1GB. I am using it to make this example entirely reproducible.

# get the data
import subprocess
command = """
wget -O grun.nc https://www.research-collection.ethz.ch/bitstream/handle/20.500.11850/324386/GRUN_v1_GSWP3_WGS84_05_1902_2014.nc?sequence=1&isAllowed=y
"""
import os
if not os.path.exists('grun.nc'):
  process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
  output, error = process.communicate()

# read the data
import xarray as xr
ds = xr.open_dataset('grun.nc')

# select a subset so we can work with it more quickly
ds = ds.isel(time=slice(-100,-1))
ds

Out[]:
<xarray.Dataset>
Dimensions:  (lat: 360, lon: 720, time: 99)
Coordinates:
  * lon      (lon) float64 -179.8 -179.2 -178.8 -178.2 ... 178.8 179.2 179.8
  * lat      (lat) float64 -89.75 -89.25 -88.75 -88.25 ... 88.75 89.25 89.75
  * time     (time) datetime64[ns] 2006-09-01 2006-10-01 ... 2014-11-01
Data variables:
    Runoff   (time, lat, lon) float32 ...
Attributes:
    title:                   GRUN
    version:                 GRUN 1.0
    meteorological_forcing:  GSWP3
    temporal_resolution:     monthly
    spatial_resolution:      0.5x0.5
    crs:                     WGS84
    proj4:                   +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
    EPSG:                    4326
    references:              Ghiggi et al.,2019. GRUN: An observation-based g...
    authors:                 Gionata Ghiggi; Lukas Gudmundsson
    contacts:                gionata.ghiggi@gmail.com; lukas.gudmundsson@env....
    institution:             Land-Climate Dynamics, Institute for Atmospheric...
    institution_id:          IAC ETHZ

What I have tried

I have nan values so I can't just apply an argmax() to the dataset. I use the same approach as @jhamman here combined with the Pangeo Examples above. I'm not entirely sure what this is giving me but it seems to be giving me

# Apply argmax where you have NAN values
def my_func(ds, dim=None):
    return ds.isel(**{dim: ds['Runoff'].argmax(dim)})

mask = ds['Runoff'].isel(time=0).notnull()  # determine where you have valid data
ds2 = ds.fillna(-9999)  # fill nans with a missing flag of some kind
new = ds2.reset_coords(drop=True).groupby('time.month').apply(my_func, dim='time').where(mask)  # do the groupby operation/reduction and reapply the mask
new

Out[]:
<xarray.Dataset>
Dimensions:  (lat: 360, lon: 720, month: 12)
Coordinates:
  * lon      (lon) float64 -179.8 -179.2 -178.8 -178.2 ... 178.8 179.2 179.8
  * lat      (lat) float64 -89.75 -89.25 -88.75 -88.25 ... 88.75 89.25 89.75
  * month    (month) int64 1 2 3 4 5 6 7 8 9 10 11 12
Data variables:
    Runoff   (month, lat, lon) float32 nan nan nan nan nan ... nan nan nan nan
Attributes:
    title:                   GRUN
    version:                 GRUN 1.0
    meteorological_forcing:  GSWP3
    temporal_resolution:     monthly
    spatial_resolution:      0.5x0.5
    crs:                     WGS84
    proj4:                   +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs
    EPSG:                    4326
    references:              Ghiggi et al.,2019. GRUN: An observation-based g...
    authors:                 Gionata Ghiggi; Lukas Gudmundsson
    contacts:                gionata.ghiggi@gmail.com; lukas.gudmundsson@env....
    institution:             Land-Climate Dynamics, Institute for Atmospheric...
    institution_id:          IAC ETHZ

This gives me

import matplotlib.pyplot as plt
fig,ax = plt.subplots(figsize=(12,8))
new.Runoff.sel(month=10).plot(ax=ax,  cmap='twilight')

 Ideal Output

What I want is for the value of each Pixel to be the month of maximum Runoff.

Happy to convert to pandas if necessary.

So I would end up with a xr.Dataset with the integer for the month of maximum runoff. Ideally, it would be great to also have the month of maximum runoff over time so I can also see the way that this seasonality has changed.

<xarray.Dataset>
Dimensions:  (lat: 360, lon: 720)
Coordinates:
  * lon      (lon) float64 -179.8 -179.2 -178.8 -178.2 ... 178.8 179.2 179.8
  * lat      (lat) float64 -89.75 -89.25 -88.75 -88.25 ... 88.75 89.25 89.75
Data variables:
    Month_of_max (lat, lon) int32 ...

# OR EVEN BETTER
<xarray.Dataset>
Dimensions:  (lat: 360, lon: 720, Year: 10)
Coordinates:
  * lon      (lon) float64 -179.8 -179.2 -178.8 -178.2 ... 178.8 179.2 179.8
  * lat      (lat) float64 -89.75 -89.25 -88.75 -88.25 ... 88.75 89.25 89.75
  * year     (year) float64 2010 2011 2012 2013 ...
Data variables:
    Month_of_max (lat, lon, year) int32 ...

Body:
So the best solution I found was to convert to a pandas.Dataframe object and then do the calculations there. I have wrapped the solution into the functions below.

First let's work with a subset of the data (it takes ages otherwise). This is a box around Kenya.

import xarray as xr
ds = xr.open_dataset('grun.nc')
ds = ds.isel(time=slice(-20,-1))
ds = ds.sel(lat=slice(-5.202,6.002),lon=slice(33.501,42.283))

ds.attrs = ''
ds

Out[]:
<xarray.Dataset>
Dimensions:  (lat: 22, lon: 18, time: 19)
Coordinates:
  * lon      (lon) float64 33.75 34.25 34.75 35.25 ... 40.75 41.25 41.75 42.25
  * lat      (lat) float64 -4.75 -4.25 -3.75 -3.25 -2.75 ... 4.25 4.75 5.25 5.75
  * time     (time) datetime64[ns] 2013-05-01 2013-06-01 ... 2014-11-01
Data variables:
    Runoff   (time, lat, lon) float32 ...

The work is all done and tied together in: calculate_annual_month_of_max(). Basically what it does is convert the xr.Dataset to a pd.Dataframe object then it extracts the timestep of maximum Runoff for each lat-lon-year. The beauty of this approach is that it returns both the Runoff value and the month integer.

import pandas as pd

def convert_to_df(ds):
    """
    Returns:
    -------
    xr.Dataset
    """
    df = ds.to_dataframe()
    df.reset_index(inplace=True)
    return df

def calculate_year_month_cols(df):
    """"""
    assert 'time' in df.columns, f"time should be in df.columns. Currently: {[c for c in df.columns]}"
    df['year'] = df.time.map(lambda x: x.year)
    df['month'] = df.time.map(lambda x: x.month)

    return df

def calculate_month_of_max_value(df, value_col):
    """
    Arguments
    ---------
    df : pd.DataFrame
        dataframe converted from xarray with ['lat','lon', 'year', value_col] columns

    value_col : str
        column that you want to find the month of maximum for
        e.g. Which month (int) in each pixel (lat,lon) has the highest runoff
    """
    max_months = df.loc[df.groupby(["lat","lon","year"])[value_col].idxmax()]
    return max_months

def convert_dataframe_to_xarray(df, index_cols=['lat','lon']):
    """
    Arguments
    ---------
    df: pd.DataFrame
        the dataframe to convert to xr.dataset

    index_cols: List[str]
        the columns that will become the coordinates
        of the output xr.Dataset

    Returns
    -------
    xr.Dataset
    """
    out = df.set_index(index_cols).dropna()
    ds = out.to_xarray()
    return ds

def calculate_annual_month_of_max(ds, variable):
    """for the `variable` in the `ds` calculate the
    month of maximum for a given pixel-year.

    Returns:
    -------
    xr.Dataset
    """
    # convert to a dataframe
    df = convert_to_df(ds)
    df = calculate_year_month_cols(df)
    # calculate the month of maximum
    df = calculate_month_of_max_value(df, value_col=variable)
    # reconstitute the dataframe object
    ds_out = convert_dataframe_to_xarray(df, index_cols=['lat','lon','year'])

    return ds_out

mon_of_max = calculate_annual_month_of_max(ds, variable='Runoff')
mon_of_max

Out[]:
<xarray.Dataset>
Dimensions:  (lat: 22, lon: 18, year: 2)
Coordinates:
  * lat      (lat) float64 -4.75 -4.25 -3.75 -3.25 -2.75 ... 4.25 4.75 5.25 5.75
  * lon      (lon) float64 33.75 34.25 34.75 35.25 ... 40.75 41.25 41.75 42.25
  * year     (year) float64 2.013e+03 2.014e+03
Data variables:
    time     (lat, lon, year) datetime64[ns] 2013-12-01 ... 2014-10-01
    Runoff   (lat, lon, year) float32 0.5894838 0.9081207 ... 0.2789653
    month    (lat, lon, year) float64 12.0 1.0 12.0 1.0 ... 11.0 10.0 11.0 10.0

Which looks like:


问:
Not able to call JQuery On Submit function from inside a modal form
I am trying to call a Jquery function on submission of a form which lies inside a modal. The modal itself is in another file test1.php. But the jquery function is not getting called

This is my HTML File:

```<code>   <!doctype html>
    <html>
        <head>
            <title>Job Entry</title>
            <link href="./css/bootstrap.min.css" rel="stylesheet"
            type="text/css">
            <link href="./css/style.css" rel="stylesheet" type="text/css">
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width initial-
            scale=1">
        </head>

        <body>
            <div class="col-md-2 col-md-push-1">
                       <a href="test1.php" id="addNewCP" name="addNewCP"
                       class="form-control btn btn-success " data-toggle="modal" data-target="#addNewCPModal"  >
                           <span class="glyphicon glyphicon-plus"></span>  Add CP</a>
                    </div>

            <!--Modal for addition of new CP details begins here-->
            <div class="modal fade text-center" id="addNewCPModal">
                <form method="post" id="enterCPDetails" name="enterCPDetails">
                <div class="modal-dialog ">
                    <div class="modal-content">
                     <!-- Rest of the content of this Modal lies in test1.php -->
                    </div>
                </div>
                </form>
            </div>

            <script src="js/jquery-3.2.0.min.js"></script>
            <script src="js/bootstrap.min.js"></script>
            <script src="js/custom.js"></script>
            <script src="js/custom1.js"></script>
        </body>
        </html>
</code>```

The modal lies in separate page titled test1.php:

```<code><div class="modal-header" style="height:55px; background-color: #122b40; color:#fff; padding:10px">
    <button type="button" class="close" style="color:white" data-dismiss="modal" aria-hidden="true"> × </button>
    Electronics Quality Control Division <br> Data Management System
</div>

    <div class="modal-body">
        <div class="container">
            <div class="row">
                <div class="col-lg-2">
                <span class="default-textSetting" > Job No: </span>
                </div>
                <div class="col-lg-2 col-lg-offset-2">
                    <input type="text" class="form-control" placeholder="CP No" name="newCPNo" id="newCPNo" required>
                </div>
            </div>
        </div><br>
                <table  id="newCPDetailsTable" class=" table table-stripped table-condensed table-bordered" >
                    <thead>
                        <tr>
                            <th>ICP No. </th>
                            <th>Substrate No. </th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input size="16" type="text" class="form-control"  name="icp1" id="icp1" required/></td>
                            <td><input size="16"  type="text" class="form-control" name="subid1" id="subid1" required/></td>
                            <td colspan="2"><a  href="JavaScript:void(0);" onclick="addRow()" style="color:green" class="glyphicon glyphicon-plus "> </a>
                                            <a  href="JavaScript:void(0);"   style="color:red" class="glyphicon glyphicon-remove-circle "></a>
                            </td>

                        </tr>

                    </tbody>
                </table>
                <input id="cntTableRows" name="cntTableRows" type="hidden" />
    </div><!--modal body ends here-->

    <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close </button>
        <button type="submit" name="newCPDetailSubmit" id="newCPDetailSubmit" class="btn btn-default" >Save</button>
    </div>
</code>```

My Jquery function is as follows:

```<code> $(function(){
        $("#enterCPDetails").on("submit", function (event) {
        alert("Hello");
       });
    });
</code>```

What wrong am i doing. Please help

答:
Try :

```<code>$('#addNewCPModal').on('submit','#enterCPDetails',function(){
   alert("Hello");
});
</code>```

Should Work.

Body:
I am trying to call a Jquery function on submission of a form which lies inside a modal. The modal itself is in another file test1.php. But the jquery function is not getting called

This is my HTML File:

   <!doctype html>

            <title>Job Entry</title>
            <link href="./css/bootstrap.min.css" rel="stylesheet"
            type="text/css">
            <link href="./css/style.css" rel="stylesheet" type="text/css">
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width initial-
            scale=1">

                             Add CP

                <form method="post" id="enterCPDetails" name="enterCPDetails">

                </form>

The modal lies in separate page titled test1.php:

    <button type="button" class="close" style="color:white" data-dismiss="modal" aria-hidden="true"> × </button>
    Electronics Quality Control Division
 Data Management System

                 Job No:

                    <input type="text" class="form-control" placeholder="CP No" name="newCPNo" id="newCPNo" required>

                            ICP No.
                            Substrate No.

                            <input size="16" type="text" class="form-control"  name="icp1" id="icp1" required/>
                            <input size="16"  type="text" class="form-control" name="subid1" id="subid1" required/>

                <input id="cntTableRows" name="cntTableRows" type="hidden" />

        <button type="button" class="btn btn-default" data-dismiss="modal">Close </button>
        <button type="submit" name="newCPDetailSubmit" id="newCPDetailSubmit" class="btn btn-default" >Save</button>

My Jquery function is as follows:

 $(function(){
        $("#enterCPDetails").on("submit", function (event) {
        alert("Hello");
       });
    });

What wrong am i doing. Please help

Body:
Try :

$('#addNewCPModal').on('submit','#enterCPDetails',function(){
   alert("Hello");
});

Should Work.


问:
Color Intensity using Average RGB values
I am working on a project where I need to calculate a color gradient on various paper strips. I have used RGB color detector app (available on Google PlayStore) to obtain RGB values. Now to plot it I simple average RGB values : (R+G+B)/3 and get a single values as intensity. Is it okay to use it or should I use other methods to obtain a single value for intensity.

The color gradient I get is ranging from dark yellow color to white. Discoloration of paper occurs with increasing concentration of chemical used. [Chemical cannot be disclosed, sorry]

答:
(R+G+B)/3 BAD, SPECTRAL WEIGHTING GOOD

(R+G+B)/3 is incorrect math for nearly every use. It happens to be used as part of the "HSI" control for setting colors, but that control is far from perceptual uniformity.

The correct math is fairly straight forward — but as you haven't clearly defined what you need or are trying to do, it is hard to guess the best approach for you.

I will make some assumptions. It sounds like you are scanning litmus strips of some sort, and are trying to put the data into some useable form in terms of how dark they become from a particular chemical concentration.

It also sounds like you are looking for some absolute values, as opposed to the difference from strip A and strip B. Color difference math is a bit different from some more absolute measure.

However, for research, color difference between a strip and a protected master reference sample is probably a better practice, especially as you are not using a real calibrated spectrophotometer in a calibrated viewing/test environment.

CAPTURE

The quality of your data capture will have a lot to do with the data usability, and the quality of your capture room lighting and camera or meter is a big part of this.

ROOM COLOR
Ideally that means a room painted a flat or matte neutral grey with around LRV around 20 such as this Glidden:

CONSISTENT LIGHTING
Then you want stray light blocked from the room, or at least the measuring area. NO NATURAL LIGHT!! Ideally you'll have a calibrated light source, but at least have something consistent with a high CRI.

CONSISTENT SAMPLE ILLUMINATION
The light needs to be the same distance from the sample surface, and the ambient light conditions must be controlled so that the samples are always receiving the same about of light.

CONSISTENT MEASUREMENT & DEVICE
If you are using a phone to take the images, you are probably at the mercy of the auto-exposure. If the Google app you are using takes over and provides consistent exposure, that's important. Otherwise, you'll do better getting a Nikon dSLR, and using it in manual exposure mode (always!) and always set to teh same expoure.

CAPTURE THE SAMPLE AND THE REFERENCE AT THE SAME TIME
in other words, have a reference sample that is ideally somewhere around the LRV of your average sample. An 18% greycard is probably great for this, if for no other reason than they are inexpensive and easy to replace with decent consistency.

If colors are involved then you want an XRite colorChecker chart.

5)

WHEN YOU CAPTURE SAMPLES
If you are taking photos, then you want the reference sample (i.e. grey card or colorchecker chart) in the image frame in the same location and same lighting every single time.

CONVERSION

If you are doing this via photography, then you want to be as consistent as possible, same exposure, and use the sRGB profile in the camera (do not use Adobe98, as it is a larger gamut and therefore LESS ACCURATE with higher delta E errors.)

bring the images into an image app and sample the colors. set the color picker to sample an average of an area around 10px X 10px (100 pixels total), again using the sRGB profile.

sRGB color data is gamma encoded — by you need it either in a linear luminance (Y) or possibly a perceptual space like CIELAB.

IF...

If you just want the absolute measurement of the lightness of each sample, then you can convert the sRGB data to luminance (the Y in CIEXYZ) and then use that figure for comparisons. Note however that luminance is linear relative to light, so it is not perceptually uniform.

For perceptual uniformity, you'd want CIELAB, and while in CIELAB you can do accurate calculations fo the difference between two colors.

CONVERSION STEPS AND MATH (in this order)

1) Convert

Convert hex or integer color values to float with 0 for black and 1.0 for white.

2) Linearize

Linearize the sRGB color data (that is, remove the gamma curve)

3) Apply spectral weighting

Apply the spectral weighting coefficients to each channel, and then sum them together for Y (luminance).

I describe these three steps in detail in this post.

4) Convert to L* a* b*

If you want to use a high quality color difference equation, then you need to convert from CIEXYZ to CIELAB.

5) Use CIEDE2000 for Difference

Once in LAB space, then use the CIEDE2000 equations for color difference.

The math for steps 4 and 5 is available here as code snippets.


问:
how to maintain model properties
i am new to ROR, just setup the enviroment
ruby 1.9.2 with rails 3.0.6

just notice one thing.
after create model.. propeties has been add into database but couldn`t see from the class..
and it just work for me.

looks like rails will scan my database schema before launching the application..

but i have a question for it:

if i frequently add or remove columns...
how do i know what properties do i have if i do not define in the class?
can i manually add properties into ActiceRecord class(es) ??

```<code>class User < ActiveRecord::Base
  has_one :contact
  validates_confirmation_of :password
end

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :username
      t.string :password

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end
</code>```

答:
You can look at db/schema.rb file to see database schema you have.

And yes, sometimes I add properies to the model class, but they are virtual properties:

```<code>def full_name
   [first_name, last_name].joun(' ')
end

def full_name=(name)
    split = name.split(' ', 2)
    self.first_name = split.first
    self.last_name = split.last
end
</code>```

In view:

```<code><p> Full name </p>
<%= f.text_field :full_name %>
</code>```

Title: how to maintain model properties

Body:
i am new to ROR, just setup the enviroment
ruby 1.9.2 with rails 3.0.6

just notice one thing.
after create model.. propeties has been add into database but couldn`t see from the class..
and it just work for me.

looks like rails will scan my database schema before launching the application..

but i have a question for it:

if i frequently add or remove columns...
how do i know what properties do i have if i do not define in the class?
can i manually add properties into ActiceRecord class(es) ??

class User < ActiveRecord::Base
  has_one :contact
  validates_confirmation_of :password
end

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :username
      t.string :password

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end

Body:
You can look at db/schema.rb file to see database schema you have.

And yes, sometimes I add properies to the model class, but they are virtual properties:

def full_name
   [first_name, last_name].joun(' ')
end

def full_name=(name)
    split = name.split(' ', 2)
    self.first_name = split.first
    self.last_name = split.last
end

In view:

<p> Full name </p>
<%= f.text_field :full_name %>


问:
How to use JSON with difficult objects
I have problem with dynamic JSON data. I don't know how to put it into my JAVA class. I need "routes" data. But i don't know what i should do with this ""2019-05-27": {...".

It is part of JSON file...

```<code>{
  "2019-05-26": {
    "lastUpdate": "2019-05-26 06:05:02",
    "routes": [
      {
        "routeId": 107,
        "agencyId": 18
      },
      {
        "routeId": 222,
        "agencyId": 22
      }
    ]
  },
  "2019-05-27": {
    "lastUpdate": "2019-05-27 06:05:02",
    "routes": [
      {
        "routeId": 33,
        "agencyId": 14
      },
      {
        "routeId": 345,
        "agencyId": 2232
      }
    ]
  }
}
</code>```

The code below doesn't work. It is not Map<String,Map<String, String>>. I think it is -

```<code>Gson gson = new Gson();

    Type mapType = new TypeToken<Map<String,Map<String, String>>>() {}.getType();
    Map<String,Map<String, String>> map = null;
    try {
        map = gson.fromJson(new FileReader("routes.json"), mapType);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
</code>```

What should I do to take this data ?

答:
Create POJO classes like that :

```<code>public class MyObject {
    private List<Route> routes;
    private String lastUpdate;

    public MyObject(List<Route> routes, String lastUpdate) {
        this.routes = routes;
        this.lastUpdate = lastUpdate;
    }

    // assume getters and setters
}

public class Route {
    private String routeId;
    private String agencyId;

    public Route(String routeId, String agencyId) {
        this.routeId = routeId;
        this.agencyId = agencyId;
    }
    // assume getters and setters
}
</code>```

To test it :

```<code>public static void main(String[] args) throws IOException {
        Gson gson = new Gson();

        String json = Files.lines(Paths.get("src/main/resources/data.json")).collect(Collectors.joining());

        Type mapType = new TypeToken<Map<String, MyObject>>() {}.getType();
        Map<String, MyObject> map = gson.fromJson(json, mapType);

        map.forEach((s, myObject) -> System.out.println(s + " " + myObject.getLastUpdate()));

}
</code>```

The output is :

```<code>2019-05-26 2019-05-26 06:05:02
2019-05-27 2019-05-27 06:05:02
</code>```

You just need to create a map which has date as a key and custom object as value.

Title: How to use JSON with difficult objects

Body:
I have problem with dynamic JSON data. I don't know how to put it into my JAVA class. I need "routes" data. But i don't know what i should do with this ""2019-05-27": {...".

It is part of JSON file...

{
  "2019-05-26": {
    "lastUpdate": "2019-05-26 06:05:02",
    "routes": [
      {
        "routeId": 107,
        "agencyId": 18
      },
      {
        "routeId": 222,
        "agencyId": 22
      }
    ]
  },
  "2019-05-27": {
    "lastUpdate": "2019-05-27 06:05:02",
    "routes": [
      {
        "routeId": 33,
        "agencyId": 14
      },
      {
        "routeId": 345,
        "agencyId": 2232
      }
    ]
  }
}

The code below doesn't work. It is not Map<String,Map<String, String>>. I think it is -

Gson gson = new Gson();

    Type mapType = new TypeToken<Map<String,Map<String, String>>>() {}.getType();
    Map<String,Map<String, String>> map = null;
    try {
        map = gson.fromJson(new FileReader("routes.json"), mapType);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

What should I do to take this data ?

Body:
Create POJO classes like that :

public class MyObject {
    private List<Route> routes;
    private String lastUpdate;

    public MyObject(List<Route> routes, String lastUpdate) {
        this.routes = routes;
        this.lastUpdate = lastUpdate;
    }

    // assume getters and setters
}

public class Route {
    private String routeId;
    private String agencyId;

    public Route(String routeId, String agencyId) {
        this.routeId = routeId;
        this.agencyId = agencyId;
    }
    // assume getters and setters
}

To test it :

public static void main(String[] args) throws IOException {
        Gson gson = new Gson();

        String json = Files.lines(Paths.get("src/main/resources/data.json")).collect(Collectors.joining());

        Type mapType = new TypeToken<Map<String, MyObject>>() {}.getType();
        Map<String, MyObject> map = gson.fromJson(json, mapType);

        map.forEach((s, myObject) -> System.out.println(s + " " + myObject.getLastUpdate()));

}

The output is :

2019-05-26 2019-05-26 06:05:02
2019-05-27 2019-05-27 06:05:02

You just need to create a map which has date as a key and custom object as value.


问:
Wordpress admin panel pop up window blank
I think photos speak for themselfs.
basically all this windows that open inside wp admin are blank.
is there any known solution?
Thanks

picture 1

picture 2

答:
The solution is to install "Ignore X-Frame headers" plugin on chromium based browsers or "Ignore X-Frame-Options Header" on firefox.

--This fixes the issue from the client side !


问:
How to identify the Drive root folder
I am having trouble identifying the root folder of a user's Drive. For English users it is named 'My Drive', however for French users it is named 'Mon Drive'. The file Id is unique for all root folders so this property can't be used.

How can I conclusively identify if the a folder is the root folder of the user's Drive only from the response from the metadata api?

答:
You may not have folders parent ID if someone shares folder with you that you did not add to your own drive yet. Basically 'Shared with Me' folders do't have a parent ID.

You can do a GET to get details of your root folder.

```<code>GET https://www.googleapis.com/drive/v2/files/root
</code>```

Remember to mention literally root at the end of this URL. This is alias of your root folder. You should get a JSOn response where you should have 'id' of root folder.

Title: How to identify the Drive root folder

Body:
You may not have folders parent ID if someone shares folder with you that you did not add to your own drive yet. Basically 'Shared with Me' folders do't have a parent ID.

You can do a GET to get details of your root folder.

GET https://www.googleapis.com/drive/v2/files/root

Remember to mention literally root at the end of this URL. This is alias of your root folder. You should get a JSOn response where you should have 'id' of root folder.


问:
Execute a method on second control from the first control in WPF
My ViewControl has a method called ZoomIn(). How can I execute this method on the ViewControl by clicking a Button control without going to the code-behind?

```<code><controls:ViewControl/>
<Button Content="Zoom In"/>
</code>```

Here is the code for ViewControl.xaml.cs:

```<code>    public void ZoomIn()
    {
        double actualWidth = m_child.ActualWidth;
        double actualHeight = m_child.ActualHeight;

        double x = (0.5 * actualWidth - Dx) / Scale;
        double y = (0.5 * actualHeight - Dy) / Scale;

        float startScale = Scale;

        Scale = Math.Min(Scale * ZoomFactor, ZoomMax);

        Dx = (float)x * (startScale - Scale) + Dx;
        Dy = (float)y * (startScale - Scale) + Dy;
    }
</code>```

I am trying to use MVVM for my design, but I'm not sure how to do this in this scenario because the ZoomIn() method is related to the View.

A similar situation would be if I had a Button and a TextBox, and I wanted to call the SelectAll() method on the TextBox when the Button is clicked. How can I do this without using the code-behind?

答:
There are actually several different ways to do this, one solution is to bind to an event using a behavior and a wrapper class. First define a wrapper for the event that your view model will trigger:

```<code>public class EventTriggerWrapper
{
    public event EventHandler OnTriggered;

    public void Trigger()
    {
        this.OnTriggered?.Invoke(this, EventArgs.Empty);
    }
}
</code>```

For the purpose of demonstration here's some XAML of a button and a WebBrowser, I'll use an instance of the wrapper in the view model to trigger the web broswer's Navigate() function whenever the button is pressed:

```<code>xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>

    <Button Content="Click Me" Command="{Binding NavigateCommand}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10" />

    <WebBrowser Grid.Row="1">
        <i:Interaction.Behaviors>
            <behaviors:MyCustomBehavior EventTrigger="{Binding EventTrigger}" />
        </i:Interaction.Behaviors>
    </WebBrowser>

</Grid>
</code>```

You can see that I've added a custom behaviour to the web browser control, and it's bound to a view model property called EventTrigger. You'll need to add this along with a command handler for the button to your view model:

```<code>public class MainViewModel
{
    public EventTriggerWrapper EventTrigger { get; } = new EventTriggerWrapper();

    private ICommand _NavigateCommand;
    public ICommand NavigateCommand => this._NavigateCommand ?? (this._NavigateCommand = new RelayCommand(OnNavigate));

    private void OnNavigate()
    {
        this.EventTrigger.Trigger();
    }
}
</code>```

So all that's left it to create the behavior with a property that subscribes to the event and then calls whatever function in your target control you want:

```<code>public class MyCustomBehavior : Behavior<WebBrowser>
{
    public EventTriggerWrapper EventTrigger
    {
        get { return (EventTriggerWrapper)GetValue(EventTriggerProperty); }
        set { SetValue(EventTriggerProperty, value); }
    }

    // Using a DependencyProperty as the backing store for EventTrigger.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty EventTriggerProperty =
        DependencyProperty.Register("EventTrigger", typeof(EventTriggerWrapper), typeof(MyCustomBehavior), new PropertyMetadata(null, OnEventTriggerChanged));

    private static void OnEventTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behaviour = d as MyCustomBehavior;
        var oldValue = e.OldValue as EventTriggerWrapper;
        if (oldValue != null)
            oldValue.OnTriggered -= behaviour.OnEventTriggered;
        var newValue = e.NewValue as EventTriggerWrapper;
        if (newValue != null)
            newValue.OnTriggered += behaviour.OnEventTriggered;
    }

    private void OnEventTriggered(object sender, EventArgs e)
    {
        if (this.AssociatedObject != null)
            this.AssociatedObject.Navigate("http://www.google.com");    // <-- change this to the function you want to invoke
    }
}
</code>```

Body:
My ViewControl has a method called ZoomIn(). How can I execute this method on the ViewControl by clicking a Button control without going to the code-behind?

<controls:ViewControl/>
<Button Content="Zoom In"/>

Here is the code for ViewControl.xaml.cs:

    public void ZoomIn()
    {
        double actualWidth = m_child.ActualWidth;
        double actualHeight = m_child.ActualHeight;

        double x = (0.5 * actualWidth - Dx) / Scale;
        double y = (0.5 * actualHeight - Dy) / Scale;

        float startScale = Scale;

        Scale = Math.Min(Scale * ZoomFactor, ZoomMax);

        Dx = (float)x * (startScale - Scale) + Dx;
        Dy = (float)y * (startScale - Scale) + Dy;
    }

I am trying to use MVVM for my design, but I'm not sure how to do this in this scenario because the ZoomIn() method is related to the View.

A similar situation would be if I had a Button and a TextBox, and I wanted to call the SelectAll() method on the TextBox when the Button is clicked. How can I do this without using the code-behind?

Body:
There are actually several different ways to do this, one solution is to bind to an event using a behavior and a wrapper class. First define a wrapper for the event that your view model will trigger:

public class EventTriggerWrapper
{
    public event EventHandler OnTriggered;

    public void Trigger()
    {
        this.OnTriggered?.Invoke(this, EventArgs.Empty);
    }
}

For the purpose of demonstration here's some XAML of a button and a WebBrowser, I'll use an instance of the wrapper in the view model to trigger the web broswer's Navigate() function whenever the button is pressed:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>

    <Button Content="Click Me" Command="{Binding NavigateCommand}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="10" />

    <WebBrowser Grid.Row="1">
        <i:Interaction.Behaviors>
            <behaviors:MyCustomBehavior EventTrigger="{Binding EventTrigger}" />
        </i:Interaction.Behaviors>
    </WebBrowser>

</Grid>

You can see that I've added a custom behaviour to the web browser control, and it's bound to a view model property called EventTrigger. You'll need to add this along with a command handler for the button to your view model:

public class MainViewModel
{
    public EventTriggerWrapper EventTrigger { get; } = new EventTriggerWrapper();

    private ICommand _NavigateCommand;
    public ICommand NavigateCommand => this._NavigateCommand ?? (this._NavigateCommand = new RelayCommand(OnNavigate));

    private void OnNavigate()
    {
        this.EventTrigger.Trigger();
    }
}

So all that's left it to create the behavior with a property that subscribes to the event and then calls whatever function in your target control you want:

public class MyCustomBehavior : Behavior<WebBrowser>
{
    public EventTriggerWrapper EventTrigger
    {
        get { return (EventTriggerWrapper)GetValue(EventTriggerProperty); }
        set { SetValue(EventTriggerProperty, value); }
    }

    // Using a DependencyProperty as the backing store for EventTrigger.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty EventTriggerProperty =
        DependencyProperty.Register("EventTrigger", typeof(EventTriggerWrapper), typeof(MyCustomBehavior), new PropertyMetadata(null, OnEventTriggerChanged));

    private static void OnEventTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var behaviour = d as MyCustomBehavior;
        var oldValue = e.OldValue as EventTriggerWrapper;
        if (oldValue != null)
            oldValue.OnTriggered -= behaviour.OnEventTriggered;
        var newValue = e.NewValue as EventTriggerWrapper;
        if (newValue != null)
            newValue.OnTriggered += behaviour.OnEventTriggered;
    }

    private void OnEventTriggered(object sender, EventArgs e)
    {
        if (this.AssociatedObject != null)
            this.AssociatedObject.Navigate("http://www.google.com");    // <-- change this to the function you want to invoke
    }
}


问:
Connecting to HIVE using JAVA with Cloudera Drivers with Kerberos Authentication
I am looking for a JAVA code to connect to a HIVE DB using Cloudera HIVE drivers, which needs Kerberos Authentication. Over the net I can only find codes with Apache Drivers, is there a difference? Can someone put forward some suggestion?</p>

答:
You can download the Cloudera hive drivers directly from the official Cloudera website. Yes it is not the same as the apache driver as Cloudera releases their own version of the driver.

Along with the driver, you will find the official documentation to connect to hive using kerberos.

A sample connection Jdbc url is as below:

```<code>jdbc:hive2://node1.example.com:10000;AuthMech=1; KrbRealm=EXAMPLE.COM;KrbHostFQDN=hs2node1.example.com; KrbServiceName=hive;KrbAuthType=2
</code>```

AuthMech = 1 enables kerberos connection and the rest is straightforward code to connect to kerberos using the realm and service information.

Note: You need to download the right driver as per your installation.

Hope this help :)

Body:
You can download the Cloudera hive drivers directly from the official Cloudera website. Yes it is not the same as the apache driver as Cloudera releases their own version of the driver.

Along with the driver, you will find the official documentation to connect to hive using kerberos.

A sample connection Jdbc url is as below:

jdbc:hive2://node1.example.com:10000;AuthMech=1; KrbRealm=EXAMPLE.COM;KrbHostFQDN=hs2node1.example.com; KrbServiceName=hive;KrbAuthType=2

AuthMech = 1 enables kerberos connection and the rest is straightforward code to connect to kerberos using the realm and service information.

Note: You need to download the right driver as per your installation.

Hope this help :)


问:
Iterate a piece of code connecting to API using two variables pulled from two lists
I'm trying to run a script (API to google search console) over a table of keywords and dates in order to check if there was improvement in keyword performance (SEO) after the date.

Since i'm really clueless im guessing and trying but Jupiter notebook isn't responding so i can't even tell if im wrong...

This git was made by Josh Carty
the git from which i took this code is:
https://github.com/joshcarty/google-searchconsole

Already pd.read_csv the input table (consist of two columns 'keyword' and 'date'),
made the columns into two separate lists (or maybe it better to use dictionary/other?):

KW_list and
Date_list

I tried:
for i in KW_list and j in Date_list:

```<code>for i in KW_list and j in Date_list:

 account = searchconsole.authenticate(client_config='client_secrets.json',
                                      credentials='credentials.json')
 webproperty = account['https://www.example.com/']
 report = webproperty.query.range(j, days=-30).filter('query', i, 'contains').get()
 report2 = webproperty.query.range(j, days=30).filter('query', i, 'contains').get()
 df = pd.DataFrame(report)
 df2 = pd.DataFrame(report2)
df
</code>```

Expect to see the data frame of all the different keywords (keyowrd1-stat1 , keyword2 - stats2 below, etc. [no overwrite]) at the dates 30 days before the date in the neighbor cell (in the input file)
or at least some respond from J.notebook so i will know what is going on.

答:
Try using the zip function to combine the lists into a list of tuples. This way, the date and the corresponding keyword are combined.

```<code>account = searchconsole.authenticate(client_config='client_secrets.json', credentials='credentials.json')
webproperty = account['https://www.example.com/']
df1 = None
df2 = None
first = True

for (keyword, date) in zip(KW_list, Date_list):
   report = webproperty.query.range(date, days=-30).filter('query', keyword, 'contains').get()
   report2 = webproperty.query.range(date, days=30).filter('query', keyword, 'contains').get()

    if first:
        df1 = pd.DataFrame(report)
        df2 = pd.DataFrame(report2)
        first = False
    else:
        df1 = df1.append(pd.DataFrame(report))
        df2 = df2.append(pd.DataFrame(report2))
</code>```

Body:
I'm trying to run a script (API to google search console) over a table of keywords and dates in order to check if there was improvement in keyword performance (SEO) after the date.

Since i'm really clueless im guessing and trying but Jupiter notebook isn't responding so i can't even tell if im wrong...

This git was made by Josh Carty
the git from which i took this code is:
https://github.com/joshcarty/google-searchconsole

Already pd.read_csv the input table (consist of two columns 'keyword' and 'date'),
made the columns into two separate lists (or maybe it better to use dictionary/other?):

KW_list and
Date_list

I tried:
for i in KW_list and j in Date_list:

for i in KW_list and j in Date_list:

 account = searchconsole.authenticate(client_config='client_secrets.json',
                                      credentials='credentials.json')
 webproperty = account['https://www.example.com/']
 report = webproperty.query.range(j, days=-30).filter('query', i, 'contains').get()
 report2 = webproperty.query.range(j, days=30).filter('query', i, 'contains').get()
 df = pd.DataFrame(report)
 df2 = pd.DataFrame(report2)
df

Expect to see the data frame of all the different keywords (keyowrd1-stat1 , keyword2 - stats2 below, etc. [no overwrite]) at the dates 30 days before the date in the neighbor cell (in the input file)
or at least some respond from J.notebook so i will know what is going on.

Body:
Try using the zip function to combine the lists into a list of tuples. This way, the date and the corresponding keyword are combined.

account = searchconsole.authenticate(client_config='client_secrets.json', credentials='credentials.json')
webproperty = account['https://www.example.com/']
df1 = None
df2 = None
first = True

for (keyword, date) in zip(KW_list, Date_list):
   report = webproperty.query.range(date, days=-30).filter('query', keyword, 'contains').get()
   report2 = webproperty.query.range(date, days=30).filter('query', keyword, 'contains').get()

    if first:
        df1 = pd.DataFrame(report)
        df2 = pd.DataFrame(report2)
        first = False
    else:
        df1 = df1.append(pd.DataFrame(report))
        df2 = df2.append(pd.DataFrame(report2))


问:
How to load and draw emojis on canvas efficiently?
I would like to print an emoji on html canvas.

It can be done using images, but it is cumbersome. Is there a better way?

const canvas = document.querySelector("#canvas");
const contex = canvas.getContext("2d");

var img = new Image();
img.src = "emoji.jpg";
img.addEventListener(
  "load",
  () => {
    context.drawImage(img, 0, 0, 200, 200);
  }
);
img.src = "img.jpg";```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
  background: red;
}</code>```

<canvas id="canvas"></canvas>```

Edit:

Okey, I think my question is misunderstood. I am able to draw emoji as an image on canvas. I don't want to do that. Because I have to screenshot all the emojis and crop them before printing them on canvas, which is cumbersome. I am looking for a more efficient way.

答:
I think you need another kind of approach. First, when we use the CanvasRenderingContext2D.drawImage() method we need: i) to load an image then we will modify the image and draw it onto the canvas, therefore, we also need ii) to resize the canvas. What about if we just use the emojis provided by Unicode emoji characters.

This example will help us to use an emoji via its codepoint value. We just need to pass a hexcode through the String.fromCodePoint method. This method returns a string created by using the specified sequence of code points. Then we can print that string into the canvas as an emoji. This approach will save a lot of time chopping, resizing and rendering each emoji. Check out this short example:

const emojis = [
  0x1F600, 0x1F601, 0x1F603, 0x1F603, 0x1F604, 0x1F605, 0x1F606,
  0x1F607, 0x1F609, 0x1F60A, 0x1F642, 0x1F643, 0x1F355, 0x1F354,
]

const emoji = []
const size = 80
const factor = 2
const placeholder = document.getElementById('emojis')

for (let i = 0; i < 3; i++) {
  emoji.push({
    x: size,
    y: size,
    src: getEmoji()
  });
}

function loadCanvas(id, emo) {
  const canvas = document.createElement('canvas')
  canvas.id = id
  placeholder.appendChild(canvas)
  const ctx = canvas.getContext('2d')
  loadEmoji(canvas, ctx, emo)
}

function loadEmoji(canvas, ctx, emo) {
  // Use the intrinsic size of image in CSS pixels for the canvas element
  canvas.width = w = size * factor
  canvas.height = h = size * factor

  const fontSize = size * (factor - .5)
  const offset = Math.floor((h - fontSize) / 4)

  ctx.font = `${size * (factor - .5)}px Arial`
  ctx.textBaseline = 'middle'
  ctx.textAlign = 'center'

  emo.x = w / 2
  emo.y = h - size + offset

  ctx.fillText(emo.src, emo.x, emo.y)
}

function getEmoji() {
  const len = emojis.length
  const emos = Math.floor(Math.random() * len)

  return String.fromCodePoint(emojis[emos])
}

window.onload = function() {
  emoji.forEach((emo, i) => {
    const id = `canvas-0${i}`
    loadCanvas(id, emo)
  })
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#emojis {
  display: flex;
  justify-content: center;
  align-items: center;
}

#emojis * {
  background: red;
}</code>```

```

Note

Remember that this might not work on all browsers and the emojis will change according to the operating system where it's been displayed.

Body:
I would like to print an emoji on html canvas.

It can be done using images, but it is cumbersome. Is there a better way?

const canvas = document.querySelector("#canvas");
const contex = canvas.getContext("2d");

var img = new Image();
img.src = "emoji.jpg";
img.addEventListener(
  "load",
  () => {
    context.drawImage(img, 0, 0, 200, 200);
  }
);
img.src = "img.jpg";

#canvas {
  background: red;
}

<canvas id="canvas"></canvas>

Edit:

Okey, I think my question is misunderstood. I am able to draw emoji as an image on canvas. I don't want to do that. Because I have to screenshot all the emojis and crop them before printing them on canvas, which is cumbersome. I am looking for a more efficient way.

Body:
I think you need another kind of approach. First, when we use the CanvasRenderingContext2D.drawImage() method we need: i) to load an image then we will modify the image and draw it onto the canvas, therefore, we also need ii) to resize the canvas. What about if we just use the emojis provided by Unicode emoji characters.

This example will help us to use an emoji via its codepoint value. We just need to pass a hexcode through the String.fromCodePoint method. This method returns a string created by using the specified sequence of code points. Then we can print that string into the canvas as an emoji. This approach will save a lot of time chopping, resizing and rendering each emoji. Check out this short example:

const emojis = [
  0x1F600, 0x1F601, 0x1F603, 0x1F603, 0x1F604, 0x1F605, 0x1F606,
  0x1F607, 0x1F609, 0x1F60A, 0x1F642, 0x1F643, 0x1F355, 0x1F354,
]

const emoji = []
const size = 80
const factor = 2
const placeholder = document.getElementById('emojis')

for (let i = 0; i < 3; i++) {
  emoji.push({
    x: size,
    y: size,
    src: getEmoji()
  });
}

function loadCanvas(id, emo) {
  const canvas = document.createElement('canvas')
  canvas.id = id
  placeholder.appendChild(canvas)
  const ctx = canvas.getContext('2d')
  loadEmoji(canvas, ctx, emo)
}

function loadEmoji(canvas, ctx, emo) {
  // Use the intrinsic size of image in CSS pixels for the canvas element
  canvas.width = w = size * factor
  canvas.height = h = size * factor

  const fontSize = size * (factor - .5)
  const offset = Math.floor((h - fontSize) / 4)

  ctx.font = `${size * (factor - .5)}px Arial`
  ctx.textBaseline = 'middle'
  ctx.textAlign = 'center'

  emo.x = w / 2
  emo.y = h - size + offset

  ctx.fillText(emo.src, emo.x, emo.y)
}

function getEmoji() {
  const len = emojis.length
  const emos = Math.floor(Math.random() * len)

  return String.fromCodePoint(emojis[emos])
}

window.onload = function() {
  emoji.forEach((emo, i) => {
    const id = `canvas-0${i}`
    loadCanvas(id, emo)
  })
}

#emojis {
  display: flex;
  justify-content: center;
  align-items: center;
}

#emojis * {
  background: red;
}

<div id="emojis"></div>

Note

Remember that this might not work on all browsers and the emojis will change according to the operating system where it's been displayed.


问:
Creating Mouse Event for image labels in QT
I am working on an application using QT. I have a mainwindow on which i have an image label. I load an image to this imagelabel and now i want to draw over it. So, my question is- how do i create mouse events for this image label only without having to derive another class of QLabel and instantiating its object to my main window.

My project's due tomorrow and its the only thing i've got left to do. I'd really appreciate the help.

Sincerely, Aayush Shrestha.

答: If you do not want to create a class that inherits from QLabel to get mouse event, you need to use the installEventFilter function using the eventFilter event of one of your class.</p>