问:
Switch between icons when using FontAwesome 5.0 SVG Framework
I'm looking to be able to switch between icons in Javascript while using the new FontAwesome SVG framework.

Previously in the old WebFont method, this was achieved by toggling or changing the class on the  tag, however as these are now rendered as SVG's in the source code this no longer works.

Is there a way to do this without needing to render both SVG icons in source code and using additional classes/CSS to toggle display?

答:
Font Awesome 5.0.0 has just been released and the migration from 4.7 to 5.0 wrecked up my javascript/jquery to change a "fa-star-o" icon to "fa-star" when the user clicks on it.

I managed to fix it so I wanted to share with you these two tips:

The icon in HTML:

```<code><i class="foo fas fa-star"></i>
</code>```

1) Change icon with jQuery (from "star" to "alarm-clock" and vice versa):

```<code>var icon = $('.foo');
var icon_fa_icon = icon.attr('data-icon');

if (icon_fa_icon === "alarm-clock") {
    icon.attr('data-icon', 'star');
} else {
    icon.attr('data-icon', 'alarm-clock');
}
</code>```

2) Change icon-style with jQuery (from 'fas' to 'far'):

```<code>var icon = $('.foo');
var icon_fa_prefix = icon.attr('data-prefix');

if (icon_fa_prefix === 'fas') {
    icon.attr('data-prefix', 'far');

} else {
    icon.attr('data-prefix', 'fas');
}
</code>```

Hope that helps anyone with the same issue.

Body:
Font Awesome 5.0.0 has just been released and the migration from 4.7 to 5.0 wrecked up my javascript/jquery to change a "fa-star-o" icon to "fa-star" when the user clicks on it.

I managed to fix it so I wanted to share with you these two tips:

The icon in HTML:

<i class="foo fas fa-star"></i>

1) Change icon with jQuery (from "star" to "alarm-clock" and vice versa):

var icon = $('.foo');
var icon_fa_icon = icon.attr('data-icon');

if (icon_fa_icon === "alarm-clock") {
    icon.attr('data-icon', 'star');
} else {
    icon.attr('data-icon', 'alarm-clock');
}

2) Change icon-style with jQuery (from 'fas' to 'far'):

var icon = $('.foo');
var icon_fa_prefix = icon.attr('data-prefix');

if (icon_fa_prefix === 'fas') {
    icon.attr('data-prefix', 'far');

} else {
    icon.attr('data-prefix', 'fas');
}

Hope that helps anyone with the same issue.


来源: stackexchange

问:
empty base class optimization
Below is a simple test on ebco, I compiled it on both vc9 and g++. The outputs differ on both compilers. What I want to know is that whether the behavior of vc is conformant.

```<code>#include <iostream>

class empty
{
};

class empty_one : public empty {};
class empty_two : public empty {};

class non_empty
    : public empty_one
    , public empty_two
{
};

int main()
{
    std::cout << "sizeof(empty): " << sizeof(empty) << std::endl;
    std::cout << "sizeof(empty_one): " << sizeof(empty_one) << std::endl;
    std::cout << "sizeof(empty_two): " << sizeof(empty_two) << std::endl;
    std::cout << "sizeof(non_empty): " << sizeof(non_empty) << std::endl;

    std::cout << std::endl;

    non_empty a[2];

    void* pe10 = static_cast<empty*>(static_cast<empty_one*>(&a[0]));
    void* pe20 = static_cast<empty*>(static_cast<empty_two*>(&a[0]));
    std::cout << "address of non_empty[0]: " << &a[0] << std::endl;
    std::cout << "address of empty of empty_one: " << pe10 << std::endl;
    std::cout << "address of empty of empty_two: " << pe20 << std::endl;

    std::cout << std::endl;

    void* pe11 = static_cast<empty*>(static_cast<empty_one*>(&a[1]));
    void* pe21 = static_cast<empty*>(static_cast<empty_two*>(&a[1]));
    std::cout << "address of non_empty[1]: " << &a[1] << std::endl;
    std::cout << "address of empty of empty_one: " << pe11 << std::endl;
    std::cout << "address of empty of empty_two: " << pe21 << std::endl;
}
</code>```

On vc,

```<code>pe20 == pe11. (test1)
</code>```

Can two sub-objects of two objects have the same address? Is this conformant?

Besides,

```<code>pe20 >= &a[0] + sizeof(a[0]) (test2)
</code>```

Can the address of an sub-object passes the end of an object ?

On g++, above two tests does not hold.

EDIT: In c++0x standard draft, 1.8/6,

Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies. Two distinct objects that are neither bit-fields nor base class subobjects of zero size shall have distinct addresses

The standard requires that two objects have different address when they are neither bit-fields nor base class subobjects of zero size. But it doesn't require that two sub-objects of zero size cannot have same address. So test1 can be true ?

答:
pe10 == pe11. Can two sub-objects of two objects have the same address? Is this conformant?

Nopes!

Size of an empty class cannot be zero because in that case two objects of the same class would be having the same address which is not possible.

Similarly two sub-objects of two different objects cannot have the same address. Your compiler is not conformant. Change it!

ContentLicense: CC BY-SA 2.5

Title: empty base class optimization

Body:
Below is a simple test on ebco, I compiled it on both vc9 and g++. The outputs differ on both compilers. What I want to know is that whether the behavior of vc is conformant.

#include <iostream>

class empty
{
};

class empty_one : public empty {};
class empty_two : public empty {};

class non_empty
    : public empty_one
    , public empty_two
{
};

int main()
{
    std::cout << "sizeof(empty): " << sizeof(empty) << std::endl;
    std::cout << "sizeof(empty_one): " << sizeof(empty_one) << std::endl;
    std::cout << "sizeof(empty_two): " << sizeof(empty_two) << std::endl;
    std::cout << "sizeof(non_empty): " << sizeof(non_empty) << std::endl;

    std::cout << std::endl;

    non_empty a[2];

    void* pe10 = static_cast<empty*>(static_cast<empty_one*>(&a[0]));
    void* pe20 = static_cast<empty*>(static_cast<empty_two*>(&a[0]));
    std::cout << "address of non_empty[0]: " << &a[0] << std::endl;
    std::cout << "address of empty of empty_one: " << pe10 << std::endl;
    std::cout << "address of empty of empty_two: " << pe20 << std::endl;

    std::cout << std::endl;

    void* pe11 = static_cast<empty*>(static_cast<empty_one*>(&a[1]));
    void* pe21 = static_cast<empty*>(static_cast<empty_two*>(&a[1]));
    std::cout << "address of non_empty[1]: " << &a[1] << std::endl;
    std::cout << "address of empty of empty_one: " << pe11 << std::endl;
    std::cout << "address of empty of empty_two: " << pe21 << std::endl;
}

On vc,

pe20 == pe11. (test1)

Can two sub-objects of two objects have the same address? Is this conformant?

Besides,

pe20 >= &a[0] + sizeof(a[0]) (test2)

Can the address of an sub-object passes the end of an object ?

On g++, above two tests does not hold.

EDIT: In c++0x standard draft, 1.8/6,

Unless an object is a bit-field or a base class subobject of zero size, the address of that object is the address of the first byte it occupies. Two distinct objects that are neither bit-fields nor base class subobjects of zero size shall have distinct addresses

The standard requires that two objects have different address when they are neither bit-fields nor base class subobjects of zero size. But it doesn't require that two sub-objects of zero size cannot have same address. So test1 can be true ?


问:
Return list of values c#
I'm new in Asp and I develop all querys with stored procedures:

I have a method like this:

```<code>  Filler.Fill(new PeriodoLogic().lstConsultaParcial(tabla).ConvertAll(o => (object)o), ref this.radcmbPeriodo, "nPeriodo", "nPeriodo", true);
</code>```

lstConsultaParcial Method:

```<code> public List<object> lstConsultaParcial(object Entidad)
        {
            return new PeriodoData().lstConsultaParcial(Entidad);
        }
</code>```

View:

```<code><td><telerik:RadComboBox runat="server" ID="radcmbPeriodo" Width="200px" MarkFirstMatch="true" Filter="Contains" DropDownAutoWidth="Enabled"
                    EmptyMessage="Seleccionar" ></telerik:RadComboBox></td>
                     <td><asp:RequiredFieldValidator ID="rfv" runat="server" ErrorMessage="<b class='red'>Requerido</b>" ControlToValidate="radcmbPeriodo"></asp:RequiredFieldValidator></td>
</code>```

It fills radcombobox, consulting a simple stored procedure, it receive values, 1,2,3,4,5,6,7,8,9,10,11,12 as:

Image

as you can see it returns values 1 to 12, so I think I dont need consult stored procedure, how can I send simple a list of 1 to 12 instead call stored procedure?

答:
You can generate it like this:</p>

```<code>var nums = Enumerable.Range(1, 12).ToList();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Return list of values c#

Body:
I'm new in Asp and I develop all querys with stored procedures:

I have a method like this:

  Filler.Fill(new PeriodoLogic().lstConsultaParcial(tabla).ConvertAll(o => (object)o), ref this.radcmbPeriodo, "nPeriodo", "nPeriodo", true);

lstConsultaParcial Method:

 public List<object> lstConsultaParcial(object Entidad)
        {
            return new PeriodoData().lstConsultaParcial(Entidad);
        }

View:

<telerik:RadComboBox runat="server" ID="radcmbPeriodo" Width="200px" MarkFirstMatch="true" Filter="Contains" DropDownAutoWidth="Enabled"
                    EmptyMessage="Seleccionar" ></telerik:RadComboBox>
                     <asp:RequiredFieldValidator ID="rfv" runat="server" ErrorMessage="Requerido" ControlToValidate="radcmbPeriodo"></asp:RequiredFieldValidator>

It fills radcombobox, consulting a simple stored procedure, it receive values, 1,2,3,4,5,6,7,8,9,10,11,12 as:

Image

as you can see it returns values 1 to 12, so I think I dont need consult stored procedure, how can I send simple a list of 1 to 12 instead call stored procedure?

Body:
You can generate it like this:

var nums = Enumerable.Range(1, 12).ToList();


问:
go get: Git settings ignored
I'm using Golang and GitLab CI, and I've got a GitLab CI configuration which works perfectly for 12 projects, but not for a 13th.

The problem I have is that I'm trying to go get some private repositories, which go get tries to run over HTTPS, which is turned off.

The solution, that works in the other repos, is this:

```<code>git config --global url."git@gitlab.my.site:".insteadOf "https://gitlab.my.site/"
</code>```

However, in the runner for this one project, on the same GitLab, with the exact same config (except for the service name), this happens:

```<code>[...]
$ git config --global url."git@gitlab.my.site:".insteadOf "https://gitlab.my.site/"
$ cd ${APP_PATH}
$ go get
# cd .; git clone https://gitlab.my.site/group/project.git /go/src/gitlab.my.site/group/project
Cloning into '/go/src/gitlab.my.site/group/projects'...
GitLab: The project you were looking for could not be found.
fatal: Could not read from remote repository.
</code>```

Why is it suddenly trying to clone over HTTPS? It happens in this one project only, consistently, but works in all the other ones. The only reason I can think about is that this one project uses a lot of different repos, rather than just one or two, but I have a hard time seing that this would be the actual issue.

How can I troubleshoot this?

Thanks.

答:
Found the answer, and it's silly, and of course, my fault. I hadn't added the deploy key to the projects, of course rejecting the clones.

To fix the problem, in GitLab, go to the repository and then "Settings" > "Repository" and fold out "Deploy keys". There, make sure that the key you're trying to clone with is available and enabled.

Title: go get: Git settings ignored

Body:
I'm using Golang and GitLab CI, and I've got a GitLab CI configuration which works perfectly for 12 projects, but not for a 13th.

The problem I have is that I'm trying to go get some private repositories, which go get tries to run over HTTPS, which is turned off.

The solution, that works in the other repos, is this:

git config --global url."git@gitlab.my.site:".insteadOf "https://gitlab.my.site/"

However, in the runner for this one project, on the same GitLab, with the exact same config (except for the service name), this happens:

[...]
$ git config --global url."git@gitlab.my.site:".insteadOf "https://gitlab.my.site/"
$ cd ${APP_PATH}
$ go get
# cd .; git clone https://gitlab.my.site/group/project.git /go/src/gitlab.my.site/group/project
Cloning into '/go/src/gitlab.my.site/group/projects'...
GitLab: The project you were looking for could not be found.
fatal: Could not read from remote repository.

Why is it suddenly trying to clone over HTTPS? It happens in this one project only, consistently, but works in all the other ones. The only reason I can think about is that this one project uses a lot of different repos, rather than just one or two, but I have a hard time seing that this would be the actual issue.

How can I troubleshoot this?

Thanks.


问:
Display a table in the userform by extracting from excel sheet
I have a table like this

Now I want to display this table In the userform. How to display it in the userform. I'm thinking of selecting the entire table range and displaying it as a label, because I want the table TO BE UNEDITABLE. How to do this?. I want to write a VBA code. please help me with this.

I have tried another way as well like displaying it in a listbox, but the I couldn't get the correct output.

The vba script which I added to the userform is:

```<code>Private Sub UserForm_Initialize()
    ListBox1.List = Sheets("Overview").Range("C1:H3").CurrentRegion.Value
End Sub
</code>```

when I used the above code, the output I got is

I'm not getting the entire table in the listbox . what's the error I'm doing??

答:
you can use the simillar code:

LastColumn = Sheets("XY").Cells(1, Columns.Count).End(xlToLeft).Column

Body:
I have a table like this

Now I want to display this table In the userform. How to display it in the userform. I'm thinking of selecting the entire table range and displaying it as a label, because I want the table TO BE UNEDITABLE. How to do this?. I want to write a VBA code. please help me with this.

I have tried another way as well like displaying it in a listbox, but the I couldn't get the correct output.

The vba script which I added to the userform is:

Private Sub UserForm_Initialize()
    ListBox1.List = Sheets("Overview").Range("C1:H3").CurrentRegion.Value
End Sub

when I used the above code, the output I got is

I'm not getting the entire table in the listbox . what's the error I'm doing??


问:
Network activity monitor for a specific process on Windows
I am looking for a programming solution for this problem, it can be win32 api, or other solution.

I have a process running on Windows, I have its PID.

I want to know what kind of multicast traffic it is doing, including receive and send.

I have searched from the web and found that:

wireshark, cannot help me, because it cannot do process specific filter

netstat, cannot help me, because it cannot show the multicast group, I did netstat -aon

network monitor, cannot help me, it cannot show the process name when the traffic is multicast

Process monitor is an application which can almost do what I want, but the problem is it will output a very large log file, and I have to parse that file to find what I want.

答:
If it might help you,

Use Crowdinspect appThe screenshot of Crowdinspect running

for your purpose just run the app then click "Live/History" button on the upper left corner so the app will start to show a history of your processes network activity and then you can click "Copy all" button then paste it in a text file or Excel sheet...

[ App Description ]

This app is used mainly for security purposes for detecting Maleware, it starts an analysis to all your processes and compare to Virus Total signatures and the possibility if the PE is injected with Malicious code.

Good Luck!

Download Link


问:
Gitlab does not automatically run post-receive hook
Gitlab is hosted locally on my server. When I push a commit, the post-receive hook doesn't work. I made the owner of the hook git:git and made it executable. When I execute the file manually, it works.

答:
GitLab will execute the custom post-receive as long as it's placed in the repo's custom_hooks directory and both the directory and file are owned by git. Also, make sure your hook is expecting input on stdin, not via standard args - I say this since you mentioned running the script manually and it worked.

Unfortunately custom post-receive errors are not as easy to debug. A pre-receive error would be sent back to the client. I suggest adding lots of your own logging in your hook so you can see exactly what's happening. Put the first log directly after the shebang so you know your hook got executed.

The docs at https://docs.gitlab.com/ee/administration/custom_hooks.html#custom-git-hooks have helpful steps, if you haven't already seen them.


问:
Why does it take so long to load a row from a postgres table?
This happens to be a rails app, but I've included the SQL generated, so it should be easy to see what I'm getting at.

I have a parent ->> children relationship in a postgres database.  There are about 5M children.  I can get all the ids (primary key) of a parents children in a short time (3s).  I can fetch a single child by id in a short time (32ms).

Why does it take too long (>5m) to fetch the first child of a parent?  What is postgres doing that it can't accomplish what feels to me like the same thing in just a few seconds?

How many children are there:

```<code>[3] pry(main)> Child.count
   (8832.5ms)  SELECT COUNT(*) FROM "children"
=> 5040608
</code>```

How many children does the parent have:

```<code>[11] pry(main)> parent.children.count
   (76.0ms)  SELECT COUNT(*) FROM "children" WHERE "children"."parent_id" = $1  [["parent_id", 98107]]
=> 5213
</code>```

Get all the ids of the parent's children:

```<code>[5] pry(main)> ids = parent.children.ids; nil
   (3184.6ms)  SELECT "children"."id" FROM "children" WHERE "children"."parent_id" = $1  [["parent_id", 98107]]
</code>```

Load the first child of the parent using it's id from the list above:

```<code>[6] pry(main)> i = Child.find ids.first
  Child Load (31.7ms)  SELECT  "children".* FROM "children" WHERE "children"."id" = $1 LIMIT $2  [["id", 7368558], ["LIMIT", 1]]
</code>```

And the explanation:

```<code>                                      QUERY PLAN
---------------------------------------------------------------------------------------
 Limit  (cost=0.44..8.46 rows=1 width=1227)
   ->  Index Scan using children_pkey on children  (cost=0.44..8.46 rows=1 width=1227)
         Index Cond: (id = 7368558)
(3 rows)
</code>```

Try to skip a step - just load the first child of the parent.  Times out after 5m.  Why?

```<code>[12] pry(main)> parent.children.first
  Child Load (308569.6ms)  SELECT  "children".* FROM "children" WHERE "children"."parent_id" = $1 ORDER BY "children"."id" ASC LIMIT $2  [["parent_id", 98107], ["LIMIT", 1]]
</code>```

I'm afraid I don't know how to get the query plan on this timed out query.  I'll poke at it...

Schema definition for the child table:

```<code>create_table "children", id: :serial, force: :cascade do |t|
  t.integer "parent_id"
  t.integer "some_table_id"
  t.integer "another_table_id"
  t.date "start_date"
  t.date "end_date"
  t.integer "number_field", default: 0, null: false
  t.string "another_number_field", default: "USD", null: false
  t.integer "probably_unused", default: 0, null: false
  t.string "probably_unused_localized", default: "USD", null: false
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.bigint "sum", default: 0, null: false
  t.integer "some_count", default: 0, null: false
  t.integer "session_count", default: 0, null: false
  t.integer "duration", default: 0, null: false
  t.string "some_cycle", null: false
  t.hstore "bad_hash", default: {}, null: false
  t.index ["parent_id", "some_table_id", "some_cycle"], name: "unique_to_parent_sim_and_cycle", unique: true
  t.index ["parent_id"], name: "index_children_on_parent_id"
  t.index ["another_table_id"], name: "index_children_on_another_table_id"
  t.index ["some_table_id"], name: "index_children_on_some_table_id"
  t.index ["start_date"], name: "index_children_on_start_date"
end
</code>```

答:
Ok, a couple of things here:

In the first query you are not using an ORDER BY:

```<code>SELECT  "children".* FROM "children"
WHERE "children"."id" = $1
LIMIT $2  [["id", 7368558], ["LIMIT", 1]]
</code>```

but in the slow query you are:

```<code>SELECT  "children".* FROM "children"
WHERE "children"."parent_id" = $1
ORDER BY "children"."id" ASC
LIMIT $2  [["parent_id", 98107], ["LIMIT", 1]]
</code>```

When you add the ORDER BY it first has to sort your children before it can pick from them.  If you omit that it will speed up, especially since it appears that children.id is not indexed.

Also, notice that in the first query your WHERE is "children"."id" and in the second by "children"."parent_id" which I assume is a typo?  Depending on what indexes you have (or don't) on those two columns you will also see a speed difference.

Body:
This happens to be a rails app, but I've included the SQL generated, so it should be easy to see what I'm getting at.

I have a parent ->> children relationship in a postgres database.  There are about 5M children.  I can get all the ids (primary key) of a parents children in a short time (3s).  I can fetch a single child by id in a short time (32ms).

Why does it take too long (>5m) to fetch the first child of a parent?  What is postgres doing that it can't accomplish what feels to me like the same thing in just a few seconds?

How many children are there:

[3] pry(main)> Child.count
   (8832.5ms)  SELECT COUNT(*) FROM "children"
=> 5040608

How many children does the parent have:

[11] pry(main)> parent.children.count
   (76.0ms)  SELECT COUNT(*) FROM "children" WHERE "children"."parent_id" = $1  [["parent_id", 98107]]
=> 5213

Get all the ids of the parent's children:

[5] pry(main)> ids = parent.children.ids; nil
   (3184.6ms)  SELECT "children"."id" FROM "children" WHERE "children"."parent_id" = $1  [["parent_id", 98107]]

Load the first child of the parent using it's id from the list above:

[6] pry(main)> i = Child.find ids.first
  Child Load (31.7ms)  SELECT  "children".* FROM "children" WHERE "children"."id" = $1 LIMIT $2  [["id", 7368558], ["LIMIT", 1]]

And the explanation:

                                      QUERY PLAN
---------------------------------------------------------------------------------------
 Limit  (cost=0.44..8.46 rows=1 width=1227)
   ->  Index Scan using children_pkey on children  (cost=0.44..8.46 rows=1 width=1227)
         Index Cond: (id = 7368558)
(3 rows)

Try to skip a step - just load the first child of the parent.  Times out after 5m.  Why?

[12] pry(main)> parent.children.first
  Child Load (308569.6ms)  SELECT  "children".* FROM "children" WHERE "children"."parent_id" = $1 ORDER BY "children"."id" ASC LIMIT $2  [["parent_id", 98107], ["LIMIT", 1]]

I'm afraid I don't know how to get the query plan on this timed out query.  I'll poke at it...

Schema definition for the child table:

create_table "children", id: :serial, force: :cascade do |t|
  t.integer "parent_id"
  t.integer "some_table_id"
  t.integer "another_table_id"
  t.date "start_date"
  t.date "end_date"
  t.integer "number_field", default: 0, null: false
  t.string "another_number_field", default: "USD", null: false
  t.integer "probably_unused", default: 0, null: false
  t.string "probably_unused_localized", default: "USD", null: false
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.bigint "sum", default: 0, null: false
  t.integer "some_count", default: 0, null: false
  t.integer "session_count", default: 0, null: false
  t.integer "duration", default: 0, null: false
  t.string "some_cycle", null: false
  t.hstore "bad_hash", default: {}, null: false
  t.index ["parent_id", "some_table_id", "some_cycle"], name: "unique_to_parent_sim_and_cycle", unique: true
  t.index ["parent_id"], name: "index_children_on_parent_id"
  t.index ["another_table_id"], name: "index_children_on_another_table_id"
  t.index ["some_table_id"], name: "index_children_on_some_table_id"
  t.index ["start_date"], name: "index_children_on_start_date"
end

Body:
Ok, a couple of things here:

In the first query you are not using an ORDER BY:

SELECT  "children".* FROM "children"
WHERE "children"."id" = $1
LIMIT $2  [["id", 7368558], ["LIMIT", 1]]

but in the slow query you are:

SELECT  "children".* FROM "children"
WHERE "children"."parent_id" = $1
ORDER BY "children"."id" ASC
LIMIT $2  [["parent_id", 98107], ["LIMIT", 1]]

When you add the ORDER BY it first has to sort your children before it can pick from them.  If you omit that it will speed up, especially since it appears that children.id is not indexed.

Also, notice that in the first query your WHERE is "children"."id" and in the second by "children"."parent_id" which I assume is a typo?  Depending on what indexes you have (or don't) on those two columns you will also see a speed difference.


问:
How to INSERT INTO [temp table] FROM [Stored Procedure] and Select * FROM [temp table]
I have something like

```<code>Create TABLE #members
(
    [member_id] [bigint] NOT NULL,
    [registration_id] [int] NOT NULL,
    [date_modified] [datetime] NULL,
    [date_created] [datetime] NULL
)
INSERT #members
(
    [member_id],
    [registration_id],
    [date_modified],
    [date_created]
)
EXEC
dbo._roster_member_GetMemberContacts_byMember_id @Member_id = 1000
Select * from #members
</code>```

when I run it in query analyzer window:
There is already an object named '#members' in the database.

答: In Query Analyzer, unless you explicitly DROP the temporary table, the temporary table will exist for the life of the Query Analyzer window.

Body:
I have something like

Create TABLE #members
(
    [member_id] [bigint] NOT NULL,
    [registration_id] [int] NOT NULL,
    [date_modified] [datetime] NULL,
    [date_created] [datetime] NULL
)
INSERT #members
(
    [member_id],
    [registration_id],
    [date_modified],
    [date_created]
)
EXEC
dbo._roster_member_GetMemberContacts_byMember_id @Member_id = 1000
Select * from #members

when I run it in query analyzer window:
There is already an object named '#members' in the database.


问:
Bootstrap modal with Vanilla Javascript
I have site navigation in Component A (Navigation).
I have a working bootstrap modal in component B (BootstrapModal).
Component A is referenced in index.html to display navigation.

What I'm trying to accomplished is a way to invoke modal window from Component B when a user clicks on a nav item containing “example” CSS class.

So will need conditional statement to invoke the modal when the CSS class is present.

Note that this is using bootstrap modal and am not able to add data-target="#myModal" to component A.

答:
```<code>jQuery(document).ready(function() {
     jQuery('a.className').on('click', function(e) {
          e.preventDefault();
          jQuery('#myModal').modal('show');
     });
});
</code>```

Title: Bootstrap modal with Vanilla Javascript


问:
How do I keep internal state in a WebAssembly module written in Rust?
I want to do computations on a large set of data each frame of my web app. Only a subset of this will be used by JavaScript, so instead of sending the entire set of data back and forth between WebAssembly and JavaScript each frame, it would be nice if the data was maintained internally in my WebAssembly module.

In C, something like this works:

#include <emscripten/emscripten.h>

int state = 0;

void EMSCRIPTEN_KEEPALIVE inc() {
    state++;
}

int EMSCRIPTEN_KEEPALIVE get() {
    return state;
}
```

<p>Is the same thing possible in Rust? I tried doing it with a <code>static</code> like this:</p>

```static mut state: i32 = 0;

pub fn main() {}

#[no_mangle]
pub fn add() {
    state += 1;
}

#[no_mangle]
pub fn get() -> i32 {
    state
}
```

But it seems static variables cannot be mutable.

答:
```<code>error[E0133]: use of mutable static requires unsafe function or block
</code>```

In general, accessing mutable global variables is unsafe, which means that you can only do it in an unsafe block. With mutable global variables, it's easy to accidentally create dangling references (think of a reference to an item of a global mutable Vec), data races (if you have multiple threads – Rust doesn't care that you don't actually use threads) or otherwise invoke undefined behavior.

Global variables are usually not the best solution to a problem because it makes your software less flexible and less reusable. Instead, consider passing the state explicitly (by reference, so you don't need to copy it) to the functions that need to operate on it. This lets the calling code work with multiple independent states.

Here's an example of allocating unique state and modifying that:

```<code>type State = i32;

#[no_mangle]
pub extern fn new() -> *mut State {
    Box::into_raw(Box::new(0))
}

#[no_mangle]
pub extern fn free(state: *mut State) {
    unsafe { Box::from_raw(state) };
}

#[no_mangle]
pub extern fn add(state: *mut State) {
    unsafe { *state += 1 };
}

#[no_mangle]
pub extern fn get(state: *mut State) -> i32 {
    unsafe { *state }
}
</code>```

```<code>const fs = require('fs-extra');

fs.readFile(__dirname + '/target/wasm32-unknown-unknown/release/state.wasm')
  .then(bytes => WebAssembly.instantiate(bytes))
  .then(({ module, instance }) => {
    const { new: newFn, free, get, add } = instance.exports;

    const state1 = newFn();
    const state2 = newFn();

    add(state1);
    add(state2);
    add(state1);

    console.log(get(state1));
    console.log(get(state2));

    free(state1);
    free(state2);
});
</code>```

2
1
```

Note — This currently needs to be compiled in release mode to work. Debugging mode has some issues at the moment.

Admittedly, this is not less unsafe because you're passing raw pointers around, but it makes it clearer in the calling code that there is some mutable state being manipulated. Also note that it is now the responsibility of the caller to ensure that the state pointer is being handled correctly.

Body:
I want to do computations on a large set of data each frame of my web app. Only a subset of this will be used by JavaScript, so instead of sending the entire set of data back and forth between WebAssembly and JavaScript each frame, it would be nice if the data was maintained internally in my WebAssembly module.

In C, something like this works:

#include <emscripten/emscripten.h>

int state = 0;

void EMSCRIPTEN_KEEPALIVE inc() {
    state++;
}

int EMSCRIPTEN_KEEPALIVE get() {
    return state;
}

Is the same thing possible in Rust? I tried doing it with a static like this:

static mut state: i32 = 0;

pub fn main() {}

#[no_mangle]
pub fn add() {
    state += 1;
}

#[no_mangle]
pub fn get() -> i32 {
    state
}

But it seems static variables cannot be mutable.

Body:
error[E0133]: use of mutable static requires unsafe function or block

In general, accessing mutable global variables is unsafe, which means that you can only do it in an unsafe block. With mutable global variables, it's easy to accidentally create dangling references (think of a reference to an item of a global mutable Vec), data races (if you have multiple threads – Rust doesn't care that you don't actually use threads) or otherwise invoke undefined behavior.

Global variables are usually not the best solution to a problem because it makes your software less flexible and less reusable. Instead, consider passing the state explicitly (by reference, so you don't need to copy it) to the functions that need to operate on it. This lets the calling code work with multiple independent states.

Here's an example of allocating unique state and modifying that:

type State = i32;

#[no_mangle]
pub extern fn new() -> *mut State {
    Box::into_raw(Box::new(0))
}

#[no_mangle]
pub extern fn free(state: *mut State) {
    unsafe { Box::from_raw(state) };
}

#[no_mangle]
pub extern fn add(state: *mut State) {
    unsafe { *state += 1 };
}

#[no_mangle]
pub extern fn get(state: *mut State) -> i32 {
    unsafe { *state }
}

const fs = require('fs-extra');

fs.readFile(__dirname + '/target/wasm32-unknown-unknown/release/state.wasm')
  .then(bytes => WebAssembly.instantiate(bytes))
  .then(({ module, instance }) => {
    const { new: newFn, free, get, add } = instance.exports;

    const state1 = newFn();
    const state2 = newFn();

    add(state1);
    add(state2);
    add(state1);

    console.log(get(state1));
    console.log(get(state2));

    free(state1);
    free(state2);
});

2
1

Note — This currently needs to be compiled in release mode to work. Debugging mode has some issues at the moment.

Admittedly, this is not less unsafe because you're passing raw pointers around, but it makes it clearer in the calling code that there is some mutable state being manipulated. Also note that it is now the responsibility of the caller to ensure that the state pointer is being handled correctly.


问:
Legacy Spring 2.5.6 Migration to Spring 3.x or 4.x in WLS & Java 8
Upon being handed a legacy Spring 2.5.6 application (deployed in WLS 12.1, java 7), I've been asked to migrate it to WLS 12.2 and java 8.  I am attempting to re-build the application with a source and target of "1.8".  It builds OK, but on deployment/test, I immediately, I have an issue where Spring 2.5.6 cannot seem to find application context files on the classpath in this new environment:

org.springframework.io.support.PathMatchingResourcePatternResolver.findPathMatchingResources(PathPatchingResourcePatternResolver.java:346)
  | Resolved location pattern [classpath*:context*.xml] to resources[]

No resources are found.  In fact, no classpath directory trees are even searched. I've checked to make sure the files are present and the classpath looks right in the WLS log files.  All of this works great in java 7/WLS 12.1 but fails in java 8/WLS 12.2.

My guess is that Spring 2.5.6 is so ancient that it may not be working correctly in a java 8 environment.  Any recommendations on how to easily migrate to Spring 3.x or 4.x w/out making any (if possible) source code changes?

Pieces of Spring 2.5.6 being used:

SpringBeanAutoWiringInterceptor (overrides getBeanFactory() to use
ClassPathXmlApplicationContext)

Spring JDBC's SimpleJdbcDaoSupport

Spring Transaction annotation (@Transactional)

That's about it. Not a whole lot of Spring but enough to warrant the question: which Spring version would be the easiest to migrate to without making any (or many) source code changes?  Or is there a better way to handle this?

答:
I got this to work by upgrading to Spring 4.1.9, which contains the same classes as Spring 2.5.6 (although many of them are deprecated).

One note, however.  When making this change I had an issue with Spring 4 no longer finding/loading the context files from the CLASSPATH when using an exploded directory on the filesystem.

The issue was resolved here:
ClassLoader.getResources returning an empty Enumeration on a Weblogic/Spring application


问:
How to read a SQL file with python with proper character encoding?
Based on a few examples (here, here) I can use psycopg2 to read and hopefully run a SQL file from python (the file is 200 lines, and though runs quickly, isn't something I want to maintain in a python file).

Here is the script to read and run the file:

```<code>sql = open("sql/sm_bounds_current.sql", "r").read()

curDest.execute(sql)
</code>```

However, when I run the script, the following error is thrown:

```<code>Error: syntax error at or near "ï»¿drop"
LINE 1: ï»¿drop table dpsdata.sm_boundaries_current_dev;
</code>```

As you can see, the first line in the script is to drop a table, but I'm not sure why the extra characters are being read, and can't seem to find a solution that might set the encoding of the file when reading it.

答:
Found this post dealing with encoding and byte order marks, which is where my problem was.

The solution was to import OPEN from CODECS, which allows for the ENCODING option on OPEN:

```<code>import codecs
from codecs import open

sqlfile = "sql/sm_bounds_current.sql"
sql = open(sqlfile, mode='r', encoding='utf-8-sig').read()
curDest.execute(sql)
</code>```

Seems to work great!

Body:
Based on a few examples (here, here) I can use psycopg2 to read and hopefully run a SQL file from python (the file is 200 lines, and though runs quickly, isn't something I want to maintain in a python file).

Here is the script to read and run the file:

sql = open("sql/sm_bounds_current.sql", "r").read()

curDest.execute(sql)

However, when I run the script, the following error is thrown:

Error: syntax error at or near "ï»¿drop"
LINE 1: ï»¿drop table dpsdata.sm_boundaries_current_dev;

As you can see, the first line in the script is to drop a table, but I'm not sure why the extra characters are being read, and can't seem to find a solution that might set the encoding of the file when reading it.

Body:
Found this post dealing with encoding and byte order marks, which is where my problem was.

The solution was to import OPEN from CODECS, which allows for the ENCODING option on OPEN:

import codecs
from codecs import open

sqlfile = "sql/sm_bounds_current.sql"
sql = open(sqlfile, mode='r', encoding='utf-8-sig').read()
curDest.execute(sql)

Seems to work great!


问:
Upload images Multipart With Moya Swift Fully example
how to upload an image using multipart/form-data in Swift With Moya

my code

```<code>var multipartBody: [MultipartFormData]? {
    switch self {
    case .registerWith(let registrationObject ):
        if let profileImageData = registrationObject.profileImageData{
        return [MultipartFormData(provider: .data(profileImageData), name: "profile_picture", fileName: "\(registrationObject.phone).jpg",
            mimeType: "image/jpeg")]
        }
        return nil
    default:
        return nil
    }
}

var task: Task {
    switch self {
    case .registerWith:
        if let multipartBody = multipartBody {
            return .upload(.multipart(multipartBody))
        }else{
            return .request
        }
    default:
        return .request
    }
}
</code>```

but I need to send the imageData in body With key "profileImage"

答:
To upload an image in Multipart using Moya version 10.0.0 and above

1- Put files you want to upload  in MultipartFormData Array

```<code>// put files in MultipartFormData Arry
   var multipartBody :[Moya.MultipartFormData]?{
    switch self {
    case .registerWith(let imageData , let name ,let description  ):
        // any additional body data or body parms
        let nameDataProvider = MultipartFormData(provider: .data(name.data(using: .utf8)!), name: "name")
        let emailDataProvider = MultipartFormData(provider: .data(email.data(using: .utf8)!), name: "email")
        // image want to upload it or file as a MultipartFormData
        let imageDataProvider = Moya.MultipartFormData(provider: MultipartFormData.FormDataProvider.data(imageData), name: "avatar", fileName: "photo.jpg", mimeType: "image/jpeg")
            return [ imageDataProvider , descriptionDataProvider ]
    default:
        return []
    }
}
</code>```

2- make task type of this method is uploadMultipart

```<code>var task: Task {
    switch self {
    case .registerWith:
        // for each method multi part use its multipartBody that declared it in step one needed
        return .uploadMultipart(multipartBody!)
    default:
        guard let parameters = self.parameters else {
            return .requestPlain
        }
        return .requestParameters(parameters: parameters.values, encoding: parameters.encoding)
    }
}
</code>```

To upload an image in Multipart using Moya version 9.0.0 and below

1- Put files you want to upload  in MultipartFormData Array

```<code>// put files in MultipartFormData Arry
var multipartBody: [MultipartFormData]? {
     switch self {
          case .registerWith(let imageData , let name ,let description  ):
              return [MultipartFormData(provider: .data(imageData),
             name: "profile_picture", fileName: "fileName", mimeType: "image/jpeg")]
              default:
               return nil
       }
}
</code>```

2- Add a provider of multipartBody to request's body of the method you need it

```<code>var parameters: [String: Any]? {
     switch self {
          case .registerWith(let registrationObject ):
          var body = registrationObject.toJSON()!
          // add the file in body
          body["profile_picture"] = multipartBody?[0].provider
          return body
     }
}
</code>```

3- make task type of this method is  upload

```<code>var task: Task {
       switch self {
           case .registerWith:
              //  multipartBody that in First step
             return .upload(.multipart(multipartBody))
        }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
how to upload an image using multipart/form-data in Swift With Moya

my code

var multipartBody: [MultipartFormData]? {
    switch self {
    case .registerWith(let registrationObject ):
        if let profileImageData = registrationObject.profileImageData{
        return [MultipartFormData(provider: .data(profileImageData), name: "profile_picture", fileName: "\(registrationObject.phone).jpg",
            mimeType: "image/jpeg")]
        }
        return nil
    default:
        return nil
    }
}

var task: Task {
    switch self {
    case .registerWith:
        if let multipartBody = multipartBody {
            return .upload(.multipart(multipartBody))
        }else{
            return .request
        }
    default:
        return .request
    }
}

but I need to send the imageData in body With key "profileImage"

Body:
To upload an image in Multipart using Moya version 10.0.0 and above

1- Put files you want to upload  in MultipartFormData Array

// put files in MultipartFormData Arry
   var multipartBody :[Moya.MultipartFormData]?{
    switch self {
    case .registerWith(let imageData , let name ,let description  ):
        // any additional body data or body parms
        let nameDataProvider = MultipartFormData(provider: .data(name.data(using: .utf8)!), name: "name")
        let emailDataProvider = MultipartFormData(provider: .data(email.data(using: .utf8)!), name: "email")
        // image want to upload it or file as a MultipartFormData
        let imageDataProvider = Moya.MultipartFormData(provider: MultipartFormData.FormDataProvider.data(imageData), name: "avatar", fileName: "photo.jpg", mimeType: "image/jpeg")
            return [ imageDataProvider , descriptionDataProvider ]
    default:
        return []
    }
}

2- make task type of this method is uploadMultipart

var task: Task {
    switch self {
    case .registerWith:
        // for each method multi part use its multipartBody that declared it in step one needed
        return .uploadMultipart(multipartBody!)
    default:
        guard let parameters = self.parameters else {
            return .requestPlain
        }
        return .requestParameters(parameters: parameters.values, encoding: parameters.encoding)
    }
}

To upload an image in Multipart using Moya version 9.0.0 and below

1- Put files you want to upload  in MultipartFormData Array

// put files in MultipartFormData Arry
var multipartBody: [MultipartFormData]? {
     switch self {
          case .registerWith(let imageData , let name ,let description  ):
              return [MultipartFormData(provider: .data(imageData),
             name: "profile_picture", fileName: "fileName", mimeType: "image/jpeg")]
              default:
               return nil
       }
}

2- Add a provider of multipartBody to request's body of the method you need it

var parameters: [String: Any]? {
     switch self {
          case .registerWith(let registrationObject ):
          var body = registrationObject.toJSON()!
          // add the file in body
          body["profile_picture"] = multipartBody?[0].provider
          return body
     }
}

3- make task type of this method is  upload

var task: Task {
       switch self {
           case .registerWith:
              //  multipartBody that in First step
             return .upload(.multipart(multipartBody))
        }
}


问:
Get Network statistic for Client Apps in PowerShell
I was looking into network statistics in powershell and there are a lot of good scripts to measure:

Network traffic through a network card using counter

List all connections using for example windows built in functions

What I am looking for is the detailed info about the network traffic per client connection, so how how much traffic (bytes sent\read) is consumed by the remote client application.

Any suggestions how to start ?

答:
I think TCPView by Sysinternals should do the trick. This gives you real-time traffic on a per process level.

You would filter by the process or remote address or source port, depending on what the Client App in question is, and then you would see sent and received packets and bytes for each TCP/UDP connection.


问:
s_client and gethostbyname failure
I am working with an external company. Lets call them evilcorp.com. I want to use openssl to debug a two way SSL handshake.

https://evilcorp.com is setup to not require client authentication.

https://evilcorp.com/webservices is setup to require client authentication.

How can I specify this path in openssl. So basically this works:

```<code>openssl s_client -connect evilcorp.com:443
</code>```

But this does not work and gives me gethostbyname failure

```<code>openssl s_client -connect evilcorp.com/webservices:443
</code>```

How can I get this to work (if possible)

答:
You have a very simple error in the address.  Here's the fix:

"openssl s_client -connect evilcorp.com:443/webservice"

You had the 443 at the end - it needs to go directly after to the domain name.

Title: s_client and gethostbyname failure

Body:
I am working with an external company. Lets call them evilcorp.com. I want to use openssl to debug a two way SSL handshake.

https://evilcorp.com is setup to not require client authentication.

https://evilcorp.com/webservices is setup to require client authentication.

How can I specify this path in openssl. So basically this works:

openssl s_client -connect evilcorp.com:443

But this does not work and gives me gethostbyname failure

openssl s_client -connect evilcorp.com/webservices:443

How can I get this to work (if possible)


问:
Navigating to Commonly/Recently Used Dirs, in Terminal (Unix/OS X)
Would it be possible to save certain locations that I've used recently/commonly (like /folder/folder/folder/) so that I don't have to manually navigate through each dir between my current and destination dir?

Sort of like alt-tab, but for paths.  I'm on OS X, but perhaps this can be done using basic Unix skills?

Thanks!

答:
Either an alias (via placing it into your ~/.bashrc or ~/.profile depending on setup):

```<code>alias godocs='cd /home/me/my_docs`
</code>```

or pushd/popd as @Jeremiah suggests.

Body:
Either an alias (via placing it into your ~/.bashrc or ~/.profile depending on setup):

alias godocs='cd /home/me/my_docs`

or pushd/popd as @Jeremiah suggests.


问:
ASP.NET Attribute Routing - Url.Action not working
This code works fine:

```<code>[RouteArea("Main", AreaPrefix = "Hello")]
[RoutePrefix("{orgCode}")]
public class ResponseController : BaseController {
  [Route("Save/{formCode}/{responseId}")]
  public ActionResult Save(string formCode, int responseId, string questionCode){}
}
</code>```

and Url.Action("Save", "Response") produces, for example, /Hello/org123/Save/form/123

However, if the Route attribute is changed and another segment added:

```<code>  [Route("Save/{formCode}/{responseId}/{questionCode}")]
</code>```

then Url.Action("Save", "Response") produces an empty string.

Is there a limit to how many sections can be defined in the route?

答:
Is there a limit to how many sections can be defined in the route?

No.

But MVC only can build URLs using route values that it knows about. This can be a combination of route values that are passed to the Url.Action() method and values that are in the current request (usually passed through the current URL).

When the framework tries to determine which route to use, it selects the first route that matches all of the route values (controller, action, and anything else) and matches all of the (optional) constraints.

The route will not match if all of the conditions below are true for any of the parameters:

Have no defaults

Are not marked UrlParameter.Optional (NOTE: Optional parameters may not have any non-optional parameters to the right of them)

Are not present in the current request

Are not explicitly passed as route values to Url.Action() (or other method that calls UrlHelper to generate a URL)

Have constraint rules that do not match

In short, a route only matches if all of the required parameters are provided and constraints are satisfied.

So, apparently there is no questionCode in the current context, and since it is required to build the URL, you get an empty string. Most likely you need to pass it explicitly.

```<code>Url.Action("Save", "Response", new { questionCode = "123" })
</code>```

You should also be careful to always explicitly pass other parameters if there may be cases where they are not present in the URL.

Body:
This code works fine:

[RouteArea("Main", AreaPrefix = "Hello")]
[RoutePrefix("{orgCode}")]
public class ResponseController : BaseController {
  [Route("Save/{formCode}/{responseId}")]
  public ActionResult Save(string formCode, int responseId, string questionCode){}
}

and Url.Action("Save", "Response") produces, for example, /Hello/org123/Save/form/123

However, if the Route attribute is changed and another segment added:

  [Route("Save/{formCode}/{responseId}/{questionCode}")]

then Url.Action("Save", "Response") produces an empty string.

Is there a limit to how many sections can be defined in the route?

Body:
Is there a limit to how many sections can be defined in the route?

No.

But MVC only can build URLs using route values that it knows about. This can be a combination of route values that are passed to the Url.Action() method and values that are in the current request (usually passed through the current URL).

When the framework tries to determine which route to use, it selects the first route that matches all of the route values (controller, action, and anything else) and matches all of the (optional) constraints.

The route will not match if all of the conditions below are true for any of the parameters:

Have no defaults

Are not marked UrlParameter.Optional (NOTE: Optional parameters may not have any non-optional parameters to the right of them)

Are not present in the current request

Are not explicitly passed as route values to Url.Action() (or other method that calls UrlHelper to generate a URL)

Have constraint rules that do not match

In short, a route only matches if all of the required parameters are provided and constraints are satisfied.

So, apparently there is no questionCode in the current context, and since it is required to build the URL, you get an empty string. Most likely you need to pass it explicitly.

Url.Action("Save", "Response", new { questionCode = "123" })

You should also be careful to always explicitly pass other parameters if there may be cases where they are not present in the URL.


问:
Working with AppDomain to temporarily load assemblies
I am building a WPF tool which will analyze via reflection the assemblies of a target application.

I have so far been using Assembly.Load etc. to load the target assemblies. This is OK except that it has a couple of limitations: I want to be able to rebuild the target application and "refresh" the tool to re-analyze the newly-built assemblies. This won't currently work because the assemblies are locked upon load and not released until the tool exits. This also precludes re-loading newly built assemblies.

I believe I can create a temporary AppDomain, load the assemblies into it, do the reflection I want to do, and then unload the domain.

The problem I am having is that I can't get it to work. I've tried numerous variations and get results such as:

Loading into the current application domain, not the one I explicitly created

Error loading the requested assembly

Error loading the tool's assembly(?)

For example, following the suggestion here: Create custom AppDomain and add assemblies to it

I created a SimpleAssemblyLoader thus:

```<code>public class SimpleAssemblyLoader : MarshalByRefObject
{
    public Assembly Load(string path)
    {
        ValidatePath(path);

        return Assembly.Load(path);
    }

    public Assembly LoadFrom(string path)
    {
        ValidatePath(path);

        return Assembly.LoadFrom(path);
    }

    public Assembly UnsafeLoadFrom(string path)
    {
        ValidatePath(path);

        return Assembly.UnsafeLoadFrom(path);
    }

    private void ValidatePath(string path)
    {
        if (path == null) throw new ArgumentNullException(nameof(path));
        if (!System.IO.File.Exists(path))
            throw new ArgumentException($"path \"{path}\" does not exist");
    }
}
</code>```

... and use it in a calling method thus:

```<code>    private static AppDomain MakeDomain(string name, string targetPath, string toolPath)
    {
        var appDomain =
            AppDomain.CreateDomain(name, AppDomain.CurrentDomain.Evidence, new AppDomainSetup
                {
                    ApplicationBase = targetPath,
                    PrivateBinPath = toolPath,
                    LoaderOptimization = LoaderOptimization.MultiDomainHost
                },
                new PermissionSet(PermissionState.Unrestricted));
        return appDomain;
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="targetPath">Location of assemblies to analyze</param>
    /// <param name="toolPath">Location of this tool</param>
    /// <param name="file">Filename of assembly to analyze</param>
    /// <returns></returns>
    public string[] Test(string targetPath, string toolPath, string file)
    {
        var dom = MakeDomain("TestDomain", targetPath, toolPath);
        var assemblyLoader = (SimpleAssemblyLoader)dom.CreateInstanceAndUnwrap(typeof(SimpleAssemblyLoader).Assembly.FullName, typeof(SimpleAssemblyLoader).FullName);

        var path = Path.Combine(targetPath, file);

        var assembly = assemblyLoader.LoadFrom(path);

        var types = assembly.GetTypes();

        List<string> methods = new List<string>();

        foreach (var type in types)
        {
            foreach (var method in type.GetMethods(BindingFlags.Instance|BindingFlags.Public))
            {
                methods.Add(method.Name);
            }
        }

        AppDomain.Unload(dom);

        return methods.ToArray();
    }
</code>```

... the tool application launches, but it fails to instantiate the SimpleAssemblyLoader, reporting a "File not found" exception associated with the tool's assembly - apparently trying to load the tool's assembly into the new domain(?).

What am I doing wrong, and how do I fix it?

答:
There are several problems here. First, as stated in documentation, PrivateBinPath should be relative to ApplicationBase - otherwise it's ignored. This is what happens in your case. Since it is ignored and ApplicationBase refers to directory with target application and not tool directory - app domain has no idea from where to load your SimpleAssemblyLoader. To fix this, just use toolPath as ApplicationBase:

```<code>private static AppDomain MakeDomain(string name, string toolPath)
{
    var appDomain =
        AppDomain.CreateDomain(name, AppDomain.CurrentDomain.Evidence, new AppDomainSetup
            {
                ApplicationBase = toolPath,
                LoaderOptimization = LoaderOptimization.MultiDomainHost
            },
            new PermissionSet(PermissionState.Unrestricted));
    return appDomain;
}
</code>```

Or just

```<code>private static AppDomain MakeDomain(string name) {
    var appDomain =
        AppDomain.CreateDomain(name, AppDomain.CurrentDomain.Evidence, new AppDomainSetup {
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
                LoaderOptimization = LoaderOptimization.MultiDomainHost
            },
            new PermissionSet(PermissionState.Unrestricted));
    return appDomain;
}
</code>```

Second problem

```<code>public Assembly LoadFrom(string path) {
    ValidatePath(path);
    return Assembly.LoadFrom(path);
}
</code>```

When you call

```<code>var assembly = assemblyLoader.LoadFrom(path);
</code>```

Assembly is loaded in child app domain BUT when you return this assembly as a result (to var assembly) - current app domain will load it too (well - will try to load and fail, because it has no idea where this assembly is located). You should not return assembly like this, because it will either get loaded in both current and child domains (bad) or just fail to load in current domain. Instead - put your whole method into MarshalByRefObject to execute it completely in child domain and return results:

```<code>public class WpfInspector : MarshalByRefObject {
    public string[] Inspect(string path) {
        ValidatePath(path);
        var assembly = Assembly.LoadFrom(path);

        var types = assembly.GetTypes();

        List<string> methods = new List<string>();

        foreach (var type in types) {
            foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)) {
                methods.Add(method.Name);
            }
        }
        return methods.ToArray();
    }

    private void ValidatePath(string path) {
        if (path == null) throw new ArgumentNullException(nameof(path));
        if (!System.IO.File.Exists(path))
            throw new ArgumentException($"path \"{path}\" does not exist");
    }
}
</code>```

Then

```<code>var dom = MakeDomain("TestDomain", toolPath);
var inspector = (WpfInspector)dom.CreateInstanceAndUnwrap(typeof(WpfInspector).Assembly.FullName, typeof(WpfInspector).FullName);

var path = Path.Combine(targetPath, file);
var methods = inspector.Inspect(path);
AppDomain.Unload(dom);
</code>```

Body:
I am building a WPF tool which will analyze via reflection the assemblies of a target application.

I have so far been using Assembly.Load etc. to load the target assemblies. This is OK except that it has a couple of limitations: I want to be able to rebuild the target application and "refresh" the tool to re-analyze the newly-built assemblies. This won't currently work because the assemblies are locked upon load and not released until the tool exits. This also precludes re-loading newly built assemblies.

I believe I can create a temporary AppDomain, load the assemblies into it, do the reflection I want to do, and then unload the domain.

The problem I am having is that I can't get it to work. I've tried numerous variations and get results such as:

Loading into the current application domain, not the one I explicitly created

Error loading the requested assembly

Error loading the tool's assembly(?)

For example, following the suggestion here: Create custom AppDomain and add assemblies to it

I created a SimpleAssemblyLoader thus:

public class SimpleAssemblyLoader : MarshalByRefObject
{
    public Assembly Load(string path)
    {
        ValidatePath(path);

        return Assembly.Load(path);
    }

    public Assembly LoadFrom(string path)
    {
        ValidatePath(path);

        return Assembly.LoadFrom(path);
    }

    public Assembly UnsafeLoadFrom(string path)
    {
        ValidatePath(path);

        return Assembly.UnsafeLoadFrom(path);
    }

    private void ValidatePath(string path)
    {
        if (path == null) throw new ArgumentNullException(nameof(path));
        if (!System.IO.File.Exists(path))
            throw new ArgumentException($"path \"{path}\" does not exist");
    }
}

... and use it in a calling method thus:

    private static AppDomain MakeDomain(string name, string targetPath, string toolPath)
    {
        var appDomain =
            AppDomain.CreateDomain(name, AppDomain.CurrentDomain.Evidence, new AppDomainSetup
                {
                    ApplicationBase = targetPath,
                    PrivateBinPath = toolPath,
                    LoaderOptimization = LoaderOptimization.MultiDomainHost
                },
                new PermissionSet(PermissionState.Unrestricted));
        return appDomain;
    }

    ///
    ///
    ///
    /// <param name="targetPath">Location of assemblies to analyze</param>
    /// <param name="toolPath">Location of this tool</param>
    /// <param name="file">Filename of assembly to analyze</param>
    /// <returns></returns>
    public string[] Test(string targetPath, string toolPath, string file)
    {
        var dom = MakeDomain("TestDomain", targetPath, toolPath);
        var assemblyLoader = (SimpleAssemblyLoader)dom.CreateInstanceAndUnwrap(typeof(SimpleAssemblyLoader).Assembly.FullName, typeof(SimpleAssemblyLoader).FullName);

        var path = Path.Combine(targetPath, file);

        var assembly = assemblyLoader.LoadFrom(path);

        var types = assembly.GetTypes();

        List<string> methods = new List<string>();

        foreach (var type in types)
        {
            foreach (var method in type.GetMethods(BindingFlags.Instance|BindingFlags.Public))
            {
                methods.Add(method.Name);
            }
        }

        AppDomain.Unload(dom);

        return methods.ToArray();
    }

... the tool application launches, but it fails to instantiate the SimpleAssemblyLoader, reporting a "File not found" exception associated with the tool's assembly - apparently trying to load the tool's assembly into the new domain(?).

What am I doing wrong, and how do I fix it?

Body:
There are several problems here. First, as stated in documentation, PrivateBinPath should be relative to ApplicationBase - otherwise it's ignored. This is what happens in your case. Since it is ignored and ApplicationBase refers to directory with target application and not tool directory - app domain has no idea from where to load your SimpleAssemblyLoader. To fix this, just use toolPath as ApplicationBase:

private static AppDomain MakeDomain(string name, string toolPath)
{
    var appDomain =
        AppDomain.CreateDomain(name, AppDomain.CurrentDomain.Evidence, new AppDomainSetup
            {
                ApplicationBase = toolPath,
                LoaderOptimization = LoaderOptimization.MultiDomainHost
            },
            new PermissionSet(PermissionState.Unrestricted));
    return appDomain;
}

Or just

private static AppDomain MakeDomain(string name) {
    var appDomain =
        AppDomain.CreateDomain(name, AppDomain.CurrentDomain.Evidence, new AppDomainSetup {
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
                LoaderOptimization = LoaderOptimization.MultiDomainHost
            },
            new PermissionSet(PermissionState.Unrestricted));
    return appDomain;
}

Second problem

public Assembly LoadFrom(string path) {
    ValidatePath(path);
    return Assembly.LoadFrom(path);
}

When you call

var assembly = assemblyLoader.LoadFrom(path);

Assembly is loaded in child app domain BUT when you return this assembly as a result (to var assembly) - current app domain will load it too (well - will try to load and fail, because it has no idea where this assembly is located). You should not return assembly like this, because it will either get loaded in both current and child domains (bad) or just fail to load in current domain. Instead - put your whole method into MarshalByRefObject to execute it completely in child domain and return results:

public class WpfInspector : MarshalByRefObject {
    public string[] Inspect(string path) {
        ValidatePath(path);
        var assembly = Assembly.LoadFrom(path);

        var types = assembly.GetTypes();

        List<string> methods = new List<string>();

        foreach (var type in types) {
            foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public)) {
                methods.Add(method.Name);
            }
        }
        return methods.ToArray();
    }

    private void ValidatePath(string path) {
        if (path == null) throw new ArgumentNullException(nameof(path));
        if (!System.IO.File.Exists(path))
            throw new ArgumentException($"path \"{path}\" does not exist");
    }
}

Then

var dom = MakeDomain("TestDomain", toolPath);
var inspector = (WpfInspector)dom.CreateInstanceAndUnwrap(typeof(WpfInspector).Assembly.FullName, typeof(WpfInspector).FullName);

var path = Path.Combine(targetPath, file);
var methods = inspector.Inspect(path);
AppDomain.Unload(dom);


问:
(42,18): error CS1525: Unexpected symbol `(', expecting `,', `;', or `='
I am making a game in unity, where i will make a time system. But im getting this error "(42,18): error CS1525: Unexpected symbol (', expecting,', ;', or='" and i can not find out why i doesnt want work.

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

public class TimeManager : MonoBehaviour {

public int seconds = 0;
public int minutes = 0;
public int hours = 0;
public int days = 0;
public int year = 0;
public Text TotalTimePlayed;

void Start(){
    StartCoroutine(time());
}

void Update(){
    TotalTimePlayed = year + " Y" + days + " D" + hours + " H" + minutes + " M" + seconds + " S";
}

private void timeAdd(){
    seconds += 1;
    if(seconds >= 60){
        minutes = 1;
    }

    if(minutes >= 60){
        hours = 1;
    }

    if(hours >= 24){
        days = 1;
    }

    if(days >= 365){
        year = 1;
    }

    IEnumerator time(){
        while (true){
            timeAdd();
            yield return new WaitForSendons(1);
        }
    }
}
}
</code>```

What would work better/at all? Right now im getting the error "(42,18): error CS1525: Unexpected symbol (', expecting,', ;', or='"

Thanks for your help.

答: There is one unnecessary } at the end of your file. Simply remove it!

Body:
I am making a game in unity, where i will make a time system. But im getting this error "(42,18): error CS1525: Unexpected symbol (', expecting,', ;', or='" and i can not find out why i doesnt want work.

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

public class TimeManager : MonoBehaviour {

public int seconds = 0;
public int minutes = 0;
public int hours = 0;
public int days = 0;
public int year = 0;
public Text TotalTimePlayed;

void Start(){
    StartCoroutine(time());
}

void Update(){
    TotalTimePlayed = year + " Y" + days + " D" + hours + " H" + minutes + " M" + seconds + " S";
}

private void timeAdd(){
    seconds += 1;
    if(seconds >= 60){
        minutes = 1;
    }

    if(minutes >= 60){
        hours = 1;
    }

    if(hours >= 24){
        days = 1;
    }

    if(days >= 365){
        year = 1;
    }

    IEnumerator time(){
        while (true){
            timeAdd();
            yield return new WaitForSendons(1);
        }
    }
}
}

What would work better/at all? Right now im getting the error "(42,18): error CS1525: Unexpected symbol (', expecting,', ;', or='"

Thanks for your help.


问:
Regular expression to extract contents between two specific words using python(or nltk)
I'm trying to build a class and take each poem as an object, which has attributes of the title (followed by "POEM:"), author and content.
I extracted title and author and put in a list.
However, I don't know how to extract the content, and put into a list.

I have a txt file which includes many poems.
Sample poems are:

```<code>POEM: lala AUTHOR: la
aaaaaaaaaaaaaa,
aaaaaaaaa,
akaaaaaaaa

POEM: alal AUTHOR: al
llllllllllll,
llllll.

llllllll,
lllllllllll

POEM: lal AUTHOR:as
sssssssss,
sssssss,
sssssss
</code>```

This is what I did

```<code>import re
f=open('Poems.txt', 'r')
data=f.read().replace('\n','')
re.findall(r"^POEM:.*?(?=POEM)",data)
</code>```

I want to get all the poems as separate strings in a list, but I can only get the first poem.

```<code>'POEM: lala AUTHOR: la, aaaaaaaaaaaaaa, aaaaaaaaa, akaaaaaaaa'
</code>```

答:
Much easier solution without using regular expressions, explained.

Explanation line by line

first you open the file

```<code>f=open('Poems.txt', 'r').read()
</code>```

you will get your poems list with the expected output that you show in the last part of your question

```<code>poems_list = ["POEM" + s for s in f.split("POEM")]
</code>```

we delete the first element because it is empty, due to the split function

```<code>poems_list.pop(0)
</code>```

Up to here, poems_list would give us what the other user is posting in his question. But if you actually want to parse the data, which I guess it was your intention by using regex, you can just go ahead and to the following:

We go over each poem in the poem list to analyse the data that they contain

```<code>for poem in poems_list:
</code>```

first we split it with the poem keyword, remember that you must leave a space between the semicolon and the poem name, or it wont work (without modifying the code)

```<code>    i1 = poem.split('POEM: ')
</code>```

now we split it by the author, again leaving the trailing spaces as appropriate. We take i1 second element because the first one was the poem name, the rest of the contend is now stored in the second element of the list.

```<code>    i2 = i1[1].split(' AUTHOR: ')
</code>```

again we will take the second element in the list to get the remaining part of the text. We split it by the new line because the poem begins after line break after stating its author

```<code>    i3 = i2[1].split('\n')
</code>```

we save the values that we have obtained

```<code>    poem_name = i2[0]
    poem_author = i3[0]
    poem_content = i3[1]
</code>```

And now its your turn to process the data how you wish. I recommend you to store it in a dictionary.

The full code

All the code without explanation (for copy-paste):

```<code>f=open('Poems.txt', 'r').read()
poems_list = ["POEM" + s for s in f.split("POEM")]
poems_list.pop(0)

for poem in poems_list:

    i1 = poem.split('POEM: ')
    i2 = i1[1].split(' AUTHOR: ')
    i3 = i2[1].split('\n')

    poem_name = i2[0]
    poem_author = i3[0]
    poem_content = i3[1]
</code>```

Further thoughts

I do not recommend you to store your data like that in that file. It is very inefficient, and tiny modifications would cause great problems in the functioning of the code, which would require great modifications. Using databases, pandas, csv format or even pickle to store dictionaries is much more recommended, or at least format it a little bit better.

Body:
I'm trying to build a class and take each poem as an object, which has attributes of the title (followed by "POEM:"), author and content.
I extracted title and author and put in a list.
However, I don't know how to extract the content, and put into a list.

I have a txt file which includes many poems.
Sample poems are:

POEM: lala AUTHOR: la
aaaaaaaaaaaaaa,
aaaaaaaaa,
akaaaaaaaa

POEM: alal AUTHOR: al
llllllllllll,
llllll.

llllllll,
lllllllllll

POEM: lal AUTHOR:as
sssssssss,
sssssss,
sssssss

This is what I did

import re
f=open('Poems.txt', 'r')
data=f.read().replace('\n','')
re.findall(r"^POEM:.*?(?=POEM)",data)

I want to get all the poems as separate strings in a list, but I can only get the first poem.

'POEM: lala AUTHOR: la, aaaaaaaaaaaaaa, aaaaaaaaa, akaaaaaaaa'

Body:
Much easier solution without using regular expressions, explained.

Explanation line by line

first you open the file

f=open('Poems.txt', 'r').read()

you will get your poems list with the expected output that you show in the last part of your question

poems_list = ["POEM" + s for s in f.split("POEM")]

we delete the first element because it is empty, due to the split function

poems_list.pop(0)

Up to here, poems_list would give us what the other user is posting in his question. But if you actually want to parse the data, which I guess it was your intention by using regex, you can just go ahead and to the following:

We go over each poem in the poem list to analyse the data that they contain

for poem in poems_list:

first we split it with the poem keyword, remember that you must leave a space between the semicolon and the poem name, or it wont work (without modifying the code)

    i1 = poem.split('POEM: ')

now we split it by the author, again leaving the trailing spaces as appropriate. We take i1 second element because the first one was the poem name, the rest of the contend is now stored in the second element of the list.

    i2 = i1[1].split(' AUTHOR: ')

again we will take the second element in the list to get the remaining part of the text. We split it by the new line because the poem begins after line break after stating its author

    i3 = i2[1].split('\n')

we save the values that we have obtained

    poem_name = i2[0]
    poem_author = i3[0]
    poem_content = i3[1]

And now its your turn to process the data how you wish. I recommend you to store it in a dictionary.

The full code

All the code without explanation (for copy-paste):

f=open('Poems.txt', 'r').read()
poems_list = ["POEM" + s for s in f.split("POEM")]
poems_list.pop(0)

for poem in poems_list:

    i1 = poem.split('POEM: ')
    i2 = i1[1].split(' AUTHOR: ')
    i3 = i2[1].split('\n')

    poem_name = i2[0]
    poem_author = i3[0]
    poem_content = i3[1]

Further thoughts

I do not recommend you to store your data like that in that file. It is very inefficient, and tiny modifications would cause great problems in the functioning of the code, which would require great modifications. Using databases, pandas, csv format or even pickle to store dictionaries is much more recommended, or at least format it a little bit better.


问:
How to change value in list for calendar?
The goal of my function is to book a slot in that calendar corresponding to the parameters day and time  - booking is done by changing the value in the calendar to “X” (to indicate that day/time is booked). Here is the code I have so far:

```<code>def find_index(val, seq):
    for index in range(len(seq)):
        place = seq[index]
        if place == val:
            return index
        else:
            return int("-1")

def init_nested_list(size_outer, size_inner):
    cal = []
    for outer_index in range(size_outer):
        nested_list = []
        for inner_index in range(size_inner):
            nested_list.append("-")
        cal.append(nested_list)
    return cal

def book_slot(cal,days_labels, times_labels, day, time):
    pos1 = find_index(day, days_labels)
    desired_day = cal[pos1]
    pos2 = find_index(time, times_labels)
    desired_time = desired_day[pos2]
    if desired_day == "X":
        print("We are sorry - that time is not available. Please try again.")
    else:
        print("Appointment is booked.")

days_labels = ["Wednesday","Thursday","Friday"]
times_labels = ["9","10","11"]
cal = init_nested_list(len(days_labels), len(times_labels))
print("before" , cal)
book_slot(cal, days_labels, times_labels, "Friday", "10")
print("after" , cal)
</code>```

This is the output I'm getting:

```<code>before [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
Appointment is booked.
after [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
</code>```

This is the output I should be getting:

```<code>before [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
Appointment is booked.
after [['-', '-', '-'], ['-', '-', '-'], ['-', 'X', '-']]
We are sorry - that time is not available. Please try again.
</code>```

As you can see, the correct output books the second element in the nested list(Friday at 10), but for my code it is not. I know desired_day is the day in cal that the user wants to book, but I'm just unsure of how to properly obtain that, and assign it to the string "X" when it is booked by the user. I also know that there is a coding error in the book_slot function that is causing this, but once again, I'm just unsure what it is...help please?

答:
This will work. See the Change # notes in the code

```<code>def find_index(val, seq):
    return seq.index(val) #Change 1

def init_nested_list(size_outer, size_inner):
    cal = []
    for outer_index in range(size_outer):
        nested_list = []
        for inner_index in range(size_inner):
            nested_list.append("-")
        cal.append(nested_list)
    return cal

def book_slot(cal, days_labels, times_labels, day, time):
    pos1 = find_index(day, days_labels)
    desired_day = cal[pos1]
    pos2 = find_index(time, times_labels)
    if desired_day[pos2] is "X": # Change 2
        print("We are sorry - that time is not available. Please try again.")
    else:
        print("Appointment is booked.")
        desired_day[pos2] = "X" # Change 3

days_labels = ["Wednesday", "Thursday", "Friday"]
times_labels = ["9", "10", "11"]
cal = init_nested_list(len(days_labels), len(times_labels))
print("before", cal)
book_slot(cal, days_labels, times_labels, "Friday", "10")
book_slot(cal, days_labels, times_labels, "Friday", "10") # Change 4: Need to do a booking twice to make it fail :-)
print("after", cal)
</code>```

will output:

```<code>('before', [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])
Appointment is booked.
('after', [['-', '-', '-'], ['-', '-', '-'], ['-', 'X', '-']])
We are sorry - that time is not available. Please try again.
</code>```

Body:
The goal of my function is to book a slot in that calendar corresponding to the parameters day and time  - booking is done by changing the value in the calendar to “X” (to indicate that day/time is booked). Here is the code I have so far:

def find_index(val, seq):
    for index in range(len(seq)):
        place = seq[index]
        if place == val:
            return index
        else:
            return int("-1")

def init_nested_list(size_outer, size_inner):
    cal = []
    for outer_index in range(size_outer):
        nested_list = []
        for inner_index in range(size_inner):
            nested_list.append("-")
        cal.append(nested_list)
    return cal

def book_slot(cal,days_labels, times_labels, day, time):
    pos1 = find_index(day, days_labels)
    desired_day = cal[pos1]
    pos2 = find_index(time, times_labels)
    desired_time = desired_day[pos2]
    if desired_day == "X":
        print("We are sorry - that time is not available. Please try again.")
    else:
        print("Appointment is booked.")

days_labels = ["Wednesday","Thursday","Friday"]
times_labels = ["9","10","11"]
cal = init_nested_list(len(days_labels), len(times_labels))
print("before" , cal)
book_slot(cal, days_labels, times_labels, "Friday", "10")
print("after" , cal)

This is the output I'm getting:

before [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
Appointment is booked.
after [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]

This is the output I should be getting:

before [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']]
Appointment is booked.
after [['-', '-', '-'], ['-', '-', '-'], ['-', 'X', '-']]
We are sorry - that time is not available. Please try again.

As you can see, the correct output books the second element in the nested list(Friday at 10), but for my code it is not. I know desired_day is the day in cal that the user wants to book, but I'm just unsure of how to properly obtain that, and assign it to the string "X" when it is booked by the user. I also know that there is a coding error in the book_slot function that is causing this, but once again, I'm just unsure what it is...help please?

Body:
This will work. See the Change # notes in the code

def find_index(val, seq):
    return seq.index(val) #Change 1

def init_nested_list(size_outer, size_inner):
    cal = []
    for outer_index in range(size_outer):
        nested_list = []
        for inner_index in range(size_inner):
            nested_list.append("-")
        cal.append(nested_list)
    return cal

def book_slot(cal, days_labels, times_labels, day, time):
    pos1 = find_index(day, days_labels)
    desired_day = cal[pos1]
    pos2 = find_index(time, times_labels)
    if desired_day[pos2] is "X": # Change 2
        print("We are sorry - that time is not available. Please try again.")
    else:
        print("Appointment is booked.")
        desired_day[pos2] = "X" # Change 3

days_labels = ["Wednesday", "Thursday", "Friday"]
times_labels = ["9", "10", "11"]
cal = init_nested_list(len(days_labels), len(times_labels))
print("before", cal)
book_slot(cal, days_labels, times_labels, "Friday", "10")
book_slot(cal, days_labels, times_labels, "Friday", "10") # Change 4: Need to do a booking twice to make it fail :-)
print("after", cal)

will output:

('before', [['-', '-', '-'], ['-', '-', '-'], ['-', '-', '-']])
Appointment is booked.
('after', [['-', '-', '-'], ['-', '-', '-'], ['-', 'X', '-']])
We are sorry - that time is not available. Please try again.


问:
R- Calculating the minimum distance between points and lines
I have a large set of polygon shapefiles of parcels (for 50+ counties) and I would like to loop through each of them and calculate the distance from the center of each parcel to the nearest railroad, stored nationally in a line shapefile.

I had come up with two different measures to do this: point2Line from the geospheres package and gDistance from rgeos package. Each had different problems for me.

For the point2line, my code looked something like this:

```<code>rail_projection <-spTransform(rail_file,CRS(proj4string(parcels)) #project to same CRS
rail_crop<-crop(rail_projection,extent(parcels)) #crop to extent of parcels
centroids<-gCentroid(parcels,byid=T) # take centroid of parcel polygons.
m<-gDistance(rail_crop,centroids,byid=T)
</code>```

but this spits out the following warning:

```<code>Warning messages:
1: In RGEOSDistanceFunc(rail_crop, centroids, byid=T, "rgeos_distance") :
Spatial object 1 is not projected; GEOS expects planar coordinates
2: In RGEOSDistanceFunc(rail_crop, centroids, byid=T, "rgeos_distance") :
Spatial object 2 is not projected; GEOS expects planar coordinates
</code>```

It also gives me a nparcels X (I think number of line matrix) of numbers for which I'm not quite sure of the measurement. I'd like the measurement in KM or miles or something.

The second method, using dist2line looks like this:
    dist<-dist2Line(centroids,rail_crop)
It works fine, but the only problem is it takes very long! For looping through 60 or so counties, it may take a couple days. Additionally, I'd rather not have to crop the rail shapefile in case the closest railroad is in another county. Running the code with the entire shapefile takes wayyy longer.

So what I'm essentially look for is a way to get nearest distance from points to a line shapefile in a fairly efficient way that spits out the distance in km or miles, or something similarly interpretable. If this can be done with gDistance in a way that doesn't have these errors then great! If there's a way to speed it up from dist2Line, or some other method, that'd also be great. If you also have any thoughts on how to crop the rail shapefile with some buffer, I'd also appreciate it. (I can't post code since the parcel data is proprietary)

I'm still a beginner with spatial stuff so sorry if I have trouble following or if this has been answered before. I've looked around and haven't found solutions I'm able to make work here.

Thanks!

Edit with Data

So I guess I figured out where my warning message was coming from using this. I was using a 3d coordinate system rather than a planar one. I've run some code with a shapefile I downloaded from the internet for a county in Wisconsin, and gDistance spits out a matrix with the number of parcels x the number of lines with distances (I presume) from each parcel to each rail line. Does anyone know in what measurement these distances come out? How can I convert them to KM or miles? Also is there a "preferred" planar projection I should be using. Furthermore, any thoughts on how to crop the shapefile with some buffer would be greatly appreciated. Files/code can be found here

答:
I would recommend looking into the Universal Transverse Mercator system. I don't know if it's the best projected coordinate system, but it's the one I see used most frequently in my field (as long as the study area is not too large).

Once you find the UTM zone specific to your region, you can use sp::spTransform() to reproject your shapefiles such that gDistance() can return your distances in either kilometers or meters.

Here's the proj4string for a UTM zone that covers Kenya: +proj=utm +zone=37 +south +ellps=WGS84 +datum=WGS84 +units=m +no_defs. As you can see, the units here are in meters (+units=m).

It might be worth your time to look into the relatively new sf package, which simplifies and standardizes functions and classes for spatial data. Here's a brief intro you can check out: http://strimas.com/r/tidy-sf/. The analogous functions from that package are st_transform() and st_distance().

Body:
I have a large set of polygon shapefiles of parcels (for 50+ counties) and I would like to loop through each of them and calculate the distance from the center of each parcel to the nearest railroad, stored nationally in a line shapefile.

I had come up with two different measures to do this: point2Line from the geospheres package and gDistance from rgeos package. Each had different problems for me.

For the point2line, my code looked something like this:

rail_projection <-spTransform(rail_file,CRS(proj4string(parcels)) #project to same CRS
rail_crop<-crop(rail_projection,extent(parcels)) #crop to extent of parcels
centroids<-gCentroid(parcels,byid=T) # take centroid of parcel polygons.
m<-gDistance(rail_crop,centroids,byid=T)

but this spits out the following warning:

Warning messages:
1: In RGEOSDistanceFunc(rail_crop, centroids, byid=T, "rgeos_distance") :
Spatial object 1 is not projected; GEOS expects planar coordinates
2: In RGEOSDistanceFunc(rail_crop, centroids, byid=T, "rgeos_distance") :
Spatial object 2 is not projected; GEOS expects planar coordinates

It also gives me a nparcels X (I think number of line matrix) of numbers for which I'm not quite sure of the measurement. I'd like the measurement in KM or miles or something.

The second method, using dist2line looks like this:
    dist<-dist2Line(centroids,rail_crop)
It works fine, but the only problem is it takes very long! For looping through 60 or so counties, it may take a couple days. Additionally, I'd rather not have to crop the rail shapefile in case the closest railroad is in another county. Running the code with the entire shapefile takes wayyy longer.

So what I'm essentially look for is a way to get nearest distance from points to a line shapefile in a fairly efficient way that spits out the distance in km or miles, or something similarly interpretable. If this can be done with gDistance in a way that doesn't have these errors then great! If there's a way to speed it up from dist2Line, or some other method, that'd also be great. If you also have any thoughts on how to crop the rail shapefile with some buffer, I'd also appreciate it. (I can't post code since the parcel data is proprietary)

I'm still a beginner with spatial stuff so sorry if I have trouble following or if this has been answered before. I've looked around and haven't found solutions I'm able to make work here.

Thanks!

Edit with Data

So I guess I figured out where my warning message was coming from using this. I was using a 3d coordinate system rather than a planar one. I've run some code with a shapefile I downloaded from the internet for a county in Wisconsin, and gDistance spits out a matrix with the number of parcels x the number of lines with distances (I presume) from each parcel to each rail line. Does anyone know in what measurement these distances come out? How can I convert them to KM or miles? Also is there a "preferred" planar projection I should be using. Furthermore, any thoughts on how to crop the shapefile with some buffer would be greatly appreciated. Files/code can be found here


问:
How to combine two RDD[String]s index-wise?
I'm working with Spark RDDs and created two idential length arrays, one is the hour of tweet, and the other is the text of a tweet.  I'm looking to combine these into one data structure (perhaps a tuple?) that I can filter by the hour and text of tweets, but I'm struggling after combining on how to perform this.

```<code>scala> val split_time = split_date.map(line => line.split(":")).map(word =>
(word(0)))
split_time: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[28] at map
at <console>:31

scala> split_time.take(10)
res8: Array[String] = Array(17, 17, 17, 17, 17, 17, 17, 17, 17, 17)

scala> val split_text = text.map(line => line.split(":")).map(word =>
(word(1).toLowerCase))
split_text: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[19] at map at <console>:29

scala> split_text.take(10)
res0: Array[String] = Array("add @joemontana to this pic and you've got
something #nfl https, "are you looking for photo editor, "#colts frank gore
needs 27 rushing yards to pass jerome bettis and 49 yards to pass ladainian
tomlinson to move int… https, "rt @nflstreamfree,.....

# combine into tuple
val tweet_tuple = (split_time, split_text)
</code>```

For example, I want to get all tweets for hour 17 with the word "colts" mentioned:

```<code>tweet_tuple.filter(tup => tup._1 == 17 && tup._2.toString.matches("colts"))

<console>:40: error: value filter is not a member of (org.apache.spark.rdd.RDD[String], org.apache.spark.rdd.RDD[String])
          tweet_tuple.map(line => line._1 == 17 && line._2.toString.matches("colts"))
</code>```

答:
The answer by Ramesh Maharjan can work only under very specific assumptions:

Both RDDs have the same number of partitions.

Corresponding partitions have the same number of elements.

This trivial for ParallelCollectionRDD but it is hard or impossible to get in general.

It is much better, but costlier, to join:

```<code>split_time.zipWithIndex.map(_.swap).join(
  split_text.zipWithIndex.map(_.swap)
).values
</code>```

or:

```<code>val split_time_with_index = split_time.zipWithIndex.map(_.swap)
val split_text_with_index = split_text.zipWithIndex.map(_.swap)

val partitioner = new org.apache.spark.RangePartitioner(
  split_time.getNumPartitions, split_time
)

split_time.join(split_text, partitioner)
</code>```

Body:
I'm working with Spark RDDs and created two idential length arrays, one is the hour of tweet, and the other is the text of a tweet.  I'm looking to combine these into one data structure (perhaps a tuple?) that I can filter by the hour and text of tweets, but I'm struggling after combining on how to perform this.

scala> val split_time = split_date.map(line => line.split(":")).map(word =>
(word(0)))
split_time: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[28] at map
at <console>:31

scala> split_time.take(10)
res8: Array[String] = Array(17, 17, 17, 17, 17, 17, 17, 17, 17, 17)

scala> val split_text = text.map(line => line.split(":")).map(word =>
(word(1).toLowerCase))
split_text: org.apache.spark.rdd.RDD[String] = MapPartitionsRDD[19] at map at <console>:29

scala> split_text.take(10)
res0: Array[String] = Array("add @joemontana to this pic and you've got
something #nfl https, "are you looking for photo editor, "#colts frank gore
needs 27 rushing yards to pass jerome bettis and 49 yards to pass ladainian
tomlinson to move int… https, "rt @nflstreamfree,.....

# combine into tuple
val tweet_tuple = (split_time, split_text)

For example, I want to get all tweets for hour 17 with the word "colts" mentioned:

tweet_tuple.filter(tup => tup._1 == 17 && tup._2.toString.matches("colts"))

<console>:40: error: value filter is not a member of (org.apache.spark.rdd.RDD[String], org.apache.spark.rdd.RDD[String])
          tweet_tuple.map(line => line._1 == 17 && line._2.toString.matches("colts"))

Body:
The answer by Ramesh Maharjan can work only under very specific assumptions:

Both RDDs have the same number of partitions.

Corresponding partitions have the same number of elements.

This trivial for ParallelCollectionRDD but it is hard or impossible to get in general.

It is much better, but costlier, to join:

split_time.zipWithIndex.map(_.swap).join(
  split_text.zipWithIndex.map(_.swap)
).values

or:

val split_time_with_index = split_time.zipWithIndex.map(_.swap)
val split_text_with_index = split_text.zipWithIndex.map(_.swap)

val partitioner = new org.apache.spark.RangePartitioner(
  split_time.getNumPartitions, split_time
)

split_time.join(split_text, partitioner)


问:
How to read properties file in Unix script where key is in another user input variable
I have below property file in same directory.

cancellation.properties

Content:

```<code>TestData=My Name
</code>```

My unix script is abc.sh

Content:

```<code>#!/bin/ksh
. ./cancellation.properties

echo  "Please enter data to read"

read data

echo $data
</code>```

While running I give the value TestData.

I am getting output as "TestData".

But I want output as "My Name".  What changes needs to be done here because key will be entered by user.

答:
If there's the possibility that you might want other configuration data read from a file, I'd suggest treating your properties file like a config rather than an embedded script, and putting your data into a structure dedicated to storing configuration. Like an array. Something like this might work:

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

declare -A canprop=()

while IFS='=' read -r key value; do
    [[ $key = #* ]] && continue      # handle comments
    canprop[$key]="$value"
done < cancellation.properties

printf '> %s\n' "${canprop[TestData]}"
</code>```

Note that this particular solution doesn't work if $key is repeated within the configuration file -- the last key read will "win". But it saves you the hassle of putting everything into your "main" namespace.

Body:
I have below property file in same directory.

cancellation.properties

Content:

TestData=My Name

My unix script is abc.sh

Content:

#!/bin/ksh
. ./cancellation.properties

echo  "Please enter data to read"

read data

echo $data

While running I give the value TestData.

I am getting output as "TestData".

But I want output as "My Name".  What changes needs to be done here because key will be entered by user.

Body:
If there's the possibility that you might want other configuration data read from a file, I'd suggest treating your properties file like a config rather than an embedded script, and putting your data into a structure dedicated to storing configuration. Like an array. Something like this might work:

#!/usr/bin/env bash

declare -A canprop=()

while IFS='=' read -r key value; do
    [[ $key = #* ]] && continue      # handle comments
    canprop[$key]="$value"
done < cancellation.properties

printf '> %s\n' "${canprop[TestData]}"

Note that this particular solution doesn't work if $key is repeated within the configuration file -- the last key read will "win". But it saves you the hassle of putting everything into your "main" namespace.


问:
64/32-bit division on a processor with 32/16-bit division
My processor, a small 16-bit microcontroller with no FPU and integer math only has 16/16 division and 32/16 division which both take 18 cycles. At the moment I'm using a very slow software routine (~7,500 cycles) to do 64/32 division. Is there any way to use these division engines to calculate a 64/32 division? Similar to how I'm already using the 16x16 multiplier and adder to calculate 32x32 multiplies? I'm using C but can work with any general explanation on how it can be done... I'm hoping to target <200 cycles (if it's at all possible.)</p>

答:
Starting point would be:
D. Knuth, The Art of Computer Programming Vol.2, Section 4.3.1, Algorithm D

But I suppose you may need to optimize the algorithm.


问:
what does the symbol [:] mean in Go?
I found this in some code:

```<code>h := s.Hash(tx)
sig, err := crypto.Sign(h[:], prv)
</code>```

What does [:] mean ?
If this is the full slice of the array, why not to pass the array itself? What kind of coding style is this, I wonder...

答:
In go, Arrays and Slices are slightly different and cannot be used interchangeably; however, you can make a slice from an array easily using the [:] operator.

This article explains in detail - Go Slices: Usage and Internals.

See also the Slice Expressions section of The Go Programming Language Specification.

In a nutshell, the [:] operator allows you to create a slice from an array, optionally using start and end bounds.  For example:

```<code>a := [4]int{1, 2, 3, 4} // "a" has type [4]int (array of 4 ints)
x := a[:]   // "x" has type []int (slice of ints) and length 4
y := a[:2]  // "y" has type []int, length 2, values {1, 2}
z := a[2:]  // "z" has type []int, length 2, values {3, 4}
m := a[1:3] // "m" has type []int, length 2, values {2, 3}
</code>```

Presumably the reason for this distinction is for an extra measure of type safety. That is, length is a formal part of an array type (e.g. [4]int is an array of four ints and a different size is a different type) whereas slices can have any length, including zero. So if you want the safety of a known-length sequence then use an Array, otherwise use a Slice for convenience.

Title: what does the symbol [:] mean in Go?

Body:
I found this in some code:

h := s.Hash(tx)
sig, err := crypto.Sign(h[:], prv)

What does [:] mean ?
If this is the full slice of the array, why not to pass the array itself? What kind of coding style is this, I wonder...

Body:
In go, Arrays and Slices are slightly different and cannot be used interchangeably; however, you can make a slice from an array easily using the [:] operator.

This article explains in detail - Go Slices: Usage and Internals.

See also the Slice Expressions section of The Go Programming Language Specification.

In a nutshell, the [:] operator allows you to create a slice from an array, optionally using start and end bounds.  For example:

a := [4]int{1, 2, 3, 4} // "a" has type [4]int (array of 4 ints)
x := a[:]   // "x" has type []int (slice of ints) and length 4
y := a[:2]  // "y" has type []int, length 2, values {1, 2}
z := a[2:]  // "z" has type []int, length 2, values {3, 4}
m := a[1:3] // "m" has type []int, length 2, values {2, 3}

Presumably the reason for this distinction is for an extra measure of type safety. That is, length is a formal part of an array type (e.g. [4]int is an array of four ints and a different size is a different type) whereas slices can have any length, including zero. So if you want the safety of a known-length sequence then use an Array, otherwise use a Slice for convenience.