问:
How to change background color of Bootstrap Navbar Toggler Icon when it's active when using other frameworks like Materialize?
I am working on a project which requires both Bootstrap & Materialize frameworks.
I have this navbar toggle which is normal when not in active state.

But when it goes into active state and has a background fill with the default colors of Materialize CSS.

I am trying to set the background color to transparent but it doesn't. This is the CSS which I tried.

```<code>.navbar-toggler-icon{
  background-color: transparent !important;
}
.navbar-toggler-icon :active{
  background-color: transparent !important;
}
</code>```

This is the codepen link.

答:
I've added an idin the div that has all the content of thenavbar.

                ReEvent
                <button  class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

```

<p>When I change the color in an <code>id</code> if the <code>id</code> is on the <code>div</code> everything that is inside the <code>div</code> will be change together. So I put it just for the <code>button</code> receive the changes.</p>

<p>But, I don't know why, the button keeps with the "bug" if you put the <code>:focus</code> just on it, so i've put the <code>:focus</code> on everything and after this I've removed the <code>:focus</code> of the <code>a</code> using one specific bg for him.</p>

<pre class="lang-css prettyprint-override"><code>body{
  background-color: #222;
}
.navbar-toggler-icon{
  background-color: transparent !important;
}
#color button :hover, #color :focus, #color button :active{
  background-color: transparent !important;
}

#color a :focus {
  background-color: white !important;
}
</code>```

Body:
I am working on a project which requires both Bootstrap & Materialize frameworks.
I have this navbar toggle which is normal when not in active state.

But when it goes into active state and has a background fill with the default colors of Materialize CSS.

I am trying to set the background color to transparent but it doesn't. This is the CSS which I tried.

.navbar-toggler-icon{
  background-color: transparent !important;
}
.navbar-toggler-icon :active{
  background-color: transparent !important;
}

This is the codepen link.

Body:
I've added an idin the div that has all the content of thenavbar.

<body>
  <div class="navbar navbar-dark navbar-expand-lg sticky-top w-100" >
            <div id="color" class="container p-2">
                <a class="navbar-brand font-weight-bold text-white mx-5 d-none d-sm-block" href="#">ReEvent</a>
                <button  class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                <span  class="navbar-toggler-icon"></span>
                  </div>
  </div>
    </body>

When I change the color in an id if the id is on the div everything that is inside the div will be change together. So I put it just for the button receive the changes.

But, I don't know why, the button keeps with the "bug" if you put the :focus just on it, so i've put the :focus on everything and after this I've removed the :focus of the a using one specific bg for him.

body{
  background-color: #222;
}
.navbar-toggler-icon{
  background-color: transparent !important;
}
#color button :hover, #color :focus, #color button :active{
  background-color: transparent !important;
}

#color a :focus {
  background-color: white !important;
}


来源: stackexchange

答:
Here's my attempt at this. Ideally I wanted to modify x.orig after every iteration but couldn't get that to work so made another variable called latest. I doubt this is the best way to do it though:

```<code>library(zoo)

latest <- x.orig
rollapplyr(x.orig, width = seq_along(x.orig), function(x) {
   #browser()
   x <- latest[index(x)]
   v <- sum(x)
   if (!is.na(v))
     latest[last(index(x))] <<- v
   latest[last(index(x))]
})

2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 2020-01-06 2020-01-07 2020-01-08 2020-01-09 2020-01-10
         1          3          7        111        126        253       1501       2010       4020       8042
</code>```

ContentLicense: CC BY-SA 4.0

Title: Result-feeding rolling window or rollapply with cumsum

Body:
Suppose I have the following zoo object:

x.orig <- read.zoo(data.frame(date=seq(as.Date('2020-01-01'), as.Date('2020-01-10'), 1), v=c(1,2,3,100,4,5,1000,8,8,10)))
2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 2020-01-06 2020-01-07 2020-01-08 2020-01-09 2020-01-10
         1          2          3        100          4          5       1000          8          8         10

I would like to compute a rolling sum of width=seq_along(x.orig) as follows:

2020-01-01 1
2020-01-02 1 + 2                                   #2020-01-01 + 2020-01-02
2020-01-03 1 + (1 + 2) + 3                         #2020-01-01 + 2020-01-02 + 2020-01-03
2010-01-04 1 + (1 + 2) + (1 + (1 + 2) + 3) + 100   #2020-01-01 + 2020-01-02 + 2020-01-03 + 2020-01-04
...

I would imagine the way to do this would be to result-feed x in some way so that x is updated after each rollapply loop so that the next rollapply iteration picks up the modified value in its window but am just not sure how to write it...

Body:
Here's my attempt at this. Ideally I wanted to modify x.orig after every iteration but couldn't get that to work so made another variable called latest. I doubt this is the best way to do it though:

library(zoo)

latest <- x.orig
rollapplyr(x.orig, width = seq_along(x.orig), function(x) {
   #browser()
   x <- latest[index(x)]
   v <- sum(x)
   if (!is.na(v))
     latest[last(index(x))] <<- v
   latest[last(index(x))]
})

2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 2020-01-06 2020-01-07 2020-01-08 2020-01-09 2020-01-10
         1          3          7        111        126        253       1501       2010       4020       8042


问:
How do I get around initializing variables inside init() if they are initialized by loading .json data?
I have a struct PrimaryUser() whose variables get loaded in through a .json file parser. One of those variables are a date string in the ISO8601 format. I want to have that value automatically converted to a Date type variable.

The problem I'm facing is that I don't know how to make this code run automatically upon creation of PrimaryUser():

```<code>        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
        self.dateOfBirth = dateFormatter.date(from: dateOfBirthISO8601)!
</code>```

If I put this code inside init(), I get the error:

```<code>'self' used before all stored properties are initialized
</code>```

If I try making dateOfBirth a lazy variable, I run into this error:

```<code>Lazy properties must have an initializer
</code>```

Again to reiterate, all the PrimaryUser() variables will be initialized with data from a .json file through a parser that's totally separate from PrimaryUser(). So it doesn't make sense to initialize the variables inside PrimaryUser().

Here's what PrimaryUser() looks like:

```<code>import Foundation
import SwiftUI

struct PrimaryUser: User, Hashable, Codable, Identifiable {
    var id: Int
    var firstName: String
    var lastName: String
    var dateOfBirthISO8601: String
    lazy var dateOfBirth: Date
    init() {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
        self.dateOfBirth = dateFormatter.date(from: dateOfBirthISO8601)!
    }
}
</code>```

答:
You can use a custom date decoding strategy when using JSONDecoder to turn your string into a Date.

Just pass your DateFormatter into the JSONDecoder with:

decoder.dateDecodingStrategy = .formatted(dateFormatter)

That way you can get rid of the lazy variable or a custom initialiser.

Body:
I have a struct PrimaryUser() whose variables get loaded in through a .json file parser. One of those variables are a date string in the ISO8601 format. I want to have that value automatically converted to a Date type variable.

The problem I'm facing is that I don't know how to make this code run automatically upon creation of PrimaryUser():

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
        self.dateOfBirth = dateFormatter.date(from: dateOfBirthISO8601)!

If I put this code inside init(), I get the error:

'self' used before all stored properties are initialized

If I try making dateOfBirth a lazy variable, I run into this error:

Lazy properties must have an initializer

Again to reiterate, all the PrimaryUser() variables will be initialized with data from a .json file through a parser that's totally separate from PrimaryUser(). So it doesn't make sense to initialize the variables inside PrimaryUser().

Here's what PrimaryUser() looks like:

import Foundation
import SwiftUI

struct PrimaryUser: User, Hashable, Codable, Identifiable {
    var id: Int
    var firstName: String
    var lastName: String
    var dateOfBirthISO8601: String
    lazy var dateOfBirth: Date
    init() {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
        self.dateOfBirth = dateFormatter.date(from: dateOfBirthISO8601)!
    }
}


问:
Reorder numeric values contained in keys and assigned as strings without losing the key assignment?
Apologies for the title, this is certainly a bit of a pretentious issue. I've got a range of numbers distributed across two arrays. These arrays hold the same dateset, however one has been converted to strings so that a reference key/tag can be assigned to each value indicating a category index.

```<code>const array1 = ["0:0", "0:5.476", "0:11.251", "0:31.916", "0:44.007", "0:53.911", "0:58.628", "0:65.729", "0:75.222", "0:88.849", "0:100", "1:0", "1:44.839", "1:60.303", "1:69.072", "1:73.150", "1:85.800", "1:100", "2:0", "2:11.796", "2:26.525", "2:81.782", "2:88.367", "2:100"]
</code>```

0: 1: 2: represent the category index.

The second representation of the dateset is numeric and assigned to a separate array in ascending order.

```<code>const array2 = [0, 0, 0, 5.476, 11.251, 11.796, 26.525, 31.916, 44.007, 44.839, 53.911, 58.628, 60.303, 65.729, 69.072, 73.150, 75.222, 81.782, 85.800, 88.367, 88.849, 100, 100, 100]
</code>```

The goal is to replicate the order of array2 in array1 whilst keeping the category index keys intact. As can be seen in the example below.

```<code>> console.log(array1);
["0:0", "1:0", "2:0", "0:5.476", "0:11.251", "2:11.796", "2:26.525", "0:31.916", "0:44.007", "1:44.839", "0:53.911", "0:58.628", "1:60.303", "0:65.729", "1:69.072", "1:73.150", "0:75.222", "2:81.782", "1:85.800", "2:88.367", "0:88.849", "0:100", "1:100", "2:100"]
</code>```

Of course if I just wanted to match the order I could just un-string array1 and run it in ascending order. This example below un-strings all the 0: values.

```<code>let array1Ascend = [];
for(i=0;i<array1.length;i++){
    array1Ascent.push(Number(array1[i].match(/(?!0*:).*/)))
}
array1Ascent.sort(function(a, b) {
                return a - b;
            });
</code>```

But the issue is that i'd of course lose the category index assignment of each value in doing that, which defeats the purpose. I'd say i'm more stuck on understanding the logic of this issue if anything. Any help would be appreciated, thank you.

答:
Here's what I would do. Probably more complicated than necessary, but it's just how my brain works. I use a few techniques that have been added to JavaScript in recent years, so feel free to ask about anything you don't understand.

const array1 = ["0:0", "0:5.476", "0:11.251", "0:31.916", "0:44.007", "0:53.911", "0:58.628", "0:65.729", "0:75.222", "0:88.849", "0:100", "1:0", "1:44.839", "1:60.303", "1:69.072", "1:73.150", "1:85.800", "1:100", "2:0", "2:11.796", "2:26.525", "2:81.782", "2:88.367", "2:100"];
const array2 = [0, 0, 0, 5.476, 11.251, 11.796, 26.525, 31.916, 44.007, 44.839, 53.911, 58.628, 60.303, 65.729, 69.072, 73.150, 75.222, 81.782, 85.800, 88.367, 88.849, 100, 100, 100];

const array3 = array1
  .map(val => {
    // get the category index and value as numbers and properties of an object
    const [ cat, value ] = val.split(':').map(v => parseFloat(v));
    return { cat, value };
  })
  .sort((a,b) =>
    // sort by the index of the value in the second array
    array2.indexOf(a.value) - array2.indexOf(b.value)
  )
  // "restringify" the category index and value to a string
  .map(({cat, value}) => `${cat}:${value}`);

console.log(array3);```

Body:
Apologies for the title, this is certainly a bit of a pretentious issue. I've got a range of numbers distributed across two arrays. These arrays hold the same dateset, however one has been converted to strings so that a reference key/tag can be assigned to each value indicating a category index.

const array1 = ["0:0", "0:5.476", "0:11.251", "0:31.916", "0:44.007", "0:53.911", "0:58.628", "0:65.729", "0:75.222", "0:88.849", "0:100", "1:0", "1:44.839", "1:60.303", "1:69.072", "1:73.150", "1:85.800", "1:100", "2:0", "2:11.796", "2:26.525", "2:81.782", "2:88.367", "2:100"]

0: 1: 2: represent the category index.

The second representation of the dateset is numeric and assigned to a separate array in ascending order.

const array2 = [0, 0, 0, 5.476, 11.251, 11.796, 26.525, 31.916, 44.007, 44.839, 53.911, 58.628, 60.303, 65.729, 69.072, 73.150, 75.222, 81.782, 85.800, 88.367, 88.849, 100, 100, 100]

The goal is to replicate the order of array2 in array1 whilst keeping the category index keys intact. As can be seen in the example below.

> console.log(array1);
["0:0", "1:0", "2:0", "0:5.476", "0:11.251", "2:11.796", "2:26.525", "0:31.916", "0:44.007", "1:44.839", "0:53.911", "0:58.628", "1:60.303", "0:65.729", "1:69.072", "1:73.150", "0:75.222", "2:81.782", "1:85.800", "2:88.367", "0:88.849", "0:100", "1:100", "2:100"]

Of course if I just wanted to match the order I could just un-string array1 and run it in ascending order. This example below un-strings all the 0: values.

let array1Ascend = [];
for(i=0;i<array1.length;i++){
    array1Ascent.push(Number(array1[i].match(/(?!0*:).*/)))
}
array1Ascent.sort(function(a, b) {
                return a - b;
            });

But the issue is that i'd of course lose the category index assignment of each value in doing that, which defeats the purpose. I'd say i'm more stuck on understanding the logic of this issue if anything. Any help would be appreciated, thank you.


问:
Extract Numeric and Special Characters Separately
I have column in a table with values stored as

```<code>Cost

499.00
£ 7.75
£ 7.75
250.00
£ 5.99
$ 6.05
</code>```

Now, I need to store these values to another table like

```<code>Currency     Cost
RS           499.00
£            7.75
£            7.75
RS           250.00
£            5.99
$            6.05
</code>```

Plz let me the Query how to do this....

答:
You can use SQL-Server string functions:</p>

```<code># Currency
SELECT SUBSTRING(<value>, 1, CHARINDEX(' ', <value>))

# Amount
SELECT SUBSTRING(<value>, CHARINDEX(' ', <value>), LEN(<value>))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have column in a table with values stored as

Cost

499.00
£ 7.75
£ 7.75
250.00
£ 5.99
$ 6.05

Now, I need to store these values to another table like

Currency     Cost
RS           499.00
£            7.75
£            7.75
RS           250.00
£            5.99
$            6.05

Plz let me the Query how to do this....

Body:
You can use SQL-Server string functions:

# Currency
SELECT SUBSTRING(<value>, 1, CHARINDEX(' ', <value>))

# Amount
SELECT SUBSTRING(<value>, CHARINDEX(' ', <value>), LEN(<value>))


问:
mysqldump Error 1045 Access denied despite correct passwords etc
This is a tricky one, I have the following output:

mysqldump: Got error: 1045: Access denied for user 'root'@'localhost' (using password: YES) when trying to connect

When attempting to export my database with mysqldump on Windows XP. The username is root, the password is correct and contains only alphanumeric characters. I have tried different cases, with/without quotes, specifying using -u and -p, specifying using --user= and --password= and other methods of specifying user/passwords etc, specifying the host (it's all local) and even specifying the database using --databases instead of just blank.  The error is always the same when using a password and always the same except the "NO" message when without.  I have tried many fixes found through searches with no success.  One fix suggested inspecting mysql.conf, but the Windows build doesn't seem to have one.  The credentials (and indeed commandline parameters) work perfectly with mysql.exe - this problem only seems to be affecting mysqldump.exe.

答:
This solution might be one of the last to try/least likely to be the culprit, but this was my problem...

My problem was that the directory I was trying to dump to needed admin privileges to write to and that's what was causing the mysqldump command to return "Access Denied".

I set the dump file path to my desktop dir and then it worked.

This was on Windows.


问:
SQL multiple query using with - in Bigquery
I'm trying to figure out how to make a single request including several queries in order to generate one view including all my queries results.

Here the example :

```<code>
WITH Query_1 AS
(
SELECT
dimension1,
dimension2,
dimension3,
dimension4,
dimension5,

CASE WHEN STARTS_WITH (dimension1, "N_") THEN '1' ELSE '0' END AS qadimension1,
CASE WHEN dimension2 IS NOT NULL THEN dimension2 ELSE '0' END AS qadimension2,
CASE WHEN dimension3 IS NOT NULL THEN dimension3 ELSE '0' END AS qadimension3,
CASE WHEN dimension4 IS NOT NULL THEN dimension4 ELSE '0' END AS qadimension4,
FROM `XXXXX.XXXXX.first_view`
WHERE dimension5='2021' AND dimension1 IS NOT NULL),

Query_2 AS (
SELECT
dimension1,
qadimension1,
dimension6,

CASE WHEN qadimension1 = dimension6 THEN '1' ELSE '0' END AS QA_check1,
FROM `XXXXX.XXXXX.first_view` , `XXXXX.XXXXX.second_view`
WHERE qadimension1 != '0'),

Query_3 AS (
SELECT
dimension1,
qadimension2,
dimension7,

CASE WHEN qadimension2 = dimension7 THEN '1' ELSE '0' END AS QA_check2,
FROM `XXXXX.XXXXX.first_view` , `XXXXX.XXXXX.third_view`
WHERE qadimension2 != '0')

SELECT
dimension1,
dimension2,
dimension3,
dimension4,
dimension5,
dimension6,
dimension7,

qadimension1,
qadimension2,
qadimension3,
qadimension4,

QA_check1,
QA_check2,

FROM
Query_1,
Query_2,
Query_3

WHERE FULL JOIN dimension1;

</code>```

still have an error : Syntax error: Unexpected keyword FULL at [242:7]

Many thanks for your help

答:
Below is for BigQuery Standard SQL

Try below - note no changes for all CTEs, so below just final select statement

```<code>SELECT
  dimension1,
  dimension2,
  dimension3,
  dimension4,
  dimension5,
  dimension6,
  dimension7,

  q2.qadimension1,
  q3.qadimension2,
  qadimension3,
  qadimension4,

  QA_check1,
  QA_check2

FROM Query_1
LEFT JOIN Query_2 q2 USING(dimension1)
LEFT JOIN Query_3 q3 USING(dimension1)
</code>```

Body:
I'm trying to figure out how to make a single request including several queries in order to generate one view including all my queries results.

Here the example :

WITH Query_1 AS
(
SELECT
dimension1,
dimension2,
dimension3,
dimension4,
dimension5,

CASE WHEN STARTS_WITH (dimension1, "N_") THEN '1' ELSE '0' END AS qadimension1,
CASE WHEN dimension2 IS NOT NULL THEN dimension2 ELSE '0' END AS qadimension2,
CASE WHEN dimension3 IS NOT NULL THEN dimension3 ELSE '0' END AS qadimension3,
CASE WHEN dimension4 IS NOT NULL THEN dimension4 ELSE '0' END AS qadimension4,
FROM `XXXXX.XXXXX.first_view`
WHERE dimension5='2021' AND dimension1 IS NOT NULL),

Query_2 AS (
SELECT
dimension1,
qadimension1,
dimension6,

CASE WHEN qadimension1 = dimension6 THEN '1' ELSE '0' END AS QA_check1,
FROM `XXXXX.XXXXX.first_view` , `XXXXX.XXXXX.second_view`
WHERE qadimension1 != '0'),

Query_3 AS (
SELECT
dimension1,
qadimension2,
dimension7,

CASE WHEN qadimension2 = dimension7 THEN '1' ELSE '0' END AS QA_check2,
FROM `XXXXX.XXXXX.first_view` , `XXXXX.XXXXX.third_view`
WHERE qadimension2 != '0')

SELECT
dimension1,
dimension2,
dimension3,
dimension4,
dimension5,
dimension6,
dimension7,

qadimension1,
qadimension2,
qadimension3,
qadimension4,

QA_check1,
QA_check2,

FROM
Query_1,
Query_2,
Query_3

WHERE FULL JOIN dimension1;

still have an error : Syntax error: Unexpected keyword FULL at [242:7]

Many thanks for your help

Body:
Below is for BigQuery Standard SQL

Try below - note no changes for all CTEs, so below just final select statement

SELECT
  dimension1,
  dimension2,
  dimension3,
  dimension4,
  dimension5,
  dimension6,
  dimension7,

  q2.qadimension1,
  q3.qadimension2,
  qadimension3,
  qadimension4,

  QA_check1,
  QA_check2

FROM Query_1
LEFT JOIN Query_2 q2 USING(dimension1)
LEFT JOIN Query_3 q3 USING(dimension1)


问:
Where can I put paginate()?
I am trying put paginate(10) to add a pagination later, but when I added it it gives me this error:

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$product

Here is my controller where I want add the pagination(10):

```<code> public function index()
    {
        $user_id = auth()->user()->id;
        $user = User::find($user_id);

        return view('your')->with('product', $user->product);
    }
</code>```

I did try this:

```<code> public function index()
    {
        $user_id = auth()->user()->id;
        $user = User::find($user_id)->paginate(10);

        return view('your')->with('product', $user->product);
    }
</code>```

How can I avoid the undefined property error?

答:
Actually find function is used for getting only 1 result and you are applying pagination on that which is resulting into an error.

You might be wanting the products data to be paginated, For that do like this

```<code>public function index()
{
    $user_id = auth()->user()->id;
    $user = User::find($user_id)->product()->paginate(10);

    return view('your')->with('product', $user);
 }
</code>```

Title: Where can I put paginate()?

Body:
I am trying put paginate(10) to add a pagination later, but when I added it it gives me this error:

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$product

Here is my controller where I want add the pagination(10):

 public function index()
    {
        $user_id = auth()->user()->id;
        $user = User::find($user_id);

        return view('your')->with('product', $user->product);
    }

I did try this:

 public function index()
    {
        $user_id = auth()->user()->id;
        $user = User::find($user_id)->paginate(10);

        return view('your')->with('product', $user->product);
    }

How can I avoid the undefined property error?

Body:
Actually find function is used for getting only 1 result and you are applying pagination on that which is resulting into an error.

You might be wanting the products data to be paginated, For that do like this

public function index()
{
    $user_id = auth()->user()->id;
    $user = User::find($user_id)->product()->paginate(10);

    return view('your')->with('product', $user);
 }


问:
How to set PT_DENY_ATTACH in Xamarin.iOS?
We recently had a pen tester audit our app and one of the findings was that a person with a jailbroken device can attach a local debugger.

The solution they suggested was to enable PT_DENY_ATTACH when starting up the app. This is fairly easy to do in a native app but I haven't been able to figure it out with our Xamarin app (not forms).

I've tried creating an objc framework in Xcode, binding that and pulling it in. I've also tried to create a shared c++ library but that isn't possible in VS Mac.

I know that PT_DENY_ATTACH has been circumvented but I'd still like to know how to implement it.

Thanks!

答:
It turns out that my objc framework was behaving properly just not in the way I expected. For some reason I was still able to attach the Visual Studio debugger but when I move to Xcode and try to attach its debugger it fails when the framework is called.

To answer my question:

In Xcode I created a new static library with one class:

GDBManager.h

```<code>#import <Foundation/Foundation.h>

@interface GDBManager : NSObject
+(void)DisableGDB;
@end
</code>```

GDBManager.m

```<code>#import "GDBManager.h"
#import <dlfcn.h>
#import <sys/types.h>

@implementation GDBManager
typedef int (*ptrace_ptr_t)(int _request, pid_t _pid, caddr_t _addr, int _data);
#define PT_DENY_ATTACH 31

+(void)DisableGDB {
    void* handle = dlopen(0, RTLD_GLOBAL | RTLD_NOW);
    ptrace_ptr_t ptrace_ptr = dlsym(handle, "ptrace");
    ptrace_ptr(PT_DENY_ATTACH, 0, 0, 0);
    dlclose(handle);
}
@end
</code>```

I followed these instructions to create a fat file for my library and to use that in a binding project.

https://learn.microsoft.com/en-us/xamarin/ios/platform/binding-objective-c/walkthrough

I then add the generated dll to my Xamarin.iOS project and call it above UIApplication.Main(args, null, "AppDelegate"); in Main.cs

Body:
It turns out that my objc framework was behaving properly just not in the way I expected. For some reason I was still able to attach the Visual Studio debugger but when I move to Xcode and try to attach its debugger it fails when the framework is called.

To answer my question:

In Xcode I created a new static library with one class:

GDBManager.h

#import <Foundation/Foundation.h>

@interface GDBManager : NSObject
+(void)DisableGDB;
@end

GDBManager.m

#import "GDBManager.h"
#import <dlfcn.h>
#import <sys/types.h>

@implementation GDBManager
typedef int (*ptrace_ptr_t)(int _request, pid_t _pid, caddr_t _addr, int _data);
#define PT_DENY_ATTACH 31

+(void)DisableGDB {
    void* handle = dlopen(0, RTLD_GLOBAL | RTLD_NOW);
    ptrace_ptr_t ptrace_ptr = dlsym(handle, "ptrace");
    ptrace_ptr(PT_DENY_ATTACH, 0, 0, 0);
    dlclose(handle);
}
@end

I followed these instructions to create a fat file for my library and to use that in a binding project.

https://learn.microsoft.com/en-us/xamarin/ios/platform/binding-objective-c/walkthrough

I then add the generated dll to my Xamarin.iOS project and call it above UIApplication.Main(args, null, "AppDelegate"); in Main.cs


问:
Spring unauthorized request despite having .permitAll()
Here's the configuration class:

```<code>@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${allowed-origins}")
    String[] allowedOrigins;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable(); // To be able to see h2 console
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/api/transform-user").authenticated()
                .anyRequest().permitAll()
                .and()
                .cors()
                .and()
                .httpBasic().realmName("RDF-TRANSFORMER")
                .and()
                .csrf().disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Arrays.asList(allowedOrigins));
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setAllowedOrigins(Arrays.asList(("*")));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

    @Bean
    public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
        return new SecurityEvaluationContextExtension();
    }

}
</code>```

You can see I have all the requests except the transform-user call enabled to not authenticated users.

But when I call the endpoint /api/identity I get this response:

```<code>{"timestamp":"2020-05-29T10:35:47.058+0000","status":401,"error":"Unauthorized","message":"Unauthorized","path":"/api/identity"}
</code>```

Edit: I just saw I get this error when deploying the app:

```<code>  [2020.05.29 12:44:21] (Coverage): Error during class instrumentation: org.springframework.security.config.annotation.authentication.configurers.ldap.LdapAuthenticationProviderConfigurer: java.lang.RuntimeException: java.io.IOException: Class not found
</code>```

答:
The security configuration order is not correct. Try below one -  </p>

```<code> @Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers().frameOptions().disable(); // To be able to see h2 console
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/api/transform-user").permitAll()
            .anyRequest().authenticated()
            .and()
            .cors()
            .and()
            .httpBasic().realmName("RDF-TRANSFORMER")
            .and()
            .csrf().disable();
}
</code>```

Body:
Here's the configuration class:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${allowed-origins}")
    String[] allowedOrigins;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable(); // To be able to see h2 console
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/api/transform-user").authenticated()
                .anyRequest().permitAll()
                .and()
                .cors()
                .and()
                .httpBasic().realmName("RDF-TRANSFORMER")
                .and()
                .csrf().disable();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOrigins(Arrays.asList(allowedOrigins));
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setAllowedOrigins(Arrays.asList(("*")));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }

    @Bean
    public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
        return new SecurityEvaluationContextExtension();
    }

}

You can see I have all the requests except the transform-user call enabled to not authenticated users.

But when I call the endpoint /api/identity I get this response:

{"timestamp":"2020-05-29T10:35:47.058+0000","status":401,"error":"Unauthorized","message":"Unauthorized","path":"/api/identity"}

Edit: I just saw I get this error when deploying the app:

  [2020.05.29 12:44:21] (Coverage): Error during class instrumentation: org.springframework.security.config.annotation.authentication.configurers.ldap.LdapAuthenticationProviderConfigurer: java.lang.RuntimeException: java.io.IOException: Class not found

Body:
The security configuration order is not correct. Try below one -

 @Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers().frameOptions().disable(); // To be able to see h2 console
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.POST, "/api/transform-user").permitAll()
            .anyRequest().authenticated()
            .and()
            .cors()
            .and()
            .httpBasic().realmName("RDF-TRANSFORMER")
            .and()
            .csrf().disable();
}


问:
IIS 6.0 Application Pool crash
Have a lot of troubles on production server. Some routing cause crashing of Application Pool with event id 1011:

Event Type: Warning
  Event Source: W3SVC
  Event Category: None
  Event ID: 1011
  Date:  1/21/2009
  Time:  9:08:17 AM
  User:  N/A
  Computer: xxxxxxxxxxxxx
  Description:

A process serving application pool 'DefaultAppPool' suffered a fatal communication error with the World Wide Web Publishing Service. The process id was '3788'. The data field contains the error number.
  8007006d

I have a few very hard hours for me before I found a problem.
Thanks to Tess Ferrandez and her blog post I found it.

Always double check Your multithreaded code in asp.net application. When  Unhandled exceptions occurs application pool crashes and it's damn hard to find WHY.

答: Tess's blog was a little advanced for me.  I had to search around for quite a bit before I found the right articles that helped me debug my dump files.  This article will help others who want to debug their crashing asp.net application pools but don't know how to start.</p>

OwnerDisplayName: AlfeG

ContentLicense: CC BY-SA 2.5

Title: IIS 6.0 Application Pool crash

LastEditorDisplayName: Fabian Steeg


问:
Discord.py code is not read/writing JSON file correctly
My code to check whether a user is in the table or not:

@client.event
async def on_message(ctx):
    id = ctx.author.id
    with open('coins.json') as coins:
        coinData = json.load(coins)

    with open('shop.json') as shop:
        shopData = json.load(shop)

    await client.process_commands(ctx)

    if id in coinData:
        print('exists')
    else:
        coinData["players"][id] = 0
        with open('coins.json', 'w') as coins:
            json.dump(coinData, coins)

```

<p>The JSON file it is reading:</p>

```{"players": {"325616103143505932": 0}}
```

<p>What happens when someone sends a message: </p>

```{"players": {"325616103143505932": 0, "325616103143505932": 0}}
```

And it doesn't print 'exists' in console, no matter how many messages the person sends, but it adds the key value pair only twice.

答:
In python, a string value and an integer value are different.

>>> a = 1
>>> b = '1'
>>> a == b
False
```

<p>So you should either convert your existing json file to using integer IDs (by removing the quotes) or by using <code>str()</code> to convert the integer ID to a string.</p>

<p>Here's using a string conversion (with integers you don't have to change anything, only update your file):</p>

<pre class="lang-py prettyprint-override"><code>@client.event
async def on_message(ctx):
    id = str(ctx.author.id) # this line
    with open('coins.json') as coins:
        coinData = json.load(coins)

    with open('shop.json') as shop:
        shopData = json.load(shop)

    await client.process_commands(ctx)

    if id in coinData:
        print('exists')
    else:
        coinData["players"][id] = 0
        with open('coins.json', 'w') as coins:
            json.dump(coinData, coins)
</code>```

Body:
My code to check whether a user is in the table or not:

@client.event
async def on_message(ctx):
    id = ctx.author.id
    with open('coins.json') as coins:
        coinData = json.load(coins)

    with open('shop.json') as shop:
        shopData = json.load(shop)

    await client.process_commands(ctx)

    if id in coinData:
        print('exists')
    else:
        coinData["players"][id] = 0
        with open('coins.json', 'w') as coins:
            json.dump(coinData, coins)

The JSON file it is reading:

{"players": {"325616103143505932": 0}}

What happens when someone sends a message:

{"players": {"325616103143505932": 0, "325616103143505932": 0}}

And it doesn't print 'exists' in console, no matter how many messages the person sends, but it adds the key value pair only twice.

Body:
In python, a string value and an integer value are different.

>>> a = 1
>>> b = '1'
>>> a == b
False

So you should either convert your existing json file to using integer IDs (by removing the quotes) or by using str() to convert the integer ID to a string.

Here's using a string conversion (with integers you don't have to change anything, only update your file):

@client.event
async def on_message(ctx):
    id = str(ctx.author.id) # this line
    with open('coins.json') as coins:
        coinData = json.load(coins)

    with open('shop.json') as shop:
        shopData = json.load(shop)

    await client.process_commands(ctx)

    if id in coinData:
        print('exists')
    else:
        coinData["players"][id] = 0
        with open('coins.json', 'w') as coins:
            json.dump(coinData, coins)


问:
Constant Flickering of ExtTextOut text, and after a set amount of time the text reverts to the default font
This is my first post, so please forgive any mistakes.

I am working with win32 c++, and I have a basic window that will give the date and time (including seconds), and update accordingly. Additionally, I've made it so the text will change position a slight amount according to the mouse position (almost like this demo, https://css-tricks.com/animate-a-container-on-mouse-over-using-perspective-and-transform/ but it moves x and y, not z according to mouse position). Whenever I run my code, however, I get this flickering on my text where it goes white for an instant then appears on the screen again. I think this is because I'm painting certain pixels twice, but I can't figure out how to fix it. Furthermore, after a certain amount of time (say 1-2 minutes), my font on my text will revert to the default font. During debug I can see the process memory continuously increases to 20, then the font changes to the default and it goes down again. Any ideas?
I think somewhere in this section I messed up:

```<code>LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
 {

switch (message)
{
case WM_COMMAND:
    {
        int wmId = LOWORD(wParam);
        // Parse the menu selections:
        switch (wmId)
        {
        case IDM_ABOUT:
            DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
            break;
        case IDM_EXIT:
            DestroyWindow(hWnd);
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
    }
    break;
  #define SECOND_TIMER 2
case WM_TIMER:
    if (wParam == SECOND_TIMER)
    {
        InvalidateRect(hWnd, NULL, TRUE); // invalidate whole window
    }
    break;
//case WM_ERASEBKGND:
  //  return 1;

case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);

        POINT point;
        GetCursorPos(&point);
        ScreenToClient(hWnd, &point);
        ClickAnim(point.x, point.y, hdc);

        SetTimer(hWnd, SECOND_TIMER, SECOND_TIMER, NULL);

        HFONT hFont = CreateFont(70, 30, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
            CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, VARIABLE_PITCH, TEXT("Segoe UI Light"));
        SelectObject(hdc, hFont);

        TCHAR time[100];
        TCHAR date[100];
        SYSTEMTIME localTime;
        GetLocalTime(&localTime);
        wsprintfW(time, L"%.2u:%.2u:%.2u", localTime.wHour, localTime.wMinute, localTime.wSecond);
        switch (localTime.wMonth)
        {
            case 1:
                wsprintfW(date, L"Jan %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 2:
                wsprintfW(date, L"Feb %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 3:
                wsprintfW(date, L"Mar %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 4:
                wsprintfW(date, L"Apr %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 5:
                wsprintfW(date, L"May %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 6:
                wsprintfW(date, L"Jun %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 7:
                wsprintfW(date, L"Jul %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 8:
                wsprintfW(date, L"Aug %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 9:
                wsprintfW(date, L"Sep %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 10:
                wsprintfW(date, L"Oct %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 11:
                wsprintfW(date, L"Nov %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 12:
                wsprintfW(date, L"Dec %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
        }

        RECT desktop;
        // Get a handle to the desktop window
        const HWND hDesktop = GetDesktopWindow();
        // Get the size of screen to the variable desktop
        GetClientRect(hDesktop, &desktop);
        // TODO: Add any drawing code that uses hdc here...
        //get dimensions of window
        RECT rect;
        GetClientRect(hWnd, &rect);

        HWND desktophWnd = GetDesktopWindow();

        ExtTextOut(hdc, rect.right / 2 - 95 - point.x / 100, rect.bottom / 2 - 40 - point.y / 100, ETO_OPAQUE, NULL, time, _tcslen(time), NULL);

        HFONT smallFont = CreateFont(35, 15, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_OUTLINE_PRECIS,
            CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, VARIABLE_PITCH, TEXT("Segoe UI"));
        SelectObject(hdc, smallFont);
        ExtTextOut(hdc, rect.right / 2 - 85 - point.x / 100, rect.bottom / 2 - 70 - point.y / 100, ETO_OPAQUE, NULL, date, _tcslen(date), NULL);

        EndPaint(hWnd, &ps);

    }
    break;
case WM_DESTROY:
    PostQuitMessage(0);
    break;
default:
    return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
</code>```

}

答:
You call CreateFont a couple of times during your paint, but you never unselect that font from the device context, nor do you delete the font objects.  Since the fonts are the always the same, just create them once and reuse that object.  This will cut down some on the paint time.

As for the flicker, the third parameter to InvalidateRect should be FALSE (so that the background is not erased when BeginPaint is called). When you go to paint your window, erase the part of the window that you will be filling (possibly including the previous location of the time).  Also do as much work as possible before calling BeginPaint. This will reduce the flicker but may not eliminate it entirely. To eliminate it entirely will require some sort of double buffering.

Body:
This is my first post, so please forgive any mistakes.

I am working with win32 c++, and I have a basic window that will give the date and time (including seconds), and update accordingly. Additionally, I've made it so the text will change position a slight amount according to the mouse position (almost like this demo, https://css-tricks.com/animate-a-container-on-mouse-over-using-perspective-and-transform/ but it moves x and y, not z according to mouse position). Whenever I run my code, however, I get this flickering on my text where it goes white for an instant then appears on the screen again. I think this is because I'm painting certain pixels twice, but I can't figure out how to fix it. Furthermore, after a certain amount of time (say 1-2 minutes), my font on my text will revert to the default font. During debug I can see the process memory continuously increases to 20, then the font changes to the default and it goes down again. Any ideas?
I think somewhere in this section I messed up:

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
 {

switch (message)
{
case WM_COMMAND:
    {
        int wmId = LOWORD(wParam);
        // Parse the menu selections:
        switch (wmId)
        {
        case IDM_ABOUT:
            DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
            break;
        case IDM_EXIT:
            DestroyWindow(hWnd);
            break;
        default:
            return DefWindowProc(hWnd, message, wParam, lParam);
        }
    }
    break;
  #define SECOND_TIMER 2
case WM_TIMER:
    if (wParam == SECOND_TIMER)
    {
        InvalidateRect(hWnd, NULL, TRUE); // invalidate whole window
    }
    break;
//case WM_ERASEBKGND:
  //  return 1;

case WM_PAINT:
    {
        PAINTSTRUCT ps;
        HDC hdc = BeginPaint(hWnd, &ps);

        POINT point;
        GetCursorPos(&point);
        ScreenToClient(hWnd, &point);
        ClickAnim(point.x, point.y, hdc);

        SetTimer(hWnd, SECOND_TIMER, SECOND_TIMER, NULL);

        HFONT hFont = CreateFont(70, 30, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS,
            CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, VARIABLE_PITCH, TEXT("Segoe UI Light"));
        SelectObject(hdc, hFont);

        TCHAR time[100];
        TCHAR date[100];
        SYSTEMTIME localTime;
        GetLocalTime(&localTime);
        wsprintfW(time, L"%.2u:%.2u:%.2u", localTime.wHour, localTime.wMinute, localTime.wSecond);
        switch (localTime.wMonth)
        {
            case 1:
                wsprintfW(date, L"Jan %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 2:
                wsprintfW(date, L"Feb %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 3:
                wsprintfW(date, L"Mar %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 4:
                wsprintfW(date, L"Apr %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 5:
                wsprintfW(date, L"May %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 6:
                wsprintfW(date, L"Jun %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 7:
                wsprintfW(date, L"Jul %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 8:
                wsprintfW(date, L"Aug %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 9:
                wsprintfW(date, L"Sep %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 10:
                wsprintfW(date, L"Oct %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 11:
                wsprintfW(date, L"Nov %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
            case 12:
                wsprintfW(date, L"Dec %.2u, %.2u", localTime.wDay, localTime.wYear);
                break;
        }

        RECT desktop;
        // Get a handle to the desktop window
        const HWND hDesktop = GetDesktopWindow();
        // Get the size of screen to the variable desktop
        GetClientRect(hDesktop, &desktop);
        // TODO: Add any drawing code that uses hdc here...
        //get dimensions of window
        RECT rect;
        GetClientRect(hWnd, &rect);

        HWND desktophWnd = GetDesktopWindow();

        ExtTextOut(hdc, rect.right / 2 - 95 - point.x / 100, rect.bottom / 2 - 40 - point.y / 100, ETO_OPAQUE, NULL, time, _tcslen(time), NULL);

        HFONT smallFont = CreateFont(35, 15, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_OUTLINE_PRECIS,
            CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, VARIABLE_PITCH, TEXT("Segoe UI"));
        SelectObject(hdc, smallFont);
        ExtTextOut(hdc, rect.right / 2 - 85 - point.x / 100, rect.bottom / 2 - 70 - point.y / 100, ETO_OPAQUE, NULL, date, _tcslen(date), NULL);

        EndPaint(hWnd, &ps);

    }
    break;
case WM_DESTROY:
    PostQuitMessage(0);
    break;
default:
    return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;

}


问:
Get data from firestore using document id
I have two collections in my firestore database, the first is list of all the documents (BlockList), and the second for the users. when the user bookmark post on the app, send only the id of this post to sub-collection (Favourites).

so how can i display this sub-collection's documents from the first collection based on its ids.

```<code>firebaseFirestore.collection("Users")
                .document(userId).collection("Favorites").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    List<String> list = new ArrayList<>();
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        list.add(document.getId());
                    }
                    Log.d(TAG, list.toString());
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });
</code>```

I Use this code to reach the list of the sub-collection ids, but i want to know how to use it to get the documents that appropriate to this ids from the main collection(BlockList).

答:
After the loop you already have a list of the ids, just loop through them and find them in blockedList:</p>

```<code>....
....
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}

//here loop through the list

for(int i = 0 ; i<list.size() ; i++){

//now refer to the id in the blocked list
firebaseFirestore.collection("BlockList").document(list.get(i)).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {

    .........

    });

}

......
......
</code>```

Body:
I have two collections in my firestore database, the first is list of all the documents (BlockList), and the second for the users. when the user bookmark post on the app, send only the id of this post to sub-collection (Favourites).

so how can i display this sub-collection's documents from the first collection based on its ids.

firebaseFirestore.collection("Users")
                .document(userId).collection("Favorites").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    List<String> list = new ArrayList<>();
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        list.add(document.getId());
                    }
                    Log.d(TAG, list.toString());
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

I Use this code to reach the list of the sub-collection ids, but i want to know how to use it to get the documents that appropriate to this ids from the main collection(BlockList).

Body:
After the loop you already have a list of the ids, just loop through them and find them in blockedList:

....
....
for (QueryDocumentSnapshot document : task.getResult()) {
list.add(document.getId());
}

//here loop through the list

for(int i = 0 ; i<list.size() ; i++){

//now refer to the id in the blocked list
firebaseFirestore.collection("BlockList").document(list.get(i)).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {

    .........

    });

}

......
......


问:
How to capture on-JVM-exit heap dumps without affecting the ECS service?
My JVM-based app runs on Amazon ECS. Under some conditions that I cannot reproduce on test environments it crashes with an OutOfMemoryError. I want to capture the JVM heap dump (using HeapDumpOnOutOfMemoryError) to see what's going on. But there is a problem - because my app uses a lot of memory, the heap dumping takes very long time and ECS kills the container in the middle of it, because the health checks fail. I end up with an unusable, truncated dump file.

I can obtain a correct heap dump by changing the health-check configuration but it potentially affects the ECS service, because without good health-check the cluster can be running unresponsive instances.

I'm looking for a way, that will let me capture the heap dumps automatically with smallest possible impact to the production cluster.

答:
Is this around a Fargate instance or EC2?

In either case, you can add an EC2 instance in the same cluster, and the node, even when the task fails, would be able to login to the host and fetch the heap dump.


问:
Sometimes "Error: Execution context was destroyed, most likely because of a navigation."
I have this code:

```<code>(async function(){
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
try{
    await page.goto('https://erp2.webmaissistemas.com.br/csp/e8p7g7q/system/www/login.csp');

    await page.click('#UserName')
    await page.keyboard.type('123');

    await page.click('#Password')
    await page.keyboard.type('123');

    await page.click('#botaoLogin')

    await page.waitForNavigation()

    let form = await page.$('#form')
    if (form){
        let content = await form.$eval('.alert-danger', element => element.textContent)
        throw content
    }
    console.log('OK')
}
catch (e){
    console.log('Error: ', e)
}
})()
</code>```

Sometimes, give "Error: Execution context was destroyed, most likely because of a navigation."

Whats is solution?

答:
If I remember correctly (you can search puppeteer issues in GitHub for this error message), this is a common, but a hardly catchable issue with some sites and navigation in the code. You can minimize it 1) with reducing race condition danger for click and navigation events and 2) with additional waiting for some time after the navigation or with waiting for some selector:

'use strict';

const puppeteer = require('puppeteer');

(async function main() {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  try {
    await page.goto('https://erp2.webmaissistemas.com.br/csp/e8p7g7q/system/www/login.csp');

    await page.click('#UserName');
    await page.keyboard.type('123');

    await page.click('#Password');
    await page.keyboard.type('123');

    await Promise.all([
      page.waitForNavigation(),
      page.click('#botaoLogin'),
    ]);

    await page.waitForSelector('#form');

    const form = await page.$('#form');
    if (form) {
      const content = await form.$eval('.alert-danger', element => element.textContent);
      throw content;
    }
    console.log('OK');
  } catch (e) {
    console.log('Error: ', e);
  }
})();

```

Body:
I have this code:

(async function(){
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
try{
    await page.goto('https://erp2.webmaissistemas.com.br/csp/e8p7g7q/system/www/login.csp');

    await page.click('#UserName')
    await page.keyboard.type('123');

    await page.click('#Password')
    await page.keyboard.type('123');

    await page.click('#botaoLogin')

    await page.waitForNavigation()

    let form = await page.$('#form')
    if (form){
        let content = await form.$eval('.alert-danger', element => element.textContent)
        throw content
    }
    console.log('OK')
}
catch (e){
    console.log('Error: ', e)
}
})()

Sometimes, give "Error: Execution context was destroyed, most likely because of a navigation."

Whats is solution?


问:
Using for loop to find the biggest number in an array
I'm a begginer in c# and I'm trying to solve problems and exercises, what I have to do is write a method that compares the jump height of a jumper to the height of the hurdles, if the jump height is equal to or greater than the biggest hurdle, the method should return true. The heights of the hurdles are imputed in the form of an array, and the jump height is an integer.
The code I wrote was:

```<code>public static bool hurdleJump(int[] hurdles, int jumpHeight)
{
    int height= 0;
    for(int i = 0; i == hurdles.Length; i++)
    {
        if(hurdles[i] > height)
            height = hurdles[i];
    }

    if(jumpHeight >= height)
    {
        return true;
    }
    else
    {
        return false;
    }
}
</code>```

I used a for loop to find the biggest value inside of the array and then compared that to the int, but this code doesn't work with some arrays and I have no idea why, what am I missing?

答:
Your loop is not running because of the condition;

```<code>for(int i = 0; i == hurdles.Length; i++)
</code>```

You must use:

```<code>for(int i = 0; i < hurdles.Length; i++)
</code>```

Body:
I'm a begginer in c# and I'm trying to solve problems and exercises, what I have to do is write a method that compares the jump height of a jumper to the height of the hurdles, if the jump height is equal to or greater than the biggest hurdle, the method should return true. The heights of the hurdles are imputed in the form of an array, and the jump height is an integer.
The code I wrote was:

public static bool hurdleJump(int[] hurdles, int jumpHeight)
{
    int height= 0;
    for(int i = 0; i == hurdles.Length; i++)
    {
        if(hurdles[i] > height)
            height = hurdles[i];
    }

    if(jumpHeight >= height)
    {
        return true;
    }
    else
    {
        return false;
    }
}

I used a for loop to find the biggest value inside of the array and then compared that to the int, but this code doesn't work with some arrays and I have no idea why, what am I missing?

Body:
Your loop is not running because of the condition;

for(int i = 0; i == hurdles.Length; i++)

You must use:

for(int i = 0; i < hurdles.Length; i++)


问:
How to make a countdown timer for a certain time and date in python?
I'm working on a countdown timer for the next spacex launch with python and tkinter. The timer is supposed to end at 2020-05-30, 22:30 CEST. I want it to update for every second HOURS:MINUTES:SECONDS. I've tried but all i could come up with is this, which still gives me an error.</p>

```<code>import tkinter as tk
from datetime import datetime
import time

HEIGHT = 250
WIDTH = 1000

def timer():
    spacex = datetime(2020, 5, 30, 22 - 1, 30, 0).timestamp()
    dif = spacex - time.time()

    # H:M:S
    while (dif >= 0):
        dif = spacex - time.time()

        textline = str(dif // 3600)[:2] + ":" + str((dif // 60) % 60)[:2] + ":" + str((dif // 1) % 60[:2]
        time.sleep(1)

        v = str(textline)
        label["text"] = v

# TKINTER BELOW
root = tk.Tk()

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame = tk.Frame(root, bg="#808080", bd=20)
frame.place(relwidth=0.6, relheight=0.4, relx=0.2, rely=0.25)

button = tk.Button(root, text="See timer!", font="Arial", command=lambda: timer())
button.place(relheight=0.1, relwidth=0.1)

label = tk.Label(frame, font="Arial")
label.place(relwidth=1, relheight=1)

root.mainloop()
</code>```

答:
The immediate error is a missing closing parenthesis for str() on this line:

```<code>... + str((dif // 1) % 60[:2]
</code>```

But while we're at it, let's use tkinter's own timing mechanism instead of a loop and sleep(), and use the time formatting functions that Python provides.  And boost the font size:

```<code>import tkinter as tk
from datetime import datetime
import time

WIDTH, HEIGHT = 1000, 250

def timer():
    space_x = datetime(2020, 5, 30, 22 - 1, 30, 0).timestamp()
    delta = space_x - time.time()

    if delta >= 0:
        label["text"] = time.strftime("%d day(s), %H:%M:%S", time.localtime(delta))

        root.after(1000, timer)

root = tk.Tk()

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame = tk.Frame(root, bg="#808080", bd=20)
frame.place(relwidth=0.6, relheight=0.4, relx=0.2, rely=0.25)

button = tk.Button(root, text="See timer!", font="Arial", command=timer)
button.place(relheight=0.1, relwidth=0.1)

label = tk.Label(frame, font=("Arial", "24", "bold"))
label.place(relwidth=1, relheight=1)

root.mainloop()
</code>```

Using strftime() this way makes it only good for a month prior.

Body:
I'm working on a countdown timer for the next spacex launch with python and tkinter. The timer is supposed to end at 2020-05-30, 22:30 CEST. I want it to update for every second HOURS:MINUTES:SECONDS. I've tried but all i could come up with is this, which still gives me an error.

import tkinter as tk
from datetime import datetime
import time

HEIGHT = 250
WIDTH = 1000

def timer():
    spacex = datetime(2020, 5, 30, 22 - 1, 30, 0).timestamp()
    dif = spacex - time.time()

    # H:M:S
    while (dif >= 0):
        dif = spacex - time.time()

        textline = str(dif // 3600)[:2] + ":" + str((dif // 60) % 60)[:2] + ":" + str((dif // 1) % 60[:2]
        time.sleep(1)

        v = str(textline)
        label["text"] = v

# TKINTER BELOW
root = tk.Tk()

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame = tk.Frame(root, bg="#808080", bd=20)
frame.place(relwidth=0.6, relheight=0.4, relx=0.2, rely=0.25)

button = tk.Button(root, text="See timer!", font="Arial", command=lambda: timer())
button.place(relheight=0.1, relwidth=0.1)

label = tk.Label(frame, font="Arial")
label.place(relwidth=1, relheight=1)

root.mainloop()

Body:
The immediate error is a missing closing parenthesis for str() on this line:

... + str((dif // 1) % 60[:2]

But while we're at it, let's use tkinter's own timing mechanism instead of a loop and sleep(), and use the time formatting functions that Python provides.  And boost the font size:

import tkinter as tk
from datetime import datetime
import time

WIDTH, HEIGHT = 1000, 250

def timer():
    space_x = datetime(2020, 5, 30, 22 - 1, 30, 0).timestamp()
    delta = space_x - time.time()

    if delta >= 0:
        label["text"] = time.strftime("%d day(s), %H:%M:%S", time.localtime(delta))

        root.after(1000, timer)

root = tk.Tk()

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame = tk.Frame(root, bg="#808080", bd=20)
frame.place(relwidth=0.6, relheight=0.4, relx=0.2, rely=0.25)

button = tk.Button(root, text="See timer!", font="Arial", command=timer)
button.place(relheight=0.1, relwidth=0.1)

label = tk.Label(frame, font=("Arial", "24", "bold"))
label.place(relwidth=1, relheight=1)

root.mainloop()

Using strftime() this way makes it only good for a month prior.


问:
Throttle HTTP request in Java Servlet
In a java servlet, how can I throttle http requests coming from users based on the client's IP address?  I do not want to serve more than X requests per second coming from a particular source IP address where X is configurable and having practical values in [0.1; 10] range (from 1 request in 10 sec to 10 requests per sec).</p>

答: I would write a Filter for that task.</p>

Title: Throttle HTTP request in Java Servlet

Body: I would write a Filter for that task.


问:
How do I fix conda UnsatisfiableError of my custom conda package?
I'm trying to package my python code to publish in on Anaconda cloud.
The folder structure looks like this:

```<code>.
├── conda-recipe
│   ├── build.bat
│   ├── build.sh
│   └── meta.yaml
├── demos
│   ├── datasets
│   │   ├── com-amazon.all.dedup.cmty.txt
│   │   ├── com-amazon.ungraph.txt
│   │   ├── email-Eu-core-department-labels.txt
│   │   └── email-Eu-core.txt
│   ├── directed_example.ipynb
│   ├── email_eu_core_network_evaluation-Copy1.ipynb
│   ├── node_classification.ipynb
│   └── zacharys_karate_club_evaluation.ipynb
├── LICENSE.txt
├── README.md
├── setup.py
├── sten
│   ├── embedding.py
│   └── __init__.py
├── test
│   ├── __init__.py
│   └── test_system.py
├── zachary_computed.png
└── zachary_expected.png

</code>```

The meta.yaml file:

package:
  name: sten
  version: "0.1.0"

source:
  path: ..

build:
  number: 0
  noarch: generic

requirements:
  build:
    - python >=3.7
    - setuptools
  run:
    - python >=3.7
    - pypardiso >=0.2.2
    - numpy >=1.18.1
    - networkx >=2.4
    - scipy >=1.4.1
    - markdown

test:
  imports:
    - sten.embedding

about:
  home: https://github.com/monomonedula/simple-graph-embedding
  license: Apache License 2.0
  license_file: LICENSE.txt
  summary: Simple deterministic algorithm for generating graph nodes topological embeddings.
```

<p>Command I am using to build the package (haasad is the name of the channel of the pypardiso package):
<code>conda build conda-recipe -c haasad</code>
The build is successful and I have uploaded it here:
https://anaconda.org/monomonedula/sten</p>

<p>However, after installation using both local build like so:
<code>conda install sten --use-local -c haasad</code>
and the build uploaded to the cloud
<code>conda install -c monomonedula sten -c haasad</code>
I am encountering several problems.</p>

<ul>
<li>When using python 3.7 I am unable to import my package even though it is listed in <code>conda list</code> (I have double checked everything, I am using the correct interpreter).</li>
<li>When using python 3.8 I am able to import and use it, but I am unable to install stellargraph for an unknown reason. The error message: </li>
</ul>

```Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: \
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
failed

UnsatisfiableError: The following specifications were found to be incompatible with each other:

Output in format: Requested package -> Available versions
```

<p>Output of <code>conda search sten -c monomonedula --info</code>:</p>

```sten 0.1.0 py38_0
-----------------
file name   : sten-0.1.0-py38_0.tar.bz2
name        : sten
version     : 0.1.0
build       : py38_0
build number: 0
size        : 16 KB
license     : Apache License 2.0
subdir      : noarch
url         : https://conda.anaconda.org/monomonedula/noarch/sten-0.1.0-py38_0.tar.bz2
md5         : 53661562513861f9433b252c8ae7b5f4
timestamp   : 2020-05-23 19:24:36 UTC
dependencies:
  - markdown
  - networkx >=2.4
  - numpy >=1.18.1
  - pypardiso >=0.2.2
  - python >=3.7
  - scipy >=1.4.1

sten 0.1.0 py38_0
-----------------
file name   : sten-0.1.0-py38_0.tar.bz2
name        : sten
version     : 0.1.0
build       : py38_0
build number: 0
size        : 16 KB
license     : Apache License 2.0
subdir      : noarch
url         : https://conda.anaconda.org/monomonedula/noarch/sten-0.1.0-py38_0.tar.bz2
md5         : 53661562513861f9433b252c8ae7b5f4
timestamp   : 2020-05-23 19:24:36 UTC
dependencies:
  - markdown
  - networkx >=2.4
  - numpy >=1.18.1
  - pypardiso >=0.2.2
  - python >=3.7
  - scipy >=1.4.1
```

<p>Output of <code>conda search stellargraph -c stellargraph --info</code>:</p>

```stellargraph 1.0.0 py_0
-----------------------
file name   : stellargraph-1.0.0-py_0.tar.bz2
name        : stellargraph
version     : 1.0.0
build       : py_0
build number: 0
size        : 7.8 MB
license     : Apache Software
subdir      : noarch
url         : https://conda.anaconda.org/stellargraph/noarch/stellargraph-1.0.0-py_0.tar.bz2
md5         : e62b9c897d0a5481159c1e7cb8024717
timestamp   : 2020-05-05 07:54:44 UTC
dependencies:
  - gensim >=3.4.0
  - ipykernel
  - ipython
  - matplotlib >=2.2
  - networkx >=2.2
  - numpy >=1.14
  - pandas >=0.24
  - python >=3.6
  - scikit-learn >=0.20
  - scipy >=1.1.0
  - tensorflow >=2.1.0
```

The repo

What am I missing here and how do I package it properly?

答:
The problem is in your meta.yaml file. According to an Anaconda blog post:

Noarch generic packages allow users to distribute docs, datasets, and source code in conda packages

and

Noarch Python packages cut down on the overhead of building multiple different pure Python packages on different architectures and Python versions by sorting out platform and Python version-specific differences at install time

Because you want to distribute a pure python package, you should use noarch: python. Also, you don't need to set the python versions in build and run. I have included an updated meta.yaml below. It also includes the build script within it, so you no longer need the build.sh and build.bat files. It also fixes the license part to something that conda will accept (it's still Apache 2.0).

```<code>package:
  name: sten
  version: "0.1.0"

source:
  path: ..

build:
  number: 0
  noarch: python
  script: {{ PYTHON }} setup.py install

requirements:
  build:
    - python
    - setuptools
  run:
    - python
    - pypardiso >=0.2.2
    - numpy >=1.18.1
    - networkx >=2.4
    - scipy >=1.4.1
    - markdown

test:
  imports:
    - sten.embedding

about:
  home: https://github.com/monomonedula/simple-graph-embedding
  license: Apache-2.0
  license_family: Apache
  license_file: LICENSE.txt
  summary: Simple deterministic algorithm for generating graph nodes topological embeddings.
</code>```

Here are the steps I used to build and install this package using the above meta.yaml file:

```<code>git clone https://github.com/monomonedula/simple-graph-embedding
cd simple-graph-embedding/
git checkout 'refactor&cleanup'
# Replace contents of `meta.yaml`
rm conda-recipe/build.sh conda-recipe/build.bat
conda create --yes -n testing python=3.7 conda-build conda-verify
conda activate testing
conda-build --channel haasad .
</code>```

And here is what I did to install the package in the 3.7 environment. You will find the full path to the sten-0.1.0-py_0.tar.bz2 towards the bottom of the conda-build log output.

```<code>conda install -n testing /home/jakub/miniconda3/envs/testing/conda-bld/noarch/sten-0.1.0-py_0.tar.bz2
conda activate testing
$CONDA_PREFIX/bin/python -c "import sten"
</code>```

I also tested the installation in a python 3.8 environment.

```<code>conda create --yes -n testing3.8 python=3.8
conda install -n testing3.8 /home/jakub/miniconda3/envs/testing/conda-bld/noarch/sten-0.1.0-py_0.tar.bz2
conda activate testing3.8
$CONDA_PREFIX/bin/python -c "import sten"
</code>```

conda install --use-local sten isn't working for me -- there is a GitHub issue about it.

Body:
I'm trying to package my python code to publish in on Anaconda cloud.
The folder structure looks like this:

.
├── conda-recipe
│   ├── build.bat
│   ├── build.sh
│   └── meta.yaml
├── demos
│   ├── datasets
│   │   ├── com-amazon.all.dedup.cmty.txt
│   │   ├── com-amazon.ungraph.txt
│   │   ├── email-Eu-core-department-labels.txt
│   │   └── email-Eu-core.txt
│   ├── directed_example.ipynb
│   ├── email_eu_core_network_evaluation-Copy1.ipynb
│   ├── node_classification.ipynb
│   └── zacharys_karate_club_evaluation.ipynb
├── LICENSE.txt
├── README.md
├── setup.py
├── sten
│   ├── embedding.py
│   └── __init__.py
├── test
│   ├── __init__.py
│   └── test_system.py
├── zachary_computed.png
└── zachary_expected.png

The meta.yaml file:

package:
  name: sten
  version: "0.1.0"

source:
  path: ..

build:
  number: 0
  noarch: generic

requirements:
  build:
    - python >=3.7
    - setuptools
  run:
    - python >=3.7
    - pypardiso >=0.2.2
    - numpy >=1.18.1
    - networkx >=2.4
    - scipy >=1.4.1
    - markdown

test:
  imports:
    - sten.embedding

about:
  home: https://github.com/monomonedula/simple-graph-embedding
  license: Apache License 2.0
  license_file: LICENSE.txt
  summary: Simple deterministic algorithm for generating graph nodes topological embeddings.

Command I am using to build the package (haasad is the name of the channel of the pypardiso package):
conda build conda-recipe -c haasad
The build is successful and I have uploaded it here:
https://anaconda.org/monomonedula/sten

However, after installation using both local build like so:
conda install sten --use-local -c haasad
and the build uploaded to the cloud
conda install -c monomonedula sten -c haasad
I am encountering several problems.

When using python 3.7 I am unable to import my package even though it is listed in conda list (I have double checked everything, I am using the correct interpreter).

When using python 3.8 I am able to import and use it, but I am unable to install stellargraph for an unknown reason. The error message:

Collecting package metadata (current_repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source.
Collecting package metadata (repodata.json): done
Solving environment: failed with initial frozen solve. Retrying with flexible solve.
Solving environment: \
Found conflicts! Looking for incompatible packages.
This can take several minutes.  Press CTRL-C to abort.
failed

UnsatisfiableError: The following specifications were found to be incompatible with each other:

Output in format: Requested package -> Available versions

Output of conda search sten -c monomonedula --info:

sten 0.1.0 py38_0
-----------------
file name   : sten-0.1.0-py38_0.tar.bz2
name        : sten
version     : 0.1.0
build       : py38_0
build number: 0
size        : 16 KB
license     : Apache License 2.0
subdir      : noarch
url         : https://conda.anaconda.org/monomonedula/noarch/sten-0.1.0-py38_0.tar.bz2
md5         : 53661562513861f9433b252c8ae7b5f4
timestamp   : 2020-05-23 19:24:36 UTC
dependencies:
  - markdown
  - networkx >=2.4
  - numpy >=1.18.1
  - pypardiso >=0.2.2
  - python >=3.7
  - scipy >=1.4.1

sten 0.1.0 py38_0
-----------------
file name   : sten-0.1.0-py38_0.tar.bz2
name        : sten
version     : 0.1.0
build       : py38_0
build number: 0
size        : 16 KB
license     : Apache License 2.0
subdir      : noarch
url         : https://conda.anaconda.org/monomonedula/noarch/sten-0.1.0-py38_0.tar.bz2
md5         : 53661562513861f9433b252c8ae7b5f4
timestamp   : 2020-05-23 19:24:36 UTC
dependencies:
  - markdown
  - networkx >=2.4
  - numpy >=1.18.1
  - pypardiso >=0.2.2
  - python >=3.7
  - scipy >=1.4.1

Output of conda search stellargraph -c stellargraph --info:

stellargraph 1.0.0 py_0
-----------------------
file name   : stellargraph-1.0.0-py_0.tar.bz2
name        : stellargraph
version     : 1.0.0
build       : py_0
build number: 0
size        : 7.8 MB
license     : Apache Software
subdir      : noarch
url         : https://conda.anaconda.org/stellargraph/noarch/stellargraph-1.0.0-py_0.tar.bz2
md5         : e62b9c897d0a5481159c1e7cb8024717
timestamp   : 2020-05-05 07:54:44 UTC
dependencies:
  - gensim >=3.4.0
  - ipykernel
  - ipython
  - matplotlib >=2.2
  - networkx >=2.2
  - numpy >=1.14
  - pandas >=0.24
  - python >=3.6
  - scikit-learn >=0.20
  - scipy >=1.1.0
  - tensorflow >=2.1.0

The repo

What am I missing here and how do I package it properly?

Body:
The problem is in your meta.yaml file. According to an Anaconda blog post:

Noarch generic packages allow users to distribute docs, datasets, and source code in conda packages

and

Noarch Python packages cut down on the overhead of building multiple different pure Python packages on different architectures and Python versions by sorting out platform and Python version-specific differences at install time

Because you want to distribute a pure python package, you should use noarch: python. Also, you don't need to set the python versions in build and run. I have included an updated meta.yaml below. It also includes the build script within it, so you no longer need the build.sh and build.bat files. It also fixes the license part to something that conda will accept (it's still Apache 2.0).

package:
  name: sten
  version: "0.1.0"

source:
  path: ..

build:
  number: 0
  noarch: python
  script: {{ PYTHON }} setup.py install

requirements:
  build:
    - python
    - setuptools
  run:
    - python
    - pypardiso >=0.2.2
    - numpy >=1.18.1
    - networkx >=2.4
    - scipy >=1.4.1
    - markdown

test:
  imports:
    - sten.embedding

about:
  home: https://github.com/monomonedula/simple-graph-embedding
  license: Apache-2.0
  license_family: Apache
  license_file: LICENSE.txt
  summary: Simple deterministic algorithm for generating graph nodes topological embeddings.

Here are the steps I used to build and install this package using the above meta.yaml file:

git clone https://github.com/monomonedula/simple-graph-embedding
cd simple-graph-embedding/
git checkout 'refactor&cleanup'
# Replace contents of `meta.yaml`
rm conda-recipe/build.sh conda-recipe/build.bat
conda create --yes -n testing python=3.7 conda-build conda-verify
conda activate testing
conda-build --channel haasad .

And here is what I did to install the package in the 3.7 environment. You will find the full path to the sten-0.1.0-py_0.tar.bz2 towards the bottom of the conda-build log output.

conda install -n testing /home/jakub/miniconda3/envs/testing/conda-bld/noarch/sten-0.1.0-py_0.tar.bz2
conda activate testing
$CONDA_PREFIX/bin/python -c "import sten"

I also tested the installation in a python 3.8 environment.

conda create --yes -n testing3.8 python=3.8
conda install -n testing3.8 /home/jakub/miniconda3/envs/testing/conda-bld/noarch/sten-0.1.0-py_0.tar.bz2
conda activate testing3.8
$CONDA_PREFIX/bin/python -c "import sten"

conda install --use-local sten isn't working for me -- there is a GitHub issue about it.


问:
Struts2 file upload - execute() is not being invoked
I'm using Struts2 2.5.20 and have written a file upload action that almost works. I can see in the debugger that setReport(), setReportContentType() and setReportFileName() are being called and the parameter values are correct. However, the execute() method is never invoked. I tried following the call stack to see where it should have been called, but there's just layer after layer of interceptors that I can't find the bottom.

Does anyone know what the reason for execute() might be?

```<code>public class ImportReportAction extends CampaignerActionSupport implements ValidationAware
{
  private File              report;
  private String            reportContentType;
  private String            reportFileName;

  @Override
  public String execute() throws Exception
  {
    ...
    return SUCCESS;
  }

  public void setReport(
    File report)
  {
    this.report = report;
  }

  public void setReportContentType(
    String reportContentType)
  {
    this.reportContentType = reportContentType;
  }

  @RequiredFieldValidator(type = ValidatorType.FIELD, key = "errors.required", messageParams = { "getText('labels.report.file')" })
  public void setReportFileName(
    String reportFileName)
  {
    this.reportFileName = reportFileName;
  }
}
</code>```

Update: I've discovered that the problem is in having the RequiredFieldValidator annotation. When that is present, the validation always fails but the s:actionerror tag is not displaying any message. When the annotation is not present, it allows a user to not pick a file and still calls execute().

The new question is: how to I correctly annotate my class for validation of a file upload?

答: I had to remove the @RequiredFieldValidator annotation, make my action implement ValidationAware and then implement a validate() method and manually put the validations in there.</p>

Body:
I'm using Struts2 2.5.20 and have written a file upload action that almost works. I can see in the debugger that setReport(), setReportContentType() and setReportFileName() are being called and the parameter values are correct. However, the execute() method is never invoked. I tried following the call stack to see where it should have been called, but there's just layer after layer of interceptors that I can't find the bottom.

Does anyone know what the reason for execute() might be?

public class ImportReportAction extends CampaignerActionSupport implements ValidationAware
{
  private File              report;
  private String            reportContentType;
  private String            reportFileName;

  @Override
  public String execute() throws Exception
  {
    ...
    return SUCCESS;
  }

  public void setReport(
    File report)
  {
    this.report = report;
  }

  public void setReportContentType(
    String reportContentType)
  {
    this.reportContentType = reportContentType;
  }

  @RequiredFieldValidator(type = ValidatorType.FIELD, key = "errors.required", messageParams = { "getText('labels.report.file')" })
  public void setReportFileName(
    String reportFileName)
  {
    this.reportFileName = reportFileName;
  }
}

Update: I've discovered that the problem is in having the RequiredFieldValidator annotation. When that is present, the validation always fails but the s:actionerror tag is not displaying any message. When the annotation is not present, it allows a user to not pick a file and still calls execute().

The new question is: how to I correctly annotate my class for validation of a file upload?


问:
Smooth scrolling on github readme
I have a github repository with README.md file. The file has anchor links, and when i click, the page immediately scrolls to anchor. How can i make that smooth. I also have github pages
one, in which i also want smooth scrolling. I can make <code>.html</code> file and add it to gihub pages, but it'll not work when you open a repository. Is there a way to make scrolling smooth in github repository's readme? </p>

答:
In general, this is a property of your browser, and whether the browser scrolls the page this way is an implementation detail of the browser and its settings.  It may be possible to change this with JavaScript, but for security reasons, GitHub ignores JavaScript in READMEs, so you can't change it there.

Since there is a potentially significant performance impact with enabling smooth scrolling, it's better to let each user choose how to configure their own browser instead of trying to force this on them.

Title: Smooth scrolling on github readme

Body:
I have a github repository with README.md file. The file has anchor links, and when i click, the page immediately scrolls to anchor. How can i make that smooth. I also have github pages
one, in which i also want smooth scrolling. I can make .html file and add it to gihub pages, but it'll not work when you open a repository. Is there a way to make scrolling smooth in github repository's readme?


问:
As a system user I have this error: ORA-01031: insufficient privileges
I have a stored procedure for deleting partitions. Before starting, I have to delete a constraint.

I installed the stored procedure on system user. When I test the procedure I have this error: 'ORA-01031: insufficient privileges'.

This is a piece of code that I wrote:

```<code>BEGIN

    EXECUTE IMMEDIATE 'ALTER TABLE USER_NAME.TABLE_NAME DISABLE CONSTRAINT CONSTRAINT_NAME';

EXCEPTION
    WHEN OTHERS THEN

        O_sCodError := 'NO_OK';
        O_sDesError := 'Error at DISABLE CONSTRAINT_NAME: ' || SQLERRM || ';';

        RETURN;

END;
</code>```

Well, as I execute the stored procedure as system, I do not understand the reason for I have that error. And I think I eventually think the same error when I try to delete a partition.

答:
You must grant SYSTEM account direct privilege (not with a role) to run ALTER TABLE on the target table because roles are not enabled in stored procedures by default: https://asktom.oracle.com/Misc/RolesAndProcedures.html.

Try:

```<code>grant alter any table to system;
</code>```

or

```<code>grant alter table on user_name.table_name to system;
</code>```

Body:
I have a stored procedure for deleting partitions. Before starting, I have to delete a constraint.

I installed the stored procedure on system user. When I test the procedure I have this error: 'ORA-01031: insufficient privileges'.

This is a piece of code that I wrote:

BEGIN

    EXECUTE IMMEDIATE 'ALTER TABLE USER_NAME.TABLE_NAME DISABLE CONSTRAINT CONSTRAINT_NAME';

EXCEPTION
    WHEN OTHERS THEN

        O_sCodError := 'NO_OK';
        O_sDesError := 'Error at DISABLE CONSTRAINT_NAME: ' || SQLERRM || ';';

        RETURN;

END;

Well, as I execute the stored procedure as system, I do not understand the reason for I have that error. And I think I eventually think the same error when I try to delete a partition.

Body:
You must grant SYSTEM account direct privilege (not with a role) to run ALTER TABLE on the target table because roles are not enabled in stored procedures by default: https://asktom.oracle.com/Misc/RolesAndProcedures.html.

Try:

grant alter any table to system;

or

grant alter table on user_name.table_name to system;


问:
Is it possible to generate random numbers through physical process simulation?
Is it possible to generate random numbers through physical process simulation?

If I simulate the physical roll of a dice (i.e. you picking it up, shaking it in your hand, releasing it onto the table and recording which side ends up "up"...) will that produce a "random" number or would I just have a complex simulation which really accomplishes nothing.

答: Unless you're prepared to model the quantum state of two entire dies you'll have nothing random...</p>

LastEditorDisplayName: Jonathan Leffler

OwnerDisplayName: Dave


问:
Adding Zooming in and out with a Tkinter Canvas Widget?
How would I add zooming in and out to the following script, i'd like to bind it to the mousewheel. If you're testing this script on linux don't forget to change the MouseWheel event to Button-4 and Button-5.</p>

```<code>from Tkinter import *
import Image, ImageTk

class GUI:
    def __init__(self,root):
        frame = Frame(root, bd=2, relief=SUNKEN)

        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)
        xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
        xscrollbar.grid(row=1, column=0, sticky=E+W)
        yscrollbar = Scrollbar(frame)
        yscrollbar.grid(row=0, column=1, sticky=N+S)
        self.canvas = Canvas(frame, bd=0, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set, xscrollincrement = 10, yscrollincrement = 10)
        self.canvas.grid(row=0, column=0, sticky=N+S+E+W)

        File = "PATH TO JPG PICTURE HERE"

        self.img = ImageTk.PhotoImage(Image.open(File))
        self.canvas.create_image(0,0,image=self.img, anchor="nw")
        self.canvas.config(scrollregion=self.canvas.bbox(ALL))
        xscrollbar.config(command=self.canvas.xview)
        yscrollbar.config(command=self.canvas.yview)

        frame.pack()

        self.canvas.bind("<Button 3>",self.grab)
        self.canvas.bind("<B3-Motion>",self.drag)
        root.bind("<MouseWheel>",self.zoom)

    def grab(self,event):
        self._y = event.y
        self._x = event.x

    def drag(self,event):
        if (self._y-event.y < 0): self.canvas.yview("scroll",-1,"units")
        elif (self._y-event.y > 0): self.canvas.yview("scroll",1,"units")
        if (self._x-event.x < 0): self.canvas.xview("scroll",-1,"units")
        elif (self._x-event.x > 0): self.canvas.xview("scroll",1,"units")
        self._x = event.x
        self._y = event.y

    def zoom(self,event):
        if event.delta>0: print "ZOOM IN!"
        elif event.delta<0: print "ZOOM OUT!"

root = Tk()
GUI(root)
root.mainloop()
</code>```

答:
Just for other's benefit who find this question I'm attaching my neer final test code which uses picture in picture/magnifying glass zooming. Its basically just an alteration to what samplebias already posted. It's also very cool to see as well :).

As I said before, if you're using this script on linux don't forget to change the MouseWheel event to Button-4 and Button-5. And you obviously need to insert a .JPG path where it says "INSERT JPG FILE PATH".

```<code>from Tkinter import *
import Image, ImageTk

class LoadImage:
    def __init__(self,root):
        frame = Frame(root)
        self.canvas = Canvas(frame,width=900,height=900)
        self.canvas.pack()
        frame.pack()
        File = "INSERT JPG FILE PATH"
        self.orig_img = Image.open(File)
        self.img = ImageTk.PhotoImage(self.orig_img)
        self.canvas.create_image(0,0,image=self.img, anchor="nw")

        self.zoomcycle = 0
        self.zimg_id = None

        root.bind("<MouseWheel>",self.zoomer)
        self.canvas.bind("<Motion>",self.crop)

    def zoomer(self,event):
        if (event.delta > 0):
            if self.zoomcycle != 4: self.zoomcycle += 1
        elif (event.delta < 0):
            if self.zoomcycle != 0: self.zoomcycle -= 1
        self.crop(event)

    def crop(self,event):
        if self.zimg_id: self.canvas.delete(self.zimg_id)
        if (self.zoomcycle) != 0:
            x,y = event.x, event.y
            if self.zoomcycle == 1:
                tmp = self.orig_img.crop((x-45,y-30,x+45,y+30))
            elif self.zoomcycle == 2:
                tmp = self.orig_img.crop((x-30,y-20,x+30,y+20))
            elif self.zoomcycle == 3:
                tmp = self.orig_img.crop((x-15,y-10,x+15,y+10))
            elif self.zoomcycle == 4:
                tmp = self.orig_img.crop((x-6,y-4,x+6,y+4))
            size = 300,200
            self.zimg = ImageTk.PhotoImage(tmp.resize(size))
            self.zimg_id = self.canvas.create_image(event.x,event.y,image=self.zimg)

if __name__ == '__main__':
    root = Tk()
    root.title("Crop Test")
    App = LoadImage(root)
    root.mainloop()
</code>```

Body:
How would I add zooming in and out to the following script, i'd like to bind it to the mousewheel. If you're testing this script on linux don't forget to change the MouseWheel event to Button-4 and Button-5.

from Tkinter import *
import Image, ImageTk

class GUI:
    def __init__(self,root):
        frame = Frame(root, bd=2, relief=SUNKEN)

        frame.grid_rowconfigure(0, weight=1)
        frame.grid_columnconfigure(0, weight=1)
        xscrollbar = Scrollbar(frame, orient=HORIZONTAL)
        xscrollbar.grid(row=1, column=0, sticky=E+W)
        yscrollbar = Scrollbar(frame)
        yscrollbar.grid(row=0, column=1, sticky=N+S)
        self.canvas = Canvas(frame, bd=0, xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set, xscrollincrement = 10, yscrollincrement = 10)
        self.canvas.grid(row=0, column=0, sticky=N+S+E+W)

        File = "PATH TO JPG PICTURE HERE"

        self.img = ImageTk.PhotoImage(Image.open(File))
        self.canvas.create_image(0,0,image=self.img, anchor="nw")
        self.canvas.config(scrollregion=self.canvas.bbox(ALL))
        xscrollbar.config(command=self.canvas.xview)
        yscrollbar.config(command=self.canvas.yview)

        frame.pack()

        self.canvas.bind("<Button 3>",self.grab)
        self.canvas.bind("<B3-Motion>",self.drag)
        root.bind("<MouseWheel>",self.zoom)

    def grab(self,event):
        self._y = event.y
        self._x = event.x

    def drag(self,event):
        if (self._y-event.y < 0): self.canvas.yview("scroll",-1,"units")
        elif (self._y-event.y > 0): self.canvas.yview("scroll",1,"units")
        if (self._x-event.x < 0): self.canvas.xview("scroll",-1,"units")
        elif (self._x-event.x > 0): self.canvas.xview("scroll",1,"units")
        self._x = event.x
        self._y = event.y

    def zoom(self,event):
        if event.delta>0: print "ZOOM IN!"
        elif event.delta<0: print "ZOOM OUT!"

root = Tk()
GUI(root)
root.mainloop()

Body:
Just for other's benefit who find this question I'm attaching my neer final test code which uses picture in picture/magnifying glass zooming. Its basically just an alteration to what samplebias already posted. It's also very cool to see as well :).

As I said before, if you're using this script on linux don't forget to change the MouseWheel event to Button-4 and Button-5. And you obviously need to insert a .JPG path where it says "INSERT JPG FILE PATH".

from Tkinter import *
import Image, ImageTk

class LoadImage:
    def __init__(self,root):
        frame = Frame(root)
        self.canvas = Canvas(frame,width=900,height=900)
        self.canvas.pack()
        frame.pack()
        File = "INSERT JPG FILE PATH"
        self.orig_img = Image.open(File)
        self.img = ImageTk.PhotoImage(self.orig_img)
        self.canvas.create_image(0,0,image=self.img, anchor="nw")

        self.zoomcycle = 0
        self.zimg_id = None

        root.bind("<MouseWheel>",self.zoomer)
        self.canvas.bind("<Motion>",self.crop)

    def zoomer(self,event):
        if (event.delta > 0):
            if self.zoomcycle != 4: self.zoomcycle += 1
        elif (event.delta < 0):
            if self.zoomcycle != 0: self.zoomcycle -= 1
        self.crop(event)

    def crop(self,event):
        if self.zimg_id: self.canvas.delete(self.zimg_id)
        if (self.zoomcycle) != 0:
            x,y = event.x, event.y
            if self.zoomcycle == 1:
                tmp = self.orig_img.crop((x-45,y-30,x+45,y+30))
            elif self.zoomcycle == 2:
                tmp = self.orig_img.crop((x-30,y-20,x+30,y+20))
            elif self.zoomcycle == 3:
                tmp = self.orig_img.crop((x-15,y-10,x+15,y+10))
            elif self.zoomcycle == 4:
                tmp = self.orig_img.crop((x-6,y-4,x+6,y+4))
            size = 300,200
            self.zimg = ImageTk.PhotoImage(tmp.resize(size))
            self.zimg_id = self.canvas.create_image(event.x,event.y,image=self.zimg)

if __name__ == '__main__':
    root = Tk()
    root.title("Crop Test")
    App = LoadImage(root)
    root.mainloop()


问:
How to take a set of data in excel and make a list that includes every data point?
I have a large data set that I need to make into a list. The data involves arrival of packages. I would need the list to be arranged by arrival time.

Currently my data looks like this.

During hour 1 (1:00) 2 blue, 3 red, 1 yellow, and 2 orange packages arrive.

During hour 2 (2:00) 5 blue, 5 red, 0 yellow, and 3 orange packages arrive.

From this data I would need to create a list arranged by arrival time for all the packages. It should look something like this.

Is there an excel function(s) that can help with this procedure?

答:
You can use PowerQuery to solve the question.

Format your Data as table (CTRL-T), name the table tbl_Packages and use this M-Code:

```<code>let
    Source = Excel.CurrentWorkbook(){[Name="tbl_Packages"]}[Content],
    Change_type = Table.TransformColumnTypes(Source,{{"Arrival Time", type text}, {"01:00", Int64.Type}, {"02:00", Int64.Type}, {"03:00", Int64.Type}, {"04:00", Int64.Type}}),
    Unpivot_Other = Table.UnpivotOtherColumns(Change_type, {"Arrival Time"}, "Time", "Count"),
    Filter_Rows = Table.SelectRows(Unpivot_Other, each ([Count] <> 0)),
    Custom_Column = Table.AddColumn(Filter_Rows, "LIst", each List.Numbers(1,[Count])),
    Expand_List = Table.ExpandListColumn(Custom_Column, "LIst"),
    Remove_other_columns = Table.SelectColumns(Expand_List,{"Arrival Time", "Time"}),
    Sort_Rows = Table.Sort(Remove_other_columns,{{"Time", Order.Ascending}, {"Arrival Time", Order.Ascending}})
in
    Sort_Rows
</code>```

Body:
You can use PowerQuery to solve the question.

Format your Data as table (CTRL-T), name the table tbl_Packages and use this M-Code:

let
    Source = Excel.CurrentWorkbook(){[Name="tbl_Packages"]}[Content],
    Change_type = Table.TransformColumnTypes(Source,{{"Arrival Time", type text}, {"01:00", Int64.Type}, {"02:00", Int64.Type}, {"03:00", Int64.Type}, {"04:00", Int64.Type}}),
    Unpivot_Other = Table.UnpivotOtherColumns(Change_type, {"Arrival Time"}, "Time", "Count"),
    Filter_Rows = Table.SelectRows(Unpivot_Other, each ([Count] <> 0)),
    Custom_Column = Table.AddColumn(Filter_Rows, "LIst", each List.Numbers(1,[Count])),
    Expand_List = Table.ExpandListColumn(Custom_Column, "LIst"),
    Remove_other_columns = Table.SelectColumns(Expand_List,{"Arrival Time", "Time"}),
    Sort_Rows = Table.Sort(Remove_other_columns,{{"Time", Order.Ascending}, {"Arrival Time", Order.Ascending}})
in
    Sort_Rows


答:
I don't think this is very common so probably there won't be a function for this, however you can hack your own fast function with Rcpp, here's an example:

```<code>library(data.table)
library(Rcpp)

DT <- data.table(date=seq(as.Date('2020-01-01'), as.Date('2020-01-10'), 1),
                 v=c(1,2,3,100,4,5,1000,8,8,10))
DT[, week := 1:.N %/% 7] # create a week column (you can adapt this to your needs)

# Add your logic to a cpp function
cppFunction("
    IntegerVector roll_cumsum(IntegerVector x) {
        int n = x.size();
        int cumsum = 0;
        IntegerVector y = clone(x);
        for (int i = 0; i < n; ++i) {
            y[i] += cumsum;
            cumsum += y[i];
        }
        return y;
    }
")

DT[, result := roll_cumsum(v), by = week][]
</code>```

Body:
Suppose I have the following zoo object:

x.orig <- read.zoo(data.frame(date=seq(as.Date('2020-01-01'), as.Date('2020-01-10'), 1), v=c(1,2,3,100,4,5,1000,8,8,10)))
2020-01-01 2020-01-02 2020-01-03 2020-01-04 2020-01-05 2020-01-06 2020-01-07 2020-01-08 2020-01-09 2020-01-10
         1          2          3        100          4          5       1000          8          8         10

I would like to compute a rolling sum of width=seq_along(x.orig) as follows:

2020-01-01 1
2020-01-02 1 + 2                                   #2020-01-01 + 2020-01-02
2020-01-03 1 + (1 + 2) + 3                         #2020-01-01 + 2020-01-02 + 2020-01-03
2010-01-04 1 + (1 + 2) + (1 + (1 + 2) + 3) + 100   #2020-01-01 + 2020-01-02 + 2020-01-03 + 2020-01-04
...

I would imagine the way to do this would be to result-feed x in some way so that x is updated after each rollapply loop so that the next rollapply iteration picks up the modified value in its window but am just not sure how to write it...

Body:
I don't think this is very common so probably there won't be a function for this, however you can hack your own fast function with Rcpp, here's an example:

library(data.table)
library(Rcpp)

DT <- data.table(date=seq(as.Date('2020-01-01'), as.Date('2020-01-10'), 1),
                 v=c(1,2,3,100,4,5,1000,8,8,10))
DT[, week := 1:.N %/% 7] # create a week column (you can adapt this to your needs)

# Add your logic to a cpp function
cppFunction("
    IntegerVector roll_cumsum(IntegerVector x) {
        int n = x.size();
        int cumsum = 0;
        IntegerVector y = clone(x);
        for (int i = 0; i < n; ++i) {
            y[i] += cumsum;
            cumsum += y[i];
        }
        return y;
    }
")

DT[, result := roll_cumsum(v), by = week][]