问:
Apache beam reading Avro files from GCS and writing to BigQuery
Running a java job to read Avro files and have been getting errors. Looking for help on this -

Here is the code -

```<code>// Get Avro Schema
String schemaJson = getSchema(options.getAvroSchema());
Schema schema = new Schema.Parser().parse(schemaJson);

// Check schema field types before starting the Dataflow job
checkFieldTypes(schema);

// Create the Pipeline object with the options we defined above.
Pipeline pipeline = Pipeline.create(options);
String bqStr = getBQString(options);
// TableSchema ts = BigQueryAvroUtils.getTableSchema(User.SCHEMA$);
// Convert Avro To CSV
PCollection<GenericRecord> records =
    pipeline.apply(
        "Read Avro files",
        AvroIO.readGenericRecords(schema)
            .from(options.getInputFile()));

records
    .apply(
        "Convert Avro to CSV formatted data",
        ParDo.of(new ConvertAvroToCsv(schemaJson, options.getCsvDelimiter())))
    .apply(
        "Write CSV formatted data",
        TextIO.write().to(options.getOutput())
            .withSuffix(".csv"));

records.apply(
      "Write to BigQuery",
      BigQueryIO.write()
          .to(bqStr)
          .withJsonSchema(schemaJson)
          .withWriteDisposition(WRITE_APPEND)
          .withCreateDisposition(CREATE_IF_NEEDED)
          .withFormatFunction(TABLE_ROW_PARSER));
  // [END bq_write]
</code>```

Here is the error that I see  -

```<code>2020-06-01 13:14:41 ERROR MonitoringUtil$LoggingHandler:99 - 2020-06-01T07:44:39.240Z: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to org.apache.avro.specific.SpecificRecord
        at com.example.AvroToCsv$1.apply(AvroToCsv.java:1)
        at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement(PrepareWrite.java:76)

2020-06-01 13:14:52 ERROR MonitoringUtil$LoggingHandler:99 - 2020-06-01T07:44:48.956Z: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to org.apache.avro.specific.SpecificRecord
        at com.example.AvroToCsv$1.apply(AvroToCsv.java:1)
        at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement(PrepareWrite.java:76)

2020-06-01 13:15:03 ERROR MonitoringUtil$LoggingHandler:99 - 2020-06-01T07:44:58.811Z: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to org.apache.avro.specific.SpecificRecord
        at com.example.AvroToCsv$1.apply(AvroToCsv.java:1)
        at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement(PrepareWrite.java:76)

2020-06-01 13:15:15 ERROR MonitoringUtil$LoggingHandler:99 - 2020-06-01T07:45:10.673Z: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to org.apache.avro.specific.SpecificRecord
        at com.example.AvroToCsv$1.apply(AvroToCsv.java:1)
        at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement(PrepareWrite.java:76)
</code>```

答:
The error is in your TABLE_ROW_PARSER function. It appears to be casting an Avro GenericRecord to a SpecificRecord.

The line in PrepareWrite that is failing is here. That line calls the format function you provide. The format function must convert each input element into a JSON TableRow. It is probably better to use withAvroFormatFunction for efficiency.

Body:
Running a java job to read Avro files and have been getting errors. Looking for help on this -

Here is the code -

// Get Avro Schema
String schemaJson = getSchema(options.getAvroSchema());
Schema schema = new Schema.Parser().parse(schemaJson);

// Check schema field types before starting the Dataflow job
checkFieldTypes(schema);

// Create the Pipeline object with the options we defined above.
Pipeline pipeline = Pipeline.create(options);
String bqStr = getBQString(options);
// TableSchema ts = BigQueryAvroUtils.getTableSchema(User.SCHEMA$);
// Convert Avro To CSV
PCollection<GenericRecord> records =
    pipeline.apply(
        "Read Avro files",
        AvroIO.readGenericRecords(schema)
            .from(options.getInputFile()));

records
    .apply(
        "Convert Avro to CSV formatted data",
        ParDo.of(new ConvertAvroToCsv(schemaJson, options.getCsvDelimiter())))
    .apply(
        "Write CSV formatted data",
        TextIO.write().to(options.getOutput())
            .withSuffix(".csv"));

records.apply(
      "Write to BigQuery",
      BigQueryIO.write()
          .to(bqStr)
          .withJsonSchema(schemaJson)
          .withWriteDisposition(WRITE_APPEND)
          .withCreateDisposition(CREATE_IF_NEEDED)
          .withFormatFunction(TABLE_ROW_PARSER));
  // [END bq_write]

Here is the error that I see  -

2020-06-01 13:14:41 ERROR MonitoringUtil$LoggingHandler:99 - 2020-06-01T07:44:39.240Z: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to org.apache.avro.specific.SpecificRecord
        at com.example.AvroToCsv$1.apply(AvroToCsv.java:1)
        at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement(PrepareWrite.java:76)

2020-06-01 13:14:52 ERROR MonitoringUtil$LoggingHandler:99 - 2020-06-01T07:44:48.956Z: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to org.apache.avro.specific.SpecificRecord
        at com.example.AvroToCsv$1.apply(AvroToCsv.java:1)
        at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement(PrepareWrite.java:76)

2020-06-01 13:15:03 ERROR MonitoringUtil$LoggingHandler:99 - 2020-06-01T07:44:58.811Z: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to org.apache.avro.specific.SpecificRecord
        at com.example.AvroToCsv$1.apply(AvroToCsv.java:1)
        at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement(PrepareWrite.java:76)

2020-06-01 13:15:15 ERROR MonitoringUtil$LoggingHandler:99 - 2020-06-01T07:45:10.673Z: java.lang.ClassCastException: org.apache.avro.generic.GenericData$Record cannot be cast to org.apache.avro.specific.SpecificRecord
        at com.example.AvroToCsv$1.apply(AvroToCsv.java:1)
        at org.apache.beam.sdk.io.gcp.bigquery.PrepareWrite$1.processElement(PrepareWrite.java:76)


来源: stackexchange

问:
Questions regarding efficiency
So while working through a course on Udemy over C++ one of the challenges was to check a string to see whether it was a palindrome or not. I completed the task successfully but went about it a different way than the instructor. I understand there are a multitude of ways to complete a task but I am wondering which is more efficient and why? It may seem stupid to be wondering about this while reteaching myself coding but I feel this is something I should be keeping in mind.

```<code>//Instructors code//

# include<iostream>
using namespace std;

/*program for reverse a string and check a string is a palidrome

*/
int main()
{
    string str="MADAM";
    string rev="";
    int len=(int)str.length();
    rev.resize(len);
    for(int i=0, j=len-1; i<len; i++, j--)
    {
        rev[i]=str[j];
    }
    rev[len]='\0';
    if(str.compare(rev)==0)
        cout<<"palindrome"<<endl;
    else
        cout<<"not a pallindrome"<<endl;
    return 0;
}
</code>```

My Approach

```<code>#include <iostream>
using namespace std;

int main(){
    string str1="test";
//    cout << "Enter a string to check if it is a Palindrome: ";
//    getline(cin,str1);

    string str2;

    string::reverse_iterator it;
    for(it=str1.rbegin(); it!= str1.rend(); it++)
    {
        str2.push_back(*it);

    }
    if(!str1.compare(str2))
        cout << "\nPalindrome";
    else
        cout << "\nNot a Palindrome";
    return 0;
}
</code>```

Thank you in advance.

答:
I would say that both are almost the same, but as mentioned in the comments, the line:

```<code>str2.push_back(*it);
</code>```

Is actually very inefficient, since std::string may copy the existing string to a new location in the memory, and then append the next char to the string, which is wasteful.

But I am wondering, why to create the copy in the first place?

It is very simple to run both from start to end, and from end to start to check it out, meaning:

```<code>
bool is_polindrom(const std::string& str)
{
    for (std::size_t idx = 0, len = str.length(); idx < len / 2; ++idx)
    {
        if (str[idx] != str[len - 1 - idx])
        {
            return false;
        }
    }

    return true;
}
</code>```

Running the code with:

```<code>
int main()
{
    const std::string right1 = "MADAM";
    const std::string right2 = "MAAM";
    const std::string wrong1 = "MADAAM";
    const std::string wrong2 = "MEDAM";

    std::cout << "MADAM result is: " << is_polindrom(right1) << std::endl;
    std::cout << "MAAM result is: " << is_polindrom(right2) << std::endl;
    std::cout << "MADAAM result is: " << is_polindrom(wrong1) << std::endl;
    std::cout << "MEDAM result is: " << is_polindrom(wrong2) << std::endl;
}
</code>```

Will yield:

MADAM result is: 1

MAAM result is: 1

MADAAM result is: 0

MEDAM result is: 0

You don't need extra memory in this case, since it is possible to iterate over a string from the end to the beginning, and you need to run on it exactly once (and notice that I stop when idx >= len / 2 since you don't really need to check each letter twice!).

ContentLicense: CC BY-SA 4.0

Title: Questions regarding efficiency

Body:
So while working through a course on Udemy over C++ one of the challenges was to check a string to see whether it was a palindrome or not. I completed the task successfully but went about it a different way than the instructor. I understand there are a multitude of ways to complete a task but I am wondering which is more efficient and why? It may seem stupid to be wondering about this while reteaching myself coding but I feel this is something I should be keeping in mind.

//Instructors code//

# include<iostream>
using namespace std;

/*program for reverse a string and check a string is a palidrome

*/
int main()
{
    string str="MADAM";
    string rev="";
    int len=(int)str.length();
    rev.resize(len);
    for(int i=0, j=len-1; i<len; i++, j--)
    {
        rev[i]=str[j];
    }
    rev[len]='\0';
    if(str.compare(rev)==0)
        cout<<"palindrome"<<endl;
    else
        cout<<"not a pallindrome"<<endl;
    return 0;
}

My Approach

#include <iostream>
using namespace std;

int main(){
    string str1="test";
//    cout << "Enter a string to check if it is a Palindrome: ";
//    getline(cin,str1);

    string str2;

    string::reverse_iterator it;
    for(it=str1.rbegin(); it!= str1.rend(); it++)
    {
        str2.push_back(*it);

    }
    if(!str1.compare(str2))
        cout << "\nPalindrome";
    else
        cout << "\nNot a Palindrome";
    return 0;
}

Thank you in advance.

Body:
I would say that both are almost the same, but as mentioned in the comments, the line:

str2.push_back(*it);

Is actually very inefficient, since std::string may copy the existing string to a new location in the memory, and then append the next char to the string, which is wasteful.

But I am wondering, why to create the copy in the first place?

It is very simple to run both from start to end, and from end to start to check it out, meaning:

bool is_polindrom(const std::string& str)
{
    for (std::size_t idx = 0, len = str.length(); idx < len / 2; ++idx)
    {
        if (str[idx] != str[len - 1 - idx])
        {
            return false;
        }
    }

    return true;
}

Running the code with:

int main()
{
    const std::string right1 = "MADAM";
    const std::string right2 = "MAAM";
    const std::string wrong1 = "MADAAM";
    const std::string wrong2 = "MEDAM";

    std::cout << "MADAM result is: " << is_polindrom(right1) << std::endl;
    std::cout << "MAAM result is: " << is_polindrom(right2) << std::endl;
    std::cout << "MADAAM result is: " << is_polindrom(wrong1) << std::endl;
    std::cout << "MEDAM result is: " << is_polindrom(wrong2) << std::endl;
}

Will yield:

MADAM result is: 1

MAAM result is: 1

MADAAM result is: 0

MEDAM result is: 0

You don't need extra memory in this case, since it is possible to iterate over a string from the end to the beginning, and you need to run on it exactly once (and notice that I stop when idx >= len / 2 since you don't really need to check each letter twice!).


问:
unable to verify a signed message in solidity
I am using this tutorial : https://web3py.readthedocs.io/en/stable/web3.eth.account.html#sign-a-message

```<code>##  in web3py

sig = Web3.soliditySha3( [uint256, address], [tokens, contractaddress] ) ## used below also
output: HexBytes('0x3efb3cf4e41109f6f1f998401d02dbe894719a8806f45e79a5fab7d4799f00bb')
</code>```

```<code>from eth_account.messages import encode_defunct
msg = sig.hex()
message = encode_defunct(text=msg)
signed_message = w3.eth.account.sign_message(message, private_key=private_key)
signed_message

SignedMessage(messageHash=HexBytes('0x4c0c7077f770069785167e8b7451d63fad1e858ef5251b239eb0781c314000d2'), r=5665764915496639843348851536709769469640799172147461427941649091688603148258, s=48121517563314450138554207713326165180739298862566159641495137088718857193470, v=27, signature=HexBytes('0x0c86b594baa5bb06a0f4054ffdf3896377cfb757d42dcaeacf0241d96a4d5fe26a63d0514338ec600c89ee808dc088e7b3aadc55b9f5d86685d3ff212e2e47fe1b'))
</code>```

When I pass these params such as signed_message.messageHash and signed_message.signature to the recoversigner(mentioned below) function in the smart contract. It gives the correct address. But when I am passing arguments tokens, contractaddress (used above) to the solidity keccak256(abi.encodePacked(token,address(this))) the message that is genarated is different from the signed_message.messageHash and in turn I get a different address as output from ecrecover.

I checked what is the output of keccak256(abi.encodePacked(..)).
I found It is same as sig value

What I have done:

Make an ERC20 token.

setup the channel

My goal:

sign messages (with web3py)

validate the signed message with solidity.

Like this:

user will pass some arguments : like contract address and number of tokens along with the signed message. and I will validate it with

```<code>    function splitSignature(bytes memory sig)
        pure
        internal
        returns (uint8 v, bytes32 r, bytes32 s)
    {
        require(sig.length == 65 , "invalid length");

        assembly {
            r := mload(add(sig, 32))
            s := mload(add(sig, 64))
            v := byte(0, mload(add(sig, 96)))
        }
        if (v < 27) {
            v += 27;
        }

        require(v == 27 || v == 28 , "value of v ");
        return (v, r, s);
    }

    function recoverSigner(bytes32 message, bytes memory sig)
        internal
        pure
        returns (address)
    {
        (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);
        return ecrecover(message, v, r, s);
    }

</code>```

```<code>bytes32 message = prefixed(keccak256(abi.encodePacked(token,address(this))));
</code>```

This is not working properly. I am not getting the correct address as output.

Please help..

答:
I'm not entirely clear on what you're trying to do, but an important clarification to make here is that Web3's eth.sign (and its underlying JSON-RPC call eth_sign) do not sign a simple hash. It adds a prefix string, with a length embedded.

See the eth_sign docs:

The sign method calculates an Ethereum specific signature with: sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))).

By adding the prefix to the passed message, your client makes sure that you aren't using eth_sign to sign a transaction (presumably, by accident, or due to attack).

Calling recoverHash(sig, ...) is sort of nonsensical. Although the variable is called "sig", it is just a hash of some data -- it hasn't been signed by anything.

If you are designing a new message signing scheme, I highly recommend using some kind of standard. If you want the simplest possible option, you could use EIP-191's "Version 0" message.

For that, you can use eth-account's encode_intended_validator(), which would look something like:

```<code>from eth_account.messages import encode_intended_validator
message = encode_intended_validator(YOUR_CONTRACT_ADDR, sig)
signed_message = w3.eth.account.sign_message(message, private_key=private_key)
</code>```

Body:
I am using this tutorial : https://web3py.readthedocs.io/en/stable/web3.eth.account.html#sign-a-message

##  in web3py

sig = Web3.soliditySha3( [uint256, address], [tokens, contractaddress] ) ## used below also
output: HexBytes('0x3efb3cf4e41109f6f1f998401d02dbe894719a8806f45e79a5fab7d4799f00bb')

from eth_account.messages import encode_defunct
msg = sig.hex()
message = encode_defunct(text=msg)
signed_message = w3.eth.account.sign_message(message, private_key=private_key)
signed_message

SignedMessage(messageHash=HexBytes('0x4c0c7077f770069785167e8b7451d63fad1e858ef5251b239eb0781c314000d2'), r=5665764915496639843348851536709769469640799172147461427941649091688603148258, s=48121517563314450138554207713326165180739298862566159641495137088718857193470, v=27, signature=HexBytes('0x0c86b594baa5bb06a0f4054ffdf3896377cfb757d42dcaeacf0241d96a4d5fe26a63d0514338ec600c89ee808dc088e7b3aadc55b9f5d86685d3ff212e2e47fe1b'))

When I pass these params such as signed_message.messageHash and signed_message.signature to the recoversigner(mentioned below) function in the smart contract. It gives the correct address. But when I am passing arguments tokens, contractaddress (used above) to the solidity keccak256(abi.encodePacked(token,address(this))) the message that is genarated is different from the signed_message.messageHash and in turn I get a different address as output from ecrecover.

I checked what is the output of keccak256(abi.encodePacked(..)).
I found It is same as sig value

What I have done:

Make an ERC20 token.

setup the channel

My goal:

sign messages (with web3py)

validate the signed message with solidity.

Like this:

user will pass some arguments : like contract address and number of tokens along with the signed message. and I will validate it with

    function splitSignature(bytes memory sig)
        pure
        internal
        returns (uint8 v, bytes32 r, bytes32 s)
    {
        require(sig.length == 65 , "invalid length");

        assembly {
            r := mload(add(sig, 32))
            s := mload(add(sig, 64))
            v := byte(0, mload(add(sig, 96)))
        }
        if (v < 27) {
            v += 27;
        }

        require(v == 27 || v == 28 , "value of v ");
        return (v, r, s);
    }

    function recoverSigner(bytes32 message, bytes memory sig)
        internal
        pure
        returns (address)
    {
        (uint8 v, bytes32 r, bytes32 s) = splitSignature(sig);
        return ecrecover(message, v, r, s);
    }

bytes32 message = prefixed(keccak256(abi.encodePacked(token,address(this))));

This is not working properly. I am not getting the correct address as output.

Please help..

Body:
I'm not entirely clear on what you're trying to do, but an important clarification to make here is that Web3's eth.sign (and its underlying JSON-RPC call eth_sign) do not sign a simple hash. It adds a prefix string, with a length embedded.

See the eth_sign docs:

The sign method calculates an Ethereum specific signature with: sign(keccak256("\x19Ethereum Signed Message:\n" + len(message) + message))).

By adding the prefix to the passed message, your client makes sure that you aren't using eth_sign to sign a transaction (presumably, by accident, or due to attack).

Calling recoverHash(sig, ...) is sort of nonsensical. Although the variable is called "sig", it is just a hash of some data -- it hasn't been signed by anything.

If you are designing a new message signing scheme, I highly recommend using some kind of standard. If you want the simplest possible option, you could use EIP-191's "Version 0" message.

For that, you can use eth-account's encode_intended_validator(), which would look something like:

from eth_account.messages import encode_intended_validator
message = encode_intended_validator(YOUR_CONTRACT_ADDR, sig)
signed_message = w3.eth.account.sign_message(message, private_key=private_key)


问:
Do a dry run to see if a database row is locked or not
Let's say I am trying to execute the following UPDATE statement in mysql (Innodb):

```<code>UPDATE main SET name = "Ralph" WHERE rowid=19283
</code>```

Is there a way before doing this statement to see if there is a row/table-level lock on rowid=19283 before running this update? Or is the application strategy of dealing with deadlocks to catch the exception and then deal with them after the fact? I find that once a deadlock is reached, it's often impossible to update that row without some very loop-y logic, and so I'm seeing if the deadlock can be detected before the potential UPDATE/INSERT statement

答:
A common pattern is

```<code>BEGIN;
SELECT ... FOR UPDATE;  -- grab a lock on the row
... do some other processing, then eventually:
UPDATE ...   -- change the row (or maybe skip this in some cases)
COMMIT;
</code>```

This allows multiple connections to gracefully change that row, but without stepping on each other.

No, this does not eliminate deadlocks.  It may turn a deadlock into a "lock wait", which is fine.

And it is not quite a "dry run".  It moves the lock from the UPDATE back to the SELECT.  If there are other things going on in this, and the competing, transaction, there could be a deadlock.

If you have 2 connections doing that transaction at "exactly" the same time, one will wait until the other finishes.  (No deadlock.)

Body:
Let's say I am trying to execute the following UPDATE statement in mysql (Innodb):

UPDATE main SET name = "Ralph" WHERE rowid=19283

Is there a way before doing this statement to see if there is a row/table-level lock on rowid=19283 before running this update? Or is the application strategy of dealing with deadlocks to catch the exception and then deal with them after the fact? I find that once a deadlock is reached, it's often impossible to update that row without some very loop-y logic, and so I'm seeing if the deadlock can be detected before the potential UPDATE/INSERT statement

Body:
A common pattern is

BEGIN;
SELECT ... FOR UPDATE;  -- grab a lock on the row
... do some other processing, then eventually:
UPDATE ...   -- change the row (or maybe skip this in some cases)
COMMIT;

This allows multiple connections to gracefully change that row, but without stepping on each other.

No, this does not eliminate deadlocks.  It may turn a deadlock into a "lock wait", which is fine.

And it is not quite a "dry run".  It moves the lock from the UPDATE back to the SELECT.  If there are other things going on in this, and the competing, transaction, there could be a deadlock.

If you have 2 connections doing that transaction at "exactly" the same time, one will wait until the other finishes.  (No deadlock.)


问:
How can I set the y axis in radians in a Python plot?
I would like to write the radian units of the axes as proportional to \pi: something like

```<code>$\frac{\pi}{4}$, $\frac{\pi}{2}$, ...
</code>```

in place of

```<code>0.785, 1.5707 ...
</code>```

Is there any standard way?
As an example, what should I add to the following code?

```<code>from pylab import *

x=arange(-10.0,10.0,0.1)
y= arctan(x)

plot(x,y,'b.')
show()
</code>```

I found this example http://matplotlib.sourceforge.net/examples/units/radian_demo.html but it does not work because I don't have  basic_units module.

Thank you!

答:
I created a PyPi Package that can format and place ticks at multiples of fractions of pi.</p>

```<code>"""Show an example of using MultiplePi on the y-axis."""
import matplotlib.pyplot as plt
import numpy as np

from matplot_fmt_pi import MultiplePi

x = np.arange(-10.0, 10.0, 0.1)
y = np.arctan(x)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.set_title("MultiplePi formatting")
ax.plot(x, y, 'b.')

y_pi = y / np.pi
unit = 0.25
y_tick = np.arange(-0.5, 0.5 + unit, unit)

# New way
manager = MultiplePi(4)
ax.yaxis.set_major_locator(manager.locator())
ax.yaxis.set_major_formatter(manager.formatter())

# Other way
y_label2 = [r"$" + format(r, ".2g") + r"\pi$" for r in y_tick]
ax2 = ax.twinx()
ax2.set_yticks(y_tick * np.pi)
ax2.set_yticklabels(y_label2)

plt.savefig("./pi_y_axis.png", dpi=120)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to write the radian units of the axes as proportional to \pi: something like

$\frac{\pi}{4}$, $\frac{\pi}{2}$, ...

in place of

0.785, 1.5707 ...

Is there any standard way?
As an example, what should I add to the following code?

from pylab import *

x=arange(-10.0,10.0,0.1)
y= arctan(x)

plot(x,y,'b.')
show()

I found this example http://matplotlib.sourceforge.net/examples/units/radian_demo.html but it does not work because I don't have  basic_units module.

Thank you!

Body:
I created a PyPi Package that can format and place ticks at multiples of fractions of pi.

"""Show an example of using MultiplePi on the y-axis."""
import matplotlib.pyplot as plt
import numpy as np

from matplot_fmt_pi import MultiplePi

x = np.arange(-10.0, 10.0, 0.1)
y = np.arctan(x)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.set_title("MultiplePi formatting")
ax.plot(x, y, 'b.')

y_pi = y / np.pi
unit = 0.25
y_tick = np.arange(-0.5, 0.5 + unit, unit)

# New way
manager = MultiplePi(4)
ax.yaxis.set_major_locator(manager.locator())
ax.yaxis.set_major_formatter(manager.formatter())

# Other way
y_label2 = [r"$" + format(r, ".2g") + r"\pi$" for r in y_tick]
ax2 = ax.twinx()
ax2.set_yticks(y_tick * np.pi)
ax2.set_yticklabels(y_label2)

plt.savefig("./pi_y_axis.png", dpi=120)


问:
I am not getting image link in my firebase database even after following the firebase code example
The link saves perfectly fine in storage but doesn't save at all in database in any format.

```<code>  private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

                StoringTextToFirebaseStorage();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}
</code>```

This is my code where I should be saving the link, I am using the code from https://firebase.google.com/docs/storage/android/download-files#download_data_via_url

I believe the issue may be that postimagesreference is also responsible for generating a random id for the image in the storage but I am not sure as I made a copy of the reference called postimagesreference 1 and it still didn't work. Is there anything I'm missing for it to save to database properly? Should I insert the code in a different location?

Here is my entire code if need be:

public class PostActivity extends AppCompatActivity {

```<code>private Toolbar mToolbar;
private ProgressDialog loadingBar;

private ImageButton SelectPostImage;
private Button AddPostButton;
private EditText PostDescription;

private static final int Gallery_Pick = 1;
private Uri ImageUri;

private StorageReference PostsImagesReference;
//private StorageReference PostsImagesReference1;
private DatabaseReference PostsRef;
private FirebaseAuth mAuth;

private String Description;
private String saveCurrentDate;
private String saveCurrentTime;
private String postRandomName;
private String currentUserID;

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

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();

    PostsImagesReference = FirebaseStorage.getInstance().getReference();
    //PostsImagesReference1 = FirebaseStorage.getInstance().getReference();

    PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");

    SelectPostImage = (ImageButton) findViewById(R.id.select_post_image);
    AddPostButton = (Button) findViewById(R.id.add_post);
    PostDescription = (EditText) findViewById(R.id.post_description);
    loadingBar = new ProgressDialog(this);

    mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle("Update Post");

    SelectPostImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            OpenGallery();

        }
    });

    AddPostButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            ValidatePostInfo();
        }
    });

}

private void ValidatePostInfo()
{
    Description = PostDescription.getText().toString();

    if(ImageUri == null)
    {
        Toast.makeText(this, "Please select image", Toast.LENGTH_SHORT).show();
    }
    else if(TextUtils.isEmpty(Description))
    {
        Toast.makeText(this, "Please say something about your image", Toast.LENGTH_SHORT).show();
    }
    else
    {
        loadingBar.setTitle("Post Uploading");
        loadingBar.setMessage("Please Wait");
        loadingBar.show();
        loadingBar.setCanceledOnTouchOutside(true);

        StoringImageToFirebaseStorage();

    }
}

private void StoringTextToFirebaseStorage()
{

    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    HashMap postsMap = new HashMap();
    postsMap.put("uid", currentUserID);
    postsMap.put("date", saveCurrentDate);
    postsMap.put("time", saveCurrentTime);
    postsMap.put("description", Description);
    postsMap.put("image", PostsImagesReference);

    PostsRef.child(currentUserID + postRandomName).updateChildren(postsMap)
            .addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if (task.isSuccessful())
                    {

                        SendUserToMainActivity();
                        Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }

            });

}

private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

                StoringTextToFirebaseStorage();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}

private void OpenGallery()
{
    Intent galleryIntent = new Intent();
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    galleryIntent.setType("image/*");
    startActivityForResult(galleryIntent, Gallery_Pick);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
    {
        ImageUri = data.getData();
        SelectPostImage.setImageURI(ImageUri);
    }
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
    int id = item.getItemId();

    if(id == android.R.id.home)
    {
        SendUserToMainActivity();
    }

    return super.onOptionsItemSelected(item);
}

private void SendUserToMainActivity()
{
    Intent mainIntent = new Intent(PostActivity.this, MainActivity.class);
    startActivity(mainIntent);
}
</code>```

}

My dependencies:

```<code>implementation fileTree(dir: 'libs', include: ['*.jar'])

        implementation 'androidx.appcompat:appcompat:1.1.0'
        implementation 'com.google.android.material:material:1.1.0'
        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
        implementation 'com.google.firebase:firebase-auth:17.0.0'
        implementation 'com.google.firebase:firebase-database:17.0.0'
        implementation 'com.google.firebase:firebase-storage:17.0.0'
        implementation 'com.squareup.picasso:picasso:2.71828'
        testImplementation 'junit:junit:4.12'
        implementation 'com.firebaseui:firebase-ui-database:6.2.1'
        androidTestImplementation 'androidx.test.ext:junit:1.1.1'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
        implementation 'com.google.firebase:firebase-messaging:20.2.0'
        implementation 'com.google.firebase:firebase-firestore:19.0.0'

        implementation 'com.android.support:multidex:2.0.1'
</code>```

答:
Within

```<code> @Override

            public void onSuccess(Uri uri)
            {
                     String downloadUrl = uri.toString();
                     DatabaseReference db = FirebaseDatabase.getInstance().getReference();
                     db.child("users").child("pics").setValue(downloadUrl);

            }
</code>```

The uri.toString(); will be your download url :)

```<code>private void StoringTextToFirebaseStorage(Uri downloadUrl)
{

    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    HashMap postsMap = new HashMap();
    postsMap.put("uid", currentUserID);
    postsMap.put("date", saveCurrentDate);
    postsMap.put("time", saveCurrentTime);
    postsMap.put("description", Description);
    postsMap.put("image", downloadUrl.toString());

    PostsRef.child(currentUserID + postRandomName).updateChildren(postsMap)
            .addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if (task.isSuccessful())
                    {

                        SendUserToMainActivity();
                        Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }

            });

}

private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {
                      StoringTextToFirebaseStorage(uri);

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}
</code>```

Body:
The link saves perfectly fine in storage but doesn't save at all in database in any format.

  private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

                StoringTextToFirebaseStorage();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}

This is my code where I should be saving the link, I am using the code from https://firebase.google.com/docs/storage/android/download-files#download_data_via_url

I believe the issue may be that postimagesreference is also responsible for generating a random id for the image in the storage but I am not sure as I made a copy of the reference called postimagesreference 1 and it still didn't work. Is there anything I'm missing for it to save to database properly? Should I insert the code in a different location?

Here is my entire code if need be:

public class PostActivity extends AppCompatActivity {

private Toolbar mToolbar;
private ProgressDialog loadingBar;

private ImageButton SelectPostImage;
private Button AddPostButton;
private EditText PostDescription;

private static final int Gallery_Pick = 1;
private Uri ImageUri;

private StorageReference PostsImagesReference;
//private StorageReference PostsImagesReference1;
private DatabaseReference PostsRef;
private FirebaseAuth mAuth;

private String Description;
private String saveCurrentDate;
private String saveCurrentTime;
private String postRandomName;
private String currentUserID;

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

    mAuth = FirebaseAuth.getInstance();
    currentUserID = mAuth.getCurrentUser().getUid();

    PostsImagesReference = FirebaseStorage.getInstance().getReference();
    //PostsImagesReference1 = FirebaseStorage.getInstance().getReference();

    PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");

    SelectPostImage = (ImageButton) findViewById(R.id.select_post_image);
    AddPostButton = (Button) findViewById(R.id.add_post);
    PostDescription = (EditText) findViewById(R.id.post_description);
    loadingBar = new ProgressDialog(this);

    mToolbar = (Toolbar) findViewById(R.id.update_post_page_toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setTitle("Update Post");

    SelectPostImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            OpenGallery();

        }
    });

    AddPostButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v)
        {
            ValidatePostInfo();
        }
    });

}

private void ValidatePostInfo()
{
    Description = PostDescription.getText().toString();

    if(ImageUri == null)
    {
        Toast.makeText(this, "Please select image", Toast.LENGTH_SHORT).show();
    }
    else if(TextUtils.isEmpty(Description))
    {
        Toast.makeText(this, "Please say something about your image", Toast.LENGTH_SHORT).show();
    }
    else
    {
        loadingBar.setTitle("Post Uploading");
        loadingBar.setMessage("Please Wait");
        loadingBar.show();
        loadingBar.setCanceledOnTouchOutside(true);

        StoringImageToFirebaseStorage();

    }
}

private void StoringTextToFirebaseStorage()
{

    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    HashMap postsMap = new HashMap();
    postsMap.put("uid", currentUserID);
    postsMap.put("date", saveCurrentDate);
    postsMap.put("time", saveCurrentTime);
    postsMap.put("description", Description);
    postsMap.put("image", PostsImagesReference);

    PostsRef.child(currentUserID + postRandomName).updateChildren(postsMap)
            .addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if (task.isSuccessful())
                    {

                        SendUserToMainActivity();
                        Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }

            });

}

private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

                StoringTextToFirebaseStorage();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}

private void OpenGallery()
{
    Intent galleryIntent = new Intent();
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
    galleryIntent.setType("image/*");
    startActivityForResult(galleryIntent, Gallery_Pick);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode==Gallery_Pick && resultCode==RESULT_OK && data!=null)
    {
        ImageUri = data.getData();
        SelectPostImage.setImageURI(ImageUri);
    }
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
{
    int id = item.getItemId();

    if(id == android.R.id.home)
    {
        SendUserToMainActivity();
    }

    return super.onOptionsItemSelected(item);
}

private void SendUserToMainActivity()
{
    Intent mainIntent = new Intent(PostActivity.this, MainActivity.class);
    startActivity(mainIntent);
}

}

My dependencies:

implementation fileTree(dir: 'libs', include: ['*.jar'])

        implementation 'androidx.appcompat:appcompat:1.1.0'
        implementation 'com.google.android.material:material:1.1.0'
        implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
        implementation 'com.google.firebase:firebase-auth:17.0.0'
        implementation 'com.google.firebase:firebase-database:17.0.0'
        implementation 'com.google.firebase:firebase-storage:17.0.0'
        implementation 'com.squareup.picasso:picasso:2.71828'
        testImplementation 'junit:junit:4.12'
        implementation 'com.firebaseui:firebase-ui-database:6.2.1'
        androidTestImplementation 'androidx.test.ext:junit:1.1.1'
        androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
        implementation 'com.google.firebase:firebase-messaging:20.2.0'
        implementation 'com.google.firebase:firebase-firestore:19.0.0'

        implementation 'com.android.support:multidex:2.0.1'

Body:
Within

 @Override

            public void onSuccess(Uri uri)
            {
                     String downloadUrl = uri.toString();
                     DatabaseReference db = FirebaseDatabase.getInstance().getReference();
                     db.child("users").child("pics").setValue(downloadUrl);

            }

The uri.toString(); will be your download url :)

private void StoringTextToFirebaseStorage(Uri downloadUrl)
{

    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForDate.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    HashMap postsMap = new HashMap();
    postsMap.put("uid", currentUserID);
    postsMap.put("date", saveCurrentDate);
    postsMap.put("time", saveCurrentTime);
    postsMap.put("description", Description);
    postsMap.put("image", downloadUrl.toString());

    PostsRef.child(currentUserID + postRandomName).updateChildren(postsMap)
            .addOnCompleteListener(new OnCompleteListener()
            {
                @Override
                public void onComplete(@NonNull Task task)
                {
                    if (task.isSuccessful())
                    {

                        SendUserToMainActivity();
                        Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                    else
                    {
                        String message = task.getException().getMessage();
                        Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }

            });

}

private void StoringImageToFirebaseStorage()
{
    Calendar callForDate = Calendar.getInstance();
    SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
    saveCurrentDate = currentDate.format(callForDate.getTime());

    Calendar callForTime = Calendar.getInstance();
    SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
    saveCurrentTime  = currentTime.format(callForTime.getTime());

    postRandomName = saveCurrentDate + saveCurrentTime;

    final StorageReference filePath = PostsImagesReference.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");

    filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task)
        {
            if (task.isSuccessful())
            {
                SendUserToMainActivity();

                PostsImagesReference.child("Post Images").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
                {
                    @Override
                    public void onSuccess(Uri uri)
                    {
                      StoringTextToFirebaseStorage(uri);

                    }
                }).addOnFailureListener(new OnFailureListener()
                {
                    @Override
                    public void onFailure(@NonNull Exception exception) {
                        // Handle any errors
                    }
                });

                Toast.makeText(PostActivity.this, "Post Uploaded", Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();

            }
            else
            {
                String message = task.getException().getMessage();
                Toast.makeText(PostActivity.this, "Error Occurred: " + message, Toast.LENGTH_SHORT).show();
                loadingBar.dismiss();
            }
        }
    });
}


问:
jsonrpc4j mapping in spring doesn't work
I'm trying to use the jsonrpc4j json-rpc library. Unfortunately it doesn't work as expected...
In fact my service doesn't get mapped at all. Here is some of my servlet-context.xml, I am using AnnotationMethodHandlerAdapter (maybe this is the problem?):

```<code><bean id="assistenzaJsonService"
        class="it.jsoftware.jacciseweb.assistenza.jsonrpcservices.AssistenzaJSonServiceImpl"></bean>

    <bean name="/AssistenzaServices.json" class="com.googlecode.jsonrpc4j.spring.JsonServiceExporter">
        <property name="service" ref="assistenzaJsonService" />
        <property name="serviceInterface"
            value="it.jsoftware.jacciseweb.assistenza.jsonrpcservices.AssistenzaJSonService" />
    </bean>
</code>```

the application is mapped at hostname.com/Appname and if I try hostname.com/Appname/AssistenzaServices.json i get 404.

Clues?

答:
You cannot directly hit AssistenzaServices.json. If you do so you will definitely get 404.
You are missing JSONrpc-spring flow.

Instead of hitting AssistenzaServices.json in the browser you will hit AssistenzaServices.html or something like this as you configure things. After you hit it the java class and dojo .js file mapped to AssistenzaServices.html will get in action. Dojo .js file serviceHandler will use AssistenzaServices.json to map a class to fetch results to show on AssistenzaServices.html.

Body:
I'm trying to use the jsonrpc4j json-rpc library. Unfortunately it doesn't work as expected...
In fact my service doesn't get mapped at all. Here is some of my servlet-context.xml, I am using AnnotationMethodHandlerAdapter (maybe this is the problem?):

<bean id="assistenzaJsonService"
        class="it.jsoftware.jacciseweb.assistenza.jsonrpcservices.AssistenzaJSonServiceImpl"></bean>

    <bean name="/AssistenzaServices.json" class="com.googlecode.jsonrpc4j.spring.JsonServiceExporter">
        <property name="service" ref="assistenzaJsonService" />
        <property name="serviceInterface"
            value="it.jsoftware.jacciseweb.assistenza.jsonrpcservices.AssistenzaJSonService" />
    </bean>

the application is mapped at hostname.com/Appname and if I try hostname.com/Appname/AssistenzaServices.json i get 404.

Clues?


问:
Combining frames with overlapping data in R
I'm working with a large frame that is comprised of many smaller frames that are constantly being updated. There is a row that had a unique identifier for all the values, however some values are NA since it is constantly being updated. Whenever I try merge the old frame and the new frame together, I get duplicate columns (ex. Age.x and Age.y) since I'm merging by the Id and nothing else.

Here is some data similar to what I am working with and what I am trying to get.

```<code>Frame1 <- data.frame(cbind("Id"=c("PS1001","PS1002","PS1003"), "Name"= c("Greg", "Paul", "Linda"), "Age"=c(14,NA, 43)))

Frame2 <- data.frame(cbind("Id"=c("PS1001","PS1002","PS1003", "PS1004"), "Name"= c(NA, "Paul", NA, "John"), "Age"=c(NA,51, 43, 31), "Housesize"= c(3,4,2,1)))

DesiredFrame <- data.frame(cbind("Id"=c("PS1001","PS1002","PS1003", "PS1004"), "Name"= c("Greg", "Paul", "Linda", "John"), "Age"=c(14,51, 43, 31), "Housesize"= c(3,4,2,1)))
</code>```

I have code that I will show below for fixing this issue, as I have run into it on some of my smaller frames, but I have about 80 variables I need to do this on for my full frame, so writing this out 80+ times is not feasible. (I also use the data.table library and have to convert the frames to data tables for this to work)

```<code>library(data.table)
Table1 <- setDT(Frame1)
Table2 <- setDT(Frame2)
CombinedTable <- merge(Table1, Table2, by="Id", all.y=TRUE)
CombinedTable$Age.x <- as.character(CombinedTable$Age.x)
CombinedTable$Age.y <- as.character(CombinedTable$Age.y)
CombinedTable[, Age := ifelse(!is.na(Age.x), Age.x, Age.y)]
CombinedTable[, `:=` (Age.x=NULL, Age.y=NULL)]
</code>```

Does anyone know of a simpler way to fix this issue? Whether that be a smoother merge or a way I could apply the singular fix I have listed above to all the variables in the frame.

答:
We can use fcoalesce after joining on 'Id'

```<code>library(data.table)
nm1 <- c('Name', 'Age')
setDT(Frame2)[Frame1, (nm1) := Map(fcoalesce,
       mget(nm1), mget(paste0('i.', nm1))), on =  .(Id)]
</code>```

Body:
I'm working with a large frame that is comprised of many smaller frames that are constantly being updated. There is a row that had a unique identifier for all the values, however some values are NA since it is constantly being updated. Whenever I try merge the old frame and the new frame together, I get duplicate columns (ex. Age.x and Age.y) since I'm merging by the Id and nothing else.

Here is some data similar to what I am working with and what I am trying to get.

Frame1 <- data.frame(cbind("Id"=c("PS1001","PS1002","PS1003"), "Name"= c("Greg", "Paul", "Linda"), "Age"=c(14,NA, 43)))

Frame2 <- data.frame(cbind("Id"=c("PS1001","PS1002","PS1003", "PS1004"), "Name"= c(NA, "Paul", NA, "John"), "Age"=c(NA,51, 43, 31), "Housesize"= c(3,4,2,1)))

DesiredFrame <- data.frame(cbind("Id"=c("PS1001","PS1002","PS1003", "PS1004"), "Name"= c("Greg", "Paul", "Linda", "John"), "Age"=c(14,51, 43, 31), "Housesize"= c(3,4,2,1)))

I have code that I will show below for fixing this issue, as I have run into it on some of my smaller frames, but I have about 80 variables I need to do this on for my full frame, so writing this out 80+ times is not feasible. (I also use the data.table library and have to convert the frames to data tables for this to work)

library(data.table)
Table1 <- setDT(Frame1)
Table2 <- setDT(Frame2)
CombinedTable <- merge(Table1, Table2, by="Id", all.y=TRUE)
CombinedTable$Age.x <- as.character(CombinedTable$Age.x)
CombinedTable$Age.y <- as.character(CombinedTable$Age.y)
CombinedTable[, Age := ifelse(!is.na(Age.x), Age.x, Age.y)]
CombinedTable[, `:=` (Age.x=NULL, Age.y=NULL)]

Does anyone know of a simpler way to fix this issue? Whether that be a smoother merge or a way I could apply the singular fix I have listed above to all the variables in the frame.

Body:
We can use fcoalesce after joining on 'Id'

library(data.table)
nm1 <- c('Name', 'Age')
setDT(Frame2)[Frame1, (nm1) := Map(fcoalesce,
       mget(nm1), mget(paste0('i.', nm1))), on =  .(Id)]


问:
namespace attributes not present in .outerHTML
In HTML5/JavaScript, if I create a namespaced dom node programmatically, like so:

```<code>svgElt = document.createElementNS("http://www.w3.org/2000/svg", 'svg')
</code>```

the node 'knows' it's own namespace, which I can retrieve like so:

```<code>svgElt.namespaceURI // result: "http://www.w3.org/2000/svg"
</code>```

But the namespace is not treated as a "normal" attribute:

```<code>svgElt.getAttribute('xmlns') // result: null
</code>```

So the behavior of the programmatically created node is different from the equivalent "straight" node

```<code><svg xmlns="http://www.w3.org/2000/svg" id="mySVG"></svg>
</code>```

for which .getAttribute works:

```<code>document.getElementById('mySVG').getAttribute('xmlns') // result: "http://www.w3.org/2000/svg"
</code>```

That is a potential problem when I use .outerHTML and need namespace information contained in the result. The namespace info might be lost for the programmatically created nodes, and I might have to add it manually; and this seems like a thing "I shouldn't have to care about" - thus the question.

An example where you need .outerHTML with namespace info in it is (see this question, Hubert OG 's answer) when you want to convert an inline SVG node into an Image by setting the image source to a data url , as in

```<code>'data:image/svg+xml,' + your_svg_element.outerHTML
</code>```

What I do is

```<code>svgNode.setAttribute('xmlns', svgNode.namespaceURI)
</code>```

SVG -> Image conversion (as I implemented it) doesn't work without this trick; see also my answer to the question linked above.

Is there a better / more elegant way to do this? What is the objective of svgElt.getAttribute('xmlns') returning null? Flaw or feature?

答:
Please read the comments under question first.

Here is how we get html with namespace info by "xhtml-ifying" the dom node, and then calling .outerHTML, which will then be xhtml (and have the namespace info the html is lacking).

```<code>function outerXHTML(node){
    var nsx = "http://www.w3.org/1999/xhtml";
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(node);
    return node.outerHTML;
}
function innerXHTML(node){
    var nsx = "http://www.w3.org/1999/xhtml";
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(node);
    return node.innerHTML;
}
</code>```

(clone node first if it should remain in original document.)

related question (x/html conversion)

related question (document creation)

fiddle for testing the html to xhtml conversion

test Kaiido version with arbitrary HTML string from textbox

Body:
In HTML5/JavaScript, if I create a namespaced dom node programmatically, like so:

svgElt = document.createElementNS("http://www.w3.org/2000/svg", 'svg')

the node 'knows' it's own namespace, which I can retrieve like so:

svgElt.namespaceURI // result: "http://www.w3.org/2000/svg"

But the namespace is not treated as a "normal" attribute:

svgElt.getAttribute('xmlns') // result: null

So the behavior of the programmatically created node is different from the equivalent "straight" node

<svg xmlns="http://www.w3.org/2000/svg" id="mySVG"></svg>

for which .getAttribute works:

document.getElementById('mySVG').getAttribute('xmlns') // result: "http://www.w3.org/2000/svg"

That is a potential problem when I use .outerHTML and need namespace information contained in the result. The namespace info might be lost for the programmatically created nodes, and I might have to add it manually; and this seems like a thing "I shouldn't have to care about" - thus the question.

An example where you need .outerHTML with namespace info in it is (see this question, Hubert OG 's answer) when you want to convert an inline SVG node into an Image by setting the image source to a data url , as in

'data:image/svg+xml,' + your_svg_element.outerHTML

What I do is

svgNode.setAttribute('xmlns', svgNode.namespaceURI)

SVG -> Image conversion (as I implemented it) doesn't work without this trick; see also my answer to the question linked above.

Is there a better / more elegant way to do this? What is the objective of svgElt.getAttribute('xmlns') returning null? Flaw or feature?

Body:
Please read the comments under question first.

Here is how we get html with namespace info by "xhtml-ifying" the dom node, and then calling .outerHTML, which will then be xhtml (and have the namespace info the html is lacking).

function outerXHTML(node){
    var nsx = "http://www.w3.org/1999/xhtml";
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(node);
    return node.outerHTML;
}
function innerXHTML(node){
    var nsx = "http://www.w3.org/1999/xhtml";
    var xdoc = document.implementation.createDocument(nsx, 'html');
    xdoc.documentElement.appendChild(node);
    return node.innerHTML;
}

(clone node first if it should remain in original document.)

related question (x/html conversion)

related question (document creation)

fiddle for testing the html to xhtml conversion

test Kaiido version with arbitrary HTML string from textbox


问:
How to proper integrate PrismJS into a Eleventy project?
I'm building a site using eleventy and want to include code examples with code-highlighting. Prism looks like a great choice for this. How would I add it proper to the build process (not as CDN)?</p>

答: Use the download option. This gives you the JS/CSS you need. Copy it to your site and ensure you are using the "Passthrough File Copy" (https://www.11ty.dev/docs/copy/) option to copy CSS and JS files over. </p>


问:
How to reload data in UIView
I am working on a project in which

As you can see that there is a horizontal view in which images are shown. I have provide facility of scroll. Therefore I have put UIView on UIScrollView than after UIButton on UIView. Images on UIButton come from plist. Problem is that when I delete the selected image from the plist I am unable to reload data so that deleted image is removed from horizontal view. Can anyone help me in reload data?

答:
The most straight forward solution for reloading the view is to remove all the subviews from the scroll view and then only add the ones that have a corresponding entry in the plist.

You could make a smarter reload that only removes the subviews that have been removed from the plist and then moves the other views, so that there's no gap left after those views. Shouldn't be too hard.

Title: How to reload data in UIView


问:
How enable ellipsis when calling Python doctest?
In Python (3.3.2) doctest, ellipsis (...) can match any string. So, for the code below

```<code>def foo():
    """
    >>> foo()
    hello ...
    """
    print("hello world")
</code>```

when running doctest it shouldn't raise any error. But

```<code>$ python -m doctest foo.py
**********************************************************************
File "./foo.py", line 3, in foo.foo
Failed example:
    foo()
Expected:
    hello ...
Got:
    hello world
**********************************************************************
1 items had failures:
   1 of   1 in foo.foo
***Test Failed*** 1 failures.
</code>```

What I must do to enable the ellipis? As far as I can tell it is disable by default.

I know that add # doctest: +ELLIPSIS, as in the code below, solve it, but I like to enable ellipsis for all tests.

```<code>def foo():
    """
    >>> foo() # doctest: +ELLIPSIS
    hello ...
    """
    print("hello world")
</code>```

答:
Since Python 3.4, you can pass the option with the -o flag:

```<code>$ python -m doctest -o=ELLIPSIS foo.py
</code>```

Source: https://docs.python.org/3/library/doctest.html#option-flags

Body:
In Python (3.3.2) doctest, ellipsis (...) can match any string. So, for the code below

def foo():
    """
    >>> foo()
    hello ...
    """
    print("hello world")

when running doctest it shouldn't raise any error. But

$ python -m doctest foo.py
**********************************************************************
File "./foo.py", line 3, in foo.foo
Failed example:
    foo()
Expected:
    hello ...
Got:
    hello world
**********************************************************************
1 items had failures:
   1 of   1 in foo.foo
***Test Failed*** 1 failures.

What I must do to enable the ellipis? As far as I can tell it is disable by default.

I know that add # doctest: +ELLIPSIS, as in the code below, solve it, but I like to enable ellipsis for all tests.

def foo():
    """
    >>> foo() # doctest: +ELLIPSIS
    hello ...
    """
    print("hello world")

Body:
Since Python 3.4, you can pass the option with the -o flag:

$ python -m doctest -o=ELLIPSIS foo.py

Source: https://docs.python.org/3/library/doctest.html#option-flags


问:
React/Node app in Heroku, serving index.html/index.js with server running
I'm pretty sure that this issue is localized to my start scripts. When looking online people will post differing start scripts.

Some have "start": "node index.js" -> (this won't start my server), gives an H10 error in heroku logs

Others have "start": "nodemon server.js" -> (this runs the server, serves the index.html, but it won't include the index.js file), no error given but not desired behavior

I used create-react-app, it works locally when i can do concurrent 'react-scripts start' and 'nodemon server', and my port is also set to the environment var.
let me know if I can provide extra info, and any help would be appreciated

Index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));
</code>```

Server.js

```<code>require('dotenv').config();

var express = require("express");
var app = express();
const cookieParser = require('cookie-parser');
var withAuth = require('./middleware');
const path = require('path');
var PORT = process.env.PORT || 4090;

const {
    receivePublicToken,
    getTransactions,
    getBalance,
    putCat,
    getCat,
    logIn,
    isUser
} = require("../src/controllers/controller");

app.use(express.json());
app.use(cookieParser());

// Get the public token and exchange it for an access token
app.post("/auth/public_token", withAuth, receivePublicToken);// Get Transactions
app.get("/transactions", getTransactions);
app.get("/accounts/balance/get", getBalance);
app.post("/users/login", logIn);
app.post("/categories/post", putCat);
app.get("/categories/get", getCat);
app.get("/auth", withAuth, isUser);
app.get("/logout", (req, res) => {
    res.clearCookie('token').sendStatus(200);
})
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/index.html'))
});

app.listen(PORT, () => {
    console.log(`Server running on ${PORT}`);
});
</code>```

start script in package.json

```<code>"scripts": {
  "dev": "concurrently \"npm run start\" \"npm run start-client\"",
  "start-client": "react-scripts start"
  "start": "nodemon server/server.js",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject",
  "postinstall": "npm run build"
  }
</code>```

directory structure

答: Did you make a Procfile? If not, make a file named "Procfile" in your main directory, and add web: node Server.js to it. That should tell heroku what to do when it starts up.</p>

Body:
I'm pretty sure that this issue is localized to my start scripts. When looking online people will post differing start scripts.

Some have "start": "node index.js" -> (this won't start my server), gives an H10 error in heroku logs

Others have "start": "nodemon server.js" -> (this runs the server, serves the index.html, but it won't include the index.js file), no error given but not desired behavior

I used create-react-app, it works locally when i can do concurrent 'react-scripts start' and 'nodemon server', and my port is also set to the environment var.
let me know if I can provide extra info, and any help would be appreciated

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

Server.js

require('dotenv').config();

var express = require("express");
var app = express();
const cookieParser = require('cookie-parser');
var withAuth = require('./middleware');
const path = require('path');
var PORT = process.env.PORT || 4090;

const {
    receivePublicToken,
    getTransactions,
    getBalance,
    putCat,
    getCat,
    logIn,
    isUser
} = require("../src/controllers/controller");

app.use(express.json());
app.use(cookieParser());

// Get the public token and exchange it for an access token
app.post("/auth/public_token", withAuth, receivePublicToken);// Get Transactions
app.get("/transactions", getTransactions);
app.get("/accounts/balance/get", getBalance);
app.post("/users/login", logIn);
app.post("/categories/post", putCat);
app.get("/categories/get", getCat);
app.get("/auth", withAuth, isUser);
app.get("/logout", (req, res) => {
    res.clearCookie('token').sendStatus(200);
})
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/index.html'))
});

app.listen(PORT, () => {
    console.log(`Server running on ${PORT}`);
});

start script in package.json

"scripts": {
  "dev": "concurrently \"npm run start\" \"npm run start-client\"",
  "start-client": "react-scripts start"
  "start": "nodemon server/server.js",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject",
  "postinstall": "npm run build"
  }

directory structure


问:
How would I make it so I can enter what I want to use in lower and upper caps?. Example - sin/SIN, tan/TAN
```<code>import math

print("Trigonometry calculator")

trig_choices = "Sin", "Tan", "Cos"

trig_choices_pick = input("Choose (Sin,Cos,Tan): ")

if trig_choices_pick == "Tan":
    opposite_value = float(input("Opposite: "))
    adjacent_value = float(input("Adjacent: "))
    print(math.degrees(math.atan(opposite_value / adjacent_value)))

elif trig_choices_pick == "Sin":
    opposite_value = float(input("Opposite: "))
    hypotenuse_value = float(input("Hypotenuse: "))
    print(math.degrees(math.asin(opposite_value / hypotenuse_value)))

elif trig_choices_pick == "Cos":
    adjacent_value = float(input("Adjacent: "))
    hypotenuse_value = float(input("Hypotenuse: "))
    print(math.degrees(math.acos(adjacent_value / hypotenuse_value)))
</code>```

To add onto the question, how would I be able to enter both the short version of "Cos" and the long version "Cosine"?

答:
```<code>if trig_choices_pick[:3].lower() == "cos":
    # will match "COSINE", "cosine", "cos", etc
    ...
</code>```

Body:
import math

print("Trigonometry calculator")

trig_choices = "Sin", "Tan", "Cos"

trig_choices_pick = input("Choose (Sin,Cos,Tan): ")

if trig_choices_pick == "Tan":
    opposite_value = float(input("Opposite: "))
    adjacent_value = float(input("Adjacent: "))
    print(math.degrees(math.atan(opposite_value / adjacent_value)))

elif trig_choices_pick == "Sin":
    opposite_value = float(input("Opposite: "))
    hypotenuse_value = float(input("Hypotenuse: "))
    print(math.degrees(math.asin(opposite_value / hypotenuse_value)))

elif trig_choices_pick == "Cos":
    adjacent_value = float(input("Adjacent: "))
    hypotenuse_value = float(input("Hypotenuse: "))
    print(math.degrees(math.acos(adjacent_value / hypotenuse_value)))

To add onto the question, how would I be able to enter both the short version of "Cos" and the long version "Cosine"?


问:
Embeding V8 in C++ causes "unrecognized external symbol" errors related to libcpp
I am trying to embed v8 into my application (using Visual Studio 2019). First, I built it to x86 (ia32) debug static linked library. I also wanted it to be monolitic. There were some errors, but eventualy I managed and I succesfully built it. I ran v8 test after compiling and the result was good.
Next, I wanted to use it, so I included all the necessery header files and linked "v8_monolith.lib" library file. But when I try to compile my application, it gives me a lot (about 4500) of linking errors, precisely "unrecognized external symbol" related to libcpp (e.g. to "__libcpp_debug_function"). I am sure that I properly selected runtime library. I also was trying to recompile it for a few times, but it didn't help. I think that libcpp is working, because I don't have any problems using it.

Here is my args.gn file:

```<code>is_debug = true
target_cpu = "x86"
v8_enable_backtrace = true
v8_enable_slow_dchecks = true
v8_optimized_debug = false
is_component_build = false
v8_static_library = true
v8_monolithic = true
v8_use_external_startup_data = false
</code>```

答: Try adding use_custom_libcxx = false to args.gn, that should help.

Body:
I am trying to embed v8 into my application (using Visual Studio 2019). First, I built it to x86 (ia32) debug static linked library. I also wanted it to be monolitic. There were some errors, but eventualy I managed and I succesfully built it. I ran v8 test after compiling and the result was good.
Next, I wanted to use it, so I included all the necessery header files and linked "v8_monolith.lib" library file. But when I try to compile my application, it gives me a lot (about 4500) of linking errors, precisely "unrecognized external symbol" related to libcpp (e.g. to "__libcpp_debug_function"). I am sure that I properly selected runtime library. I also was trying to recompile it for a few times, but it didn't help. I think that libcpp is working, because I don't have any problems using it.

Here is my args.gn file:

is_debug = true
target_cpu = "x86"
v8_enable_backtrace = true
v8_enable_slow_dchecks = true
v8_optimized_debug = false
is_component_build = false
v8_static_library = true
v8_monolithic = true
v8_use_external_startup_data = false


问:
Having trouble returning 404 responses with asyncio/aiohttp
```<code>import time
import asyncio
import aiohttp

async def is_name_available(s, name):
    async with s.get("https://twitter.com/%s" % name) as res:
        if res.raise_for_status == 404:
            print('%s is available!' % name)
            return name

async def check_all_names(names):
    async with aiohttp.ClientSession(raise_for_status=True) as s:
        tasks = []
        for name in names:
            task = asyncio.create_task(is_name_available(s, name))
            tasks.append(task)
        return await asyncio.gather(*tasks)

def main():
    with open('names.txt') as in_file, open('available.txt', 'w') as out_file:
        names = [name.strip() for name in in_file]
        start_time = time.time()
        results = asyncio.get_event_loop().run_until_complete(check_all_names(names))
        results = [i for i in results if i]
        out_file.write('\n'.join(results))
        print(f'[ <? ] Checked {len(names)} words in {round(time.time()-start_time, 2)} second(s)')

if __name__ == '__main__':
    main()
</code>```

I cannot seem to figure out how to go about returning only 404'd links in is_name_available with this asyncio/aiohttp structure I'm using from another project of mine. I'm a beginner in python and any help is appreciated.

答:
This line is incorrect:

```<code>        if res.raise_for_status == 404:
</code>```

raise_for_status is a method, so you're supposed to call it, not compare it to a number (which will always return false). And in your case, you don't want to call raise_for_status in the first place because you don't want to raise an exception when encountering 404, but detect it. To detect 404, you can simply write:

```<code>        if res.status == 404:
</code>```

Also note that you don't want to specify raise_for_status=True because it will raise an exception for 404 before the if gets a chance to run.

Body:
import time
import asyncio
import aiohttp

async def is_name_available(s, name):
    async with s.get("https://twitter.com/%s" % name) as res:
        if res.raise_for_status == 404:
            print('%s is available!' % name)
            return name

async def check_all_names(names):
    async with aiohttp.ClientSession(raise_for_status=True) as s:
        tasks = []
        for name in names:
            task = asyncio.create_task(is_name_available(s, name))
            tasks.append(task)
        return await asyncio.gather(*tasks)

def main():
    with open('names.txt') as in_file, open('available.txt', 'w') as out_file:
        names = [name.strip() for name in in_file]
        start_time = time.time()
        results = asyncio.get_event_loop().run_until_complete(check_all_names(names))
        results = [i for i in results if i]
        out_file.write('\n'.join(results))
        print(f'[ <? ] Checked {len(names)} words in {round(time.time()-start_time, 2)} second(s)')

if __name__ == '__main__':
    main()

I cannot seem to figure out how to go about returning only 404'd links in is_name_available with this asyncio/aiohttp structure I'm using from another project of mine. I'm a beginner in python and any help is appreciated.

Body:
This line is incorrect:

        if res.raise_for_status == 404:

raise_for_status is a method, so you're supposed to call it, not compare it to a number (which will always return false). And in your case, you don't want to call raise_for_status in the first place because you don't want to raise an exception when encountering 404, but detect it. To detect 404, you can simply write:

        if res.status == 404:

Also note that you don't want to specify raise_for_status=True because it will raise an exception for 404 before the if gets a chance to run.


问:
Swift Combine Future with multiple values?
I may be going about this the wrong way, but I have a function with which I want to emit multiple values over time. But I don’t want it to start emitting until something is subscribed to that object. I’m coming to combine from RxSwift, so I’m basically trying to duplicated Observable.create() in the RxSwift world. The closest I have found is returning a Future, but futures only succeed or fail (so they are basically like a Single in RxSwift.) </p>

<p>Is there some fundamental thing I am missing here? My end goal is to make a function that processes a video file and emits progress events until it completes, then emits a URL for the completed file. </p>

答:
Generally you can use a PassthroughSubject to publish custom outputs. You can wrap a PassthroughSubject (or multiple PassthroughSubjects) in your own implementation of Publisher to ensure that only your process can send events through the subject.

Let's mock a VideoFrame type and some input frames for example purposes:

```<code>typealias VideoFrame = String
let inputFrames: [VideoFrame] = ["a", "b", "c"]
</code>```

Now we want to write a function that synchronously processes these frames. Our function should report progress somehow, and at the end, it should return the output frames. To report progress, our function will take a PassthroughSubject<Double, Never>, and send its progress (as a fraction from 0 to 1) to the subject:

```<code>func process(_ inputFrames: [VideoFrame], progress: PassthroughSubject<Double, Never>) -> [VideoFrame] {
    var outputFrames: [VideoFrame] = []
    for input in inputFrames {
        progress.send(Double(outputFrames.count) / Double(inputFrames.count))
        outputFrames.append("output for \(input)")
    }
    return outputFrames
}
</code>```

Okay, so now we want to turn this into a publisher. The publisher needs to output both progress and a final result. So we'll use this enum as its output:

```<code>public enum ProgressEvent<Value> {
    case progress(Double)
    case done(Value)
}
</code>```

Now we can define our Publisher type. Let's call it SyncPublisher, because when it receives a Subscriber, it immediately (synchronously) performs its entire computation.

```<code>public struct SyncPublisher<Value>: Publisher {
    public init(_ run: @escaping (PassthroughSubject<Double, Never>) throws -> Value) {
        self.run = run
    }

    public var run: (PassthroughSubject<Double, Never>) throws -> Value

    public typealias Output = ProgressEvent<Value>
    public typealias Failure = Error

    public func receive<Downstream: Subscriber>(subscriber: Downstream) where Downstream.Input == Output, Downstream.Failure == Failure {
        let progressSubject = PassthroughSubject<Double, Never>()
        let doneSubject = PassthroughSubject<ProgressEvent<Value>, Error>()
        progressSubject
            .setFailureType(to: Error.self)
            .map { ProgressEvent<Value>.progress($0) }
            .append(doneSubject)
            .subscribe(subscriber)
        do {
            let value = try run(progressSubject)
            progressSubject.send(completion: .finished)
            doneSubject.send(.done(value))
            doneSubject.send(completion: .finished)
        } catch {
            progressSubject.send(completion: .finished)
            doneSubject.send(completion: .failure(error))
        }
    }
}
</code>```

Now we can turn our process(_:progress:) function into a SyncPublisher like this:

```<code>let inputFrames: [VideoFrame] = ["a", "b", "c"]
let pub = SyncPublisher<[VideoFrame]> { process(inputFrames, progress: $0) }
</code>```

The run closure is { process(inputFrames, progress: $0) }. Remember that $0 here is a PassthroughSubject<Double, Never>, exactly what process(_:progress:) wants as its second argument.

When we subscribe to this pub, it will first create two subjects. One subject is the progress subject and gets passed to the closure. We'll use the other subject to publish either the final result and a .finished completion, or just a .failure completion if the run closure throws an error.

The reason we use two separate subjects is because it ensures that our publisher is well-behaved. If the run closure returns normally, the publisher publishes zero or more progress reports, followed by a single result, followed by .finished. If the run closure throws an error, the publisher publishes zero or more progress reports, followed by a .failed. There is no way for the run closure to make the publisher emit multiple results, or emit more progress reports after emitting the result.

At last, we can subscribe to pub to see if it works properly:

```<code>pub
    .sink(
        receiveCompletion: { print("completion: \($0)") },
        receiveValue: { print("output: \($0)") })
</code>```

Here's the output:

```<code>output: progress(0.0)
output: progress(0.3333333333333333)
output: progress(0.6666666666666666)
output: done(["output for a", "output for b", "output for c"])
completion: finished
</code>```

Body:
I may be going about this the wrong way, but I have a function with which I want to emit multiple values over time. But I don’t want it to start emitting until something is subscribed to that object. I’m coming to combine from RxSwift, so I’m basically trying to duplicated Observable.create() in the RxSwift world. The closest I have found is returning a Future, but futures only succeed or fail (so they are basically like a Single in RxSwift.)

Is there some fundamental thing I am missing here? My end goal is to make a function that processes a video file and emits progress events until it completes, then emits a URL for the completed file.

Body:
Generally you can use a PassthroughSubject to publish custom outputs. You can wrap a PassthroughSubject (or multiple PassthroughSubjects) in your own implementation of Publisher to ensure that only your process can send events through the subject.

Let's mock a VideoFrame type and some input frames for example purposes:

typealias VideoFrame = String
let inputFrames: [VideoFrame] = ["a", "b", "c"]

Now we want to write a function that synchronously processes these frames. Our function should report progress somehow, and at the end, it should return the output frames. To report progress, our function will take a PassthroughSubject<Double, Never>, and send its progress (as a fraction from 0 to 1) to the subject:

func process(_ inputFrames: [VideoFrame], progress: PassthroughSubject<Double, Never>) -> [VideoFrame] {
    var outputFrames: [VideoFrame] = []
    for input in inputFrames {
        progress.send(Double(outputFrames.count) / Double(inputFrames.count))
        outputFrames.append("output for \(input)")
    }
    return outputFrames
}

Okay, so now we want to turn this into a publisher. The publisher needs to output both progress and a final result. So we'll use this enum as its output:

public enum ProgressEvent<Value> {
    case progress(Double)
    case done(Value)
}

Now we can define our Publisher type. Let's call it SyncPublisher, because when it receives a Subscriber, it immediately (synchronously) performs its entire computation.

public struct SyncPublisher<Value>: Publisher {
    public init(_ run: @escaping (PassthroughSubject<Double, Never>) throws -> Value) {
        self.run = run
    }

    public var run: (PassthroughSubject<Double, Never>) throws -> Value

    public typealias Output = ProgressEvent<Value>
    public typealias Failure = Error

    public func receive<Downstream: Subscriber>(subscriber: Downstream) where Downstream.Input == Output, Downstream.Failure == Failure {
        let progressSubject = PassthroughSubject<Double, Never>()
        let doneSubject = PassthroughSubject<ProgressEvent<Value>, Error>()
        progressSubject
            .setFailureType(to: Error.self)
            .map { ProgressEvent<Value>.progress($0) }
            .append(doneSubject)
            .subscribe(subscriber)
        do {
            let value = try run(progressSubject)
            progressSubject.send(completion: .finished)
            doneSubject.send(.done(value))
            doneSubject.send(completion: .finished)
        } catch {
            progressSubject.send(completion: .finished)
            doneSubject.send(completion: .failure(error))
        }
    }
}

Now we can turn our process(_:progress:) function into a SyncPublisher like this:

let inputFrames: [VideoFrame] = ["a", "b", "c"]
let pub = SyncPublisher<[VideoFrame]> { process(inputFrames, progress: $0) }

The run closure is { process(inputFrames, progress: $0) }. Remember that $0 here is a PassthroughSubject<Double, Never>, exactly what process(_:progress:) wants as its second argument.

When we subscribe to this pub, it will first create two subjects. One subject is the progress subject and gets passed to the closure. We'll use the other subject to publish either the final result and a .finished completion, or just a .failure completion if the run closure throws an error.

The reason we use two separate subjects is because it ensures that our publisher is well-behaved. If the run closure returns normally, the publisher publishes zero or more progress reports, followed by a single result, followed by .finished. If the run closure throws an error, the publisher publishes zero or more progress reports, followed by a .failed. There is no way for the run closure to make the publisher emit multiple results, or emit more progress reports after emitting the result.

At last, we can subscribe to pub to see if it works properly:

pub
    .sink(
        receiveCompletion: { print("completion: \($0)") },
        receiveValue: { print("output: \($0)") })

Here's the output:

output: progress(0.0)
output: progress(0.3333333333333333)
output: progress(0.6666666666666666)
output: done(["output for a", "output for b", "output for c"])
completion: finished


问:
Validating JWT token before every API call
Currently I am working on a project in React which has protected routes (protected by JWT authorization).

Some pages are rendered differently, based on the user's permissions.
These permissions are encrypted in the token payload.

Since JWT tokens can be decrypted and altered, users could—in theory—alter the token in order to gain access to a page they really shouldn't have access to.
Because the token lost its validity, the backend server won't process any requests by that specific user, so no damage can be done.

I still don't want the user to be able to gain access to protected pages just by altering the JWT token. My solution to this problem would be to send a request to an endpoint which validates the token.
Depending on the endpoint's response a second API call would be made, which then would return the required data for the protected page.
If the validation endpoint returns that the token is no longer valid, the user would be redirected to a login page.

Login > Go to protected page > Validate token > Access protected page

Login > Alter received JWT token > Go to protected route > Validate token > Error > Login page

Now my question: is this a good approach to this problem? Is there a better way to do this?

Thank you very much in advance. :)

答:
JWT token has 3 parts:

Header

Payload

Signature

Signature is used to verify Header and Payload is not changed. So the attacker needs to create a new signature for the altered token. It is -in theory- nearly impossible to create a valid signature without your secret key.

The extra step you proposed doesn't do anything. If your client can alter the key successfully, she can easily bypass this step and make an API call to protected resources.

The token validation step should be done in the backend.

Login(front end) > Go to protected route(front end) > Validate token(back end) > Return protected page(back end)

Login(front end) > Alter received JWT token(front end) > Go to protected route(front end) > Validate token(back end) >  return error(back end)> Login page(front end)

Edit
To hide views from users in the front end:

You can validate JWT in the front end(using the public key) without making a request if you are using an asymmetrical key.

Or as you mentioned, you can create an endpoint to validate tokens.


问:
Contourplot in matplot showing incorrect linestyle
I'm plotting a 2D matrix, which has positive and negative values, in matplotlib using contourplot. It is supposed to show solid lines for positive values and dashed lines for negative values:

```<code>loc = matplotlib.ticker.MaxNLocator(20)
Z = psi
lvls = loc.tick_values(Z.min(), Z.max())
fig, ax = plt.subplots(figsize=(7,7))
cp = plt.contour(X, Y, Z, 20, colors='k', linestyles=where(lvls >= 0, "-", "--"))
plt.xlabel('X')
plt.ylabel('Y')
plt.clabel(cp, inline=True, fontsize=10)
plt.gca().set_aspect('equal', adjustable='box')
plt.title('Stream function - Re = ' + str(Re) + ', t = {:.2f}'.format((t)*dt))
plt.savefig('SF' + '_Re' + str(Re) + '_N' + str(nx) + '_o' + str(order) + '_SF' + '.png')
plt.close()
</code>```

However, this is what this code is plotting:

As you can see, there are dashed lines where it is supposed to show solid lines and solid lines where it is supposed to show dashed lines. Any ideas?

Edit: the code below works just fine:

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker

nx = 100
ny = 100

# Generate 2D mesh
x = 2*np.pi*np.arange(0,nx,1)/(nx)
#x = linspace(0,Lx,nx,endpoint=True)
y = 2*np.pi*np.arange(0,ny,1)/(ny)
#y = linspace(0,Ly,ny,endpoint=True)
X, Y = np.meshgrid(x, y,indexing='ij')

Z = -np.sin(X/2)*np.cos(Y**1.5)

loc = matplotlib.ticker.MaxNLocator(20)
lvls = loc.tick_values(Z.min(), Z.max())
fig, ax = plt.subplots(figsize=(7,7))
cp = plt.contour(X,Y,Z,20, colors='k', linestyles=np.where(lvls >= 0, "-", "--"))
plt.clabel(cp, inline=True, fontsize=10)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()
</code>```

The output:

答:
You should switch the order of the line styles. Currently, your condition will assign - (solid line) to contours where lvls >= 0 otherwise it will assign -- (dashed line). That's how the where argument works.

In pseudo form, np.where(condition, A, B) means if condition is True assign A else assign B

Your present code (Not desired):

```<code>linestyles=np.where(lvls >= 0, "-", "--")
</code>```

Right style (desired style):

```<code>linestyles=np.where(lvls >= 0, "--", "-")
</code>```

Body:
I'm plotting a 2D matrix, which has positive and negative values, in matplotlib using contourplot. It is supposed to show solid lines for positive values and dashed lines for negative values:

loc = matplotlib.ticker.MaxNLocator(20)
Z = psi
lvls = loc.tick_values(Z.min(), Z.max())
fig, ax = plt.subplots(figsize=(7,7))
cp = plt.contour(X, Y, Z, 20, colors='k', linestyles=where(lvls >= 0, "-", "--"))
plt.xlabel('X')
plt.ylabel('Y')
plt.clabel(cp, inline=True, fontsize=10)
plt.gca().set_aspect('equal', adjustable='box')
plt.title('Stream function - Re = ' + str(Re) + ', t = {:.2f}'.format((t)*dt))
plt.savefig('SF' + '_Re' + str(Re) + '_N' + str(nx) + '_o' + str(order) + '_SF' + '.png')
plt.close()

However, this is what this code is plotting:

As you can see, there are dashed lines where it is supposed to show solid lines and solid lines where it is supposed to show dashed lines. Any ideas?

Edit: the code below works just fine:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker

nx = 100
ny = 100

# Generate 2D mesh
x = 2*np.pi*np.arange(0,nx,1)/(nx)
#x = linspace(0,Lx,nx,endpoint=True)
y = 2*np.pi*np.arange(0,ny,1)/(ny)
#y = linspace(0,Ly,ny,endpoint=True)
X, Y = np.meshgrid(x, y,indexing='ij')

Z = -np.sin(X/2)*np.cos(Y**1.5)

loc = matplotlib.ticker.MaxNLocator(20)
lvls = loc.tick_values(Z.min(), Z.max())
fig, ax = plt.subplots(figsize=(7,7))
cp = plt.contour(X,Y,Z,20, colors='k', linestyles=np.where(lvls >= 0, "-", "--"))
plt.clabel(cp, inline=True, fontsize=10)
plt.gca().set_aspect('equal', adjustable='box')
plt.show()

The output:

Body:
You should switch the order of the line styles. Currently, your condition will assign - (solid line) to contours where lvls >= 0 otherwise it will assign -- (dashed line). That's how the where argument works.

In pseudo form, np.where(condition, A, B) means if condition is True assign A else assign B

Your present code (Not desired):

linestyles=np.where(lvls >= 0, "-", "--")

Right style (desired style):

linestyles=np.where(lvls >= 0, "--", "-")