问:
How to mapping an Object with ArrayList with Retrofit2?
I have trying to make this call works, but always the return is null (and the problem isn't on API). If I try to make a Call  (Object with ArrayList), the callback is successful but the body is null. How I mapping this with Retrofit2 (I'm new with Retrofit2)? This is my service:

```<code>  @GET("farms/abstract")
  Call<Farm> getFarmList(@Header("Authorization") String token);
</code>```

The API response:

```<code>{
    "farms": [
        {
            "id": "0fc2b30c-4500-c399-4171-e2809373e281",
            "name": "Areado"
        },
        {
            "id": "81041a28-1193-4310-b616-fabcabdf63d1",
            "name": "Fazenda 3"
        }
    ]
}
</code>```

I use jsonschema2pojo.org to make my classes:

```<code>public class Farm {
    @SerializedName("farms")
    @Expose
    private List<FarmList> farms;

    public Farm() {
    }

    public List<FarmList> getFarms() {
        return farms;
    }

    public void setFarms(List<FarmList> farms) {
        this.farms = farms;
    }

    @Override
    public String toString() {
        return "Farm{" +
                "farms=" + farms +
                '}';
    }
}
</code>```

My FarmList.class:

```<code>public class FarmList {

    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;

    public FarmList() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "FarmList{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}
</code>```

RetrofitConfig:

```<code>public class RetrofitConfig {
    private final Retrofit retrofit;

    public RetrofitConfig() {
        this.retrofit = new Retrofit.Builder()
                /*URL API*/
                .baseUrl("API_URL")

                .addConverterFactory(GsonConverterFactory.create())

                .build();
    }

    public LoginService getLogin() {
        return this.retrofit.create(LoginService.class);
    }

    public FarmService getFarm() {
        return this.retrofit.create(FarmService.class);
    }

    public FarmService getFarmList() {
        return this.retrofit.create(FarmService.class);
    }
}
</code>```

答:
Only pass the endpoint in your call method @GET("abstract")
If you have not created a RetrofigConfig Class. I'd suggest first you make that, there you can define Baseurl for your apis

If your url is dynamic then you can make the call like this

```<code>@GET
Call<HashMap<String, String>> getLocationWithUrl(@Url String url);
</code>```

Body:
I have trying to make this call works, but always the return is null (and the problem isn't on API). If I try to make a Call  (Object with ArrayList), the callback is successful but the body is null. How I mapping this with Retrofit2 (I'm new with Retrofit2)? This is my service:

  @GET("farms/abstract")
  Call<Farm> getFarmList(@Header("Authorization") String token);

The API response:

{
    "farms": [
        {
            "id": "0fc2b30c-4500-c399-4171-e2809373e281",
            "name": "Areado"
        },
        {
            "id": "81041a28-1193-4310-b616-fabcabdf63d1",
            "name": "Fazenda 3"
        }
    ]
}

I use jsonschema2pojo.org to make my classes:

public class Farm {
    @SerializedName("farms")
    @Expose
    private List<FarmList> farms;

    public Farm() {
    }

    public List<FarmList> getFarms() {
        return farms;
    }

    public void setFarms(List<FarmList> farms) {
        this.farms = farms;
    }

    @Override
    public String toString() {
        return "Farm{" +
                "farms=" + farms +
                '}';
    }
}

My FarmList.class:

public class FarmList {

    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("name")
    @Expose
    private String name;

    public FarmList() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "FarmList{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

RetrofitConfig:

public class RetrofitConfig {
    private final Retrofit retrofit;

    public RetrofitConfig() {
        this.retrofit = new Retrofit.Builder()
                /*URL API*/
                .baseUrl("API_URL")

                .addConverterFactory(GsonConverterFactory.create())

                .build();
    }

    public LoginService getLogin() {
        return this.retrofit.create(LoginService.class);
    }

    public FarmService getFarm() {
        return this.retrofit.create(FarmService.class);
    }

    public FarmService getFarmList() {
        return this.retrofit.create(FarmService.class);
    }
}

Body:
Only pass the endpoint in your call method @GET("abstract")
If you have not created a RetrofigConfig Class. I'd suggest first you make that, there you can define Baseurl for your apis

If your url is dynamic then you can make the call like this

@GET
Call<HashMap<String, String>> getLocationWithUrl(@Url String url);


来源: stackexchange

问:
grouping continuous data with specific pattern
I have a data frame with a column like this (I am not posting other columns)

```<code>Value
1
1
1
0
0
1
0
0
1
1
2
2
0
0
1
0
0
1
1
1
0
0
2
2
1
1
2
0
0
1
0
</code>```

I am trying to group it based on a specific condition. Grouping has to be done when I have 1 and 2. But conditions like these are one group :

```<code>1 1 0 0 1 1 0 0
</code>```

Basically I need to group occurrences of 1 but in between 0s are allowed

Expected output:

```<code>Value   Group
    1   1
    1   1
    1   1
    0   1
    0   1
    1   1
    0   1
    0   1
    1   1
    1   1
    2   2
    2   2
    0   2
    0   2
    1   3
    0   3
    0   3
    1   3
    1   3
    1   3
    0   3
    0   3
    2   4
    2   4
    1   5
    1   5
    2   6
    0   6
    0   6
    1   7
    0   7
    2   8
    0   8
    2   8
    1   9
</code>```

答:
Here is another base approach that uses ave() to count the changes between 1 and 2 and then uses cummax() on the result to give the final groupings.

```<code>dat$Group <- cummax(ave(dat$Value, dat$Value == 0, FUN = function(x) cumsum(c(x[1], diff(x) != 0))))

dat
   Value Group
1      1     1
2      1     1
3      1     1
4      0     1
5      0     1
6      1     1
7      0     1
8      0     1
9      1     1
10     1     1
11     2     2
12     2     2
13     0     2
14     0     2
15     1     3
16     0     3
17     0     3
18     1     3
19     1     3
20     1     3
21     0     3
22     0     3
23     2     4
24     2     4
25     1     5
26     1     5
27     2     6
28     0     6
29     0     6
30     1     7
31     0     7
</code>```

In response to your comment, if you want the result by grouped by date, you can use a nested ave():

```<code>ave(ave(dat$Value, dat$Value == 0, dat$date, FUN = function(x) cumsum(c(x[1], diff(x) != 0))), dat$date, FUN = cummax)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a data frame with a column like this (I am not posting other columns)

Value
1
1
1
0
0
1
0
0
1
1
2
2
0
0
1
0
0
1
1
1
0
0
2
2
1
1
2
0
0
1
0

I am trying to group it based on a specific condition. Grouping has to be done when I have 1 and 2. But conditions like these are one group :

1 1 0 0 1 1 0 0

Basically I need to group occurrences of 1 but in between 0s are allowed

Expected output:

Value   Group
    1   1
    1   1
    1   1
    0   1
    0   1
    1   1
    0   1
    0   1
    1   1
    1   1
    2   2
    2   2
    0   2
    0   2
    1   3
    0   3
    0   3
    1   3
    1   3
    1   3
    0   3
    0   3
    2   4
    2   4
    1   5
    1   5
    2   6
    0   6
    0   6
    1   7
    0   7
    2   8
    0   8
    2   8
    1   9

Body:
Here is another base approach that uses ave() to count the changes between 1 and 2 and then uses cummax() on the result to give the final groupings.

dat$Group <- cummax(ave(dat$Value, dat$Value == 0, FUN = function(x) cumsum(c(x[1], diff(x) != 0))))

dat
   Value Group
1      1     1
2      1     1
3      1     1
4      0     1
5      0     1
6      1     1
7      0     1
8      0     1
9      1     1
10     1     1
11     2     2
12     2     2
13     0     2
14     0     2
15     1     3
16     0     3
17     0     3
18     1     3
19     1     3
20     1     3
21     0     3
22     0     3
23     2     4
24     2     4
25     1     5
26     1     5
27     2     6
28     0     6
29     0     6
30     1     7
31     0     7

In response to your comment, if you want the result by grouped by date, you can use a nested ave():

ave(ave(dat$Value, dat$Value == 0, dat$date, FUN = function(x) cumsum(c(x[1], diff(x) != 0))), dat$date, FUN = cummax)


问:
Firebase Crashlytics: Upload missing dSYMs to see crashes from 1 versions.(iOS)
Error Message: Upload missing dSYMs to see crashes from 1 versions.
Versions affected: 1.0 (1)

I am trying to implement Firebase Crashlytics in my iOS project. I did all the setups according to Firebase Crashlytics Doucmentation. The crash is performed manually when the button is clicked just to see whether the crashlytics is working.

```<code>@IBAction func onTestCrashButtonClick(_ sender: UIButton) {

    Crashlytics.sharedInstance().crash()

}
</code>```

But when i tried to see the error report in the firebase console, it shows something like this image.

After reading Get Deobfuscated crash reports I just Set Debug Information Format to DWARF with dSYM File like below but the problem not fixed till now.

答:
Download appDsyms archive from App Store

1.1 Login: https://appstoreconnect.apple.com

1.2 Go to: MyApps -> Choose your app -> Test Flight -> Select app version that is in the App Store -> Build Metadata -> Includes Symbols (right side) -> Press: Download dSYM.

New way - June 2022

New way to upload directly in Firebase Crashlytics.
Go to firebase crashlytics https://console.firebase.google.com
-> Select your project -> Go to crashlytics (left side) -> Upload your dSYM files.

Other way - Upload dSYM files via terminal

Open terminal, drag and drop 3 files on terminal on this order:

1.1 drag an drop: "upload-symbols" which can be found in
/project/Pods/FirebaseCrashlytics/upload-symbols

1.2 write " -gsp "

1.3 drag an drop: "GoogleService-Info.plist" which can be found in /project/GoogleService-Info.plist

1.4 write " -p ios "

1.5 drag an drop: "appDsyms" folder (unarchived, zip file might not work!) which usually is in Download folder /Users/username/Downloads/appDsyms

1.6 Press Enter

In terminal the complete command should include -gsp and -p ios, full command looks like this: 1.1 -gsp 1.3 -p ios 1.5

```<code>/project/Pods/FirebaseCrashlytics/upload-symbols -gsp /project/GoogleService-Info.plist -p ios /Users/username/Downloads/appDsyms
</code>```

All Set, wait for upload in the terminal!

Terminal example:

-

One way how to get a file or folder location with a drag and drop to terminal:

-

AppStore Connect, Download dSYM:

ContentLicense: CC BY-SA 3.0

Body:
Error Message: Upload missing dSYMs to see crashes from 1 versions.
Versions affected: 1.0 (1)

I am trying to implement Firebase Crashlytics in my iOS project. I did all the setups according to Firebase Crashlytics Doucmentation. The crash is performed manually when the button is clicked just to see whether the crashlytics is working.

@IBAction func onTestCrashButtonClick(_ sender: UIButton) {

    Crashlytics.sharedInstance().crash()

}

But when i tried to see the error report in the firebase console, it shows something like this image.

After reading Get Deobfuscated crash reports I just Set Debug Information Format to DWARF with dSYM File like below but the problem not fixed till now.

Body:
Download appDsyms archive from App Store

1.1 Login: https://appstoreconnect.apple.com

1.2 Go to: MyApps -> Choose your app -> Test Flight -> Select app version that is in the App Store -> Build Metadata -> Includes Symbols (right side) -> Press: Download dSYM.

New way - June 2022

New way to upload directly in Firebase Crashlytics.
Go to firebase crashlytics https://console.firebase.google.com
-> Select your project -> Go to crashlytics (left side) -> Upload your dSYM files.

Other way - Upload dSYM files via terminal

Open terminal, drag and drop 3 files on terminal on this order:

1.1 drag an drop: "upload-symbols" which can be found in
/project/Pods/FirebaseCrashlytics/upload-symbols

1.2 write " -gsp "

1.3 drag an drop: "GoogleService-Info.plist" which can be found in /project/GoogleService-Info.plist

1.4 write " -p ios "

1.5 drag an drop: "appDsyms" folder (unarchived, zip file might not work!) which usually is in Download folder /Users/username/Downloads/appDsyms

1.6 Press Enter

In terminal the complete command should include -gsp and -p ios, full command looks like this: 1.1 -gsp 1.3 -p ios 1.5

/project/Pods/FirebaseCrashlytics/upload-symbols -gsp /project/GoogleService-Info.plist -p ios /Users/username/Downloads/appDsyms

All Set, wait for upload in the terminal!

Terminal example:

-

One way how to get a file or folder location with a drag and drop to terminal:

-

AppStore Connect, Download dSYM:


问:
How do I compare with a string in ng-class?
This line doesn't seem to work for me.

```<code>Sort By: <a href="" ng-click="setOrder('title')" ng-class="{active: orderProp == 'title'}">Alphabetical</a>
</code>```

Do I have to escape 'title' in orderProp == 'title' somehow?

in the controller I have

```<code>...
$scope.orderProp = 'title';
$scope.setOrder = function(sortBy){
            $scope.orderProp = sortBy;
}
...
</code>```

Thank you

Update: Using v1.3.0-beta.17

Adding  ng-class="{active:orderProp=='pagetitle'} to

```<code><a href="" ng-click="setOrder('pagetitle')" ng-class="{active:orderProp=='pagetitle'}">Alphabetical</a>
</code>```

throws an error

```<code>"Error: [$parse:syntax] http://errors.angularjs.org/1.3.0-beta.17/$parse/syntax?p0=undefined&p1=not%20a%20primary%20expression&p2=null&p3=%7Bactive%3AorderProp%3D%3D&p4=%7Bactive%3AorderProp%3D%3D
</code>```

Sorry for the way I present the error but I just started angular last week and don't know a better way

Update 2:
error seems to be coming from = == ===. I tried > and no error occured. Is there an alternative syntax to like eq?

Update 3 with solve

I mapped each string to an int pagetile->1 code->2 + data-ng-class="{active:orderPropIdx==1};"
Inside the controller I just do if pagetitle set active:orderPropIdx to 1 and so on

Maybe this is a bug in angular 1.3

答:
This is for people coming to this answer looking for the solution with [ngClass].

```<code><a [ngClass]="{ active: selectedValue === 'foo bar' }"> FooBar </a>
</code>```

This would result in adding class="active" to the anchor element when the variable selectedValue is given the value "foo bar".

Body:
This line doesn't seem to work for me.

Sort By: Alphabetical

Do I have to escape 'title' in orderProp == 'title' somehow?

in the controller I have

...
$scope.orderProp = 'title';
$scope.setOrder = function(sortBy){
            $scope.orderProp = sortBy;
}
...

Thank you

Update: Using v1.3.0-beta.17

Adding  ng-class="{active:orderProp=='pagetitle'} to

Alphabetical

throws an error

"Error: [$parse:syntax] http://errors.angularjs.org/1.3.0-beta.17/$parse/syntax?p0=undefined&p1=not%20a%20primary%20expression&p2=null&p3=%7Bactive%3AorderProp%3D%3D&p4=%7Bactive%3AorderProp%3D%3D

Sorry for the way I present the error but I just started angular last week and don't know a better way

Update 2:
error seems to be coming from = == ===. I tried > and no error occured. Is there an alternative syntax to like eq?

Update 3 with solve

I mapped each string to an int pagetile->1 code->2 + data-ng-class="{active:orderPropIdx==1};"
Inside the controller I just do if pagetitle set active:orderPropIdx to 1 and so on

Maybe this is a bug in angular 1.3

Body:
This is for people coming to this answer looking for the solution with [ngClass].

<a [ngClass]="{ active: selectedValue === 'foo bar' }"> FooBar </a>

This would result in adding class="active" to the anchor element when the variable selectedValue is given the value "foo bar".


问:
How to find specific header in a div when web scraping using Python?
I'm currently trying to scape the headers within a div, shown in the following screenshot:

I am trying to find the text highlighted in light blue from the div class in green, but instead my code (below) print the code boxed in pink.

My code

Any help is appreciated. Thanks.

Edit: The headers do not contain any tags or class.

答:
If what you want is just the club name and & amount for each separate club, then you need to .findAll() the
 tags, rather than requesting the content of a specific box. The
 tags contain the information you want, and .findAll() pulls them out as a list.

Here's a minimal example:

# Import statements

import requests
from bs4 import BeautifulSoup

# Get the page

page = requests.get("https://talksport.com/football/572055/")
soup = BeautifulSoup(page.content)

# Find all the H3 tags and store them in a list

clubs = soup.findAll("h3")

# Print out the text of each heading
# I've picked the list indexes to ignore the irrelevant H3 tags. I could
# also have filtered by the text itself, but for a single page, this works.

for club in clubs[17:-2]:
    print(club.text)
```

Body:
If what you want is just the club name and & amount for each separate club, then you need to .findAll() the <h3> tags, rather than requesting the content of a specific box. The <h3> tags contain the information you want, and .findAll() pulls them out as a list.

Here's a minimal example:

# Import statements

import requests
from bs4 import BeautifulSoup

# Get the page

page = requests.get("https://talksport.com/football/572055/")
soup = BeautifulSoup(page.content)

# Find all the H3 tags and store them in a list

clubs = soup.findAll("h3")

# Print out the text of each heading
# I've picked the list indexes to ignore the irrelevant H3 tags. I could
# also have filtered by the text itself, but for a single page, this works.

for club in clubs[17:-2]:
    print(club.text)


问:
Local Host didnt send any data :ERR_EMPTY_RESPONSE ,either express not working or chrome
Here is my code:

```<code>const express= require('express');

var app=express();

app.get('/',(req,res)=>{
    console.log('Sending data');
    res.send('Hello Express!');
    console.log('Data sent');
});

const port = process.env.port || 8080;

app.listen(port,()=>{
    console.log('Listening to port ',port);
});
</code>```

Operating system is Windows 10
and node version is 10.11.0
and express version is 4.14.0
Code Editor is VS Code

On running the localhost:8080/,the prompt is showing:

Listening to port 8080
Sending data
Data sent
Sending data
Data sent
Sending data
Data sent

and then the page shows:
This page isn’t working
localhost didn’t send any data.
ERR_EMPTY_RESPONSE

I have tried port 3000 and still same error.I have also tried Internet Explorer.
I think either express not sending data or browser is unable to receive.

答:
Probably process.env.PORT is not defined on your machine and its returning undefined then its trying to listen on 8080 which is already occupied.
Please try 4000 or something higher than this it will work.</p>

Body:
Here is my code:

const express= require('express');

var app=express();

app.get('/',(req,res)=>{
    console.log('Sending data');
    res.send('Hello Express!');
    console.log('Data sent');
});

const port = process.env.port || 8080;

app.listen(port,()=>{
    console.log('Listening to port ',port);
});

Operating system is Windows 10
and node version is 10.11.0
and express version is 4.14.0
Code Editor is VS Code

On running the localhost:8080/,the prompt is showing:

Listening to port 8080
Sending data
Data sent
Sending data
Data sent
Sending data
Data sent

and then the page shows:
This page isn’t working
localhost didn’t send any data.
ERR_EMPTY_RESPONSE

I have tried port 3000 and still same error.I have also tried Internet Explorer.
I think either express not sending data or browser is unable to receive.


问:
How can I get unstuck from CondaUpgradeError "A newer version of conda is required."?
I attempted to downgrade my conda version.  With conda at version 4.6.2, I ran conda install conda=4.5.12.  I then went to run other conda commands, but was met with the following error:

```<code>CondaUpgradeError: This environment has previously been operated on by a conda version that's newer
than the conda currently being used. A newer version of conda is required.
  target environment location: /home/selah/anaconda3
  current conda version: 4.5.12
  minimum conda version: 4.6
</code>```

I am now stuck and unable to successfully run any conda commands.  How can I get conda back in working order again?

答:
I really struggled with this issue.
All the solutions here did not work for me. This is what works for me:

Find the /conda-meta/history file in the root. (Multile Locations)

Delete or rename it,

Then conda update conda.

To help local this folder on mac you can use: mdfind kind:folder "conda-meta"

Body:
I attempted to downgrade my conda version.  With conda at version 4.6.2, I ran conda install conda=4.5.12.  I then went to run other conda commands, but was met with the following error:

CondaUpgradeError: This environment has previously been operated on by a conda version that's newer
than the conda currently being used. A newer version of conda is required.
  target environment location: /home/selah/anaconda3
  current conda version: 4.5.12
  minimum conda version: 4.6

I am now stuck and unable to successfully run any conda commands.  How can I get conda back in working order again?


问:
Why is my paragraph popup coming outside my div with the "mousedown" event?
I need to show my paragraph inside my
 when click on the
. This is my code:

const area = document.getElementById("area");
const popup = document.getElementById("popup");

function showPopup(event) {
    let x = event.clientX;
    let y = event.clientY;
    popup.style.left = `${x}px`;
    popup.style.top = `${y}px`;
    popup.style.visibility = "visible";
}

area.addEventListener("mousedown", showPopup);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.area {
    border: 1px solid;
    position: absolute;
    height: 200px;
    width: 200px;
}

.popup {
    visibility: hidden;
    position: absolute;
    display: inline-block;
}</code>```

popup

```

Note that this is inside another main body
 (also with position: absolute).

答:
Try this

```<code> <div id="area">
<div class="area""
        <p class="popup" id="popup">popup</p>
     </div>
  </div>
</code>```

Body:
I need to show my paragraph inside my
 when click on the
. This is my code:

const area = document.getElementById("area");
const popup = document.getElementById("popup");

function showPopup(event) {
    let x = event.clientX;
    let y = event.clientY;
    popup.style.left = `${x}px`;
    popup.style.top = `${y}px`;
    popup.style.visibility = "visible";
}

area.addEventListener("mousedown", showPopup);

.area {
    border: 1px solid;
    position: absolute;
    height: 200px;
    width: 200px;
}

.popup {
    visibility: hidden;
    position: absolute;
    display: inline-block;
}

popup

Note that this is inside another main body
 (also with position: absolute).

Body:
Try this

 <div id="area">
<div class="area""
        <p class="popup" id="popup">popup</p>
     </div>
  </div>


问:
setState always (I want to setState Status as success always if I go to the previous screen or go to the next screen)

constructor(props) {
    super();
    this.state = {
      Status: '',
    };
  }
  Successful = () => {
    console.log('Status' + this.state.Status);
    if (this.state.Status === 'SUCCESS') {
      this.props.navigation.navigate('OScreen');
    }
  };

  render() {
    return (
      <View style={styles.container}>
          <Text style={styles.text}>PAY</Text>
        <TouchableOpacity style={styles.button}
            onPress=this.setState({Status: 'SUCCESS'});>
          <View style={styles.item}>
            <Text style={styles.pay}>Proceed</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
   }```

答:
wrap the onpress with function

```<code>onPress={() => { alert('doing something') } }
</code>```

constructor(props) {
    super();
    this.state = {
      Status: '',
    };
  }

  render() {
    return (
      <View style={styles.container}>
          <Text style={styles.text}>PAY</Text>
        <TouchableOpacity style={styles.button}
            onPress={()=>{
                this.setState({Status: 'SUCCESS'});
                this.props.navigation.navigate('OScreen');
            }}>
          <View style={styles.item}>
            <Text style={styles.pay}>Proceed</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
   }```

Body:
wrap the onpress with function

onPress={() => { alert('doing something') } }

constructor(props) {
    super();
    this.state = {
      Status: '',
    };
  }

  render() {
    return (
      <View style={styles.container}>
          <Text style={styles.text}>PAY</Text>
        <TouchableOpacity style={styles.button}
            onPress={()=>{
                this.setState({Status: 'SUCCESS'});
                this.props.navigation.navigate('OScreen');
            }}>
          <View style={styles.item}>
            <Text style={styles.pay}>Proceed</Text>
          </View>
        </TouchableOpacity>
      </View>
    );
   }


问:
How to work on array of bitmaps without '['
I wrote a program which checks parity of 32-bit integer without bitwise operators. I can't also use ] sign apart from declaration. My program is already good, but I don't know how can I make it work without [ sign. I tried many ways but my program doesn't want to compile. Here is my program:

```<code>#ifndef bit_set
#define bit_set
struct bit{
    unsigned b0 : 1;
    unsigned b1 : 1;
    unsigned b2 : 1;
    unsigned b3 : 1;
    unsigned b4 : 1;
    unsigned b5 : 1;
    unsigned b6 : 1;
    unsigned b7 : 1;
};
union bit_set
{
    unsigned int x;
    struct bit foo[4];
}word;
#endif

</code>```

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"

int main(void) {
    printf("Input number: ");
    if (scanf("%u", &word.x) == 0) {
        printf("Incorrect input");
        return 1;
    }
    int sum = 0;
    for (int i = 0; i < 4; i++) {
        sum += word.foo[i].b0 + word.foo[i].b1 + word.foo[i].b2 + word.foo[i].b3 + word.foo[i].b4 + word.foo[i].b5 + word.foo[i].b6 + word.foo[i].b7;
    }
    sum % 2 ? printf("NO") : printf("YES");
    return 0;
}
</code>```

答:
I can't also use ] sign apart from declaration

That doesn't make any sense. But in that case you can use trigraphs instead:

```<code>word.foo??(i??).b0
</code>```

Or if you prefer digraphs:

```<code>word.foo<:i:>.b0
</code>```

Body:
I wrote a program which checks parity of 32-bit integer without bitwise operators. I can't also use ] sign apart from declaration. My program is already good, but I don't know how can I make it work without [ sign. I tried many ways but my program doesn't want to compile. Here is my program:

#ifndef bit_set
#define bit_set
struct bit{
    unsigned b0 : 1;
    unsigned b1 : 1;
    unsigned b2 : 1;
    unsigned b3 : 1;
    unsigned b4 : 1;
    unsigned b5 : 1;
    unsigned b6 : 1;
    unsigned b7 : 1;
};
union bit_set
{
    unsigned int x;
    struct bit foo[4];
}word;
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "bit_set.h"

int main(void) {
    printf("Input number: ");
    if (scanf("%u", &word.x) == 0) {
        printf("Incorrect input");
        return 1;
    }
    int sum = 0;
    for (int i = 0; i < 4; i++) {
        sum += word.foo[i].b0 + word.foo[i].b1 + word.foo[i].b2 + word.foo[i].b3 + word.foo[i].b4 + word.foo[i].b5 + word.foo[i].b6 + word.foo[i].b7;
    }
    sum % 2 ? printf("NO") : printf("YES");
    return 0;
}

Body:
I can't also use ] sign apart from declaration

That doesn't make any sense. But in that case you can use trigraphs instead:

word.foo??(i??).b0

Or if you prefer digraphs:

word.foo<:i:>.b0


问:
Angular 9 with RxJs - combining 2 observables results in data but async pipe always sees a null result
I have 2 observables that return data from Firebase, and no matter what type of combination operator I use (forkJoin, CombineLatest etc) the async pipe does not receive the data.

I have an AuthService, with a method that initialises the user from a Firebase realtime database:

```<code>  private initUser(firebaseUser: firebase.User) {
    const myUser: User = {account: {}, profile: {}};
    const userId = `US_${firebaseUser.uid}`;

    const accountSnapshot: Observable<UserAccount> = this.db
      .object(`/users/accounts/${userId}`)
      .valueChanges()
      .pipe(first()) as Observable<UserAccount>;

    const profileSnapshot: Observable<UserProfile> = this.db
      .object(`/users/profiles/${userId}`)
      .valueChanges()
      .pipe(first()) as Observable<UserProfile>;

    forkJoin([accountSnapshot, profileSnapshot])
      .subscribe((result: [UserAccount, UserProfile]) => {
        if (result) {
          myUser.account = result[0];
          myUser.profile = result[1];
          this.setCurrentUser(myUser);
        }
      });
  }
</code>```

CurrentUser is set up as a subject with getter/setter:

```<code>  private currentUser = new Subject<User>();

  public get getCurrentUser(): Observable<User> {
    return this.currentUser.asObservable();
  }

  public setCurrentUser(user: User): void {
    this.currentUser.next(user);
  }
</code>```

In the consuming component:

```<code>  currentUser$: Observable<User>;
  user: User;

  ngOnInit(): void {
    this.currentUser$ = this.authService.getCurrentUser;
    this.currentUser$.subscribe(user => {
      this.user = user;
    });
  }
</code>```

and in the template:

```<code><p>Email: {{ ((currentUser$ | async)?.account).email }}</p>. <- ** DOES NOT WORK **
<p>Email: {{ (user?.account).email }}</p> <- ** DOES WORK **
</code>```

Now, here is the strange part. If I change the initUser method to NOT combine the observables from firebase, but to get them separately (and set the users profile and account as separate operations), then async works. Like this:

```<code>accountSnapshot.subscribe((account: UserAccount) => {
  if (account) {
    myUser.account = account;
    this.setCurrentUser(myUser);
  }
});
profileSnapshot.subscribe((profile: UserProfile) => {
  if (profile) {
    myUser.profile = profile;
    this.setCurrentUser(myUser);
  }
});
</code>```

then the async pipe works.

I have tried changing the forkJoin to CombineLatest and zip. I've also tried removing the pipe(first()) but the async pipe never works.

Why is this?

Is there something wrong with async or with my code, or maybe my understanding of how async works...?

答:
It is not working because you have already susbcribed to that forkjoin :-

Change it to :-

```<code>this.currentUser$ = forkJoin([accountSnapshot, profileSnapshot])
      .pipe(map((result: [UserAccount, UserProfile]) => {
        if (result) {
          myUser.account = result[0];
          myUser.profile = result[1];
          this.setCurrentUser(myUser);
        }
      }));
</code>```

then use this currentUser$ with asyncpipe in your template.

Body:
I have 2 observables that return data from Firebase, and no matter what type of combination operator I use (forkJoin, CombineLatest etc) the async pipe does not receive the data.

I have an AuthService, with a method that initialises the user from a Firebase realtime database:

  private initUser(firebaseUser: firebase.User) {
    const myUser: User = {account: {}, profile: {}};
    const userId = `US_${firebaseUser.uid}`;

    const accountSnapshot: Observable<UserAccount> = this.db
      .object(`/users/accounts/${userId}`)
      .valueChanges()
      .pipe(first()) as Observable<UserAccount>;

    const profileSnapshot: Observable<UserProfile> = this.db
      .object(`/users/profiles/${userId}`)
      .valueChanges()
      .pipe(first()) as Observable<UserProfile>;

    forkJoin([accountSnapshot, profileSnapshot])
      .subscribe((result: [UserAccount, UserProfile]) => {
        if (result) {
          myUser.account = result[0];
          myUser.profile = result[1];
          this.setCurrentUser(myUser);
        }
      });
  }

CurrentUser is set up as a subject with getter/setter:

  private currentUser = new Subject<User>();

  public get getCurrentUser(): Observable<User> {
    return this.currentUser.asObservable();
  }

  public setCurrentUser(user: User): void {
    this.currentUser.next(user);
  }

In the consuming component:

  currentUser$: Observable<User>;
  user: User;

  ngOnInit(): void {
    this.currentUser$ = this.authService.getCurrentUser;
    this.currentUser$.subscribe(user => {
      this.user = user;
    });
  }

and in the template:

Email: {{ ((currentUser$ | async)?.account).email }}
. <- ** DOES NOT WORK **

Email: {{ (user?.account).email }}
 <- ** DOES WORK **

Now, here is the strange part. If I change the initUser method to NOT combine the observables from firebase, but to get them separately (and set the users profile and account as separate operations), then async works. Like this:

accountSnapshot.subscribe((account: UserAccount) => {
  if (account) {
    myUser.account = account;
    this.setCurrentUser(myUser);
  }
});
profileSnapshot.subscribe((profile: UserProfile) => {
  if (profile) {
    myUser.profile = profile;
    this.setCurrentUser(myUser);
  }
});

then the async pipe works.

I have tried changing the forkJoin to CombineLatest and zip. I've also tried removing the pipe(first()) but the async pipe never works.

Why is this?

Is there something wrong with async or with my code, or maybe my understanding of how async works...?

Body:
It is not working because you have already susbcribed to that forkjoin :-

Change it to :-

this.currentUser$ = forkJoin([accountSnapshot, profileSnapshot])
      .pipe(map((result: [UserAccount, UserProfile]) => {
        if (result) {
          myUser.account = result[0];
          myUser.profile = result[1];
          this.setCurrentUser(myUser);
        }
      }));

then use this currentUser$ with asyncpipe in your template.


问:
How to create a HMAC-SHA1 hash in Nestjs
I am consuming an API in my nestjs app. I am required to supply hash as part of the payload.

In the API documentation, I am supposed to do this

Create a hash using the hash_hmac function as such

```<code>computed_hash = hash_hmac("sha1", somecombinedstring, privatekey)
</code>```

So I used cryptojs in nodejs

```<code>var hash = crypto.createHmac('sha1', combinestring, privatekey);

</code>```

When I pass hash to the endpoint, I got Invalid Hash

How can I create a valid hash

Thanks

答:
I got it to work with this</p>

```<code>  const hash = crypto.createHmac('sha1', privatekey)
            .update(somestringcombined)
            .digest('hex');
</code>```

Body:
I am consuming an API in my nestjs app. I am required to supply hash as part of the payload.

In the API documentation, I am supposed to do this

Create a hash using the hash_hmac function as such

computed_hash = hash_hmac("sha1", somecombinedstring, privatekey)

So I used cryptojs in nodejs

var hash = crypto.createHmac('sha1', combinestring, privatekey);

When I pass hash to the endpoint, I got Invalid Hash

How can I create a valid hash

Thanks

Body:
I got it to work with this

  const hash = crypto.createHmac('sha1', privatekey)
            .update(somestringcombined)
            .digest('hex');


问:
Lookup Acct. Balance on specified day in Google Sheets
Sounded so simple! I have a sheet called "Account", containing a running balance in column "G" and I have another sheet called "Performance", with a table which lists historical dates and column "D" needs to lookup the account balance on the day stated in column "A".

"Account" Sheet

"Performance" Sheet

For example, Performance!D2 should be "210,000.00".

Performance!D7 should be "110,000.00".

Performance!D9 would be "40,000.00".

To make this slightly more difficult I like to put formulas into the heading row as arrayformulas where possible, to avoid problems when copying and pasting data or adding new rows, etc.

I've tried many different possibilities and nothing has worked. I'm currently trying to make the following formula work, which is in Performance!D1.

```<code>=ARRAYFORMULA(if(row(D1:D) = 1, "Cash", VLOOKUP(A1:A, MIN('Balance'!A4:A <= A1:A), 7, 1)))
</code>```

I've also tried some solutions involving MATCH(), FILTER(), VLOOKUP() and LOOKUP() but so far no cookie!

答:
this should work:

```<code>=ARRAYFORMULA({"Cash";if(A2:A="",,VLOOKUP(A2:A, SORT('Account'!A4:G),7,TRUE))})
</code>```

VLOOKUP(...,true) returns the value associated with the closest match in the first column without going over. Provided that the range into which you're doing the vlookup is sorted by the first column of that range.

Body:
Sounded so simple! I have a sheet called "Account", containing a running balance in column "G" and I have another sheet called "Performance", with a table which lists historical dates and column "D" needs to lookup the account balance on the day stated in column "A".

"Account" Sheet

"Performance" Sheet

For example, Performance!D2 should be "210,000.00".

Performance!D7 should be "110,000.00".

Performance!D9 would be "40,000.00".

To make this slightly more difficult I like to put formulas into the heading row as arrayformulas where possible, to avoid problems when copying and pasting data or adding new rows, etc.

I've tried many different possibilities and nothing has worked. I'm currently trying to make the following formula work, which is in Performance!D1.

=ARRAYFORMULA(if(row(D1:D) = 1, "Cash", VLOOKUP(A1:A, MIN('Balance'!A4:A <= A1:A), 7, 1)))

I've also tried some solutions involving MATCH(), FILTER(), VLOOKUP() and LOOKUP() but so far no cookie!

Body:
this should work:

=ARRAYFORMULA({"Cash";if(A2:A="",,VLOOKUP(A2:A, SORT('Account'!A4:G),7,TRUE))})

VLOOKUP(...,true) returns the value associated with the closest match in the first column without going over. Provided that the range into which you're doing the vlookup is sorted by the first column of that range.


问:
Build Simple User Interface using Android Studio
I have downloaded and installed Android Studio 4.0 on my Mac running macOS Mojave 10.14.5 Everything seems to be working fine except when I try to build a simple User Interface using the Android Studio Layout Editor. When I try to drag and drop a View from the palette into the Layout Editor, it doesn't stay there. Has anyone experienced this problem, and if so how did you resolve it?</p>

答: By default it creates ConstraintLayout and you should add bounds to the view. You can find all required documentation here https://developer.android.com/</p>


问:
uWSGI: How can I mount a paste-deploy (Pyramid) app?

What I have:

I have a Pyramid application that is built from a Paste ini, served by uWSGI and proxied by nginx. It works great. Here is the nginx config:

```<code>server {
    listen 80;
    server_name localhost;
    access_log /var/log/myapp/nginx.access.log;
    error_log /var/log/myapp/nginx.error.log warn;

    location / {
        uwsgi_pass localhost:8080;
        include uwsgi_params;
    }
}
</code>```

Here is the uWSGI ini configuration:

```<code>[uwsgi]
socket = 127.0.0.1:8080
virtualenv = /srv/myapp/venv
die-on-term = 1
master = 1
logto = /var/log/myapp/uwsgi.log
</code>```

This configuration is located inside Pyramid's production.ini, such that I serve the application with this command:

```<code>uwsgi --ini-paste-logged production.ini
</code>```

All of this works just fine.

What I want to do:

One simple change. I want to serve this application as a subfolder, rather than as the root. Rather than serving it from http://localhost, I want to serve it from http://localhost/myapp.

And now everything is broken.

If I change the nginx location directive from / to /myapp or /myapp/, I get 404s, because the WSGI application receives uris that are all prepended with /myapp.

The uWSGI solution appears to be to mount the WSGI callable on the subfolder, and then pass the --manage-script-name option, at which point uWSGI should magically strip the subfolder prefix from the uri and fix the issue.

However, the documentation and every other resource I've found have only given examples of the form:

```<code>mount = /myapp=myapp.py
</code>```

I don't have a myapp.py that contains a WSGI callable, because my callable is being built by PasteDeploy.

So, is it possible to mount the WSGI callable from within the Paste ini? Or am I going to have to split the uwsgi configuration out of the Paste ini and also define a separate wsgi.py with a call to paste.deploy.loadapp to generate a wsgi callable that I can mount?

Or is there another way to serve this app as a subfolder from nginx while not messing up the url reversing?

答:
I've hit this very problem with my deployment after switching from Python2 to Python3.

with Python2 I used the uwsgi_modifier1 30; trick, but it doesn't work anymore with Python3, as described here: https://github.com/unbit/uwsgi/issues/876

It is very badly documented (not at all? I know it from reading the uWSGI source code), but --mount option accepts the following syntax:

```<code>--mount=/app=config:/path/to/app.ini
</code>```

Please note: with --mount you also need --manage-script-name option.

There are other problems with it: https://github.com/unbit/uwsgi/issues/2172

It's trivial to write a wrapper script around Paste-Deploy app, which is the way I deploy now:

from paste.script.util.logging_config import fileConfig as configure_logging
from paste.deploy import loadapp as load_app
from os import environ

config_file = environ['INI_FILE']

configure_logging(config_file)
application = load_app('config:' + config_file)
```

Save it to e.g. app.py and you can use it with --mount /app=app.py, the INI_FILE environment var should point to your .ini file.

As a side note - I consider moving away from uWSGI, it's buggy and documentation lacks a lot.

Body:
What I have:

I have a Pyramid application that is built from a Paste ini, served by uWSGI and proxied by nginx. It works great. Here is the nginx config:

server {
    listen 80;
    server_name localhost;
    access_log /var/log/myapp/nginx.access.log;
    error_log /var/log/myapp/nginx.error.log warn;

    location / {
        uwsgi_pass localhost:8080;
        include uwsgi_params;
    }
}

Here is the uWSGI ini configuration:

[uwsgi]
socket = 127.0.0.1:8080
virtualenv = /srv/myapp/venv
die-on-term = 1
master = 1
logto = /var/log/myapp/uwsgi.log

This configuration is located inside Pyramid's production.ini, such that I serve the application with this command:

uwsgi --ini-paste-logged production.ini

All of this works just fine.

What I want to do:

One simple change. I want to serve this application as a subfolder, rather than as the root. Rather than serving it from http://localhost, I want to serve it from http://localhost/myapp.

And now everything is broken.

If I change the nginx location directive from / to /myapp or /myapp/, I get 404s, because the WSGI application receives uris that are all prepended with /myapp.

The uWSGI solution appears to be to mount the WSGI callable on the subfolder, and then pass the --manage-script-name option, at which point uWSGI should magically strip the subfolder prefix from the uri and fix the issue.

However, the documentation and every other resource I've found have only given examples of the form:

mount = /myapp=myapp.py

I don't have a myapp.py that contains a WSGI callable, because my callable is being built by PasteDeploy.

So, is it possible to mount the WSGI callable from within the Paste ini? Or am I going to have to split the uwsgi configuration out of the Paste ini and also define a separate wsgi.py with a call to paste.deploy.loadapp to generate a wsgi callable that I can mount?

Or is there another way to serve this app as a subfolder from nginx while not messing up the url reversing?

Body:
I've hit this very problem with my deployment after switching from Python2 to Python3.

with Python2 I used the uwsgi_modifier1 30; trick, but it doesn't work anymore with Python3, as described here: https://github.com/unbit/uwsgi/issues/876

It is very badly documented (not at all? I know it from reading the uWSGI source code), but --mount option accepts the following syntax:

--mount=/app=config:/path/to/app.ini

Please note: with --mount you also need --manage-script-name option.

There are other problems with it: https://github.com/unbit/uwsgi/issues/2172

It's trivial to write a wrapper script around Paste-Deploy app, which is the way I deploy now:

from paste.script.util.logging_config import fileConfig as configure_logging
from paste.deploy import loadapp as load_app
from os import environ

config_file = environ['INI_FILE']

configure_logging(config_file)
application = load_app('config:' + config_file)

Save it to e.g. app.py and you can use it with --mount /app=app.py, the INI_FILE environment var should point to your .ini file.

As a side note - I consider moving away from uWSGI, it's buggy and documentation lacks a lot.


问:
Create all subsets from string- recursively
I am trying to create all subset of a given string recursively.
Given string = 'aab', we generate all subsets for the characters being distinct.
The answer is: ["", "b", "a", "ab", "ba", "a", "ab", "ba", "aa", "aa", "aab", "aab", "aba", "aba", "baa", "baa"].
I have been looking at several solutions  such as this one
but I am trying to make the function accept a single variable- only the string and work with that, and can't figure out how.
I have been also looking at this solution of a similar problem, but as it deals with lists and not strings I seem to have some trouble transforming that to accept and generate strings.
Here is my code, in this example I can't connect the str to the list. Hence my question.
I edited the input and the output.

```<code>def gen_all_strings(word):

    if len(word) == 0:
        return ''

    rest = gen_all_strings(word[1:])

    return  rest + [[ + word[0]] + dummy for dummy in rest]
</code>```

答:
This is the powerset of the set of characters in the string.</p>

```<code>from itertools import chain, combinations

s = set('ab') #split string into a set of characters

# combinations gives the elements of the  powerset of a given length r
# from_iterable puts all these into an 'iterable'
# which is converted here to a list

list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1)))
</code>```

Body:
I am trying to create all subset of a given string recursively.
Given string = 'aab', we generate all subsets for the characters being distinct.
The answer is: ["", "b", "a", "ab", "ba", "a", "ab", "ba", "aa", "aa", "aab", "aab", "aba", "aba", "baa", "baa"].
I have been looking at several solutions  such as this one
but I am trying to make the function accept a single variable- only the string and work with that, and can't figure out how.
I have been also looking at this solution of a similar problem, but as it deals with lists and not strings I seem to have some trouble transforming that to accept and generate strings.
Here is my code, in this example I can't connect the str to the list. Hence my question.
I edited the input and the output.

def gen_all_strings(word):

    if len(word) == 0:
        return ''

    rest = gen_all_strings(word[1:])

    return  rest + [[ + word[0]] + dummy for dummy in rest]

Body:
This is the powerset of the set of characters in the string.

from itertools import chain, combinations

s = set('ab') #split string into a set of characters

# combinations gives the elements of the  powerset of a given length r
# from_iterable puts all these into an 'iterable'
# which is converted here to a list

list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1)))


问:
x.ToString() is not supported by the entity framework!
Entity framework doesn't recognize my ToString method that converts the route object to specifix string:

```<code>public IEnumerable<Route> GetRoutes(string prefix, string searchPattern, string code)
{
    return Routes.
        Where(x => code == null || x.Code == code).
        Where(x => searchPattern == null || x.ToString().Contains(searchPattern)).
        Where(x => prefix == null || x.ToString().StartsWith(prefix));
}
</code>```

Here is my Route entity:

```<code> public class Route : IDataEntity, ISoftDeletable
    {
        public virtual long Id { get; set; }
        public virtual string Code { get; set; }
        public virtual bool IsDeleted { get; set; }
        public virtual Guid CompanyId { get; set; }
        public virtual IList<LocationInRoute> Locations { get; set; }

        public override string ToString()
        {
            StringBuilder str = new StringBuilder();
            foreach (LocationInRoute loc in Locations)
            {
                if (str.Length > 0)
                {
                    str.Append(" > ");
                }
                str.Append(loc.ToString());
            }
            return str.ToString();
        }
    }
</code>```

All the x.ToString() throws an exception of not supported in linq to entities..
Any workaround?

答:
I think you have to have a preperty called ID or Name which you want to compare with the searchPattern and then use:

```<code> .Where(x => searchPattern == null || x.Name.Contains(searchPattern));
</code>```

Because I'm asuuming that x demonstrate an entity, so, how do you want to compare the entiy's name itself with a search patternn ?

Edit:

After seeing the changes in the question, it's still unable to use ToString() method in this query because it's not able to convert to a SQL Statement.

Now, you have two options:

The first one: (I'm not sure if applicable depend on the suspected data size), try to load all the records from the database using ToList() extension before calling Where extension.
This should work well but it might cause a problem with huge tables.

The second one: You have to create a stored procedure and move the logic to the database.

Body:
Entity framework doesn't recognize my ToString method that converts the route object to specifix string:

public IEnumerable<Route> GetRoutes(string prefix, string searchPattern, string code)
{
    return Routes.
        Where(x => code == null || x.Code == code).
        Where(x => searchPattern == null || x.ToString().Contains(searchPattern)).
        Where(x => prefix == null || x.ToString().StartsWith(prefix));
}

Here is my Route entity:

 public class Route : IDataEntity, ISoftDeletable
    {
        public virtual long Id { get; set; }
        public virtual string Code { get; set; }
        public virtual bool IsDeleted { get; set; }
        public virtual Guid CompanyId { get; set; }
        public virtual IList<LocationInRoute> Locations { get; set; }

        public override string ToString()
        {
            StringBuilder str = new StringBuilder();
            foreach (LocationInRoute loc in Locations)
            {
                if (str.Length > 0)
                {
                    str.Append(" > ");
                }
                str.Append(loc.ToString());
            }
            return str.ToString();
        }
    }

All the x.ToString() throws an exception of not supported in linq to entities..
Any workaround?

Body:
I think you have to have a preperty called ID or Name which you want to compare with the searchPattern and then use:

 .Where(x => searchPattern == null || x.Name.Contains(searchPattern));

Because I'm asuuming that x demonstrate an entity, so, how do you want to compare the entiy's name itself with a search patternn ?

Edit:

After seeing the changes in the question, it's still unable to use ToString() method in this query because it's not able to convert to a SQL Statement.

Now, you have two options:

The first one: (I'm not sure if applicable depend on the suspected data size), try to load all the records from the database using ToList() extension before calling Where extension.
This should work well but it might cause a problem with huge tables.

The second one: You have to create a stored procedure and move the logic to the database.


问:
How to keep object of subclass in another class in cpp? Base class undefined error
I'm coding simple shop program in cpp. I have 3 classes: Shop, Client, Bucket. Shop is parent class for Bucket. Shop has vector of clients and every client has his own bucket.
I've got problem with #include's. I have to include Client.h in Shop.h so the Shop could see the vector of clients, but it seems I also have to include Bucket.h in Clinet.h for similar reason.
This generates a problem: Bucket is being included before Shop so I get 'Base Class Undefined' error.
How can I make this work?

Shop.h

```<code>#pragma once
#include <vector>
#include <string>
#include "functions.h"
#include "Client.h"

class Shop {

protected:
    std::vector<int> quantities;
    std::vector<std::string> products;
    std::vector<float> prices;
private:
    std::vector<Client*> clients;
    int loggedClient;
public:
    Shop();
    ~Shop();
    int readProducts();
    int loadClientsBase();
    int checkLoginData(std::string log, std::string pass, int *logged);
    int checkIfSameLogin(std::string log);
    int addClient();
    void login();
    void logout();
    int sell();
    virtual void display();
    void displayLoggedClient();
    int saveHistory();
};

</code>```

Client.h

```<code>#pragma once
#include "Bucket.h"

class Client
{
private:
    float money=0.0;
    Bucket bucket;
    std::string login;
    std::string password;
    std::string description;
public:
    Client();
    ~Client();
    void addLoginData(std::string log, std::string pass, std::string desc, float mon);
    std::string getLogin() { return login; };
    std::string getPassword() { return password; };
    std::string getDescription() { return description; };
    float getMoney() { return money; };
    void addLogin(std::string log);
    void addPassword(std::string pass);
    void addDescription(std::string desc);
    void addMoney(float m);
    void addToBucket(std::string prod, int quant, float price);
    void displayBucket();
    Bucket getBucket() { return bucket; };

    friend std::ostream& operator<<(std::ostream& os, Client& client);
};
</code>```

Bucket.h

```<code>#pragma once
#include <vector>
#include <string>
#include "Shop.h"

class Bucket : public Shop
{
public:
    Bucket();
    ~Bucket();
    void addProduct(std::string name, int amount, float price);
    void deleteProduct();
    void display();
    std::string getProduct(int i);
    int getQuantity(int i);
    float getPrice(int i);
    int getNumberOfProducts() { return products.size(); };
    void clearBucket();
};
</code>```

答:
Bucket.h includes Shop.h which includes Client.h which includes Bucket.h... And so on forever and ever. This is a circular dependency.

Shop.h doesn't need to include Client.h, it only needs to forward declare the Client class:

```<code>#pragma once
#include <vector>
#include <string>
#include "functions.h"
// #include "Client.h"

class Client;  // Forward declaration of the class, that's needed for pointers to it

class Shop {
    ...
};
</code>```

The implementation of Shop needs the full definition of Client, so the Shop source file (Shop.cpp?) needs to include Client.h.

Body:
I'm coding simple shop program in cpp. I have 3 classes: Shop, Client, Bucket. Shop is parent class for Bucket. Shop has vector of clients and every client has his own bucket.
I've got problem with #include's. I have to include Client.h in Shop.h so the Shop could see the vector of clients, but it seems I also have to include Bucket.h in Clinet.h for similar reason.
This generates a problem: Bucket is being included before Shop so I get 'Base Class Undefined' error.
How can I make this work?

Shop.h

#pragma once
#include <vector>
#include <string>
#include "functions.h"
#include "Client.h"

class Shop {

protected:
    std::vector<int> quantities;
    std::vector<std::string> products;
    std::vector<float> prices;
private:
    std::vector<Client*> clients;
    int loggedClient;
public:
    Shop();
    ~Shop();
    int readProducts();
    int loadClientsBase();
    int checkLoginData(std::string log, std::string pass, int *logged);
    int checkIfSameLogin(std::string log);
    int addClient();
    void login();
    void logout();
    int sell();
    virtual void display();
    void displayLoggedClient();
    int saveHistory();
};

Client.h

#pragma once
#include "Bucket.h"

class Client
{
private:
    float money=0.0;
    Bucket bucket;
    std::string login;
    std::string password;
    std::string description;
public:
    Client();
    ~Client();
    void addLoginData(std::string log, std::string pass, std::string desc, float mon);
    std::string getLogin() { return login; };
    std::string getPassword() { return password; };
    std::string getDescription() { return description; };
    float getMoney() { return money; };
    void addLogin(std::string log);
    void addPassword(std::string pass);
    void addDescription(std::string desc);
    void addMoney(float m);
    void addToBucket(std::string prod, int quant, float price);
    void displayBucket();
    Bucket getBucket() { return bucket; };

    friend std::ostream& operator<<(std::ostream& os, Client& client);
};

Bucket.h

#pragma once
#include <vector>
#include <string>
#include "Shop.h"

class Bucket : public Shop
{
public:
    Bucket();
    ~Bucket();
    void addProduct(std::string name, int amount, float price);
    void deleteProduct();
    void display();
    std::string getProduct(int i);
    int getQuantity(int i);
    float getPrice(int i);
    int getNumberOfProducts() { return products.size(); };
    void clearBucket();
};

Body:
Bucket.h includes Shop.h which includes Client.h which includes Bucket.h... And so on forever and ever. This is a circular dependency.

Shop.h doesn't need to include Client.h, it only needs to forward declare the Client class:

#pragma once
#include <vector>
#include <string>
#include "functions.h"
// #include "Client.h"

class Client;  // Forward declaration of the class, that's needed for pointers to it

class Shop {
    ...
};

The implementation of Shop needs the full definition of Client, so the Shop source file (Shop.cpp?) needs to include Client.h.


问:
Can you modify a Twilio call in-progress while it's still ringing?
I'm trying to simulate a typical phone behaviour, where a call comes in and "rings" until someone picks it up, however I'd like to problematically control this pickup action.

Initially, when the call comes in, I throw the following TwiML at the call:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Pause length="300"/>
    <Reject reason="busy"/>
</Response>
</code>```

This delays answering the call by up to 5 minutes while the app waits for user input. The caller hears ringing during this time. If there's no input within 5 minutes, the app will disconnect the call as busy. Once the user or program has decided what to do with the call, I'd like to be able to send a new TwiML instructions.

However, when I use the method described here to modify the call, I am given an error by Twilio that the call can't be modified as it's not in-progress.

Is there any way to send new instructions towards the call at this point to have it answered and redirected during the Pause?

答:
You cannot modify the call until you answer it (in-progress), as the error message suggests. You must wait for the <Pause length="300"/> to complete, as it is the first verb in the returned TwiML and the call will remained unanswered until it completes and a TwiML Verb which answers the call is reached.

TwiML™ Voice: Pause

Body:
I'm trying to simulate a typical phone behaviour, where a call comes in and "rings" until someone picks it up, however I'd like to problematically control this pickup action.

Initially, when the call comes in, I throw the following TwiML at the call:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Pause length="300"/>
    <Reject reason="busy"/>
</Response>

This delays answering the call by up to 5 minutes while the app waits for user input. The caller hears ringing during this time. If there's no input within 5 minutes, the app will disconnect the call as busy. Once the user or program has decided what to do with the call, I'd like to be able to send a new TwiML instructions.

However, when I use the method described here to modify the call, I am given an error by Twilio that the call can't be modified as it's not in-progress.

Is there any way to send new instructions towards the call at this point to have it answered and redirected during the Pause?


问:
Where can I find firebase-debug.log to understand why emulators did not cleanly shut down?
I am using firebase emulators:start to start firebase emulators. When shutting it down, through Ctrl+C, it tells me it didn't shut down correctly and that I need to consult firebase-debug.log which is nowhere to be found. I suspect it should be in functions/ folder where everything else related to cloud functions live, but it's not there.

```<code>i  emulators: Shutting down emulators.
i  hub: Stopping emulator hub
i  ui: Stopping Emulator UI
⚠  Emulator UI has exited upon receiving signal: SIGINT
i  logging: Stopping Logging Emulator
i  functions: Stopping Functions Emulator
i  firestore: Stopping Firestore Emulator
i  database: Stopping Database Emulator
⚠  emulators: emulators failed to shut down cleanly, see firebase-debug.log for details.
</code>```

The problem is there is no firebase-debug.log to be found. Where can I find this debug file? See below contents of functions folder:

答:
firebase-debug.log is created in the root directory, one level up from the functions directory, beside the firebase.json file.

You can also launch the firebase with --debug flag firebase --debug emulators:start, in this case all debug messages will be printed into the console output.

Body:
I am using firebase emulators:start to start firebase emulators. When shutting it down, through Ctrl+C, it tells me it didn't shut down correctly and that I need to consult firebase-debug.log which is nowhere to be found. I suspect it should be in functions/ folder where everything else related to cloud functions live, but it's not there.

i  emulators: Shutting down emulators.
i  hub: Stopping emulator hub
i  ui: Stopping Emulator UI
⚠  Emulator UI has exited upon receiving signal: SIGINT
i  logging: Stopping Logging Emulator
i  functions: Stopping Functions Emulator
i  firestore: Stopping Firestore Emulator
i  database: Stopping Database Emulator
⚠  emulators: emulators failed to shut down cleanly, see firebase-debug.log for details.

The problem is there is no firebase-debug.log to be found. Where can I find this debug file? See below contents of functions folder:


问:
How to list opened sql server connections and close the specific one
We have a remote SQL server and c# ERP client programs that use it. Sometimes people are opening the program and forget to close it. In that situation, their SQL connections are staying opened and I won't be able to do some operations.

Yes, I can do this from the client side by setting a timer and keep checking if they do any operations or they are AFK but, I want the power to close the connections without the client side's volition.

To sum up,
1- Is there any way to check the open all connections to the server and list them by a SQL query or command.
2- Force to close the specific connection I want even they are sleeping or not?

Any help would be appreciated. Thank you so much.

答: Check out the table sys.dm_exec_sessions and the KILL statement


问:
confluence wiki API detele attachment
I want to delete one page's attachments with Python by Confluence API but it doesn't provide such API. Is there any method？
enter image description here</p>

答:
The Confluence API does provide a possibility to get the page attachment list (or a single one by its file name) and delete all one by one. To do so try something like this (converting JavaScript to Python first):

var headers = {
  'Authorization': 'Basic <base64 encoded username:password>',
  'X-Atlassian-Token': 'nocheck'
};

// this might differ depending on the server configuration:
var apiRoot = 'https://confluence.host.net/rest/api';

// page id:
var containerId = '171607042'

// get all attachments:
var getAttachmentsUrl = `${apiRoot}/content/${containerId}/child/attachment`;

// get only the one attachment:
var fileName = 'some.file';
getAttachmentsUrl += `?fileName=${encodeURIComponent(fileName)}`;

fetch(getAttachmentsUrl, {headers})
  .then(r => r.json())
  .then(o => Promise.all(o.results.map(
    i=>fetch(i._links.self, {method: "DELETE", headers})
  )))
  .then(r => console.log('r', r));
```

Title: confluence wiki API detele attachment


问:
Traversing List in C
I'm trying to implement a linked list traversal, however my code is not working and I don't udnerstand why I've reassigned my pointer but it doesn't stick?

```<code>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void inserter(Node *n1, int num){
    if(n1==NULL){
    Node *temp =(Node*)malloc(sizeof(Node));
    temp->data=num;
    temp->next=NULL;
    n1=temp;
    }
    else{
        Node *trav=n1;
        while(trav!=NULL){
            trav=trav->next;
        }
    }

}

int main(int argc, char **argv)
{

    Node *l1 = NULL;
    inserter(l1,l2,5);
    inserter(l1,l2,11);
    //It goes back into the NULL bracket despite me assigning it a node?

}

</code>```

Here is the accompanying struct

```<code>typedef anode {
    struct Node *next;
    int data;
}Node;
</code>```

Thank you for any help!I'm still new to all of this.

答:
You're passing inserter() a pointer and an int. If you modify that int, no modifications would be visible from the calling function (I think you know that already). Same goes for the pointer: Node * is just a numeric type that holds an address, which has been passed by value.

If you want to modify where n1 points to, you'd need to dereference it. But because you don't want to change the contents of the memory that n1 points to, but change the value of n1 itself, your function would need to be passed a Node **.

Here's a quick example:

```<code>void inserter(Node **n, int num) {
    if (*n == NULL) {
        *n = malloc(...);
        ....;
    }
    ....
}
</code>```

That way you would change the actual value of n globally instead of just locally.

Title: Traversing List in C

Body:
I'm trying to implement a linked list traversal, however my code is not working and I don't udnerstand why I've reassigned my pointer but it doesn't stick?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void inserter(Node *n1, int num){
    if(n1==NULL){
    Node *temp =(Node*)malloc(sizeof(Node));
    temp->data=num;
    temp->next=NULL;
    n1=temp;
    }
    else{
        Node *trav=n1;
        while(trav!=NULL){
            trav=trav->next;
        }
    }

}

int main(int argc, char **argv)
{

    Node *l1 = NULL;
    inserter(l1,l2,5);
    inserter(l1,l2,11);
    //It goes back into the NULL bracket despite me assigning it a node?

}

Here is the accompanying struct

typedef anode {
    struct Node *next;
    int data;
}Node;

Thank you for any help!I'm still new to all of this.

Body:
You're passing inserter() a pointer and an int. If you modify that int, no modifications would be visible from the calling function (I think you know that already). Same goes for the pointer: Node * is just a numeric type that holds an address, which has been passed by value.

If you want to modify where n1 points to, you'd need to dereference it. But because you don't want to change the contents of the memory that n1 points to, but change the value of n1 itself, your function would need to be passed a Node **.

Here's a quick example:

void inserter(Node **n, int num) {
    if (*n == NULL) {
        *n = malloc(...);
        ....;
    }
    ....
}

That way you would change the actual value of n globally instead of just locally.


问:
Automatically convert date text to correct date format using Google Sheets
I'm trying to convert date from "text" to correct format. It is logged to Google Spreadsheets and I'm unable to use it to plot graphs.

This is the text format: February 3, 2018, at 11:21 AM

Time is not relevant, all I need is the date converted: DD/MM/YYYY.

I found a similar question where Gary's Student answered with a formula that looks like this for a different format:

```<code>=DATEVALUE(SUBSTITUTE(A1,MID(A1,FIND(" ",A1)-2,2),""))
</code>```

(link to that question)

How can I use above formula (or something similar) so that text is converted to date?

Thanks in advance.

答:
Another solution is to create custom function.

Open tools → script editor in menu to open script editor in new tab

Click Untitled project in top left corner and rename

Open Resources → Libraries in top menu

Paste library key MHMchiX6c1bwSqGM1PZiW_PxhMjh3Sh48 and click Add to add the Moment library to your script

Choose Moment version 9 and click Save

Paste function

function parseDate(dateString, format){
  return Moment.moment(dateString, format).toDate()
}
```

<p>to <code>Code.gs</code> and save project <code>Ctrl+S</code></p>

<p>Now you use your function in any cell in your sheet:</p>

```=parseDate(B2,"MMM D, YYYY, at HH:mm A")
```

<p>more details about format:
https://momentjs.com/docs/#/parsing/string-formats/</p>

<p>You can also create function to display date in custom format:</p>

<pre class="lang-js prettyprint-override"><code>function formatDate(date, format){
  return Moment.moment(date).format(format)
}
</code>```

Use it like this in cell

```<code>=formatDate(B5,"DD/MM/YYYY")
</code>```

or

```<code>=formatDate(parseDate(B2,"MMM D, YYYY, at HH:mm A"),"DD/MM/YYYY")
</code>```

Body:
I'm trying to convert date from "text" to correct format. It is logged to Google Spreadsheets and I'm unable to use it to plot graphs.

This is the text format: February 3, 2018, at 11:21 AM

Time is not relevant, all I need is the date converted: DD/MM/YYYY.

I found a similar question where Gary's Student answered with a formula that looks like this for a different format:

=DATEVALUE(SUBSTITUTE(A1,MID(A1,FIND(" ",A1)-2,2),""))

(link to that question)

How can I use above formula (or something similar) so that text is converted to date?

Thanks in advance.

Body:
Another solution is to create custom function.

Open tools → script editor in menu to open script editor in new tab

Click Untitled project in top left corner and rename

Open Resources → Libraries in top menu

Paste library key MHMchiX6c1bwSqGM1PZiW_PxhMjh3Sh48 and click Add to add the Moment library to your script

Choose Moment version 9 and click Save

Paste function

function parseDate(dateString, format){
  return Moment.moment(dateString, format).toDate()
}

to Code.gs and save project Ctrl+S

Now you use your function in any cell in your sheet:

=parseDate(B2,"MMM D, YYYY, at HH:mm A")

more details about format:
https://momentjs.com/docs/#/parsing/string-formats/

You can also create function to display date in custom format:

function formatDate(date, format){
  return Moment.moment(date).format(format)
}

Use it like this in cell

=formatDate(B5,"DD/MM/YYYY")

or

=formatDate(parseDate(B2,"MMM D, YYYY, at HH:mm A"),"DD/MM/YYYY")


问:
How do those indices operations on matrixes work in python?
I am reviewing an algorithm for matrix multiplication in python but I am not familiar with python.

I can't figure out (or find what does the following do exactly)

```<code>import numpy as np

p = A.shape[0]
q = A.shape[1]

A11 = A[0:p //2, 0: q // 2]
A21 = A[p //2: p, 0: q // 2]
A12 = A[0:p //2, q // 2 : q]
A22 = A[p //2:p, q // 2 : q]
</code>```

do these operations return a 2d-matrix for each line or what's going on here?

答:
A is a matrix or a tensor. the dimensions can be extracted by looking at the .shape. .shape[0] is the length of the first dim and .shape[1] length of second dim, i.e. number of rows and cols. Let's just assume A is in fact a matrix with 2 dimensions.

You can subset a matrix via [] where [ indices on first dim, indices on second dim].

For illustration we set A to np.arange(50).reshape(10, 5) which looks as follows

Upper left

The first subset selects elements in the upper left, because // is division which floors. roughly 0 to 10 divided by two and rounded down to integer

```<code>p = A.shape[0]
q = A.shape[1]

A11 = A[0:p //2, 0: q // 2]
</code>```

Lower left

```<code>A21 = A[p //2: p, 0: q // 2]
</code>```

Lower right

```<code>A[p //2:p, q // 2 : q]
</code>```

Upper right

```<code>A[0:p //2, q // 2 : q]
</code>```

Body:
I am reviewing an algorithm for matrix multiplication in python but I am not familiar with python.

I can't figure out (or find what does the following do exactly)

import numpy as np

p = A.shape[0]
q = A.shape[1]

A11 = A[0:p //2, 0: q // 2]
A21 = A[p //2: p, 0: q // 2]
A12 = A[0:p //2, q // 2 : q]
A22 = A[p //2:p, q // 2 : q]

do these operations return a 2d-matrix for each line or what's going on here?

Body:
A is a matrix or a tensor. the dimensions can be extracted by looking at the .shape. .shape[0] is the length of the first dim and .shape[1] length of second dim, i.e. number of rows and cols. Let's just assume A is in fact a matrix with 2 dimensions.

You can subset a matrix via [] where [ indices on first dim, indices on second dim].

For illustration we set A to np.arange(50).reshape(10, 5) which looks as follows

Upper left

The first subset selects elements in the upper left, because // is division which floors. roughly 0 to 10 divided by two and rounded down to integer

p = A.shape[0]
q = A.shape[1]

A11 = A[0:p //2, 0: q // 2]

Lower left

A21 = A[p //2: p, 0: q // 2]

Lower right

A[p //2:p, q // 2 : q]

Upper right

A[0:p //2, q // 2 : q]


问:
Why is the BehaviorSubject not async?
I created a method to be able to return if the data has already been entered in the store and loaded, but this way it is not async.

It only looks async if I insert a variable outside, inside the subscribe.

What happens is that the value is "true" which is the initial value of the Behavior

SERVICE

```<code>export class StoreService {
    constructor(protected readonly userStore: UserStoreService, protected readonly chatStore: ChatStoreService) {}

    create(): void {
        this.userStore.setAll();
        this.chatStore.setAll();
    }

    get loading(): BehaviorSubject<boolean> {
        const isLoading = new BehaviorSubject(true);

        timer(1000).subscribe(() => {
            combineLatest([this.userStore.loading, this.chatStore.loading])
                .pipe(
                    filter(([userLoading, chatLoading]) => !userLoading && !chatLoading),
                    takeWhile(([userLoading, chatLoading]) => !userLoading && !chatLoading)
                )
                .subscribe(() => isLoading.next(false));
        });

        return isLoading;
    }
}
</code>```

COMPONENT:

```<code>export class AppComponent implements OnInit {
    constructor(public readonly store: StoreService) {}

    ngOnInit(): void {
        this.store.create();
    }
}

{{ store.loading | async | json }}
</code>```

答:
The problem of get loading() is that every time it's called it returns a new stream despite it relies on this.userStore.loading and this.chatStore.loading.

you need to make it fix, as an option make it a readonly property that does the same:

export class StoreService {
  constructor(protected readonly userStore: UserStoreService, protected readonly chatStore: ChatStoreService) {}

  create(): void {
    this.userStore.setAll();
    this.chatStore.setAll();
  }

  // to add $ to mark it as an observable is a nice style.
  public readonly loading$: Observable<boolean> = combineLatest([
    this.userStore.loading,
    this.chatStore.loading,
  ]).pipe(
    // maps to true if anyone is loading.
    map(flags => flags.indexOf(true) !== -1),

    // our start value is true.
    startWith(true),
  );
}
```

<p>and now every time when one of them or both are loading it will return true, otherwise false.</p>

<pre class="lang-js prettyprint-override"><code>{{ store.loading$ | async | json }}
</code>```

Title: Why is the BehaviorSubject not async?

Body:
I created a method to be able to return if the data has already been entered in the store and loaded, but this way it is not async.

It only looks async if I insert a variable outside, inside the subscribe.

What happens is that the value is "true" which is the initial value of the Behavior

SERVICE

export class StoreService {
    constructor(protected readonly userStore: UserStoreService, protected readonly chatStore: ChatStoreService) {}

    create(): void {
        this.userStore.setAll();
        this.chatStore.setAll();
    }

    get loading(): BehaviorSubject<boolean> {
        const isLoading = new BehaviorSubject(true);

        timer(1000).subscribe(() => {
            combineLatest([this.userStore.loading, this.chatStore.loading])
                .pipe(
                    filter(([userLoading, chatLoading]) => !userLoading && !chatLoading),
                    takeWhile(([userLoading, chatLoading]) => !userLoading && !chatLoading)
                )
                .subscribe(() => isLoading.next(false));
        });

        return isLoading;
    }
}

COMPONENT:

export class AppComponent implements OnInit {
    constructor(public readonly store: StoreService) {}

    ngOnInit(): void {
        this.store.create();
    }
}

{{ store.loading | async | json }}

Body:
The problem of get loading() is that every time it's called it returns a new stream despite it relies on this.userStore.loading and this.chatStore.loading.

you need to make it fix, as an option make it a readonly property that does the same:

export class StoreService {
  constructor(protected readonly userStore: UserStoreService, protected readonly chatStore: ChatStoreService) {}

  create(): void {
    this.userStore.setAll();
    this.chatStore.setAll();
  }

  // to add $ to mark it as an observable is a nice style.
  public readonly loading$: Observable<boolean> = combineLatest([
    this.userStore.loading,
    this.chatStore.loading,
  ]).pipe(
    // maps to true if anyone is loading.
    map(flags => flags.indexOf(true) !== -1),

    // our start value is true.
    startWith(true),
  );
}

and now every time when one of them or both are loading it will return true, otherwise false.

{{ store.loading$ | async | json }}


问:
react-native-webview commands failed to compile, how to fix?
someone has fixed or saw this issue?

I'm using last version of (react-native) and also macOS Catalina.
I did install react-native-webview by yarn and after into the (./ios) folder I had install the pods.

So build failed, after react-native run-ios.

```<code>    The following build commands failed:
            CompileC /Users/mymac/Library/Developer/Xcode/DerivedData/Project-cnketoyhxyitfqbbcdkdvhpuajey/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/react-native-webview.build/Objects-normal/x86_64/RNCWebView.o /Users/mymac/Desktop/React/project/node_modules/react-native-webview/apple/RNCWebView.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
    (1 failure)
</code>```

答:
Are you running the latest version of Xcode?

See react-native-webview issue #1399

Body:
someone has fixed or saw this issue?

I'm using last version of (react-native) and also macOS Catalina.
I did install react-native-webview by yarn and after into the (./ios) folder I had install the pods.

So build failed, after react-native run-ios.

    The following build commands failed:
            CompileC /Users/mymac/Library/Developer/Xcode/DerivedData/Project-cnketoyhxyitfqbbcdkdvhpuajey/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/react-native-webview.build/Objects-normal/x86_64/RNCWebView.o /Users/mymac/Desktop/React/project/node_modules/react-native-webview/apple/RNCWebView.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler
    (1 failure)


问:
How can I formulate the function solution?

x = [1, 2, 3, 4]
t = []
c = []
for(i = 0; i<x.length; i++){
   function solution(){
       t = Math.pow(x, 2)
       c = t[i]++
    return c
   }
}```

The function needs to:

Count the squares of the array numbers

Then to get sum of squared (I am not sure if I wrote it correct, LOL) numbers. Thanks!

答:
const result = [1, 2, 3, 4].map(n => n ** 2).reduce((acc, val) => acc + val, 0);

console.log(result);```

You can also use ** operator which is faster than Math.pow(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators

Body:
x = [1, 2, 3, 4]
t = []
c = []
for(i = 0; i<x.length; i++){
   function solution(){
       t = Math.pow(x, 2)
       c = t[i]++
    return c
   }
}

The function needs to:

Count the squares of the array numbers

Then to get sum of squared (I am not sure if I wrote it correct, LOL) numbers. Thanks!

Body:
const result = [1, 2, 3, 4].map(n => n ** 2).reduce((acc, val) => acc + val, 0);

console.log(result);

You can also use ** operator which is faster than Math.pow(). https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators


问:
UIPopoverController dismiss on 'tap off' - how do I detect this event?
I am using a UIPopover on my navigation bar. I have several UIBarButtonItems and the popover extends from one of these.

When the popOver is activated I changed the style of the button to UIBarButtonItemStyleDone.

However, the popOver is dismissed by tapping off the UIPopoverController as expected, but upon this I want to change the style back to UIBarButtonItemStyleBordered.

Is there a way I can detect if the UIPopOverController is closing? And therefore piggyback this for my own needs?

答:
Implement the -popoverControllerDidDismissPopover: method in your UIPopoverControllerDelegate and you should be able to do what you need to do in there.

```<code>- (void) popoverControllerDidDismissPopover:(UIPopoverController *) popoverController {
   //do stuff here...
}
</code>```

Body:
Implement the -popoverControllerDidDismissPopover: method in your UIPopoverControllerDelegate and you should be able to do what you need to do in there.

- (void) popoverControllerDidDismissPopover:(UIPopoverController *) popoverController {
   //do stuff here...
}


问:
how to change the column value based on other column value in data frame?
I am trying to change one column value based on other columns value. Can you please help me how to do this?

Example:

```<code>priority     comb_fld_order       start_bracs     end_bracs
1                                   (
1.1
2.3           1                     (
2.3.1         1                                      )
3.7                                                  )
</code>```

Expected Output:

```<code>priority     comb_fld_order       start_bracs     end_bracs
1
1.1
2.3           1                     (
2.3.1         1                                      )
3.7
</code>```

Means if comb_fld_order is null then we should to remove brackets from start_bracs and end_bracs column.

答:
You can use pandas apply method.</p>

```<code>def removeBracks(record):
    if record['comb_fld_order'] is None:
       record['start_bracs'] = None
       record['end_bracs'] = None
    return record

df = df.apply(removeBracks, axis=1)
</code>```

Body:
I am trying to change one column value based on other columns value. Can you please help me how to do this?

Example:

priority     comb_fld_order       start_bracs     end_bracs
1                                   (
1.1
2.3           1                     (
2.3.1         1                                      )
3.7                                                  )

Expected Output:

priority     comb_fld_order       start_bracs     end_bracs
1
1.1
2.3           1                     (
2.3.1         1                                      )
3.7

Means if comb_fld_order is null then we should to remove brackets from start_bracs and end_bracs column.

Body:
You can use pandas apply method.

def removeBracks(record):
    if record['comb_fld_order'] is None:
       record['start_bracs'] = None
       record['end_bracs'] = None
    return record

df = df.apply(removeBracks, axis=1)


问:
Acumatica Access by Sales Order Type
Good day

How do you limit users in Acumatica to only have access to certain Sales order Types ?

Thanks

答:
This is older code, but you could try limiting according to Role. In this example, Guest Role users are limited to IN and TR OrderTypes: </p>

```<code>    [PXDBString(2, IsKey = true, IsFixed = true, InputMask = ">aa")]
    [PXDefault(SOOrderTypeConstants.SalesOrder, typeof(SOSetup.defaultOrderType))]
    [PXSelector(typeof(Search5<SOOrderType.orderType,
        InnerJoin<SOOrderTypeOperation, On<SOOrderTypeOperation.orderType,
            Equal<SOOrderType.orderType>, And<SOOrderTypeOperation.operation, Equal<SOOrderType.defaultOperation>>>,
        LeftJoin<SOSetupApproval, On<SOOrderType.orderType, Equal<SOSetupApproval.orderType>>
            , InnerJoin<Users, On<Current<AccessInfo.userName>, Equal<Users.username>>
            , InnerJoin<UsersInRoles, On<Users.username, Equal<UsersInRoles.username>>
            , InnerJoin<Roles, On<Roles.rolename, Equal<UsersInRoles.rolename>>>>>>>,
         Where2<Where<Roles.guest, Equal<False>>,
                Or<Where<SOOrderType.orderType, Equal<string_IN>,
                        Or<SOOrderType.orderType, Equal<string_TR>>>>>,
        Aggregate<GroupBy<SOOrderType.orderType>>>))]
    [PXRestrictor(typeof(Where<SOOrderTypeOperation.iNDocType, NotEqual<INTranType.transfer>,
        Or<FeatureInstalled<FeaturesSet.warehouse>>>), ErrorMessages.ElementDoesntExist, typeof(SOOrderType.orderType))]
    [PXRestrictor(typeof(Where<SOOrderType.requireAllocation, NotEqual<True>,
        Or<AllocationAllowed>>), ErrorMessages.ElementDoesntExist, typeof(SOOrderType.orderType))]
    [PXRestrictor(typeof(Where<SOOrderType.active, Equal<True>>), null)]
    [PXUIField(DisplayName = "Order Type", Visibility = PXUIVisibility.SelectorVisible)]
    [PX.Data.EP.PXFieldDescription]
    protected virtual void SOOrder_OrderType_CacheAttached(PXCache sender) { }
</code>```

Title: Acumatica Access by Sales Order Type

Body:
This is older code, but you could try limiting according to Role. In this example, Guest Role users are limited to IN and TR OrderTypes:

    [PXDBString(2, IsKey = true, IsFixed = true, InputMask = ">aa")]
    [PXDefault(SOOrderTypeConstants.SalesOrder, typeof(SOSetup.defaultOrderType))]
    [PXSelector(typeof(Search5<SOOrderType.orderType,
        InnerJoin<SOOrderTypeOperation, On<SOOrderTypeOperation.orderType,
            Equal<SOOrderType.orderType>, And<SOOrderTypeOperation.operation, Equal<SOOrderType.defaultOperation>>>,
        LeftJoin<SOSetupApproval, On<SOOrderType.orderType, Equal<SOSetupApproval.orderType>>
            , InnerJoin<Users, On<Current<AccessInfo.userName>, Equal<Users.username>>
            , InnerJoin<UsersInRoles, On<Users.username, Equal<UsersInRoles.username>>
            , InnerJoin<Roles, On<Roles.rolename, Equal<UsersInRoles.rolename>>>>>>>,
         Where2<Where<Roles.guest, Equal<False>>,
                Or<Where<SOOrderType.orderType, Equal<string_IN>,
                        Or<SOOrderType.orderType, Equal<string_TR>>>>>,
        Aggregate<GroupBy<SOOrderType.orderType>>>))]
    [PXRestrictor(typeof(Where<SOOrderTypeOperation.iNDocType, NotEqual<INTranType.transfer>,
        Or<FeatureInstalled<FeaturesSet.warehouse>>>), ErrorMessages.ElementDoesntExist, typeof(SOOrderType.orderType))]
    [PXRestrictor(typeof(Where<SOOrderType.requireAllocation, NotEqual<True>,
        Or<AllocationAllowed>>), ErrorMessages.ElementDoesntExist, typeof(SOOrderType.orderType))]
    [PXRestrictor(typeof(Where<SOOrderType.active, Equal<True>>), null)]
    [PXUIField(DisplayName = "Order Type", Visibility = PXUIVisibility.SelectorVisible)]
    [PX.Data.EP.PXFieldDescription]
    protected virtual void SOOrder_OrderType_CacheAttached(PXCache sender) { }


问:
making a list into dictionary
suppose you have a list

```<code>A = ["A: 1", "B: 2", "C: 3"]
</code>```

can you make this into a dictionary of

```<code>dict_A = {"A" : 1, "B": 2, "C": 3}
</code>```

I got stuck at making the list into a dictionary

答:
```<code>A = ["A: 1", "B: 2", "C: 3"]
B={}
for i in A:
    B[i[0]]=int(i[3])
print(B)

{'A': 1, 'B': 2, 'C': 3}
</code>```

the length of every string here is 4. the i[0] is the key like 'A' and the i[3] is the value like '1'. converting it to int would give you the exact value you want, and then you just assign it to the dictionary for each key values.

Title: making a list into dictionary

Body:
suppose you have a list

A = ["A: 1", "B: 2", "C: 3"]

can you make this into a dictionary of

dict_A = {"A" : 1, "B": 2, "C": 3}

I got stuck at making the list into a dictionary

Body:
A = ["A: 1", "B: 2", "C: 3"]
B={}
for i in A:
    B[i[0]]=int(i[3])
print(B)

{'A': 1, 'B': 2, 'C': 3}

the length of every string here is 4. the i[0] is the key like 'A' and the i[3] is the value like '1'. converting it to int would give you the exact value you want, and then you just assign it to the dictionary for each key values.


问:
Pairwise intersection counts of multiple columns in SQL
Say I have a SQL db with multiple tables, and each of these tables has a column code. What I want to produce is a table showing the number of codes shared between each pair of code columns. I.e. a pairwise intersection count plot:

```<code>       table1 table2 table3 table4
table1     10      2      3      5
table2      2     10      4      1
table3      3      4     10      2
table4      5      1      2     10
</code>```

I can get each value individually using e.g.

```<code>WITH abc AS
(
SELECT code FROM table1
INTERSECT
SELECT code FROM table2
)

SELECT COUNT(*) AS table1Xtable2 FROM abc
</code>```

But is there a query that will generate the entire output as desired as a table?

答:
The following gets all combinations among the tables:

```<code>select t1, t2, t3, t4, count(*)
from (select code, max(t1) as t1, max(t2) as t2, max(t3) as t3, max(t4) as t4
      from ((select code, 1 as t1, 0 as t2, 0 as t3, 0 as t4
             from table1
            ) union all
            (select code, 0 as t1, 1 as t2, 0 as t3, 0 as t4
             from table2
            ) union all
            (select code, 0 as t1, 0 as t2, 1 as t3, 0 as t4
             from table3
            ) union all
            (select code, 0 as t1, 0 as t2, 0 as t3, 1 as t4
             from table4
            )
           ) t
      group by code
     ) t
group by t1, t2, t3, t4;
</code>```

For your particular problem, you can use:

```<code>with t as (
      select code, 'table1' as tablename from table1 union all
      select code, 'table2' as tablename from table2 union all
      select code, 'table3' as tablename from table3 union all
      select code, 'table4' as tablename from table4
     )
select t1.tablename,
       sum(case when t2.tablename = 'table1' then 1 else 0 end) as t1,
       sum(case when t2.tablename = 'table2' then 1 else 0 end) as t2,
       sum(case when t2.tablename = 'table3' then 1 else 0 end) as t3,
       sum(case when t2.tablename = 'table4' then 1 else 0 end) as t4
from t t1 join
     t t2
on t1.code = t2.code
group by t1.tablename
</code>```

Note that the above assumes that code is unique in the tables.  If it is duplicated, you can replace union all with union.

Body:
Say I have a SQL db with multiple tables, and each of these tables has a column code. What I want to produce is a table showing the number of codes shared between each pair of code columns. I.e. a pairwise intersection count plot:

       table1 table2 table3 table4
table1     10      2      3      5
table2      2     10      4      1
table3      3      4     10      2
table4      5      1      2     10

I can get each value individually using e.g.

WITH abc AS
(
SELECT code FROM table1
INTERSECT
SELECT code FROM table2
)

SELECT COUNT(*) AS table1Xtable2 FROM abc

But is there a query that will generate the entire output as desired as a table?

Body:
The following gets all combinations among the tables:

select t1, t2, t3, t4, count(*)
from (select code, max(t1) as t1, max(t2) as t2, max(t3) as t3, max(t4) as t4
      from ((select code, 1 as t1, 0 as t2, 0 as t3, 0 as t4
             from table1
            ) union all
            (select code, 0 as t1, 1 as t2, 0 as t3, 0 as t4
             from table2
            ) union all
            (select code, 0 as t1, 0 as t2, 1 as t3, 0 as t4
             from table3
            ) union all
            (select code, 0 as t1, 0 as t2, 0 as t3, 1 as t4
             from table4
            )
           ) t
      group by code
     ) t
group by t1, t2, t3, t4;

For your particular problem, you can use:

with t as (
      select code, 'table1' as tablename from table1 union all
      select code, 'table2' as tablename from table2 union all
      select code, 'table3' as tablename from table3 union all
      select code, 'table4' as tablename from table4
     )
select t1.tablename,
       sum(case when t2.tablename = 'table1' then 1 else 0 end) as t1,
       sum(case when t2.tablename = 'table2' then 1 else 0 end) as t2,
       sum(case when t2.tablename = 'table3' then 1 else 0 end) as t3,
       sum(case when t2.tablename = 'table4' then 1 else 0 end) as t4
from t t1 join
     t t2
on t1.code = t2.code
group by t1.tablename

Note that the above assumes that code is unique in the tables.  If it is duplicated, you can replace union all with union.


问:
Looking for a simpler Objective-C solution
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

```<code>-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;
</code>```

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

答:
```<code>@"l", [NSNumber numberWithUnsignedInt: self.leftVent  ? 1 : 0],
@"r", [NSNumber numberWithUnsignedInt: self.rightVent ? 1 : 0],
</code>```

will shorten it by 2 lines

ContentLicense: CC BY-SA 2.5

Body:
Maybe simpler isn't the proper word; terse might do as well. I'm well-aware that Objective-C is a verbose language; I'm just wondering if it has to be as verbose as it is in the solution I'm showing below. I'm relatively new to the language.

This piece of code counts the number of each type of field in a record, pursuant to generating a  variable-height UITableViewCell containing one label per field. My question isn't about how to do this -- I've already figured that out -- I'm just wondering: isn't there a simpler or less verbose way of doing this in Objective-C, using an NSDictionary object? Is this as terse as it gets using an NSDictionary? Solutions using other collection-type objects are also welcome.

Here's my -PartsRecord.countFields method. I've simplified the code slightly.

-(NSDictionary*) countFields {
NSDictionary* dict = [[NSDictionary alloc] initWithObjectAndKeys:
     @"s", [NSNumber numberWithUnsignedInt: [self.struts count]],
     @"h", [NSNumber numberWithUnsignedInt: [self.headAssemblies count]],
     @"l", (self.leftVent == nil) ?   [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     @"r", (self.rightVent == nil) ?  [NSNumber numberWithUnsignedInt: 0] :
                                      [NSNumber numberWithUnsignedInt: 1],
     nil ];
return dict;

}

Any errors in the above code are errors in transcription , not actual errors in the code.

TIA,

Howard

Body:
@"l", [NSNumber numberWithUnsignedInt: self.leftVent  ? 1 : 0],
@"r", [NSNumber numberWithUnsignedInt: self.rightVent ? 1 : 0],

will shorten it by 2 lines