问:
I have an error while using firebase php which is cURL error 35
I am trying to use php with firebase

after installing the package "composer require kreait/firebase-php ^4.0"

and adjusting my firebase

it shows me that error:

Fatal error: Uncaught GuzzleHttp\Exception\ConnectException: cURL error 35: OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to ff64t.firebaseio.com:443 (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in C:\xampp\htdocs\dashboard\webservice\php_firebase\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:200 Stack trace: #0 C:\xampp\htdocs\dashboard\webservice\php_firebase\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(155): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array) #1 C:\xampp\htdocs\dashboard\webservice\php_firebase\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(105): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory)) #2 C:\xampp\htdocs\dashboard\webservice\php_firebase\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(Guz in C:\xampp\htdocs\dashboard\webservice\php_firebase\vendor\kreait\firebase-php\src\Firebase\Exception\ApiException.php on line 40

my php code is so simple:

```<code> <?php
 require_once './vendor/autoload.php';
 use Kreait\Firebase\Factory;
     use Kreait\Firebase\ServiceAccount;
 $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/secret/clone-7ef2-642f.json');
 $firebase = (new Factory)
    ->withServiceAccount($serviceAccount)
    //->withDatabaseUri("https://ff64t.firebaseio.com")
    ->create();
    $database = $firebase->getDatabase();
    $ref = $database->getReference('users');
    $res = $ref->getChild('1z7ni171Hwgq8fdnandRNjfxBfw2')->getChild('name')->getValue();
    var_dump($res);

?>
</code>```

so anyone has faced something like that and how to solve this problem

I've tried many solutions but none of them works.

I tried to reinstall curl and put it like system variable
I also tried to add

```<code>curl_setopt($easy->handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
</code>```

to make curl deal with IPV4... it gave me a new error which is:

Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 0: The cURL request was retried 3 times and did not succeed. The most likely reason for the failure is that cURL was unable to rewind the body of the request and subsequent retries resulted in the same error. Turn on the debug option to see what went wrong. See https://bugs.php.net/bug.php?id=47204 for more information. (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in C:\xampp\htdocs\dashboard\webservice\firebase_php\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:201 Stack trace: #0 C:\xampp\htdocs\dashboard\webservice\firebase_php\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(537): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array) #1 C:\xampp\htdocs\dashboard\webservice\firebase_php\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(152): GuzzleHttp\Handler\CurlFactory::retryFailedRewind(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Array) #2 C:\xam in C:\xampp\htdocs\dashboard\webservice\firebase_php\vendor\kreait\firebase-php\src\Firebase\Exception\ApiException.php on line 40

I also checked curl support and ssl from phpinfo

答:
According to the curl(1) manual page, an error code 35 is an SSL handshake failure:

```<code>EXIT CODES
  ...
  35     SSL connect error. The SSL handshaking failed.
</code>```

You can try temporarily disabling the SSL certificate verification to see if that fixes the issue.

```<code>curl_setopt($handle, CURLOPT_VERIFYPEER, 0); // ***JUST A TEST! DO __NOT__ PUSH THIS TO PRODUCTION!***
</code>```

If that does fix the issue, the reason is probably one of the two most common SSL handshake failures:

A missing CA certificate on your host machine, meaning that cURL couldn't verify the certificate's authenticity.

An expired certificate being presented by the machine you're connecting to.

If that does NOT fix the issue, the reason is probably:

Your machine and the remote one couldn't negotiate a cipher suite and/or SSL version.

Any number of other SSL errors.

Body:
I am trying to use php with firebase

after installing the package "composer require kreait/firebase-php ^4.0"

and adjusting my firebase

it shows me that error:

Fatal error: Uncaught GuzzleHttp\Exception\ConnectException: cURL error 35: OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to ff64t.firebaseio.com:443 (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in C:\xampp\htdocs\dashboard\webservice\php_firebase\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:200 Stack trace: #0 C:\xampp\htdocs\dashboard\webservice\php_firebase\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(155): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array) #1 C:\xampp\htdocs\dashboard\webservice\php_firebase\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(105): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory)) #2 C:\xampp\htdocs\dashboard\webservice\php_firebase\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(Guz in C:\xampp\htdocs\dashboard\webservice\php_firebase\vendor\kreait\firebase-php\src\Firebase\Exception\ApiException.php on line 40

my php code is so simple:

 <?php
 require_once './vendor/autoload.php';
 use Kreait\Firebase\Factory;
     use Kreait\Firebase\ServiceAccount;
 $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/secret/clone-7ef2-642f.json');
 $firebase = (new Factory)
    ->withServiceAccount($serviceAccount)
    //->withDatabaseUri("https://ff64t.firebaseio.com")
    ->create();
    $database = $firebase->getDatabase();
    $ref = $database->getReference('users');
    $res = $ref->getChild('1z7ni171Hwgq8fdnandRNjfxBfw2')->getChild('name')->getValue();
    var_dump($res);

?>

so anyone has faced something like that and how to solve this problem

I've tried many solutions but none of them works.

I tried to reinstall curl and put it like system variable
I also tried to add

curl_setopt($easy->handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

to make curl deal with IPV4... it gave me a new error which is:

Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 0: The cURL request was retried 3 times and did not succeed. The most likely reason for the failure is that cURL was unable to rewind the body of the request and subsequent retries resulted in the same error. Turn on the debug option to see what went wrong. See https://bugs.php.net/bug.php?id=47204 for more information. (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) in C:\xampp\htdocs\dashboard\webservice\firebase_php\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:201 Stack trace: #0 C:\xampp\htdocs\dashboard\webservice\firebase_php\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(537): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array) #1 C:\xampp\htdocs\dashboard\webservice\firebase_php\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(152): GuzzleHttp\Handler\CurlFactory::retryFailedRewind(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Array) #2 C:\xam in C:\xampp\htdocs\dashboard\webservice\firebase_php\vendor\kreait\firebase-php\src\Firebase\Exception\ApiException.php on line 40

I also checked curl support and ssl from phpinfo

Body:
According to the curl(1) manual page, an error code 35 is an SSL handshake failure:

EXIT CODES
  ...
  35     SSL connect error. The SSL handshaking failed.

You can try temporarily disabling the SSL certificate verification to see if that fixes the issue.

curl_setopt($handle, CURLOPT_VERIFYPEER, 0); // ***JUST A TEST! DO __NOT__ PUSH THIS TO PRODUCTION!***

If that does fix the issue, the reason is probably one of the two most common SSL handshake failures:

A missing CA certificate on your host machine, meaning that cURL couldn't verify the certificate's authenticity.

An expired certificate being presented by the machine you're connecting to.

If that does NOT fix the issue, the reason is probably:

Your machine and the remote one couldn't negotiate a cipher suite and/or SSL version.

Any number of other SSL errors.


来源: stackexchange

问:
PostgreSQL 11 spring JPA query error with java.sql.Date object and TO_DATE fucntion with format YYYY-DD-MM
I am passing java.sql.Date object to CrudRepository native query. This date object is passed to a date function with a format ('YYYY-DD-MM'). This query is working with PostgreSQL 9.4, but it gives error when the database is PostgreSQL 11. I tried JDBC driver v42.2.11 and 9.1-901-1. Both are giving same result.

The error message is:

```<code>ERROR: date/time field value out of range: "2020-05-27 +00:00"
</code>```

Code:

```<code>@Query(value = "SELECT TO_DATE(?1, 'YYYY-DD-MM')", nativeQuery = true)
public String sampleQuery(java.sql.Date date);
</code>```

When I gave the date format as "SELECT TO_DATE(?1, 'YYYY-MM-DD')", that time it worked in PostgreSQL 11.

Any idea what is happening here.

ContentLicense: CC BY-SA 4.0

Body:
I am passing java.sql.Date object to CrudRepository native query. This date object is passed to a date function with a format ('YYYY-DD-MM'). This query is working with PostgreSQL 9.4, but it gives error when the database is PostgreSQL 11. I tried JDBC driver v42.2.11 and 9.1-901-1. Both are giving same result.

The error message is:

ERROR: date/time field value out of range: "2020-05-27 +00:00"

Code:

@Query(value = "SELECT TO_DATE(?1, 'YYYY-DD-MM')", nativeQuery = true)
public String sampleQuery(java.sql.Date date);

When I gave the date format as "SELECT TO_DATE(?1, 'YYYY-MM-DD')", that time it worked in PostgreSQL 11.

Any idea what is happening here.

Body:
Because 27 is not a valid month it should not work:

postgres=# select version();
                                                 version
---------------------------------------------------------------------------------------------------------
 PostgreSQL 11.7 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit
(1 row)

postgres=# select to_date('2020-05-27 +00:00','YYYY-DD-MM');
ERROR:  date/time field value out of range: "2020-05-27 +00:00"
postgres=#

And if it works in 9.4 it gives an unexpected result:

postgres=# select version();
                                                    version
----------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.4.26 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39), 64-bit
(1 row)

postgres=# select to_date('2020-05-27 +00:00','YYYY-DD-MM');
  to_date
------------
 2022-03-09
(1 row)

postgres=#


问:
Trouble downloading files in Google Apps Script web app after Chrome update
I've had a Google Apps Script web app running for a bit over a year which gave users an option to download a csv file. It worked perfectly fine, although in the console it gave a warning about downloading from an iFrame being deprecated.

After updating Chrome, I now get the following error when trying to download:

Download is disallowed. The frame initiating or instantiating the
  download is sandboxed, but the flag ‘allow-downloads’ is not set. See
  https://www.chromestatus.com/feature/5706745674465280 for more
  details.

When following the above link, it provides the following information:

Chrome is planning on removing this capability - i.e. Chrome is going
  to block all downloads initiated from or instantiated in a sandboxed
  iframe by default. The embedder may add "allow-downloads" to the
  sandbox attributes list to opt in. This allows content providers to
  restrict malicious or abusive downloads.

How can I add "allow-downloads" to the sandbox attributes in the Google Apps Script environment? Alternatively, is there a workaround to enable downloading files?

答: It is discussed here https://issuetracker.google.com/issues/157368720 that HtmlService.XFrameOptionsMode.ALLOWALL should set allow-downloads on GAS web app sandbox. We should watch this issue for changes.


问:
How do I overcome error 'Avoid using JavaScript keyword as "v-on" value'
How do I get rid of this error in my App.vue component?

Failed to compile.

./src/App.vue
    Module Error (from ./node_modules/eslint-loader/index.js):

C:\xampp2\htdocs\exchproto\src\App.vue
      15:69  error  Avoid using JavaScript keyword as "v-on" value: ""  vue/valid-v-on

✖ 1 problem (1 error, 0 warnings)

I tested the whole code (including sub-components) with CDN pull of vuejs/vuetify css/js etc and all worked well. This error only comes up as I am breaking down the code into components and doing everything by "yarn install". Been poking at it for some time with no luck.

```<code><template>
  <v-app>
   <v-app-bar app>
    <v-app-bar-nav-icon @click="drawer = !drawer"></v-app-bar-nav-icon>
    <v-spacer></v-spacer>

    <v-menu :offset-y="true">
     <template v-slot:activator="{ on }">
      <v-btn icon v-on="on">
        <v-icon>mdi-dots-horizontal</v-icon>
      </v-btn>
     </template>

     <v-list>
      <v-list-item v-for="(item, i) in rightMenuitems" :key="i" @click="">
       <v-list-item-title>{{ item.title }}</v-list-item-title>
      </v-list-item>
     </v-list>
    </v-menu>
   </v-app-bar>
   <!--router-view></!--router-view-->
  </v-app>
 </template>

 <script>

  export default {
   name: 'App',
   components: {},
   data() {
    return {
     drawer: false,
     rightMenuitems: [
      { title: 'Choice 1' },
      { title: 'Choice 2' },
      { title: 'Choice 3' },
      { title: 'Choice 4' }
     ],
    }
   }
  }
 </script>
</code>```

答:
Remove 'click event' and add to property in v-list-item where v-for is being used.

Note:

You can bind links with the to props, and also links in every objects of rightMenuitems.

Here is an example:

Body:
How do I get rid of this error in my App.vue component?

Failed to compile.

./src/App.vue
    Module Error (from ./node_modules/eslint-loader/index.js):

C:\xampp2\htdocs\exchproto\src\App.vue
      15:69  error  Avoid using JavaScript keyword as "v-on" value: ""  vue/valid-v-on

✖ 1 problem (1 error, 0 warnings)

I tested the whole code (including sub-components) with CDN pull of vuejs/vuetify css/js etc and all worked well. This error only comes up as I am breaking down the code into components and doing everything by "yarn install". Been poking at it for some time with no luck.

<template>
  <v-app>
   <v-app-bar app>
    <v-app-bar-nav-icon @click="drawer = !drawer"></v-app-bar-nav-icon>
    <v-spacer></v-spacer>

    <v-menu :offset-y="true">
     <template v-slot:activator="{ on }">
      <v-btn icon v-on="on">
        <v-icon>mdi-dots-horizontal</v-icon>
      </v-btn>
     </template>

     <v-list>
      <v-list-item v-for="(item, i) in rightMenuitems" :key="i" @click="">
       <v-list-item-title>{{ item.title }}</v-list-item-title>
      </v-list-item>
     </v-list>
    </v-menu>
   </v-app-bar>

  </v-app>
 </template>


问:
Using R to remove all columns that sum to 0
I have a very large CSV file containing counts of unique DNA sequences, and there is a column for each unique sequence. I started with hundreds of samples and cut it down to only 15 that I care about but now I have THOUSANDS of columns that contain nothing but Zeroes and it is messing up my data processing. How do I go about completely removing any column that sums to zero? I’ve seen some similar questions on here but none of those suggestions have worked for me.

I have 6653 columns and 16 rows in my data frame.

If it matters my columns all have super crazy names, some several hundred characters long ( AATCGGCTAA..., etc) and the row names are the sample IDs which are also not entirely numeric. Any tips greatly appreciated. I am still new to R so please let me know where I will need to change things in code examples if you can! Thanks!

Body:
You can use colSums

set.seed(10)
df <- as.data.frame(matrix(sample(0:1, 50, replace = TRUE, prob = c(.8, .2)),
                           5, 10))

df
#  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
# 1  0  0  0  0  1  0  0  0  0   0
# 2  0  0  0  0  0  1  0  1  0   0
# 3  0  0  0  0  0  0  0  1  0   0
# 4  0  0  0  0  0  0  1  0  0   0
# 5  0  0  0  1  0  0  0  0  0   1

df[colSums(df) != 0]
#   V4 V5 V6 V7 V8 V10
# 1  0  1  0  0  0   0
# 2  0  0  1  0  1   0
# 3  0  0  0  0  1   0
# 4  0  0  0  1  0   0
# 5  1  0  0  0  0   1

But you might not want to remove all columns which sum to 0, because that could be true even if not all elements are 0. Take V4 in the data frame below as an example.

df$V4[1] <- -1
df
#   V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
# 1  0  0  0 -1  1  0  0  0  0   0
# 2  0  0  0  0  0  1  0  1  0   0
# 3  0  0  0  0  0  0  0  1  0   0
# 4  0  0  0  0  0  0  1  0  0   0
# 5  0  0  0  1  0  0  0  0  0   1

So if you want to only remove columns where all elements are 0, you can do

df[colSums(df == 0) < nrow(df)]
#   V4 V5 V6 V7 V8 V10
# 1 -1  1  0  0  0   0
# 2  0  0  1  0  1   0
# 3  0  0  0  0  1   0
# 4  0  0  0  1  0   0
# 5  1  0  0  0  0   1


问:
Return Stripe Session.id from Django view
Im trying to implement Stripe Payment API into my django site.
From my cart.html page I have a button that goes to my checkoutView and creates Products and Prices from the cart:

```<code>def checkout(request):
    customer = request.user.customer
    order = Order.objects.get(customer=customer)
    items = order.orderitem_set.all()
    prices =[]
    for item in items:
        product =stripe.Product.create(
            name = item.product.name,
            description= item.product.description
        )
        price = stripe.Price.create(
            product= product.id,
            unit_amount=int(item.product.price.amount)*100,
            currency='gbp',
        )
        prices.append(price.id)

    line_items=[]
    for item, price in zip(items,prices):
            line_items.append({'price':price,'quantity':item.quantity}),
    session = stripe.checkout.Session.create(
    payment_method_types=['card'],
    line_items=line_items,

    mode='payment',
    success_url='http://127.0.0.1:8000/SUCCESS/?session_id={CHECKOUT_SESSION_ID}',
    cancel_url='http://127.0.0.1:8000/'
    )
</code>```

I then have to redirect to Stripes checkout Docs here. I would like to call this from a button on my cart but im not sure how to get the SessionId from the view BACK to the template and call this.

Any help would be greatly appreciated.

答:
Typically you would pass the Session ID into your view, or use an asynchronous request to create the session from your backend. For example:

from django.shortcuts import render

def build_checkout_session(customer):
  # Use your existing code to create Products, Prices, etc...
  session = stripe.checkout.Session.create(…)
  return session

def checkout_view(request):
  session = build_checkout_session(customer=request.user.customer)
  return render(request, 'checkout.html', {'session_id': session.id})
```

<p>Then, in your checkout.html:</p>

<pre class="lang-html prettyprint-override"><code><script src="https://js.stripe.com/v3/"></script>
<script type="text/javascript">
  const sessionID = "{{ session_id }}";

  const stripe = Stripe("pk_test_12345"); // Put your publishable key here
  document.getElementById('checkoutButton').addEventListener('click' (evt) => {
    evt.preventDefault();
    stripe.redirectToCheckout({sessionId: sessionID});
  });
</script>
</code>```

I wanted to note also that rather than create Products and Prices each time, you can pass ad-hoc data into the Checkout Session as shown here: https://stripe.com/docs/payments/checkout/accept-a-payment#creating-ad-hoc-prices

Body:
Im trying to implement Stripe Payment API into my django site.
From my cart.html page I have a button that goes to my checkoutView and creates Products and Prices from the cart:

def checkout(request):
    customer = request.user.customer
    order = Order.objects.get(customer=customer)
    items = order.orderitem_set.all()
    prices =[]
    for item in items:
        product =stripe.Product.create(
            name = item.product.name,
            description= item.product.description
        )
        price = stripe.Price.create(
            product= product.id,
            unit_amount=int(item.product.price.amount)*100,
            currency='gbp',
        )
        prices.append(price.id)

    line_items=[]
    for item, price in zip(items,prices):
            line_items.append({'price':price,'quantity':item.quantity}),
    session = stripe.checkout.Session.create(
    payment_method_types=['card'],
    line_items=line_items,

    mode='payment',
    success_url='http://127.0.0.1:8000/SUCCESS/?session_id={CHECKOUT_SESSION_ID}',
    cancel_url='http://127.0.0.1:8000/'
    )

I then have to redirect to Stripes checkout Docs here. I would like to call this from a button on my cart but im not sure how to get the SessionId from the view BACK to the template and call this.

Any help would be greatly appreciated.

Body:
Typically you would pass the Session ID into your view, or use an asynchronous request to create the session from your backend. For example:

from django.shortcuts import render

def build_checkout_session(customer):
  # Use your existing code to create Products, Prices, etc...
  session = stripe.checkout.Session.create(…)
  return session

def checkout_view(request):
  session = build_checkout_session(customer=request.user.customer)
  return render(request, 'checkout.html', {'session_id': session.id})

Then, in your checkout.html:

<script src="https://js.stripe.com/v3/"></script>
<script type="text/javascript">
  const sessionID = "{{ session_id }}";

  const stripe = Stripe("pk_test_12345"); // Put your publishable key here
  document.getElementById('checkoutButton').addEventListener('click' (evt) => {
    evt.preventDefault();
    stripe.redirectToCheckout({sessionId: sessionID});
  });
</script>

I wanted to note also that rather than create Products and Prices each time, you can pass ad-hoc data into the Checkout Session as shown here: https://stripe.com/docs/payments/checkout/accept-a-payment#creating-ad-hoc-prices


问:
unhandled rejection: action is undefined React js and Redux
I am new to Redux and  I have encountered this issue and cannot seem to find a solution for it.

I have several  API calls inside of thunks and they all work fine. This one however fails. It is different to the others in the sense that I am  implementing a search feature that uses payload. I have tried to debug it but can't seem to find where the error happens exactly.

this is the error that I get on the screen:

these are the action, reducer and code in the search component:

and this is the logic to connect the component to the store and access state and actions:

Surely it must be something I am not fully understanding, I hope you can make some sense out of this.

答:
You should change action.loadSearchResults.result to action.searchResults.result. I am assuming there is a key called result you are getting in your response from HomePageApi.searchResults(searchInput).

I know this because in your action you have this code:

export function searchMoviewResultsSuccess(searchResults) {
  return {
    type: types.SEARCH_RESULTS_SUCCESS,
    searchResults: searchResults // This is the key you should get in your reducer not `loadSearchResults`
  }
}
```


问:
HTML Content Overflowing the Page
Im working on a small site and I've encountered a problem where my website content overflows a little off the page by about 100px.

I want my content to not overflow where the user will have to always scroll to the right to see all of the content.

I have included a snippet of code here that I have made to replicate the problem. I have tried using the overflow property but it doesnt seem to change my result.

It may be the image I am using on my site (which I cant post here), but maybe thats too wide? I'm not sure why the content is overflowing all of a sudden. Thanks for any help!

.body
{
  width: 100%;
}

.flex-wrapper
{
  display: flex;
}

.image_div
{
  flex: 1;
}

.text_div
{
  flex: 1;
}

#image
{
  width: 90%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

<div class="flex-wrapper">
<div class="image_div">
<img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" id="image">
</div>

<div class="text_div">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
</div>

</body></code>```

答:
Firstly you should remove that dot in .body { and leave it just body { since if you put .body you're giving the css to a body class and you're not using any class named body and about you having a scrollbar on y axis.

I think you could use a viewport dimensions, adjust your div's to your screen and hide the overflow on y, but to make it more easy for you to understand check the code below

body
{
  width: 100%;
  max-height:100%;
  overflow-y:hidden;
  overflow-x:scroll;
}

.flex-wrapper
{
  display: flex;
  height:80vh;
}

.image_div
{
  flex: 1;
}

.text_div
{
  flex: 1;
  height:70%;
}

#image
{
  width: 70%;
height:70%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div style="height:20vh;"><p style="height:80%;overflow:auto">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

<div class="flex-wrapper">
<div class="image_div">
<img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" id="image">
</div>

<div class="text_div">
<p style="height:50%;overflow:auto;">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
</div>

</body></code>```

NOTE : The viewport work is a percentage of your screen with this i mean you have to divide your screen until reaching 100, on the example i gave you the top paragraph has 40% of the screen and the image and other text has 60% of the screen

Hope it helps

Title: HTML Content Overflowing the Page

Body:
Im working on a small site and I've encountered a problem where my website content overflows a little off the page by about 100px.

I want my content to not overflow where the user will have to always scroll to the right to see all of the content.

I have included a snippet of code here that I have made to replicate the problem. I have tried using the overflow property but it doesnt seem to change my result.

It may be the image I am using on my site (which I cant post here), but maybe thats too wide? I'm not sure why the content is overflowing all of a sudden. Thanks for any help!

.body
{
  width: 100%;
}

.flex-wrapper
{
  display: flex;
}

.image_div
{
  flex: 1;
}

.text_div
{
  flex: 1;
}

#image
{
  width: 90%;
}

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.

Body:
Firstly you should remove that dot in .body { and leave it just body { since if you put .body you're giving the css to a body class and you're not using any class named body and about you having a scrollbar on y axis.

I think you could use a viewport dimensions, adjust your div's to your screen and hide the overflow on y, but to make it more easy for you to understand check the code below

body
{
  width: 100%;
  max-height:100%;
  overflow-y:hidden;
  overflow-x:scroll;
}

.flex-wrapper
{
  display: flex;
  height:80vh;
}

.image_div
{
  flex: 1;
}

.text_div
{
  flex: 1;
  height:70%;
}

#image
{
  width: 70%;
height:70%;
}

<body>
<div style="height:20vh;"><p style="height:80%;overflow:auto">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

<div class="flex-wrapper">
<div class="image_div">
<img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80" id="image">
</div>

<div class="text_div">
<p style="height:50%;overflow:auto;">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
</div>

</body>

NOTE : The viewport work is a percentage of your screen with this i mean you have to divide your screen until reaching 100, on the example i gave you the top paragraph has 40% of the screen and the image and other text has 60% of the screen

Hope it helps


问:
PowerShell if elseif else
Wondering if anyone could please assist with below.

I've tried a few different ways to get the below code working. Have three possible outcomes.

UM enabled with 5 digit extension.

UM enabled with no 5 digit extension.

UM not enabled.

```<code>          #test for UM extension number#
          $um1 = Get-UmMailbox $user -ErrorAction SilentlyContinue | Select @{name=”Extensions”;expression={$_.Extensions -join “;”}} | ?{ $_.Extensions -match '^\d\d\d\d\d$' }
          $umextensionnumber = if ($um1) { $um1.Extensions } elseif (!$um1) { 'UM not enabled' } else { 'No UM Extension Number' }
</code>```

Any help would be greatly appreciated.

答:
Way easier to read (and reason about) with nested if's instead:

```<code>$umextensionnumber = if($um1){
  # UM is enabled, let's check the extension:
  if($um1.Extensions -match '\d\d\d\d\d'){
    $um1.Extensions
  }
  else {
    "No extension found"
  }
}
else {
  "UM not enabled"
}
</code>```

Title: PowerShell if elseif else

Body:
Wondering if anyone could please assist with below.

I've tried a few different ways to get the below code working. Have three possible outcomes.

UM enabled with 5 digit extension.

UM enabled with no 5 digit extension.

UM not enabled.

          #test for UM extension number#
          $um1 = Get-UmMailbox $user -ErrorAction SilentlyContinue | Select @{name=”Extensions”;expression={$_.Extensions -join “;”}} | ?{ $_.Extensions -match '^\d\d\d\d\d$' }
          $umextensionnumber = if ($um1) { $um1.Extensions } elseif (!$um1) { 'UM not enabled' } else { 'No UM Extension Number' }

Any help would be greatly appreciated.

Body:
Way easier to read (and reason about) with nested if's instead:

$umextensionnumber = if($um1){
  # UM is enabled, let's check the extension:
  if($um1.Extensions -match '\d\d\d\d\d'){
    $um1.Extensions
  }
  else {
    "No extension found"
  }
}
else {
  "UM not enabled"
}


问:
help with sql query join?
i have two tables with type(type,playerid) and player(playerid,date)
i have to find out for each year how many man of the match awards were won by which type of player ?

eg the table should be like

```<code>year type      noofawards
2011 batsmen       3
2011 bowler        5
2010 batsmen       2
</code>```

i can get the total number of awards won each year but cannot segregate them on type so what i get is

```<code>year noofawards
2011     3

select year , count(year) as "Number of awards"
from
(
select to_char(p.date,'YYYY') as year
from player p, type t
where p.playerid = t.playerid
)
group by year
order by year;
</code>```

what should i do?

答:
This should work:</p>

```<code>SELECT year,
       type,
       COUNT(*) as number
FROM (
       SELECT type,
              to_char(player.date,'YYYY') as year
       FROM player
       NATURAL JOIN type
     ) AS T
GROUP BY year,
         type
</code>```

ContentLicense: CC BY-SA 3.0

Title: help with sql query join?

Body:
i have two tables with type(type,playerid) and player(playerid,date)
i have to find out for each year how many man of the match awards were won by which type of player ?

eg the table should be like

year type      noofawards
2011 batsmen       3
2011 bowler        5
2010 batsmen       2

i can get the total number of awards won each year but cannot segregate them on type so what i get is

year noofawards
2011     3

select year , count(year) as "Number of awards"
from
(
select to_char(p.date,'YYYY') as year
from player p, type t
where p.playerid = t.playerid
)
group by year
order by year;

what should i do?

Body:
This should work:

SELECT year,
       type,
       COUNT(*) as number
FROM (
       SELECT type,
              to_char(player.date,'YYYY') as year
       FROM player
       NATURAL JOIN type
     ) AS T
GROUP BY year,
         type


问:
How to do background sync instead of fetch requests on UI changes?
For example, let's take a simple web application with comments feature. In my understanding, when a user posts a new comment, the following would occur:

display UI loader;

update the front-end state;

send a fetch request to the API to post a new comment;

Wait for the response;

send another fetch request to the API to request the new list of comments;

waiting;

update the front-end state with new comments;

update UI to reflect the new state with a new comment;

And the user needs to wait while front-end app interacts with back-end on almost every data change. The same way we did it earlier with PHP/Python/Ruby, ajax, server-side rendering and templates.

That makes me think what's the point of adding so much front-end complexity with something like react, when the result is basically the same.

My question is: are there any alternative approaches to this? Is it possible instead to do the above case the following way:

user clicks to post a comment;

update the front-end state;

update UI to reflect the new state with a new comment;

sync front-end state with API DB in the background;

答:
You definitely could, your first method is just way of doing it.

Apart from 'syncing' your front-end state, another method is also to just pre-emptively update the UI (step 7 & 8 in your first method) before doing step 3-6, and only reverse the action if the API call failed. This should allow for slightly better UX for the end-user too.


问:
Getstream.io - Sending one message to many channels
What is the best pattern for sending one message from one user to many 'messaging' channels? In my case, it could be as many as 300 or more. From reviewing the documentation, it looks like I need to query the channels 30 at a time, then iterate through those channels and send a message to each one. That seems very cumbersome and I was wondering if there was a better way. Would using Mult-Tenant and Teams be a solution somehow?</p>

答:
Unfortunately, the way you explained (query -> send -> repeat) is the solution.

A batch endpoint would be useful but it might be more involved than expected due to unread message maintenance, push notifications, etc.

However, it's not there today and not planned for very soon either.


问:
How to set different time slots for a single https requests in jmeter
I have a http request where I need to send random time values in given time frame

Request looks like this:
http://domain/api1?&mt=getEmp&punchTime=1590678744

I've shifts pre-defined
Morning: 0900 to 1400
Evening: 1400 to 1900
Night: 1900 to 2300
Expectation is: random epoch time value between pre-defined shift time slot should be put as punch-time for each request.

I don't want to separate out the request as per different time shifts.

Could anyone please help me to achieve this with JMeter?

答:
You can calculate the random time stamp in the given range using a suitable JSR223 Test Element and Groovy language.

Example code which produces random time between 9 and 14 hour of the current day and store it into randomMorningTime JMeter Variable would be something like:

```<code>def calendar = Calendar.getInstance()
def morningStart = new GregorianCalendar(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 9, 00).getTimeInMillis()
def morningEnd = new GregorianCalendar(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 14, 00).getTimeInMillis()

def randomMorningTime = org.apache.commons.lang3.RandomUtils.nextLong(morningStart, morningEnd)
def timestamp = ( randomMorningTime / 1000).round() as String
log.info('Random morning time for current day: ' + new Date(randomMorningTime))
log.info('Associated timestamp: ' + timestamp)
vars.put('randomMorningTime', timestamp)
</code>```

Demo:

You will be able to access the generated value as ${randomMorningTime} where required.

See JavaDoc on GregorianCalendar class for more information

Body:
You can calculate the random time stamp in the given range using a suitable JSR223 Test Element and Groovy language.

Example code which produces random time between 9 and 14 hour of the current day and store it into randomMorningTime JMeter Variable would be something like:

def calendar = Calendar.getInstance()
def morningStart = new GregorianCalendar(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 9, 00).getTimeInMillis()
def morningEnd = new GregorianCalendar(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 14, 00).getTimeInMillis()

def randomMorningTime = org.apache.commons.lang3.RandomUtils.nextLong(morningStart, morningEnd)
def timestamp = ( randomMorningTime / 1000).round() as String
log.info('Random morning time for current day: ' + new Date(randomMorningTime))
log.info('Associated timestamp: ' + timestamp)
vars.put('randomMorningTime', timestamp)

Demo:

You will be able to access the generated value as ${randomMorningTime} where required.

See JavaDoc on GregorianCalendar class for more information


问:
Replace string between first and second occurrence of forward slash
i'm not very familiar with regex and i need help replacing a string value between the first and second occurrence of forward slash in it.

Example

```<code>const str = '/questions/ask/1'
const strReplace = str.replace(/\[.*?\]\s?/g, 'example')

</code>```

Output:

/questions/ask/1 to /example/ask/1

/questions-math/ask/1 to /example/ask/1

I can't seem to get right regex.
Thanks for any help. I know there are lot of similar questions but I just could not find a solution.

答:
You can use the below regex:

```<code>^(\/)(?:[-\w!#$]+)(.*?)$
</code>```

Explanation of the regex:

^ - Represents the start of the given string.

(\/) - Represents 1st capturing group. This group is used in the replacement as $1.

(?:[-\w!#$]+) - Represents a non-capturing group since you need to replace it containing word characters and all the special symbols that you need to replace one or more times. You can although add other special symbols that you need to exclude here.

(.*?) - Represents 2nd capturing group capturing everything except the new line character lazily coming after your replacement. This group is used in the replacement as $2.

$ - Represents the end of the given test String.

You can find the demo of the above regex in here.

IMPLEMENTATION IN JAVASCRIPT:

const regex = /^(\/)(?:[-\w!#$]+)(.*?)$/gm;
const str = `/questions-math/ask/1
/questions/ask/1`;
const subst = `$1examples$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);```

Body:
i'm not very familiar with regex and i need help replacing a string value between the first and second occurrence of forward slash in it.

Example

const str = '/questions/ask/1'
const strReplace = str.replace(/\[.*?\]\s?/g, 'example')

Output:

/questions/ask/1 to /example/ask/1

/questions-math/ask/1 to /example/ask/1

I can't seem to get right regex.
Thanks for any help. I know there are lot of similar questions but I just could not find a solution.

Body:
You can use the below regex:

^(\/)(?:[-\w!#$]+)(.*?)$

Explanation of the regex:

^ - Represents the start of the given string.

(\/) - Represents 1st capturing group. This group is used in the replacement as $1.

(?:[-\w!#$]+) - Represents a non-capturing group since you need to replace it containing word characters and all the special symbols that you need to replace one or more times. You can although add other special symbols that you need to exclude here.

(.*?) - Represents 2nd capturing group capturing everything except the new line character lazily coming after your replacement. This group is used in the replacement as $2.

$ - Represents the end of the given test String.

You can find the demo of the above regex in here.

IMPLEMENTATION IN JAVASCRIPT:

const regex = /^(\/)(?:[-\w!#$]+)(.*?)$/gm;
const str = `/questions-math/ask/1
/questions/ask/1`;
const subst = `$1examples$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);


问:
How to make user interest prediction for article reading
I am trying to get user interest prediction on the daily articles read for an website by using below sample data :

```<code>from datetime import date, timedelta
import pandas as pd
import numpy as np
sdate = date(2019,1,1)   # start date
edate = date(2019,1,7)   # end date -6days

required_dates = pd.date_range(sdate,edate-timedelta(days=1),freq='d')
# initialize list of lists
data = [['2019-01-01', 1000,101], ['2019-01-03', 1000,201] ,['2019-01-02', 1500,301],
        ['2019-01-02', 1400,101],['2019-01-04', 1500,201],['2019-01-01', 2000,201],
        ['2019-01-04', 2000,101],['2019-01-04', 1400,301],['2019-01-05', 1400,301],['2019-01-05', 1400,301]]
# Create the pandas DataFrame
df1 = pd.DataFrame(data, columns = ['OnlyDate', 'ArticleID','UserID'])
df1=df1[['OnlyDate','UserID','ArticleID']]
df1.sort_values(by=['UserID','ArticleID'],inplace=True)
df1.reset_index(inplace=True,drop=True)
# raw data
raw_data= df1

# Final Data
final_data= (df1.groupby(['OnlyDate','UserID','ArticleID'])
    .size()
    .unstack('OnlyDate', fill_value=0)
    .unstack('UserID', fill_value=0)
    .unstack()
    .reset_index(name='InterestValue'))
</code>```

My Data looks like :

Now I am using XGB model :

```<code>import xgboost as xgb
from sklearn.model_selection import KFold, cross_val_score, train_test_split
# converting data for model
final_data['OnlyDate']=pd.to_datetime(final_data['OnlyDate'],format="%Y-%m-%d")
final_data['OnlyDate']= final_data['OnlyDate'].dt.strftime('%Y%m%d')
final_data['OnlyDate']=final_data['OnlyDate'].astype(np.int64)
final_data.info()
# splitting data
X, y = final_data.drop('InterestValue',axis=1), final_data.InterestValue
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=44)
print(X.shape,y.shape,X_train.shape, X_test.shape, y_train.shape, y_test.shape)
xgb_model = xgb.XGBClassifier().fit(X_train, y_train)
print('Accuracy of XGB classifier on training set: {:.2f}'
       .format(xgb_model.score(X_train, y_train)))
print('Accuracy of XGB classifier on test set: {:.2f}'
       .format(xgb_model.score(X_test[X_train.columns], y_test)))
#making prediction here
y_pred = xgb_model.predict(X_test)
#Checking how data looks after prediction
X_test_afterPrediction = X_test.copy()
X_test_afterPrediction['InterestValue']= y_test
X_test_afterPrediction['PredictedValues'] = y_pred
X_test_afterPrediction
</code>```

Prediction output looks like :

Currently with my original dataset I am getting only 20% prediction were correct.
Let me know which are the other ways or models I should use to improve my prediction rate?

Edit:  with LSTM multivariante I am able to predict for single user data at a time with 28% prediction rate.

答:
Well, this is a really really broad question, did you do EDA? Because my first question would be what's the distribution for InterestValue. And further than that, what is the distribution on ANY of those data fields.

If interestvalues are mostly zeros then the model is going to fit more zeros, in that case, stratification in your sampling will help a lot, is it a binary prediction or multiclass?

Also, what sort of tuning did you do on this model, it looks like it's just the default hyperparameters.

Body:
I am trying to get user interest prediction on the daily articles read for an website by using below sample data :

from datetime import date, timedelta
import pandas as pd
import numpy as np
sdate = date(2019,1,1)   # start date
edate = date(2019,1,7)   # end date -6days

required_dates = pd.date_range(sdate,edate-timedelta(days=1),freq='d')
# initialize list of lists
data = [['2019-01-01', 1000,101], ['2019-01-03', 1000,201] ,['2019-01-02', 1500,301],
        ['2019-01-02', 1400,101],['2019-01-04', 1500,201],['2019-01-01', 2000,201],
        ['2019-01-04', 2000,101],['2019-01-04', 1400,301],['2019-01-05', 1400,301],['2019-01-05', 1400,301]]
# Create the pandas DataFrame
df1 = pd.DataFrame(data, columns = ['OnlyDate', 'ArticleID','UserID'])
df1=df1[['OnlyDate','UserID','ArticleID']]
df1.sort_values(by=['UserID','ArticleID'],inplace=True)
df1.reset_index(inplace=True,drop=True)
# raw data
raw_data= df1

# Final Data
final_data= (df1.groupby(['OnlyDate','UserID','ArticleID'])
    .size()
    .unstack('OnlyDate', fill_value=0)
    .unstack('UserID', fill_value=0)
    .unstack()
    .reset_index(name='InterestValue'))

My Data looks like :

Now I am using XGB model :

import xgboost as xgb
from sklearn.model_selection import KFold, cross_val_score, train_test_split
# converting data for model
final_data['OnlyDate']=pd.to_datetime(final_data['OnlyDate'],format="%Y-%m-%d")
final_data['OnlyDate']= final_data['OnlyDate'].dt.strftime('%Y%m%d')
final_data['OnlyDate']=final_data['OnlyDate'].astype(np.int64)
final_data.info()
# splitting data
X, y = final_data.drop('InterestValue',axis=1), final_data.InterestValue
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=44)
print(X.shape,y.shape,X_train.shape, X_test.shape, y_train.shape, y_test.shape)
xgb_model = xgb.XGBClassifier().fit(X_train, y_train)
print('Accuracy of XGB classifier on training set: {:.2f}'
       .format(xgb_model.score(X_train, y_train)))
print('Accuracy of XGB classifier on test set: {:.2f}'
       .format(xgb_model.score(X_test[X_train.columns], y_test)))
#making prediction here
y_pred = xgb_model.predict(X_test)
#Checking how data looks after prediction
X_test_afterPrediction = X_test.copy()
X_test_afterPrediction['InterestValue']= y_test
X_test_afterPrediction['PredictedValues'] = y_pred
X_test_afterPrediction

Prediction output looks like :

Currently with my original dataset I am getting only 20% prediction were correct.
Let me know which are the other ways or models I should use to improve my prediction rate?

Edit:  with LSTM multivariante I am able to predict for single user data at a time with 28% prediction rate.


问:
How do I perform an operation iteratively on a python list/array whithout a for loop?
Is it possible to perform the following operation on the first two elements of the list, storing the result and then performing the next operation on the previous result and the next item in the list for all items in the list without a for loop? Here F(x) is an arbitrarily defined function.
This is the working code with a for loop:

```<code>list   = [a,b,c,d,e,f,g,h]
result = F(a,b)

for i in range(2,len(list)):
    result = F(result,list[i])

print(result)
</code>```

Thank you very much in advance, the best answer gets a pancake.

答:
Yes, this is a reduction:

```<code>from functools import reduce

result = reduce(F, list)
</code>```

reduce applies a function to an accumulator (result), along with each element of a list. In the first iteration though, if you don't specify an initial accumulator, it will use the initial element as the accumulator.

Body:
Is it possible to perform the following operation on the first two elements of the list, storing the result and then performing the next operation on the previous result and the next item in the list for all items in the list without a for loop? Here F(x) is an arbitrarily defined function.
This is the working code with a for loop:

list   = [a,b,c,d,e,f,g,h]
result = F(a,b)

for i in range(2,len(list)):
    result = F(result,list[i])

print(result)

Thank you very much in advance, the best answer gets a pancake.

Body:
Yes, this is a reduction:

from functools import reduce

result = reduce(F, list)

reduce applies a function to an accumulator (result), along with each element of a list. In the first iteration though, if you don't specify an initial accumulator, it will use the initial element as the accumulator.


问:
Is there a better way to convert byte array to an int?
The first 3 bytes of a byte array are just integers, is there a better way to convert them? So far I have this but it just feels like a bad way of doing it.</p>

```<code>public int parse_code(byte[] bs) {
    char[] array = new char[3];
    for(int i = 0; i < 3; i++) {
        array[i] = (char) bs[i];
    }

    // Dirty way of doing it
    return Integer.parseInt(new String(array));
}
</code>```

答:
It looks like you are trying to convert three byte of ASCII text like 123 as [49, 50, 51] to 123.

```<code>public static long parse_code(byte... bs) {
    long value = 0;
    for(byte b: bs)
       value = value * 10 + b - '0';
    return value;
}
</code>```

if you know it will always be 3 bytes.

```<code>public static int parse_code(byte... bs) {
    return bs[0]*100 + bs[1]*10 + bs[2] - '0' * 111;
}
</code>```

Body:
The first 3 bytes of a byte array are just integers, is there a better way to convert them? So far I have this but it just feels like a bad way of doing it.

public int parse_code(byte[] bs) {
    char[] array = new char[3];
    for(int i = 0; i < 3; i++) {
        array[i] = (char) bs[i];
    }

    // Dirty way of doing it
    return Integer.parseInt(new String(array));
}

Body:
It looks like you are trying to convert three byte of ASCII text like 123 as [49, 50, 51] to 123.

public static long parse_code(byte... bs) {
    long value = 0;
    for(byte b: bs)
       value = value * 10 + b - '0';
    return value;
}

if you know it will always be 3 bytes.

public static int parse_code(byte... bs) {
    return bs[0]*100 + bs[1]*10 + bs[2] - '0' * 111;
}


问:
Is there any way to get the date N days from now in AIML 1.0?
I need the date (say) 7 days from now as a  variable but couldn't find any implementation for the same for AIML version 1.0</p>

答:
You can put the date of today in a variable and use a loop with successor to add 7days.
Or build a map with all the dates and use a loop with this map to add 7days.</p>


问:
Unable to read a cab file using pandas
I am trying to read a file named Data.csv using the code: pd.read_csv("Data.csv") through pandas but it is showing  'FileNotFoundError: [Errno 2] File does not exist:

Even though I have the file in the system.

答:
Given the information you provided, my best guess is that the directory containing your file 'Data.csv' isn't your python working directory (most of the time, it corresponds to the directory from which you executed your python script).

If you're not sure, here's an easy way to check what your python working directory is:

import os
print(os.getcwd())
```

Now, let's say your working directory is ~/projetct and your file is located here: ~/projetct/files/Data.csv

You can open your file by using pd.read_csv("./files/Data.csv")

Title: Unable to read a cab file using pandas

Body:
Given the information you provided, my best guess is that the directory containing your file 'Data.csv' isn't your python working directory (most of the time, it corresponds to the directory from which you executed your python script).

If you're not sure, here's an easy way to check what your python working directory is:

import os
print(os.getcwd())

Now, let's say your working directory is ~/projetct and your file is located here: ~/projetct/files/Data.csv

You can open your file by using pd.read_csv("./files/Data.csv")


问:
How to copy files from host to Docker container?
I am trying to build a backup and restore solution for the Docker containers that we work with.

I have Docker base image that I have created, ubuntu:base, and do not want have to rebuild it each time with a Docker file to add files to it.

I want to create a script that runs from the host machine and creates a new container using the ubuntu:base Docker image and then copies files into that container.

How can I copy files from the host to the container?

答:
Copy from container to host dir

```<code>docker cp [container-name/id]:./app/[index.js] index.js
</code>```

(assume you have created a workdir /app in your dockerfile)

Copy from host to container

```<code>docker cp index.js [container-name/id]:./app/index.js
</code>```

Body:
Copy from container to host dir

docker cp [container-name/id]:./app/[index.js] index.js

(assume you have created a workdir /app in your dockerfile)

Copy from host to container

docker cp index.js [container-name/id]:./app/index.js


问:
How to connect to 2 different rabbitmq clusters from a service which has in the configuration defined spring.rabbitmq.addresses
we have some services sharing basic common configuration to connect with different external systems (DBs, Rabbitmq, etc) and common setup.

One of the variables we have for rabbitmq is spring.rabbitmq.addresses with the main cluster, which is overwritten when we want to connect to another cluster from a service, but we are connecting just to one of them.
 We are trying to modify one service to connect to 2 different clusters, but always prevails the value from spring.rabbitmq.addresses.

We tried following the documentation (https://cloud.spring.io/spring-cloud-static/spring-cloud.html#multiple-systems), with something like:

```<code>spring.rabbitmq.addresses: host-rabbitmq2:5672

spring.cloud.stream:
  binders:
    rabbitInput:
      defaultCandidate: false
      type: rabbit
      environment.spring.rabbitmq.host: host-rabbitmq1:5672
    rabbitOutput:
      defaultCandidate: false
      type: rabbit
      environment.spring.rabbitmq.host: host-rabbitmq1:5672
    rabbitMainClusterInput:
      defaultCandidate: false
      type: rabbit
      environment.spring.rabbitmq.host: host-rabbitmq2:5672
</code>```

But always was using the cluster defined in spring.rabbitmq.addresses.

Another attempt was setting an environment for the binder, something like:

```<code>spring.rabbitmq.addresses: host-rabbitmq2:5672

 spring.cloud:
   config:
     override-system-properties: false
     allowOverride: true
     overrideNone: true
   stream:
     binders:
       rabbitDefaultInput:
         inheritEnvironment: false
         defaultCandidate: false
         type: rabbit
         environment.spring.rabbitmq:
           host: host-rabbitmq1:5672
           username: xxxxxx
           password: yyyyyy
</code>```

With the same result.

Another attempt was putting both clusters in the variable spring.rabbitmq.addresses,

```<code>spring.rabbitmq.addresses: host-rabbitmq2:5672,host-rabbitmq1:5672
</code>```

but the result was that, it opened connections with the 2 clusters, but only connected with the queues in cluster that was the first in the list.

The question is, if there is any way to without removing the spring.rabbitmq.addresses variable, to connect to 2 different clusters using spring cloud stream?

thanks in advance

答:
addresses overrides host and by default, the binders inherit the parent environment - have you tried using addresses in the binder environments instead of host?

You can also set inheritEnvironment to false.

Body:
we have some services sharing basic common configuration to connect with different external systems (DBs, Rabbitmq, etc) and common setup.

One of the variables we have for rabbitmq is spring.rabbitmq.addresses with the main cluster, which is overwritten when we want to connect to another cluster from a service, but we are connecting just to one of them.
 We are trying to modify one service to connect to 2 different clusters, but always prevails the value from spring.rabbitmq.addresses.

We tried following the documentation (https://cloud.spring.io/spring-cloud-static/spring-cloud.html#multiple-systems), with something like:

spring.rabbitmq.addresses: host-rabbitmq2:5672

spring.cloud.stream:
  binders:
    rabbitInput:
      defaultCandidate: false
      type: rabbit
      environment.spring.rabbitmq.host: host-rabbitmq1:5672
    rabbitOutput:
      defaultCandidate: false
      type: rabbit
      environment.spring.rabbitmq.host: host-rabbitmq1:5672
    rabbitMainClusterInput:
      defaultCandidate: false
      type: rabbit
      environment.spring.rabbitmq.host: host-rabbitmq2:5672

But always was using the cluster defined in spring.rabbitmq.addresses.

Another attempt was setting an environment for the binder, something like:

spring.rabbitmq.addresses: host-rabbitmq2:5672

 spring.cloud:
   config:
     override-system-properties: false
     allowOverride: true
     overrideNone: true
   stream:
     binders:
       rabbitDefaultInput:
         inheritEnvironment: false
         defaultCandidate: false
         type: rabbit
         environment.spring.rabbitmq:
           host: host-rabbitmq1:5672
           username: xxxxxx
           password: yyyyyy

With the same result.

Another attempt was putting both clusters in the variable spring.rabbitmq.addresses,

spring.rabbitmq.addresses: host-rabbitmq2:5672,host-rabbitmq1:5672

but the result was that, it opened connections with the 2 clusters, but only connected with the queues in cluster that was the first in the list.

The question is, if there is any way to without removing the spring.rabbitmq.addresses variable, to connect to 2 different clusters using spring cloud stream?

thanks in advance


问:
What steps should I take to build and run .net core Web API application in 32-bit environment/runtime?
We developed an a .NET Core Web API application using the following technologies:

-NET Core (3.1)

-Visual Studio 2019

Unfortunately, we have to deploy said application to the following environment:

-32-bit Environment

-Windows Server 2008 R2 Enterprise (Service Pack 1)

-IIS Version 7.5

-8 GB RAM

Therefore, within my Visual Studio 2019, I brought up the application, and took the following steps:

Force x86 in VS go to the Properties > Build and change Platform target from Any CPU to x86

Created a  Directory.Build.targets in the the .NET Core application's Project root directory:

```<code><Project>

      <PropertyGroup

      Condition="'$(OS)' == 'Windows_NT' and

                 '$(PlatformTarget)' == 'x86' and

                 '$(TargetFrameworkIdentifier)' == '.NETCoreApp' and

                 '$(SelfContained)' != 'true'"

                  >

       <RunCommand>$(MSBuildProgramFiles32)\dotnet\dotnet</RunCommand>

      </PropertyGroup>

< /Project >
</code>```

From Visual Studio 2019 Developer Command Prompt v16.4.6, I navigated to the .NET Core application's Project root directory.

I ran:

>
>

```<code>dotnet clean
...........................
.............

dotnet build

C:\Program
Files\dotnet\sdk\3.1.101\Microsoft.Common.CurrentVersion.targets(2726,5):
error MSB4216: Could not run the "ResolveComReference" task because
MSBuild could not create or connect to a task host with runtime "CLR4"
and architecture "x86".  Please ensure that (1) the requested runtime
and/or architecture are available on the machine, and (2) that the
required executable "C:\Program Files\dotnet\sdk\3.1.101\MSBuild.exe"
exists and can be run.
[D:\ blah blah.csproj]
    6 Warning(s)
    1 Error(s)

Time Elapsed 00:00:04.63'
</code>```

Could someone please tell me how I can build and run this application in a 32-bit environment?

答:
@akseli @omajid @perry-qian-msft @yongqing-yu Sorry, this failed to work, we had to move away from using .NET Core technology( and had to migrate over to .NET Framework 4.7.2) because it would work properly for a little while, and then give us 500 error, and then later some 401 error.  I think it has something to do with the configuration because we are using:

-NET Core (3.1)

-In-Process within IIS Server

therefore, Within the standalone IIS Server, we should Not have to run  the .NET Core (3.1) application within it's own application pool as "Not Managed Code" because it's all In-Process and .NET Core (3.1) can run on IIS.  In any case, we do Not have time to resolve this problem so we migrate over to .NET Framework 4.7.2

@akseli @omajid @perry-qian-msft @yongqing-yu All Thank you for all your responses.
My Team Tech Lead found the solution by specifying the .NET Core Web API Application's Build Settings to "Any CPU" Within Visual Studio 2019. ( Within Visual Studio 2019, Right-click on .NET Core Web API Application, and then choose properties from the drop-down context menu, and then when the window pane shows up on, you select the Build Tab. )

Also, on the IIS Server, my Team Tech Lead ensured that that deployed .NET Core Web API Application's Application pool had the following settings( important to keep in mind that it is "Not Managed Code":

Body:
We developed an a .NET Core Web API application using the following technologies:

-NET Core (3.1)

-Visual Studio 2019

Unfortunately, we have to deploy said application to the following environment:

-32-bit Environment

-Windows Server 2008 R2 Enterprise (Service Pack 1)

-IIS Version 7.5

-8 GB RAM

Therefore, within my Visual Studio 2019, I brought up the application, and took the following steps:

Force x86 in VS go to the Properties > Build and change Platform target from Any CPU to x86

Created a  Directory.Build.targets in the the .NET Core application's Project root directory:

<Project>

      <PropertyGroup

      Condition="'$(OS)' == 'Windows_NT' and

                 '$(PlatformTarget)' == 'x86' and

                 '$(TargetFrameworkIdentifier)' == '.NETCoreApp' and

                 '$(SelfContained)' != 'true'"

                  >

       <RunCommand>$(MSBuildProgramFiles32)\dotnet\dotnet</RunCommand>

      </PropertyGroup>

< /Project >

From Visual Studio 2019 Developer Command Prompt v16.4.6, I navigated to the .NET Core application's Project root directory.

I ran:

>
>

dotnet clean
...........................
.............

dotnet build

C:\Program
Files\dotnet\sdk\3.1.101\Microsoft.Common.CurrentVersion.targets(2726,5):
error MSB4216: Could not run the "ResolveComReference" task because
MSBuild could not create or connect to a task host with runtime "CLR4"
and architecture "x86".  Please ensure that (1) the requested runtime
and/or architecture are available on the machine, and (2) that the
required executable "C:\Program Files\dotnet\sdk\3.1.101\MSBuild.exe"
exists and can be run.
[D:\ blah blah.csproj]
    6 Warning(s)
    1 Error(s)

Time Elapsed 00:00:04.63'

Could someone please tell me how I can build and run this application in a 32-bit environment?


问:
Was there a good reason for redundant try catch code in original Microsoft Membership and Role Provider code?
I know that this is redundant (per Why does resharper say 'Catch clause with single 'throw' statement is redundant'?).

```<code>try
{
    bla bla bla
}
catch
{
    throw
}
</code>```

So, I'm going through the old Microsoft Membership and Role Provider code (made available since 2006 per http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx).  And, low and behold, the code is chock full of this redundant code.

Was there a good reason?

答: Microsoft's coding standards are not the same as Resharper's. Having redundant try/catch blocks isn't wrong, its just bad style. Much of the MS source code could have plenty of positive code standard changes (much of it lacks the use of var, for example).</p>

Body:
I know that this is redundant (per Why does resharper say 'Catch clause with single 'throw' statement is redundant'?).

try
{
    bla bla bla
}
catch
{
    throw
}

So, I'm going through the old Microsoft Membership and Role Provider code (made available since 2006 per http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx).  And, low and behold, the code is chock full of this redundant code.

Was there a good reason?


问:
adding values to pandas dataframe columns based on another dataframe
I have a dataframe that looks like this(df):

```<code>HOUSEID    PERSONID      WHY_TRP
20000017      1            1
20000017      1            1
20000017      1            1
20000017      2            1
20000017      2            3
20000231      1            11
20000231      1            11
20000231      2            11
20000521      1            11
20000521      2            11
20000521      2            3
</code>```

Each row describes a trip made by a person. I have another dataframe of the same kind in which each row describes a person(df_p):

```<code>    HOUSEID   PERSONID
    20000017      1
    20000017      2
    20000231      1
    20000231      2
    20000521      1
    20000521      2
</code>```

I want to make three new columns in the second dataframe to show the frequency of 1, 3 and 11 for each person. basically I already have a second dataframe (df_p) with other features so I shouldn't use groupby. for some reason the first and second dataframe don't have the same number of people. that's why I needed the strategy below. This is the code I tried but took hours to complete(1 million iterations):

```<code>df_p.insert(2, 'WHY_TRP_1', 0)
df_p.insert(3, 'WHY_TRP_2', 0)
df_p.insert(4, 'WHY_TRP_3', 0)

def trip_counter(i, r):
  if r[2] == 1:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] == r[1]), ['WHY_TRP_1']] += 1
  elif r[2] == 3:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_3']] += 1
  elif r[2] == 11:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_11']] += 1

for i ,r in df.iterrows():
  trip_counter(i ,r)
</code>```

output:

```<code>     HOUSEID   PERSONID   WHY_TRP_1     WHY_TRP_3      WHY_TRP_11
    20000017      1            3            0            0
    20000017      2            1            1            0
    20000231      1            0            0            2
    20000231      2            0            0            1
    20000521      1            0            0            1
    20000521      2            0            1            1
</code>```

Is there a faster way to do this?

thank you

答:
You could also do a pivot_table and then merge:

```<code>m = df.pivot_table(index=['HOUSEID','PERSONID'],
                   columns='WHY_TRP',aggfunc=len,fill_value=0)

out= df_p.merge(m.add_prefix('WHY_TRP'),left_on=['HOUSEID','PERSONID'],right_index=True)
</code>```

```<code>print(out)

    HOUSEID  PERSONID  WHY_TRP1  WHY_TRP3  WHY_TRP11
0  20000017         1         3         0          0
1  20000017         2         1         1          0
2  20000231         1         0         0          2
3  20000231         2         0         0          1
4  20000521         1         0         0          1
5  20000521         2         0         1          1
</code>```

Body:
I have a dataframe that looks like this(df):

HOUSEID    PERSONID      WHY_TRP
20000017      1            1
20000017      1            1
20000017      1            1
20000017      2            1
20000017      2            3
20000231      1            11
20000231      1            11
20000231      2            11
20000521      1            11
20000521      2            11
20000521      2            3

Each row describes a trip made by a person. I have another dataframe of the same kind in which each row describes a person(df_p):

    HOUSEID   PERSONID
    20000017      1
    20000017      2
    20000231      1
    20000231      2
    20000521      1
    20000521      2

I want to make three new columns in the second dataframe to show the frequency of 1, 3 and 11 for each person. basically I already have a second dataframe (df_p) with other features so I shouldn't use groupby. for some reason the first and second dataframe don't have the same number of people. that's why I needed the strategy below. This is the code I tried but took hours to complete(1 million iterations):

df_p.insert(2, 'WHY_TRP_1', 0)
df_p.insert(3, 'WHY_TRP_2', 0)
df_p.insert(4, 'WHY_TRP_3', 0)

def trip_counter(i, r):
  if r[2] == 1:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] == r[1]), ['WHY_TRP_1']] += 1
  elif r[2] == 3:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_3']] += 1
  elif r[2] == 11:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_11']] += 1

for i ,r in df.iterrows():
  trip_counter(i ,r)

output:

     HOUSEID   PERSONID   WHY_TRP_1     WHY_TRP_3      WHY_TRP_11
    20000017      1            3            0            0
    20000017      2            1            1            0
    20000231      1            0            0            2
    20000231      2            0            0            1
    20000521      1            0            0            1
    20000521      2            0            1            1

Is there a faster way to do this?

thank you

Body:
You could also do a pivot_table and then merge:

m = df.pivot_table(index=['HOUSEID','PERSONID'],
                   columns='WHY_TRP',aggfunc=len,fill_value=0)

out= df_p.merge(m.add_prefix('WHY_TRP'),left_on=['HOUSEID','PERSONID'],right_index=True)

print(out)

    HOUSEID  PERSONID  WHY_TRP1  WHY_TRP3  WHY_TRP11
0  20000017         1         3         0          0
1  20000017         2         1         1          0
2  20000231         1         0         0          2
3  20000231         2         0         0          1
4  20000521         1         0         0          1
5  20000521         2         0         1          1


答:
There is a reduce function to do this: https://www.geeksforgeeks.org/reduce-in-python/

# importing functools for reduce()
import functools

# initializing list
lis = [ 1 , 3, 5, 6, 2, ]

# using reduce to compute sum of list
print ("The sum of the list elements is : ",end="")
print (functools.reduce(lambda a,b : a+b,lis))
```

<p>For your example</p>

<pre class="lang-py prettyprint-override"><code>import functools
list   = [a,b,c,d,e,f,g,h]
def F(a,b):
  return a + b #or whatever

result = functools.reduce(F, list)

print(result)
</code>```

Title: How do I perform an operation iteratively on a python list/array whithout a for loop?

Body:
There is a reduce function to do this: https://www.geeksforgeeks.org/reduce-in-python/

# importing functools for reduce()
import functools

# initializing list
lis = [ 1 , 3, 5, 6, 2, ]

# using reduce to compute sum of list
print ("The sum of the list elements is : ",end="")
print (functools.reduce(lambda a,b : a+b,lis))

For your example

import functools
list   = [a,b,c,d,e,f,g,h]
def F(a,b):
  return a + b #or whatever

result = functools.reduce(F, list)

print(result)


问:
Gitlab-ci - Pipeline status is 'succeeded' in overview
My .gitlab-ci.yml file is as follows:

always_on:
    before_script:
        - echo 'before_script'
    script: echo 'script done'

always_fail:
    before_script:
        - echo 'before_script'
    script: fail_now

backend_only_mr:
    only:
        refs:
            - merge_requests
            - master
        changes:
            - scripts/**/*
    before_script:
        - echo 'before_script'
    script: echo 'script done'
```

As you can see, there is always_fail job which always fails. If I have no changes in scripts directory, this works fine and Merge-request overview shows the pipeline is failed:

When I have made a change in the scripts directory, the job fails, as expected, but the overview shows that the job has succeeded because backend_only_mr is succeeded:

The jobs are as follows:

backend_only_mr is flagged as detached, if it helps.

答:
That is expected behavior currently, as the two pipelines run for the commit and merge request separately.  Then the merge request pipeline passes "after" the commit one fails, and GitLab sees it as passed.

There are a couple of options to deal with this:

Specify only: merge_requests on every job you want to count against "can we merge this"?

The new global workflow setting lets you say "I want all of my jobs to run on a merge request pipeline".

There are a number of issues around how consolidated pipelines should work going foward.  Would love your feedback in thos.

You also can read more about how we're solving for this with rules: vs. only/except: here: https://docs.gitlab.com/ee/ci/yaml/#key-details-when-using-rules.

Body:
My .gitlab-ci.yml file is as follows:

always_on:
    before_script:
        - echo 'before_script'
    script: echo 'script done'

always_fail:
    before_script:
        - echo 'before_script'
    script: fail_now

backend_only_mr:
    only:
        refs:
            - merge_requests
            - master
        changes:
            - scripts/**/*
    before_script:
        - echo 'before_script'
    script: echo 'script done'

As you can see, there is always_fail job which always fails. If I have no changes in scripts directory, this works fine and Merge-request overview shows the pipeline is failed:

When I have made a change in the scripts directory, the job fails, as expected, but the overview shows that the job has succeeded because backend_only_mr is succeeded:

The jobs are as follows:

backend_only_mr is flagged as detached, if it helps.


问:
Unity3d with Firebase: Can't Start Coroutine
Greeting,

I'm currently facing a problem that my coroutine can't start. This is the first time I facing this issues and I can't find a proper solution online. Much appreciated if anyone can point me to the right direction to solve this issue.

Here are the code.

```<code>path_reference.GetDownloadUrlAsync().ContinueWith((Task<Uri> task) => {

if (!task.IsFaulted && !task.IsCanceled)
            {
                Debug.Log("Download URL: " + task.Result);

                StartCoroutine(DownloadStuff(task.Result));
            }
            else
            {
                Debug.Log(task.Exception.ToString());
            }
        });
    }
</code>```

```<code>IEnumerator DownloadStuff(Uri uri)
{
    Debug.Log("Start Download");

    using (var www = UnityWebRequestTexture.GetTexture(uri))
    {
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            var texture = DownloadHandlerTexture.GetContent(www);

            //Texture2D texture = new Texture2D(1, 1);

            //if you need sprite for SpriteRenderer or Image
            Sprite sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width,
                    texture.height), new Vector2(0.5f, 0.5f), 100.0f);
            Debug.Log("Finished downloading!");
        }

        Debug.Log(www.downloadProgress);
    }
}'
</code>```

答:
The task returned by Firebase probably finishes execution on a thread other than the main thread, and Unity coroutines can only run on the main thread.

Unity's support of multithreading and async is pretty spotty, including "eating" some errors if the continuations of those errors would execute on another thread other than the main thread.

To fix this, you need to change the function that starts your coroutine:

try {
    // Important: ConfigureAwait(true) ensures the code after this will run in the
    // same thread as the code before (which is the main thread!)
    var url = await path_reference.GetDownloadUrlAsync().ConfigureAwait(true);
    StartCoroutine(DownloadStuff(url));
} catch (Exception ex) {
    // Tip: when logging errors, use LogException and pass the whole exception,
    // that way you will get pretty links to the error line in the whole stack trace.
    Debug.LogException(ex);
}
```

<hr>

<p>As an aside, I usually have a few extension methods on all my projects to deal with that while staying in async-world instead of coroutine-world (because at least with async I can catch errors and not just "halt and catch fire" like Unity's coroutines)</p>

<p>The main ones are:</p>

<pre class="lang-cs prettyprint-override"><code>public static Task ToTask(this YieldInstruction self, MonoBehaviour owner) {
    var source = new TaskCompletionSource<object>();

    IEnumerable Routine() {
        yield return self;
        source.SetResult(null);
    }

    return source.Task;
}

private static Task SendAsync(this UnityWebRequest self, MonoBehaviour owner) {
    var source = new TaskCompletionSource<object>();

    await self.SendWebRequest().ToTask(owner);

    if (
        self.isHttpError
        || self.isNetworkError
    ) {
        source.SetException(new Exception(request.error));
        yield break;
    }

    source.SetResult(null);
}
</code>```

Which you can use like this, inside a MonoBehaviour:

await new WaitForSeconds(0.2f).ToTask(this);

UnityWebRequest request = /* etc */;
await request.SendAsync(this);
var texture = DownloadHandlerTexture.GetContent(request);
```

Note that these methods do not require ConfigureAwait, since their SetResult/SetException invocations are ran from Unity-provided coroutine continuations.

Body:
Greeting,

I'm currently facing a problem that my coroutine can't start. This is the first time I facing this issues and I can't find a proper solution online. Much appreciated if anyone can point me to the right direction to solve this issue.

Here are the code.

path_reference.GetDownloadUrlAsync().ContinueWith((Task<Uri> task) => {

if (!task.IsFaulted && !task.IsCanceled)
            {
                Debug.Log("Download URL: " + task.Result);

                StartCoroutine(DownloadStuff(task.Result));
            }
            else
            {
                Debug.Log(task.Exception.ToString());
            }
        });
    }

IEnumerator DownloadStuff(Uri uri)
{
    Debug.Log("Start Download");

    using (var www = UnityWebRequestTexture.GetTexture(uri))
    {
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            var texture = DownloadHandlerTexture.GetContent(www);

            //Texture2D texture = new Texture2D(1, 1);

            //if you need sprite for SpriteRenderer or Image
            Sprite sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width,
                    texture.height), new Vector2(0.5f, 0.5f), 100.0f);
            Debug.Log("Finished downloading!");
        }

        Debug.Log(www.downloadProgress);
    }
}'

Body:
The task returned by Firebase probably finishes execution on a thread other than the main thread, and Unity coroutines can only run on the main thread.

Unity's support of multithreading and async is pretty spotty, including "eating" some errors if the continuations of those errors would execute on another thread other than the main thread.

To fix this, you need to change the function that starts your coroutine:

try {
    // Important: ConfigureAwait(true) ensures the code after this will run in the
    // same thread as the code before (which is the main thread!)
    var url = await path_reference.GetDownloadUrlAsync().ConfigureAwait(true);
    StartCoroutine(DownloadStuff(url));
} catch (Exception ex) {
    // Tip: when logging errors, use LogException and pass the whole exception,
    // that way you will get pretty links to the error line in the whole stack trace.
    Debug.LogException(ex);
}

As an aside, I usually have a few extension methods on all my projects to deal with that while staying in async-world instead of coroutine-world (because at least with async I can catch errors and not just "halt and catch fire" like Unity's coroutines)

The main ones are:

public static Task ToTask(this YieldInstruction self, MonoBehaviour owner) {
    var source = new TaskCompletionSource<object>();

    IEnumerable Routine() {
        yield return self;
        source.SetResult(null);
    }

    return source.Task;
}

private static Task SendAsync(this UnityWebRequest self, MonoBehaviour owner) {
    var source = new TaskCompletionSource<object>();

    await self.SendWebRequest().ToTask(owner);

    if (
        self.isHttpError
        || self.isNetworkError
    ) {
        source.SetException(new Exception(request.error));
        yield break;
    }

    source.SetResult(null);
}

Which you can use like this, inside a MonoBehaviour:

await new WaitForSeconds(0.2f).ToTask(this);

UnityWebRequest request = /* etc */;
await request.SendAsync(this);
var texture = DownloadHandlerTexture.GetContent(request);

Note that these methods do not require ConfigureAwait, since their SetResult/SetException invocations are ran from Unity-provided coroutine continuations.


问:
PHP: Getting the include/require process right
I am looking for a better method for handling relative paths in PHP.  An issue I ran into was including a file from a sub-directory that was also including files.  Using this process resulted in relative paths breaking.  To alleviate this issue was by changing the variable (path) if the file didn't exist.  But, for some reason, it doesn't settle well with me as I think there has to be a better way to handle this.

Example:

ROOT/config/config.php

ROOT/includes/functions.php

ROOT/includes/header.php <-- includes functions.php and config.php

ROOT/index.php <-- includes header.php

ROOT/admin/index.php <--- also includes header.php (as ../includes/header.php) and has the code below to fix the broken links

Below is the code I used which did solve the problem but I am just verifying that this is okay or if there is a better method to handling relative file paths.

```<code>    define('PREV_DIR', '../');

    $config_file = './config/config.php';
    $functions_file = './includes/functions.php';

    if ( !file_exists($config_file)) {
        $config_file = PREV_DIR . './config/config.php';
    }

    if ( !file_exists($functions_file)) {
        $functions_file = PREV_DIR . './config/config.php';
    }

    include $config_file;
    include $functions_file;
</code>```

While I have achieved my goal, I just want to move forward with best practices and minimize a sloppy approach.

答:
While your project is simple enough (from what I can see in your post), you could define path constants in your configuration file, thus making it simpler to rename / replace them just by changing the directory name and the value of the constant.

For example:

```<code><?php #index.php

define('ROOT', __dir__);
define('CONFIG_DIR', ROOT . DIRECTORY_SEPARATOR . 'config');
define('INCLUDES_DIR', ROOT . DIRECTORY_SEPARATOR . 'includes');
</code>```

For classes, there is a standard that most use and that is highly recommended, and that is the PSR-4 Autoload standard, where you have Namespace/SubNamespaces/ClassName.

Body:
I am looking for a better method for handling relative paths in PHP.  An issue I ran into was including a file from a sub-directory that was also including files.  Using this process resulted in relative paths breaking.  To alleviate this issue was by changing the variable (path) if the file didn't exist.  But, for some reason, it doesn't settle well with me as I think there has to be a better way to handle this.

Example:

ROOT/config/config.php

ROOT/includes/functions.php

ROOT/includes/header.php <-- includes functions.php and config.php

ROOT/index.php <-- includes header.php

ROOT/admin/index.php <--- also includes header.php (as ../includes/header.php) and has the code below to fix the broken links

Below is the code I used which did solve the problem but I am just verifying that this is okay or if there is a better method to handling relative file paths.

    define('PREV_DIR', '../');

    $config_file = './config/config.php';
    $functions_file = './includes/functions.php';

    if ( !file_exists($config_file)) {
        $config_file = PREV_DIR . './config/config.php';
    }

    if ( !file_exists($functions_file)) {
        $functions_file = PREV_DIR . './config/config.php';
    }

    include $config_file;
    include $functions_file;

While I have achieved my goal, I just want to move forward with best practices and minimize a sloppy approach.

Body:
While your project is simple enough (from what I can see in your post), you could define path constants in your configuration file, thus making it simpler to rename / replace them just by changing the directory name and the value of the constant.

For example:

<?php #index.php

define('ROOT', __dir__);
define('CONFIG_DIR', ROOT . DIRECTORY_SEPARATOR . 'config');
define('INCLUDES_DIR', ROOT . DIRECTORY_SEPARATOR . 'includes');

For classes, there is a standard that most use and that is highly recommended, and that is the PSR-4 Autoload standard, where you have Namespace/SubNamespaces/ClassName.


问:
Add items to a collection if the collection does NOT already contain it by comparing a property of the items?
Basically, how do I make it so I can do something similar to: CurrentCollection.Contains(...), except by comparing if the item's property is already in the collection?

```<code>public class Foo
{
    public Int32 bar;
}

ICollection<Foo> CurrentCollection;
ICollection<Foo> DownloadedItems;

//LINQ: Add any downloaded items where the bar Foo.bar is not already in the collection?
</code>```

答:
```<code>    List<int> current = new List<int> { 1, 2 };
    List<int> add = new List<int> { 2, 3 };
    current.AddRange(add.Except(current));
</code>```

This will result in 1,2,3, using the default comparing.

This will also work for Foo if you change the compare behaviour:

```<code>    public class Foo : IEquatable<Foo>
    {
        public Int32 bar;
        public bool Equals(Foo other)
        {
            return bar == other.bar;
        }
        public override bool Equals(object obj) => Equals(obj as Foo);
        public override int GetHashCode() => (bar).GetHashCode(); // (prop1,prop2,prop3).GetHashCode()
    }
</code>```

You could also implement an IEqualityComparer<Foo>, and pass it as second parameter to except

```<code>    current.AddRange(add.Except(current, new FooComparer()));

    public class FooComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo x, Foo y)
        {
            return x.bar.Equals(y.bar);
        }
        public int GetHashCode(Foo obj)
        {
            return obj.bar.GetHashCode();
        }
    }
</code>```

Body:
Basically, how do I make it so I can do something similar to: CurrentCollection.Contains(...), except by comparing if the item's property is already in the collection?

public class Foo
{
    public Int32 bar;
}

ICollection<Foo> CurrentCollection;
ICollection<Foo> DownloadedItems;

//LINQ: Add any downloaded items where the bar Foo.bar is not already in the collection?

Body:
    List<int> current = new List<int> { 1, 2 };
    List<int> add = new List<int> { 2, 3 };
    current.AddRange(add.Except(current));

This will result in 1,2,3, using the default comparing.

This will also work for Foo if you change the compare behaviour:

    public class Foo : IEquatable<Foo>
    {
        public Int32 bar;
        public bool Equals(Foo other)
        {
            return bar == other.bar;
        }
        public override bool Equals(object obj) => Equals(obj as Foo);
        public override int GetHashCode() => (bar).GetHashCode(); // (prop1,prop2,prop3).GetHashCode()
    }

You could also implement an IEqualityComparer<Foo>, and pass it as second parameter to except

    current.AddRange(add.Except(current, new FooComparer()));

    public class FooComparer : IEqualityComparer<Foo>
    {
        public bool Equals(Foo x, Foo y)
        {
            return x.bar.Equals(y.bar);
        }
        public int GetHashCode(Foo obj)
        {
            return obj.bar.GetHashCode();
        }
    }


问:
STL + typedefs vs. OOP, best practices?
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like: </p>

```<code>typedef std::map<std::string, std::map<std::string, int> > CSVData;
</code>```

<p>Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this? </p>

答:
If this is for some one-off code: sure, use typedefs, why not?

But code rarely is. And the problem with reusable code (or code that will, potentially, at some future point be reused) is: there are 1000 different ways of using it wrongly. Don’t artificially add reasons 1001–1255.

Code should be easy to use, and hard to misuse. Among other things this means: have one obvious interface and forbid all operations that aren’t supported, meaningful, or that are somehow unnecessary. Providing a typedef fails in this regard: your CSV data type supports all kinds of irrelevant operations.

There are multiple other reasons against typedefs: for instance, this makes the interface easy to break when you need to change the underlying implementation of your data structure (change of requirements, performance issues …). Essentially, you cannot do that without breaking all uses of your typedef’d data structure.

But a properly designed, well encapsulated data structure can easily change its internal implementation without breaking consumer code, as long as the interface remains identical.

This is one of the most important concepts of large architectures: information hiding.

Furthermore, it is a logical error (albeit a small one): your typedef models a logical is-a relation. But this isn’t true: CSV data isn’t a map of maps. Rather, it can be implemented in terms of a map of maps. This is a fundamental difference.

That said, C++ does teach that object orientation isn’t needed for large object hierarchies: essentially the whole standard library (except for the IO stream library) isn’t object oriented: it’s algorithm oriented instead. But that doesn’t mean that you don’t have to write your own classes.

Title: STL + typedefs vs. OOP, best practices?

Body:
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like:

typedef std::map<std::string, std::map<std::string, int> > CSVData;

Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this?