问:
Onclick show div overlapping/hiding others
I'm trying to achieve 3 clickable
 that expand and hide/overlap others on click, while showing what's inside each clicked
. I only have JQuery as of right now.

My initial question is, what should I use? (Flexbox? CSS animation? React?)
Is it possible in vanilla html+css+js stack without having a bonky transition ?
I made an image to illustrate what I'm trying to say:

答:
First of all, you should write your script in the question when asking questions on stackoverflow. Because we must see what code do you have.

About your question, there are so many options. If you want to use jQuery:

HTML:

```<code><div class="group"></div>
<div class="group"></div>
<div class="group"></div>
</code>```

JavaScript:

```<code>$('.group').on('click', function(){
    $('.group').hide();
    $(this).show();
});
</code>```

If you want to make it with CSS, you can do something like:

HTML:

```<code><div class="group"></div>
<div class="group"></div>
<div class="group"></div>
</code>```

CSS:

```<code>.group{
    display: none;
}
.group:active{
    display: block;
}
</code>```

If you want to make some animation you can use CSS transition

Body:
First of all, you should write your script in the question when asking questions on stackoverflow. Because we must see what code do you have.

About your question, there are so many options. If you want to use jQuery:

HTML:

<div class="group"></div>
<div class="group"></div>
<div class="group"></div>

JavaScript:

$('.group').on('click', function(){
    $('.group').hide();
    $(this).show();
});

If you want to make it with CSS, you can do something like:

HTML:

<div class="group"></div>
<div class="group"></div>
<div class="group"></div>

CSS:

.group{
    display: none;
}
.group:active{
    display: block;
}

If you want to make some animation you can use CSS transition


来源: stackexchange

问:
Remove unwanted space inside a column while placing image at end in flutter?
am new for flutter development i have got struck in placing the image in corner of the column which i have shown in the image

Need to remove the spacing  which i have marked with arrow how to do this? now let me post what i tried so far:

```<code>Card(
                  margin: EdgeInsets.all(10),
                  clipBehavior: Clip.antiAlias,
                  shape: RoundedRectangleBorder(
                    side: BorderSide(color: Colors.white, width: 1),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  color: Colors.white,
                  child: Container(
                    width: MediaQuery.of(context).size.width / 2.3,
                    height: 200,
                    // color: Colors.pink,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          color: Colors.red,
                          child: Image.asset('assets/intersection_png.png',
                          fit: BoxFit.cover,),
                        )
                      ],
                    ),
                  ),
                )
</code>```

Thanks in advance!!

答:
wrap your Container widget with Expanded and use BoxFit.fill like this:

```<code> Expanded(
                  child: Container(
                    color: Colors.red,
                    child: Image.asset('assets/intersection_png.png',
                          fit: BoxFit.fill,
                    )
                  ),
                )
</code>```

example:

ContentLicense: CC BY-SA 4.0

Body:
am new for flutter development i have got struck in placing the image in corner of the column which i have shown in the image

Need to remove the spacing  which i have marked with arrow how to do this? now let me post what i tried so far:

Card(
                  margin: EdgeInsets.all(10),
                  clipBehavior: Clip.antiAlias,
                  shape: RoundedRectangleBorder(
                    side: BorderSide(color: Colors.white, width: 1),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  color: Colors.white,
                  child: Container(
                    width: MediaQuery.of(context).size.width / 2.3,
                    height: 200,
                    // color: Colors.pink,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      mainAxisSize: MainAxisSize.min,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          color: Colors.red,
                          child: Image.asset('assets/intersection_png.png',
                          fit: BoxFit.cover,),
                        )
                      ],
                    ),
                  ),
                )

Thanks in advance!!

Body:
wrap your Container widget with Expanded and use BoxFit.fill like this:

 Expanded(
                  child: Container(
                    color: Colors.red,
                    child: Image.asset('assets/intersection_png.png',
                          fit: BoxFit.fill,
                    )
                  ),
                )

example:


问:
How can I eliminate spacing between inline elements in CSS?
I have a div with a bunch of image tags inside, here is an example:

```<code><div style="margin: 0; padding: 0; border: 0;">
    <a href="/view/foo1"><img src="foo1.jpg" alt="Foo1" /></a>
    <a href="/view/foo2"><img src="foo2.jpg" alt="Foo2" /></a>
    <a href="/view/foo3"><img src="foo3.jpg" alt="Foo3" /></a>
</div>
</code>```

Because there is whitespace between the tags, browsers will display some whitespace between the images (Chrome decides on 4px). How can I tell the browser to show NO whitespace whatsoever between the images, without placing the > and < directly next to each other? I know letter-spacing applies in addition to what the browser decides to use, so that's useless even with a negative value. Basically I'm going for something like Twitter has at the bottom of their home page. I looked at their code and they're using an unordered list. I could just do that but I'd like the technical explanation for why there appears to be no way to eliminate the white space from between these images.

答:
If you for some reason want to do it:

without using floats, and;

without collapsing the whitespace in your HTML (which is the easiest solution, and for what it's worth, what Twitter is doing)

You can use the solution from here:

How to remove the space between inline-block elements?

I've refined it slightly since then.

See: http://jsfiddle.net/JVd7G/

letter-spacing: -1px is to fix Safari.

```<code>div {
    font-size: 0;
    letter-spacing: -1px
}

<div style="margin: 0; padding: 0; border: 0;">
    <a href="/view/foo1"><img src="http://dummyimage.com/64x64/444/fff" alt="Foo1" /></a>
    <a href="/view/foo2"><img src="http://dummyimage.com/64x68/888/fff" alt="Foo2" /></a>
    <a href="/view/foo3"><img src="http://dummyimage.com/64x72/bbb/fff" alt="Foo3" /></a>
</div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a div with a bunch of image tags inside, here is an example:

Because there is whitespace between the tags, browsers will display some whitespace between the images (Chrome decides on 4px). How can I tell the browser to show NO whitespace whatsoever between the images, without placing the > and < directly next to each other? I know letter-spacing applies in addition to what the browser decides to use, so that's useless even with a negative value. Basically I'm going for something like Twitter has at the bottom of their home page. I looked at their code and they're using an unordered list. I could just do that but I'd like the technical explanation for why there appears to be no way to eliminate the white space from between these images.

Body:
If you for some reason want to do it:

without using floats, and;

without collapsing the whitespace in your HTML (which is the easiest solution, and for what it's worth, what Twitter is doing)

You can use the solution from here:

How to remove the space between inline-block elements?

I've refined it slightly since then.

See: http://jsfiddle.net/JVd7G/

letter-spacing: -1px is to fix Safari.

div {
    font-size: 0;
    letter-spacing: -1px
}

<div style="margin: 0; padding: 0; border: 0;">
    <a href="/view/foo1"><img src="http://dummyimage.com/64x64/444/fff" alt="Foo1" /></a>
    <a href="/view/foo2"><img src="http://dummyimage.com/64x68/888/fff" alt="Foo2" /></a>
    <a href="/view/foo3"><img src="http://dummyimage.com/64x72/bbb/fff" alt="Foo3" /></a>
</div>


问:
Python compare part of string to list
I have multiple strings that looks like this:

```<code>“BPBA-SG790-NGTP-W-AU-BUN-3Y”
</code>```

I want to compare the string to my list and if part of the string is in the list, I want to get only the part that is found on the list as a new variable.

This is my code:

```<code>    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> ['770', '790', '1470', '1490']
</code>```

For example this is what I want to get:

```<code>    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> 790
</code>```

Any idea how to do this?

答:
You can use the in keyword from python:

```<code>mylist = ["770", "790", "1470", "1490"]
sq = "BPBA-SG790-NGTP-W-AU-BUN-3Y"
for i in mylist:
    if i in sq:
        print(i)

</code>```

The code iterates through the list and prints the list element if it is in the string

Title: Python compare part of string to list

Body:
I have multiple strings that looks like this:

“BPBA-SG790-NGTP-W-AU-BUN-3Y”

I want to compare the string to my list and if part of the string is in the list, I want to get only the part that is found on the list as a new variable.

This is my code:

    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> ['770', '790', '1470', '1490']

For example this is what I want to get:

    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> 790

Any idea how to do this?

Body:
You can use the in keyword from python:

mylist = ["770", "790", "1470", "1490"]
sq = "BPBA-SG790-NGTP-W-AU-BUN-3Y"
for i in mylist:
    if i in sq:
        print(i)

The code iterates through the list and prints the list element if it is in the string


问:
Is there any alternative to 'rawtohex' to insert data to a blob column in H2?
I have a Java application which connects to an Oracle database. One of the tables contains a blob column, which we populate using utl_raw.cast_to_raw, like this:

public class MyDAO extends JdbcDaoSupport {
    public void persist(String name, String data) {
        String sql = "insert into table (id, name, data) values " +
                     "(sequence.nextval, ?, utl_raw.cast_to_raw(?))";
        getJdbcTemplate().update(sql, [name, data]);
    }
}
```

<p>For some reason beyond my knowledge, we don't use Hibernate, JPA or anything like that in this application. Just plain SQL statements and Spring JDBC to execute them. (...) Anyway, the above method works fine. At least with Oracle.</p>

<p>I've set up an in-memory H2 database with minimal data, to use in our JUnit tests. But there is no <code>utl_raw</code> package in H2. Apparently, the way to go is to use the <code>rawtohex</code> function instead. It <em>kind of works</em>... but <strong>it doubles the data length</strong>. For example, if I persist the string <code>"TEST"</code> in the blob column and later I retrieve its value, it becomes <code>" T E S T"</code>. As a byte array, it would be <code>[0, 84, 0, 69, 0, 83, 0, 84]</code>. The H2 documentation states that this is supposed to happen:</p>

<blockquote>
  <p>Converts a string to the hex representation. 4 hex characters per string character are used.</p>
</blockquote>

<p>Weird. I guess it's that way to support UTF-16 strings (?), but I'm using UTF-8. It actually <em>corrupts</em> my data.</p>

<p><strong>Is there any other way to store the blob in H2?</strong> I've seen this answer where they suggest using a PreparedStatement, but then I'd have to handle the connection myself:</p>

<pre class="lang-java prettyprint-override"><code>super.getConnection().prepareStatement(/* ... */).executeUpdate();
// release the statement and the connection, handle exceptions
</code>```

Sure, it's not much uglier than what we have right now, but still, I'm very reluctant to change working production code only to make it compatible with our JUnit test setup.

Another option would be to retrieve the blob as if it were an UTF-16 string, so it will actually use 4 hexs per character. But again, I would be fixing the problem just for H2, and breaking it for Oracle instead.

Do I have any other choice? Is there any way I can tell the H2 database to use just 1 byte per character in rawtohex? Or perhaps another function I can use instead of rawtohex?

答:
I have been trying this using Liquibase at build time for populating an in memory H2 database.

I encountered the same space padding issue, but resolved it by switching from using RAWTOHEX to using StringToUTF8.

Body:
I have a Java application which connects to an Oracle database. One of the tables contains a blob column, which we populate using utl_raw.cast_to_raw, like this:

public class MyDAO extends JdbcDaoSupport {
    public void persist(String name, String data) {
        String sql = "insert into table (id, name, data) values " +
                     "(sequence.nextval, ?, utl_raw.cast_to_raw(?))";
        getJdbcTemplate().update(sql, [name, data]);
    }
}

For some reason beyond my knowledge, we don't use Hibernate, JPA or anything like that in this application. Just plain SQL statements and Spring JDBC to execute them. (...) Anyway, the above method works fine. At least with Oracle.

I've set up an in-memory H2 database with minimal data, to use in our JUnit tests. But there is no utl_raw package in H2. Apparently, the way to go is to use the rawtohex function instead. It kind of works... but it doubles the data length. For example, if I persist the string "TEST" in the blob column and later I retrieve its value, it becomes " T E S T". As a byte array, it would be [0, 84, 0, 69, 0, 83, 0, 84]. The H2 documentation states that this is supposed to happen:

Converts a string to the hex representation. 4 hex characters per string character are used.

Weird. I guess it's that way to support UTF-16 strings (?), but I'm using UTF-8. It actually corrupts my data.

Is there any other way to store the blob in H2? I've seen this answer where they suggest using a PreparedStatement, but then I'd have to handle the connection myself:

super.getConnection().prepareStatement(/* ... */).executeUpdate();
// release the statement and the connection, handle exceptions

Sure, it's not much uglier than what we have right now, but still, I'm very reluctant to change working production code only to make it compatible with our JUnit test setup.

Another option would be to retrieve the blob as if it were an UTF-16 string, so it will actually use 4 hexs per character. But again, I would be fixing the problem just for H2, and breaking it for Oracle instead.

Do I have any other choice? Is there any way I can tell the H2 database to use just 1 byte per character in rawtohex? Or perhaps another function I can use instead of rawtohex?


问:
Wildfly 17 enabling JMX remote on the same server gives logmanager errors
I’m looking to enable JMX to allow datadog to monitor our java JBoss wildfly systems but keep hitting runtime errors

I have set up the standalone.xml with

```<code><subsystem xmlns="urn:jboss:domain:jmx:1.3">
            <expose-resolved-model/>
            <expose-expression-model/>
            <remoting-connector use-management-endpoint="true"/>
</subsystem>
</code>```

And

```<code><interfaces>
    <interface name="management">
    <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>
</interface>
</code>```

As well as

```<code><socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>
</code>```

Then in my startup.sh i have added

```<code>JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote"
</code>```

But this gives me

java.lang.IllegalStateException: The LogManager was not properly
  installed (you must set the "java.util.logging.manager" system
  property to "org.jboss.logmanage r.LogManager")

This seems to be fairly common if I look at both here and on google but there seem to be different solutions depending on the version of wildfly.

I think I need to do something like
Set at the start of the standalone.conf

```<code>JBOSS_MODULES_SYSTEM_PKGS="org.jboss.logmanager"
</code>```

And then

```<code>JBOSS_HOME="/opt/wildfly"
JAVA_OPTS="$JAVA_OPTS -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Xbootclasspath/p:$JBOSS_HOME/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-2.1.11.Final.jar -Xbootclasspath/p:$JBOSS_HOME/modules/system/layers/base/org/jboss/log4j/logmanager/main/log4j-jboss-logmanager-1.2.0.Final.jar"
</code>```

At the end.

But I still get errors “Could not load Logmanager "org.jboss.logmanager.LogManager"”

Any advice would be appreciated.

答: Use the supplied jconsole.sh script in bin, don't try and build up the classpath by hand. You also need to use the custom service url. See the docs for details</p>

Body:
I’m looking to enable JMX to allow datadog to monitor our java JBoss wildfly systems but keep hitting runtime errors

I have set up the standalone.xml with

<subsystem xmlns="urn:jboss:domain:jmx:1.3">
            <expose-resolved-model/>
            <expose-expression-model/>
            <remoting-connector use-management-endpoint="true"/>
</subsystem>

And

<interfaces>
    <interface name="management">
    <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>
</interface>

As well as

<socket-binding name="management-http" interface="management" port="${jboss.management.http.port:9990}"/>

Then in my startup.sh i have added

JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote"

But this gives me

java.lang.IllegalStateException: The LogManager was not properly
  installed (you must set the "java.util.logging.manager" system
  property to "org.jboss.logmanage r.LogManager")

This seems to be fairly common if I look at both here and on google but there seem to be different solutions depending on the version of wildfly.

I think I need to do something like
Set at the start of the standalone.conf

JBOSS_MODULES_SYSTEM_PKGS="org.jboss.logmanager"

And then

JBOSS_HOME="/opt/wildfly"
JAVA_OPTS="$JAVA_OPTS -Djava.util.logging.manager=org.jboss.logmanager.LogManager -Xbootclasspath/p:$JBOSS_HOME/modules/system/layers/base/org/jboss/logmanager/main/jboss-logmanager-2.1.11.Final.jar -Xbootclasspath/p:$JBOSS_HOME/modules/system/layers/base/org/jboss/log4j/logmanager/main/log4j-jboss-logmanager-1.2.0.Final.jar"

At the end.

But I still get errors “Could not load Logmanager "org.jboss.logmanager.LogManager"”

Any advice would be appreciated.


问:
How can I make the corners of my bottom sheet dialog rounded?
I'm trying to make the top corners of my BottomSheetDialog rounded, but I haven't had any luck with anything online. This is what I would like for it to look like:

No matter what I've tried, I keep getting this:

I've tried the method here and using shapeAppearanceLargeComponent (what I'm using now).

Here is my code:

styles.xml

```<code> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ...
    <item name="shapeAppearanceLargeComponent">@style/CustomShapeAppearanceBottomSheetDialog</item>
</style>

<style name="CustomShapeAppearanceBottomSheetDialog" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSizeTopRight">16dp</item>
    <item name="cornerSizeTopLeft">16dp</item>
</style>
</code>```

BottomNavMenuFragment:

```<code>public class BottomNavMenuFragment extends BottomSheetDialogFragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bottom_nav_drawer, container, false);
    }
}
</code>```

And this is how I'm showing the fragment:

```<code>BottomNavMenuFragment navFragment = new BottomNavMenuFragment();
navFragment.show(getSupportFragmentManager(), navFragment.getTag());
</code>```

Nothing I seem to do works. Could someone point me in the right direction?

答: After messing around with the possible solutions people posted, I figured out that my code was working fine, but the corners of my NavigationView were obscuring the rounded corners of the drawer. After adding some padding, the rounded corners are displaying correctly.</p>

Body:
I'm trying to make the top corners of my BottomSheetDialog rounded, but I haven't had any luck with anything online. This is what I would like for it to look like:

No matter what I've tried, I keep getting this:

I've tried the method here and using shapeAppearanceLargeComponent (what I'm using now).

Here is my code:

styles.xml

BottomNavMenuFragment:

public class BottomNavMenuFragment extends BottomSheetDialogFragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bottom_nav_drawer, container, false);
    }
}

And this is how I'm showing the fragment:

BottomNavMenuFragment navFragment = new BottomNavMenuFragment();
navFragment.show(getSupportFragmentManager(), navFragment.getTag());

Nothing I seem to do works. Could someone point me in the right direction?


问:
How to access sub-collections across multiple documents within a single collection in firestore?
I have a database structure as follows (simplified for purposes of this question):

```<code>Collection: registrations
    -> Document: params = {someParameter: "value"}
    -> Document: user_01
        -> Sub-collection: orders
            -> Document: order_AA = {type: "Q1", address: {pincode: "000000", city:"Paris"}
            -> Document: order_AB = {type: "Q2", address: {pincode: "111111", city:"London"}
            ...
    -> Document: user_02
        -> Sub-collection: orders
            -> Document: order_AC = {type: "Q1", address: {pincode: "222222", city:"Berlin"}
            -> Document: order_AD = {type: "Q1", address: {pincode: "333333", city:"Paris"}
            ...
</code>```

What I want to do:
Obtain a list of all the orders across all users within the collection "registrations".
(please note that the number of "user" documents is variable over time, and also the number of "order" documents within the sub-collection)

In more words...
Query FireStore to find all the available documents (users) within the collection "registrations", and for each of these documents (users) find all the orders in their sub-collection named "orders".

How can I do this in the shortest steps (fewest queries)?

Also, is it essential for me to add a "dummy" field within each "user" document? I have read on StackOverflow that FireStore cannot query sub-collections unless the parent document has "regular" fields. Even after adding a dummy field, I was unable to get it to work.

My most recent effort has been:

```<code>let ordersList = [];
await firestore()
    .collection("registrations")
    .get()
    .then((collectionRef) => {
        collectionRef.forEach((userDoc) => {
            console.log("==", userDoc.id);
            if(userDoc.id.startsWith("user")) {
                userDoc.collections("orders")
                    .get()
                    .then((ordersSnapshot) => {
                        ordersSnapshot.forEach((orderDoc) => {
                            ordersList.push(orderDoc.data());
                        });
                    });
            }
        });
    })
    .catch(error => {
        console.log("Error in retrieving data!");
        console.log('Error: ', error);
    })
</code>```

I get the error:

Error:  [TypeError: userDoc.collections is not a function. (In
  'userDoc.collections("orders")', 'userDoc.collections' is undefined)]

答:
You can use a collection group query to query all documents among collections and subcollections with the same name.  So, for the subcollection "orders", you can query all documents in those collections using:

```<code>firestore().collectionGroup("orders").get()
</code>```

If you don't want all of the order documents, you will need to add a filter in the same way that you would any other query.  You can only filter using the fields available in each orders document (you can't filter per user unless you have a "user" field in the document to use).

I have read on StackOverflow that FireStore cannot query sub-collections unless the parent document has "regular" fields

This is not true.  There is no need to have a parent document in place to query its nested subcollections.

Body:
I have a database structure as follows (simplified for purposes of this question):

Collection: registrations
    -> Document: params = {someParameter: "value"}
    -> Document: user_01
        -> Sub-collection: orders
            -> Document: order_AA = {type: "Q1", address: {pincode: "000000", city:"Paris"}
            -> Document: order_AB = {type: "Q2", address: {pincode: "111111", city:"London"}
            ...
    -> Document: user_02
        -> Sub-collection: orders
            -> Document: order_AC = {type: "Q1", address: {pincode: "222222", city:"Berlin"}
            -> Document: order_AD = {type: "Q1", address: {pincode: "333333", city:"Paris"}
            ...

What I want to do:
Obtain a list of all the orders across all users within the collection "registrations".
(please note that the number of "user" documents is variable over time, and also the number of "order" documents within the sub-collection)

In more words...
Query FireStore to find all the available documents (users) within the collection "registrations", and for each of these documents (users) find all the orders in their sub-collection named "orders".

How can I do this in the shortest steps (fewest queries)?

Also, is it essential for me to add a "dummy" field within each "user" document? I have read on StackOverflow that FireStore cannot query sub-collections unless the parent document has "regular" fields. Even after adding a dummy field, I was unable to get it to work.

My most recent effort has been:

let ordersList = [];
await firestore()
    .collection("registrations")
    .get()
    .then((collectionRef) => {
        collectionRef.forEach((userDoc) => {
            console.log("==", userDoc.id);
            if(userDoc.id.startsWith("user")) {
                userDoc.collections("orders")
                    .get()
                    .then((ordersSnapshot) => {
                        ordersSnapshot.forEach((orderDoc) => {
                            ordersList.push(orderDoc.data());
                        });
                    });
            }
        });
    })
    .catch(error => {
        console.log("Error in retrieving data!");
        console.log('Error: ', error);
    })

I get the error:

Error:  [TypeError: userDoc.collections is not a function. (In
  'userDoc.collections("orders")', 'userDoc.collections' is undefined)]

Body:
You can use a collection group query to query all documents among collections and subcollections with the same name.  So, for the subcollection "orders", you can query all documents in those collections using:

firestore().collectionGroup("orders").get()

If you don't want all of the order documents, you will need to add a filter in the same way that you would any other query.  You can only filter using the fields available in each orders document (you can't filter per user unless you have a "user" field in the document to use).

I have read on StackOverflow that FireStore cannot query sub-collections unless the parent document has "regular" fields

This is not true.  There is no need to have a parent document in place to query its nested subcollections.


问:
Tensorflow: Why does Modulo (i.e. tf.math.floormod) not support unsigned integers?
From the Docs:

x:   A Tensor. Must be one of the following types: int32, int64,
  bfloat16, half, float32, float64.

Example:

```<code>x = tf.math.mod(tf.constant(4, tf.dtypes.uint64), tf.constant(2, tf.dtypes.uint64))

[...]

NotFoundError: Could not find valid device for node.
Node:{{node FloorMod}}
All kernels registered for op FloorMod :
  device='XLA_CPU'; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF]
  device='XLA_CPU_JIT'; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF]
  device='CPU'; T in [DT_DOUBLE]
  device='CPU'; T in [DT_FLOAT]
  device='CPU'; T in [DT_INT64]
  device='CPU'; T in [DT_INT32]
 [Op:FloorMod]
</code>```

答:
As you have pointed it out in the documentation as of now they only support these allowed datatypes.

```<code>int32, int64, bfloat16, half, float32, float64.
</code>```

Still, if you want to pass the uint64 values, you need to convert it using numPy from uint64 to int64 and pass the int64 value to the tf.math.mod like below.

```<code>import numpy
input = numpy.int64( numpy.uint64(your_number))
</code>```

You can raise an issue in Github for the same.

Body:
From the Docs:

x:   A Tensor. Must be one of the following types: int32, int64,
  bfloat16, half, float32, float64.

Example:

x = tf.math.mod(tf.constant(4, tf.dtypes.uint64), tf.constant(2, tf.dtypes.uint64))

[...]

NotFoundError: Could not find valid device for node.
Node:{{node FloorMod}}
All kernels registered for op FloorMod :
  device='XLA_CPU'; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF]
  device='XLA_CPU_JIT'; T in [DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64, DT_BFLOAT16, DT_HALF]
  device='CPU'; T in [DT_DOUBLE]
  device='CPU'; T in [DT_FLOAT]
  device='CPU'; T in [DT_INT64]
  device='CPU'; T in [DT_INT32]
 [Op:FloorMod]

Body:
As you have pointed it out in the documentation as of now they only support these allowed datatypes.

int32, int64, bfloat16, half, float32, float64.

Still, if you want to pass the uint64 values, you need to convert it using numPy from uint64 to int64 and pass the int64 value to the tf.math.mod like below.

import numpy
input = numpy.int64( numpy.uint64(your_number))

You can raise an issue in Github for the same.


问:
How do I create the expected output in this Arithmetic Operators problem on HackerRank?
I am a beginner in Python 3 and I am trying to practice more of my Python 3 skills by trying to solve  HackerRank problems but I am a little stuck on this one problem. I have already written some code but I am having trouble with getting the expected output. Can someone please help?

The instructions:

Read two integers from STDIN and print three lines where:

The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.

Output Format

Print the three lines as explained above.

Sample Input

```<code>3
2
</code>```

Sample Output

```<code>5
1
6
</code>```

Here is my code, I created three functions to add, subtract, and multiply the inputted numbers but I need to know how to write some code that will iterate through a list and make the outputted numbers move vertically:

```<code>def addition(a, b):
    print (a + b)

#Main
a = int(input())
b = int(input())
addition(a, b)

def subtraction (a, b):
    print (a - b)

#Main
a = int(input())
b = int(input())
subtraction(a, b)

def multiplication(a, b):
    print (a * b)

#Main
a = int(input())
b = int(input())
multiplication(a, b)
</code>```

答:
You can do it this way:

```<code>def addition(a, b):
    print (a + b)

def subtraction (a, b):
    print (a - b)

def multiplication(a, b):
    print (a * b)

a = int(input())
b = int(input())
addition(a, b)
subtraction(a, b)
multiplication(a, b)
</code>```

Input:

```<code>3
2
</code>```

Output:

```<code>5
1
6
</code>```

Body:
I am a beginner in Python 3 and I am trying to practice more of my Python 3 skills by trying to solve  HackerRank problems but I am a little stuck on this one problem. I have already written some code but I am having trouble with getting the expected output. Can someone please help?

The instructions:

Read two integers from STDIN and print three lines where:

The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.

Output Format

Print the three lines as explained above.

Sample Input

3
2

Sample Output

5
1
6

Here is my code, I created three functions to add, subtract, and multiply the inputted numbers but I need to know how to write some code that will iterate through a list and make the outputted numbers move vertically:

def addition(a, b):
    print (a + b)

#Main
a = int(input())
b = int(input())
addition(a, b)

def subtraction (a, b):
    print (a - b)

#Main
a = int(input())
b = int(input())
subtraction(a, b)

def multiplication(a, b):
    print (a * b)

#Main
a = int(input())
b = int(input())
multiplication(a, b)

Body:
You can do it this way:

def addition(a, b):
    print (a + b)

def subtraction (a, b):
    print (a - b)

def multiplication(a, b):
    print (a * b)

a = int(input())
b = int(input())
addition(a, b)
subtraction(a, b)
multiplication(a, b)

Input:

3
2

Output:

5
1
6


答:
Not sure I get your question, but the following should do the trick

```<code>[x for x in mylist if x in sq]
</code>```

It return you with a list of those elements of the list that appears in the string

Title: Python compare part of string to list

Body:
Not sure I get your question, but the following should do the trick

[x for x in mylist if x in sq]

It return you with a list of those elements of the list that appears in the string


问:
skimage.feature.greycomatrix only producing diagonal values
I am attempting to produce glcm on a trend-reduced digital elevation model. My current problem is that the output of skimage.feature.greycomatrix(image) only contains values in the diagonal entries of the matrix.

```<code>glcm = greycomatrix(image,distances=[1],levels=100,angles=[0] ,symmetric=True,normed=True)
</code>```

The image is quantized prior with the following code:

```<code>import numpy as np
from skimage.feature import greycomatrix
def quantize(raster):
    print("\n Quantizing \n")
    raster += (np.abs(np.min(raster)) + 1)
    mean = np.nanmean(raster.raster[raster.raster > 0])
    std = np.nanstd(raster.raster[raster.raster > 0])

    raster[raster == None] = 0 # set all None values to 0
    raster[np.isnan(raster)] = 0
    raster[raster > (mean + 1.5*std)] = 0
    raster[raster < (mean - 1.5*std)] = 0 # High pass filter
    raster[raster > 0] = raster[raster > 0] - (np.min(raster[raster > 0]) - 1)
    raster[raster>101] = 0
    raster = np.rint(raster)
    flat = np.ndarray.flatten(raster[raster > 0])
    range = np.max(flat) - np.min(flat)
    print("\n\nRaster Range: {}\n\n".format(range))
    raster = raster.astype(np.uint8)
    raster[raster > 101] = 0
</code>```

How would I go about making the glcm compute values outside of the diagonal matrix (i.e. just the frequencies of the values themselves), and is there something fundamentally wrong with my approach?

答:
If pixel intensities are correlated in an image, the co-occurrence of two similar levels is highly probable, and therefore the nonzero elements of the corresponding GLCM will concentrate around the main diagonal. In contrast, if pixel intensities are uncorrelated the nonzero elements of the GLCM will be spread all over the matrix. The following example makes this apparent:

import numpy as np
from skimage import data
import matplotlib.pyplot as plt
from skimage.feature import greycomatrix

x = data.brick()
y = data.gravel()

mx = greycomatrix(x, distances=[1], levels=256, angles=[0], normed=True)
my = greycomatrix(y, distances=[1], levels=256, angles=[0], normed=True)

fig, ax = plt.subplots(2, 2, figsize=(12, 8))
ax[0, 0].imshow(x, cmap='gray')
ax[0, 1].imshow(mx[:, :, 0, 0])
ax[1, 0].imshow(y, cmap='gray')
ax[1, 1].imshow(my[:, :, 0, 0])
```

Despite I haven't seen your raster image I'm guessing that the intensity changes very smoothly across the image returned by quantize, and hence the GLCM is mostly diagonal.

Body:
I am attempting to produce glcm on a trend-reduced digital elevation model. My current problem is that the output of skimage.feature.greycomatrix(image) only contains values in the diagonal entries of the matrix.

glcm = greycomatrix(image,distances=[1],levels=100,angles=[0] ,symmetric=True,normed=True)

The image is quantized prior with the following code:

import numpy as np
from skimage.feature import greycomatrix
def quantize(raster):
    print("\n Quantizing \n")
    raster += (np.abs(np.min(raster)) + 1)
    mean = np.nanmean(raster.raster[raster.raster > 0])
    std = np.nanstd(raster.raster[raster.raster > 0])

    raster[raster == None] = 0 # set all None values to 0
    raster[np.isnan(raster)] = 0
    raster[raster > (mean + 1.5*std)] = 0
    raster[raster < (mean - 1.5*std)] = 0 # High pass filter
    raster[raster > 0] = raster[raster > 0] - (np.min(raster[raster > 0]) - 1)
    raster[raster>101] = 0
    raster = np.rint(raster)
    flat = np.ndarray.flatten(raster[raster > 0])
    range = np.max(flat) - np.min(flat)
    print("\n\nRaster Range: {}\n\n".format(range))
    raster = raster.astype(np.uint8)
    raster[raster > 101] = 0

How would I go about making the glcm compute values outside of the diagonal matrix (i.e. just the frequencies of the values themselves), and is there something fundamentally wrong with my approach?

Body:
If pixel intensities are correlated in an image, the co-occurrence of two similar levels is highly probable, and therefore the nonzero elements of the corresponding GLCM will concentrate around the main diagonal. In contrast, if pixel intensities are uncorrelated the nonzero elements of the GLCM will be spread all over the matrix. The following example makes this apparent:

import numpy as np
from skimage import data
import matplotlib.pyplot as plt
from skimage.feature import greycomatrix

x = data.brick()
y = data.gravel()

mx = greycomatrix(x, distances=[1], levels=256, angles=[0], normed=True)
my = greycomatrix(y, distances=[1], levels=256, angles=[0], normed=True)

fig, ax = plt.subplots(2, 2, figsize=(12, 8))
ax[0, 0].imshow(x, cmap='gray')
ax[0, 1].imshow(mx[:, :, 0, 0])
ax[1, 0].imshow(y, cmap='gray')
ax[1, 1].imshow(my[:, :, 0, 0])

Despite I haven't seen your raster image I'm guessing that the intensity changes very smoothly across the image returned by quantize, and hence the GLCM is mostly diagonal.


问:
Read 16-bit PNG image file using Python
I'm trying to read a PNG image file written in 16-bit data type. The data should be converted to a NumPy array. But I have no idea how to read the file in '16-bit'. I tried with PIL and SciPy, but they converted the 16-bit data to 8-bit when they load it. Could anyone please let me know how to read data from a 16-bit PNG file and convert it to NumPy array without changing the datatype?

The following is the script that I used.

```<code>from scipy import misc
import numpy as np
from PIL import Image
#make a png file
a = np.zeros((1304,960), dtype=np.uint16)
a[:] = np.arange(960)
misc.imsave('16bit.png',a)

#read the png file using scipy
b = misc.imread('16bit.png')
print "scipy:" ,b.dtype

#read the png file using PIL
c = Image.open('16bit.png')
d = np.array(c)
print "PIL:", d.dtype

</code>```

答:
I'd recommend using opencv:

pip install opencv-python
```

<p>and</p>

<pre class="lang-py prettyprint-override"><code>import cv2
image = cv2.imread('16bit.png', cv2.IMREAD_UNCHANGED)

</code>```

in contrast to OpenImageIO, opencv could be installed from pip

The time, required to read a single 4000x4000 png is about the same as PIL, but PIL uses more CPU and requires additional time to convert data back to uint16.

Title: Read 16-bit PNG image file using Python

Body:
I'm trying to read a PNG image file written in 16-bit data type. The data should be converted to a NumPy array. But I have no idea how to read the file in '16-bit'. I tried with PIL and SciPy, but they converted the 16-bit data to 8-bit when they load it. Could anyone please let me know how to read data from a 16-bit PNG file and convert it to NumPy array without changing the datatype?

The following is the script that I used.

from scipy import misc
import numpy as np
from PIL import Image
#make a png file
a = np.zeros((1304,960), dtype=np.uint16)
a[:] = np.arange(960)
misc.imsave('16bit.png',a)

#read the png file using scipy
b = misc.imread('16bit.png')
print "scipy:" ,b.dtype

#read the png file using PIL
c = Image.open('16bit.png')
d = np.array(c)
print "PIL:", d.dtype

Body:
I'd recommend using opencv:

pip install opencv-python

and

import cv2
image = cv2.imread('16bit.png', cv2.IMREAD_UNCHANGED)

in contrast to OpenImageIO, opencv could be installed from pip

The time, required to read a single 4000x4000 png is about the same as PIL, but PIL uses more CPU and requires additional time to convert data back to uint16.


问:
CefSharp - Change Loading Screen Background Color
Is it possible to change the loading screen color on CEFSharp. Like Chrome, when loading a new url it will show a white page until its loaded and rendered. Is it possible to change this loading color to black?

With CEF directly, there seems to be a command line argument: --background-color=black (Source https://bitbucket.org/chromiumembedded/cef/issues/1984/momentary-white-flash-with-osr-in#comment-33637201)

But there doesn't seem to be a way to do this with CEFSharp Directly.

答:
On button click:

Dim script="document.body.style.backgroundcolor='black';"

Browser.executescriptasync(script)

//that is if u using vb


问:
Pandas - String Concatenation with Array column
I am trying to make a new string from two columns in my dataframe. One of my columns contains 1 value. The other column contains an array. The end result should look like the third column below.

```<code>  Alpha  Val                Result
0   A    ['1, 2, 3']    ['A1', 'A2', 'A3']
</code>```

I had tried list comprehension but it just returns an error "can only concatenate str (not "list") to str"

[alpha + val for alpha in df['Alpha'].str.split(",") for val in df['Val'].str.split(",")]

This kind of like a 1X1 matrix by a 1X3 matrix (but concatenating the strings) but I'm not sure how to achieve this using pandas.

答:
```<code>import pandas as pd

df = pd.DataFrame({'Alpha':['A', 'B'],
                  'Val':[['1, 2, 3'], ['4, 5, 6, 7']]})

def newlist(A,B):
    return [A + i.strip() for i in B[0].split(',')]

df['Result'] = df.apply(lambda x: newlist(x.Alpha, x.Val), axis=1)

</code>```

Body:
I am trying to make a new string from two columns in my dataframe. One of my columns contains 1 value. The other column contains an array. The end result should look like the third column below.

  Alpha  Val                Result
0   A    ['1, 2, 3']    ['A1', 'A2', 'A3']

I had tried list comprehension but it just returns an error "can only concatenate str (not "list") to str"

[alpha + val for alpha in df['Alpha'].str.split(",") for val in df['Val'].str.split(",")]

This kind of like a 1X1 matrix by a 1X3 matrix (but concatenating the strings) but I'm not sure how to achieve this using pandas.


问:
JS why FOR LOOP not iterating when condition is A&&B but works when B&&A (A==B==true)
This is my first question so hello everyone!

I wanted to write condition in way to terminate loop ASAP.

Loop which doesn`t work but should terminate loop faster:

```<code>for (
      let i = 0;
      transactionsSortedByTime[i].unixTime <= unixEndTime && i < listLength;
      i++
    ) {}
</code>```

Loop which works:

```<code>for (
      let i = 0;
       i < listLength && transactionsSortedByTime[i].unixTime <= unixEndTime;
      i++
    ) {}
</code>```

Till now I was certain that results of A&&B and B&&A are the same but terminates with false result in different time (when one of them {A or B} is false).

My question is why second one loop iterates properly while first one doesn`t.

答:
In your case, A & B is not same as B & A because in first code snippet, you are accessing the i'th index of transactionsSortedByTime array before checking if i is less then listLength. Doing this will give you undefined when i < listLength is false.

So i < listLength should be written before transactionsSortedByTime[i].unixTime <= unixEndTime to make sure your code doesn't tries to access an index that is out of bounds of the transactionsSortedByTime array.

Body:
This is my first question so hello everyone!

I wanted to write condition in way to terminate loop ASAP.

Loop which doesn`t work but should terminate loop faster:

for (
      let i = 0;
      transactionsSortedByTime[i].unixTime <= unixEndTime && i < listLength;
      i++
    ) {}

Loop which works:

for (
      let i = 0;
       i < listLength && transactionsSortedByTime[i].unixTime <= unixEndTime;
      i++
    ) {}

Till now I was certain that results of A&&B and B&&A are the same but terminates with false result in different time (when one of them {A or B} is false).

My question is why second one loop iterates properly while first one doesn`t.


问:
On push message open crash iOS
I had crash when open push notification. crash log from apple. where is a problem

Help read this log

I just open "OrderDetailsVC" when user open push

```<code>xception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001028b15f8
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [870]
Triggered by Thread:  0

Thread 0 name:
Thread 0 Crashed:
0   Moitane                         0x00000001028b15f8 OrderDetailsVC.viewDidLoad() + 268 (OrderDetailsVC.swift:144)
1   Moitane                         0x00000001028b1618 @objc OrderDetailsVC.viewDidLoad() + 28 (<compiler-generated>:0)
2   UIKitCore                       0x00000001bdf7ae08 -[UIViewController _sendViewDidLoadWithAppearanceProxyObjectTaggingEnabled] + 100 (UIViewController.m:2283)
3   UIKitCore                       0x00000001bdf7f898 -[UIViewController loadViewIfRequired] + 936 (UIViewController.m:3382)
4   UIKitCore                       0x00000001bdf7fca0 -[UIViewController view] + 28 (UIViewController.m:3404)
5   UIKitCore                       0x00000001bdedf528 -[UINavigationController _startCustomTransition:] + 1180 (UINavigationController.m:1893)
6   UIKitCore                       0x00000001bdef33f0 -[UINavigationController _startDeferredTransitionIfNeeded:] + 688 (UINavigationController.m:6719)
7   UIKitCore                       0x00000001bdef4790 -[UINavigationController __viewWillLayoutSubviews] + 172 (UINavigationController.m:6988)
8   UIKitCore                       0x00000001bded7cf0 -[UILayoutContainerView layoutSubviews] + 224 (UILayoutContainerView.m:86)
9   UIKitCore                       0x00000001bea6ec7c -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2144 (UIView.m:17176)
10  QuartzCore                      0x00000001c10084ac -[CALayer layoutSublayers] + 284 (CALayer.mm:9644)
11  QuartzCore                      0x00000001c100e604 CA::Layer::layout_if_needed(CA::Transaction*) + 468 (CALayer.mm:9518)
12  QuartzCore                      0x00000001c1019148 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 140 (CALayer.mm:2468)
13  QuartzCore                      0x00000001c0f61e34 CA::Context::commit_transaction(CA::Transaction*, double) + 296 (CAContextInternal.mm:1992)
14  QuartzCore                      0x00000001c0f8b7c4 CA::Transaction::commit() + 676 (CATransactionInternal.mm:438)
15  QuartzCore                      0x00000001c0f8c1d8 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 92 (CATransactionInternal.mm:890)
16  CoreFoundation                  0x00000001ba492fb8 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32 (CFRunLoop.c:1758)
17  CoreFoundation                  0x00000001ba48deac __CFRunLoopDoObservers + 420 (CFRunLoop.c:1868)
18  CoreFoundation                  0x00000001ba48e328 __CFRunLoopRun + 968 (CFRunLoop.c:2910)
19  CoreFoundation                  0x00000001ba48dc34 CFRunLoopRunSpecific + 424 (CFRunLoop.c:3192)
20  GraphicsServices                0x00000001c45d738c GSEventRunModal + 160 (GSEvent.c:2246)
21  UIKitCore                       0x00000001be5c022c UIApplicationMain + 1932 (UIApplication.m:4820)
22  Moitane                         0x0000000102887b70 main + 68 (LocalizableBtn.swift:19)
23  libdyld.dylib                   0x00000001ba315800 start + 4

</code>```

答:
Your viewDidLoad in OrderDetailsVC.swift (frames 1 and 2 of the stack trace) are the culprit:

```<code>0   Moitane                         0x00000001028b15f8 OrderDetailsVC.viewDidLoad() + 268 (OrderDetailsVC.swift:144)
1   Moitane                         0x00000001028b1618 @objc OrderDetailsVC.viewDidLoad() + 28 (<compiler-generated>:0)
</code>```

Title: On push message open crash iOS

Body:
I had crash when open push notification. crash log from apple. where is a problem

Help read this log

I just open "OrderDetailsVC" when user open push

xception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x00000001028b15f8
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [870]
Triggered by Thread:  0

Thread 0 name:
Thread 0 Crashed:
0   Moitane                         0x00000001028b15f8 OrderDetailsVC.viewDidLoad() + 268 (OrderDetailsVC.swift:144)
1   Moitane                         0x00000001028b1618 @objc OrderDetailsVC.viewDidLoad() + 28 (<compiler-generated>:0)
2   UIKitCore                       0x00000001bdf7ae08 -[UIViewController _sendViewDidLoadWithAppearanceProxyObjectTaggingEnabled] + 100 (UIViewController.m:2283)
3   UIKitCore                       0x00000001bdf7f898 -[UIViewController loadViewIfRequired] + 936 (UIViewController.m:3382)
4   UIKitCore                       0x00000001bdf7fca0 -[UIViewController view] + 28 (UIViewController.m:3404)
5   UIKitCore                       0x00000001bdedf528 -[UINavigationController _startCustomTransition:] + 1180 (UINavigationController.m:1893)
6   UIKitCore                       0x00000001bdef33f0 -[UINavigationController _startDeferredTransitionIfNeeded:] + 688 (UINavigationController.m:6719)
7   UIKitCore                       0x00000001bdef4790 -[UINavigationController __viewWillLayoutSubviews] + 172 (UINavigationController.m:6988)
8   UIKitCore                       0x00000001bded7cf0 -[UILayoutContainerView layoutSubviews] + 224 (UILayoutContainerView.m:86)
9   UIKitCore                       0x00000001bea6ec7c -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2144 (UIView.m:17176)
10  QuartzCore                      0x00000001c10084ac -[CALayer layoutSublayers] + 284 (CALayer.mm:9644)
11  QuartzCore                      0x00000001c100e604 CA::Layer::layout_if_needed(CA::Transaction*) + 468 (CALayer.mm:9518)
12  QuartzCore                      0x00000001c1019148 CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 140 (CALayer.mm:2468)
13  QuartzCore                      0x00000001c0f61e34 CA::Context::commit_transaction(CA::Transaction*, double) + 296 (CAContextInternal.mm:1992)
14  QuartzCore                      0x00000001c0f8b7c4 CA::Transaction::commit() + 676 (CATransactionInternal.mm:438)
15  QuartzCore                      0x00000001c0f8c1d8 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 92 (CATransactionInternal.mm:890)
16  CoreFoundation                  0x00000001ba492fb8 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32 (CFRunLoop.c:1758)
17  CoreFoundation                  0x00000001ba48deac __CFRunLoopDoObservers + 420 (CFRunLoop.c:1868)
18  CoreFoundation                  0x00000001ba48e328 __CFRunLoopRun + 968 (CFRunLoop.c:2910)
19  CoreFoundation                  0x00000001ba48dc34 CFRunLoopRunSpecific + 424 (CFRunLoop.c:3192)
20  GraphicsServices                0x00000001c45d738c GSEventRunModal + 160 (GSEvent.c:2246)
21  UIKitCore                       0x00000001be5c022c UIApplicationMain + 1932 (UIApplication.m:4820)
22  Moitane                         0x0000000102887b70 main + 68 (LocalizableBtn.swift:19)
23  libdyld.dylib                   0x00000001ba315800 start + 4

Body:
Your viewDidLoad in OrderDetailsVC.swift (frames 1 and 2 of the stack trace) are the culprit:

0   Moitane                         0x00000001028b15f8 OrderDetailsVC.viewDidLoad() + 268 (OrderDetailsVC.swift:144)
1   Moitane                         0x00000001028b1618 @objc OrderDetailsVC.viewDidLoad() + 28 (<compiler-generated>:0)


问:
Jenkins fails while copying the repo despite correct credentials
unfortunately my build fails every time.

The copy process is apparently always supposed to fail.
But this user on Jenkins has 100% access to the repo.
I can exclude this error to 100%.

Does anyone know what caused it?

```<code>        using GIT_ASKPASS to set credentials for Bitbucket Notifier plugin and Nexus service
     > git.exe fetch --tags --progress -- https://URL/bitbucket/test.git +refs/heads/*:refs/remotes/origin/* # timeout=10
    ERROR: Timeout after 10 minutes
    ERROR: Error fetching remote repo 'origin'
   ....
    stderr: Logon failed, use ctrl+c to cancel basic credential prompt.
    remote: Counting objects: 1
    remote: Counting objects: 4198, done.
    remote: Compressing objects:   0% (1/2939)
    ...
    remote: Compressing objects:  99% (2935/2939)

    ...
    Finished: FAILURE
</code>```

Thank you.

答:
The issue is here :

ERROR: Timeout after 10 minutes

ERROR: Error fetching remote repo 'origin'

What you have to do is, update your SCM configuration where you have put down Bitbucket Repo details. There will be a setting for "timeout", its set to 10 be default if I remember correctly.

You can keep it blank so that timeout won't occur.

Body:
unfortunately my build fails every time.

The copy process is apparently always supposed to fail.
But this user on Jenkins has 100% access to the repo.
I can exclude this error to 100%.

Does anyone know what caused it?

        using GIT_ASKPASS to set credentials for Bitbucket Notifier plugin and Nexus service
     > git.exe fetch --tags --progress -- https://URL/bitbucket/test.git +refs/heads/*:refs/remotes/origin/* # timeout=10
    ERROR: Timeout after 10 minutes
    ERROR: Error fetching remote repo 'origin'
   ....
    stderr: Logon failed, use ctrl+c to cancel basic credential prompt.
    remote: Counting objects: 1
    remote: Counting objects: 4198, done.
    remote: Compressing objects:   0% (1/2939)
    ...
    remote: Compressing objects:  99% (2935/2939)

    ...
    Finished: FAILURE

Thank you.


问:
How can I implement this more efficiently
So I have a function (I'm writing this in a pseudo-functional language, I hope its clear):

```<code>dampen (lr : Num, x : Num) = x + lr*(1-x)
</code>```

And I wish to apply this n times to a value x.  I could implement it recursively:

```<code>dampenN (0, lr, x) = dampen(lr, x)
dampenN (n, lr, x) = dampenN(n-1, lr, dampen(x))
</code>```

But there must be a way I can do it mathematically without resorting to an iterative procedure (recursive, or a loop).

Unfortunately my algebra skills are rusty beyond belief, can anyone help?

答:
We can eliminate the series from your formula entirely.

We are given:

```<code>x_(n+1) = x_n + lr(1-x_n)
</code>```

This can be made simpler by rewriting as follows:

```<code>x_(n+1) = (1-lr)x_n + lr
</code>```

Effectively, we've transformed this into tail recursion.  (If you want the computer science perspective.)

This means that:

```<code>x_n = (1-lr)^n * x_0    +   ((1-lr)^(n-1) + (1-lr)^(n-2) + ... + 1)*lr
</code>```

The big term on the right is a geometric series, so that can be collapsed as well:

```<code>x_n = (1-lr)^n * x_0   +   lr *  (1 - (1-lr)^n) / (1- (1 -lr))
x_n = (1-lr)^n * x_0   +   1 - (1 - lr)^n
</code>```

Edited due to a small error in the final expressions.  +1 to comingstorm.

OwnerDisplayName: sanity

ContentLicense: CC BY-SA 2.5

Body:
So I have a function (I'm writing this in a pseudo-functional language, I hope its clear):

dampen (lr : Num, x : Num) = x + lr*(1-x)

And I wish to apply this n times to a value x.  I could implement it recursively:

dampenN (0, lr, x) = dampen(lr, x)
dampenN (n, lr, x) = dampenN(n-1, lr, dampen(x))

But there must be a way I can do it mathematically without resorting to an iterative procedure (recursive, or a loop).

Unfortunately my algebra skills are rusty beyond belief, can anyone help?

Body:
We can eliminate the series from your formula entirely.

We are given:

x_(n+1) = x_n + lr(1-x_n)

This can be made simpler by rewriting as follows:

x_(n+1) = (1-lr)x_n + lr

Effectively, we've transformed this into tail recursion.  (If you want the computer science perspective.)

This means that:

x_n = (1-lr)^n * x_0    +   ((1-lr)^(n-1) + (1-lr)^(n-2) + ... + 1)*lr

The big term on the right is a geometric series, so that can be collapsed as well:

x_n = (1-lr)^n * x_0   +   lr *  (1 - (1-lr)^n) / (1- (1 -lr))
x_n = (1-lr)^n * x_0   +   1 - (1 - lr)^n

Edited due to a small error in the final expressions.  +1 to comingstorm.

OwnerDisplayName: Rob

LastEditorDisplayName: Rob


问:
__dopostback not working as expected
Scenario 1 (That Works)
This is a POC i created.
I have a script manager, a html textbox, an ASP.NET button, an updatepanel with async trigger set for Click event of above mentioned button. For html textbox i have, onkeyup='__doPostBack('<%=ASPBUTTON.ClientID%>',''). AND IT WORKS, the Click event of button is hit, and updatepanel is updated asynchronously.

Scenario 2 (It's not working)
The only difference with my actual codebase is that i have a JQUERY FILAMENTGROUP datetimepicker whose onchange event is being used instead of html textbox's onchange. Further, here my page uses a master page. Now, my problem is that when onchange event for datetimepicker fires, the request goes server side, but BUTTON click event is not getting fired.

Some more details,
I want to update the updatepanel automatically on datetimepicker selection. So, the button would be actually hidden through css (display:none).

Button id - btnDateRangeCallback

Datetimepicker Textbox (non ASP control) - dateRange

```<code>        onChange: function() {__doPostBack('<%=btnDateRangeCallback.ClientID%>',   $('#dateRange').val());}
</code>```

[Please remember i said it works in case of my simplistic POC, while in my actual codebase i am using a masterpage to inherit from, and so all these controls are placed in a contentplaceholder. Furthermore, postback is happening, and i can see _EVENTTARGET and _EVENTARGUMENT being sent correctly if i break at Page_Load]

Please help.

To put it more simply,
After postback, when i break at Page_Load, i see the Request.Form contents as,
ctl00%24ContentPlaceHolder1%24SMgr1=ctl00%24ContentPlaceHolder1%24SMgr1%7cctl00_ContentPlaceHolder1_btnDateRangeCallback
&__EVENTTARGET=ctl00_ContentPlaceHolder1_btnDateRangeCallback
&_EVENTARGUMENT=5%2f3%2f2011+-+6%2f2%2f2011
&_VIEWSTATE=%2fwEPDwULLTE3NDY5NDIwMDRkZIuTqMNNsFHlRYhjpKaUCaCXj42h
&_EVENTVALIDATION=%2fwEWAgLBx52kBALP6Ln6DdkkwE%2frVIKQzKE1L0k4QhIc768w
&_ASYNCPOST=true&

Why is not Click event for btnDateRangeCallback hitting???

答:
Why not just click the button?

```<code>onchange="$('#<%= ASPBUTTON.ClientID %>').click()"
</code>```

(Ideally, don't use inline event handlers either...)

If that's no good for you, you could work around it using __EVENTTARGET and __EVENTARGUMENT (see this article for a guide).

Title: __dopostback not working as expected

Body:
Scenario 1 (That Works)
This is a POC i created.
I have a script manager, a html textbox, an ASP.NET button, an updatepanel with async trigger set for Click event of above mentioned button. For html textbox i have, onkeyup='__doPostBack('<%=ASPBUTTON.ClientID%>',''). AND IT WORKS, the Click event of button is hit, and updatepanel is updated asynchronously.

Scenario 2 (It's not working)
The only difference with my actual codebase is that i have a JQUERY FILAMENTGROUP datetimepicker whose onchange event is being used instead of html textbox's onchange. Further, here my page uses a master page. Now, my problem is that when onchange event for datetimepicker fires, the request goes server side, but BUTTON click event is not getting fired.

Some more details,
I want to update the updatepanel automatically on datetimepicker selection. So, the button would be actually hidden through css (display:none).

Button id - btnDateRangeCallback

Datetimepicker Textbox (non ASP control) - dateRange

        onChange: function() {__doPostBack('<%=btnDateRangeCallback.ClientID%>',   $('#dateRange').val());}

[Please remember i said it works in case of my simplistic POC, while in my actual codebase i am using a masterpage to inherit from, and so all these controls are placed in a contentplaceholder. Furthermore, postback is happening, and i can see _EVENTTARGET and _EVENTARGUMENT being sent correctly if i break at Page_Load]

Please help.

To put it more simply,
After postback, when i break at Page_Load, i see the Request.Form contents as,
ctl00%24ContentPlaceHolder1%24SMgr1=ctl00%24ContentPlaceHolder1%24SMgr1%7cctl00_ContentPlaceHolder1_btnDateRangeCallback
&__EVENTTARGET=ctl00_ContentPlaceHolder1_btnDateRangeCallback
&_EVENTARGUMENT=5%2f3%2f2011+-+6%2f2%2f2011
&_VIEWSTATE=%2fwEPDwULLTE3NDY5NDIwMDRkZIuTqMNNsFHlRYhjpKaUCaCXj42h
&_EVENTVALIDATION=%2fwEWAgLBx52kBALP6Ln6DdkkwE%2frVIKQzKE1L0k4QhIc768w
&_ASYNCPOST=true&

Why is not Click event for btnDateRangeCallback hitting???

Body:
Why not just click the button?

onchange="$('#<%= ASPBUTTON.ClientID %>').click()"

(Ideally, don't use inline event handlers either...)

If that's no good for you, you could work around it using __EVENTTARGET and __EVENTARGUMENT (see this article for a guide).


问:
PostgreSQL - Convert string to ASCII integer
How do I get the ASCII value of a string as an int in PostgreSQL?

For example: the string S06.6X9A

Currently, I am using an ASCII function, but it returns only the first character of a given string.

答:
Use string_to_array('S06.6X9A', null) to split the string into a text[] of individual characters. Then unnest to turn that text[] into a table. Then use that in a from clause and run ascii() over each row.

```<code>select ascii(char)
from (
  select unnest( string_to_array('S06.6X9A', null) )
) as chars(char);

 ascii
-------
    83
    48
    54
    46
    54
    88
    57
    65
</code>```

Body:
Use string_to_array('S06.6X9A', null) to split the string into a text[] of individual characters. Then unnest to turn that text[] into a table. Then use that in a from clause and run ascii() over each row.

select ascii(char)
from (
  select unnest( string_to_array('S06.6X9A', null) )
) as chars(char);

 ascii
-------
    83
    48
    54
    46
    54
    88
    57
    65


问:
Python round to next highest power of 10
How would I manage to perform math.ceil such that a number is assigned to the next highest power of 10?

```<code># 0.04  ->  0.1
# 0.7   ->  1
# 1.1   ->  10
# 90    ->  100
# ...
</code>```

My current solution is a dictionary that checks the range of the input number, but it's hardcoded and I would prefer a one-liner solution. Maybe I am missing a simple mathematical trick or a corresponding numpy function here?

答:
I think the simplest way is:

```<code>import math

number = int(input('Enter a number: '))
next_pow_ten = round(10 ** math.ceil(math.log10(number)))
print(str(10) + ' power ' + str(round(math.log10(number))) + ' = '\
      + str(next_pow_ten))
</code>```

I hope this help you.

Body:
How would I manage to perform math.ceil such that a number is assigned to the next highest power of 10?

# 0.04  ->  0.1
# 0.7   ->  1
# 1.1   ->  10
# 90    ->  100
# ...

My current solution is a dictionary that checks the range of the input number, but it's hardcoded and I would prefer a one-liner solution. Maybe I am missing a simple mathematical trick or a corresponding numpy function here?

Body:
I think the simplest way is:

import math

number = int(input('Enter a number: '))
next_pow_ten = round(10 ** math.ceil(math.log10(number)))
print(str(10) + ' power ' + str(round(math.log10(number))) + ' = '\
      + str(next_pow_ten))

I hope this help you.


问:
Average request duration using Prometheus
I have deployed the Istio Bookinfo application in a Kubernetes cluster. Following the documentation, I'm trying to measure the average request duration using the following query:

```<code>rate(istio_request_duration_milliseconds_sum[1m]) / rate(istio_request_duration_milliseconds_count[1m])
</code>```

This query returns me "doubled" results i.e. for each request I get two results, with different Value but same source and destination, one labelled as reporter="source" and the other as reporter="destination". I was not able to find any clarification about it and I have not clear how these measures work. Why I have two values returned?

答:
The metrics are indeed reported from two sources, once from the request sender and another time from the request receiver. This is a bit redundant, but in some situations the values differ and especially for requests duration: from request sender (reporter=source), the duration stands for the whole request latency (server processing time + network roundtrip) whereas from the request receiver (reporter=destination), it stands mainly for server processing time.

In a few special situations there is no redundancy and metrics are only reported once (be it from source or from destination): e.g. when istio features such as fault injection or traffic mirroring come into play.

As a result, in Prometheus you should always filter all your queries with either {reporter="source"} or {reporter="destination"}.

Body:
I have deployed the Istio Bookinfo application in a Kubernetes cluster. Following the documentation, I'm trying to measure the average request duration using the following query:

rate(istio_request_duration_milliseconds_sum[1m]) / rate(istio_request_duration_milliseconds_count[1m])

This query returns me "doubled" results i.e. for each request I get two results, with different Value but same source and destination, one labelled as reporter="source" and the other as reporter="destination". I was not able to find any clarification about it and I have not clear how these measures work. Why I have two values returned?


问:
PyPika how to generate IF statement
How do I generate an IF statement in PyPika?

I am trying to generate a BigQuery query that pivots a row to a column. I found that if I use the following in a query (where date_range is from a WITH statement):

```<code>IF (date_range.kind = 'year', date_range.name, NULL) as year
</code>```

then this will work. However, I haven't found a way to generate this SQL fragment in PyPika.

For completeness, this is an example of a query I need to run in BigQuery:

```<code>WITH date_range AS (
SELECT
    CAST(EXTRACT(year FROM year) as string) name,
    'year' kind,
    year start_date,
    DATE_ADD(year, INTERVAL 1 year) end_date
FROM UNNEST(GENERATE_DATE_ARRAY('2010-01-01','2020-06-01',INTERVAL 1 year)) year

UNION ALL

SELECT
    FORMAT_DATE('%B', month)||' '||EXTRACT(year FROM month) name,
    'month' kind,
    month start_date,
    DATE_ADD(month,INTERVAL 1 month) end_date
FROM
    UNNEST(GENERATE_DATE_ARRAY('2010-01-01','2020-06-01',INTERVAL 1 month)) month
)
SELECT
IF(date_range.kind='year', date_range.name, null) as year,
IF(date_range.kind='month', date_range.name, null) as month,
SUM(sales.sales_value) sales_value,
FROM sales
JOIN date_range ON sales.start_date>=date_range.start_date AND sales.end_date<date_range.end_date
GROUP BY year, month
ORDER BY year, month
</code>```

The more general question I have is, is there a way to pass literal strings to PyPika so that those will be included in the resulting query string? There are several SQL fragments that Pypika does not generate (such as GENERATE_DATE_ARRAY and UNNEST, at least as far I can find) and passing the actual SQL fragment to PyPika would solve the problem.

Thanks!

答:
Not sure if it applies but be sure to also check whether the CASE statement can help you.

Other than that you can either subclass PyPika's Function class and overwrite get_sql and use that or (ab)use the CustomFunction and PseudoColumn utility classes like this:

```<code>from pypika import CustomFunction

sales_table = Table('sales')
MyIf = CustomFunction('IF', ['condition', 'if', 'else'])
q = Query.from_(sales_table).select(
    MyIf(PseudoColumn("date_range.kind = 'year'"), PseudoColumn("date_range.name"), None, alias="year")
)
</code>```

However, I'd probably recommend making a ticket on the PyPika Github.

Note: I wasn't able to test this.

Title: PyPika how to generate IF statement

Body:
How do I generate an IF statement in PyPika?

I am trying to generate a BigQuery query that pivots a row to a column. I found that if I use the following in a query (where date_range is from a WITH statement):

IF (date_range.kind = 'year', date_range.name, NULL) as year

then this will work. However, I haven't found a way to generate this SQL fragment in PyPika.

For completeness, this is an example of a query I need to run in BigQuery:

WITH date_range AS (
SELECT
    CAST(EXTRACT(year FROM year) as string) name,
    'year' kind,
    year start_date,
    DATE_ADD(year, INTERVAL 1 year) end_date
FROM UNNEST(GENERATE_DATE_ARRAY('2010-01-01','2020-06-01',INTERVAL 1 year)) year

UNION ALL

SELECT
    FORMAT_DATE('%B', month)||' '||EXTRACT(year FROM month) name,
    'month' kind,
    month start_date,
    DATE_ADD(month,INTERVAL 1 month) end_date
FROM
    UNNEST(GENERATE_DATE_ARRAY('2010-01-01','2020-06-01',INTERVAL 1 month)) month
)
SELECT
IF(date_range.kind='year', date_range.name, null) as year,
IF(date_range.kind='month', date_range.name, null) as month,
SUM(sales.sales_value) sales_value,
FROM sales
JOIN date_range ON sales.start_date>=date_range.start_date AND sales.end_date<date_range.end_date
GROUP BY year, month
ORDER BY year, month

The more general question I have is, is there a way to pass literal strings to PyPika so that those will be included in the resulting query string? There are several SQL fragments that Pypika does not generate (such as GENERATE_DATE_ARRAY and UNNEST, at least as far I can find) and passing the actual SQL fragment to PyPika would solve the problem.

Thanks!

Body:
Not sure if it applies but be sure to also check whether the CASE statement can help you.

Other than that you can either subclass PyPika's Function class and overwrite get_sql and use that or (ab)use the CustomFunction and PseudoColumn utility classes like this:

from pypika import CustomFunction

sales_table = Table('sales')
MyIf = CustomFunction('IF', ['condition', 'if', 'else'])
q = Query.from_(sales_table).select(
    MyIf(PseudoColumn("date_range.kind = 'year'"), PseudoColumn("date_range.name"), None, alias="year")
)

However, I'd probably recommend making a ticket on the PyPika Github.

Note: I wasn't able to test this.


问:
How to get html range input type's max value through javascript?
If I have set:

```<code><input class="slider" type="range" min="0" max="100">
<input class="slider" type="range" min="0" max="255">
</code>```

How can I use jQuery/JavaScript to get the min and max value?

I want to do something like this later, I can get the max value and parse it to a variable maxValue.

```<code>if (maxValue == 100) {console.log("100");}
else if (maxValue == 255) {console.log("255");}
</code>```

答:
Using only JavaScript you can pass the values to a function:

in HTML:

```<code><input class="slider" type="range" min="0" max="100" onchange="showResult(this.min, this.max)">
<p id=max>Max value will appear here</p>
<p id=min>Min value will appear here</p>
</code>```

in JavaScript:

```<code>function showResult(min, max) {
    // Use min and max variables as desired

    // Display min and max in HTML
    document.getElementById('max').innerHTML = max;
    document.getElementById('min').innerHTML = min;
}
</code>```

Try it out here https://jsfiddle.net/vdja45xo/

Body:
If I have set:

<input class="slider" type="range" min="0" max="100">
<input class="slider" type="range" min="0" max="255">

How can I use jQuery/JavaScript to get the min and max value?

I want to do something like this later, I can get the max value and parse it to a variable maxValue.

if (maxValue == 100) {console.log("100");}
else if (maxValue == 255) {console.log("255");}

Body:
Using only JavaScript you can pass the values to a function:

in HTML:

<input class="slider" type="range" min="0" max="100" onchange="showResult(this.min, this.max)">
<p id=max>Max value will appear here</p>
<p id=min>Min value will appear here</p>

in JavaScript:

function showResult(min, max) {
    // Use min and max variables as desired

    // Display min and max in HTML
    document.getElementById('max').innerHTML = max;
    document.getElementById('min').innerHTML = min;
}

Try it out here https://jsfiddle.net/vdja45xo/


问:
about SQLite query
I'm using SQLite & in that i'm using the following query-

```<code>INSERT INTO Contact(FirstName, LastName, MobileNumber, IsArchive) VALUES('mina', 'Ambani', '9874587458', 1); SELECT last_insert_rowid() AS 'Identity';
</code>```

this query insert the record & also gives last insert row id of identity column in my table but initially it generates error as-

```<code>The following errors were encountered while parsing the contents of the SQL pane:

Unable to parse query text
</code>```

How to remove this error?

thanks.

答:
Sqlite does not seem to support multiple SQL statements in one query. Run a separate subsequent query. Something like

```<code>SQLiteCommand IDCmd = new SQLiteCommand("Select last_insert_rowid();", conn);
cmd.ExecuteNonQuery(); // EXECUTE INSERT HERE
long id = (long)IDCmd.ExecuteScalar();
</code>```

Connection open/close and error handling is missing from this example.

Title: about SQLite query

Body:
I'm using SQLite & in that i'm using the following query-

INSERT INTO Contact(FirstName, LastName, MobileNumber, IsArchive) VALUES('mina', 'Ambani', '9874587458', 1); SELECT last_insert_rowid() AS 'Identity';

this query insert the record & also gives last insert row id of identity column in my table but initially it generates error as-

The following errors were encountered while parsing the contents of the SQL pane:

Unable to parse query text

How to remove this error?

thanks.

Body:
Sqlite does not seem to support multiple SQL statements in one query. Run a separate subsequent query. Something like

SQLiteCommand IDCmd = new SQLiteCommand("Select last_insert_rowid();", conn);
cmd.ExecuteNonQuery(); // EXECUTE INSERT HERE
long id = (long)IDCmd.ExecuteScalar();

Connection open/close and error handling is missing from this example.


问:
How to remove UIWebView from Pod frameworks?
I have implemented Google Ads with some partner networks. but some of them uses UIWebView and when i upload build to appStore getting warning like this.

ITMS-90809: Deprecated API Usage - Apple will no longer accept submissions of new apps that use UIWebView as of April 30, 2020 and app updates that use UIWebView as of December 2020. Instead, use WKWebView for improved security and reliability.

Note: i have searched UIWebView word in my project but wasn't found it.

i use this command in terminal and through this it gives the framework list which uses UIWebView.

here is the screenshot.

Here is my pods

```<code>pod 'GoogleMobileAdsMediationAdColony'
pod 'GoogleMobileAdsMediationInMobi'
pod 'GoogleMobileAdsMediationVungle'
</code>```

Please guide me to fix this?

答:
No need to remove UIWebView from the Google Ads Pod framework.
I have it in the GoogleMobileAds binary file, but hadn’t any problems.
Try to do the follows:

Add new row and set a key and value in your info.plist to use WKWebView instead of UIWebView.

Key: gad_preferred_webview

Value: wkwebview

Create and upload archive to the App Store

It works for me

Body:
I have implemented Google Ads with some partner networks. but some of them uses UIWebView and when i upload build to appStore getting warning like this.

ITMS-90809: Deprecated API Usage - Apple will no longer accept submissions of new apps that use UIWebView as of April 30, 2020 and app updates that use UIWebView as of December 2020. Instead, use WKWebView for improved security and reliability.

Note: i have searched UIWebView word in my project but wasn't found it.

i use this command in terminal and through this it gives the framework list which uses UIWebView.

here is the screenshot.

Here is my pods

pod 'GoogleMobileAdsMediationAdColony'
pod 'GoogleMobileAdsMediationInMobi'
pod 'GoogleMobileAdsMediationVungle'

Please guide me to fix this?


问:
How do I open a file in python?
I need to read the file called, "ranks.dat", however whenever I try opening the file it says there is no such file or directory even though I have downloaded the file. Below is my code:

```<code># Reading from a file
numFile = open("ranks.dat", "r")

while True:
    text = numFile.readline()
    #rstrip removes the newline character read at the end of the line
    text = text.rstrip("\n")
    if text=="":
        break
    print (text, end = "\t")

numFile.close()
</code>```

The files should always have the following fields:
Rank - Word of Size 15 or less - the Name of the Card
Power - Integer less than 100 - the Power of the Card
Number - Integer less than 100 - the Number of these cards

I need to store each of the fields into their own list. But it does not seem to work.

答:
First make sure that Python is able to read the path to your file.

```<code>from os import path

if path.exists('ranks.dat'):
   # do the file processing
else:
   print('Filepath does not exist.')
</code>```

If it prints out that the file path does not exist, then you can provide the full filepath to ranks.dat and it should work.

In addition, you can also use a context manager to open and close the file for you when you are done

```<code>with open('ranks.dat', 'r') as f:
    for line in f.readlines():
        print(line)
</code>```

Title: How do I open a file in python?

Body:
I need to read the file called, "ranks.dat", however whenever I try opening the file it says there is no such file or directory even though I have downloaded the file. Below is my code:

# Reading from a file
numFile = open("ranks.dat", "r")

while True:
    text = numFile.readline()
    #rstrip removes the newline character read at the end of the line
    text = text.rstrip("\n")
    if text=="":
        break
    print (text, end = "\t")

numFile.close()

The files should always have the following fields:
Rank - Word of Size 15 or less - the Name of the Card
Power - Integer less than 100 - the Power of the Card
Number - Integer less than 100 - the Number of these cards

I need to store each of the fields into their own list. But it does not seem to work.

Body:
First make sure that Python is able to read the path to your file.

from os import path

if path.exists('ranks.dat'):
   # do the file processing
else:
   print('Filepath does not exist.')

If it prints out that the file path does not exist, then you can provide the full filepath to ranks.dat and it should work.

In addition, you can also use a context manager to open and close the file for you when you are done

with open('ranks.dat', 'r') as f:
    for line in f.readlines():
        print(line)


问:
Python compare part of string to list
I have multiple strings that looks like this:

```<code>“BPBA-SG790-NGTP-W-AU-BUN-3Y”
</code>```

I want to compare the string to my list and if part of the string is in the list, I want to get only the part that is found on the list as a new variable.

This is my code:

```<code>    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> ['770', '790', '1470', '1490']
</code>```

For example this is what I want to get:

```<code>    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> 790
</code>```

Any idea how to do this?

答:
try</p>

```<code>mylist = ["770", "790", "1470", "1490"]
sq = "BPBA-SG790-NGTP-W-AU-BUN-3Y"

b = [x for x in mylist if sq.find(x) != -1]
print b
</code>```

Title: Python compare part of string to list

Body:
I have multiple strings that looks like this:

“BPBA-SG790-NGTP-W-AU-BUN-3Y”

I want to compare the string to my list and if part of the string is in the list, I want to get only the part that is found on the list as a new variable.

This is my code:

    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> ['770', '790', '1470', '1490']

For example this is what I want to get:

    mylist = ["770", "790", "1470", "1490"]
    sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”

    matching = [s for s in mylist if any(xs in s for xs in sq)]
    print(matching)

>>> 790

Any idea how to do this?

Body:
try

mylist = ["770", "790", "1470", "1490"]
sq = "BPBA-SG790-NGTP-W-AU-BUN-3Y"

b = [x for x in mylist if sq.find(x) != -1]
print b


问:
My div is fixed, but when i open one dialog (popup), div is no more fixed
I have a div notification which it is in fixed position has you can see in the first screen. The probleme that when I open a dialog by clicking in update or remove button, the div notification is no more fixed when the popup (dialog) is open. How to resolve this problem, when i open my dialog the div as to keep the same fixed position.

.list {
  width: 90%;
  margin: 0 auto;
  margin-bottom: 3%;
  display: flex;
}

.content {
  width: 100%;
  margin-left: 22%;
}

table {
  width: 100%;
}

img {
  height: 140px;
  width: 100px;
  margin-top: 5%;
  margin-bottom: 5%;
}

.update {
  color: grey;
}

.notifications {
  width: 16%;
  position: fixed;
  text-align: center;
  border-radius: 10px;
  -webkit-box-shadow: 9px 9px 18px 3px rgba(163,158,163,1);
  -moz-box-shadow: 9px 9px 18px 3px rgba(163,158,163,1);
  box-shadow: 9px 9px 18px 3px rgba(163,158,163,1);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="list">
  <div class="notifications">
    <h2>Tv Shows List</h2>
    <h4 class="number"><span class="badge badge-danger">Tv Shows Finished : {{ tvShowsFinished }} </span></h4>
    <h4 class="number"><span class="badge badge-primary">Tv Shows Waiting : {{ tvShowsWaiting }} </span></h4>
    <h4 class="number"><span class="badge badge-warning">Tv Shows Watching : {{ tvShowsWatching }} </span></h4>
  </div>
  <div class="mat-elevation-z8 content">
    <table mat-table [dataSource]="dataSource">

      <ng-container matColumnDef="poster">
        <th mat-header-cell *matHeaderCellDef> Poster</th>
        <td mat-cell *matCellDef="let element">
          <div *ngIf="element.poster_path; else noPoster">
            <img src="https://image.tmdb.org/t/p/w200/{{element.poster_path}}" alt="...">
          </div>
          <ng-template #noPoster>
            <img src="../../assets/not_found.jpg" alt="...">
          </ng-template>
        </td>
      </ng-container>

      <ng-container matColumnDef="title">
        <th mat-header-cell *matHeaderCellDef> Title </th>
        <td mat-cell *matCellDef="let element"> {{element.name}} </td>
      </ng-container>

      <ng-container matColumnDef="status">
        <th mat-header-cell *matHeaderCellDef> Status </th>
        <td mat-cell *matCellDef="let element" >
          <div *ngIf="element.status === 0">
            <h5><span class="badge badge-secondary">Never finished</span></h5>
          </div>
          <div *ngIf="element.status === 1">
            <h5><span class="badge badge-danger">Finished</span></h5>
          </div>
          <div *ngIf="element.status === 2">
            <h5><span class="badge badge-primary">Waiting for season/episode</span></h5>
          </div>
          <div *ngIf="element.status === 3">
            <h5><span class="badge badge-warning">Watching</span></h5>
          </div>
        </td>
      </ng-container>

      <ng-container matColumnDef="date">
        <th mat-header-cell *matHeaderCellDef> Date </th>
        <td mat-cell *matCellDef="let element"> {{element.first_air_date | date: 'dd MMMM, y'}} </td>
      </ng-container>

      <ng-container matColumnDef="vote">
          <th mat-header-cell *matHeaderCellDef> Vote </th>
          <td mat-cell *matCellDef="let element"> {{element.vote_average}} </td>
        </ng-container>

      <ng-container matColumnDef="update">
          <th mat-header-cell *matHeaderCellDef> Update </th>
          <td mat-cell *matCellDef="let element">
            <button mat-icon-button class="update" (click)="update(element)">
              <mat-icon>create</mat-icon>
            </button>
          </td>
        </ng-container>

      <ng-container matColumnDef="remove">
        <th mat-header-cell *matHeaderCellDef> Remove </th>
        <td mat-cell *matCellDef="let element">
          <button mat-icon-button color="warn" (click)="remove(element)">
            <mat-icon>delete</mat-icon>
          </button>
        </td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>

    <mat-paginator [pageSizeOptions]="[25, 50, 100]" showFirstLastButtons></mat-paginator>
  </div>
</div></code>```

If you have some idea to resolve this problem I will be happy.

Thanks

答: You could try issuing a margin-top: 10%; through javascript when you load the notification. 10% is just an assumption, you can change this to whatever you see fit.

Body:
I have a div notification which it is in fixed position has you can see in the first screen. The probleme that when I open a dialog by clicking in update or remove button, the div notification is no more fixed when the popup (dialog) is open. How to resolve this problem, when i open my dialog the div as to keep the same fixed position.

.list {
  width: 90%;
  margin: 0 auto;
  margin-bottom: 3%;
  display: flex;
}

.content {
  width: 100%;
  margin-left: 22%;
}

table {
  width: 100%;
}

img {
  height: 140px;
  width: 100px;
  margin-top: 5%;
  margin-bottom: 5%;
}

.update {
  color: grey;
}

.notifications {
  width: 16%;
  position: fixed;
  text-align: center;
  border-radius: 10px;
  -webkit-box-shadow: 9px 9px 18px 3px rgba(163,158,163,1);
  -moz-box-shadow: 9px 9px 18px 3px rgba(163,158,163,1);
  box-shadow: 9px 9px 18px 3px rgba(163,158,163,1);
}

Tv Shows List

Tv Shows Finished : {{ tvShowsFinished }}

Tv Shows Waiting : {{ tvShowsWaiting }}

Tv Shows Watching : {{ tvShowsWatching }}

      <ng-container matColumnDef="poster">
         Poster

          <ng-template #noPoster>

          </ng-template>

      </ng-container>

      <ng-container matColumnDef="title">
         Title
         {{element.name}}
      </ng-container>

      <ng-container matColumnDef="status">
         Status

Never finished

Finished

Waiting for season/episode

Watching

      </ng-container>

      <ng-container matColumnDef="date">
         Date
         {{element.first_air_date | date: 'dd MMMM, y'}}
      </ng-container>

      <ng-container matColumnDef="vote">
           Vote
           {{element.vote_average}}
        </ng-container>

      <ng-container matColumnDef="update">
           Update

            <button mat-icon-button class="update" (click)="update(element)">
              <mat-icon>create</mat-icon>
            </button>

        </ng-container>

      <ng-container matColumnDef="remove">
         Remove

          <button mat-icon-button color="warn" (click)="remove(element)">
            <mat-icon>delete</mat-icon>
          </button>

      </ng-container>

    <mat-paginator [pageSizeOptions]="[25, 50, 100]" showFirstLastButtons></mat-paginator>

If you have some idea to resolve this problem I will be happy.

Thanks


问:
jQuery conditional chaining
Let's say I have the following jQuery code. It works great, but then I need to include the .after($('
')) only if var insertAfter equals true. Is there an elegant jQuery way of doing this?

```<code>$('#whatEver')
    .parent()
    .show()
    .width(123)
    .addClass('bebo')
    .before($('<div />'))
    .after($('<div />'))
    .parent()
    .addClass('bla');
</code>```

答:
A couple of jQuery methods allow passing a function func. Often not clearly documented, but returning undefined from func is like a no-op, even in setters like .attr('src', func).

(In this setter example, func should return whatever you want 'src' set to otherwise.)

Title: jQuery conditional chaining

Body:
Let's say I have the following jQuery code. It works great, but then I need to include the .after($('
')) only if var insertAfter equals true. Is there an elegant jQuery way of doing this?

$('#whatEver')
    .parent()
    .show()
    .width(123)
    .addClass('bebo')
    .before($('
'))
    .after($('
'))
    .parent()
    .addClass('bla');


问:
Finding common characters in two strings
I am coding for the problem in which we got to count the number of common characters in two strings. Main part of the count goes like this

```<code>for(i=0; i < strlen(s1); i++) {
    for(j = 0; j < strlen(s2); j++) {
        if(s1[i] == s2[j]) {
            count++;
            s2[j] = '*';
            break;
        }
    }
}
</code>```

This goes with an O(n^2) logic. However I could not think of a better solution than this. Can anyone help me in coding with an O(n) logic.

答:
No need to initialize and keep an array of 26 elements (numbers for each letter in alphabet). Just fo the following:

Using HashMap store letter as a key and integer got the count as a value.

Create a Set of characters.

Iterate through each string characters, add to the Set from step 2. If add() method returned false, (means that same character already exists in the Set), then add the character to the map and increment the value.

These steps are written considering Java programming language.

Body:
I am coding for the problem in which we got to count the number of common characters in two strings. Main part of the count goes like this

for(i=0; i < strlen(s1); i++) {
    for(j = 0; j < strlen(s2); j++) {
        if(s1[i] == s2[j]) {
            count++;
            s2[j] = '*';
            break;
        }
    }
}

This goes with an O(n^2) logic. However I could not think of a better solution than this. Can anyone help me in coding with an O(n) logic.


问:
Surfaces or Sprites in Pygame?
Good evening, I'm making a platformer and would like to know when you should use one of the both.
For example for:

1)The player controlled character

2)The textured tiles that make up the level

3)The background

Should/Could you make everything with sprites ?

I just want to know how you would do it if you were to work on a pygame project.

I ask this because I see lots of pygame tutorials that explain adding textures by using surfaces but then in other tutorials, they use sprite objects instead.

答:
Yes you could make everything including the background with sprites. It usually does not make sense for the background though (unless you;re doing layers of some form).

The rest often make senses as sprite, but that depends on your situation.

Title: Surfaces or Sprites in Pygame?


问:
Include HTML in Shiny - tabPanel doens't change size
I'm working on a dashboard in Shiny and I would like to include some images (and be able to position them on the page. However, the box in which I included some text and images doesn't have any height. Does anyone know how to fix this? I've included my code and a screenshot of my dashboard.

My code (UI) (The problem is in Tab4):

```<code>dashboardBody(
    useShinyjs(),
    fluidRow(
        tabBox(
            side = 'right',
            width = 12,
            height = "100%",
            selected = "Tab1",
            tabPanel("Tab1",
                dataTableOutput('table2')),
            tabPanel("Tab2",
                dataTableOutput('table1')),
            tabPanel("Tab3",
                h2("Old:"),
                h4("some text to explain the datatable"),
                DT::dataTableOutput('table3'),
                hr(),
                h2("New:"),
                h4("Some more text to explain this datatable."),
                DT::dataTableOutput('table4')
              ),
            tabPanel("Tab4",
                div(h2("This is an example"),
                    p("some text"),
                    h3("some header"),
                    p('Even more text'),
                    img(src='logoStackOverflow.PNG'),
                    p('explain something about the image'),
                    style ="position:absolute;
                    max-width:1200px;
                    left:30px;
                    top:40px;
                    height:100%;"),
                div(img(src="logoStackOverflow.PNG"),
                    img(src="logoStackOverflow.PNG"),
                    style ="position:absolute;
                            border: 1px solid;
                            max-width:300px;
                            box-align:right;
                            position: fixed;
                            height:auto;
                            right:100px;
                            top:150px;")
             )
          )
         )
        )
</code>```

答: You were very close.  Replace img() with tags$img() and provide height and width as tags$img(height=100, width=100, src="YBS.png", style="text-align: right;").  Then you get the following output in tab4.

Body:
I'm working on a dashboard in Shiny and I would like to include some images (and be able to position them on the page. However, the box in which I included some text and images doesn't have any height. Does anyone know how to fix this? I've included my code and a screenshot of my dashboard.

My code (UI) (The problem is in Tab4):

dashboardBody(
    useShinyjs(),
    fluidRow(
        tabBox(
            side = 'right',
            width = 12,
            height = "100%",
            selected = "Tab1",
            tabPanel("Tab1",
                dataTableOutput('table2')),
            tabPanel("Tab2",
                dataTableOutput('table1')),
            tabPanel("Tab3",
                h2("Old:"),
                h4("some text to explain the datatable"),
                DT::dataTableOutput('table3'),
                hr(),
                h2("New:"),
                h4("Some more text to explain this datatable."),
                DT::dataTableOutput('table4')
              ),
            tabPanel("Tab4",
                div(h2("This is an example"),
                    p("some text"),
                    h3("some header"),
                    p('Even more text'),
                    img(src='logoStackOverflow.PNG'),
                    p('explain something about the image'),
                    style ="position:absolute;
                    max-width:1200px;
                    left:30px;
                    top:40px;
                    height:100%;"),
                div(img(src="logoStackOverflow.PNG"),
                    img(src="logoStackOverflow.PNG"),
                    style ="position:absolute;
                            border: 1px solid;
                            max-width:300px;
                            box-align:right;
                            position: fixed;
                            height:auto;
                            right:100px;
                            top:150px;")
             )
          )
         )
        )