问:
How to create a Test scenario for a code block with Test not running check
I am trying to test a section of code which runs only when the condition is [ If(!test.isRunning()) ] is true,

If I make a certain test case to run this code it won't go inside this if block as the condition is false.

```<code>if(!Test.isRunningTest()){
//do something
}
</code>```

答:
You can't test that code. That's the explicit intention of the !Test.isRunningTest(). Code guarded by that condition will never run in an Apex unit test context.

For that reason, this structure is and should be used rarely in Apex code, and only for those code elements that absolutely cannot be executed in a unit test. One example is the addFields() call sometimes used in a Visualforce controller's constructor, which is not allowed in test context.

It is very rare to see more than one line of code guarded this way, and it makes me suspect the code is badly architected. With only a single line of code guarded, you can still get code coverage to 100% by writing the if and its body on a single line:

```<code>if (!Test.isRunningTest()) controller.addFields(new List<String> { 'Name' });
</code>```

So long as the if test is run in a test, the entire line is counted as covered.

It used to be common to use this pattern to block callouts. In modern code, Mocks should be used instead.

Body:
I am trying to test a section of code which runs only when the condition is [ If(!test.isRunning()) ] is true,

If I make a certain test case to run this code it won't go inside this if block as the condition is false.

if(!Test.isRunningTest()){
//do something
}

Body:
You can't test that code. That's the explicit intention of the !Test.isRunningTest(). Code guarded by that condition will never run in an Apex unit test context.

For that reason, this structure is and should be used rarely in Apex code, and only for those code elements that absolutely cannot be executed in a unit test. One example is the addFields() call sometimes used in a Visualforce controller's constructor, which is not allowed in test context.

It is very rare to see more than one line of code guarded this way, and it makes me suspect the code is badly architected. With only a single line of code guarded, you can still get code coverage to 100% by writing the if and its body on a single line:

if (!Test.isRunningTest()) controller.addFields(new List<String> { 'Name' });

So long as the if test is run in a test, the entire line is counted as covered.

It used to be common to use this pattern to block callouts. In modern code, Mocks should be used instead.


来源: stackexchange

问:
ActiveRecord: doing a join with unscoped doesn't skip the default_scope
I am having some issues when trying to skip a default_scope when doing an ActiveRecord join.

Even though the codebase is quite large, I am just showing the basics as I think it shows pretty well what the problem is:

class Client
  belongs_to :company
end

class Company
  default_scope { where(version_id: nil) }
end
```

<p>I am building a complex report, so I need to join multiple tables and filter on them. However, I can't successfully skip the default scope when fetching <code>Client</code>s.</p>

<pre class="lang-rb prettyprint-override"><code>Client.joins(:company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL
</code>```

As you can see that is automatically including the Company default_scope. So I tried this:

Company.unscoped { Client.joins(:company) }.to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL
```

<p>Again, I got the same result, even when using <code>unscoped</code> with the block.</p>

<p>Then I decided to add a new association to the model, with the <code>unscoped</code> scope:</p>

<pre class="lang-rb prettyprint-override"><code>class Client
  belongs_to :company
  belongs_to :unscoped_company, -> { unscoped }, foreign_key: :company_id, class_name: "Company"
end
</code>```

Having added that, I gave another try:

Client.joins(:unscoped_company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL
```

And still the scoped is being applied.

Do you know how can I successfully join both tables without applying that default_scope?
Removing that default_scope is not an option as It is a big application and changing that will require too much time.

Rails v4.2.7

Ruby v2.2.3

答:
I did some research without finding any straight solution.

Here a couple of workarounds. I cannot say if they're going to work in your chained joins.

First basic, do it manually:
```<code>Client.joins("INNER JOINS companies ON companies.id = clients.company_id").to_sql
</code>```

Other option define a `CompanyUnscoped` class which inherits from `Company`, removing the default_scope:
```<code>class CompanyUnscoped < Company

  self.default_scopes = []

end
</code>```

Don't forget to add this line to Client class:

```<code>belongs_to :company_unscoped, foreign_key: :company_id
</code>```

Then you should be able to call

```<code>Client.joins(:company_unscoped)
#=> SELECT "clients".* FROM "clients" INNER JOIN "companies" ON "companies"."id" = "clients"."company_id"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am having some issues when trying to skip a default_scope when doing an ActiveRecord join.

Even though the codebase is quite large, I am just showing the basics as I think it shows pretty well what the problem is:

class Client
  belongs_to :company
end

class Company
  default_scope { where(version_id: nil) }
end

I am building a complex report, so I need to join multiple tables and filter on them. However, I can't successfully skip the default scope when fetching Clients.

Client.joins(:company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL

As you can see that is automatically including the Company default_scope. So I tried this:

Company.unscoped { Client.joins(:company) }.to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL

Again, I got the same result, even when using unscoped with the block.

Then I decided to add a new association to the model, with the unscoped scope:

class Client
  belongs_to :company
  belongs_to :unscoped_company, -> { unscoped }, foreign_key: :company_id, class_name: "Company"
end

Having added that, I gave another try:

Client.joins(:unscoped_company).to_sql
# SELECT clients.* FROM clients INNER JOIN companies
# ON companies.id = clients.company_id AND companies.version_id IS NULL

And still the scoped is being applied.

Do you know how can I successfully join both tables without applying that default_scope?
Removing that default_scope is not an option as It is a big application and changing that will require too much time.

Rails v4.2.7

Ruby v2.2.3

Body:
I did some research without finding any straight solution.

Here a couple of workarounds. I cannot say if they're going to work in your chained joins.

First basic, do it manually:

Client.joins("INNER JOINS companies ON companies.id = clients.company_id").to_sql

Other option define a `CompanyUnscoped` class which inherits from `Company`, removing the default_scope:

class CompanyUnscoped < Company

  self.default_scopes = []

end

Don't forget to add this line to Client class:

belongs_to :company_unscoped, foreign_key: :company_id

Then you should be able to call

Client.joins(:company_unscoped)
#=> SELECT "clients".* FROM "clients" INNER JOIN "companies" ON "companies"."id" = "clients"."company_id"


问:
parseInt() - String to Integer and back in PHP
Im trying to reverse engineering some Javascript code and recode it in PHP.
There is a String which is "converted" with parseInt(String, 36) to an Integer.
I need a posibility to convert the integer back to the secret String in PHP, without knowing the secret string.

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510```
</div>
</div>
</p>

<p>How i can do that in PHP?
<code>115802171408044510</code> back to <code>0vo8fz4kvy03</code></p>

<p>This interger contains some informations:</p>

```decode="115802171408044510";
storeID = decode.substr(0, 4); // 1158
posID = decode.substr(12, 2); // 04
orderID = decode.substr(14, 2); // 45
day = decode.substr(6, 2); // 17
month = decode.substr(4, 2); // 02
hour = decode.substr(8, 2); // 14
minutes = decode.substr(10, 2); // 08
```

I would like to edit this values above and convert this back to a "secretCode" String.
They are doing exactly this somehow server-side.

答:
The Number.prototype.toString() method receives an optional argument, which lets you set the base of the result.

So all you need to do is (+decode).toString(36).

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510
console.log((+decode).toString(36));```

Notice that I'm converting your decode to a number. This is needed because you converted the result of parseInt directly to a string, so you never actually hold the number.

Body:
Im trying to reverse engineering some Javascript code and recode it in PHP.
There is a String which is "converted" with parseInt(String, 36) to an Integer.
I need a posibility to convert the integer back to the secret String in PHP, without knowing the secret string.

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510

How i can do that in PHP?
115802171408044510 back to 0vo8fz4kvy03

This interger contains some informations:

decode="115802171408044510";
storeID = decode.substr(0, 4); // 1158
posID = decode.substr(12, 2); // 04
orderID = decode.substr(14, 2); // 45
day = decode.substr(6, 2); // 17
month = decode.substr(4, 2); // 02
hour = decode.substr(8, 2); // 14
minutes = decode.substr(10, 2); // 08

I would like to edit this values above and convert this back to a "secretCode" String.
They are doing exactly this somehow server-side.

Body:
The Number.prototype.toString() method receives an optional argument, which lets you set the base of the result.

So all you need to do is (+decode).toString(36).

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510
console.log((+decode).toString(36));

Notice that I'm converting your decode to a number. This is needed because you converted the result of parseInt directly to a string, so you never actually hold the number.


问:
Is Java overkill for news websites?
A client of mine wants a news website designed in Java, and I told him that Java is overkill for that kind of website. I suggested to him that there are dozens of CMS that we can customize for him, as well as other programming languages that are better suited for websites but he insisted.

Is Java overkill for news websites?

答: have him take a look at http://en.wikipedia.org/wiki/Magnolia_(CMS) (http://www.magnolia-cms.com/home.html) - it is written in java. the community edition is open source</p>

OwnerDisplayName: Ainab

ContentLicense: CC BY-SA 2.5

Title: Is Java overkill for news websites?

LastEditorDisplayName: LFSR Consulting

OwnerDisplayName: Ray Tayek


问:
Trying to reformat a list of dictionaries in Python
I have a column called genres in my dataframe where each row consists of a list of dictionaries objects. For example, here is the first row:

```<code>[{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]
</code>```

What I would like to do is reformat this so that each row only contains the information found in the "name" key, preferably dumped into a list.

So for example, the output for the first row would resemble the following:

```<code>["Action", "Adventure", "Fantasy", "Science Fiction"]
</code>```

Any help would be immensely appreciated.

答:
You can also use itemgetter using 'name' as the key

```<code>import operator

lst = [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"},
       {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]

answer = list(map(operator.itemgetter('name'), lst))

# ["Action", "Adventure", "Fantasy", "Science Fiction"]
</code>```

Body:
I have a column called genres in my dataframe where each row consists of a list of dictionaries objects. For example, here is the first row:

[{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]

What I would like to do is reformat this so that each row only contains the information found in the "name" key, preferably dumped into a list.

So for example, the output for the first row would resemble the following:

["Action", "Adventure", "Fantasy", "Science Fiction"]

Any help would be immensely appreciated.

Body:
You can also use itemgetter using 'name' as the key

import operator

lst = [{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"},
       {"id": 14, "name": "Fantasy"}, {"id": 878, "name": "Science Fiction"}]

answer = list(map(operator.itemgetter('name'), lst))

# ["Action", "Adventure", "Fantasy", "Science Fiction"]


问:
How to get the exit status a loop in bash
I know how to check the status of the previously executed command using $?, and we can make that status using exit command. But for the loops in bash are always returning a status 0 and is there any way I can break the loop with some status. </p>

```<code>#!/bin/bash
while true
do
        if [ -f "/test" ] ; then
                break ### Here I would like to exit with some status
        fi

done
echo $?  ## Here I want to check the status.
</code>```

答:
I would like to submit an alternative solution which is simpler and I think more elegant:</p>

```<code>(while true
 do
    if [ -f "test" ] ; then
        break
    fi
 done

Of course of this is part of a script then you could user return 1 instead of exit 1
 exit 1
)
echo "Exit status is: $?"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know how to check the status of the previously executed command using $?, and we can make that status using exit command. But for the loops in bash are always returning a status 0 and is there any way I can break the loop with some status.

#!/bin/bash
while true
do
        if [ -f "/test" ] ; then
                break ### Here I would like to exit with some status
        fi

done
echo $?  ## Here I want to check the status.

Body:
I would like to submit an alternative solution which is simpler and I think more elegant:

(while true
 do
    if [ -f "test" ] ; then
        break
    fi
 done

Of course of this is part of a script then you could user return 1 instead of exit 1
 exit 1
)
echo "Exit status is: $?"


问:
Can I stop a record from being inserted in the object trigger without letting the user know in Salesforce?
In order to stay backward compatible with existing customers, I have to be able to handle attachments and files in Salesforce.  Basically, some customers need to be able to insert files and other attachments in our community portal.  I would like to do this without the user knowing which one they are inserting.

The easiest way I can think to do this is to leave the current apex pages used for uploading alone.  Then in the Attachment trigger, I can determine (using a flag somewhere) if the attachment should stay or be changed to a File (ContentVersion).  If it should be a file; then I would create all the necessary records, ContentVersion, ContentDocumentLink and then skip the attachment.  However, I can't figure out a way to stop the attachments from inserting without generating an error to the user.  I really don't want to allow the attachment to insert and then delete it in the after insert trigger because it seems like a lot of overhead.

Using the trigger means I can handle multiple places where community users can add files.  Otherwise, I will have to make changes in all locations to determine which type of record to insert.

So after all of that, the main question is whether or not there is a way to stop inserting records without the addError method?

答:
No, there isn't. You cannot stop the insertion of the Attachment record in a trigger without forcing a rollback of the entire transaction or savepoint region, which would include any DML your Attachment trigger performed to add Content objects instead.

The only options that I see are to perform the deletion as you describe, or to change the front-end code to directly insert Content records instead of Attachments.


问:
UIApplication not launching to make phone call
I have this code:

```<code>NSString *telURL = [NSString stringWithFormat:@"tel:1-%@",((UIButton*) sender).titleLabel.text];
telURL = [telURL stringByReplacingOccurrencesOfString:@"\n" withString:@""];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:telURL]];
</code>```

But it does not launch the dialer application to make a phone call.

I've checked the string telURL and its contents are : "tel:[REDACTED]", which to my understanding is what it needs to be.

Any ideas?

EDIT:
In the event that it matters I've just been running this on the simulator. I won't have a physical device for a few days. (And from the answers  below apparently it does matter)

答:
That matters. There is no telephone app in the simulator. And trying to open a telephone URL on a device (iPod touch, simulator) that doesn't have the app, just silently fails.

Your formatting is correct though.

Body:
I have this code:

NSString *telURL = [NSString stringWithFormat:@"tel:1-%@",((UIButton*) sender).titleLabel.text];
telURL = [telURL stringByReplacingOccurrencesOfString:@"\n" withString:@""];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:telURL]];

But it does not launch the dialer application to make a phone call.

I've checked the string telURL and its contents are : "tel:[REDACTED]", which to my understanding is what it needs to be.

Any ideas?

EDIT:
In the event that it matters I've just been running this on the simulator. I won't have a physical device for a few days. (And from the answers  below apparently it does matter)


问:
Pyplot savefig memory leak - alternative?
Is there an alternative to pyplot to plot some graphs in python?
I'm having some memory leaks which make my project impossible to complete.

I've tried the usual recommended "solutions" of using plt.close(), plt.clf(), etc with and without a single fig = plt.figure() object, but it did absolutely nothing.

I also tried using a thread but it's the first time I used it in python so I may have done it wrong :

```<code>import gc
import psutil
from threading import Thread
import matplotlib.pyplot as plt

def plot_func():
    plt.plot([1,2,3], [1,2,3])
    plt.savefig('plot_test.png')
    plt.close()

gc.collect()
init_mem_tot = psutil.Process().memory_info().rss / 2**20
for i in range(20):
    init_mem = psutil.Process().memory_info().rss / 2**20
    thread = Thread(target=plot_func)
    thread.start()
    thread.join()

    # tried with and without those the two following lines
    del thread
    gc.collect()
    new_mem = psutil.Process().memory_info().rss / 2**20
    print("Memory : %f, previous : %f. (%f difference)" % (new_mem, init_mem, init_mem - new_mem))

final_mem = psutil.Process().memory_info().rss / 2**20
print("Final : %f, Init : %f. (%f tot difference)" % (final_mem, init_mem_tot, final_mem - init_mem_tot))
</code>```

Result gives :

```<code>Memory : 107.441406, previous : 102.687500. (4.753906 difference)
Memory : 108.578125, previous : 107.445312. (1.132812 difference)
Memory : 109.941406, previous : 108.578125. (1.363281 difference)
Memory : 111.281250, previous : 109.941406. (1.339844 difference)
Memory : 112.195312, previous : 111.281250. (0.914062 difference)
Memory : 113.281250, previous : 112.195312. (1.085938 difference)
Memory : 114.535156, previous : 113.281250. (1.253906 difference)
Memory : 115.640625, previous : 114.535156. (1.105469 difference)
Memory : 116.707031, previous : 115.640625. (1.066406 difference)
Memory : 117.843750, previous : 116.707031. (1.136719 difference)
Memory : 119.175781, previous : 117.843750. (1.332031 difference)
Memory : 120.367188, previous : 119.175781. (1.191406 difference)
Memory : 121.507812, previous : 120.367188. (1.140625 difference)
Memory : 122.660156, previous : 121.507812. (1.152344 difference)
Memory : 123.937500, previous : 122.660156. (1.277344 difference)
Memory : 124.828125, previous : 123.937500. (0.890625 difference)
Memory : 126.406250, previous : 124.832031. (1.574219 difference)
Memory : 127.671875, previous : 126.406250. (1.265625 difference)
Memory : 128.585938, previous : 127.671875. (0.914062 difference)
Memory : 129.699219, previous : 128.589844. (1.109375 difference)
Final : 129.699219, Init : 102.687500. (27.011719 tot difference)
</code>```

If those are all the solutions, is there an other way for me to plot stuff?

答:
If not using threading and not using pyplot, only a very slight memory consumption increase is observed. I do not know where it comes from, but it might be bearable.

```<code>import gc
import psutil
from matplotlib.figure import Figure

def plot_func():
    fig = Figure()
    ax = fig.add_subplot()
    ax.plot([1,2,3], [1,2,3])
    fig.savefig('plot_test.png')

init_mem_tot = psutil.Process().memory_info().rss / 2**20
for i in range(100):
    init_mem = psutil.Process().memory_info().rss / 2**20

    plot_func()
    gc.collect()
    new_mem = psutil.Process().memory_info().rss / 2**20
    print("Memory : %f, previous : %f. (%f difference)" % (new_mem, init_mem, init_mem - new_mem))

final_mem = psutil.Process().memory_info().rss / 2**20
print("Final : %f, Init : %f. (%f tot difference)" % (final_mem, init_mem_tot, final_mem - init_mem_tot))
</code>```

Output: (Note how 95% are by the very first plot)

```<code>Memory : 48.113281, previous : 44.140625. (-3.972656 difference)
Memory : 48.152344, previous : 48.113281. (-0.039062 difference)
Memory : 48.195312, previous : 48.152344. (-0.042969 difference)
Memory : 48.199219, previous : 48.195312. (-0.003906 difference)
Memory : 48.199219, previous : 48.199219. (0.000000 difference)
Memory : 48.199219, previous : 48.199219. (0.000000 difference)
Memory : 48.257812, previous : 48.199219. (-0.058594 difference)
Memory : 48.257812, previous : 48.257812. (0.000000 difference)
Memory : 48.265625, previous : 48.257812. (-0.007812 difference)
Memory : 48.265625, previous : 48.265625. (0.000000 difference)
Memory : 48.269531, previous : 48.265625. (-0.003906 difference)
Memory : 48.273438, previous : 48.269531. (-0.003906 difference)
Memory : 48.273438, previous : 48.273438. (0.000000 difference)
Memory : 48.273438, previous : 48.273438. (0.000000 difference)
Memory : 48.273438, previous : 48.273438. (0.000000 difference)
Memory : 48.273438, previous : 48.273438. (0.000000 difference)
Memory : 48.281250, previous : 48.273438. (-0.007812 difference)
Memory : 48.285156, previous : 48.281250. (-0.003906 difference)
Memory : 48.285156, previous : 48.285156. (0.000000 difference)
Memory : 48.312500, previous : 48.285156. (-0.027344 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.316406, previous : 48.312500. (-0.003906 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.320312, previous : 48.316406. (-0.003906 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Final : 48.320312, Init : 44.140625. (4.179688 tot difference)
</code>```

Body:
Is there an alternative to pyplot to plot some graphs in python?
I'm having some memory leaks which make my project impossible to complete.

I've tried the usual recommended "solutions" of using plt.close(), plt.clf(), etc with and without a single fig = plt.figure() object, but it did absolutely nothing.

I also tried using a thread but it's the first time I used it in python so I may have done it wrong :

import gc
import psutil
from threading import Thread
import matplotlib.pyplot as plt

def plot_func():
    plt.plot([1,2,3], [1,2,3])
    plt.savefig('plot_test.png')
    plt.close()

gc.collect()
init_mem_tot = psutil.Process().memory_info().rss / 2**20
for i in range(20):
    init_mem = psutil.Process().memory_info().rss / 2**20
    thread = Thread(target=plot_func)
    thread.start()
    thread.join()

    # tried with and without those the two following lines
    del thread
    gc.collect()
    new_mem = psutil.Process().memory_info().rss / 2**20
    print("Memory : %f, previous : %f. (%f difference)" % (new_mem, init_mem, init_mem - new_mem))

final_mem = psutil.Process().memory_info().rss / 2**20
print("Final : %f, Init : %f. (%f tot difference)" % (final_mem, init_mem_tot, final_mem - init_mem_tot))

Result gives :

Memory : 107.441406, previous : 102.687500. (4.753906 difference)
Memory : 108.578125, previous : 107.445312. (1.132812 difference)
Memory : 109.941406, previous : 108.578125. (1.363281 difference)
Memory : 111.281250, previous : 109.941406. (1.339844 difference)
Memory : 112.195312, previous : 111.281250. (0.914062 difference)
Memory : 113.281250, previous : 112.195312. (1.085938 difference)
Memory : 114.535156, previous : 113.281250. (1.253906 difference)
Memory : 115.640625, previous : 114.535156. (1.105469 difference)
Memory : 116.707031, previous : 115.640625. (1.066406 difference)
Memory : 117.843750, previous : 116.707031. (1.136719 difference)
Memory : 119.175781, previous : 117.843750. (1.332031 difference)
Memory : 120.367188, previous : 119.175781. (1.191406 difference)
Memory : 121.507812, previous : 120.367188. (1.140625 difference)
Memory : 122.660156, previous : 121.507812. (1.152344 difference)
Memory : 123.937500, previous : 122.660156. (1.277344 difference)
Memory : 124.828125, previous : 123.937500. (0.890625 difference)
Memory : 126.406250, previous : 124.832031. (1.574219 difference)
Memory : 127.671875, previous : 126.406250. (1.265625 difference)
Memory : 128.585938, previous : 127.671875. (0.914062 difference)
Memory : 129.699219, previous : 128.589844. (1.109375 difference)
Final : 129.699219, Init : 102.687500. (27.011719 tot difference)

If those are all the solutions, is there an other way for me to plot stuff?

Body:
If not using threading and not using pyplot, only a very slight memory consumption increase is observed. I do not know where it comes from, but it might be bearable.

import gc
import psutil
from matplotlib.figure import Figure

def plot_func():
    fig = Figure()
    ax = fig.add_subplot()
    ax.plot([1,2,3], [1,2,3])
    fig.savefig('plot_test.png')

init_mem_tot = psutil.Process().memory_info().rss / 2**20
for i in range(100):
    init_mem = psutil.Process().memory_info().rss / 2**20

    plot_func()
    gc.collect()
    new_mem = psutil.Process().memory_info().rss / 2**20
    print("Memory : %f, previous : %f. (%f difference)" % (new_mem, init_mem, init_mem - new_mem))

final_mem = psutil.Process().memory_info().rss / 2**20
print("Final : %f, Init : %f. (%f tot difference)" % (final_mem, init_mem_tot, final_mem - init_mem_tot))

Output: (Note how 95% are by the very first plot)

Memory : 48.113281, previous : 44.140625. (-3.972656 difference)
Memory : 48.152344, previous : 48.113281. (-0.039062 difference)
Memory : 48.195312, previous : 48.152344. (-0.042969 difference)
Memory : 48.199219, previous : 48.195312. (-0.003906 difference)
Memory : 48.199219, previous : 48.199219. (0.000000 difference)
Memory : 48.199219, previous : 48.199219. (0.000000 difference)
Memory : 48.257812, previous : 48.199219. (-0.058594 difference)
Memory : 48.257812, previous : 48.257812. (0.000000 difference)
Memory : 48.265625, previous : 48.257812. (-0.007812 difference)
Memory : 48.265625, previous : 48.265625. (0.000000 difference)
Memory : 48.269531, previous : 48.265625. (-0.003906 difference)
Memory : 48.273438, previous : 48.269531. (-0.003906 difference)
Memory : 48.273438, previous : 48.273438. (0.000000 difference)
Memory : 48.273438, previous : 48.273438. (0.000000 difference)
Memory : 48.273438, previous : 48.273438. (0.000000 difference)
Memory : 48.273438, previous : 48.273438. (0.000000 difference)
Memory : 48.281250, previous : 48.273438. (-0.007812 difference)
Memory : 48.285156, previous : 48.281250. (-0.003906 difference)
Memory : 48.285156, previous : 48.285156. (0.000000 difference)
Memory : 48.312500, previous : 48.285156. (-0.027344 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.312500, previous : 48.312500. (0.000000 difference)
Memory : 48.316406, previous : 48.312500. (-0.003906 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.316406, previous : 48.316406. (0.000000 difference)
Memory : 48.320312, previous : 48.316406. (-0.003906 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Memory : 48.320312, previous : 48.320312. (0.000000 difference)
Final : 48.320312, Init : 44.140625. (4.179688 tot difference)


问:
Embed two online websites in one HTML page
I am trying to embed two websites in one page like YouTube and Google using div tags and the links in between the div tags....is there any way this could work?</p>

答:
Their is three types which I define to add any other website in your webpage.

Note: But nowadays Google, Facebook, and other lots of websites do not allow you to load their website or webpage on your Webpage for some security issues.

<object data="https://www.example.com" width="400" height="300" type="text/html">
    Alternative Content
</object>

<embed src="https://www.example.com" width=200 height=200 onerror="alert('URL invalid !!');" />```

Body:
Their is three types which I define to add any other website in your webpage.

Note: But nowadays Google, Facebook, and other lots of websites do not allow you to load their website or webpage on your Webpage for some security issues.

<iframe src="https://www.example.com" height="200" width="300"></iframe>

<object data="https://www.example.com" width="400" height="300" type="text/html">
    Alternative Content
</object>

<embed src="https://www.example.com" width=200 height=200 onerror="alert('URL invalid !!');" />


问:
multiple condition grouping and counting pandas
I am going to try to express this problem in the most general way possible. Suppose I have a pandas dataframe with multiple columns ['A', 'B', 'C', 'D'].

For each unique value in 'A', I need to get the following ratio: the number of times 'B' == x, divided by the number of times 'B' == y, when 'C' == q OR p...

I'm sorry, but I don't know how to express this pythonically.

Sample data:

df = pd.DataFrame({'A': ['foo', 'zar', 'zar', 'bar', 'foo', 'bar','foo', 'bar', 'tar', 'foo', 'foo'],
'B': ['one', 'two', 'four', 'three', 'one', 'two', 'three','two', 'two', 'one', 'three'],
'C': np.random.randn(11),'D': np.random.randn(11)})`
```

I need something like the following. For each unique value i in 'A', I need the ratio of the number of times 'B' == 'one' over the number of times 'B' == 'two' when 'C' > 2.

So, an output would be something like:
foo = 0.75

答:
I multiplied np.random.randn(11) by 10 so that the C > 2 constraint can exist, since np.random.randn(11) returns decimal values. The following code will produce what you want in steps. Feel free to condense. Also, it was ambiguous whether the C > 2 constraint applies to both the numerator and denominator or just the denominator. I assumed just the denominator. If you need it to be applied to the numerator, add the [df.C > 2] constraint to the n variable as well. Also, the ratios returned for this current df are inf if divide by 0 occurs and nan if 0 divided by 0 occurs.

```<code>for i in df.A.unique():
    #print unique value
    print(f"Unique Val: {i}")

    #print numerator
    print("Numerator:")
    n = (df[df.A == i].B == 'one').sum()
    print(n)

    #print denominator
    print("Denominator:")
    d = (df[df.A == i][df.C > 2].B == 'two').sum()
    print(d)

    #print ratio
    print("Ratio:")
    r = n/d
    print(r, "\n")
</code>```

Body:
I am going to try to express this problem in the most general way possible. Suppose I have a pandas dataframe with multiple columns ['A', 'B', 'C', 'D'].

For each unique value in 'A', I need to get the following ratio: the number of times 'B' == x, divided by the number of times 'B' == y, when 'C' == q OR p...

I'm sorry, but I don't know how to express this pythonically.

Sample data:

df = pd.DataFrame({'A': ['foo', 'zar', 'zar', 'bar', 'foo', 'bar','foo', 'bar', 'tar', 'foo', 'foo'],
'B': ['one', 'two', 'four', 'three', 'one', 'two', 'three','two', 'two', 'one', 'three'],
'C': np.random.randn(11),'D': np.random.randn(11)})`

I need something like the following. For each unique value i in 'A', I need the ratio of the number of times 'B' == 'one' over the number of times 'B' == 'two' when 'C' > 2.

So, an output would be something like:
foo = 0.75

Body:
I multiplied np.random.randn(11) by 10 so that the C > 2 constraint can exist, since np.random.randn(11) returns decimal values. The following code will produce what you want in steps. Feel free to condense. Also, it was ambiguous whether the C > 2 constraint applies to both the numerator and denominator or just the denominator. I assumed just the denominator. If you need it to be applied to the numerator, add the [df.C > 2] constraint to the n variable as well. Also, the ratios returned for this current df are inf if divide by 0 occurs and nan if 0 divided by 0 occurs.

for i in df.A.unique():
    #print unique value
    print(f"Unique Val: {i}")

    #print numerator
    print("Numerator:")
    n = (df[df.A == i].B == 'one').sum()
    print(n)

    #print denominator
    print("Denominator:")
    d = (df[df.A == i][df.C > 2].B == 'two').sum()
    print(d)

    #print ratio
    print("Ratio:")
    r = n/d
    print(r, "\n")


问:
Handling equivalent file extensions in Snakemake
Essentially, I want to know what the recomended way of handling equivalent file extensions is in snakemake. For example, lets say I have a rule that counts the number of entries in a fasta file. The rule might look something like....

```<code>rule count_entries:
    input:
        ["{some}.fasta"]
    output:
        ["{some}.entry_count"]
    shell:
        'grep -c ">" {input[0]} > {output[0]}'
</code>```

This works great. But what if I want this rule to also permit "{some}.fa" as input?

Is there any clean way to do this?

EDIT:

Here is my best guess at the first proposed sollution. This can probably be turned into a higher order function to be more general purpose but this is the basic idea as I understand it. I don't think this idea really fits any general use case though as it doesn't cooperate with other rules at the "building DAG" stage.

```<code>import os

def handle_ext(wcs):
    base = wcs["base"]
    for file_ext in [".fasta", ".fa"]:
        if(os.path.exists(base + file_ext)):
            return [base + file_ext]

rule count_entries:
    input:
        handle_ext
    output:
        ["{base}.entry_count"]
    shell:
        'grep -c ">" {input[0]} > {output[0]}'
</code>```

EDIT2: Here is the best current sollution as I see it...

```<code>count_entries_cmd = 'grep -c ">" {input} > {output}'
count_entries_output = "{some}.entry_count"

rule count_entries_fasta:
    input:
        "{some}.fasta"
    output:
        count_entries_output
    shell:
        count_entries_cmd

rule count_entries_fa:
    input:
        "{some}.fa"
    output:
        count_entries_output
    shell:
        count_entries_cmd
</code>```

答:
One thing I noticed is that you are trying to specify lists of files in both input and output sections but actually your rule takes a single file and produces another file.
I propose you a straightforward solution of specifying two separate rules for different extensions:

```<code>rule count_entries_fasta:
    input:
        "{some}.fasta"
    output:
        "{some}.entry_count"
    shell:
        'grep -c ">" {input} > {output}'

rule count_entries_fa:
    input:
        "{some}.fa"
    output:
        "{some}.entry_count"
    shell:
        'grep -c ">" {input} > {output}'
</code>```

These rules are not ambiguous unless you keep files with the same {some} name and different extension in the same folder (which I hope you don't do).

Body:
Essentially, I want to know what the recomended way of handling equivalent file extensions is in snakemake. For example, lets say I have a rule that counts the number of entries in a fasta file. The rule might look something like....

rule count_entries:
    input:
        ["{some}.fasta"]
    output:
        ["{some}.entry_count"]
    shell:
        'grep -c ">" {input[0]} > {output[0]}'

This works great. But what if I want this rule to also permit "{some}.fa" as input?

Is there any clean way to do this?

EDIT:

Here is my best guess at the first proposed sollution. This can probably be turned into a higher order function to be more general purpose but this is the basic idea as I understand it. I don't think this idea really fits any general use case though as it doesn't cooperate with other rules at the "building DAG" stage.

import os

def handle_ext(wcs):
    base = wcs["base"]
    for file_ext in [".fasta", ".fa"]:
        if(os.path.exists(base + file_ext)):
            return [base + file_ext]

rule count_entries:
    input:
        handle_ext
    output:
        ["{base}.entry_count"]
    shell:
        'grep -c ">" {input[0]} > {output[0]}'

EDIT2: Here is the best current sollution as I see it...

count_entries_cmd = 'grep -c ">" {input} > {output}'
count_entries_output = "{some}.entry_count"

rule count_entries_fasta:
    input:
        "{some}.fasta"
    output:
        count_entries_output
    shell:
        count_entries_cmd

rule count_entries_fa:
    input:
        "{some}.fa"
    output:
        count_entries_output
    shell:
        count_entries_cmd

Body:
One thing I noticed is that you are trying to specify lists of files in both input and output sections but actually your rule takes a single file and produces another file.
I propose you a straightforward solution of specifying two separate rules for different extensions:

rule count_entries_fasta:
    input:
        "{some}.fasta"
    output:
        "{some}.entry_count"
    shell:
        'grep -c ">" {input} > {output}'

rule count_entries_fa:
    input:
        "{some}.fa"
    output:
        "{some}.entry_count"
    shell:
        'grep -c ">" {input} > {output}'

These rules are not ambiguous unless you keep files with the same {some} name and different extension in the same folder (which I hope you don't do).


问:
How to programmatically click Select element and trigger onChange handler?
For example, with the following code. I tried several solutions.

```<code>function handleChange() {
    alert('hello')
}

<select id="names" onchange="handleChange()">
    <option>Foo</option>
    <option>Bar</option>
</select>
</code>```

Solution 1.

```<code>document.getElementById('#select').selectedIndex = 1
</code>```

This would change the value and display of select but doesn't trigger handleChange();

Solution 2

```<code>var element = document.getElementById('names');
var event = new Event('change');
element.dispatchEvent(event);
</code>```

This returns true but still doesn't trigger handleChange();

Any ideas on how to do this? Or can it actually be done? Solution has to be javascript/html only and sadly no jQuery.

答:
one way would be as below from the below answer for another question here

Trigger change() event when setting <select>'s value with val() function

```<code> $('#selectField').val(10).change();
</code>```

or simple one just to trigger the event

```<code> $('#selectField').change();
</code>```

or if you do not want to use Jquery
you can use the below method

```<code> const $roomID = document.querySelector('.roomID')
$roomID.onchange = function () {
   if ($("#ddlRoom").val() !== "") {
       var ID = $("#ddlRoom").val();
       console.log(ID);
} ;
};

$roomID.dispatchEvent(new Event('change'));
</code>```

Body:
For example, with the following code. I tried several solutions.

function handleChange() {
    alert('hello')
}

<select id="names" onchange="handleChange()">
    <option>Foo</option>
    <option>Bar</option>
</select>

Solution 1.

document.getElementById('#select').selectedIndex = 1

This would change the value and display of select but doesn't trigger handleChange();

Solution 2

var element = document.getElementById('names');
var event = new Event('change');
element.dispatchEvent(event);

This returns true but still doesn't trigger handleChange();

Any ideas on how to do this? Or can it actually be done? Solution has to be javascript/html only and sadly no jQuery.

Body:
one way would be as below from the below answer for another question here

Trigger change() event when setting <select>'s value with val() function

 $('#selectField').val(10).change();

or simple one just to trigger the event

 $('#selectField').change();

or if you do not want to use Jquery
you can use the below method

 const $roomID = document.querySelector('.roomID')
$roomID.onchange = function () {
   if ($("#ddlRoom").val() !== "") {
       var ID = $("#ddlRoom").val();
       console.log(ID);
} ;
};

$roomID.dispatchEvent(new Event('change'));


问:
Having difficulty sorting this array
I want to sort by a string that appears in different place in each array object.

I have an nsarray that contains objects like this:

```<code>Jones John 05-12-1993 Diabetes *05-13-2019 **R ***No Data ****68xxx

Smith John 05-12-2019 Hypertension *05-12-2019 **R ***05-12-2019 ****117xx

Smithers John 05-12-1947 COPD *05-13-2019 **R ***05-13-2019 ****89xxx

Wilson John 05-13-2019 Atrial Fibrillation *05-13-2019 **R ***05-16-2019 ****90xxx

Davis Joe 05-23-1905 Hypertension *05-25-2019 **R ***05-23-2019 ****42xxx
</code>```

I need to sort the array by the date after the single asterisk. I cannot figure out how to do this. I've tried a number of example but it doesn't work.  Any suggestions? Thanks.

I have tried this and of course it only sorts by the beginning of each object

```<code>[self.nameAndDOB sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; // 1-5 sort patient roster by last name
</code>```

答:
You may do the following things

Extract the date from the string, you have to do according to your algorithm or Regular Expression.

Convert the string to Date

Compare Date

Title: Having difficulty sorting this array

Body:
I want to sort by a string that appears in different place in each array object.

I have an nsarray that contains objects like this:

Jones John 05-12-1993 Diabetes *05-13-2019 **R ***No Data ****68xxx

Smith John 05-12-2019 Hypertension *05-12-2019 **R ***05-12-2019 ****117xx

Smithers John 05-12-1947 COPD *05-13-2019 **R ***05-13-2019 ****89xxx

Wilson John 05-13-2019 Atrial Fibrillation *05-13-2019 **R ***05-16-2019 ****90xxx

Davis Joe 05-23-1905 Hypertension *05-25-2019 **R ***05-23-2019 ****42xxx

I need to sort the array by the date after the single asterisk. I cannot figure out how to do this. I've tried a number of example but it doesn't work.  Any suggestions? Thanks.

I have tried this and of course it only sorts by the beginning of each object

[self.nameAndDOB sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; // 1-5 sort patient roster by last name


答: You can't. The number overflows the maximum safe integer size, therefore it is impossible to reverse this process (as the number gets rounded to the next safe integer). Therefore the code is broken.</p>

Title: parseInt() - String to Integer and back in PHP

Body:
Im trying to reverse engineering some Javascript code and recode it in PHP.
There is a String which is "converted" with parseInt(String, 36) to an Integer.
I need a posibility to convert the integer back to the secret String in PHP, without knowing the secret string.

secretCode = "0vo8fz4kvy03";
decode = parseInt(secretCode, 36).toString();
console.log(decode); //= 115802171408044510

How i can do that in PHP?
115802171408044510 back to 0vo8fz4kvy03

This interger contains some informations:

decode="115802171408044510";
storeID = decode.substr(0, 4); // 1158
posID = decode.substr(12, 2); // 04
orderID = decode.substr(14, 2); // 45
day = decode.substr(6, 2); // 17
month = decode.substr(4, 2); // 02
hour = decode.substr(8, 2); // 14
minutes = decode.substr(10, 2); // 08

I would like to edit this values above and convert this back to a "secretCode" String.
They are doing exactly this somehow server-side.


问:
I can not connect to postgres database
When trying to connect to the database

Me connectig property:

```<code>const sequelize = new Sequelize("postgres", "postgres", "postgres", {
  dialect: "postgres",
  host: "127.0.0.1",
  port: "5432",
});
</code>```

Server setting:
enter image description here

Error:

```<code>{ SequelizeConnectionError: ������������ "postgres" �� ������ �������� ����������� (�� ������)
    at connection.connect.err (E:\Dropbox\BigDeal\BigDealExpressJSTest\node_modules\sequelize\lib\dialects\postgres\connection-manager.js:182:24)
    at Connection.connectingErrorHandler (E:\Dropbox\BigDeal\BigDealExpressJSTest\node_modules\pg\lib\client.js:174:14)
    at Connection.emit (events.js:189:13)
    at Socket.<anonymous> (E:\Dropbox\BigDeal\BigDealExpressJSTest\node_modules\pg\lib\connection.js:126:12)
    at Socket.emit (events.js:189:13)
    at addChunk (_stream_readable.js:284:12)
    at readableAddChunk (_stream_readable.js:265:11)
    at Socket.Readable.push (_stream_readable.js:220:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  name: 'SequelizeConnectionError',
</code>```

How to fix it?

答:
I only used Sequelize once some time ago, but that's how I initialized it.:

```<code>const sequelize = new Sequelize({
    database: 'project-db',
    username: 'postgres',
    password: 'postgres',
    host: 'localhost',
    port: 5432,
    dialect: 'postgres'
});
</code>```

EDIT:

Reading the Sequelize documentation it seems your way to connect should also work. Are you sure "postgres" (the first parameter) is the name of an existing database?

Title: I can not connect to postgres database

Body:
When trying to connect to the database

Me connectig property:

const sequelize = new Sequelize("postgres", "postgres", "postgres", {
  dialect: "postgres",
  host: "127.0.0.1",
  port: "5432",
});

Server setting:
enter image description here

Error:

{ SequelizeConnectionError: ������������ "postgres" �� ������ �������� ����������� (�� ������)
    at connection.connect.err (E:\Dropbox\BigDeal\BigDealExpressJSTest\node_modules\sequelize\lib\dialects\postgres\connection-manager.js:182:24)
    at Connection.connectingErrorHandler (E:\Dropbox\BigDeal\BigDealExpressJSTest\node_modules\pg\lib\client.js:174:14)
    at Connection.emit (events.js:189:13)
    at Socket.<anonymous> (E:\Dropbox\BigDeal\BigDealExpressJSTest\node_modules\pg\lib\connection.js:126:12)
    at Socket.emit (events.js:189:13)
    at addChunk (_stream_readable.js:284:12)
    at readableAddChunk (_stream_readable.js:265:11)
    at Socket.Readable.push (_stream_readable.js:220:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
  name: 'SequelizeConnectionError',

How to fix it?

Body:
I only used Sequelize once some time ago, but that's how I initialized it.:

const sequelize = new Sequelize({
    database: 'project-db',
    username: 'postgres',
    password: 'postgres',
    host: 'localhost',
    port: 5432,
    dialect: 'postgres'
});

EDIT:

Reading the Sequelize documentation it seems your way to connect should also work. Are you sure "postgres" (the first parameter) is the name of an existing database?


问:
ASP.NET MVC 4 C# HttpPostedFileBase, How do I Store File
Model

```<code>public partial class Assignment
{
    public Assignment()
    {
        this.CourseAvailables = new HashSet<CourseAvailable>();
    }

    public string AssignmentID { get; set; }
    public Nullable<System.DateTime> SubmissionDate { get; set; }
    public string Status { get; set; }
    public Nullable<decimal> Mark { get; set; }
    public string Comments { get; set; }
    public string FileLocation  { get; set; }
    public virtual ICollection<CourseAvailable> CourseAvailables { get; set; }
}}
</code>```

Controller

```<code> public ActionResult Create(Assignment assignment)
    {
        if (ModelState.IsValid)
        {

            db.Assignments.Add(assignment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(assignment);
    }
</code>```

View

```<code><div class="editor-field">
    <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
    <%: Html.ValidationMessageFor(model => model.FileLocation) %>
</div>
</code>```

How do I store a file if I wanted to store the file into the server/path folder and in the database I only want to store the Path name/string.

答:
            List<Vozila> svaVozila = new List<Vozila>();
            using (StreamReader sr = new StreamReader(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\vozila.txt"))
            {
                while (sr.Peek() >= 0)
                {
                    string str;
                    string[] strArray;
                    str = sr.ReadLine();

                    strArray = str.Split('|');
                    Vozila auto = new Vozila();
                    auto.Registracija = strArray[0];
                    auto.Marka = strArray[1];
                    auto.GodinaProiz = strArray[2];
                    auto.Boja = strArray[3];

                    svaVozila.Add(auto);

                }
            }
            string registracija = Request.Form["registracija"];
            string datum = Request.Form["Datum"];
            string odM = Request["odMesta"];
            string doM = Request.Form["doMesta"];
            string kilometara = Request.Form["kilometara"];
            if (!String.IsNullOrEmpty(registracija))
            {
                using (StreamWriter wr = new StreamWriter(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\" + registracija + ".txt", true))
                {
                    wr.WriteLine(registracija + "|" + datum + "|" + odM + "|" + doM + "|" + kilometara);

                }
            }

            return View(svaVozila);
        }
        public ActionResult Prikaz()
        {

            List<Vozila> svaVozila = new List<Vozila>();
            using (StreamReader sr = new StreamReader(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\vozila.txt"))
            {
                while (sr.Peek() >= 0)
                {
                    string str;
                    string[] strArray;
                    str = sr.ReadLine();

                    strArray = str.Split('|');
                    Vozila auto = new Vozila();
                    auto.Registracija = strArray[0];
                    auto.Marka = strArray[1];
                    auto.GodinaProiz = strArray[2];
                    auto.Boja = strArray[3];

                    svaVozila.Add(auto);

                }
            }
            string reg = Request["reg"];
            string Marka = "";
            string godia = "";
            int kilometri = 0;
            for (int i = 0; i < svaVozila.Count; i++)
            {
                if (svaVozila[i].Registracija == reg)
                {
                    Marka = svaVozila[i].Marka;
                    godia = svaVozila[i].GodinaProiz;

                }

            }
            if (!String.IsNullOrEmpty(reg))
            {
                List<PredjeniPut> predj = new List<PredjeniPut>();
                using (StreamReader sr = new StreamReader(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\" + reg + ".txt"))
                {
                    while (sr.Peek() >= 0)
                    {
                        string str;
                        string[] strArray;
                        str = sr.ReadLine();

                        strArray = str.Split('|');
                        PredjeniPut put = new PredjeniPut();
                        put.Registracija = strArray[0];
                        put.Datum = strArray[1];
                        put.Odmesta = strArray[2];
                        put.Domesta = strArray[3];
                        put.Kilometara = Convert.ToInt32(strArray[4]);

                        predj.Add(put);

                    }

                }

                for (int i = 0; i < predj.Count; i++)
                {
                    kilometri += predj[i].Kilometara;

                }
            }
            ViewData["Kilometri"] = kilometri;
            ViewData["reg"] = reg;
            ViewData["Marka"] = Marka;
            ViewData["godina"] = godia;

            return View(svaVozila);
        }

    }
}
@*@model List<MvcApplication1.Models.Vozila>
@{

    ViewBag.Title = "Index";

}

Index

@using (Html.BeginForm("index,home"))
{

<select id="Select1" name="registracija">
    @foreach (var i in Model)
    {
  <option value="@i.Registracija">@i.Registracija</option>

    }
    </select>

    Datum<input id="Text1" type="text"name ="datum" />

        Od mesta<input id="Text1" type="text"name="odMesta" />

       Do mesta <input id="Text1" type="text"name="doMesta" />

       Kilometara <input id="Text1" type="text"name="kilometara" />

<input id="Submit1" type="submit" value="Prosledi" />
}
  @Html.ActionLink("Prikaz","Prikaz","home");*@
@*@model List<MvcApplication1.Models.Vozila>
@{
    ViewBag.Title = "Prikaz";
}

Prikaz

@using (Html.BeginForm("Prikaz,home"))
{
<select id="Select1" name="reg">
    @foreach (var i in Model)
    {
  <option value="@i.Registracija">@i.Registracija</option>

    }
    </select>
<input id="Submit1" type="submit" value="Prikazi" />

            Registracija
            GodinaProizvodnje
            Marka
            Kilometri

            @ViewData["reg"]
            @ViewData["Godina"]
            @ViewData["Marka"]
            @ViewData["Kilometri"]

}
*@```

Body:
Model

public partial class Assignment
{
    public Assignment()
    {
        this.CourseAvailables = new HashSet<CourseAvailable>();
    }

    public string AssignmentID { get; set; }
    public Nullable<System.DateTime> SubmissionDate { get; set; }
    public string Status { get; set; }
    public Nullable<decimal> Mark { get; set; }
    public string Comments { get; set; }
    public string FileLocation  { get; set; }
    public virtual ICollection<CourseAvailable> CourseAvailables { get; set; }
}}

Controller

 public ActionResult Create(Assignment assignment)
    {
        if (ModelState.IsValid)
        {

            db.Assignments.Add(assignment);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(assignment);
    }

View

    <%: Html.TextBoxFor(model => model.FileLocation, new { type="file"})%>
    <%: Html.ValidationMessageFor(model => model.FileLocation) %>

How do I store a file if I wanted to store the file into the server/path folder and in the database I only want to store the Path name/string.

Body:
            List<Vozila> svaVozila = new List<Vozila>();
            using (StreamReader sr = new StreamReader(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\vozila.txt"))
            {
                while (sr.Peek() >= 0)
                {
                    string str;
                    string[] strArray;
                    str = sr.ReadLine();

                    strArray = str.Split('|');
                    Vozila auto = new Vozila();
                    auto.Registracija = strArray[0];
                    auto.Marka = strArray[1];
                    auto.GodinaProiz = strArray[2];
                    auto.Boja = strArray[3];

                    svaVozila.Add(auto);

                }
            }
            string registracija = Request.Form["registracija"];
            string datum = Request.Form["Datum"];
            string odM = Request["odMesta"];
            string doM = Request.Form["doMesta"];
            string kilometara = Request.Form["kilometara"];
            if (!String.IsNullOrEmpty(registracija))
            {
                using (StreamWriter wr = new StreamWriter(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\" + registracija + ".txt", true))
                {
                    wr.WriteLine(registracija + "|" + datum + "|" + odM + "|" + doM + "|" + kilometara);

                }
            }

            return View(svaVozila);
        }
        public ActionResult Prikaz()
        {

            List<Vozila> svaVozila = new List<Vozila>();
            using (StreamReader sr = new StreamReader(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\vozila.txt"))
            {
                while (sr.Peek() >= 0)
                {
                    string str;
                    string[] strArray;
                    str = sr.ReadLine();

                    strArray = str.Split('|');
                    Vozila auto = new Vozila();
                    auto.Registracija = strArray[0];
                    auto.Marka = strArray[1];
                    auto.GodinaProiz = strArray[2];
                    auto.Boja = strArray[3];

                    svaVozila.Add(auto);

                }
            }
            string reg = Request["reg"];
            string Marka = "";
            string godia = "";
            int kilometri = 0;
            for (int i = 0; i < svaVozila.Count; i++)
            {
                if (svaVozila[i].Registracija == reg)
                {
                    Marka = svaVozila[i].Marka;
                    godia = svaVozila[i].GodinaProiz;

                }

            }
            if (!String.IsNullOrEmpty(reg))
            {
                List<PredjeniPut> predj = new List<PredjeniPut>();
                using (StreamReader sr = new StreamReader(@"C:\proba\MvcApplication1\MvcApplication1\fajlovi\" + reg + ".txt"))
                {
                    while (sr.Peek() >= 0)
                    {
                        string str;
                        string[] strArray;
                        str = sr.ReadLine();

                        strArray = str.Split('|');
                        PredjeniPut put = new PredjeniPut();
                        put.Registracija = strArray[0];
                        put.Datum = strArray[1];
                        put.Odmesta = strArray[2];
                        put.Domesta = strArray[3];
                        put.Kilometara = Convert.ToInt32(strArray[4]);

                        predj.Add(put);

                    }

                }

                for (int i = 0; i < predj.Count; i++)
                {
                    kilometri += predj[i].Kilometara;

                }
            }
            ViewData["Kilometri"] = kilometri;
            ViewData["reg"] = reg;
            ViewData["Marka"] = Marka;
            ViewData["godina"] = godia;

            return View(svaVozila);
        }

    }
}
@*@model List<MvcApplication1.Models.Vozila>
@{

    ViewBag.Title = "Index";

}

<h2>Index</h2>
@using (Html.BeginForm("index,home"))
{

<select id="Select1" name="registracija">
    @foreach (var i in Model)
    {
  <option value="@i.Registracija">@i.Registracija</option>

    }
    </select>

    <br />
    <label>Datum</label><input id="Text1" type="text"name ="datum" /> <br />
        <label>Od mesta</label><input id="Text1" type="text"name="odMesta" /><br />
       <label>Do mesta</label> <input id="Text1" type="text"name="doMesta" /><br />
       <label>Kilometara</label> <input id="Text1" type="text"name="kilometara" /><br />

<input id="Submit1" type="submit" value="Prosledi" />
}
  @Html.ActionLink("Prikaz","Prikaz","home");*@
@*@model List<MvcApplication1.Models.Vozila>
@{
    ViewBag.Title = "Prikaz";
}

<h2>Prikaz</h2>
@using (Html.BeginForm("Prikaz,home"))
{
<select id="Select1" name="reg">
    @foreach (var i in Model)
    {
  <option value="@i.Registracija">@i.Registracija</option>

    }
    </select>
<input id="Submit1" type="submit" value="Prikazi" />

    <table border="1">
        <tr>
            <th>Registracija</th>
            <th>GodinaProizvodnje</th>
            <th>Marka</th>
            <th>Kilometri</th>

        </tr>
        <tr>
            <td>@ViewData["reg"]</td>
            <td>@ViewData["Godina"]</td>
            <td>@ViewData["Marka"]</td>
            <td>@ViewData["Kilometri"]</td>

        </tr>

    </table>

}
*@


问:
How to show mobile view in mobile device?
I have problem with wordpress theme , when I open my website in mobile the theme is exactly desktop view but when I change the view to mobile view in inspect element it's work true .

https://www.pdfcar.com

答:
```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
    box-sizing: border-box;
}

style>.responsiveImg1 {
    width: 50%;
    max-width: 800px;
    height: auto;
}

.clsdivmain {
    background-color: #660066; /* Green */
}

.center {
    margin: auto;
    width: 60%;
    padding: 10px;
    text-align: center;
}

.table {
    border: 1px solid black;
    width: 70%;
    margin: auto;
}

.table1 {
    padding: 10px;
    width: 70%;
    margin: auto;
}

.table2 {
    width: 70%;
    margin: auto;
    background-size: 70%;
}

.tableheader {
    width: 70%;
    height: 70%;
    margin: auto;
    background-size: 70%;
}

.tablerowwidth {
    width: 50%;
}

.tablerowwidth3 {
    width: 10%;
}

.buttonPay {
    background-color: #660066; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    margin: 4px 2px;
    cursor: pointer;
    -webkit-transition-duration: 0.4s; /* Safari */
    transition-duration: 0.4s;
    width: 40%;
}

.buttonCancel {
    background-color: #0071A5; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    -webkit-transition-duration: 0.4s; /* Safari */
    transition-duration: 0.4s;
    width: 40%;
}

.buttonPay1 {
    width: 80%;
    padding: 5px;
    box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0
        rgba(0, 0, 0, 0.19);
}

.buttonCancel1 {
    width: 80%;
    padding: 5px;
    box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0
        rgba(0, 0, 0, 0.19);
}

.headingtext1 {
    color: #063871;
    font-style: bold;
    font: 22px arial, verdana;
    padding: 5px;
    float: left;
    width: 50%;
    height: 50%;
}

.infoText {
    color: #063871;
    font-style: normal;
    font: 15px arial, verdana;
    align: center;
    float: left;
    width: 100%;
    background-size: 100%;
}

.disclaimerText {
    color: #063871;
    font-style: normal;
    font: 15px arial, verdana;
    align: top;
    float: left;
    width: 100%;
    background-size: 100%;
}

.labels {
    color: #063871;
    font-style: normal;
    font: 15px arial, verdana;
    font-weight: bold;
    align: center;
    padding: 10px;
    float: left;
    width: 100%;
    margin: auto;
    background-size: 70%;
}

.generaltext {
    color: #063871;
    font-style: normal;
    font: 15px arial, verdana;
    padding: 5px;
    align: center;
    float: left;
    width: 100%;
    background-size: 70%;
    margin: auto;
}

.variables {
    color: #063871;
    background-color: #c9c9c9;
    font-size: 15px;
    font-style: normal;
    font: 15px arial, verdana;
    align: center;
    padding: 20px;
    float: left;
    width: 100%;
    background-size: 70%;
    margin: auto;
}

.main {
    background-color: #f1f1f1;
    padding: 20px;
    float: left;
    width: 60%; /* The width is 60%, by default */
}

.right {
    background-color: #4CAF50;
    padding: 20px;
    float: left;
    width: 20%; /* The width is 20%, by default */
}

/* Use a media query to add a break point at 800px: */
@media screen and (max-width:800px) {
    .table {
        padding: 10px;
        width: 100%;
        margin: auto;
    }
    .tablerowwidth3 {
        width: 1%;
    }
    .tableheader {
        width: 100%;
    }
    .buttonPay1 {
        width: 100%;
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0
            rgba(0, 0, 0, 0.19);
    }
    .buttonCancel1 {
        width: 100%;
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0
            rgba(0, 0, 0, 0.19);
    }
    .tablerowwidth {
        width: 100%;
    }
    .headingtext1 {
        width: 100%;
        height: 50%;
    }
    .responsiveImg1 {
        width: 100%;
    }
    .table2 {
        width: 100%;
        margin: auto;
    }
    .tableheader {
        width: 100%;
        height: 70%;
        margin: auto;
    }
    .table1 {
        padding: 10px;
        width: 100%;
        margin: auto;
    }
}
</style>
</head>
<body>
    <table class="tableheader">
        <tr>
            <td align="right"><img src="logo.png" clas="responsiveImg1">
            </td>

        </tr>
    </table>
    <table class="tableheader">
        <tr>
            <td class="tablerowwidth" height="10"><label
                class="headingtext1">Heading 1</label></td>
        </tr>
    </table>
    <div class="infoText">
        <table class="table1">
            <tr>
                <td>Mr, </br>
                </br>Message one</br>Message two</td>
            </tr>
        </table>
    </div>

    <div class="labels">
        <p class="table2">Subheading one</p>
        <table class="table">
            <tr>
                <td width="30%">Field one</td>
                <td width="45%" class="generaltext">AAAAAAAA</td>
                <td width="20%" class="tablerowwidth3"></td>
                <td width="20%" class="tablerowwidth3"></td>
            </tr>
            <tr>
                <td width="20%">Field one</td>
                <td width="45%" class="generaltext">BBBBBBBB</td>
                <td width="10%" class="tablerowwidth3"></td>
                <td width="10%" class="tablerowwidth3"></td>
            </tr>
            <tr>
                <td width="20%">Field one</td>
                <td width="65%" class="generaltext">CCCCCCCCC</td>
                <td width="10%" class="tablerowwidth3"></td>
                <td width="10%" class="tablerowwidth3"></td>
            </tr>
            <tr>
                <td width="20%">Field one</td>
                <td width="65%" class="generaltext">DDDDDDDD</td>
                <td width="10%" class="tablerowwidth3"></td>
                <td width="10%" class="tablerowwidth3"></td>
            </tr>
            <tr>
                <td width="20%"></td>
                <td width="65%" class="generaltext">EEEEEEEE</td>
                <td width="10%" class="tablerowwidth3"></td>
                <td width="10%" class="tablerowwidth3"></td>
            </tr>
            <tr>
                <td width="20%">Field one</td>
                <td width="65%" class="generaltext">FFFFFFFF</td>
                <td width="10%" class="tablerowwidth3"></td>
                <td width="10%" class="tablerowwidth3"></td>
            </tr>
            <tr>
                <td width="20%">Field one</td>
                <td width="65%" class="generaltext">GGGGGGGG</td>
                <td width="10%" class="tablerowwidth3"></td>
                <td width="10%" class="tablerowwidth3"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit"
                    class="buttonPay buttonPay1" name="PayNow" value="Submit"></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit"
                    class="buttonCancel buttonCancel1" name="PayCancel"
                    value="Reset"></td>
            </tr>

        </table>
        <div class="disclaimerText">
            <table class="table1">
                <tr>
                    <td align="top">---Disclaimer </br>Field. </br>Field.</br>Field.</td>
                </tr>
            </table>
        </div>
    </div>
</body>
</html>
</code>```


问:
What do back brackets do in this bash script code?
so i'm doing a problem with bashscript, this one: ./namefreq.sh ANA should return a list of two names (on separate lines) ANA and RENEE, both of which have frequency 0.120.

Basically I have a file from table.csv shown in the code below that have names and a frequency number next to them e.g. Anna, 0.120

I'm still unsure what the `` does for this code, and I'm also struggling to understand how this code is able to print out two names with identical frequencies. The way I read the code is:

grep compares the word (-w) typed by the user (./bashscript.sh Anna) to the value of (a), which then uses the cut command to be able to compare the 2nd field of the line separated by the delimiter "," which is the frequency from the file table.csv and then | cut -f1 -d"," prints out the first fields which are the names with the same frequency

^ would this be correct?

thanks :)

```<code>#!/bin/bash
a=`grep -w $1 table.csv  | cut -f2 -d','`
grep -w $a  table.csv | cut -f1 -d',' | sort -d
</code>```

答:
When a command is in backticks or $(), the output of the command is subsituted back into the command in place of it. So if the file has Anna,0.120

```<code>a=`grep -w Anna table.csv  | cut -f2 -d','`
</code>```

will execute the grep and cut commands, which will output 0.120, so it will be equivalent to

```<code>a=0.120
</code>```

Then the command looks for all the lines that match 0.120, extracts the first field with cut, and sorts them.

Body:
so i'm doing a problem with bashscript, this one: ./namefreq.sh ANA should return a list of two names (on separate lines) ANA and RENEE, both of which have frequency 0.120.

Basically I have a file from table.csv shown in the code below that have names and a frequency number next to them e.g. Anna, 0.120

I'm still unsure what the `` does for this code, and I'm also struggling to understand how this code is able to print out two names with identical frequencies. The way I read the code is:

grep compares the word (-w) typed by the user (./bashscript.sh Anna) to the value of (a), which then uses the cut command to be able to compare the 2nd field of the line separated by the delimiter "," which is the frequency from the file table.csv and then | cut -f1 -d"," prints out the first fields which are the names with the same frequency

^ would this be correct?

thanks :)

#!/bin/bash
a=`grep -w $1 table.csv  | cut -f2 -d','`
grep -w $a  table.csv | cut -f1 -d',' | sort -d

Body:
When a command is in backticks or $(), the output of the command is subsituted back into the command in place of it. So if the file has Anna,0.120

a=`grep -w Anna table.csv  | cut -f2 -d','`

will execute the grep and cut commands, which will output 0.120, so it will be equivalent to

a=0.120

Then the command looks for all the lines that match 0.120, extracts the first field with cut, and sorts them.


问:
Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)
Before mark it as duplicate please read the question.

I have set both SHA1 and SHA256 in my google console.

I have tried many way but still facing error.

Unhandled Exception: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null)

Also tried with Flutter and google_sign_in plugin: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10: , null) and other so many.

Where I'm still missing ?

答:
A lot can go wrong and I struggled for a very long time to fix this issue. My fix was that I needed to select the support email address in the settings of my firebase project.

Good luck

Johan


问:
How-to get the code for downloading metadata along with images in IBM content manager
I am trying to find the code in java  API which works with cm IBM.. the sample code is there but it is just for logging in.. can anyone help to get the code to download the images along with metadata</p>

答:
as you said you have basic connection code, use the below function to download the document..</p>

```<code> public String retrieveDocument(CMBConnection connection, CMBItem item)
          throws CMBException, IOException, Exception
     {
          // Get an instance of data management bean
          CMBDataManagement dataManagement = connection.getDataManagement();
          // Set the current data item
          dataManagement.setDataObject(item);
          // Retrieve the original file name
          CMBObject object = dataManagement.getContent(0);
          String inputFileName = object.getOriginalFileName();
          // Parse the file name from the full path
          int pos=inputFileName.lastIndexOf("\\");
          inputFileName = inputFileName.substring(pos+1);
          // Write the document content to a new file
          String fileName = System.getProperty("user.dir")
               + File.separator + inputFileName;
          System.out.println("Output file name " + fileName);
          FileOutputStream fileoutstream = new FileOutputStream(fileName);
          fileoutstream.write(dataManagement.getContent(0).getData());
          fileoutstream.close();
          // Return file name
          return fileName;
     }
</code>```

Body:
as you said you have basic connection code, use the below function to download the document..

 public String retrieveDocument(CMBConnection connection, CMBItem item)
          throws CMBException, IOException, Exception
     {
          // Get an instance of data management bean
          CMBDataManagement dataManagement = connection.getDataManagement();
          // Set the current data item
          dataManagement.setDataObject(item);
          // Retrieve the original file name
          CMBObject object = dataManagement.getContent(0);
          String inputFileName = object.getOriginalFileName();
          // Parse the file name from the full path
          int pos=inputFileName.lastIndexOf("\\");
          inputFileName = inputFileName.substring(pos+1);
          // Write the document content to a new file
          String fileName = System.getProperty("user.dir")
               + File.separator + inputFileName;
          System.out.println("Output file name " + fileName);
          FileOutputStream fileoutstream = new FileOutputStream(fileName);
          fileoutstream.write(dataManagement.getContent(0).getData());
          fileoutstream.close();
          // Return file name
          return fileName;
     }


问:
Why does dplyr filter_all using all_vars > 0 work on a character string?
Given:

```<code>df <- structure(list(word = c("aaliyahmaxwell", "abasc", "abbslovesfed",
"abbycastro", "abc", "abccarpet", "abdul", "ability", "abnormile",
"abraham"), chardonnay = c(4, 0, 0, 0, 0, 0, 0, 0, 0, 0), coffee = c(0,
1, 1, 1, 1, 1, 1, 1, 1, 1)), .Names = c("word", "chardonnay",
"coffee"), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

Why does df %>% filter_all(all_vars(. > 0)) work?

I mean that my first column is of type character and can't be > 0.
I can understand why it works on the other two columns but need an explanation on why it works when I have a mixture of character and double type columns.

Please advise.

答:
It is due to type change.  Here, 0 a numeric entry gets type converted to a character one.  According to `?Comparison

If the two arguments are atomic vectors of different types, one is coerced to the type of the other, the (decreasing) order of precedence being character, complex, numeric, integer, logical and raw.

```<code>df %>%
   filter(word > 0)
</code>```

giving all the rows of the original data because

```<code>letters > 0
#[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
#[26] TRUE
</code>```

In the 'word' column, it is all characters which would any way be greater than "0" due to type conversion, leaving only the all_vars to essentially check whether the other numeric columns are greater than 0

In the OP's dataset example, none of the rows match the criteria because one of the numeric columns is always less than or equal to 0 in each of the rows.  If we change the first row of 'coffee' to 2 or 1, that row would be picked up because the 'chardonnay' is greater than 0, the first column 'word' is always greater

```<code>df$coffee[1] <- 2
df %>%
    filter_all(all_vars(. > 0))
# A tibble: 1 x 3
#  word           chardonnay coffee
#   <chr>               <dbl>  <dbl>
#1 aaliyahmaxwell          4      2
</code>```

To select only numeric columns, use filter_if (as in the comments)

```<code>df %>%
   filter_if(is.numeric, all_vars(. > 0))
</code>```

Body:
Given:

df <- structure(list(word = c("aaliyahmaxwell", "abasc", "abbslovesfed",
"abbycastro", "abc", "abccarpet", "abdul", "ability", "abnormile",
"abraham"), chardonnay = c(4, 0, 0, 0, 0, 0, 0, 0, 0, 0), coffee = c(0,
1, 1, 1, 1, 1, 1, 1, 1, 1)), .Names = c("word", "chardonnay",
"coffee"), row.names = c(NA, -10L), class = c("tbl_df", "tbl",
"data.frame"))

Why does df %>% filter_all(all_vars(. > 0)) work?

I mean that my first column is of type character and can't be > 0.
I can understand why it works on the other two columns but need an explanation on why it works when I have a mixture of character and double type columns.

Please advise.

Body:
It is due to type change.  Here, 0 a numeric entry gets type converted to a character one.  According to `?Comparison

If the two arguments are atomic vectors of different types, one is coerced to the type of the other, the (decreasing) order of precedence being character, complex, numeric, integer, logical and raw.

df %>%
   filter(word > 0)

giving all the rows of the original data because

letters > 0
#[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
#[26] TRUE

In the 'word' column, it is all characters which would any way be greater than "0" due to type conversion, leaving only the all_vars to essentially check whether the other numeric columns are greater than 0

In the OP's dataset example, none of the rows match the criteria because one of the numeric columns is always less than or equal to 0 in each of the rows.  If we change the first row of 'coffee' to 2 or 1, that row would be picked up because the 'chardonnay' is greater than 0, the first column 'word' is always greater

df$coffee[1] <- 2
df %>%
    filter_all(all_vars(. > 0))
# A tibble: 1 x 3
#  word           chardonnay coffee
#   <chr>               <dbl>  <dbl>
#1 aaliyahmaxwell          4      2

To select only numeric columns, use filter_if (as in the comments)

df %>%
   filter_if(is.numeric, all_vars(. > 0))


问:
How can I render a component in React to 2 different components?
I'm working on a ReactJS project. I have 3 components in the main page "Index component" as follows,

Nav-
Featured-
Footer

My Nav component has 2 links to 2 different components.
My Switch is as follows,

```<code>  <Switch>
      <Route path="/home" component={props => <Index {...props} />} />
      <Route path="/register" component={Register} />
      <Route path="/login" component={Login} />
      <Route path="/cart" component={Cart} />
      <Redirect from="/" to="home" />
  </Switch>
</code>```

I also have my Index component as follows,

```<code>   <React.Fragment>
       <Search />
       <Nav history={history} />
    {this.homePageComponents()}
       <Route
      path="/home/bedding"
      component={props => (
        <Bedding beddingProducts={this.beddingProducts()} {...props} />
      )}
    />
       <Route
      path="/home/bath"
      component={props => (
        <Bath bathProducts={this.bathProducts()} {...props} />
      )}
    />
       <Route path="/home/search" component={Search} />
  </React.Fragment>
</code>```

I'm trying to render the Nav component to both Bath and Bedding products but whenever I import it and use it there it gives me an Error saying this.props.history.replace is undefined.
This is the project's link.
https://github.com/MaxOffline/beetle

答:
I found a very simple way to fix the problem.
All I needed to do is render components to the homepage conditionally so I simply added the following helper method to my "Index" Component.

```<code>homePageComponents = () => {
const featuredProducts = this.state.products.filter(
  product => product.featured === true
);
if (this.props.history.location.pathname === "/home") {
  return <Featured featuredProducts={featuredProducts} />;
}
</code>```

};

Body:
I'm working on a ReactJS project. I have 3 components in the main page "Index component" as follows,

Nav-
Featured-
Footer

My Nav component has 2 links to 2 different components.
My Switch is as follows,

  <Switch>
      <Route path="/home" component={props => <Index {...props} />} />
      <Route path="/register" component={Register} />
      <Route path="/login" component={Login} />
      <Route path="/cart" component={Cart} />
      <Redirect from="/" to="home" />
  </Switch>

I also have my Index component as follows,

   <React.Fragment>
       <Search />

    {this.homePageComponents()}
       <Route
      path="/home/bedding"
      component={props => (
        <Bedding beddingProducts={this.beddingProducts()} {...props} />
      )}
    />
       <Route
      path="/home/bath"
      component={props => (
        <Bath bathProducts={this.bathProducts()} {...props} />
      )}
    />
       <Route path="/home/search" component={Search} />
  </React.Fragment>

I'm trying to render the Nav component to both Bath and Bedding products but whenever I import it and use it there it gives me an Error saying this.props.history.replace is undefined.
This is the project's link.
https://github.com/MaxOffline/beetle

Body:
I found a very simple way to fix the problem.
All I needed to do is render components to the homepage conditionally so I simply added the following helper method to my "Index" Component.

homePageComponents = () => {
const featuredProducts = this.state.products.filter(
  product => product.featured === true
);
if (this.props.history.location.pathname === "/home") {
  return <Featured featuredProducts={featuredProducts} />;
}

};


问:
Intent Passing SkuDetails
I would like to pass my selected Subscription Package to the next activity page. The class object is SkuDetails

What extension do I have to apply to do so ?

```<code>    val intent = Intent(this, SignUpActivity::class.java)
intent.putExtra("selected_plan" , selectedSkuDetails)
            startActivity(intent)
</code>```

SkuDetails:

https://developer.android.com/reference/com/android/billingclient/api/SkuDetails

答:
You need to extend your POJO class by Serializable because you cannot send an object to another class you have to make it into bytes or streams to send to another class and Serializable class do it for you. Here is an Example.

```<code>    //This object needs to send to activity
    data class WeatherResponse(
        @SerializedName("cod")
        val cod: String? = null,
        @SerializedName("count")
        val count: Int? = null,
        @SerializedName("message")
        val message: String? = null
    ) : Serializable

    //For sending Serializable Object to Activity
    val weatherResponse = WeatherResponse("Demo",1,"Hi Deummy")
    val intent = Intent(this, SignUpActivity::class.java)
    intent.putExtra("weather_response" , weatherResponse)
    startActivity(intent)

    //for receiving Serializable Object into Activity
    var weatherResponse = intent.getSerializableExtra("weather_response") as WeatherResponse
</code>```

Title: Intent Passing SkuDetails

Body:
I would like to pass my selected Subscription Package to the next activity page. The class object is SkuDetails

What extension do I have to apply to do so ?

    val intent = Intent(this, SignUpActivity::class.java)
intent.putExtra("selected_plan" , selectedSkuDetails)
            startActivity(intent)

SkuDetails:

https://developer.android.com/reference/com/android/billingclient/api/SkuDetails

Body:
You need to extend your POJO class by Serializable because you cannot send an object to another class you have to make it into bytes or streams to send to another class and Serializable class do it for you. Here is an Example.

    //This object needs to send to activity
    data class WeatherResponse(
        @SerializedName("cod")
        val cod: String? = null,
        @SerializedName("count")
        val count: Int? = null,
        @SerializedName("message")
        val message: String? = null
    ) : Serializable

    //For sending Serializable Object to Activity
    val weatherResponse = WeatherResponse("Demo",1,"Hi Deummy")
    val intent = Intent(this, SignUpActivity::class.java)
    intent.putExtra("weather_response" , weatherResponse)
    startActivity(intent)

    //for receiving Serializable Object into Activity
    var weatherResponse = intent.getSerializableExtra("weather_response") as WeatherResponse


问:
Can't stop form closing when background worker is in progress
I have a form with a background worker in a c# winforms application (Visual Studio 2010, .net 4). When the background worker is busy I would like to warn the user aboout it when tries to close the form and cancel form closing. I'd like to handle it in form closing event by setting form close cancellation to true.

BUT it still closes the form!

Here is the code snippet I use:

```<code>private void FormDrivenDistance_FormClosing(object sender, FormClosingEventArgs e)
{
  if (myBackgroundWorker.IsBusy)
  {
     Messenger.ShowCriticalMessage("Don't close, in progress!");
                    e.Cancel = true;
  }
}
</code>```

Where is the bug?!

Thanks in advance!

答:
Are you sure that myBackgroundWorker.IsBusy returns true?  Have you tried setting a break point inside the check to make sure it's being called?

Are you sure that the event is hooked up properly?

If those things are true, the bug would have to be in some other part of the code.

There may also be some other handler on FormClosing setting Cancel to false, but that's probably a less likely scenario.

Body:
I have a form with a background worker in a c# winforms application (Visual Studio 2010, .net 4). When the background worker is busy I would like to warn the user aboout it when tries to close the form and cancel form closing. I'd like to handle it in form closing event by setting form close cancellation to true.

BUT it still closes the form!

Here is the code snippet I use:

private void FormDrivenDistance_FormClosing(object sender, FormClosingEventArgs e)
{
  if (myBackgroundWorker.IsBusy)
  {
     Messenger.ShowCriticalMessage("Don't close, in progress!");
                    e.Cancel = true;
  }
}

Where is the bug?!

Thanks in advance!


问:
Where can i find NuGet.Clients documentation?
I'm trying to add Nuget package management to my newly developed IDE.
The github repository seems to have UI components here
but i can't find any resources for how to use it.

the only documentation i can find doesn't say anything about UI components

答:
As devNull pointed out, there is a page in the docs saying that certain packages on nuget.org are provided and usable in your project. But this roughly corresponds to the projects under src\NuGet.Core.

The projects under src\NuGet.Clients are tools that we distribute as a product, but are not intended to be a library or reusable. The UI components are extremely tied to Visual Studio, depending on several other components in Visual Studio, so you would have to implement all the dependencies to be able to use the UI. In my opinion you'd be better off using the core packages and build your own UI on top of them.