问:
ApiGatewayV2 how to set the "Execution Role" via CloudFormation
I'm trying to setup websockets via API Gateway. When I try to make a connection I get the error Execution failed due to configuration error: Invalid permissions on Lambda function in my CloudWatch logs.

I have created AWS::IAM::Role resource in my CloudFormation and attached it as the Role in my AWS::Lambda::Function resource. But I think I need to attach it to the AWS::ApiGatewayV2::Integration but I don't see how.

When I look in the AWS Console, I see there is no Execution Role selected:

But I can't see how to add the role in CloudFormation. What am I missing?

Full CloudFormation:

---
AWSTemplateFormatVersion: '2010-09-09'
Description: Website S3 Hosted, API Gateway Backend
Parameters:
  DomainName:
    Type: String
    Description: The DNS name of an Amazon Route 53 hosted zone e.g. server.com
    AllowedPattern: '(?!-)[a-zA-Z0-9-.]{1,63}(?<!-)'
    ConstraintDescription: must be a valid DNS zone name.
  DiscordToken:
    Type: String
  DiscordChannelID:
    Type: String
  HostedZoneId:
    Type: String
  SSLARN:
    Description: Cloudfront SSL ARN (us-east-1)
    Type: String

Mappings:
  APIRegionMap:
    us-east-1:
      APIHostedZoneId: Z1UJRXOUMOOFQ8
    us-east-2:
      APIHostedZoneId: ZOJJZC49E0EPZ
    us-west-1:
      APIHostedZoneId: Z2MUQ32089INYE
    us-west-2:
      APIHostedZoneId: Z2OJLYMUO9EFXC

Resources:

  # SSL

  SSL:
    Type: AWS::CertificateManager::Certificate
    Properties:
      DomainName: !Ref DomainName
      DomainValidationOptions:
        - DomainName: !Join ['.', ['api', !Ref DomainName]]
          HostedZoneId: !Ref HostedZoneId
      SubjectAlternativeNames:
        - !Join ['.', ['*', !Ref DomainName]]
      ValidationMethod: DNS

  # DynamoDB Tables

  SocketTable:
    Type: AWS::DynamoDB::Table
    Properties:
      AttributeDefinitions:
        -
          AttributeName: connectionId
          AttributeType: S
      KeySchema:
        -
          AttributeName: connectionId
          KeyType: HASH
      BillingMode: PAY_PER_REQUEST
      TableName: clients

  # Lambda Items

  LambdaExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service: lambda.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: '/'
      Policies:
      - PolicyName: execution
        PolicyDocument:
          Statement:
          - Effect: Allow
            Action:
            - logs:CreateLogGroup
            - logs:CreateLogStream
            - logs:PutLogEvents
            Resource: '*'
          - Effect: Allow
            Action:
            - s3:GetObject
            - s3:PutObject
            - s3:ListBucket
            Resource: '*'
            Resource: '*'
          - Effect: Allow
            Action:
            - lambda:InvokeFunction
            Resource: '*'
          - Effect: Allow
            Action:
            - execute-api:Invoke
            - execute-api:ManageConnections
            Resource: '*'

  LambdaFunctionSocketServer:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: exports.handler = function (event, context, callback) { callback(null, event); };
      Handler: index.handler
      MemorySize: 1024
      Role: !GetAtt LambdaExecutionRole.Arn
      Runtime: nodejs12.x
      Timeout: 900
      Environment:
        Variables:
          DBTable: !Ref SocketTable
          DiscordToken: !Ref DiscordToken
          DiscordChannelID: !Ref DiscordChannelID

  # API Gateway Items

  WebSocketLoggingRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
        - Effect: Allow
          Principal:
            Service: apigateway.amazonaws.com
          Action:
          - sts:AssumeRole
      Path: '/'
      Policies:
      - PolicyName: execution
        PolicyDocument:
          Statement:
          - Effect: Allow
            Action:
            - logs:CreateLogGroup
            - logs:CreateLogStream
            - logs:DescribeLogGroups
            - logs:DescribeLogStreams
            - logs:PutLogEvents
            - logs:GetLogEvents
            - logs:FilterLogEvents
            Resource: '*'

  WebSocketAPI:
    Type: AWS::ApiGatewayV2::Api
    Properties:
      Name: !Join ['-', !Split ['.', !Join ['.', ['ws', !Ref DomainName]]]]
      ProtocolType: WEBSOCKET
      RouteSelectionExpression: "$request.body.action"

  WebSocketInteg:
    Type: AWS::ApiGatewayV2::Integration
    DependsOn:
      - LambdaFunctionSocketServer
    Properties:
      ApiId: !Ref WebSocketAPI
      Description: WebSocket Integration
      IntegrationType: AWS_PROXY
      IntegrationUri: !Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${LambdaFunctionSocketServer.Arn}/invocations'

  WebSocketConnectRoute:
    Type: AWS::ApiGatewayV2::Route
    Properties:
      ApiId: !Ref WebSocketAPI
      RouteKey: $connect
      AuthorizationType: NONE
      OperationName: ConnectRoute
      Target: !Join ['/', ['integrations', !Ref WebSocketInteg]]

  WebSocketDisconnectRoute:
    Type: AWS::ApiGatewayV2::Route
    Properties:
      ApiId: !Ref WebSocketAPI
      RouteKey: $disconnect
      AuthorizationType: NONE
      OperationName: DisconnectRoute
      Target: !Join ['/', ['integrations', !Ref WebSocketInteg]]

  WebSocketSendRoute:
    Type: AWS::ApiGatewayV2::Route
    Properties:
      ApiId: !Ref WebSocketAPI
      RouteKey: sendmessage
      AuthorizationType: NONE
      OperationName: SendRoute
      Target: !Join ['/', ['integrations', !Ref WebSocketInteg]]

  WebSocketDeployment:
    Type: AWS::ApiGatewayV2::Deployment
    DependsOn:
      - WebSocketConnectRoute
      - WebSocketSendRoute
      - WebSocketDisconnectRoute
    Properties:
      ApiId: !Ref WebSocketAPI

  WebSocketLogGroup:
    Type: AWS::Logs::LogGroup
    Properties:
      LogGroupName: !Join ['.', ['ws', !Ref DomainName]]
      RetentionInDays: 3

  WebSocketStage:
    Type: AWS::ApiGatewayV2::Stage
    Properties:
      StageName: Prod
      Description: Prod Stage
      DeploymentId: !Ref WebSocketDeployment
      ApiId: !Ref WebSocketAPI

  WebSocketDomain:
    Type: 'AWS::ApiGatewayV2::DomainName'
    Properties:
      DomainName: !Join ['.', ['ws', !Ref DomainName]]
      DomainNameConfigurations:
        - EndpointType: REGIONAL
          CertificateArn: !Ref SSL

  WebSocketMapping:
    Type: 'AWS::ApiGatewayV2::ApiMapping'
    DependsOn:
      - WebSocketDeployment
    Properties:
      DomainName: !Ref WebSocketDomain
      ApiId: !Ref WebSocketAPI
      Stage: !Ref WebSocketStage

  # Website items

  WebsiteBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Delete
    DependsOn:
      - WebSocketDeployment
    Properties:
      BucketName:
        Ref: DomainName
      AccessControl: PublicRead
      WebsiteConfiguration:
        IndexDocument: index.html
        ErrorDocument: 404.html
      Tags:
      - Key: Name
        Value: !Join ['_', ['WebsiteBucket', !Ref 'AWS::StackName']]
      - Key: Domain
        Value: !Ref DomainName
    DeletionPolicy: Retain

  WWWBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Delete
    DependsOn:
      - WebSocketDeployment
    Properties:
      BucketName: !Join ['.', ['www', !Ref DomainName]]
      AccessControl: PublicRead
      WebsiteConfiguration:
        RedirectAllRequestsTo:
          HostName: !Ref WebsiteBucket
      Tags:
      - Key: Name
        Value: !Join ['_', ['WWWBucket', !Ref 'AWS::StackName']]
      - Key: Domain
        Value: !Ref DomainName

  ImageBucket:
    Type: AWS::S3::Bucket
    DeletionPolicy: Delete
    DependsOn:
      - WebSocketDeployment
    Properties:
      BucketName: !Join ['.', ['images', !Ref DomainName]]
      AccessControl: Private
      Tags:
      - Key: Name
        Value: !Join ['_', ['ImageBucket', !Ref 'AWS::StackName']]
      - Key: Domain
        Value: !Ref DomainName
    DeletionPolicy: Retain

  WebsiteBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref WebsiteBucket
      PolicyDocument:
        Statement:
        - Action:
          - s3:GetObject
          Effect: Allow
          Resource: !Join ['', ['arn:aws:s3:::', !Ref WebsiteBucket, '/*']]
          Principal: '*'

  WWWBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref WWWBucket
      PolicyDocument:
        Statement:
        - Action:
          - s3:GetObject
          Effect: Allow
          Resource: !Join ['', ['arn:aws:s3:::', !Ref WWWBucket, '/*']]
          Principal: '*'

  WebsiteCloudfront:
    Type: AWS::CloudFront::Distribution
    DependsOn:
    - WebsiteBucket
    Properties:
      DistributionConfig:
        Comment: !Ref DomainName
        Origins:
        - DomainName: !Select [2, !Split ["/", !GetAtt WebsiteBucket.WebsiteURL]]
          Id: S3Origin
          CustomOriginConfig:
            HTTPPort: '80'
            HTTPSPort: '443'
            OriginProtocolPolicy: http-only
        Enabled: true
        HttpVersion: 'http2'
        DefaultRootObject: index.html
        Aliases:
        - !Ref DomainName
        - !Join ['.', ['www', !Ref DomainName]]
        DefaultCacheBehavior:
          DefaultTTL: 60
          MaxTTL: 60
          MinTTL: 60
          AllowedMethods:
          - GET
          - HEAD
          Compress: true
          TargetOriginId: S3Origin
          ForwardedValues:
            QueryString: true
            Cookies:
              Forward: none
          ViewerProtocolPolicy: redirect-to-https
        PriceClass: PriceClass_All
        ViewerCertificate:
          AcmCertificateArn: !Ref SSLARN
          SslSupportMethod: sni-only
        CustomErrorResponses:
          - ErrorCode: 404
            ResponseCode: 200
            ResponsePagePath: /index.html

  CloudfrontDNSRecord:
    Type: AWS::Route53::RecordSetGroup
    Properties:
      HostedZoneName:
        Fn::Join: ['', [!Ref DomainName, '.']]
      Comment: Cloudfront zone records.
      RecordSets:
      - Name: !Ref DomainName
        Type: A
        AliasTarget:
          HostedZoneId: Z2FDTNDATAQYW2
          DNSName: !GetAtt [WebsiteCloudfront, DomainName]
      - Name: !Join ['.', ['www', !Ref DomainName]]
        Type: A
        AliasTarget:
          HostedZoneId: Z2FDTNDATAQYW2
          DNSName: !GetAtt [WebsiteCloudfront, DomainName]

  WebsocketDNSRecord:
    Type: AWS::Route53::RecordSetGroup
    Properties:
      HostedZoneName:
        Fn::Join: ['', [!Ref DomainName, '.']]
      Comment: Websocket zone records.
      RecordSets:
      - Name: !Join ['.', ['ws', !Ref DomainName]]
        Type: A
        AliasTarget:
          HostedZoneId:
            Fn::FindInMap:
            - APIRegionMap
            - Ref: AWS::Region
            - APIHostedZoneId
          DNSName: !GetAtt [WebSocketDomain, RegionalDomainName]

Outputs:
  S3WebsiteURL:
    Value: !GetAtt WebsiteBucket.WebsiteURL
    Description: URL for website hosted on S3
```

答:
I think you just need to add an AWS::Lambda::Permission to allow the gateway to invoke the function.

```<code>OnConnectPermission:
  Type: AWS::Lambda::Permission
  DependsOn:
    - WebSocketAPI
  Properties:
    Action: lambda:InvokeFunction
    FunctionName: !Ref LambdaFunctionSocketServer
    Principal: apigateway.amazonaws.com
</code>```

Body:
I think you just need to add an AWS::Lambda::Permission to allow the gateway to invoke the function.

OnConnectPermission:
  Type: AWS::Lambda::Permission
  DependsOn:
    - WebSocketAPI
  Properties:
    Action: lambda:InvokeFunction
    FunctionName: !Ref LambdaFunctionSocketServer
    Principal: apigateway.amazonaws.com


来源: stackexchange

问:
F# record: ref vs mutable field
While refactoring my F# code, I found a record with a field of type bool ref:

type MyType =
  {
    Enabled : bool ref
    // other, irrelevant fields here
  }
```
<p>I decided to try changing it to a <code>mutable</code> field instead</p>
<pre class="lang-ml prettyprint-override"><code>// Refactored version
type MyType =
  {
    mutable Enabled : bool
    // other fields unchanged
  }
</code>```

Also, I applied all the changes required to make the code compile (i.e. changing := to <-, removing incr and decr functions, etc).

I noticed that after the changes some of the unit tests started to fail.
As the code is pretty large, I can't really see what exactly changed.

Is there a significant difference in implementation of the two that could change the behavior of my program?

答:
You have the difference not because one is first-value, passed by reference/value or other things. It's because a ref is just a container (class) on its own.

The difference is more obvious when you implement a ref by yourself. You could do it like this:

```<code>type Reference<'a> = {
    mutable Value: 'a
}
</code>```

Now look at both definitions.

```<code>type MyTypeA = {
    mutable Enabled: bool
}

type MyTypeB = {
    Enabled: Reference<bool>
}
</code>```

MyTypeA has a Enabled field that can be directly changed or with other word is mutable.

On the other-side you have MyTypeB that is theoretically immutable but has a Enabled that reference to a mutable class.

The Enabled from MyTypeB just reference to an object that is mutable like the millions of other classes in .NET. From the above type definitions, you can create objects like these.

```<code>let t = { MyTypeA.Enabled = true }
let u = { MyTypeB.Enabled = { Value = true }}
</code>```

Creating the types makes it more obvious, that the first is a mutable field, and the second contains an object with a mutable field.

You find the implementation of ref in FSharp.Core/prim-types.fs it looks like this:

```<code>    [<DebuggerDisplay("{contents}")>]
    [<StructuralEquality; StructuralComparison>]
    [<CompiledName("FSharpRef`1")>]
    type Ref<'T> =
        {
          [<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
          mutable contents: 'T }
        member x.Value
            with get() = x.contents
            and  set v = x.contents <- v

    and 'T ref = Ref<'T>
</code>```

The ref keyword in F# is just the built-in way to create such a pre-defined mutable Reference object, instead that you create your own type for this. And it has some benefits that it works well whenever you need to pass byref, in or out values in .NET. So you should use ref. But you also can use a mutable for this. For example, both code examples do the same.

With a reference

```<code>let parsed =
    let result = ref 0
    match System.Int32.TryParse("1234", result) with
    | true  -> result.Value
    | false -> result.Value
</code>```

With a mutable

```<code>let parsed =
    let mutable result = 0
    match System.Int32.TryParse("1234", &result) with
    | true  -> result
    | false -> result
</code>```

In both examples you get a 1234 as an int parsed. But the first example will create a FSharpRef and pass it to Int32.TryParse while the second example creates a field or variable and passes it with out to Int32.TryParse

ContentLicense: CC BY-SA 4.0

Title: F# record: ref vs mutable field

Body:
While refactoring my F# code, I found a record with a field of type bool ref:

type MyType =
  {
    Enabled : bool ref
    // other, irrelevant fields here
  }

I decided to try changing it to a mutable field instead

// Refactored version
type MyType =
  {
    mutable Enabled : bool
    // other fields unchanged
  }

Also, I applied all the changes required to make the code compile (i.e. changing := to <-, removing incr and decr functions, etc).

I noticed that after the changes some of the unit tests started to fail.
As the code is pretty large, I can't really see what exactly changed.

Is there a significant difference in implementation of the two that could change the behavior of my program?

Body:
You have the difference not because one is first-value, passed by reference/value or other things. It's because a ref is just a container (class) on its own.

The difference is more obvious when you implement a ref by yourself. You could do it like this:

type Reference<'a> = {
    mutable Value: 'a
}

Now look at both definitions.

type MyTypeA = {
    mutable Enabled: bool
}

type MyTypeB = {
    Enabled: Reference<bool>
}

MyTypeA has a Enabled field that can be directly changed or with other word is mutable.

On the other-side you have MyTypeB that is theoretically immutable but has a Enabled that reference to a mutable class.

The Enabled from MyTypeB just reference to an object that is mutable like the millions of other classes in .NET. From the above type definitions, you can create objects like these.

let t = { MyTypeA.Enabled = true }
let u = { MyTypeB.Enabled = { Value = true }}

Creating the types makes it more obvious, that the first is a mutable field, and the second contains an object with a mutable field.

You find the implementation of ref in FSharp.Core/prim-types.fs it looks like this:

    [<DebuggerDisplay("{contents}")>]
    [<StructuralEquality; StructuralComparison>]
    [<CompiledName("FSharpRef`1")>]
    type Ref<'T> =
        {
          [<DebuggerBrowsable(DebuggerBrowsableState.Never)>]
          mutable contents: 'T }
        member x.Value
            with get() = x.contents
            and  set v = x.contents <- v

    and 'T ref = Ref<'T>

The ref keyword in F# is just the built-in way to create such a pre-defined mutable Reference object, instead that you create your own type for this. And it has some benefits that it works well whenever you need to pass byref, in or out values in .NET. So you should use ref. But you also can use a mutable for this. For example, both code examples do the same.

With a reference

let parsed =
    let result = ref 0
    match System.Int32.TryParse("1234", result) with
    | true  -> result.Value
    | false -> result.Value

With a mutable

let parsed =
    let mutable result = 0
    match System.Int32.TryParse("1234", &result) with
    | true  -> result
    | false -> result

In both examples you get a 1234 as an int parsed. But the first example will create a FSharpRef and pass it to Int32.TryParse while the second example creates a field or variable and passes it with out to Int32.TryParse


问:
How do i make my website inaccesible from public?
i want to make a website that will not be accessed by anyone, there will be a login page in which you can't make an account, only for admins.

for example, i have a homepage which will be on example.com/homepage, if normal people accessed this they wouldn't be able to see it and instead get redirected to example.com/login unless they login with the right account they won't be able to go to the other sections of the websites.

答:
This can be done by configuring your web server. E.g. Apache has multiple choices, the simplest one being with just two files https://httpd.apache.org/docs/2.4/howto/auth.html#gettingitworking

For more complicated solutions you'll need a server side programming language, like PHP.


问:
Is it possible to read characters from `io::stdin()` without caching input line-by-line?
This question refers to the stable Rust version 1.2.0

I just want to iterate over the characters in the standard input of my CLI application. It's perfectly possible to do read stdin's read_line method into a temporary String instance and then iterate over it's chars() iterator.

But I don't like this approach, as it allocates a totally unnecessary String object. Stdin trait's documentations implements Read trait, which has chars() iterator, but it is marked as unstable (and thus can't be used with a stable compiler version).

Is there an alternative, possible less obvious way to read stdin char-by-char without any additional Rust-side buffering?

答:
For those who from future, we have fn bytes(self) -> Bytes<Self>](link) in std::io::Read , which allows us to reimplement XAMPPRocky's code in a more elegant way.

use std::io::{Read, stdin};

fn main() {
    for c in stdin().bytes().map(|x| x.expect("cannot read char from stdin")) {
        println!("CHAR {}", char::from(c));
    }
}
```

ContentLicense: CC BY-SA 3.0


问:
Convert json schema to a c# poco without attributes
I'm looking to convert a simple json schema into a c# poco.

```<code>{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Test_Schema",
  "description": "A schema for validating a test object",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "GeneralData": {
      "type": "object",
      "description": "Advsor and admin customer information",
      "properties": {
        "Name": {
          "type": [ "string", "null" ],
          "description": "Customer's advisor name"
        },
        "Age": {
          "type": [ "string", "null" ],
          "description": "Customer's advisor email"
        },
        "Location": {
          "type": [ "string", "null" ],
          "description": "The advisor's manager email'"
        }
      },
      "required": [ "Name", "Location", "Age" ],
      "additionalProperties": false
    },
    "ClientData": {
      "type": "object",
      "description": "Customer's information",
      "properties": {
        "Title": {
          "type": [ "string", "null" ]
        },
        "Forename": {
          "type": [ "string", "null" ]
        },
        "Surname": {
          "type": [ "string", "null" ]
        }
      },
      "required": [ "Title" ],
      "if": {
        "properties": {
          "Forename": { "enum": [ "Someone" ] }
        }
      },
      "then": { "required": [ "Surname" ] },
      "additionalProperties": false
    }
  }
}
</code>```

I was using NJsonSchema to do this and it does a great job. However, I'm looking to create the POCO without any attributes which would fail on the serialization. I want to populate the C# object and then let the json schema validation run.If something is required or null let the poco populate, then allow me to serialize it and then potentially fail on the json validation against the schema.

NJsonSchema is perfect in many ways, however I cannot find a way to abolish the attribute JsonProperty on generation.

Here is my NJsonSchema code generation code.

```<code> internal void WriteJsonToFile(JsonSchema jsonSchema)
        {
            var generator = new CSharpGenerator(jsonSchema)
            {
                Settings =
                {
                    GenerateDataAnnotations = false,
                    RequiredPropertiesMustBeDefined = false,
                    EnforceFlagEnums = false,
                    ClassStyle = CSharpClassStyle.Poco,
                    GenerateNativeRecords = false,
                    Namespace = nameof(JsonValidation)+"."+ nameof(TestSchemaPoco),
                    SchemaType = SchemaType.JsonSchema,
                    PropertyNameGenerator = new CSharpPropertyNameGenerator{}

                }
            };

            var file = generator.GenerateFile();
            File.WriteAllText("somefile.cs", file);
        }
</code>```

Here is the class which is generated

```<code>//----------------------
// <auto-generated>
//     Generated using the NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0) (http://NJsonSchema.org)
// </auto-generated>
//----------------------

namespace JsonValidation.TestSchemaPoco
{
    #pragma warning disable // Disable all warnings

    /// <summary>
    /// A schema for validating a test object
    /// </summary>
    [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "11.0.0.0 (Newtonsoft.Json v13.0.0.0)")]
    public partial class Test_Schema
    {
        /// <summary>
        /// Advsor and admin customer information
        /// </summary>
        [Newtonsoft.Json.JsonProperty("GeneralData", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public GeneralData GeneralData { get; set; }

        /// <summary>
        /// Customer's information
        /// </summary>
        [Newtonsoft.Json.JsonProperty("ClientData", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public ClientData ClientData { get; set; }

    }

    [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "11.0.0.0 (Newtonsoft.Json v13.0.0.0)")]
    public partial class GeneralData
    {
        /// <summary>
        /// Customer's advisor name
        /// </summary>
        [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Name { get; set; }

        /// <summary>
        /// Customer's advisor email
        /// </summary>
        [Newtonsoft.Json.JsonProperty("Age", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Age { get; set; }

        /// <summary>
        /// The advisor's manager email'
        /// </summary>
        [Newtonsoft.Json.JsonProperty("Location", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Location { get; set; }

    }

    [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "11.0.0.0 (Newtonsoft.Json v13.0.0.0)")]
    public partial class ClientData
    {
        [Newtonsoft.Json.JsonProperty("Title", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Title { get; set; }

        [Newtonsoft.Json.JsonProperty("Forename", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Forename { get; set; }

        [Newtonsoft.Json.JsonProperty("Surname", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Surname { get; set; }

    }
}
</code>```

答:
From what I can find. This is not possible with NJsonSchema.

https://github.com/RicoSuter/NJsonSchema/issues/521

https://github.com/RicoSuter/NSwag/issues/2213

My solution for this was to use the vim editor and create a macro for removing what I find on /[System and /[Newtonsoft

This removes the annotations and gives me a clean POCO class.

Body:
I'm looking to convert a simple json schema into a c# poco.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Test_Schema",
  "description": "A schema for validating a test object",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "GeneralData": {
      "type": "object",
      "description": "Advsor and admin customer information",
      "properties": {
        "Name": {
          "type": [ "string", "null" ],
          "description": "Customer's advisor name"
        },
        "Age": {
          "type": [ "string", "null" ],
          "description": "Customer's advisor email"
        },
        "Location": {
          "type": [ "string", "null" ],
          "description": "The advisor's manager email'"
        }
      },
      "required": [ "Name", "Location", "Age" ],
      "additionalProperties": false
    },
    "ClientData": {
      "type": "object",
      "description": "Customer's information",
      "properties": {
        "Title": {
          "type": [ "string", "null" ]
        },
        "Forename": {
          "type": [ "string", "null" ]
        },
        "Surname": {
          "type": [ "string", "null" ]
        }
      },
      "required": [ "Title" ],
      "if": {
        "properties": {
          "Forename": { "enum": [ "Someone" ] }
        }
      },
      "then": { "required": [ "Surname" ] },
      "additionalProperties": false
    }
  }
}

I was using NJsonSchema to do this and it does a great job. However, I'm looking to create the POCO without any attributes which would fail on the serialization. I want to populate the C# object and then let the json schema validation run.If something is required or null let the poco populate, then allow me to serialize it and then potentially fail on the json validation against the schema.

NJsonSchema is perfect in many ways, however I cannot find a way to abolish the attribute JsonProperty on generation.

Here is my NJsonSchema code generation code.

 internal void WriteJsonToFile(JsonSchema jsonSchema)
        {
            var generator = new CSharpGenerator(jsonSchema)
            {
                Settings =
                {
                    GenerateDataAnnotations = false,
                    RequiredPropertiesMustBeDefined = false,
                    EnforceFlagEnums = false,
                    ClassStyle = CSharpClassStyle.Poco,
                    GenerateNativeRecords = false,
                    Namespace = nameof(JsonValidation)+"."+ nameof(TestSchemaPoco),
                    SchemaType = SchemaType.JsonSchema,
                    PropertyNameGenerator = new CSharpPropertyNameGenerator{}

                }
            };

            var file = generator.GenerateFile();
            File.WriteAllText("somefile.cs", file);
        }

Here is the class which is generated

//----------------------
// <auto-generated>
//     Generated using the NJsonSchema v11.0.0.0 (Newtonsoft.Json v13.0.0.0) (http://NJsonSchema.org)
// </auto-generated>
//----------------------

namespace JsonValidation.TestSchemaPoco
{
    #pragma warning disable // Disable all warnings

    ///
    /// A schema for validating a test object
    ///
    [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "11.0.0.0 (Newtonsoft.Json v13.0.0.0)")]
    public partial class Test_Schema
    {
        ///
        /// Advsor and admin customer information
        ///
        [Newtonsoft.Json.JsonProperty("GeneralData", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public GeneralData GeneralData { get; set; }

        ///
        /// Customer's information
        ///
        [Newtonsoft.Json.JsonProperty("ClientData", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public ClientData ClientData { get; set; }

    }

    [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "11.0.0.0 (Newtonsoft.Json v13.0.0.0)")]
    public partial class GeneralData
    {
        ///
        /// Customer's advisor name
        ///
        [Newtonsoft.Json.JsonProperty("Name", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Name { get; set; }

        ///
        /// Customer's advisor email
        ///
        [Newtonsoft.Json.JsonProperty("Age", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Age { get; set; }

        ///
        /// The advisor's manager email'
        ///
        [Newtonsoft.Json.JsonProperty("Location", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Location { get; set; }

    }

    [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "11.0.0.0 (Newtonsoft.Json v13.0.0.0)")]
    public partial class ClientData
    {
        [Newtonsoft.Json.JsonProperty("Title", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Title { get; set; }

        [Newtonsoft.Json.JsonProperty("Forename", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Forename { get; set; }

        [Newtonsoft.Json.JsonProperty("Surname", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]
        public string Surname { get; set; }

    }
}


问:
Graph Sensor Data with Python and Matplotlib
I have a csv file like this:

```<code>sensor_name, time
bed, 01:08:40
bed, 01:09:33
bed, 01:09:51
bed, 01:11:06
kitchen, 01:27:57
kitchen, 01:30:03
living, 01:32:51
living, 01:33:06
living, 01:34:06
living, 01:35:06
living, 01:37:06
bed, 01:40:50
bed, 01:41:06
bed, 01:42:54
bed, 01:45:06
living, 01:50:30
</code>```

In order to track movements, I just want to plot - with matplotlib - only the values where a sensor change occurs, thus the first and last before the change and eliminate the rest. The expected result looks like this:

```<code>sensor_name, time
bed, 01:08:40
bed, 01:11:06
kitchen, 01:27:57
kitchen, 01:30:03
living, 01:32:51
living, 01:37:06
bed, 01:40:50
bed, 01:45:06
living, 01:50:30
</code>```

Thanks, all the best.

答:
You can compute a mask by checking if the sensor_name changes (get the next row with shift):

```<code>mask = df['sensor_name'].ne(df['sensor_name'].shift())

# change + previous row
df[mask|mask.shift(-1)]
</code>```

output:

```<code>   sensor_name      time
0          bed  01:08:40
3          bed  01:11:06
4      kitchen  01:27:57
5      kitchen  01:30:03
6       living  01:32:51
10      living  01:37:06
11         bed  01:40:50
14         bed  01:45:06
15      living  01:50:30
</code>```

Body:
I have a csv file like this:

sensor_name, time
bed, 01:08:40
bed, 01:09:33
bed, 01:09:51
bed, 01:11:06
kitchen, 01:27:57
kitchen, 01:30:03
living, 01:32:51
living, 01:33:06
living, 01:34:06
living, 01:35:06
living, 01:37:06
bed, 01:40:50
bed, 01:41:06
bed, 01:42:54
bed, 01:45:06
living, 01:50:30

In order to track movements, I just want to plot - with matplotlib - only the values where a sensor change occurs, thus the first and last before the change and eliminate the rest. The expected result looks like this:

sensor_name, time
bed, 01:08:40
bed, 01:11:06
kitchen, 01:27:57
kitchen, 01:30:03
living, 01:32:51
living, 01:37:06
bed, 01:40:50
bed, 01:45:06
living, 01:50:30

Thanks, all the best.

Body:
You can compute a mask by checking if the sensor_name changes (get the next row with shift):

mask = df['sensor_name'].ne(df['sensor_name'].shift())

# change + previous row
df[mask|mask.shift(-1)]

output:

   sensor_name      time
0          bed  01:08:40
3          bed  01:11:06
4      kitchen  01:27:57
5      kitchen  01:30:03
6       living  01:32:51
10      living  01:37:06
11         bed  01:40:50
14         bed  01:45:06
15      living  01:50:30


问:
How to proxy VideoJS Source from ajax call
I'm trying to create a simple www.myserver.com/proxy.php in order to stream www.mediafire/myvideo.mp4 back to the browser. I do this to avoid CORS error when calling the video directly from the browser. (mediafire server doesn't allows CORS)

In the post below I found the code, but:

How do I fetch the ajax response back to the  element in VideoJS?

Many Thanks

AJAX cross domain call

The jQuery part:

```<code>$.ajax({
    url: 'proxy.php',
    type: 'POST',
    success: function(response) {
        // response now contains myfile.mp4
    }
});
</code>```

the PHP (proxy.php):

```<code>echo file_get_contents("www.mediafire.com/myvid.mp4");
</code>```

And a simple VideoJS script:

```<code>    <video
        id="fplayer"
        class="video-js vjs-default-skin vjs-16-9"
        controls
        preload="none"

        data-setup='{"fluid": false}'>
        <source src="??" type="application/x-mpegURL">
       // it was: <source src="www.mediafire.com/myvid.mp4">
    </video>

</code>```

The link below suggest to build the HTML videoJS element once I get the ajax response.
But the datatype is JSON, whereas I'm fetching a binary MP4 or a m3u8 video and I'm not sure if putting the response in the Source element will work. In addition VideoJS may not initialize using this solution because the Video element doesn't exist when page load is ready.

Load video source into videojs or mediaelementjs dynamically from ajax?

答: We can use AJAX to make a request to our local server, and then use a proxy such as Express JS (Node JS) which is able to route the request to the local video we want to stream. But streaming a video from a remote server (eg. mediafire.com) requires full access to the HTTP Headers, which they're usually not willing to provide.</p>

Body:
I'm trying to create a simple www.myserver.com/proxy.php in order to stream www.mediafire/myvideo.mp4 back to the browser. I do this to avoid CORS error when calling the video directly from the browser. (mediafire server doesn't allows CORS)

In the post below I found the code, but:

How do I fetch the ajax response back to the  element in VideoJS?

Many Thanks

AJAX cross domain call

The jQuery part:

$.ajax({
    url: 'proxy.php',
    type: 'POST',
    success: function(response) {
        // response now contains myfile.mp4
    }
});

the PHP (proxy.php):

echo file_get_contents("www.mediafire.com/myvid.mp4");

And a simple VideoJS script:

    <video
        id="fplayer"
        class="video-js vjs-default-skin vjs-16-9"
        controls
        preload="none"

        data-setup='{"fluid": false}'>
        <source src="??" type="application/x-mpegURL">
       // it was: <source src="www.mediafire.com/myvid.mp4">
    </video>

The link below suggest to build the HTML videoJS element once I get the ajax response.
But the datatype is JSON, whereas I'm fetching a binary MP4 or a m3u8 video and I'm not sure if putting the response in the Source element will work. In addition VideoJS may not initialize using this solution because the Video element doesn't exist when page load is ready.

Load video source into videojs or mediaelementjs dynamically from ajax?


问:
How to set '-Xuse-experimental=kotlin.experimental' in IntelliJ
while trying to build a Kotlin/Ktor application in IntelliJ, multiple warnings of the form

```<code>Warning:(276, 6) Kotlin: This class can only be used with the compiler argument '-Xuse-experimental=kotlin.Experimental'
</code>```

are output.  The warnings refer to

```<code>@UseExperimental(KtorExperimentalLocationsAPI::class)
</code>```

so I expected to satisfy the warning by setting Settings -> Build -> Compiler -> Kotlin Compiler -> Additional command line parameters to -version -Xuse-experimental=kotlin.Experimental.  (-version was already there).  But the warning is still generated.  How do I satisfy it?  Thanks in expectation.

答:
Go to your app/build.gradle file and add the below task on the bottom part

```<code>tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
    kotlinOptions {
        freeCompilerArgs += "-Xopt-in=io.ktor.util.KtorExperimentalAPI"
    }
}
</code>```

Body:
while trying to build a Kotlin/Ktor application in IntelliJ, multiple warnings of the form

Warning:(276, 6) Kotlin: This class can only be used with the compiler argument '-Xuse-experimental=kotlin.Experimental'

are output.  The warnings refer to

@UseExperimental(KtorExperimentalLocationsAPI::class)

so I expected to satisfy the warning by setting Settings -> Build -> Compiler -> Kotlin Compiler -> Additional command line parameters to -version -Xuse-experimental=kotlin.Experimental.  (-version was already there).  But the warning is still generated.  How do I satisfy it?  Thanks in expectation.

Body:
Go to your app/build.gradle file and add the below task on the bottom part

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
    kotlinOptions {
        freeCompilerArgs += "-Xopt-in=io.ktor.util.KtorExperimentalAPI"
    }
}


问:
How do i sum given range in pandas dataframe?
Pandas dataframe

Hi i have dataframe where i want to sum the range of columns(CE_net, PE_net, CE_chg, PE_chg) where the column strike are from 17000 to 17500 and i cant pass direct values like 17000:17500. I want to pass the range through variables like start:end

答:
```<code>#Ok i did this
#First got index of values
index1= np.where(df["column_name"]==value1)[0][0]
index2= np.where(df["column_n.ame"]==value2)[0][0]
index2 = index2 +1
#Then

df.iloc[index1:index2, 3:4].sum()[0]
</code>```


问:
Create objects dynamically out of a dot notation like string
I'm trying to create a JS object dynamically providing a key and a value. The key is in dot notation, so if a string like car.model.color is provided the generated object would be:

```<code>{
  car: {
    model: {
      color: value;
    }
  }
}
</code>```

The problem has a trivial solution if the key provided is a simple property, but i'm struggling to make it work for composed keys.

My code:

```<code>function (key, value) {
  var object = {};
  var arr = key.split('.');
  for(var i = 0; i < arr.length; i++) {
    object = object[arr[i]] = {};
  }
  object[arr[arr.length-1]] = value;
  return object;
}
</code>```

答:
Here's a recursive approach to the problem:</p>
```<code>const strToObj = (parts, val) => {
  if (!Array.isArray(parts)) {
    parts = parts.split(".");
  }
  if (!parts.length) {
    return val;
  }
  return {
    [parts.shift()]: strToObj(parts, val)
  };
}
</code>```

Body:
I'm trying to create a JS object dynamically providing a key and a value. The key is in dot notation, so if a string like car.model.color is provided the generated object would be:

{
  car: {
    model: {
      color: value;
    }
  }
}

The problem has a trivial solution if the key provided is a simple property, but i'm struggling to make it work for composed keys.

My code:

function (key, value) {
  var object = {};
  var arr = key.split('.');
  for(var i = 0; i < arr.length; i++) {
    object = object[arr[i]] = {};
  }
  object[arr[arr.length-1]] = value;
  return object;
}

Body:
Here's a recursive approach to the problem:

const strToObj = (parts, val) => {
  if (!Array.isArray(parts)) {
    parts = parts.split(".");
  }
  if (!parts.length) {
    return val;
  }
  return {
    [parts.shift()]: strToObj(parts, val)
  };
}


问:
Silverlight datagrid twoway binding
I have datagrid in which one of the column is Textbox control, have set the binding as twoway. the grid is binded to a observable collection.
Issue : If I enter some value in text box, collection get populated. now if I clears that textbox the same has not been reflected to the collection. my binded property is nullable.

Thanks N Advance

答:
You may use </p>

```<code><TextBox IsReadOnly="True" Text="{Binding BUApprovalQty, Mode=TwoWay, TargetNullValue=''}"></TextBox>
</code>```

Title: Silverlight datagrid twoway binding

Body:
You may use

<TextBox IsReadOnly="True" Text="{Binding BUApprovalQty, Mode=TwoWay, TargetNullValue=''}"></TextBox>


问:
Show resize handle on hover
I need elements to be resizable using resize: both, and it does work, but I want to show the corner handle just when hovering the element, is there a way to do it?

That's the handle I want to show on hover only.

答:
Use resize: both; inside the :hover rule

.resize {
  outline: 1px solid black;
  overflow: auto;
  min-height: 100px;
  min-width: 100px;
}

.resize:hover {
  resize: both;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="resize"></div></code>```

Title: Show resize handle on hover

Body:
Use resize: both; inside the :hover rule

.resize {
  outline: 1px solid black;
  overflow: auto;
  min-height: 100px;
  min-width: 100px;
}

.resize:hover {
  resize: both;
}

<div class="resize"></div>


问:
Why is the value of n equal to 5 in the first iteration?
I have a question that why is the value of n being used in the first iteration is 5 and not 6. I checked it on stackeoverflow and there many of them said that in the first iteration the value of n is used and then it is decreased by 1 and used in the next iteration.</p>
```<code>#include <stdio.h>

int main()
{
    int ans = 1, n = 6;

    while (n--)
    {
        printf("n = %d\n", n);

        if (n != 0)
        {
            ans *= n;
        }
    }

    printf("ans = %d", ans);

    return 0;
}

Output:
n = 5
n = 4
n = 3
n = 2
n = 1
n = 0
ans = 120
</code>```

答:
The answer lies in the post decrement operator. Every time while (n--) is encountered, the value of n remains n and not n-1 as expected from the post decrement operator --.

```<code>while (n--) { // At first, n is 6 for this statement
    // n is 5 then 4, 3, 2, 1
}
</code>```

On the same note,

```<code>for (int i = 0; i < n; i--) {
    // Some code
}
</code>```

and

```<code>for (int i = 0; i < n; --i) {
    // Some code
}
</code>```

have same values of i.

Body:
I have a question that why is the value of n being used in the first iteration is 5 and not 6. I checked it on stackeoverflow and there many of them said that in the first iteration the value of n is used and then it is decreased by 1 and used in the next iteration.

#include <stdio.h>

int main()
{
    int ans = 1, n = 6;

    while (n--)
    {
        printf("n = %d\n", n);

        if (n != 0)
        {
            ans *= n;
        }
    }

    printf("ans = %d", ans);

    return 0;
}

Output:
n = 5
n = 4
n = 3
n = 2
n = 1
n = 0
ans = 120

Body:
The answer lies in the post decrement operator. Every time while (n--) is encountered, the value of n remains n and not n-1 as expected from the post decrement operator --.

while (n--) { // At first, n is 6 for this statement
    // n is 5 then 4, 3, 2, 1
}

On the same note,

for (int i = 0; i < n; i--) {
    // Some code
}

and

for (int i = 0; i < n; --i) {
    // Some code
}

have same values of i.


问:
Is there AdMob support for Flutter web?
Is there AdMob support for Flutter web? All libraries that I found are intended only for Android and IOS</p>

答:
As you can see in the image below, Google Admobe is not supported for the web so you can not use it for flutter web or other web frameworks.

On other hand, you can use adsense and set your ads for flutter web,
and I find this solution for using Adsense as HTML(with IFrameElement)

first created an html file adview.html

```<code><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:inline-block;width:320px;height:80px"
     data-ad-client="ca-pub-xxxxxx"
     data-ad-slot="xxxxxxx"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</code>```

And then, an IFrameElement to make use of the HTML:

```<code>import 'dart:html';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

Widget adsenseAdsView() {
  // ignore: undefined_prefixed_name
  ui.platformViewRegistry.registerViewFactory(
      'adViewType',
      (int viewID) => IFrameElement()
        ..width = '320'
        ..height = '100'
        ..src = 'adview.html'
        ..style.border = 'none');

  return SizedBox(
    height: 100.0,
    width: 320.0,
    child: HtmlElementView(
      viewType: 'adViewType',
    ),
  );
}
</code>```

Title: Is there AdMob support for Flutter web?

Body:
As you can see in the image below, Google Admobe is not supported for the web so you can not use it for flutter web or other web frameworks.

On other hand, you can use adsense and set your ads for flutter web,
and I find this solution for using Adsense as HTML(with IFrameElement)

first created an html file adview.html

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
     style="display:inline-block;width:320px;height:80px"
     data-ad-client="ca-pub-xxxxxx"
     data-ad-slot="xxxxxxx"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

And then, an IFrameElement to make use of the HTML:

import 'dart:html';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';

Widget adsenseAdsView() {
  // ignore: undefined_prefixed_name
  ui.platformViewRegistry.registerViewFactory(
      'adViewType',
      (int viewID) => IFrameElement()
        ..width = '320'
        ..height = '100'
        ..src = 'adview.html'
        ..style.border = 'none');

  return SizedBox(
    height: 100.0,
    width: 320.0,
    child: HtmlElementView(
      viewType: 'adViewType',
    ),
  );
}


问:
xampp MySQL does not start
I installed Xampp on Windows 7 32-bit. When I try to start MySql in XAMPP control panel (v3.2.1) I have the following message and MySql does not start.

```<code>23:02:03  [mysql]   Problem detected!
23:02:03  [mysql]   Port 3306 in use by ""C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --defaults-file="C:\Program Files\MySQL\MySQL Server 5.1\my.ini" MySQL"!
23:02:03  [mysql]   MySQL WILL NOT start without the configured ports free!
23:02:03  [mysql]   You need to uninstall/disable/reconfigure the blocking application
23:02:03  [mysql]   or reconfigure MySQL and the Control Panel to listen on a different port
23:02:03  [mysql]   Attempting to start MySQL service...
</code>```

A similar problem was reported here but there is no working answer. When I try to install with MySql disabled, the result is that I even don't have an option even to try to run it.

I am new to Xampp and don't know where and what to look for to solve the issue

I need to run Apache and MySql with Php.

答: My fix was to stop MySQL57 in services, Xampp now starts/stops Apache/MySQL as expected.

Title: xampp MySQL does not start

Body:
I installed Xampp on Windows 7 32-bit. When I try to start MySql in XAMPP control panel (v3.2.1) I have the following message and MySql does not start.

23:02:03  [mysql]   Problem detected!
23:02:03  [mysql]   Port 3306 in use by ""C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --defaults-file="C:\Program Files\MySQL\MySQL Server 5.1\my.ini" MySQL"!
23:02:03  [mysql]   MySQL WILL NOT start without the configured ports free!
23:02:03  [mysql]   You need to uninstall/disable/reconfigure the blocking application
23:02:03  [mysql]   or reconfigure MySQL and the Control Panel to listen on a different port
23:02:03  [mysql]   Attempting to start MySQL service...

A similar problem was reported here but there is no working answer. When I try to install with MySql disabled, the result is that I even don't have an option even to try to run it.

I am new to Xampp and don't know where and what to look for to solve the issue

I need to run Apache and MySql with Php.


问:
Is there a rule or setting when Narrator ignore aria-label on element while aria-label's value same as element 's content?
When I set aria-label's value same as button's content, the screen-reader cannot readout aria-label.

 <button aria-label="Close">Close</button>

But when I change aria-label's value different from button's content, the screen-reader readout the aria-label.

 <button aria-label="Close X">Close</button>

Is there a rule or setting when Narrator ignore aria-label on element while aria-label's value same as element 's content?

Thanks for your help.

答:
No there is not any convention about this.

By default, an HTML element will use its text content as the
accessibility label. If an element has aria-label, the accessible name
becomes the string that it's passed in the attribute.

Your code works with the chrome screen reader extension.
please take a look at this link for more information.

There is also a chrome extension that helps you with missing ARIA labels, misused ARIA roles, and an incomplete keyboard called ARIA DevTools. here is the link


问:
Install Microsoft.WindowsDesktop.App along with wpf app during squirrel.windows install
I have a wpf app here which requires .net runtime after installation of the app.

Here is the App csproj.

```<code><Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWPF>true</UseWPF>
    <Version>1.7.0</Version>
    <AssemblyVersion>1.8.0</AssemblyVersion>
    <FileVersion>1.8.0</FileVersion>
    <Authors>Me</Authors>
    <PackageIcon>AppIcon.JPG</PackageIcon>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="Images\SloVVo_Logo.JPG" />
    <None Include="..\..\SloVVoNotes\Icon\AppIcon.JPG">
      <Pack>True</Pack>
      <PackagePath></PackagePath>
    </None>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="EntityFramework" Version="6.4.4" />
    <PackageReference Include="FontAwesome.WPF" Version="4.7.0.9" />
    <PackageReference Include="NLog" Version="4.7.10" />
    <PackageReference Include="NLog.Config" Version="4.7.10" />
    <PackageReference Include="NLog.Schema" Version="4.7.10" />
    <PackageReference Include="System.Runtime.Caching" Version="5.0.0" />
    <PackageReference Include="System.Windows.Interactivity.WPF" Version="2.0.20525" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\SloVVo.Logic\SloVVo.Logic.csproj" />
  </ItemGroup>

  <ItemGroup>
    <Resource Include="Images\SloVVo_Logo.JPG">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
  </ItemGroup>

  <ItemGroup>
    <Compile Update="Views\AddContent - Copy.xaml.cs">
      <SubType>Code</SubType>
      <DependentUpon>AddContentWindow.xaml.cs</DependentUpon>
    </Compile>
  </ItemGroup>

  <ItemGroup>
    <Folder Include="bin\Debug\netcoreapp3.1\bin\" />
  </ItemGroup>

</Project>

</code>```

I create a build and use squirrel.windows to create a setup file.

I use the following powershell methods to acompish that.

Create package:

```<code>function Write-Package {
    param(
        [System.IO.DirectoryInfo] $BinDir,
        [System.IO.FileInfo] $ExeFile,
        [System.IO.FileInfo] $NuspecFile
    )

    $binDirPath = (Resolve-Path $BinDir).Path
    $exeFilePath = (Resolve-Path $ExeFile).Path
    $nuspecFilePath = (Resolve-Path $NuspecFile).Path

    $version =$([System.Diagnostics.FileVersionInfo]::GetVersionInfo("$exeFilePath").FileVersion)
    nuget pack $nuspecFilePath `
        -Verbosity quiet `
        -Version $version `
        -OutputDirectory $binDirPath `
        -BasePath $binDirPath
    $nupkgFileName = Get-ChildItem -Path $binDirPath -Filter *.nupkg
    $appName = $nupkgFileName.Name.Split('.')[0]
    $nupkgFilePath = (Join-Path -Path "$binDirPath" -ChildPath "$appName.$version.nupkg")
    return $nupkgFilePath
}
</code>```

Squirrel Releasify the package

```<code> .Example
 Write-Releases -SquirrelExe C:\tools\squirrel.exe -NupkgFile .\bin\Release\MyApp.1.0.0.nupkg
#>
function Write-Releases {
    param(
        [System.IO.FileInfo] $SquirrelExe,
        [System.IO.FileInfo] $NupkgFile
    )
    $squirrelExePath = (Resolve-Path $SquirrelExe).Path
    $nupkgFilePath = (Resolve-Path $NupkgFile).Path
    $arguments= "--logLevel","Debug","--no-msi","--releasify",$nupkgFilePath
    Start-Process -FilePath $SquirrelExe `
        -ArgumentList $arguments `
        -PassThru | Wait-Process
}
</code>```

the nuspec file

```<code><?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>MyApp</id>
    <version>1.0.0</version>
    <title>MyApp</title>
    <authors>Me</authors>
    <owners>Me</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Application</description>
    <dependencies>
      <group targetFramework="netcoreapp3.1" />
      <group targetFramework=".NETFramework4.5" />
    </dependencies>
    <frameworkReferences>
    <group targetFramework="netcoreapp3.1" />
    </frameworkReferences>
  </metadata>
  <files>
    <file src="*\*.*" target="lib\net45\" exclude="*.pdb;*.nupkg;*.vshost.*"/>
  </files>
</package>
</code>```

Now, after I install the app on a new machine it says that .net core runtime is not installed and

Microsoft.WindowsDesktop.App 3.1.0 is not installed.

Could someone provide a useful resource as to how I can prepackage that and it's installed alongside the app so that the user does not have to download and install the .net core runtime?

答:
I migrated back to .Net461 and the below is my nuspec file:</p>
```<code><?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>SloVVo</id>
    <version>2.0.0</version>
    <title>SloVVo</title>
    <authors>Me</authors>
    <owners>Me</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Application</description>
    <dependencies>
        <group targetFramework=".NETFramework4.6.1"/>
    </dependencies>
  </metadata>
  <files>
    <file src="**\*.*" target="lib\net461" exclude="*.pdb;*.nupkg;*.vshost.*"/>
  </files>
</package>
</code>```

Body:
I have a wpf app here which requires .net runtime after installation of the app.

Here is the App csproj.

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">

  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <UseWPF>true</UseWPF>
    <Version>1.7.0</Version>
    <AssemblyVersion>1.8.0</AssemblyVersion>
    <FileVersion>1.8.0</FileVersion>
    <Authors>Me</Authors>
    <PackageIcon>AppIcon.JPG</PackageIcon>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="Images\SloVVo_Logo.JPG" />
    <None Include="..\..\SloVVoNotes\Icon\AppIcon.JPG">
      <Pack>True</Pack>
      <PackagePath></PackagePath>
    </None>
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="EntityFramework" Version="6.4.4" />
    <PackageReference Include="FontAwesome.WPF" Version="4.7.0.9" />
    <PackageReference Include="NLog" Version="4.7.10" />
    <PackageReference Include="NLog.Config" Version="4.7.10" />
    <PackageReference Include="NLog.Schema" Version="4.7.10" />
    <PackageReference Include="System.Runtime.Caching" Version="5.0.0" />
    <PackageReference Include="System.Windows.Interactivity.WPF" Version="2.0.20525" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\SloVVo.Logic\SloVVo.Logic.csproj" />
  </ItemGroup>

  <ItemGroup>
    <Resource Include="Images\SloVVo_Logo.JPG">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Resource>
  </ItemGroup>

  <ItemGroup>
    <Compile Update="Views\AddContent - Copy.xaml.cs">
      <SubType>Code</SubType>
      <DependentUpon>AddContentWindow.xaml.cs</DependentUpon>
    </Compile>
  </ItemGroup>

  <ItemGroup>
    <Folder Include="bin\Debug\netcoreapp3.1\bin\" />
  </ItemGroup>

</Project>

I create a build and use squirrel.windows to create a setup file.

I use the following powershell methods to acompish that.

Create package:

function Write-Package {
    param(
        [System.IO.DirectoryInfo] $BinDir,
        [System.IO.FileInfo] $ExeFile,
        [System.IO.FileInfo] $NuspecFile
    )

    $binDirPath = (Resolve-Path $BinDir).Path
    $exeFilePath = (Resolve-Path $ExeFile).Path
    $nuspecFilePath = (Resolve-Path $NuspecFile).Path

    $version =$([System.Diagnostics.FileVersionInfo]::GetVersionInfo("$exeFilePath").FileVersion)
    nuget pack $nuspecFilePath `
        -Verbosity quiet `
        -Version $version `
        -OutputDirectory $binDirPath `
        -BasePath $binDirPath
    $nupkgFileName = Get-ChildItem -Path $binDirPath -Filter *.nupkg
    $appName = $nupkgFileName.Name.Split('.')[0]
    $nupkgFilePath = (Join-Path -Path "$binDirPath" -ChildPath "$appName.$version.nupkg")
    return $nupkgFilePath
}

Squirrel Releasify the package

 .Example
 Write-Releases -SquirrelExe C:\tools\squirrel.exe -NupkgFile .\bin\Release\MyApp.1.0.0.nupkg
#>
function Write-Releases {
    param(
        [System.IO.FileInfo] $SquirrelExe,
        [System.IO.FileInfo] $NupkgFile
    )
    $squirrelExePath = (Resolve-Path $SquirrelExe).Path
    $nupkgFilePath = (Resolve-Path $NupkgFile).Path
    $arguments= "--logLevel","Debug","--no-msi","--releasify",$nupkgFilePath
    Start-Process -FilePath $SquirrelExe `
        -ArgumentList $arguments `
        -PassThru | Wait-Process
}

the nuspec file

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>MyApp</id>
    <version>1.0.0</version>
    <title>MyApp</title>
    <authors>Me</authors>
    <owners>Me</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Application</description>
    <dependencies>
      <group targetFramework="netcoreapp3.1" />
      <group targetFramework=".NETFramework4.5" />
    </dependencies>
    <frameworkReferences>
    <group targetFramework="netcoreapp3.1" />
    </frameworkReferences>
  </metadata>
  <files>
    <file src="*\*.*" target="lib\net45\" exclude="*.pdb;*.nupkg;*.vshost.*"/>
  </files>
</package>

Now, after I install the app on a new machine it says that .net core runtime is not installed and

Microsoft.WindowsDesktop.App 3.1.0 is not installed.

Could someone provide a useful resource as to how I can prepackage that and it's installed alongside the app so that the user does not have to download and install the .net core runtime?

Body:
I migrated back to .Net461 and the below is my nuspec file:

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>SloVVo</id>
    <version>2.0.0</version>
    <title>SloVVo</title>
    <authors>Me</authors>
    <owners>Me</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Application</description>
    <dependencies>
        <group targetFramework=".NETFramework4.6.1"/>
    </dependencies>
  </metadata>
  <files>
    <file src="**\*.*" target="lib\net461" exclude="*.pdb;*.nupkg;*.vshost.*"/>
  </files>
</package>


问:
How to ensure my regular expression does not match too much
A file has few words with numbers in the begining of them. i want to extract a particular no line.when given 1, it extracts line 1 also with 11, 21

FILE.txt has contents:

```
1.sample
lines of
2.sentences
present in
...
...
10.the
11.file
```

when Executed pro 1 file.txt
gives results from line 1,10 and also from line 11
as these three results have 1 in their string. i.e

Output of the script:

```
1.sample
10.the
11.file
```

Expected output: the output which i am expecting
is only line 1 contents and not the line 10 or line 11 contents.
i.e

Expected output:

```1.sample```

My current code:

```<code>proc pro { pattern args} {

   set file [open $args r]
   set lnum 0
   set occ 0
   while {[gets $file line] >=0} {
      incr lnum
      if {[regexp $pattern $line]} {
          incr occ
          puts "The pattern is present in line: $lnum"
          puts "$line"
      } else {
         puts "not found"
      }
   }
   puts "total number of occurencese : $occ"
   close $file
}
</code>```

the program is working fine but the thing is i am retrieving lines that i dont want to along with the expected line. As the number (1) which i want to retrieve is present in the other strings such as 11, 21, 14 etc these lines are also getting printed.

kindly tolerate my unclear way of explaining the question.

答:
You can solve the problem using word boundaries as suggested by glen but you can also consider the following things:

If after every line number there is a . then you can use it as delimiter in regular expression

```<code>regexp "^$lineNo\\." $a
</code>```

I would also suggest to use ^ (match at the beginning of line) so that even if number is present in the line elsewhere it would not get counted.

tcl word boundaries are well explained at http://www.regular-expressions.info/wordboundaries.html

Body:
A file has few words with numbers in the begining of them. i want to extract a particular no line.when given 1, it extracts line 1 also with 11, 21

FILE.txt has contents:

1.sample
lines of
2.sentences
present in
...
...
10.the
11.file

when Executed pro 1 file.txt
gives results from line 1,10 and also from line 11
as these three results have 1 in their string. i.e

Output of the script:

1.sample
10.the
11.file

Expected output: the output which i am expecting
is only line 1 contents and not the line 10 or line 11 contents.
i.e

Expected output:

1.sample

My current code:

proc pro { pattern args} {

   set file [open $args r]
   set lnum 0
   set occ 0
   while {[gets $file line] >=0} {
      incr lnum
      if {[regexp $pattern $line]} {
          incr occ
          puts "The pattern is present in line: $lnum"
          puts "$line"
      } else {
         puts "not found"
      }
   }
   puts "total number of occurencese : $occ"
   close $file
}

the program is working fine but the thing is i am retrieving lines that i dont want to along with the expected line. As the number (1) which i want to retrieve is present in the other strings such as 11, 21, 14 etc these lines are also getting printed.

kindly tolerate my unclear way of explaining the question.

Body:
You can solve the problem using word boundaries as suggested by glen but you can also consider the following things:

If after every line number there is a . then you can use it as delimiter in regular expression

regexp "^$lineNo\\." $a

I would also suggest to use ^ (match at the beginning of line) so that even if number is present in the line elsewhere it would not get counted.

tcl word boundaries are well explained at http://www.regular-expressions.info/wordboundaries.html


问:
Chart JS tick options not working for y axis
I have been struggling to make a chart.js line chart start at 0 when all of the values are 0. If all of the data of a dataset is 0 the y axis will always show values below 0 which I don't want there.

Here is the example:

```<code><div class="container">
    <canvas id="lineChart"></canvas>
    <script>
        var ctx = document.getElementById('lineChart');
        var lineChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: [1,2,3],
                datasets: [{
                    data: [0, 0, 0]
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        ticks: {
                            beginAtZero:true
                        }
                    }
                }
            }
        });
    </script>
<div>
</code>```

As you can see I am changing the options the scales as suggested in the documentation here (apparently there has been migration and this is the way to go in v3, which is what I am using). But the graph still won't start at 0:

Any axis options other than the ticks work correctly.
Any ideas of what I might be doing wrong?

答:
You tried to place the beginAtZero in the V2 place, in V3 you have to put it in the root of the scale object like so:

const options = {
  type: 'line',
  data: {
    labels: [1, 2, 3],
    datasets: [{
      label: '# of Votes',
      data: [0, 0, 0],
      borderColor: 'pink'
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body></code>```

For all changes between V2 and V3 you can read the migration guide

Body:
I have been struggling to make a chart.js line chart start at 0 when all of the values are 0. If all of the data of a dataset is 0 the y axis will always show values below 0 which I don't want there.

Here is the example:

    <canvas id="lineChart"></canvas>

As you can see I am changing the options the scales as suggested in the documentation here (apparently there has been migration and this is the way to go in v3, which is what I am using). But the graph still won't start at 0:

Any axis options other than the ticks work correctly.
Any ideas of what I might be doing wrong?

Body:
You tried to place the beginAtZero in the V2 place, in V3 you have to put it in the root of the scale object like so:

const options = {
  type: 'line',
  data: {
    labels: [1, 2, 3],
    datasets: [{
      label: '# of Votes',
      data: [0, 0, 0],
      borderColor: 'pink'
    }]
  },
  options: {
    scales: {
      y: {
        beginAtZero: true
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

For all changes between V2 and V3 you can read the migration guide


问:
crossAxisAlignment: CrossAxisAlignment.end doesn't work
I am pretty new to programming and also to Flutter, so please excuse me if my question is silly. I am trying to push Skip button to the bottom left corner of the screen. But the crossAxisAlignment: CrossAxisAlignment.end code doesn't work. How could I do this the right way so it can adapt to all screen formats properly? The problematic part is at the bottom of the entire code. Thank you in advance!

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15, top: 30),
            width: 230,
            decoration: BoxDecoration(),
            child: Image.asset('images/logo1.png'),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, top: 30),
            child: Text(
              'Login',
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 30),
            height: 50,
            width: double.infinity,
            child: Text(
              'E-mail',
              style: TextStyle(fontSize: 20, color: Colors.black54),
            ),
            padding: EdgeInsets.only(top: 10, left: 15, bottom: 10),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: Colors.black54,
              ),
              borderRadius: BorderRadius.all(
                Radius.circular(7),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 15),
            height: 50,
            width: double.infinity,
            child: Text(
              'Password',
              style: TextStyle(fontSize: 20, color: Colors.black54),
            ),
            padding: EdgeInsets.only(top: 10, left: 15, bottom: 10),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: Colors.black54,
              ),
              borderRadius: BorderRadius.all(
                Radius.circular(7),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 15),
            child: MaterialButton(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(7),
              ),
              height: 50.0,
              minWidth: double.infinity,
              color: Colors.orangeAccent,
              child: Text(
                "Login",
                style: TextStyle(
                  fontSize: 20.0,
                  color: Colors.white,
                ),
              ),
              onPressed: () => {},
              splashColor: Colors.redAccent,
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 5),
            child: Center(
              child: TextButton(
                style: TextButton.styleFrom(
                  textStyle: TextStyle(fontSize: 17),
                ),
                onPressed: () {},
                child: Text(
                  'Forgot your password?',
                  style: TextStyle(color: Colors.black54),
                ),
              ),
            ),
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Container(
                margin: EdgeInsets.only(top: 5),
                child: TextButton(
                  style: TextButton.styleFrom(
                    textStyle: TextStyle(fontSize: 17),
                  ),
                  onPressed: () {},
                  child: Text(
                    'Skip',
                    style: TextStyle(color: Colors.black54),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
```

Mobile Display

答:
Remove Row(). Add alignment: Alignment.centerRight, to your Container.

```<code>Container(
            margin: EdgeInsets.only(top: 5),
            alignment: Alignment.centerRight,
            child: TextButton(
              style: TextButton.styleFrom(
                textStyle: TextStyle(fontSize: 17),
              ),
              onPressed: () {},
              child: Text(
                'Skip',
                style: TextStyle(color: Colors.black54),
              ),
            ),
          ),
</code>```

Body:
I am pretty new to programming and also to Flutter, so please excuse me if my question is silly. I am trying to push Skip button to the bottom left corner of the screen. But the crossAxisAlignment: CrossAxisAlignment.end code doesn't work. How could I do this the right way so it can adapt to all screen formats properly? The problematic part is at the bottom of the entire code. Thank you in advance!

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(left: 15, top: 30),
            width: 230,
            decoration: BoxDecoration(),
            child: Image.asset('images/logo1.png'),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, top: 30),
            child: Text(
              'Login',
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 30),
            height: 50,
            width: double.infinity,
            child: Text(
              'E-mail',
              style: TextStyle(fontSize: 20, color: Colors.black54),
            ),
            padding: EdgeInsets.only(top: 10, left: 15, bottom: 10),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: Colors.black54,
              ),
              borderRadius: BorderRadius.all(
                Radius.circular(7),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 15),
            height: 50,
            width: double.infinity,
            child: Text(
              'Password',
              style: TextStyle(fontSize: 20, color: Colors.black54),
            ),
            padding: EdgeInsets.only(top: 10, left: 15, bottom: 10),
            decoration: BoxDecoration(
              border: Border.all(
                width: 1,
                color: Colors.black54,
              ),
              borderRadius: BorderRadius.all(
                Radius.circular(7),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15, right: 15, top: 15),
            child: MaterialButton(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(7),
              ),
              height: 50.0,
              minWidth: double.infinity,
              color: Colors.orangeAccent,
              child: Text(
                "Login",
                style: TextStyle(
                  fontSize: 20.0,
                  color: Colors.white,
                ),
              ),
              onPressed: () => {},
              splashColor: Colors.redAccent,
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 5),
            child: Center(
              child: TextButton(
                style: TextButton.styleFrom(
                  textStyle: TextStyle(fontSize: 17),
                ),
                onPressed: () {},
                child: Text(
                  'Forgot your password?',
                  style: TextStyle(color: Colors.black54),
                ),
              ),
            ),
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Container(
                margin: EdgeInsets.only(top: 5),
                child: TextButton(
                  style: TextButton.styleFrom(
                    textStyle: TextStyle(fontSize: 17),
                  ),
                  onPressed: () {},
                  child: Text(
                    'Skip',
                    style: TextStyle(color: Colors.black54),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

Mobile Display

Body:
Remove Row(). Add alignment: Alignment.centerRight, to your Container.

Container(
            margin: EdgeInsets.only(top: 5),
            alignment: Alignment.centerRight,
            child: TextButton(
              style: TextButton.styleFrom(
                textStyle: TextStyle(fontSize: 17),
              ),
              onPressed: () {},
              child: Text(
                'Skip',
                style: TextStyle(color: Colors.black54),
              ),
            ),
          ),


问:
How can I add css class to the to the nested element using DOM?
I have four child divs inside the container div, every child div has a button, image, and text inside. Images have to be blurry and text has to be hidden by default.

And when the user clicks the button, the button should be hidden, image and text should become clear and visible.

I'm trying to add or remove CSS classes from elements using for loop, but that just doesn't work at all...

let btns = document.querySelectorAll(".btn");
let images = document.querySelectorAll(".img");
let imgTexts = document.querySelectorAll(".img-text");

images.forEach((el) => el.classList.add("blur"));
imgTexts.forEach((el) => el.classList.add("hidden"));
for (let i = 0; i < btns; i++) {
  btns[i].addEventListener("click", function () {
    btns[i].classList.add("hidden");
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.blur {
  filter: blur(8px);
  -webkit-filter: blur(8px);
}
.hidden {
  display: none;
}</code>```

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

```

答:
There is not a boundation that you can create only one class. You can create multiple classes and just on and add and remove the class according to your need.
example code
HTML

```<code><img class = "image imageHidden" src = alt = >
<button class = "button buttonHidden">Click me</button>
</code>```

now I created two classes at the same time I can use them to my need in javascript
CSS

```<code>.image {
visiblity: visible}
.imageHidden {
visibility: hidden}
.button {
visibility: visible}
.buttonHidden {
visibility: hidden}
</code>```

now I used them in CSS that I can use in javascript

document.querySelector(".button").addEventListener("click",function () {

```<code>document.querySelector("img").classList.add("image");
document.querySelector("button").classList.add("buttonHidden");});
</code>```

this code will hide the button and show the image you can use this method according to your need.

Body:
I have four child divs inside the container div, every child div has a button, image, and text inside. Images have to be blurry and text has to be hidden by default.

And when the user clicks the button, the button should be hidden, image and text should become clear and visible.

I'm trying to add or remove CSS classes from elements using for loop, but that just doesn't work at all...

let btns = document.querySelectorAll(".btn");
let images = document.querySelectorAll(".img");
let imgTexts = document.querySelectorAll(".img-text");

images.forEach((el) => el.classList.add("blur"));
imgTexts.forEach((el) => el.classList.add("hidden"));
for (let i = 0; i < btns; i++) {
  btns[i].addEventListener("click", function () {
    btns[i].classList.add("hidden");
  });
}

.blur {
  filter: blur(8px);
  -webkit-filter: blur(8px);
}
.hidden {
  display: none;
}

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

Body:
There is not a boundation that you can create only one class. You can create multiple classes and just on and add and remove the class according to your need.
example code
HTML

<img class = "image imageHidden" src = alt = >
<button class = "button buttonHidden">Click me</button>

now I created two classes at the same time I can use them to my need in javascript
CSS

.image {
visiblity: visible}
.imageHidden {
visibility: hidden}
.button {
visibility: visible}
.buttonHidden {
visibility: hidden}

now I used them in CSS that I can use in javascript

document.querySelector(".button").addEventListener("click",function () {

document.querySelector("img").classList.add("image");
document.querySelector("button").classList.add("buttonHidden");});

this code will hide the button and show the image you can use this method according to your need.


问:
django: unable to save new user
I'm trying to build a view that shows a form for creating a new user.

Next are the template I'm using, urls.py and the code attempts at views.py and forms.py.

```<code>user_form.html

    <form action="{% url 'app:register' %}" method="post">
        {% csrf_token %}
        {{form.as_p}}
    <input type="submit" value="Register">
    </form>
</code>```
```<code>urls.py

urlpatterns = [
    ...
    path('newuser/',views.NewUser.as_view(), name='newuser'),
    ...
]
</code>```

First attempt:

```<code>views.py

class NewUser(generic.CreateView):
    model = User
    fields = ['username','email','password']
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('register')
</code>```

This one didn't return errors, but was unable to save the new user data.

Second try involved creating a form for the occasion:

```<code>forms.py

class NewUserForm(forms.Form):
    username = forms.CharField(max_length=100)
    email = forms.EmailField()
    password = forms.PasswordInput()

views.py

class NewUser(generic.CreateView):
    model = User
    form_class = NewUserForm
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('register')
</code>```

This one returned an error: TypeError at /newuser/ BaseForm.__init__() got an unexpected keyword argument 'instance'

Third:

```<code>forms.py

class NewUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username','email','password']

views.py

class NewUser(generic.CreateView):
    model = User
    form_class = NewUserForm
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('cadastro')

</code>```

Can't save a new User instance either.
I've also noticed that the model = User line in this last try can be removed.

I'm using the User.objects.all() query in the terminal and the admin page to check for new users.

What am I not doing?

答:
when you use CreateView on a model, it calls create method.

but User model is different. User model doesn't have create, instead have create_user. and CreateView doesn't know about it.
i suggest that you use View class like this:

```<code>class UserRegisterView(View):
    form_class = UserRegistrationForm
    template_name = 'account/register.html'

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('home:home')
        return super().dispatch(request, *args, **kwargs)

    def get(self, request):
        form = self.form_class()
        return render(request, self.template_name, {'form':form})

    def post(self, request):
        form = self.form_class(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            User.objects.create_user(cd['username'], cd['email'], cd['password1'])
            messages.success(request, 'you registered successfully', 'success')
            return redirect('home:home')
        return render(request, self.template_name, {'form':form})
</code>```

this snippet totally works.

Title: django: unable to save new user

Body:
I'm trying to build a view that shows a form for creating a new user.

Next are the template I'm using, urls.py and the code attempts at views.py and forms.py.

user_form.html

    <form action="{% url 'app:register' %}" method="post">
        {% csrf_token %}
        {{form.as_p}}
    <input type="submit" value="Register">
    </form>

urls.py

urlpatterns = [
    ...
    path('newuser/',views.NewUser.as_view(), name='newuser'),
    ...
]

First attempt:

views.py

class NewUser(generic.CreateView):
    model = User
    fields = ['username','email','password']
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('register')

This one didn't return errors, but was unable to save the new user data.

Second try involved creating a form for the occasion:

forms.py

class NewUserForm(forms.Form):
    username = forms.CharField(max_length=100)
    email = forms.EmailField()
    password = forms.PasswordInput()

views.py

class NewUser(generic.CreateView):
    model = User
    form_class = NewUserForm
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('register')

This one returned an error: TypeError at /newuser/ BaseForm.__init__() got an unexpected keyword argument 'instance'

Third:

forms.py

class NewUserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username','email','password']

views.py

class NewUser(generic.CreateView):
    model = User
    form_class = NewUserForm
    template_name = 'app/user_form.html'
    success_url = reverse_lazy('cadastro')

Can't save a new User instance either.
I've also noticed that the model = User line in this last try can be removed.

I'm using the User.objects.all() query in the terminal and the admin page to check for new users.

What am I not doing?

Body:
when you use CreateView on a model, it calls create method.

but User model is different. User model doesn't have create, instead have create_user. and CreateView doesn't know about it.
i suggest that you use View class like this:

class UserRegisterView(View):
    form_class = UserRegistrationForm
    template_name = 'account/register.html'

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('home:home')
        return super().dispatch(request, *args, **kwargs)

    def get(self, request):
        form = self.form_class()
        return render(request, self.template_name, {'form':form})

    def post(self, request):
        form = self.form_class(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            User.objects.create_user(cd['username'], cd['email'], cd['password1'])
            messages.success(request, 'you registered successfully', 'success')
            return redirect('home:home')
        return render(request, self.template_name, {'form':form})

this snippet totally works.


问:
Pandas - Data representation
I want to improve my data science skills, so I am working on a private project about paramedic events in my region. Therefore I have several Excel list from the year 2004 until 2021. Each excel list contains the same rows and columns - just different data. Just like
2004:

A
B
C

X
1
2
3

Y
4
5
6

Z
7
8
9

2005:

A
B
C

X
9
8
7

Y
6
5
4

Z
3
2
1

What is now the best way to represent these Data as pandas dataframe? Yes I can make a list of dataframes, but this isn't very pythonic.
I'm looking forward for your help ;-)
Regards Michael

答:
Assuming you have a list of the dataframes in order, use pandas.concat:

```<code>lst = [df1, df2]
years = [2004, 2005]
df = pd.concat(lst, keys=years)
</code>```

output:

```<code>        A  B  C
2004 X  1  2  3
     Y  4  5  6
     Z  7  8  9
2005 X  9  8  7
     Y  6  5  4
     Z  3  2  1
</code>```

or, for a wide format:

```<code>pd.concat(lst, keys=years, axis=1)
</code>```

output:

```<code>  2004       2005
     A  B  C    A  B  C
X    1  2  3    9  8  7
Y    4  5  6    6  5  4
Z    7  8  9    3  2  1
</code>```

Title: Pandas - Data representation

Body:
Assuming you have a list of the dataframes in order, use pandas.concat:

lst = [df1, df2]
years = [2004, 2005]
df = pd.concat(lst, keys=years)

output:

        A  B  C
2004 X  1  2  3
     Y  4  5  6
     Z  7  8  9
2005 X  9  8  7
     Y  6  5  4
     Z  3  2  1

or, for a wide format:

pd.concat(lst, keys=years, axis=1)

output:

  2004       2005
     A  B  C    A  B  C
X    1  2  3    9  8  7
Y    4  5  6    6  5  4
Z    7  8  9    3  2  1


问:
Permission to only read Wallet Address
I just want to collect the user's Wallet Address. I think these permission are too much. I don't need to see balance or initiate transactions. Just read-wallet-address.

What is the easiest and clean way to get the wallet address?
This is the code I am using:

```<code>const provider = new ethers.providers.Web3Provider(window.ethereum)
await provider.send("eth_requestAccounts", []);
signer = provider.getSigner()
const walletAddress = await signer.getAddress()
</code>```

答:
This is currently the only option. There's no "read address but cannot request transactions" permission type. Your code is correct.

Docs: https://docs.metamask.io/guide/rpc-api.html#eth-requestaccounts

Title: Permission to only read Wallet Address

Body:
I just want to collect the user's Wallet Address. I think these permission are too much. I don't need to see balance or initiate transactions. Just read-wallet-address.

What is the easiest and clean way to get the wallet address?
This is the code I am using:

const provider = new ethers.providers.Web3Provider(window.ethereum)
await provider.send("eth_requestAccounts", []);
signer = provider.getSigner()
const walletAddress = await signer.getAddress()


问:
Magento 2 commands. setup update let theme disappear
I have Magento 2.
I edit a module and then i try run this command code:

```<code>php -dmemory_limit=5G -f bin/magento setup:upgrade
</code>```

But i after done that site and back-end theme disappear so i have to run this command always:

```<code>php -dmemory_limit=5G -f bin/magento setup:static-content:deploy -f
</code>```

Is it possible to prevent the site from falling down after upgrading a module?

答:
This is how it's meant to work (production mode).

The module you enable is likely to contain it's own templates, layouts, static content etc.
The second command is how magento gathers the static content from all modules so they are actually usable on the front-end website.

Body:
I have Magento 2.
I edit a module and then i try run this command code:

php -dmemory_limit=5G -f bin/magento setup:upgrade

But i after done that site and back-end theme disappear so i have to run this command always:

php -dmemory_limit=5G -f bin/magento setup:static-content:deploy -f

Is it possible to prevent the site from falling down after upgrading a module?


问:
How to send data from a Windows Form Application to a Asp.Net Web Service Application
I have a Windows Form Application connected to a database. It does some simple select operations and shows the result on the DataGridView.

I want to send that data on the grid to a web service. I did some research on the Internet about web services and found that I can easily creat a web service, define its methods and use these methods from my Windows Form Application by using Visual Studio 2010. Unfortunately, that is not what I want. I already have a Windows Form Application with some methods in it. All I want is to send the data (xml) to a web service that I created in Visual Studio. How can I do that?

Thanks in advance.

答: See "How to Consume a Web Service".</p>

Body: See "How to Consume a Web Service".


问:
Why is pypy flask aplication slower than cpython?
I have a flask application (app.py) which returns a string,

```<code>from flask import Flask
import os

app = Flask(__name__)

@app.route("/")
def hello():
    return "Flask inside Docker!!"

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 6000))
    app.run(debug=True,host='0.0.0.0',port=port)
</code>```

I ran this application using the below dockerfile content, which gave me the throughput of 320/sec

```<code>FROM opensuse/leap:15.3
RUN zypper -n install python3 python3-pip python3-Flask
COPY . /app
WORKDIR /app
ENTRYPOINT ["python3"]
CMD ["app.py"]

</code>```

However with pypy3, I got only 200/sec throughput, the docker file is given below.

```<code>FROM opensuse/leap:15.3
FROM pypy:3
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["pypy3"]
CMD ["app.py"]

</code>```

where requirements.txt contains only "flask".

What could be the reason for this performance degradation?

答:
Two things comes to mind.

It could be that running a basic app that just return a string doesn't really make use of pypy JIT compilation and other pypy optimizations. And in this specific case pypy interpreter is running slower

Are you wrapping flask with gunicorn? if so and even if you dont, could it be that you set it up in a way that each invocation is executed in a new process? If each invocation is a new process, pypy JIT warmup is lost between each invocation, which means JIT is basically not working and you are just paying high price of pypy trying to JIT.

Body:
I have a flask application (app.py) which returns a string,

from flask import Flask
import os

app = Flask(__name__)

@app.route("/")
def hello():
    return "Flask inside Docker!!"

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 6000))
    app.run(debug=True,host='0.0.0.0',port=port)

I ran this application using the below dockerfile content, which gave me the throughput of 320/sec

FROM opensuse/leap:15.3
RUN zypper -n install python3 python3-pip python3-Flask
COPY . /app
WORKDIR /app
ENTRYPOINT ["python3"]
CMD ["app.py"]

However with pypy3, I got only 200/sec throughput, the docker file is given below.

FROM opensuse/leap:15.3
FROM pypy:3
COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
ENTRYPOINT ["pypy3"]
CMD ["app.py"]

where requirements.txt contains only "flask".

What could be the reason for this performance degradation?


问:
How to remove a Client event listener?
I have a <Client>.on function and I want to stop the listening of this event, example:

```<code>bot.on('messageCreate', message => {
  // some code
});
</code>```

How to stop it and not receive this event anymore?

答:
You ran into an issue I was troubleshooting myself, trying to filter events per each server and I finally had figured it out.
In this instance I am using the bot object rather than client. But this is how you can filter a singular event per server, just add onto the if/else statements. I am only going to note the method for the channelCreate, but the concept applies to most of the events you can listen to. In the documentation it noted that channel types are integers, but in my debugging it showed them as a string. On the if statement line, the method works by checking where the creation channel resides in (guild it was created in), if that matches your criteria then it continues.

bot.on("channelCreate", (channel) => {
    if(channel.guild.id == "######"){
        if(channel.type == 4 || channel.type == "category"){
            console.log(`Category Created: ID: ${channel.id} Name: ${channel.name}`)
        }
        else if(channel.type == 0 || channel.type == "text"){
            console.log(`Channel Created: ID: ${channel.id} Name: ${channel.name}`)
        }
    }
    else if (channel.guild.id == "######"){
      //do other stuff
    }
});
```

Links:

Discord Documentation that lists events:
https://discord.js.org/#/docs/main/stable/class/Client

A nice github gist to see functions:
https://gist.github.com/koad/316b265a91d933fd1b62dddfcc3ff584

Channel Types:
https://discord.js.org/#/docs/main/stable/typedef/ChannelType
https://discord.com/developers/docs/resources/channel#channel-object-channel-types

Title: How to remove a Client event listener?

Body:
I have a <Client>.on function and I want to stop the listening of this event, example:

bot.on('messageCreate', message => {
  // some code
});

How to stop it and not receive this event anymore?

Body:
You ran into an issue I was troubleshooting myself, trying to filter events per each server and I finally had figured it out.
In this instance I am using the bot object rather than client. But this is how you can filter a singular event per server, just add onto the if/else statements. I am only going to note the method for the channelCreate, but the concept applies to most of the events you can listen to. In the documentation it noted that channel types are integers, but in my debugging it showed them as a string. On the if statement line, the method works by checking where the creation channel resides in (guild it was created in), if that matches your criteria then it continues.

bot.on("channelCreate", (channel) => {
    if(channel.guild.id == "######"){
        if(channel.type == 4 || channel.type == "category"){
            console.log(`Category Created: ID: ${channel.id} Name: ${channel.name}`)
        }
        else if(channel.type == 0 || channel.type == "text"){
            console.log(`Channel Created: ID: ${channel.id} Name: ${channel.name}`)
        }
    }
    else if (channel.guild.id == "######"){
      //do other stuff
    }
});

Links:

Discord Documentation that lists events:
https://discord.js.org/#/docs/main/stable/class/Client

A nice github gist to see functions:
https://gist.github.com/koad/316b265a91d933fd1b62dddfcc3ff584

Channel Types:
https://discord.js.org/#/docs/main/stable/typedef/ChannelType
https://discord.com/developers/docs/resources/channel#channel-object-channel-types