问:
Chrome SameSite=None; Secure Cookie Settings - Cookies that you access in both a first and third-party context
After the latest Chrome updated  - the third party cookie setting is not working for me. To make it work I have to set SameSite=None;Secure. But this require HTTPS connection to work  . How do we make it work for HTTP ?

答: With the new behaviour in Chrome as defined by Incrementally Better Cookies you will only be able to have cookies in a third-party context over HTTPS. I would strongly suggest looking at migrating to HTTPS over trying to make cross-site cookies work over plain HTTP.</p>


来源: stackexchange

问:
Is ActionFilterAttribute instantiated for each action?
I want to have a field in ActionFilterAttribute that is only relevant for the action it lives in eg

```<code>    public class TimedAction : ActionFilterAttribute
    {
        long start, end;

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            start = Stopwatch.GetTimestamp();

            base.OnActionExecuting(actionContext);
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

            end = Stopwatch.GetTimestamp();
        }
    }
</code>```

is it safe to assume that TimedAction will be instantiated for each API call action?

EDIT: I changed code to this and now it appears requests are shared (what??) and I get exception when I try to add keyvaluepair: An item with the same key has already been added.

```<code>        public override void OnActionExecuting(HttpActionContext context)
        {
            var start = Stopwatch.GetTimestamp();

            context.Request.Properties.Add(new KeyValuePair<string, object>("Stopwatch", start));

            base.OnActionExecuting(context);
        }

        public override void OnActionExecuted(HttpActionExecutedContext context)
        {
            base.OnActionExecuted(context);

            var end = Stopwatch.GetTimestamp();

            object o;
            long start = 0;
            if (context.Request.Properties.TryGetValue("Stopwatch", out o))
            {
                start = (long)o;
            }
        }
</code>```

答:
Apparently there is no difference between what I did (see the code in the OP) and @RicardoPeres approach.

The problem was that I accidentally set attribute twice to a method.

Yet I feel Ricardo's version is better than mine so I kept it.

ContentLicense: CC BY-SA 4.0

Body:
I want to have a field in ActionFilterAttribute that is only relevant for the action it lives in eg

    public class TimedAction : ActionFilterAttribute
    {
        long start, end;

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            start = Stopwatch.GetTimestamp();

            base.OnActionExecuting(actionContext);
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

            end = Stopwatch.GetTimestamp();
        }
    }

is it safe to assume that TimedAction will be instantiated for each API call action?

EDIT: I changed code to this and now it appears requests are shared (what??) and I get exception when I try to add keyvaluepair: An item with the same key has already been added.

        public override void OnActionExecuting(HttpActionContext context)
        {
            var start = Stopwatch.GetTimestamp();

            context.Request.Properties.Add(new KeyValuePair<string, object>("Stopwatch", start));

            base.OnActionExecuting(context);
        }

        public override void OnActionExecuted(HttpActionExecutedContext context)
        {
            base.OnActionExecuted(context);

            var end = Stopwatch.GetTimestamp();

            object o;
            long start = 0;
            if (context.Request.Properties.TryGetValue("Stopwatch", out o))
            {
                start = (long)o;
            }
        }


问:
MultiPartMimeStreamFormatException error when importing pbix files using rest-api
So I'm using powershell to automate my power BI reports into my workspace through imports API.
here's the code which I'm using :

```<code>    $PBIXuri="my azure blob storage url",
    $Workspaceurl="https://api.powerbi.com/v1.0/myorg/groups/mygroups/imports?datasetDisplayName=myreportname",
    $AccessToken="my oauth token"

    #download my pbix file from azure blob storage
    $cli = New-Object System.Net.WebClient
    $exportpbix = $cli.DownloadData($PBIXuri)

    $powerBiBody = @'
    --exptest
    Content-Disposition: form-data; name="file";
    Content-Type: application/x-zip-compressed

    {0}
    --exptest--

    '@

    #set my pbix file into request body
    $encoding = [System.Text.Encoding]::GetEncoding('iso-8859-1')
    $body = $powerBiBody -f $encoding.GetString($exportpbix)

    $headers = @{
    "Authorization" = "Bearer " + $AccessToken}

    Invoke-RestMethod -Uri $Workspaceurl -Method Post -Headers $headers -Body $body -ContentType "multipart/form-data; boundary=--exptest"
</code>```

but it always return an error like :

```<code>Invoke-RestMethod :     {"error":
     {"code":"MultiPartMimeStreamFormatException","pbi.error":
       {"code":"MultiPartMimeStreamFormatException",
        "parameters":{},
        "details":[],
        "exceptionCulprit":1
        }
      }
    }
</code>```

where do I went wrong on my code?

答:
To import a file, request Headers should include Content-Type: multipart/form-data with the file encoded as form data in the request body, as noted in the documentation. The request body should look like this:

See Upload a local PBIX file using the import API.

Maybe the easiest way is to try to save the downloaded data to a file on disk, let's say in $filePath, and add -InFile parameter to your your call:

```<code>Invoke-RestMethod -Uri $Workspaceurl -Method Post -InFile $filePath -ContentType "multipart/form-data"
</code>```

Body:
So I'm using powershell to automate my power BI reports into my workspace through imports API.
here's the code which I'm using :

    $PBIXuri="my azure blob storage url",
    $Workspaceurl="https://api.powerbi.com/v1.0/myorg/groups/mygroups/imports?datasetDisplayName=myreportname",
    $AccessToken="my oauth token"

    #download my pbix file from azure blob storage
    $cli = New-Object System.Net.WebClient
    $exportpbix = $cli.DownloadData($PBIXuri)

    $powerBiBody = @'
    --exptest
    Content-Disposition: form-data; name="file";
    Content-Type: application/x-zip-compressed

    {0}
    --exptest--

    '@

    #set my pbix file into request body
    $encoding = [System.Text.Encoding]::GetEncoding('iso-8859-1')
    $body = $powerBiBody -f $encoding.GetString($exportpbix)

    $headers = @{
    "Authorization" = "Bearer " + $AccessToken}

    Invoke-RestMethod -Uri $Workspaceurl -Method Post -Headers $headers -Body $body -ContentType "multipart/form-data; boundary=--exptest"

but it always return an error like :

Invoke-RestMethod :     {"error":
     {"code":"MultiPartMimeStreamFormatException","pbi.error":
       {"code":"MultiPartMimeStreamFormatException",
        "parameters":{},
        "details":[],
        "exceptionCulprit":1
        }
      }
    }

where do I went wrong on my code?

Body:
To import a file, request Headers should include Content-Type: multipart/form-data with the file encoded as form data in the request body, as noted in the documentation. The request body should look like this:

See Upload a local PBIX file using the import API.

Maybe the easiest way is to try to save the downloaded data to a file on disk, let's say in $filePath, and add -InFile parameter to your your call:

Invoke-RestMethod -Uri $Workspaceurl -Method Post -InFile $filePath -ContentType "multipart/form-data"


问:
I want to understand the concept of list comprehension in python

Given code

```<code>x=[(a,b) for a in range(3) for b in range(a)]
print(x)
</code>```

Output

```<code>[(1, 0), (2, 0), (2, 1)]
</code>```

I know the comprehension can be broken down as follows:

```<code>for a in range(3):
    for b in range(a):
        print(a,b)
</code>```

Can someone explain me how the output came as such provided above....

答:
I think what you're looking for is this:

first, a=0 so the inner loop skips as range(0) returns an empty list.

then, a=1 so the inner loop is only executed for 0 as range(1) is qual to [0] so the first pair is (1, 0)

a=2 and the inner loop runs for b=0 and b=1 hence the other two pair (2, 0) and (2, 1)

I think it's clear what's going on now. right?

Body:
Given code

x=[(a,b) for a in range(3) for b in range(a)]
print(x)

Output

[(1, 0), (2, 0), (2, 1)]

I know the comprehension can be broken down as follows:

for a in range(3):
    for b in range(a):
        print(a,b)

Can someone explain me how the output came as such provided above....


问:
How to hide element with AngularJS based on DOM element
I have an Umbraco setup. And when I edit in the CMS I would like for the "Preview" button to disappear whenever there is not a text-editor present in the DOM.

Angular file in localtion Umbraco/Views/content/edit.html

<form novalidate name="contentForm"
    ng-controller="Umbraco.Editors.Content.EditController"
    ng-show="loaded"
    ng-submit="save()"
    val-form-manager>

    <umb-panel umb-tabs ng-class="{'editor-breadcrumb': ancestors && ancestors.length > 0}">
        <umb-header tabs="content.tabs">

                <umb-content-name placeholder="@placeholders_entername"
                                  ng-model="content.name" />

{{formStatus}}

                    <umb-options-menu ng-show="currentNode"
                                      current-node="currentNode"
                                      current-section="{{currentSection}}">
                    </umb-options-menu>

        </umb-header>

        <umb-tab-view>
            <umb-tab id="tab{{tab.id}}" rel="{{tab.id}}" ng-repeat="tab in content.tabs">

                    <umb-property property="property"
                                  ng-repeat="property in tab.properties">
                        <umb-editor model="property"></umb-editor>
                    </umb-property>

                                <localize key="buttons_returnToList">Return to list</localize>

                                <localize key="buttons_showPage">Preview page</localize>

                                <localize key="{{defaultButton.labelKey}}">{{defaultButton.labelKey}}</localize>

                             0">

                            Return to list

 0">

                                        <localize key="{{btn.labelKey}}">{{btn.labelKey}}</localize>

            </umb-tab>
        </umb-tab-view>

 0">

                {{ancestor.name}}

    </umb-panel>
</form>
```

I am not certain this is the correct file - but it seems to be the place where the Preview button is created.

The question now is. Can I somehow determine with angular if the text editor is active and then if it is, show the Preview button next to the Save and publish?

答:
I found a second solution I might as well add here. I used the Umbraco Plugin Backoffice Tweaking.

Here I added this to my Config\BackofficeTweaking.config file

```<code><?xml version="1.0" encoding="utf-8"?>
<Config>
  <Rules>
    <Rule Type="HideButtons" Enabled="true" Names="preview" Users="" UserTypes="" ContentTypes="Omraader,Grund,Udstykning,Indstillinger,Niveau,Oversigt_Mappe,Oversigt,Information_Mappe,Information,Afstande_Mappe,Afstande" Description="" />
  </Rules>
  <Scripts>
    <Script Name="example"></Script>
  </Scripts>
</Config>
</code>```

Here you can also make some scripting or do many other things. The plugin also has a visual editor for Umbraco. Pretty easy to use.

Body:
I have an Umbraco setup. And when I edit in the CMS I would like for the "Preview" button to disappear whenever there is not a text-editor present in the DOM.

Angular file in localtion Umbraco/Views/content/edit.html

<form novalidate name="contentForm"
    ng-controller="Umbraco.Editors.Content.EditController"
    ng-show="loaded"
    ng-submit="save()"
    val-form-manager>

    <umb-panel umb-tabs ng-class="{'editor-breadcrumb': ancestors && ancestors.length > 0}">
        <umb-header tabs="content.tabs">

                <umb-content-name placeholder="@placeholders_entername"
                                  ng-model="content.name" />

{{formStatus}}

                    <umb-options-menu ng-show="currentNode"
                                      current-node="currentNode"
                                      current-section="{{currentSection}}">
                    </umb-options-menu>

        </umb-header>

        <umb-tab-view>
            <umb-tab id="tab{{tab.id}}" rel="{{tab.id}}" ng-repeat="tab in content.tabs">

                    <umb-property property="property"
                                  ng-repeat="property in tab.properties">
                        <umb-editor model="property"></umb-editor>
                    </umb-property>

                                <localize key="buttons_returnToList">Return to list</localize>

                                <localize key="buttons_showPage">Preview page</localize>

                                <localize key="{{defaultButton.labelKey}}">{{defaultButton.labelKey}}</localize>

                             0">

                            Return to list

 0">

                                        <localize key="{{btn.labelKey}}">{{btn.labelKey}}</localize>

            </umb-tab>
        </umb-tab-view>

 0">

                {{ancestor.name}}

    </umb-panel>
</form>

I am not certain this is the correct file - but it seems to be the place where the Preview button is created.

The question now is. Can I somehow determine with angular if the text editor is active and then if it is, show the Preview button next to the Save and publish?

Body:
I found a second solution I might as well add here. I used the Umbraco Plugin Backoffice Tweaking.

Here I added this to my Config\BackofficeTweaking.config file

<?xml version="1.0" encoding="utf-8"?>
<Config>
  <Rules>
    <Rule Type="HideButtons" Enabled="true" Names="preview" Users="" UserTypes="" ContentTypes="Omraader,Grund,Udstykning,Indstillinger,Niveau,Oversigt_Mappe,Oversigt,Information_Mappe,Information,Afstande_Mappe,Afstande" Description="" />
  </Rules>
  <Scripts>
    <Script Name="example"></Script>
  </Scripts>
</Config>

Here you can also make some scripting or do many other things. The plugin also has a visual editor for Umbraco. Pretty easy to use.


问:
c# registry time attributes
Summary:
Can i get registry creation, modification, and last write times like i can with files and folders?

Details:
I current have my code setup to display a directory's 3 time attributes and the same with files. I would love to do this with the registry values that i am searching for as well. is this possible? If so how?

Code sample:
Below are the 3 segments I am using. The Directory and file headings below are just samples from my already working code which does everything i want it to do. I just wanted to show that i know how to get those attributes. The Registry segment is the sanitized code i am using to cycle registry keys (take it and use it if you like ;)) that i wish to add time attributes to in the output.

Directory:

```<code>//print out which folders are not whitelisted
string pt = System.String.Concat("\n" + dir, "\n");
Output.AppendText(pt);
DateTime creationTimeUtc = Directory.GetCreationTimeUtc(dir);
DateTime lastWriteTimeUtc = Directory.GetLastWriteTimeUtc(dir);
DateTime lastAccessTimeUtc = Directory.GetLastAccessTimeUtc(dir);
Output.AppendText("creationTimeUtc: " + creationTimeUtc + "\n");
Output.AppendText("lastWriteTimeUtc: " + lastWriteTimeUtc + "\n");
Output.AppendText("lastAccessTimeUtc: " + lastAccessTimeUtc + "\n");
</code>```

File:

```<code>//print out which folders are not whitelisted
string pt = System.String.Concat("\n" + file, "\n");
Output.AppendText(pt);
DateTime creationTimeUtc = File.GetCreationTimeUtc(file);
DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(file);
DateTime lastAccessTimeUtc = File.GetLastAccessTimeUtc(file);
Output.AppendText("creationTimeUtc: " + creationTimeUtc + "\n");
Output.AppendText("lastWriteTimeUtc: " + lastWriteTimeUtc + "\n");
Output.AppendText("lastAccessTimeUtc: " + lastAccessTimeUtc + "\n");
</code>```

Registry:

```<code>//check for malware registry values
private void malwareRegCheck()
{
    //lists of registries
    List<string> hkey = new List<string>();
    List<string> names = new List<string>();
    //try
    try
    {
        // Open HKEY_USERS
        // on a remote computer.
        string remoteName = host;
        RegistryKey environmentKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.Users, remoteName);
        //put all hkey_user entries in list
        foreach (string subKeyName in environmentKey.GetSubKeyNames())
        {
            //add SID to hkey list
            hkey.Add(subKeyName);
        }
        //go through the list and enumerate each one
        foreach (string sid in hkey)
        {
            //get the subkeys of each SID under hkey
            RegistryKey sids = RegistryKey.OpenRemoteBaseKey(RegistryHive.Users, remoteName).OpenSubKey(sid);
            //for each id under hkey
            foreach (string id in sids.GetSubKeyNames())
            {
                //create SID path and add to names list
                string SIDpath = sid + "\\" + id;
                names.Add(SIDpath);
            }

        }
        // Close the registry key.
        environmentKey.Close();
        //check if reg entry is whitelisted
        foreach (string fname in names)
        {
            //create path to check
            String fullPath = "\\\\" + host + "\\" + fname;
            //split file path in to parts
            string[] folders = fname.Split('\\');
            //get length of array
            int folderlen = folders.Length;
            //folder is last element in array
            string folder = folders[folderlen - 1];
            //if folder is whitelisted
            if ((xmlmalware2reg.Contains(folder)) || (folder.Length > 6))
            {
                //do nothing
            }
            //if folder is not whitelisted
            else
            {
                //print out which folders are not whitelisted
                string pt = System.String.Concat(fullPath + ", not whitelisted\n");
                Output.AppendText(pt);

            }
        }

    }
    //catch all exceptions
    catch
    {
    }

}
</code>```

答: there is no answer for this question. time variables for registry items can not be gathered via this method.</p>

ContentLicense: CC BY-SA 3.0

Title: c# registry time attributes

Body:
Summary:
Can i get registry creation, modification, and last write times like i can with files and folders?

Details:
I current have my code setup to display a directory's 3 time attributes and the same with files. I would love to do this with the registry values that i am searching for as well. is this possible? If so how?

Code sample:
Below are the 3 segments I am using. The Directory and file headings below are just samples from my already working code which does everything i want it to do. I just wanted to show that i know how to get those attributes. The Registry segment is the sanitized code i am using to cycle registry keys (take it and use it if you like ;)) that i wish to add time attributes to in the output.

Directory:

//print out which folders are not whitelisted
string pt = System.String.Concat("\n" + dir, "\n");
Output.AppendText(pt);
DateTime creationTimeUtc = Directory.GetCreationTimeUtc(dir);
DateTime lastWriteTimeUtc = Directory.GetLastWriteTimeUtc(dir);
DateTime lastAccessTimeUtc = Directory.GetLastAccessTimeUtc(dir);
Output.AppendText("creationTimeUtc: " + creationTimeUtc + "\n");
Output.AppendText("lastWriteTimeUtc: " + lastWriteTimeUtc + "\n");
Output.AppendText("lastAccessTimeUtc: " + lastAccessTimeUtc + "\n");

File:

//print out which folders are not whitelisted
string pt = System.String.Concat("\n" + file, "\n");
Output.AppendText(pt);
DateTime creationTimeUtc = File.GetCreationTimeUtc(file);
DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(file);
DateTime lastAccessTimeUtc = File.GetLastAccessTimeUtc(file);
Output.AppendText("creationTimeUtc: " + creationTimeUtc + "\n");
Output.AppendText("lastWriteTimeUtc: " + lastWriteTimeUtc + "\n");
Output.AppendText("lastAccessTimeUtc: " + lastAccessTimeUtc + "\n");

Registry:

//check for malware registry values
private void malwareRegCheck()
{
    //lists of registries
    List<string> hkey = new List<string>();
    List<string> names = new List<string>();
    //try
    try
    {
        // Open HKEY_USERS
        // on a remote computer.
        string remoteName = host;
        RegistryKey environmentKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.Users, remoteName);
        //put all hkey_user entries in list
        foreach (string subKeyName in environmentKey.GetSubKeyNames())
        {
            //add SID to hkey list
            hkey.Add(subKeyName);
        }
        //go through the list and enumerate each one
        foreach (string sid in hkey)
        {
            //get the subkeys of each SID under hkey
            RegistryKey sids = RegistryKey.OpenRemoteBaseKey(RegistryHive.Users, remoteName).OpenSubKey(sid);
            //for each id under hkey
            foreach (string id in sids.GetSubKeyNames())
            {
                //create SID path and add to names list
                string SIDpath = sid + "\\" + id;
                names.Add(SIDpath);
            }

        }
        // Close the registry key.
        environmentKey.Close();
        //check if reg entry is whitelisted
        foreach (string fname in names)
        {
            //create path to check
            String fullPath = "\\\\" + host + "\\" + fname;
            //split file path in to parts
            string[] folders = fname.Split('\\');
            //get length of array
            int folderlen = folders.Length;
            //folder is last element in array
            string folder = folders[folderlen - 1];
            //if folder is whitelisted
            if ((xmlmalware2reg.Contains(folder)) || (folder.Length > 6))
            {
                //do nothing
            }
            //if folder is not whitelisted
            else
            {
                //print out which folders are not whitelisted
                string pt = System.String.Concat(fullPath + ", not whitelisted\n");
                Output.AppendText(pt);

            }
        }

    }
    //catch all exceptions
    catch
    {
    }

}


问:
Creating a route53 record set via aws cli
I am connecting to an ec2 instance via AWS SSM session manager.

From within this instance I am attempting to create a record set for our domain (to finalise the verification of the domain for AWS Simple Email Service).

AWS CLI command:

```<code>[root@ip-XX-XXX-XX-XXX igor]# aws route53 change-resource-record-sets --hosted-zone-id <HOSTED_ZONE_ID> --change-batch ./record-set.json
</code>```

JSON file:

```<code>{
  "Comment": "Add SES record set for this domain",
  "Changes": [
    {
      "Action": "CREATE",
      "ResourceRecordSet": {
        "Name": "_amazonses.domain.something.something.org.",
        "Type": "TXT",
        "Region":"eu-west-1",
        "TTL": 1800,
        "ResourceRecords": [
          {
            "Value": "<generated-verification-id>"
          }
        ]
      }
    }
  ]
}
</code>```

Problem:
As I run the above command, I receive the following error:

```<code>[root@ip-XX-XXX-XX-XXX igor]# aws route53 change-resource-record-sets --hosted-zone-id <HOSTED_ZONE_ID> --change-batch "./record-set.json"

Error parsing parameter '--change-batch': Expected: '=', received: 'EOF' for input:
./record-set.json
</code>```

What is the problem?

答:
Fixed using file:// instead of ./ in the file path (not sure how this works)

[root@ip-XX-XXX-XX-XXX igor]# aws route53 change-resource-record-sets --hosted-zone-id  --change-batch "file://record-set.json"

Body:
I am connecting to an ec2 instance via AWS SSM session manager.

From within this instance I am attempting to create a record set for our domain (to finalise the verification of the domain for AWS Simple Email Service).

AWS CLI command:

[root@ip-XX-XXX-XX-XXX igor]# aws route53 change-resource-record-sets --hosted-zone-id <HOSTED_ZONE_ID> --change-batch ./record-set.json

JSON file:

{
  "Comment": "Add SES record set for this domain",
  "Changes": [
    {
      "Action": "CREATE",
      "ResourceRecordSet": {
        "Name": "_amazonses.domain.something.something.org.",
        "Type": "TXT",
        "Region":"eu-west-1",
        "TTL": 1800,
        "ResourceRecords": [
          {
            "Value": "<generated-verification-id>"
          }
        ]
      }
    }
  ]
}

Problem:
As I run the above command, I receive the following error:

[root@ip-XX-XXX-XX-XXX igor]# aws route53 change-resource-record-sets --hosted-zone-id <HOSTED_ZONE_ID> --change-batch "./record-set.json"

Error parsing parameter '--change-batch': Expected: '=', received: 'EOF' for input:
./record-set.json

What is the problem?


问:
How can i send emails without a server ? Only front-end Javascript with sendgrid or
i was wondering lately how i could send emails with only a front-end language like Javascript through Email as a Service apps like sendgrid or mandrill or so.

Sendgrid and mandrill have Curl APIS, so basically i can just do an AJAX post request to their API to send a mail but the thing is, i will have to put my API secret key in the JS file, this means it will be public... while it's supposed to be secret.

On those two apps, there's nothing in the docs concerning front-end use except having your own server which will use the API, but i'm currently on front-end based project. No server programming, the server only renders the assets that's all.

Do you guys know any method or apps of this kind to acheive this ? Thanks

答: You could use a serverless architecture with AWS Lambda functions written in JavaScript.</p>


问:
is it possilbe to list all shared drive(TeamDrive) list and the folders inside the drives?
i want to know if it's possible to list all drives id list and the folder's Id inside of all drives?

for the moment i can only get the list of drives

```<code> var request = service.Files.Get(driveFileId);

            request.SupportsAllDrives = true;
            request.SupportsTeamDrives = true;
            request.Fields = "*";
            var result = request.Execute();
            return request.Execute();
</code>```

答:
Yes, it's possible

You can list the drives with the method Drives: list

You can list the folders within those drives with Files: list by specifying the q parameter as

```<code>request.Q = "'XXX' in parents and mimeType = 'application/vnd.google-apps.folder'"
</code>```

whereby XXX should be replaced by the id / variable containing the id of the shared drive.

Body:
i want to know if it's possible to list all drives id list and the folder's Id inside of all drives?

for the moment i can only get the list of drives

 var request = service.Files.Get(driveFileId);

            request.SupportsAllDrives = true;
            request.SupportsTeamDrives = true;
            request.Fields = "*";
            var result = request.Execute();
            return request.Execute();

Body:
Yes, it's possible

You can list the drives with the method Drives: list

You can list the folders within those drives with Files: list by specifying the q parameter as

request.Q = "'XXX' in parents and mimeType = 'application/vnd.google-apps.folder'"

whereby XXX should be replaced by the id / variable containing the id of the shared drive.


问:
Can't find variable: counter, in expo
Been using React for a bit and wanted to try out native using expo, when I click on a button to increment a counter, I get a ReferenceError on my phone saying "Can't find variable: counter", I don't get any error on the expo gui or in VSCode, very confused.</p>

```<code>import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { Button } from "react-native-elements";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    };
  }

  increment() {
    this.setState({ counter: (counter += 1) });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>{this.state.counter}</Text>
        <Button title="Press Me" onPress={this.increment}></Button>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

</code>```

答:
The counter variable you are referring inside increment function doesn't refer to the state variable. Access the state object using this.state.counter and then increment it by 1.

Please update the increment function as below

```<code>  increment() {
    this.setState({ counter: this.state.counter+ 1) });
  }

  <Button title="Press Me" onPress={() => this.increment()}></Button>
</code>```

Title: Can't find variable: counter, in expo

Body:
Been using React for a bit and wanted to try out native using expo, when I click on a button to increment a counter, I get a ReferenceError on my phone saying "Can't find variable: counter", I don't get any error on the expo gui or in VSCode, very confused.

import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { Button } from "react-native-elements";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    };
  }

  increment() {
    this.setState({ counter: (counter += 1) });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app!</Text>
        <Text>{this.state.counter}</Text>
        <Button title="Press Me" onPress={this.increment}></Button>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
  }
});

Body:
The counter variable you are referring inside increment function doesn't refer to the state variable. Access the state object using this.state.counter and then increment it by 1.

Please update the increment function as below

  increment() {
    this.setState({ counter: this.state.counter+ 1) });
  }

  <Button title="Press Me" onPress={() => this.increment()}></Button>


问:
How to suppress specific compiler warnings in Xcode11
I am using third party framework in my swift project with Xcode11, which is having many warnings for

Non-portable path to file "HeaderFile.h"; Specified path differs in case from file name on disk Headerfile.h

Is there any way to suppress these specific warnings? or any way to silent framework warnings?

I went through with many threads but did't find the expected solution.

Any inputs would be a great help here, Thank you!!

答:
Add -Wno-nonportable-include-path to your compiler options.

In Xcode, click the “Show the Project navigator” icon at the top left (leftmost icon under the red-yellow-green window buttons) or select View > Navigators > Show Project Navigator.

The select the project (topmost item in the tree shown in the sidebar once the project navigator view is shown). To the right, click on Build Settings. Below that, and to the left, in Basic / Customized / All, click All.

Scroll to “Apple Clang - Custom Compiler Flags”. Click the blank field to the right of “Other Warning Flags”. A dialog with fields to enter options will pop up. Click “+” at the bottom left. In the empty field that becomes editable, enter “-Wno-nonportable-include-path”.


问:
How to get the exception that was thrown when a Cucumber test failed in Java?
I can perform actions on test failure by using:

```<code>@After
public void afterTest(Scenario scenario) {
    if (scenario.isFailed()) {
        /*Do stuff*/
    }
}
</code>```

However some of the actions I need to perform depend on the Exception that was thrown and in what context it was thrown. Is there a way to get the Throwable that caused the test to fail? For example in JUnit I would do this by extending TestWatcher and add a rule to my tests:

```<code>@Override
protected void failed(Throwable e, Description description) {
    /*Do stuff with e*/
}
</code>```

However the cucumber-junit iplementation does not allow the use of rules, so this solution would not work with Cucumber.

I don't think I need to explain why accessing a thrown exception on test failure would be useful, however I will still provide an Example:

My test environment is not always stable, so my tests might fail unexpectedly at any moment (there's no specific place I can try to catch the exception since it could occur at any time). When this happens I need the test to reschedule for another attempt, and log the incident so that we can get some good statistical data on the environment instability (when, how frequent, how long etc.)

答:
After a lot of experimentation I now removed the Before/After-Annotations and rely on Cucumber-Events instead. They contain the TestCase (which is what the Scenario-class wraps) and a Result where you can call getError(); to get the Throwable.

Here is a simple example to get it working

```<code>import io.cucumber.plugin.EventListener;
import io.cucumber.plugin.event.EventPublisher;
import io.cucumber.plugin.event.Result;
import io.cucumber.plugin.event.Status;
import io.cucumber.plugin.event.TestCase;
import io.cucumber.plugin.event.TestCaseFinished;
import io.cucumber.plugin.event.TestCaseStarted;
import org.openqa.selenium.WebDriver;

public class TestCaseListener implements EventListener {
    @Override
    public void setEventPublisher(final EventPublisher publisher) {
        publisher.registerHandlerFor(TestCaseStarted.class, this::onTestCaseStarted);
        publisher.registerHandlerFor(TestCaseFinished.class, this::onTestCaseFinished);
    }

    public void onTestCaseStarted(TestCaseStarted event) {
        TestCase testCase = event.getTestCase();
        System.out.println("Starting " + testCase.getName());

        // Other stuff you did in your @Before-Method.
        // ...
    }

    private void onTestCaseFinished(final TestCaseFinished event) {
        TestCase testCase = event.getTestCase();
        System.out.println("Finished " + testCase.getName());

        Result result = event.getResult();
        if (result.getStatus() == Status.FAILED) {
            final Throwable error = result.getError();
            error.printStackTrace();
        }

        // Other stuff you did in your @After-Method.
        // ...
    }
}
</code>```

All that's left to do is to register this class as a Cucumber-Plugin.
I did this by modifying my @CucumberOptions-annotation:

```<code>@CucumberOptions(plugin = {"com.example.TestCaseListener"})
</code>```

I find this much cleaner than all of this reflection-madness, however it requires a lot more code-changes.

Edit

I don't know why, but this caused a lot of tests to randomly fail in a multithreaded environment.
I tried to figure it out, but now also use the ugly reflections mentioned in this thread:

```<code>public class SeleniumUtils {
private static final Logger log = LoggerFactory.getLogger(SeleniumUtils.class);

private static final Field field = FieldUtils.getField(Scenario.class, "delegate", true);
private static Method getError;

public static Throwable getError(Scenario scenario) {
    try {
        final TestCaseState testCase = (TestCaseState) field.get(scenario);
        if (getError == null) {
            getError = MethodUtils.getMatchingMethod(testCase.getClass(), "getError");
            getError.setAccessible(true);
        }
        return (Throwable) getError.invoke(testCase);
    } catch (Exception e) {
        log.warn("error receiving exception", e);
    }
    return null;
}
}
</code>```

Body:
I can perform actions on test failure by using:

@After
public void afterTest(Scenario scenario) {
    if (scenario.isFailed()) {
        /*Do stuff*/
    }
}

However some of the actions I need to perform depend on the Exception that was thrown and in what context it was thrown. Is there a way to get the Throwable that caused the test to fail? For example in JUnit I would do this by extending TestWatcher and add a rule to my tests:

@Override
protected void failed(Throwable e, Description description) {
    /*Do stuff with e*/
}

However the cucumber-junit iplementation does not allow the use of rules, so this solution would not work with Cucumber.

I don't think I need to explain why accessing a thrown exception on test failure would be useful, however I will still provide an Example:

My test environment is not always stable, so my tests might fail unexpectedly at any moment (there's no specific place I can try to catch the exception since it could occur at any time). When this happens I need the test to reschedule for another attempt, and log the incident so that we can get some good statistical data on the environment instability (when, how frequent, how long etc.)

Body:
After a lot of experimentation I now removed the Before/After-Annotations and rely on Cucumber-Events instead. They contain the TestCase (which is what the Scenario-class wraps) and a Result where you can call getError(); to get the Throwable.

Here is a simple example to get it working

import io.cucumber.plugin.EventListener;
import io.cucumber.plugin.event.EventPublisher;
import io.cucumber.plugin.event.Result;
import io.cucumber.plugin.event.Status;
import io.cucumber.plugin.event.TestCase;
import io.cucumber.plugin.event.TestCaseFinished;
import io.cucumber.plugin.event.TestCaseStarted;
import org.openqa.selenium.WebDriver;

public class TestCaseListener implements EventListener {
    @Override
    public void setEventPublisher(final EventPublisher publisher) {
        publisher.registerHandlerFor(TestCaseStarted.class, this::onTestCaseStarted);
        publisher.registerHandlerFor(TestCaseFinished.class, this::onTestCaseFinished);
    }

    public void onTestCaseStarted(TestCaseStarted event) {
        TestCase testCase = event.getTestCase();
        System.out.println("Starting " + testCase.getName());

        // Other stuff you did in your @Before-Method.
        // ...
    }

    private void onTestCaseFinished(final TestCaseFinished event) {
        TestCase testCase = event.getTestCase();
        System.out.println("Finished " + testCase.getName());

        Result result = event.getResult();
        if (result.getStatus() == Status.FAILED) {
            final Throwable error = result.getError();
            error.printStackTrace();
        }

        // Other stuff you did in your @After-Method.
        // ...
    }
}

All that's left to do is to register this class as a Cucumber-Plugin.
I did this by modifying my @CucumberOptions-annotation:

@CucumberOptions(plugin = {"com.example.TestCaseListener"})

I find this much cleaner than all of this reflection-madness, however it requires a lot more code-changes.

Edit

I don't know why, but this caused a lot of tests to randomly fail in a multithreaded environment.
I tried to figure it out, but now also use the ugly reflections mentioned in this thread:

public class SeleniumUtils {
private static final Logger log = LoggerFactory.getLogger(SeleniumUtils.class);

private static final Field field = FieldUtils.getField(Scenario.class, "delegate", true);
private static Method getError;

public static Throwable getError(Scenario scenario) {
    try {
        final TestCaseState testCase = (TestCaseState) field.get(scenario);
        if (getError == null) {
            getError = MethodUtils.getMatchingMethod(testCase.getClass(), "getError");
            getError.setAccessible(true);
        }
        return (Throwable) getError.invoke(testCase);
    } catch (Exception e) {
        log.warn("error receiving exception", e);
    }
    return null;
}
}


问:
Gaussian Mixture Model cross-validation
I'd like to cross-validate my gaussian mixture model. Currently I use sklearn's cross_validation method as below.

```<code>clf = GaussianMixture(n_components=len(np.unique(y)), covariance_type='full')
cv_ortho = cross_validate(clf, parameters_train, y, cv=10, n_jobs=-1, scoring=scorer)
</code>```

I see that cross_validation is training my classifier with y_train making it a supervised classifier.

```<code>try:
    if y_train is None:
        estimator.fit(X_train, **fit_params)
    else:
        estimator.fit(X_train, y_train, **fit_params)
</code>```

However, I wanted to cross-validate an unsupervised classifier clf.fit(parameters_train). I understand that the classifier then assigns its own class labels. Since, I have two distinguished clusters (see image) and y I can decipher the corresponding labels. Then cross-validate. Is there a routine in sklearn which does this?

A routine similar to this example: https://scikit-learn.org/stable/auto_examples/mixture/plot_gmm_covariances.html

答:
It seems that typical cross-validation is not something that either makes sense or has been used for unsupervised learning (see this question of Cross Validated Stack Exchange).

Why it does not make sense?

In the strict case, cross validation requires some ground truth about the "correct" labels or values provided by the model. Typically denoted as the y in scikit-learn methods definition.
When you are training in an unsupervised way the sheer notion of the training not being supervised means that there are no y labels; no true labels, no "ground truth".
This is raised also in this answer of a question on evaluation of unsupervised learning (which is a broader term than cross-validation).

Title: Gaussian Mixture Model cross-validation

Body:
I'd like to cross-validate my gaussian mixture model. Currently I use sklearn's cross_validation method as below.

clf = GaussianMixture(n_components=len(np.unique(y)), covariance_type='full')
cv_ortho = cross_validate(clf, parameters_train, y, cv=10, n_jobs=-1, scoring=scorer)

I see that cross_validation is training my classifier with y_train making it a supervised classifier.

try:
    if y_train is None:
        estimator.fit(X_train, **fit_params)
    else:
        estimator.fit(X_train, y_train, **fit_params)

However, I wanted to cross-validate an unsupervised classifier clf.fit(parameters_train). I understand that the classifier then assigns its own class labels. Since, I have two distinguished clusters (see image) and y I can decipher the corresponding labels. Then cross-validate. Is there a routine in sklearn which does this?

A routine similar to this example: https://scikit-learn.org/stable/auto_examples/mixture/plot_gmm_covariances.html


问:
Group objects by one of its params with javascript
Basically I would want to transform this

```<code>[
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
]
</code>```

To this where every object with the key of  0 would go into the first array and every object with the key of 1 would go into the second array.

```<code>[
  [
    { key: 0, name: 'Some name' },
    { key: 0, name: 'Some name' },
  ],
  [
    { key: 1, name: 'Some name' },
    { key: 1, name: 'Some name' },
  ],
];
</code>```

Would really not mind using lodash for this but couldn't find the correct array method.

答:
```<code>var array = [
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
];
array.sort(function(a,b){return a.key - b.key})
var temp = array[0].key;
var newArray = [];
var tempArray =[];
for(var i=0;i<array.length;i++){
    if(temp != array[i].key){
        newArray.push(tempArray);
        tempArray =[];
        temp = array[i].key;
    }
    tempArray.push(array[i]);
}
newArray.push(tempArray);
</code>```

Body:
Basically I would want to transform this

[
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
]

To this where every object with the key of  0 would go into the first array and every object with the key of 1 would go into the second array.

[
  [
    { key: 0, name: 'Some name' },
    { key: 0, name: 'Some name' },
  ],
  [
    { key: 1, name: 'Some name' },
    { key: 1, name: 'Some name' },
  ],
];

Would really not mind using lodash for this but couldn't find the correct array method.


问:
How to set default clouse param in View method?
I tried to set else default param in ifLet method but I face an error: Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements. What did wrong?

extension View {
    func ifLet<Value, Then: View, Else: View>(
        _ value: Value?,
        then: (Value) -> Then,
        else: () -> View = { EmptyView() }
    ) -> _ConditionalContent<Then, Else> {
        if let value = value {
            return ViewBuilder.buildEither(first: then(value))
        } else {
            return ViewBuilder.buildEither(second: `else`())
        }
    }
}
```

<p>Using:</p>

<pre class="lang-swift prettyprint-override"><code>struct TestView: View {
    var test: String?

    var body: some View {
        Group {
            ifLet(test) { Text($0) }
            ifLet(test, then: { Text($0) }, else: { Text("Empty") })
        }
    }
}
</code>```

The best solution without using the unofficial _ConditionalContent that might be changed or removed in the future check out here

答:
Here is possible approach. Tested & works with Xcode 11.2 / iOS 13.2.</p>

```<code>struct TestingIfLet: View {
    var some: String?
    var body: some View {
        VStack {
            ifLet(some, then: {value in Text("Test1 \(value)") })
            ifLet(some, then: {value in Text("Test2 \(value)") },
                else: { Text("Test3") })
        }
    }
}

extension View {

    func ifLet<Value, Then: View>(
        _ value: Value?,
        then: (Value) -> Then
    ) -> _ConditionalContent<Then, EmptyView> {
        if let value = value {
            return ViewBuilder.buildEither(first: then(value))
        } else {
            return ViewBuilder.buildEither(second: EmptyView())
        }
    }

    func ifLet<Value, Then: View, Else: View>(
        _ value: Value?,
        then: (Value) -> Then,
        else: () -> Else
    ) -> _ConditionalContent<Then, Else> {
        if let value = value {
            return ViewBuilder.buildEither(first: then(value))
        } else {
            return ViewBuilder.buildEither(second: `else`())
        }
    }
}
</code>```

Body:
I tried to set else default param in ifLet method but I face an error: Protocol 'View' can only be used as a generic constraint because it has Self or associated type requirements. What did wrong?

extension View {
    func ifLet<Value, Then: View, Else: View>(
        _ value: Value?,
        then: (Value) -> Then,
        else: () -> View = { EmptyView() }
    ) -> _ConditionalContent<Then, Else> {
        if let value = value {
            return ViewBuilder.buildEither(first: then(value))
        } else {
            return ViewBuilder.buildEither(second: `else`())
        }
    }
}

Using:

struct TestView: View {
    var test: String?

    var body: some View {
        Group {
            ifLet(test) { Text($0) }
            ifLet(test, then: { Text($0) }, else: { Text("Empty") })
        }
    }
}

The best solution without using the unofficial _ConditionalContent that might be changed or removed in the future check out here

Body:
Here is possible approach. Tested & works with Xcode 11.2 / iOS 13.2.

struct TestingIfLet: View {
    var some: String?
    var body: some View {
        VStack {
            ifLet(some, then: {value in Text("Test1 \(value)") })
            ifLet(some, then: {value in Text("Test2 \(value)") },
                else: { Text("Test3") })
        }
    }
}

extension View {

    func ifLet<Value, Then: View>(
        _ value: Value?,
        then: (Value) -> Then
    ) -> _ConditionalContent<Then, EmptyView> {
        if let value = value {
            return ViewBuilder.buildEither(first: then(value))
        } else {
            return ViewBuilder.buildEither(second: EmptyView())
        }
    }

    func ifLet<Value, Then: View, Else: View>(
        _ value: Value?,
        then: (Value) -> Then,
        else: () -> Else
    ) -> _ConditionalContent<Then, Else> {
        if let value = value {
            return ViewBuilder.buildEither(first: then(value))
        } else {
            return ViewBuilder.buildEither(second: `else`())
        }
    }
}


问:
Call a method for List in parallel?
I must iterate over an list and call for every object a method, but in parallel. After the loop, there other statements, which must wait for the parallel method invocations. How can I do that in JAVA? </p>

```<code>public void a(List<Object> list) {
    for(Object o : list) {
        asynchMethod(o); // this n method call must run in the same time
    }

    // wait for all asynchMethod result
    /**
     * ...other statements
     */
}

private void asynchMethod(Object o) {
    // some code
}
</code>```

答:
Use CompletableFuture.

```<code>CompletableFuture.allOf(list.stream()
  .map(i -> CompletableFuture.submit(o -> asyncMethod(I))
  .toArray()))
     .join();
</code>```

Title: Call a method for List in parallel?

Body:
I must iterate over an list and call for every object a method, but in parallel. After the loop, there other statements, which must wait for the parallel method invocations. How can I do that in JAVA?

public void a(List<Object> list) {
    for(Object o : list) {
        asynchMethod(o); // this n method call must run in the same time
    }

    // wait for all asynchMethod result
    /**
     * ...other statements
     */
}

private void asynchMethod(Object o) {
    // some code
}

Body:
Use CompletableFuture.

CompletableFuture.allOf(list.stream()
  .map(i -> CompletableFuture.submit(o -> asyncMethod(I))
  .toArray()))
     .join();


问:
How can peer admin create a channel when it does not have permissions to write to orderer?
In all of the fabric-samples the creation of a channel is done by a peer admin user. However this user does not even have permissions to write to the orderer. So how can it succeed? Taking a specific example of first-network:

```<code>- CORE_PEER_LOCALMSPID=Org1MSP
- CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp
</code>```

so the channel creation is executed under org1's admin credentials. But when we look at configtx.yaml:

```<code> - &OrdererOrg
        # DefaultOrg defines the organization which is used in the sampleconfig
        # of the fabric.git development environment
        Name: OrdererOrg

        # ID to load the MSP definition as
        ID: OrdererMSP

        # MSPDir is the filesystem path which contains the MSP configuration
        MSPDir: crypto-config/ordererOrganizations/example.com/msp

        # Policies defines the set of policies at this level of the config tree
        # For organization policies, their canonical path is usually
        #   /Channel/<Application|Orderer>/<OrgName>/<PolicyName>
        Policies:
            Readers:
                Type: Signature
                Rule: "OR('OrdererMSP.member')"
            Writers:
                Type: Signature
                Rule: "OR('OrdererMSP.member')"
            Admins:
                Type: Signature
                Rule: "OR('OrdererMSP.admin')"
</code>```

in order to write to the orderer one has to be OrdererMSP.member which clearly org1's admin is not. So how can it pass the policy check?

When we try to develop an application using the pattern in fabric-samples, we get error while trying to create a channel under peer admin credentials:

```<code>2019-03-12 17:05:09.337 UTC [orderer/common/msgprocessor] ProcessConfigUpdateMsg -> DEBU 0d9 Processing config update message for channel dscsa
2019-03-12 17:05:09.337 UTC [policies] Evaluate -> DEBU 0da == Evaluating *policies.implicitMetaPolicy Policy /Channel/Writers ==
2019-03-12 17:05:09.337 UTC [policies] Evaluate -> DEBU 0db This is an implicit meta policy, it will trigger other policy evaluations, whose failures may be benign
2019-03-12 17:05:09.337 UTC [policies] Evaluate -> DEBU 0dc == Evaluating *policies.implicitMetaPolicy Policy /Channel/Orderer/Writers ==
2019-03-12 17:05:09.337 UTC [policies] Evaluate -> DEBU 0dd This is an implicit meta policy, it will trigger other policy evaluations, whose failures may be benign
2019-03-12 17:05:09.337 UTC [policies] Evaluate -> DEBU 0de == Evaluating *cauthdsl.policy Policy /Channel/Orderer/ord/Writers ==
2019-03-12 17:05:09.337 UTC [msp] DeserializeIdentity -> DEBU 0df Obtaining identity
2019-03-12 17:05:09.337 UTC [msp/identity] newIdentity -> DEBU 0e0 Creating identity instance for cert -----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
2019-03-12 17:05:09.338 UTC [cauthdsl] func1 -> DEBU 0e1 0xc42000e1e8 gate 1552410309337999686 evaluation starts
2019-03-12 17:05:09.338 UTC [cauthdsl] func2 -> DEBU 0e2 0xc42000e1e8 signed by 0 principal evaluation starts (used [false])
2019-03-12 17:05:09.338 UTC [cauthdsl] func2 -> DEBU 0e3 0xc42000e1e8 processing identity 0 with bytes of ...
2019-03-12 17:05:09.338 UTC [cauthdsl] func2 -> DEBU 0e4 0xc42000e1e8 identity 0 does not satisfy principal: the identity is a member of a different MSP (expected ordMSP, got org1MSP)
2019-03-12 17:05:09.338 UTC [cauthdsl] func2 -> DEBU 0e5 0xc42000e1e8 principal evaluation fails
2019-03-12 17:05:09.338 UTC [cauthdsl] func1 -> DEBU 0e6 0xc42000e1e8 gate 1552410309337999686 evaluation fails
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0e7 Signature set did not satisfy policy /Channel/Orderer/ord/Writers
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0e8 == Done Evaluating *cauthdsl.policy Policy /Channel/Orderer/ord/Writers
2019-03-12 17:05:09.338 UTC [policies] func1 -> DEBU 0e9 Evaluation Failed: Only 0 policies were satisfied, but needed 1 of [ ord.Writers ]
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0ea Signature set did not satisfy policy /Channel/Orderer/Writers
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0eb == Done Evaluating *policies.implicitMetaPolicy Policy /Channel/Orderer/Writers
2019-03-12 17:05:09.338 UTC [policies] func1 -> DEBU 0ec Evaluation Failed: Only 0 policies were satisfied, but needed 1 of [ Orderer.Writers Consortiums.Writers ]
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0ed Signature set did not satisfy policy /Channel/Writers
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0ee == Done Evaluating *policies.implicitMetaPolicy Policy /Channel/Writers
2019-03-12 17:05:09.338 UTC [orderer/common/broadcast] Handle -> WARN 0ef [channel: dscsa] Rejecting broadcast of config message from 10.0.0.192:54232 because of error: Failed to reach implicit threshold of 1 sub-policies, required 1 remaining: permission denied
</code>```

答:
I hope you got your answer by now as it is 11 months old question. If not, here is my explanation. The policies for Orderer org is to read, make changes to the Orderer organization/ orderer system channel. Not to the application channels. Ord1 admin can make changes as that is defined in the Application section's policies of confitx.yaml which is ImplecitMeta constructed from the participating Orgs's Signature policies.

I hope it helps.

Body:
In all of the fabric-samples the creation of a channel is done by a peer admin user. However this user does not even have permissions to write to the orderer. So how can it succeed? Taking a specific example of first-network:

- CORE_PEER_LOCALMSPID=Org1MSP
- CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp

so the channel creation is executed under org1's admin credentials. But when we look at configtx.yaml:

 - &OrdererOrg
        # DefaultOrg defines the organization which is used in the sampleconfig
        # of the fabric.git development environment
        Name: OrdererOrg

        # ID to load the MSP definition as
        ID: OrdererMSP

        # MSPDir is the filesystem path which contains the MSP configuration
        MSPDir: crypto-config/ordererOrganizations/example.com/msp

        # Policies defines the set of policies at this level of the config tree
        # For organization policies, their canonical path is usually
        #   /Channel/<Application|Orderer>/<OrgName>/<PolicyName>
        Policies:
            Readers:
                Type: Signature
                Rule: "OR('OrdererMSP.member')"
            Writers:
                Type: Signature
                Rule: "OR('OrdererMSP.member')"
            Admins:
                Type: Signature
                Rule: "OR('OrdererMSP.admin')"

in order to write to the orderer one has to be OrdererMSP.member which clearly org1's admin is not. So how can it pass the policy check?

When we try to develop an application using the pattern in fabric-samples, we get error while trying to create a channel under peer admin credentials:

2019-03-12 17:05:09.337 UTC [orderer/common/msgprocessor] ProcessConfigUpdateMsg -> DEBU 0d9 Processing config update message for channel dscsa
2019-03-12 17:05:09.337 UTC [policies] Evaluate -> DEBU 0da == Evaluating *policies.implicitMetaPolicy Policy /Channel/Writers ==
2019-03-12 17:05:09.337 UTC [policies] Evaluate -> DEBU 0db This is an implicit meta policy, it will trigger other policy evaluations, whose failures may be benign
2019-03-12 17:05:09.337 UTC [policies] Evaluate -> DEBU 0dc == Evaluating *policies.implicitMetaPolicy Policy /Channel/Orderer/Writers ==
2019-03-12 17:05:09.337 UTC [policies] Evaluate -> DEBU 0dd This is an implicit meta policy, it will trigger other policy evaluations, whose failures may be benign
2019-03-12 17:05:09.337 UTC [policies] Evaluate -> DEBU 0de == Evaluating *cauthdsl.policy Policy /Channel/Orderer/ord/Writers ==
2019-03-12 17:05:09.337 UTC [msp] DeserializeIdentity -> DEBU 0df Obtaining identity
2019-03-12 17:05:09.337 UTC [msp/identity] newIdentity -> DEBU 0e0 Creating identity instance for cert -----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
2019-03-12 17:05:09.338 UTC [cauthdsl] func1 -> DEBU 0e1 0xc42000e1e8 gate 1552410309337999686 evaluation starts
2019-03-12 17:05:09.338 UTC [cauthdsl] func2 -> DEBU 0e2 0xc42000e1e8 signed by 0 principal evaluation starts (used [false])
2019-03-12 17:05:09.338 UTC [cauthdsl] func2 -> DEBU 0e3 0xc42000e1e8 processing identity 0 with bytes of ...
2019-03-12 17:05:09.338 UTC [cauthdsl] func2 -> DEBU 0e4 0xc42000e1e8 identity 0 does not satisfy principal: the identity is a member of a different MSP (expected ordMSP, got org1MSP)
2019-03-12 17:05:09.338 UTC [cauthdsl] func2 -> DEBU 0e5 0xc42000e1e8 principal evaluation fails
2019-03-12 17:05:09.338 UTC [cauthdsl] func1 -> DEBU 0e6 0xc42000e1e8 gate 1552410309337999686 evaluation fails
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0e7 Signature set did not satisfy policy /Channel/Orderer/ord/Writers
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0e8 == Done Evaluating *cauthdsl.policy Policy /Channel/Orderer/ord/Writers
2019-03-12 17:05:09.338 UTC [policies] func1 -> DEBU 0e9 Evaluation Failed: Only 0 policies were satisfied, but needed 1 of [ ord.Writers ]
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0ea Signature set did not satisfy policy /Channel/Orderer/Writers
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0eb == Done Evaluating *policies.implicitMetaPolicy Policy /Channel/Orderer/Writers
2019-03-12 17:05:09.338 UTC [policies] func1 -> DEBU 0ec Evaluation Failed: Only 0 policies were satisfied, but needed 1 of [ Orderer.Writers Consortiums.Writers ]
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0ed Signature set did not satisfy policy /Channel/Writers
2019-03-12 17:05:09.338 UTC [policies] Evaluate -> DEBU 0ee == Done Evaluating *policies.implicitMetaPolicy Policy /Channel/Writers
2019-03-12 17:05:09.338 UTC [orderer/common/broadcast] Handle -> WARN 0ef [channel: dscsa] Rejecting broadcast of config message from 10.0.0.192:54232 because of error: Failed to reach implicit threshold of 1 sub-policies, required 1 remaining: permission denied


问:
ChartJs: X Axis labels cutting at bottom
I am creating vertical x axis labels however the labels cut off at bottom on mobile device:

my code is as follows:

```<code>window.chartColors = {
    red: 'rgb(255, 99, 132)',
    orange: 'rgb(255, 159, 64)',
    yellow: 'rgb(255, 205, 86)',
    green: 'rgb(51, 204, 51)',
    blue: 'rgb(54, 162, 235)',
    purple: 'rgb(153, 102, 255)',
    grey: 'rgb(201, 203, 207)'
};

var options2 = {
type: 'line',
data: {
    labels: ["02/07/2020 8:01", "02/07/2020 13:00", "02/07/2020 17:00", "02/07/2020 22:00", "02/08/2020 8:01", "02/08/2020 13:01", "02/08/2020 17:00", "02/08/2020 22:00", "02/09/2020 8:01", "02/09/2020 13:00", "02/09/2020 17:00", "02/09/2020 22:00"],
    datasets: [
        {
            label: 'Water Level',
            data: [13.534,13.652,13.298,13.062,11.763,13.613,13.534,12.629,11.369,13.495,13.574,13.456],
            borderWidth: 1,
            lineTension: 0,
            fill: false,
            backgroundColor: window.chartColors.blue,
            borderColor: window.chartColors.blue,
        }
    ],
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: false
        }
      }]
    }
},
options: {
    legend: {
        position: 'bottom',
        display: false
    },
    responsive: true,
    bezierCurve: false,
    scales: {
        xAxes: [{
            ticks: {
                autoSkip: true,
                maxRotation: 90,
                minRotation: 90
            }
        }],
        yAxes: [{
            ticks: {
              min: 0,
              max: 36,
              stepSize: 10
            },
            scaleLabel: {
              display: true,
              labelString: 'inches'
            }
        }]
    },
    backgroundRules: [{
        backgroundColor: window.chartColors.green,
        yAxisSegement: 6
    }, {
        backgroundColor: window.chartColors.grey,
        yAxisSegement: 12
    }, {
        backgroundColor: window.chartColors.red,
        yAxisSegement: 999999
    }]
},
plugins: [{
    beforeDraw: function (chart) {
        var rules = chart.chart.options.backgroundRules;
        var ctx = chart.chart.ctx;
        var yAxis = chart.chart.scales["y-axis-0"];
        var xaxis = chart.chart.scales["x-axis-0"];
        for (var i = 0; i < rules.length; ++i) {
            var yAxisSegement = (rules[i].yAxisSegement > yAxis.ticksAsNumbers[0] ? yAxis.ticksAsNumbers[0] : rules[i].yAxisSegement);
            var yAxisPosStart = yAxis.height - ((yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]) + chart.chart.controller.chartArea.top;
            var yAxisPosEnd = (i === 0 ? yAxis.height : yAxis.height - ((rules[i - 1].yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]));
            ctx.fillStyle = rules[i].backgroundColor;
            ctx.fillRect(xaxis.left, yAxisPosStart, xaxis.width, yAxisPosEnd - yAxisPosStart + chart.chart.controller.chartArea.top);
        }
    }
}]
};

var ctx2 = document.getElementById('chart2').getContext('2d');
var chart2 = new Chart(ctx2, options2);
</code>```

Fiddle: https://jsfiddle.net/nitinjs/3nkwbeh0/10/

help

update

to replicate in firefox press CTRL + shift + m

答:
If you add this option to your chart options it will solve the problem:

```<code>maintainAspectRatio: false,
</code>```

full javscript (added code at line 40):

window.chartColors = {
  red: 'rgb(255, 99, 132)',
  orange: 'rgb(255, 159, 64)',
  yellow: 'rgb(255, 205, 86)',
  green: 'rgb(51, 204, 51)',
  blue: 'rgb(54, 162, 235)',
  purple: 'rgb(153, 102, 255)',
  grey: 'rgb(201, 203, 207)'
};

var options2 = {
  type: 'line',
  data: {
    labels: ["02/07/2020 8:01", "02/07/2020 13:00", "02/07/2020 17:00", "02/07/2020 22:00", "02/08/2020 8:01", "02/08/2020 13:01", "02/08/2020 17:00", "02/08/2020 22:00", "02/09/2020 8:01", "02/09/2020 13:00", "02/09/2020 17:00", "02/09/2020 22:00"],
    datasets: [
      {
        label: 'Water Level',
        data: [13.534,13.652,13.298,13.062,11.763,13.613,13.534,12.629,11.369,13.495,13.574,13.456],
        borderWidth: 1,
        lineTension: 0,
        fill: false,
        backgroundColor: window.chartColors.blue,
        borderColor: window.chartColors.blue,
      }
    ],
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: false
        }
      }]
    }
  },
  options: {
    legend: {
      position: 'bottom',
      display: false
    },
    maintainAspectRatio: false,  // <--- THIS LINE WAS ADDED
    responsive: true,
    bezierCurve: false,
    scales: {
      xAxes: [{
        ticks: {
          autoSkip: true,
          maxRotation: 90,
          minRotation: 90
        }
      }],
      yAxes: [{
        ticks: {
          min: 0,
          max: 36,
          stepSize: 10
        },
        scaleLabel: {
          display: true,
          labelString: 'inches'
        }
      }]
    }
  },
  plugins: []
};
var ctx2 = document.getElementById('chart2').getContext('2d');
var chart2 = new Chart(ctx2, options2);

function RefreshGraph2() {
  console.log(chart2);
  var dt2 = {
    serial: "310021000e51353532343635",
    from: $("#txtFrom2").val(),
    to: $("#txtTo2").val()
  };

  $.post("/Mobile/GetGraphData", dt2, function(data) {
    var labels2 = _.pluck(data.result, 'createdAtLabel');
    var values2 = _.pluck(data.result, 'waterLevel');
    chart2.data.labels = labels2;
    chart2.data.datasets[0].data = values2;
    console.log(labels2);
    console.log(values2);
    //chart2.data.datasets[0].data = data.result;
    chart2.update();
    return false;
  });
}

$(document).ready(function () {
  $("#btnRefresh2").on("click", function () {
    RefreshGraph2();
    return false;
  });
});
```

JSFiddle

Body:
I am creating vertical x axis labels however the labels cut off at bottom on mobile device:

my code is as follows:

window.chartColors = {
    red: 'rgb(255, 99, 132)',
    orange: 'rgb(255, 159, 64)',
    yellow: 'rgb(255, 205, 86)',
    green: 'rgb(51, 204, 51)',
    blue: 'rgb(54, 162, 235)',
    purple: 'rgb(153, 102, 255)',
    grey: 'rgb(201, 203, 207)'
};

var options2 = {
type: 'line',
data: {
    labels: ["02/07/2020 8:01", "02/07/2020 13:00", "02/07/2020 17:00", "02/07/2020 22:00", "02/08/2020 8:01", "02/08/2020 13:01", "02/08/2020 17:00", "02/08/2020 22:00", "02/09/2020 8:01", "02/09/2020 13:00", "02/09/2020 17:00", "02/09/2020 22:00"],
    datasets: [
        {
            label: 'Water Level',
            data: [13.534,13.652,13.298,13.062,11.763,13.613,13.534,12.629,11.369,13.495,13.574,13.456],
            borderWidth: 1,
            lineTension: 0,
            fill: false,
            backgroundColor: window.chartColors.blue,
            borderColor: window.chartColors.blue,
        }
    ],
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: false
        }
      }]
    }
},
options: {
    legend: {
        position: 'bottom',
        display: false
    },
    responsive: true,
    bezierCurve: false,
    scales: {
        xAxes: [{
            ticks: {
                autoSkip: true,
                maxRotation: 90,
                minRotation: 90
            }
        }],
        yAxes: [{
            ticks: {
              min: 0,
              max: 36,
              stepSize: 10
            },
            scaleLabel: {
              display: true,
              labelString: 'inches'
            }
        }]
    },
    backgroundRules: [{
        backgroundColor: window.chartColors.green,
        yAxisSegement: 6
    }, {
        backgroundColor: window.chartColors.grey,
        yAxisSegement: 12
    }, {
        backgroundColor: window.chartColors.red,
        yAxisSegement: 999999
    }]
},
plugins: [{
    beforeDraw: function (chart) {
        var rules = chart.chart.options.backgroundRules;
        var ctx = chart.chart.ctx;
        var yAxis = chart.chart.scales["y-axis-0"];
        var xaxis = chart.chart.scales["x-axis-0"];
        for (var i = 0; i < rules.length; ++i) {
            var yAxisSegement = (rules[i].yAxisSegement > yAxis.ticksAsNumbers[0] ? yAxis.ticksAsNumbers[0] : rules[i].yAxisSegement);
            var yAxisPosStart = yAxis.height - ((yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]) + chart.chart.controller.chartArea.top;
            var yAxisPosEnd = (i === 0 ? yAxis.height : yAxis.height - ((rules[i - 1].yAxisSegement * yAxis.height) / yAxis.ticksAsNumbers[0]));
            ctx.fillStyle = rules[i].backgroundColor;
            ctx.fillRect(xaxis.left, yAxisPosStart, xaxis.width, yAxisPosEnd - yAxisPosStart + chart.chart.controller.chartArea.top);
        }
    }
}]
};

var ctx2 = document.getElementById('chart2').getContext('2d');
var chart2 = new Chart(ctx2, options2);

Fiddle: https://jsfiddle.net/nitinjs/3nkwbeh0/10/

help

update

to replicate in firefox press CTRL + shift + m

Body:
If you add this option to your chart options it will solve the problem:

maintainAspectRatio: false,

full javscript (added code at line 40):

window.chartColors = {
  red: 'rgb(255, 99, 132)',
  orange: 'rgb(255, 159, 64)',
  yellow: 'rgb(255, 205, 86)',
  green: 'rgb(51, 204, 51)',
  blue: 'rgb(54, 162, 235)',
  purple: 'rgb(153, 102, 255)',
  grey: 'rgb(201, 203, 207)'
};

var options2 = {
  type: 'line',
  data: {
    labels: ["02/07/2020 8:01", "02/07/2020 13:00", "02/07/2020 17:00", "02/07/2020 22:00", "02/08/2020 8:01", "02/08/2020 13:01", "02/08/2020 17:00", "02/08/2020 22:00", "02/09/2020 8:01", "02/09/2020 13:00", "02/09/2020 17:00", "02/09/2020 22:00"],
    datasets: [
      {
        label: 'Water Level',
        data: [13.534,13.652,13.298,13.062,11.763,13.613,13.534,12.629,11.369,13.495,13.574,13.456],
        borderWidth: 1,
        lineTension: 0,
        fill: false,
        backgroundColor: window.chartColors.blue,
        borderColor: window.chartColors.blue,
      }
    ],
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: false
        }
      }]
    }
  },
  options: {
    legend: {
      position: 'bottom',
      display: false
    },
    maintainAspectRatio: false,  // <--- THIS LINE WAS ADDED
    responsive: true,
    bezierCurve: false,
    scales: {
      xAxes: [{
        ticks: {
          autoSkip: true,
          maxRotation: 90,
          minRotation: 90
        }
      }],
      yAxes: [{
        ticks: {
          min: 0,
          max: 36,
          stepSize: 10
        },
        scaleLabel: {
          display: true,
          labelString: 'inches'
        }
      }]
    }
  },
  plugins: []
};
var ctx2 = document.getElementById('chart2').getContext('2d');
var chart2 = new Chart(ctx2, options2);

function RefreshGraph2() {
  console.log(chart2);
  var dt2 = {
    serial: "310021000e51353532343635",
    from: $("#txtFrom2").val(),
    to: $("#txtTo2").val()
  };

  $.post("/Mobile/GetGraphData", dt2, function(data) {
    var labels2 = _.pluck(data.result, 'createdAtLabel');
    var values2 = _.pluck(data.result, 'waterLevel');
    chart2.data.labels = labels2;
    chart2.data.datasets[0].data = values2;
    console.log(labels2);
    console.log(values2);
    //chart2.data.datasets[0].data = data.result;
    chart2.update();
    return false;
  });
}

$(document).ready(function () {
  $("#btnRefresh2").on("click", function () {
    RefreshGraph2();
    return false;
  });
});

JSFiddle


问:
Call the "C++" Struct in C File
I have a problem, that I explain below code, How Can I call the C++ struct in C file without any error ?

I have a C++ library in my code, in the this library include this defines:

In the C++ library code example.h:

```<code>struct P_BRIDGE;

  typedef void  (*CALLBACK_ENABLE_TRAPPING)          (const struct P_BRIDGE* bridge, bool enable, unsigned int timestamp);
    struct S_CALLBACKS
    {
        CALLBACK_ENABLE_TRAPPING        enableTrapping;

    };
</code>```

And I want to call this struct in main.c file like this

```<code>    #include example.h
....
        extern P_CALLBACKS const p_callbacks;
          P_BRIDGE* bridge = NULL;
</code>```

`
 I have this error :

```<code>Src/main.c:175:24: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'const'
Src/main.c:176:3: error: unknown type name P_BRIDGE'
</code>```

答:
P_BRIDGE is a struct.  In C, the syntax for declaring a struct variable needs the word struct in front eg

```<code>struct P_BRIDGE* bridge = NULL;
</code>```

Title: Call the "C++" Struct in C File

Body:
I have a problem, that I explain below code, How Can I call the C++ struct in C file without any error ?

I have a C++ library in my code, in the this library include this defines:

In the C++ library code example.h:

struct P_BRIDGE;

  typedef void  (*CALLBACK_ENABLE_TRAPPING)          (const struct P_BRIDGE* bridge, bool enable, unsigned int timestamp);
    struct S_CALLBACKS
    {
        CALLBACK_ENABLE_TRAPPING        enableTrapping;

    };

And I want to call this struct in main.c file like this

    #include example.h
....
        extern P_CALLBACKS const p_callbacks;
          P_BRIDGE* bridge = NULL;

`
 I have this error :

Src/main.c:175:24: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'const'
Src/main.c:176:3: error: unknown type name P_BRIDGE'

Body:
P_BRIDGE is a struct.  In C, the syntax for declaring a struct variable needs the word struct in front eg

struct P_BRIDGE* bridge = NULL;


问:
The app that runs on my device is different to the preview
android java

button positioning

the display that runs up on my device is different to the preview. The width and height aren't fixed, and this is in ConstraintLayout. The problem is with the Button; I want it to appear lower than both TextViews. What should i change with my code? (I did try to google it, and look for an answer but couldn't find anything relevant except for the "absoluteX, absoluteY" code for the button)

```<code> <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

 <Button
   android:id="@+id/button_button_view"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textAllCaps="true"
   android:text="order"
   tools:layout_editor_absoluteY="100dp"
   tools:layout_editor_absoluteX="4dp"/>

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAllCaps="true"
    android:text="quantity"
    android:textSize="16sp"
    app:layout_constraintLeft_toLeftOf="parent"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    app:layout_constraintBottom_toBottomOf="@id/quantity_text_view"
    app:layout_constraintTop_toTopOf="@id/button_button_view"/>
</code>```

答:
You have to use properties to align the views

Vertical Alignments

layout_constraintTop_toBottomOf,layout_constraintBottom_toTopOf

Horizondal Alignments:

layout_constraintStart_toStartOf,layout_constraintEnd_toStartOf,layout_constraintStart_toEndOf

updated xml :

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_button_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="order"
        android:textAllCaps="true"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/text2" />

    <TextView
        android:id="@+id/quantity_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="quantity"
        android:textAllCaps="true"
        android:textSize="16sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/quantity_text_view" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
android java

button positioning

the display that runs up on my device is different to the preview. The width and height aren't fixed, and this is in ConstraintLayout. The problem is with the Button; I want it to appear lower than both TextViews. What should i change with my code? (I did try to google it, and look for an answer but couldn't find anything relevant except for the "absoluteX, absoluteY" code for the button)

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

 <Button
   android:id="@+id/button_button_view"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textAllCaps="true"
   android:text="order"
   tools:layout_editor_absoluteY="100dp"
   tools:layout_editor_absoluteX="4dp"/>

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAllCaps="true"
    android:text="quantity"
    android:textSize="16sp"
    app:layout_constraintLeft_toLeftOf="parent"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    app:layout_constraintBottom_toBottomOf="@id/quantity_text_view"
    app:layout_constraintTop_toTopOf="@id/button_button_view"/>

Body:
You have to use properties to align the views

Vertical Alignments

layout_constraintTop_toBottomOf,layout_constraintBottom_toTopOf

Horizondal Alignments:

layout_constraintStart_toStartOf,layout_constraintEnd_toStartOf,layout_constraintStart_toEndOf

updated xml :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button_button_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="order"
        android:textAllCaps="true"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/text2" />

    <TextView
        android:id="@+id/quantity_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="quantity"
        android:textAllCaps="true"
        android:textSize="16sp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/quantity_text_view" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Visual Studio 2008: how to pause the running program to see a variable value?
I have started a long loop, and i dont want to start it over (been running 3 hours now, i calculated it to run only 1 hour instead), and i am afraid that my program is working incorrectly because its taking so long. I was too stupid to actually output any state values for myself (i didnt think it would take 3 damn hours).

So, is there some way to spy one specific variable value while the program was launched from visual studio in "Release" mode?

答:
If the program was launched from Visual Studio it is possible that it already has a debugger (Visual Studio) attached to the process.

Visual Studio will have VCR/DVD looking buttons on the toolbar for Go, Stop, Pause, etc. Press the Stop button, or go into the Debug menu and choose Break All.


问:
-1103 Error Domain=NSURLErrorDomain Code=-1103 "resource exceeds maximum size" iOS 13
We are facing the following networking error when the response is somehow large(14kb) on iOS 13.

[-1103] Error Domain=NSURLErrorDomain Code=-1103 "resource exceeds maximum size"

As we are using Alamofire, this problem is treated as error result which breaks our treatments of the results.

The strange thing is that if we use NSURLSession directly, though this error is still seen from logging, we don't actually receive it in the callback of

```<code>session.dataTask(with: request) { value, response, error in ... }
</code>```

So the result can treated correctly.

This problem is never seen before. Anyone has got some idea on that ?

答:
I have face same issue and find out the solution.

You can't pass parameter in body while using GET.

Either use POST method if API support or pass it in URL like below.

AnyURL?Parameter=Value&Parameter=Value

Body:
We are facing the following networking error when the response is somehow large(14kb) on iOS 13.

[-1103] Error Domain=NSURLErrorDomain Code=-1103 "resource exceeds maximum size"

As we are using Alamofire, this problem is treated as error result which breaks our treatments of the results.

The strange thing is that if we use NSURLSession directly, though this error is still seen from logging, we don't actually receive it in the callback of

session.dataTask(with: request) { value, response, error in ... }

So the result can treated correctly.

This problem is never seen before. Anyone has got some idea on that ?


问:
Helm upgrade command fails for no apparent reason
I want to perform a helm upgrade on a GKE k8s cluster.

I am executing the following command

```<code>helm upgrade --force --tls --install --set master.installPlugins=[u'kubernetes:1.21.2', u'workflow-job:2.36', u'workflow-aggregator:2.6', u'credentials-binding:1.20', u'git:4.0.0'] --set master.tag=lts --set agent.tag=3.27-1 -f /org_files/tmp/kerkyra-jenkins/jenkins-values.yaml --namespace jenkins my-jenkins stable/jenkins
</code>```

However it fails with the following name:

Error: This command needs 2 arguments: release name, chart path

I do pass at the end of the command however both

release name: my-jenkins

chart path: stable/jenkins

Why is it failing?

答:
Assuming you're using helm3 it requires the 2 arguments before the flags.

```<code>Error: "helm upgrade" requires 2 arguments
Usage:  helm upgrade [RELEASE] [CHART] [flags]
</code>```

So this should then work:

```<code>helm upgrade my-jenkins stable/jenkins --force --tls --install --set master.installPlugins=[u'kubernetes:1.21.2', u'workflow-job:2.36', u'workflow-aggregator:2.6', u'credentials-binding:1.20', u'git:4.0.0'] --set master.tag=lts --set agent.tag=3.27-1 -f /org_files/tmp/kerkyra-jenkins/jenkins-values.yaml --namespace jenkins
</code>```

Update: Should be the same for helm 2

Body:
I want to perform a helm upgrade on a GKE k8s cluster.

I am executing the following command

helm upgrade --force --tls --install --set master.installPlugins=[u'kubernetes:1.21.2', u'workflow-job:2.36', u'workflow-aggregator:2.6', u'credentials-binding:1.20', u'git:4.0.0'] --set master.tag=lts --set agent.tag=3.27-1 -f /org_files/tmp/kerkyra-jenkins/jenkins-values.yaml --namespace jenkins my-jenkins stable/jenkins

However it fails with the following name:

Error: This command needs 2 arguments: release name, chart path

I do pass at the end of the command however both

release name: my-jenkins

chart path: stable/jenkins

Why is it failing?

Body:
Assuming you're using helm3 it requires the 2 arguments before the flags.

Error: "helm upgrade" requires 2 arguments
Usage:  helm upgrade [RELEASE] [CHART] [flags]

So this should then work:

helm upgrade my-jenkins stable/jenkins --force --tls --install --set master.installPlugins=[u'kubernetes:1.21.2', u'workflow-job:2.36', u'workflow-aggregator:2.6', u'credentials-binding:1.20', u'git:4.0.0'] --set master.tag=lts --set agent.tag=3.27-1 -f /org_files/tmp/kerkyra-jenkins/jenkins-values.yaml --namespace jenkins

Update: Should be the same for helm 2


问:
VBA Loop along a row
Is it possible to loop along a row?

I have a header row of dates, I want to loop through those dates and if one of the dates is earlier than todays date I want an action to copy the content of the cells below and paste the values to override the formulas in that column.

I've done loops down a column before but I'm really struggling doing it along a row. any help or guidance would be greatly appreciated.

Thanks in advance :)

答:
There are three methods to examine cells in a range

1  If you know the size you can use For Each

```<code>   Dim r as range
   For each r in Range("A1:F1")
       'r is assigned to each cell in range above in turn
   Next r
</code>```

(Or if the user highlights the range before hand you can use the Selection Property)

```<code>  For each r in Selection
</code>```

2  Or You can loop through using a For Next and Cells

```<code>    Dim x as long
    For x = 1 to 6
     If Cells(1,x) = "Some Value" Then
     End If
    Next x
</code>```

3  If you don't know the  end and just want to go till the next blank cell then use a Do Loop

```<code>   Dim r as Range
   Set r = Range("A1")
   Do
      'something
       Set r = r.Offset(0,1)  'move pointer right
    Loop Until r = ""
</code>```

Hope this helps

Title: VBA Loop along a row

Body:
There are three methods to examine cells in a range

1  If you know the size you can use For Each

   Dim r as range
   For each r in Range("A1:F1")
       'r is assigned to each cell in range above in turn
   Next r

(Or if the user highlights the range before hand you can use the Selection Property)

  For each r in Selection

2  Or You can loop through using a For Next and Cells

    Dim x as long
    For x = 1 to 6
     If Cells(1,x) = "Some Value" Then
     End If
    Next x

3  If you don't know the  end and just want to go till the next blank cell then use a Do Loop

   Dim r as Range
   Set r = Range("A1")
   Do
      'something
       Set r = r.Offset(0,1)  'move pointer right
    Loop Until r = ""

Hope this helps