问:
ASP.NET Parser Error Cannot load code behind
Hey I am getting the following error

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type '_AddToCart'.

Source Error:

```<code>Line 1:  <%@ Page Language="C#" AutoEventWireup="true" Codebehind="AddToCart.aspx.cs" Inherits="_AddToCart" Title="Untitled Page" %>
Line 2:
Line 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Source File: /FSAICart/AddToCart.aspx    Line: 1
</code>```

Where I do have the matching code behind file which is defined as follows

```<code>    using System;
  public partial class _AddToCart : System.Web.UI.Page {
</code>```

Any Ideas ?

答:
Try changing CodeBehind:

```<code><%@ Page Language="C#"
AutoEventWireup="true"
**Codebehind**="AddToCart.aspx.cs"
Inherits="_AddToCart" Title="Untitled
Page" %>
</code>```

To CodeFile:

```<code><%@ Page Language="C#"
AutoEventWireup="true"
**CodeFile**="AddToCart.aspx.cs"
Inherits="_AddToCart" Title="Untitled
Page" %>
</code>```

ASP .NET 1.1 used CodeBehind for compiling code in a separate file. ASP .NET 2.0 introduced the CodeFile syntax for compilation of partial classes.

See here for a more detailed explanation.

Body:
Hey I am getting the following error

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type '_AddToCart'.

Source Error:

Line 1:  <%@ Page Language="C#" AutoEventWireup="true" Codebehind="AddToCart.aspx.cs" Inherits="_AddToCart" Title="Untitled Page" %>
Line 2:
Line 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Source File: /FSAICart/AddToCart.aspx    Line: 1

Where I do have the matching code behind file which is defined as follows

    using System;
  public partial class _AddToCart : System.Web.UI.Page {

Any Ideas ?

Body:
Try changing CodeBehind:

<%@ Page Language="C#"
AutoEventWireup="true"
**Codebehind**="AddToCart.aspx.cs"
Inherits="_AddToCart" Title="Untitled
Page" %>

To CodeFile:

<%@ Page Language="C#"
AutoEventWireup="true"
**CodeFile**="AddToCart.aspx.cs"
Inherits="_AddToCart" Title="Untitled
Page" %>

ASP .NET 1.1 used CodeBehind for compiling code in a separate file. ASP .NET 2.0 introduced the CodeFile syntax for compilation of partial classes.

See here for a more detailed explanation.


来源: stackexchange

问:
paper_trail 7.1.3 Support for ActiveRecord < 4.2
We are using rails 4.1.15 & ActiveRecord 4.1.15. We integrated with the latest version of paper_trail(7.1.3) that supports our rails version.

When using this, we receive a warning:

DEPRECATION WARNING: Your version of ActiveRecord (< 4.2) has reached EOL. PaperTrail will soon drop support. Please upgrade ActiveRecord ASAP.
(This change was added in March 2017 as part of commit)

As we have a huge application and no current plans to upgrade our rails, wanted to understand a few things:

PaperTrail will soon drop support - When will this happen?

When PaperTrail does drop support, what will be the impact? I assume that it will work just fine. Is there something we need to be careful of?

Is there is a way to suppress this warning?

答:
DEPRECATION WARNING: Your version of ActiveRecord (< 4.2) has reached EOL. PaperTrail will soon drop support. Please upgrade ActiveRecord ASAP. (This change was added in March 2017 as part of commit)

PaperTrail will soon drop support - When will this happen?

This happened years ago. See the changelog for exact date.

When PaperTrail does drop support, what will be the impact? I assume that it will work just fine. Is there something we need to be careful of?

You can continue to use old, unsupported versions of PT and/or rails as long as you want.

Is there is a way to suppress this warning?

You could fork PT, or pipe to /dev/null.

ContentLicense: CC BY-SA 4.0


问:
How to test HTML content with React testing library
Currently I am writing a test to test the content that is inside (HTML content), but it seems I cannot test that properly with React testing library. It can find the id value of that, but how do I get the HTML content inside that element.

import React from 'react';

export const TopBar = () => {
    return (

Dashboard Menu

    )
}

import React from "react";
import { render } from "@testing-library/react";
import { TopBar } from "./TopBar";
import { Provider } from "react-redux";
import { store } from "../../Store";
import { screen } from "@testing-library/dom";
import "@testing-library/jest-dom/extend-expect";

test("It should check if content matches", () => {
    render(
        <Provider store={store}>
            <TopBar/>
        </Provider>
    )
    const checkContent = screen.getAllByTestId("title-content");
    expect(checkContent.text()).toBe("Dashboard Menu");
});```

答:
You're using "@testing-library/jest-dom/extend-expect" which provides a set of custom jest matchers that you can use, fore example you have toHaveTextContent(text: string | RegExp, options?: {normalizeWhitespace: boolean}) that you can use here:

```<code>const checkContent = screen.getByTestId("title-content");
expect(checkContent).toHaveTextContent("Dashboard Menu");
</code>```

Body:
You're using "@testing-library/jest-dom/extend-expect" which provides a set of custom jest matchers that you can use, fore example you have toHaveTextContent(text: string | RegExp, options?: {normalizeWhitespace: boolean}) that you can use here:

const checkContent = screen.getByTestId("title-content");
expect(checkContent).toHaveTextContent("Dashboard Menu");


问:
Is there anyway in python to retrieve a line from a .txt file randomly, then print it and do this multiple times without repeating the same one?
currently, I can only randomly select a line. but I don't know how to prevent it from being repeated. how would I do this?</p>

```<code>  Proxy = None
  for line in fileinput.input("file.path"):
      if random.randrange(fileinput.lineno()) == 0:
        Proxy = line
</code>```

答:
If you can keep all the file in memory you can use random in order to shuffle it and then print the shuffled lines.

```<code>import random
random.sample(lines, len(lines))
</code>```

You can also shuffle them in place using random.shuffle(lines)

Body:
currently, I can only randomly select a line. but I don't know how to prevent it from being repeated. how would I do this?

  Proxy = None
  for line in fileinput.input("file.path"):
      if random.randrange(fileinput.lineno()) == 0:
        Proxy = line

Body:
If you can keep all the file in memory you can use random in order to shuffle it and then print the shuffled lines.

import random
random.sample(lines, len(lines))

You can also shuffle them in place using random.shuffle(lines)


问:
Trying to pass binary files through Logstash
Some process is producing into my Kafka binary files (from Java it comes as bytearray).

I'm trying to consume from Kafka with Logstash and upload the file into s3.

My pipeline:

```<code>input {
  kafka {
    bootstrap_servers => "my-broker:9092"
    topic => "my-topic"
    partition_assignment_strategy => "org.apache.kafka.clients.consumer.StickyAssignor"
    value_deserializer_class => "org.apache.kafka.common.serialization.ByteArrayDeserializer"
  }
}
filter {
  mutate {
    remove_field => ["@timestamp", "host"]
  }
}
output {
  s3 {
    region => "eu-west-1"
    bucket => "my_bucket"
    time_file => 1
    prefix => "files/"
    rotation_strategy => "time"
  }
}
</code>```

As you can see I used a different deserializer class. However, it seems that Logstash uses by default a coded that converts the bytes array to string. My goal is to upload the file to s3 as it is. Is there any codec known that doesn't do anything to the input data and upload it as it is to?

Right now the files are uploaded to s3, but I can't read them or open them. The binary content was corrupted by Logstash somehow. For example - I tried sending a gzip that contains multiple files inside and I can't open it afterwards in s3.

The warning that I get on Logstash:

```<code>0-06-02T10:49:29,149][WARN ][logstash.codecs.plain    ][my_pipeline] Received an event that has a different character encoding than you configured. {:text=>"7z\\xBC\\xAF'\\u001C\\u0000\\u0002\\xA6j<........more binary data", :expected_charset=>"UTF-8"}
</code>```

答:
I don't think you really understand what logstash is for.

As it's name log-stash it is for streaming ascii type of files using EOL delimiter to deffer between different log events.

I did managed to find community developed kafkaBeat for reading data from Kafka Topics, there are 2 options:

kafkabeat - Reads data from Kafka topics.

kafkabeat2 - Reads data (json or plain) from Kafka topics.

I didn't test those my own, but using the S3 output option with those might do the trick. If the S3 option is not yet supported you can develop it yourself and push it to the open-source so everyone can enjoy it :-)

Body:
Some process is producing into my Kafka binary files (from Java it comes as bytearray).

I'm trying to consume from Kafka with Logstash and upload the file into s3.

My pipeline:

input {
  kafka {
    bootstrap_servers => "my-broker:9092"
    topic => "my-topic"
    partition_assignment_strategy => "org.apache.kafka.clients.consumer.StickyAssignor"
    value_deserializer_class => "org.apache.kafka.common.serialization.ByteArrayDeserializer"
  }
}
filter {
  mutate {
    remove_field => ["@timestamp", "host"]
  }
}
output {
  s3 {
    region => "eu-west-1"
    bucket => "my_bucket"
    time_file => 1
    prefix => "files/"
    rotation_strategy => "time"
  }
}

As you can see I used a different deserializer class. However, it seems that Logstash uses by default a coded that converts the bytes array to string. My goal is to upload the file to s3 as it is. Is there any codec known that doesn't do anything to the input data and upload it as it is to?

Right now the files are uploaded to s3, but I can't read them or open them. The binary content was corrupted by Logstash somehow. For example - I tried sending a gzip that contains multiple files inside and I can't open it afterwards in s3.

The warning that I get on Logstash:

0-06-02T10:49:29,149][WARN ][logstash.codecs.plain    ][my_pipeline] Received an event that has a different character encoding than you configured. {:text=>"7z\\xBC\\xAF'\\u001C\\u0000\\u0002\\xA6j<........more binary data", :expected_charset=>"UTF-8"}


问:
How to loop over multiple fields in Django template?
I have models that inherit from an abstract model like this:

```<code>class ImprovementAbstraction(models.Model):
    needsImprovement = models.BooleanField()
    hasFallacies = models.BooleanField()
    hasEmotionalDeficiency = models.BooleanField()
    isNecessaryToObtain = models.BooleanField()
    doesAReallyCauseB = models.BooleanField()
    areAllStepsPresent = models.BooleanField()
    isCauseSufficient = models.BooleanField()
    areAllClausesIdentified = models.BooleanField()
    isCausalityCertain = models.BooleanField()
    languageIsEnglish = models.BooleanField()
    isTautologyPresent = models.BooleanField()

    class Meta:
        abstract = True

class Assumption(MainAbstractModel, ImprovementAbstraction):
    need = models.ForeignKey(Need, on_delete=models.SET_NULL, null=True)
    assumption = models.CharField(max_length=500, default="", null=True)

    def __str__(self):
        return self.assumption
</code>```

In the template I would like to display all of the "ToImprovementAbstraction" Model fields associated with the Assumption model. Is there a way to loop over all the fields in the template, something like Assumption.ImprovementAbstractionFields.all() (made up code)?

答:
get the assumption object in view and render the ImprovementAbstraction through foreign key. for example:

```<code>def get_item():
  queryset = Assumption.objects.all()

return render(request, 'template.html', {'queryset': queryset})
</code>```

Now in your template you can access the data this way

```<code>{% for query in queryset %}
  {{query.need.needImprovement}}
  {{query.need.hasFallacies}}
  {{...}}

 {% endfor %}
</code>```

This way you can display everything in one loop. Hope this gets you some idea.

Body:
I have models that inherit from an abstract model like this:

class ImprovementAbstraction(models.Model):
    needsImprovement = models.BooleanField()
    hasFallacies = models.BooleanField()
    hasEmotionalDeficiency = models.BooleanField()
    isNecessaryToObtain = models.BooleanField()
    doesAReallyCauseB = models.BooleanField()
    areAllStepsPresent = models.BooleanField()
    isCauseSufficient = models.BooleanField()
    areAllClausesIdentified = models.BooleanField()
    isCausalityCertain = models.BooleanField()
    languageIsEnglish = models.BooleanField()
    isTautologyPresent = models.BooleanField()

    class Meta:
        abstract = True

class Assumption(MainAbstractModel, ImprovementAbstraction):
    need = models.ForeignKey(Need, on_delete=models.SET_NULL, null=True)
    assumption = models.CharField(max_length=500, default="", null=True)

    def __str__(self):
        return self.assumption

In the template I would like to display all of the "ToImprovementAbstraction" Model fields associated with the Assumption model. Is there a way to loop over all the fields in the template, something like Assumption.ImprovementAbstractionFields.all() (made up code)?

Body:
get the assumption object in view and render the ImprovementAbstraction through foreign key. for example:

def get_item():
  queryset = Assumption.objects.all()

return render(request, 'template.html', {'queryset': queryset})

Now in your template you can access the data this way

{% for query in queryset %}
  {{query.need.needImprovement}}
  {{query.need.hasFallacies}}
  {{...}}

 {% endfor %}

This way you can display everything in one loop. Hope this gets you some idea.


问:
Unit Test case for pre hook in mongoose using jest
i AM trying to write a unit test case for pre-hook. I was facing the issue in condition to check this.isNew when I pass the document in the console it prints as undefined. Can anyone tell me what's wrong in this code?

schema

```<code>// hooks callback
    export async function arrayCount(this: any, next: NextFunction) {
      if (this.isNew) {
        const parentArray = (this as any).parentArray();
        const maxSequence = parentArray.reduce((maximum: number, review: ReviewRatingType) => {
          if (review.review_rating_no) {
            const sequenceString = review.review_rating_no.match(/\d+/g);
            if (!sequenceString) {
              throw new Error('Invalid sequence in array.');
            }
            const sequenceNumber = parseInt(sequenceString.toString());
            if (sequenceNumber > maximum) {
              maximum = sequenceNumber;
            }
          }
          return maximum;
        }, 0);
        const sequence = 'RAT' + (maxSequence + 1 + '').padStart(3, '0');
        this.set({ review_rating_no: sequence });
      }
      next();
    }
    /**
     * Product Review Schema.
     */
    @singleton()
    export class ReviewRatingSchema extends AbstractSchema {
      isSubDocument = true;
      entityName = 'review_rating';
      schemaDefinition = {
        review_rating_user_id: {
          type: ObjectId,
          required: [true, 'review_rating_user_id is required'],
          ref: 'UserModel',
          unique: true,
        },
        review_rating_user_full_name: {
          type: String,
          trim: true,
          minlength: 3,
          maxlength: 20,
          validate: {
            validator: function (value: string) {
              return RegexConstants.betaRegex.test(value);
            },
            message: 'review_rating_user_full_name is invalid.',
          },
          required: [true, 'review_rating_user_full_name is required'],
        },
        review_rating_user_rating: {
          type: String,
          minlength: 1,
          maxlength: 1,
          validate: {
            validator: function (value: string) {
              return RegexConstants.rating.test(value);
            },
            message: 'review_rating_user_rating is invalid.',
          },
          required: [true, 'review_rating_user_rating is required'],
        },
        review_rating_description: {
          type: String,
          trim: true,
          minlength: 10,
          maxlength: 500,
          validate: {
            validator: function (value: string) {
              return RegexConstants.alphaRegex.test(value);
            },
            message: 'review_rating_description is invalid.',
          },
          required: [true, 'review_rating_description is required'],
        },
      };

      indexes = ['review_rating_user_id'];

      hooks = () => {
        // sequence for review rating
        this.schema?.pre('save', arrayCount);
      };
    }
</code>```

Test Case

```<code>  describe('save hook', () => {
    it('should encrypt user password.', async () => {
      // Preparing
      const context = [
        {
          review_rating_status_is_active: false,
          review_rating_user_id: '5d5e6329a85f1a0ba718ceb3',
          review_rating_user_full_name: 'susdhassr',
          review_rating_modified_date: ' 2020-05-20T06:31:37.728Z',
        },
        {
          review_rating_status_is_active: false,
          review_rating_user_id: '5d5e6329a85f1a0ba718ceb5',
          review_rating_user_full_name: 'susdhassr',
          review_rating_modified_date: ' 2020-05-20T06:31:37.728Z',
        }
      ];
      for (let i in context){
        // console.log(context[i])
        await arrayCount.call(context[i], next);
      }
      // Verifying
      expect(next).toBeCalledTimes(2);
    });
  });
</code>```

答:
```<code>   it('should call next when valid document is passed.', async () => {
      // Preparing
      const ProductReview = [
        {
          review_rating_status_is_active: false,
          review_rating_user_id: '5d5e6329a85f1a0ba718ceb3',
          review_rating_user_full_name: 'susdhassr',
          review_rating_user_rating: '2',
          review_rating_description: 'W Ds as always, solid build, worthy product',
          review_rating_created_date: '2020-05-20T06:31:37.728Z',
          review_rating_modified_date: ' 2020-05-20T06:31:37.728Z',
        },
      ];
      const context = {
        isNew: jest.fn().mockReturnValue(ProductReview)
      };
      await arrayCount.call(context, next);
      // Verifying
      expect(next).toBeCalledTimes(1);
    });
</code>```

Body:
i AM trying to write a unit test case for pre-hook. I was facing the issue in condition to check this.isNew when I pass the document in the console it prints as undefined. Can anyone tell me what's wrong in this code?

schema

// hooks callback
    export async function arrayCount(this: any, next: NextFunction) {
      if (this.isNew) {
        const parentArray = (this as any).parentArray();
        const maxSequence = parentArray.reduce((maximum: number, review: ReviewRatingType) => {
          if (review.review_rating_no) {
            const sequenceString = review.review_rating_no.match(/\d+/g);
            if (!sequenceString) {
              throw new Error('Invalid sequence in array.');
            }
            const sequenceNumber = parseInt(sequenceString.toString());
            if (sequenceNumber > maximum) {
              maximum = sequenceNumber;
            }
          }
          return maximum;
        }, 0);
        const sequence = 'RAT' + (maxSequence + 1 + '').padStart(3, '0');
        this.set({ review_rating_no: sequence });
      }
      next();
    }
    /**
     * Product Review Schema.
     */
    @singleton()
    export class ReviewRatingSchema extends AbstractSchema {
      isSubDocument = true;
      entityName = 'review_rating';
      schemaDefinition = {
        review_rating_user_id: {
          type: ObjectId,
          required: [true, 'review_rating_user_id is required'],
          ref: 'UserModel',
          unique: true,
        },
        review_rating_user_full_name: {
          type: String,
          trim: true,
          minlength: 3,
          maxlength: 20,
          validate: {
            validator: function (value: string) {
              return RegexConstants.betaRegex.test(value);
            },
            message: 'review_rating_user_full_name is invalid.',
          },
          required: [true, 'review_rating_user_full_name is required'],
        },
        review_rating_user_rating: {
          type: String,
          minlength: 1,
          maxlength: 1,
          validate: {
            validator: function (value: string) {
              return RegexConstants.rating.test(value);
            },
            message: 'review_rating_user_rating is invalid.',
          },
          required: [true, 'review_rating_user_rating is required'],
        },
        review_rating_description: {
          type: String,
          trim: true,
          minlength: 10,
          maxlength: 500,
          validate: {
            validator: function (value: string) {
              return RegexConstants.alphaRegex.test(value);
            },
            message: 'review_rating_description is invalid.',
          },
          required: [true, 'review_rating_description is required'],
        },
      };

      indexes = ['review_rating_user_id'];

      hooks = () => {
        // sequence for review rating
        this.schema?.pre('save', arrayCount);
      };
    }

Test Case

  describe('save hook', () => {
    it('should encrypt user password.', async () => {
      // Preparing
      const context = [
        {
          review_rating_status_is_active: false,
          review_rating_user_id: '5d5e6329a85f1a0ba718ceb3',
          review_rating_user_full_name: 'susdhassr',
          review_rating_modified_date: ' 2020-05-20T06:31:37.728Z',
        },
        {
          review_rating_status_is_active: false,
          review_rating_user_id: '5d5e6329a85f1a0ba718ceb5',
          review_rating_user_full_name: 'susdhassr',
          review_rating_modified_date: ' 2020-05-20T06:31:37.728Z',
        }
      ];
      for (let i in context){
        // console.log(context[i])
        await arrayCount.call(context[i], next);
      }
      // Verifying
      expect(next).toBeCalledTimes(2);
    });
  });


问:
PHP: Extract string from another
i have some strings (address), all like this:

2 rue lambda, 75018, PARIS

I want to get the postal code, in this exemple "75018". I've been trying different solution, but i'm not familiar with escaped characters , and don't know how to detect coma in the string. Which function should i use to extract the postal code?

答:
If all your addresses are of France, which has a 5 digit postal code then you can use the following regex to capture it:

```<code>\b(\d{5})\b
</code>```

In PHP you can use it with preg_match as:

```<code>$input = '2 rue lambda, 75018, PARIS';
if(preg_match('/\b(\d{5})\b/',$input,$match)) {
   $postal_code = $match[1];
}
</code>```

Note that this will capture the first 5 digit number in the address. Generally the postal code comes at the end of the address, so we can improve the method by capturing the last 5 digit number in the address by using the regex:

```<code>.*\b(\d{5})\b
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP: Extract string from another

Body:
If all your addresses are of France, which has a 5 digit postal code then you can use the following regex to capture it:

\b(\d{5})\b

In PHP you can use it with preg_match as:

$input = '2 rue lambda, 75018, PARIS';
if(preg_match('/\b(\d{5})\b/',$input,$match)) {
   $postal_code = $match[1];
}

Note that this will capture the first 5 digit number in the address. Generally the postal code comes at the end of the address, so we can improve the method by capturing the last 5 digit number in the address by using the regex:

.*\b(\d{5})\b


答:
If your file doesn't have 78 billion lines, you can use this:

with open("file.path") as f:
    Proxy = random.choice(f.readlines())
```

<p>If you don't want the whole file in your memory, you can use this:</p>

<pre class="lang-py prettyprint-override"><code>def get_random_line():
    lines_to_skip = 0
    with open("file.path") as f:
        lines_to_skip = sum(1 for line in f)
    choice = random.randint(0, lines_to_skip)
    with open("file.path") as f:
        for line in f:
            if lines_to_skip <= 0:
                return line
            lines_to_skip -= 1
</code>```

It opens the file twice. The first loop is to count the lines and in the second loop it grabs the chosen line

Title: Is there anyway in python to retrieve a line from a .txt file randomly, then print it and do this multiple times without repeating the same one?

Body:
If your file doesn't have 78 billion lines, you can use this:

with open("file.path") as f:
    Proxy = random.choice(f.readlines())

If you don't want the whole file in your memory, you can use this:

def get_random_line():
    lines_to_skip = 0
    with open("file.path") as f:
        lines_to_skip = sum(1 for line in f)
    choice = random.randint(0, lines_to_skip)
    with open("file.path") as f:
        for line in f:
            if lines_to_skip <= 0:
                return line
            lines_to_skip -= 1

It opens the file twice. The first loop is to count the lines and in the second loop it grabs the chosen line


问:
What is function designator and actual call?
According to C99 Standard:

The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.

Could anyone explain clearly what is function designator and actual call; and what is difference between them ?

答:
"What is a function designator?"

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, 66) or the unary & operator, a function designator with type "function returning type" is converted to an expression that has type "pointer to function returning type".

66) Because this conversion does not occur, the operand of the sizeof operator remains a function designator and violates the constraints in 6.5.3.4.

Source: C18, §6.3.2.1/4 - "Lvalues, arrays, and function designators"

A function designator is an expression which identifies a certain function and that designates a function when evaluated.

```<code>int tip (int);
</code>```

tip (the name of the function)  is for example a function designator.

Or for example in:

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

int tip (int a) {
    return a;
}

int main (void) {

    int (**foo)(int);

    int (*bar[5])(int);

    bar[0] = &tip;

    foo = &bar;

    printf("%d", (**foo)(4));
}
</code>```

The pointer to pointer to function returning int foo - (**foo)(4) - is a function designator for the function tip.

"What is the function call?"

The function call is actually just the call to a function, like tip(4);.

Body:
"What is a function designator?"

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, 66) or the unary & operator, a function designator with type "function returning type" is converted to an expression that has type "pointer to function returning type".

66) Because this conversion does not occur, the operand of the sizeof operator remains a function designator and violates the constraints in 6.5.3.4.

Source: C18, §6.3.2.1/4 - "Lvalues, arrays, and function designators"

A function designator is an expression which identifies a certain function and that designates a function when evaluated.

int tip (int);

tip (the name of the function)  is for example a function designator.

Or for example in:

#include <stdio.h>

int tip (int a) {
    return a;
}

int main (void) {

    int (**foo)(int);

    int (*bar[5])(int);

    bar[0] = &tip;

    foo = &bar;

    printf("%d", (**foo)(4));
}

The pointer to pointer to function returning int foo - (**foo)(4) - is a function designator for the function tip.

"What is the function call?"

The function call is actually just the call to a function, like tip(4);.


问:
Is there something wrong with this SQL query
I am new to SQL queries and trying to understand it a little better.
Is this SQL query valid regarding the picture below
The question I was given was:

"For each book authored (or co-authored) by "Stephen King", retrieve the title and the number of copies owned by the librarybranch whose name is "Central"

```<code>SELECT Title
FROM BOOK
WHERE BookID =
(
 SELECT BookID
 FROM BOOK_AUTHORS
 WHERE AuthorName = 'Stephen King'
)
AND
BookID =
(
 SELECT BookID, No_Of_Copies
 FROM BOOK_COPIES
 WHERE BranchID =
 (
  SELECT BranchID
  FROM LIBRARY_BRANCH
  WHERE BranchName = 'Central'
 )
)
</code>```

答:
Please use below query, but the right approach is to use joins instead of multiple sub queries

Joins

```<code>SELECT B.Title
FROM BOOK B
inner join BOOK_AUTHORS BA
on (B.bookid = ba.bookid)
inner join BOOK_COPIES BC
on (B.bookid = BC.bookid)
inner join LIBRARY_BRANCH LB
on (BC.branchid = LB.branchid)
where B.AuthorName = 'Stephen King'
and LB.BranchName = 'Central';
</code>```

Subquery

```<code>SELECT Title
FROM BOOK
WHERE BookID in
(
 SELECT BookID
 FROM BOOK_AUTHORS
 WHERE AuthorName = 'Stephen King'
)
AND
BookID in
(
 SELECT BookID
 FROM BOOK_COPIES
 WHERE BranchID in
 (
  SELECT BranchID
  FROM LIBRARY_BRANCH
  WHERE BranchName = 'Central'
 )
);
</code>```

Body:
I am new to SQL queries and trying to understand it a little better.
Is this SQL query valid regarding the picture below
The question I was given was:

"For each book authored (or co-authored) by "Stephen King", retrieve the title and the number of copies owned by the librarybranch whose name is "Central"

SELECT Title
FROM BOOK
WHERE BookID =
(
 SELECT BookID
 FROM BOOK_AUTHORS
 WHERE AuthorName = 'Stephen King'
)
AND
BookID =
(
 SELECT BookID, No_Of_Copies
 FROM BOOK_COPIES
 WHERE BranchID =
 (
  SELECT BranchID
  FROM LIBRARY_BRANCH
  WHERE BranchName = 'Central'
 )
)

Body:
Please use below query, but the right approach is to use joins instead of multiple sub queries

Joins

SELECT B.Title
FROM BOOK B
inner join BOOK_AUTHORS BA
on (B.bookid = ba.bookid)
inner join BOOK_COPIES BC
on (B.bookid = BC.bookid)
inner join LIBRARY_BRANCH LB
on (BC.branchid = LB.branchid)
where B.AuthorName = 'Stephen King'
and LB.BranchName = 'Central';

Subquery

SELECT Title
FROM BOOK
WHERE BookID in
(
 SELECT BookID
 FROM BOOK_AUTHORS
 WHERE AuthorName = 'Stephen King'
)
AND
BookID in
(
 SELECT BookID
 FROM BOOK_COPIES
 WHERE BranchID in
 (
  SELECT BranchID
  FROM LIBRARY_BRANCH
  WHERE BranchName = 'Central'
 )
);


问:
Read data from PostgreSQL in spark return py4j.protocol.Py4JJavaError
I am trying to read data from postgres in apache spark using python, but return an py4j.protocol.Py4JJavaError

Here's my code:

```<code>import pyspark
from pyspark import SparkConf
from pyspark.sql import SparkSession

spark = SparkSession \
    .builder \
    .appName("PySpark Read") \
    .config("spark.jars", "C:\spark\spark-2.4.5-bin-hadoop2.7\jars\postgresql-42.2.12.jar") \
    .getOrCreate()

df = spark.read \
    .format("jdbc") \
    .option("driver", "org.postgresql.Driver") \
    .option("url", "jdbc:postgresql://127.0.0.1:5432/db_test") \
    .option("dbtable", "test") \
    .option("user", "postgres") \
    .option("password", "postgres") \
    .load()

df.printSchema()
</code>```

And here's the error log:

```<code>WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/C:/spark/spark-2.4.5-bin-hadoop2.7/jars/spark-unsafe_2.11-2.4.5.jar) to method java.nio.Bits.unaligned()
WARNING: Please consider reporting this to the maintainers of org.apache.spark.unsafe.Platform
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Traceback (most recent call last):
  File "C:/spark/spark-2.4.5-bin-hadoop2.7/read-rdbms.py", line 17, in <module>
    .option("password", "postgres") \
  File "C:\spark\spark-2.4.5-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\sql\readwriter.py", line 172, in load
  File "C:\spark\spark-2.4.5-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py", line 1257, in __call__
  File "C:\spark\spark-2.4.5-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\sql\utils.py", line 63, in deco
  File "C:\spark\spark-2.4.5-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\protocol.py", line 328, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o39.load.
: org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"
        at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:525)
        at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:146)
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:197)
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:211)
        at org.postgresql.Driver.makeConnection(Driver.java:459)
        at org.postgresql.Driver.connect(Driver.java:261)
        at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:63)
        at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:54)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:56)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation$.getSchema(JDBCRelation.scala:210)
        at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:35)
        at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:318)
        at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:223)
        at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:211)
        at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:167)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:282)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:238)
        at java.base/java.lang.Thread.run(Thread.java:832)
</code>```

By the way I am running my pyspark script locally on my machine, and I realize there's

FATAL: password authentication failed for user "postgres"

But when I test to connect using Navicat and Dbeaver using same credential it succesfully connect without a problem? Is there something I miss?

答: Based on @mazaneicha answer it works after downgrading my JDK to 8u251 (my previous JDK was 14 or latest version).</p>

Body:
I am trying to read data from postgres in apache spark using python, but return an py4j.protocol.Py4JJavaError

Here's my code:

import pyspark
from pyspark import SparkConf
from pyspark.sql import SparkSession

spark = SparkSession \
    .builder \
    .appName("PySpark Read") \
    .config("spark.jars", "C:\spark\spark-2.4.5-bin-hadoop2.7\jars\postgresql-42.2.12.jar") \
    .getOrCreate()

df = spark.read \
    .format("jdbc") \
    .option("driver", "org.postgresql.Driver") \
    .option("url", "jdbc:postgresql://127.0.0.1:5432/db_test") \
    .option("dbtable", "test") \
    .option("user", "postgres") \
    .option("password", "postgres") \
    .load()

df.printSchema()

And here's the error log:

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.spark.unsafe.Platform (file:/C:/spark/spark-2.4.5-bin-hadoop2.7/jars/spark-unsafe_2.11-2.4.5.jar) to method java.nio.Bits.unaligned()
WARNING: Please consider reporting this to the maintainers of org.apache.spark.unsafe.Platform
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Traceback (most recent call last):
  File "C:/spark/spark-2.4.5-bin-hadoop2.7/read-rdbms.py", line 17, in <module>
    .option("password", "postgres") \
  File "C:\spark\spark-2.4.5-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\sql\readwriter.py", line 172, in load
  File "C:\spark\spark-2.4.5-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py", line 1257, in __call__
  File "C:\spark\spark-2.4.5-bin-hadoop2.7\python\lib\pyspark.zip\pyspark\sql\utils.py", line 63, in deco
  File "C:\spark\spark-2.4.5-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\protocol.py", line 328, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o39.load.
: org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"
        at org.postgresql.core.v3.ConnectionFactoryImpl.doAuthentication(ConnectionFactoryImpl.java:525)
        at org.postgresql.core.v3.ConnectionFactoryImpl.tryConnect(ConnectionFactoryImpl.java:146)
        at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:197)
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:211)
        at org.postgresql.Driver.makeConnection(Driver.java:459)
        at org.postgresql.Driver.connect(Driver.java:261)
        at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:63)
        at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:54)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:56)
        at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation$.getSchema(JDBCRelation.scala:210)
        at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:35)
        at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:318)
        at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:223)
        at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:211)
        at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:167)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
        at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
        at py4j.Gateway.invoke(Gateway.java:282)
        at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
        at py4j.commands.CallCommand.execute(CallCommand.java:79)
        at py4j.GatewayConnection.run(GatewayConnection.java:238)
        at java.base/java.lang.Thread.run(Thread.java:832)

By the way I am running my pyspark script locally on my machine, and I realize there's

FATAL: password authentication failed for user "postgres"

But when I test to connect using Navicat and Dbeaver using same credential it succesfully connect without a problem? Is there something I miss?


问:
Java error Caused by: Javax.net.ssl.SSLHandhakeException: Java.security.cert.CertificateExpiredException
We are having a problem with absorbing data from several FTP servers (hosted by a third paty) Our system is unable to absorb any files from the FTP servers while we are able to reach them via FileZilla. Other systems are able to reach them and place the files on the path, but our system will not pick them up and gives an error:
Caused by: Javax.net.ssl.SSLHandhakeException: Java.security.cert.CertificateExpiredException
enter image description here
Is someone able to advise us as all parties are saying it is not caused by them;
The Website hosting says its not caused by them, the FTP hosting says its not caused by them, and the developpers are also saying it is not caused by them :(</p>

答:
Certificate Expired Exception. This is thrown whenever the current
  Date or the specified Date is after the notAfter date/time specified
  in the validity period of the certificate.

Check if your application server and FileZilla try to access the same server.
If so, then you might need to update the certificate in the trust store of your application server. (The certificate might have been added to the machine from which you are using FileZilla - as far as I understand these 2 are different machines).


问:
Allowing KeyProtection for CX509PrivateKeyClass in C#
We currently have a solution to generate CA certificates using Microsoft Active Directory Certificate Services.

We have an application which you can login to and you can send a request for a CA certificate.

Behind the scenes this loads an iframe (pointing to a form on the MS CA certificate service) copies a load of data using jQuery and submits the form.

The form submission creates a CSR using ActiveX and CertEnroll and POSTs it to another ASP page. (The whole MS AD certificate service is ASP pages)

The issue is that this only works in IE (obviously)

My proposal was to move the CSR generation server side so that this wouldn't rely on an IE and could be used from any browser.

I have a solution that works, it sends the data to an api and within the api it generates a CSR and forwards it over to the MS CA cert server and this generates valid certificates.

The problem

The issue is that once I install the certificates, the information which states "You have a private key that corresponds to this certificate" is missing. On the existing system this message is displayed as below:

My assumption is that this is because the KeyProtection has not been set for the Private Key. Unfortunately, the flag that it used in the existing VBScript implementation requires user input: XCN_NCRYPT_UI_PROTECT_KEY_FLAG. Each time a certificate is requested the user is prompted to secure the key

For my .Net Framework implementation I have attempted two different CSR generators, one using Bouncy Castle and one using an interop for the CERTENROLLLib.

The code I'll display below will be the CERTENROLLLib implementation, but if anyone has ideas for either solution I would be happy to hear them

The CERTENROLLLib CSR  generation

```<code>        var values = new Dictionary<string, string>
        {
            { "E", emailAddress },
            { "CN", commonName },
            { "OU", organizationalUnit },
            { "L", locality }
        };

        var privateKey = new CX509PrivateKeyClass
        {
            Length = 1024,
            MachineContext = false,
            CspInformations = GetCryptographicProvider(),
            // This can't be set as it requires UI feedback
            //KeyProtection = X509PrivateKeyProtection.XCN_NCRYPT_UI_PROTECT_KEY_FLAG,
            ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_NONE,
        };

        //  Create the actual key pair
        privateKey.Create();

        //  Initialize the PKCS#10 certificate request object based on the private key.
        //  Using the context, indicate that this is a user certificate request and don't
        //  provide a template name
        var certificateRequest = new CX509CertificateRequestPkcs10Class();

        certificateRequest.InitializeFromPrivateKey(
            X509CertificateEnrollmentContext.ContextUser,
            privateKey,
            string.Empty
        );

        var extension = new CX509ExtensionsClass
        {
            GetExtensionKeyUsage(),
            GetExtensionEnhancedKeyUsage()
        };

        certificateRequest.X509Extensions.AddRange(extension);

        //  Encode the name in using the Distinguished Name object
        var valueCollection = values.Select(v => $"{v.Key}={v.Value}").Reverse();

        var subject = new CX500DistinguishedNameClass();
        subject.Encode(
            string.Join(";", valueCollection), X500NameFlags.XCN_CERT_NAME_STR_ENABLE_PUNYCODE_FLAG
        );

        //  Assigning the subject name by using the Distinguished Name object initialized above
        certificateRequest.Subject = subject;

        // Create enrollment request
        var enrollmentRequest = new CX509EnrollmentClass();
        enrollmentRequest.InitializeFromRequest(certificateRequest);

        var csr = enrollmentRequest.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER);
</code>```

So my question is how can I add key protection to the private key as shown in the screenshot?

As this is server side I can't expect any user feedback, so is there another approach.

Any guidance will be welcome, as is probably painfully clear, I am quite new to CSR generation.

Eventually this will be rewritten and we'll probably be generating our own certificates, but I was simply trying to improve the current situation.

Many thanks

答:
First of all this is not a answer, but sharing some thoughts and experience which could help.

I used a similar code before with the version 1.0.0.0 of the library CERTENROLLLib (This is the way to go as it has most settings for generation of certificates, instead of Bouncy Castle).

I think your request is correct but somehow the MS CA is issuing a certificate without a private key, hence you import it and you end up with missing "You have a private key that corresponds to this certificate".

I am saying this because my code did not set KeyProtection and leave the default value of X509PrivateKeyProtection.XCN_NCRYPT_UI_NO_PROTECTION_FLAG, but I was able to generate a certificate with the private key included (I actually used CERTENROLLLib again to generate the certificate instead of MS CA so this is a major difference).

It is like exporting a certificate in .cer format (without PK) and in .pfx format (with PK).

So there must be some special setting for the enrollment request for the MS CA.

Here is my code for reference, which creates a certificate and adds it to the Personal Certificates on the local computer.

```<code>    // Create enrollment request
    var enrollmentRequest = new CX509Enrollment();
    enrollmentRequest.InitializeFromRequest(certificateRequest);

    string csr = enrollmentRequest.CreateRequest();

    // and install it back as the response
    enrollmentRequest.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
        csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password
    // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
    var base64encoded = enrollmentRequest.CreatePFX("", // no password, this is for internal consumption
        PFXExportOptions.PFXExportChainWithRoot);

    // instantiate the target class with the PKCS#12 data (and the empty password)
    var certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
        System.Convert.FromBase64String(base64encoded), "",
        // mark the private key as exportable (this is usually what you want to do)
        System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
    );
</code>```

I also decided to post this, because you said

we'll probably be generating our own certificates

Which is actually what my code does, and it includes the PK, so just perhaps this post could be helpful.

Body:
We currently have a solution to generate CA certificates using Microsoft Active Directory Certificate Services.

We have an application which you can login to and you can send a request for a CA certificate.

Behind the scenes this loads an iframe (pointing to a form on the MS CA certificate service) copies a load of data using jQuery and submits the form.

The form submission creates a CSR using ActiveX and CertEnroll and POSTs it to another ASP page. (The whole MS AD certificate service is ASP pages)

The issue is that this only works in IE (obviously)

My proposal was to move the CSR generation server side so that this wouldn't rely on an IE and could be used from any browser.

I have a solution that works, it sends the data to an api and within the api it generates a CSR and forwards it over to the MS CA cert server and this generates valid certificates.

The problem

The issue is that once I install the certificates, the information which states "You have a private key that corresponds to this certificate" is missing. On the existing system this message is displayed as below:

My assumption is that this is because the KeyProtection has not been set for the Private Key. Unfortunately, the flag that it used in the existing VBScript implementation requires user input: XCN_NCRYPT_UI_PROTECT_KEY_FLAG. Each time a certificate is requested the user is prompted to secure the key

For my .Net Framework implementation I have attempted two different CSR generators, one using Bouncy Castle and one using an interop for the CERTENROLLLib.

The code I'll display below will be the CERTENROLLLib implementation, but if anyone has ideas for either solution I would be happy to hear them

The CERTENROLLLib CSR  generation

        var values = new Dictionary<string, string>
        {
            { "E", emailAddress },
            { "CN", commonName },
            { "OU", organizationalUnit },
            { "L", locality }
        };

        var privateKey = new CX509PrivateKeyClass
        {
            Length = 1024,
            MachineContext = false,
            CspInformations = GetCryptographicProvider(),
            // This can't be set as it requires UI feedback
            //KeyProtection = X509PrivateKeyProtection.XCN_NCRYPT_UI_PROTECT_KEY_FLAG,
            ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_NONE,
        };

        //  Create the actual key pair
        privateKey.Create();

        //  Initialize the PKCS#10 certificate request object based on the private key.
        //  Using the context, indicate that this is a user certificate request and don't
        //  provide a template name
        var certificateRequest = new CX509CertificateRequestPkcs10Class();

        certificateRequest.InitializeFromPrivateKey(
            X509CertificateEnrollmentContext.ContextUser,
            privateKey,
            string.Empty
        );

        var extension = new CX509ExtensionsClass
        {
            GetExtensionKeyUsage(),
            GetExtensionEnhancedKeyUsage()
        };

        certificateRequest.X509Extensions.AddRange(extension);

        //  Encode the name in using the Distinguished Name object
        var valueCollection = values.Select(v => $"{v.Key}={v.Value}").Reverse();

        var subject = new CX500DistinguishedNameClass();
        subject.Encode(
            string.Join(";", valueCollection), X500NameFlags.XCN_CERT_NAME_STR_ENABLE_PUNYCODE_FLAG
        );

        //  Assigning the subject name by using the Distinguished Name object initialized above
        certificateRequest.Subject = subject;

        // Create enrollment request
        var enrollmentRequest = new CX509EnrollmentClass();
        enrollmentRequest.InitializeFromRequest(certificateRequest);

        var csr = enrollmentRequest.CreateRequest(EncodingType.XCN_CRYPT_STRING_BASE64REQUESTHEADER);

So my question is how can I add key protection to the private key as shown in the screenshot?

As this is server side I can't expect any user feedback, so is there another approach.

Any guidance will be welcome, as is probably painfully clear, I am quite new to CSR generation.

Eventually this will be rewritten and we'll probably be generating our own certificates, but I was simply trying to improve the current situation.

Many thanks

Body:
First of all this is not a answer, but sharing some thoughts and experience which could help.

I used a similar code before with the version 1.0.0.0 of the library CERTENROLLLib (This is the way to go as it has most settings for generation of certificates, instead of Bouncy Castle).

I think your request is correct but somehow the MS CA is issuing a certificate without a private key, hence you import it and you end up with missing "You have a private key that corresponds to this certificate".

I am saying this because my code did not set KeyProtection and leave the default value of X509PrivateKeyProtection.XCN_NCRYPT_UI_NO_PROTECTION_FLAG, but I was able to generate a certificate with the private key included (I actually used CERTENROLLLib again to generate the certificate instead of MS CA so this is a major difference).

It is like exporting a certificate in .cer format (without PK) and in .pfx format (with PK).

So there must be some special setting for the enrollment request for the MS CA.

Here is my code for reference, which creates a certificate and adds it to the Personal Certificates on the local computer.

    // Create enrollment request
    var enrollmentRequest = new CX509Enrollment();
    enrollmentRequest.InitializeFromRequest(certificateRequest);

    string csr = enrollmentRequest.CreateRequest();

    // and install it back as the response
    enrollmentRequest.InstallResponse(InstallResponseRestrictionFlags.AllowUntrustedCertificate,
        csr, EncodingType.XCN_CRYPT_STRING_BASE64, ""); // no password
    // output a base64 encoded PKCS#12 so we can import it back to the .Net security classes
    var base64encoded = enrollmentRequest.CreatePFX("", // no password, this is for internal consumption
        PFXExportOptions.PFXExportChainWithRoot);

    // instantiate the target class with the PKCS#12 data (and the empty password)
    var certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(
        System.Convert.FromBase64String(base64encoded), "",
        // mark the private key as exportable (this is usually what you want to do)
        System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable
    );

I also decided to post this, because you said

we'll probably be generating our own certificates

Which is actually what my code does, and it includes the PK, so just perhaps this post could be helpful.


问:
Error using useEffect in react functional component
I am learning to use react hooks to manage state but I get the error saying
  Line 5:3:  React Hook "useEffect" is called in function "cockpit" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

here is my code

```<code>import React, {useEffect} from "react";
import classes from "./Cockpit.module.css";

const cockpit = (props) => {
  useEffect(() => {
    console.log('Cockpit js useEffect');

  });

  const assiginedClasses = [];
  let btnClass = "";
  if (props.showPersons) {
    btnClass = classes.Red;
  }

  if (props.persons.length <= 2) {
    assiginedClasses.push(classes.red);
  }

  if (props.persons.length <= 1) {
    assiginedClasses.push(classes.bold);
  }
  return (
    <div className={classes.Cockpit}>
      <h1>Hi I'm a React App</h1>
      <p className={assiginedClasses.join(" ")}>This is really Working!</p>
      <button className={btnClass} onClick={props.clicked}>
        Toggle Name
      </button>
    </div>
  );
};

export default cockpit;
</code>```

答:
Below line changed after remove error solved.
This code is work.
1. const cockpit = (props) => {
2. export default cockpit;

Replace below Line
1. const Cockpit = (props) => {
2. export default Cockpit;

Body:
I am learning to use react hooks to manage state but I get the error saying
  Line 5:3:  React Hook "useEffect" is called in function "cockpit" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks

here is my code

import React, {useEffect} from "react";
import classes from "./Cockpit.module.css";

const cockpit = (props) => {
  useEffect(() => {
    console.log('Cockpit js useEffect');

  });

  const assiginedClasses = [];
  let btnClass = "";
  if (props.showPersons) {
    btnClass = classes.Red;
  }

  if (props.persons.length <= 2) {
    assiginedClasses.push(classes.red);
  }

  if (props.persons.length <= 1) {
    assiginedClasses.push(classes.bold);
  }
  return (

Hi I'm a React App

This is really Working!

      <button className={btnClass} onClick={props.clicked}>
        Toggle Name
      </button>

  );
};

export default cockpit;


问:
How to insert a string to a text field programatically in JavaScript
I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

```<code><form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>
</code>```

I have tried something like this but it doesn't work:

```<code><script type="text/javascript"> edit-form.value="the new value"; </script>
</code>```

How can I do this?

答:
```<code>var textfield = document.getElementByName("x");
textfield.value = "My text";
</code>```

or directly document.getElementByName("x").value = "My text";

Instead of using getElementByName you can use getElementById if you want to get your element depending of its id instead of its name.

Body:
I would like to add a string of text to a text field using JavaScript but I don't want to use the onClick or onLoad events to do so.

I simply want the JavaScript to be executed as soon as the browser reads it and the JavaScript will be within the body of the html.

The text field is something like:

<form action="" method="post" name="formname" id="user-registration-form">
    <input type="text" name="edit-form" id="edit-form" />
</form>

I have tried something like this but it doesn't work:

How can I do this?

Body:
var textfield = document.getElementByName("x");
textfield.value = "My text";

or directly document.getElementByName("x").value = "My text";

Instead of using getElementByName you can use getElementById if you want to get your element depending of its id instead of its name.


问:
Multiple lines of the same plot with amXYChart() function
I'm trying to use the amXYChart() function for the first time and I would like to represent two lines on the same plot but I don't manage to.

For example with that dataset. I can represent one line with the code below.

```<code>x <- data.frame("value" = 1:5, "cats" = c(10,20,30,40,50), "dogs" = c(15,25,35,36,48))
amXYChart(x="value", y="dogs", dataProvider=x, keepNA = TRUE) %>%
  addGraph(xField = "value", yField = "dogs")

</code>```

However when I try to represent the two lines, my plot window is empty (Only the x axis is displayed).

```<code>x <- data.frame("value" = 1:5, "cats" = c(10,20,30,40,50), "dogs" = c(15,25,35,36,48))
amXYChart(x="value", y=c("cats","dogs"), dataProvider=x, keepNA = TRUE) %>%
  addGraph(xField = "value", yField = c("cats","dogs"))
</code>```

Also I'm trying to use this package because of interactivity but when I place my curser of the plot (the first one) nothing appears. With the example below it works perfectly.

```<code>library(lubridate)
data("data_stock_2")
amTimeSeries(data_stock_2, 'date', c('ts1', 'ts2'))
</code>```

Is interactivity only for time series data ?

Thanks very much for helping !

答:
I suggest to use amSerialChart as follows:

```<code>amSerialChart(dataProvider=dts, keepNA = TRUE, categoryField="value") %>%
  addGraph(valueField = "cats") %>%
  addGraph(valueField = "dogs") %>%
  setChartCursor()
</code>```

or

```<code>vars <- c("cats", "dogs")
p <- amSerialChart(dataProvider=dts, keepNA = TRUE, categoryField="value")
for (vark in vars) {
  p <- p %>% addGraph(valueField = vark)
}
p %>% setChartCursor()
</code>```

Body:
I'm trying to use the amXYChart() function for the first time and I would like to represent two lines on the same plot but I don't manage to.

For example with that dataset. I can represent one line with the code below.

x <- data.frame("value" = 1:5, "cats" = c(10,20,30,40,50), "dogs" = c(15,25,35,36,48))
amXYChart(x="value", y="dogs", dataProvider=x, keepNA = TRUE) %>%
  addGraph(xField = "value", yField = "dogs")

However when I try to represent the two lines, my plot window is empty (Only the x axis is displayed).

x <- data.frame("value" = 1:5, "cats" = c(10,20,30,40,50), "dogs" = c(15,25,35,36,48))
amXYChart(x="value", y=c("cats","dogs"), dataProvider=x, keepNA = TRUE) %>%
  addGraph(xField = "value", yField = c("cats","dogs"))

Also I'm trying to use this package because of interactivity but when I place my curser of the plot (the first one) nothing appears. With the example below it works perfectly.

library(lubridate)
data("data_stock_2")
amTimeSeries(data_stock_2, 'date', c('ts1', 'ts2'))

Is interactivity only for time series data ?

Thanks very much for helping !

Body:
I suggest to use amSerialChart as follows:

amSerialChart(dataProvider=dts, keepNA = TRUE, categoryField="value") %>%
  addGraph(valueField = "cats") %>%
  addGraph(valueField = "dogs") %>%
  setChartCursor()

or

vars <- c("cats", "dogs")
p <- amSerialChart(dataProvider=dts, keepNA = TRUE, categoryField="value")
for (vark in vars) {
  p <- p %>% addGraph(valueField = vark)
}
p %>% setChartCursor()


问:
I get an error when I pull data from the internet
I can get the data in the first fragment but I can't get the data in the second fragment

```<code>W/System.err: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
    W/System.err:     at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
            at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103
            at java.net.InetAddress.getAllByName(InetAddress.java:1152)
    W/System.err:     at okhttp3.Dns$Companion$DnsSystem.lookup(Dns.kt:49)
            at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.kt:164)
            at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.kt:129)
    W/System.err:     at okhttp3.internal.connection.RouteSelector.next(RouteSelector.kt:71)
            at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:213)
            at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:108)
    W/System.err:     at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:76)
            at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:245)
    W/System.err:     at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
            at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
    W/System.err:     at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:96)
    W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
            at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
            at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
    W/System.err:     at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
            at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
    W/System.err:     at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
            at okhttp3.internal.connection.RealCall.execute(RealCall.kt:148)
    W/System.err:     at retrofit2.OkHttpCall.execute(OkHttpCall.java:188)
            at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:45)
            at io.reactivex.Observable.subscribe(Observable.java:12246)
            at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
            at io.reactivex.Observable.subscribe(Observable.java:12246)
            at io.reactivex.internal.operators.observable.ObservableObserveOn.subscribeActual(ObservableObserveOn.java:45)
    W/System.err:     at io.reactivex.Observable.subscribe(Observable.java:12246)
            at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
    W/System.err:     at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:124)
    W/System.err:     at android.os.Handler.handleCallback(Handler.java:883)
            at android.os.Handler.dispatchMessage(Handler.java:100)
            at android.os.Looper.loop(Looper.java:214)
    W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7356)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
</code>```

I think it is related to threads but I couldn't find how to solve it.

```<code>class MovieDetailViewModel(application: Application) : BaseViewModel(application) {
    private val movieAPIService = MovieAPIService()
    private val disposable = CompositeDisposable()
    val oneMovie = MutableLiveData<Movie>()

    fun loadData(id: Int){
        getMovie(id)
    }

    private fun getMovie(id: Int) {
        println(id)
        disposable.add(movieAPIService.getMovie(id)
            .observeOn(Schedulers.io())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribeWith(object : DisposableObserver<FirstModel2>(){
                override fun onComplete() {

                }

                override fun onNext(t: FirstModel2) {
                    val movie : OneMovie = t.data
                    oneMovie.value = movie.movie
                }

                override fun onError(e: Throwable) {
                    e.printStackTrace()
                }

            }))
    }
}
</code>```

I show the movies in recyclerview using the api in the first fragment, and when I click on it, I want to switch to the second fragment and show the details of the film by using the id of the film again

答: You mixed schedulers in observeOn and subscribeOn. Swap them.</p>

Body:
I can get the data in the first fragment but I can't get the data in the second fragment

W/System.err: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1565)
    W/System.err:     at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
            at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103
            at java.net.InetAddress.getAllByName(InetAddress.java:1152)
    W/System.err:     at okhttp3.Dns$Companion$DnsSystem.lookup(Dns.kt:49)
            at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.kt:164)
            at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.kt:129)
    W/System.err:     at okhttp3.internal.connection.RouteSelector.next(RouteSelector.kt:71)
            at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:213)
            at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:108)
    W/System.err:     at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:76)
            at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:245)
    W/System.err:     at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
            at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
    W/System.err:     at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:96)
    W/System.err:     at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
            at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
            at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
    W/System.err:     at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
            at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
    W/System.err:     at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
            at okhttp3.internal.connection.RealCall.execute(RealCall.kt:148)
    W/System.err:     at retrofit2.OkHttpCall.execute(OkHttpCall.java:188)
            at retrofit2.adapter.rxjava2.CallExecuteObservable.subscribeActual(CallExecuteObservable.java:45)
            at io.reactivex.Observable.subscribe(Observable.java:12246)
            at retrofit2.adapter.rxjava2.BodyObservable.subscribeActual(BodyObservable.java:34)
            at io.reactivex.Observable.subscribe(Observable.java:12246)
            at io.reactivex.internal.operators.observable.ObservableObserveOn.subscribeActual(ObservableObserveOn.java:45)
    W/System.err:     at io.reactivex.Observable.subscribe(Observable.java:12246)
            at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
    W/System.err:     at io.reactivex.android.schedulers.HandlerScheduler$ScheduledRunnable.run(HandlerScheduler.java:124)
    W/System.err:     at android.os.Handler.handleCallback(Handler.java:883)
            at android.os.Handler.dispatchMessage(Handler.java:100)
            at android.os.Looper.loop(Looper.java:214)
    W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:7356)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

I think it is related to threads but I couldn't find how to solve it.

class MovieDetailViewModel(application: Application) : BaseViewModel(application) {
    private val movieAPIService = MovieAPIService()
    private val disposable = CompositeDisposable()
    val oneMovie = MutableLiveData<Movie>()

    fun loadData(id: Int){
        getMovie(id)
    }

    private fun getMovie(id: Int) {
        println(id)
        disposable.add(movieAPIService.getMovie(id)
            .observeOn(Schedulers.io())
            .subscribeOn(AndroidSchedulers.mainThread())
            .subscribeWith(object : DisposableObserver<FirstModel2>(){
                override fun onComplete() {

                }

                override fun onNext(t: FirstModel2) {
                    val movie : OneMovie = t.data
                    oneMovie.value = movie.movie
                }

                override fun onError(e: Throwable) {
                    e.printStackTrace()
                }

            }))
    }
}

I show the movies in recyclerview using the api in the first fragment, and when I click on it, I want to switch to the second fragment and show the details of the film by using the id of the film again


问:
Bash gotcha: cat FILE | while read A ; do ... exit .. done
I had a long pause in writing bash script, and I got trapped again:

```<code>cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                exit
        fi
done
</code>```

I happily assumed the exit will exit the whole bash script, as it should, but as it is in pipe, it probably exits just the sub-process dispatched to run while part.

I already forgot how to easily workaround this. Please remind me! :-)

**EDIT: ** now I have changed the code (for some other reason) to use variable instead, and I am looking for workaround for this:

```<code>EXIST="no"
cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                EXIST="yes"
        fi
done
</code>```

but I guess this is the same case, I need the inside of the loop to be run with the same shell as runs the whole script.

答:
A common workaround for the variable assignment is to increase the scope with {}:

```<code>cmd | {
    while read spid; do var=assigned-value-$spid; break; done;
    : here, var retains the value assigned in the while loop
}
: now var retains whatever value it had (or is unset) before the pipeline
</code>```

To "elevate" the exit, it is common to do:

```<code>if ! cmd | { while read spid; do ... if ... exit 1; ... done; ... exit 0; }; then
   exit
fi
</code>```

If the subshell exits non-zero, the entire shell will exit.

Body:
I had a long pause in writing bash script, and I got trapped again:

cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                exit
        fi
done

I happily assumed the exit will exit the whole bash script, as it should, but as it is in pipe, it probably exits just the sub-process dispatched to run while part.

I already forgot how to easily workaround this. Please remind me! :-)

**EDIT: ** now I have changed the code (for some other reason) to use variable instead, and I am looking for workaround for this:

EXIST="no"
cat FILE | while read SPID ; do
        if ls $ODIR/*$SPID*.csv > /dev/null 2>&1 ; then
                echo Error: some files exist in the directory $ODIR:
                ls -la $ODIR/*$SPID*.csv
                EXIST="yes"
        fi
done

but I guess this is the same case, I need the inside of the loop to be run with the same shell as runs the whole script.

Body:
A common workaround for the variable assignment is to increase the scope with {}:

cmd | {
    while read spid; do var=assigned-value-$spid; break; done;
    : here, var retains the value assigned in the while loop
}
: now var retains whatever value it had (or is unset) before the pipeline

To "elevate" the exit, it is common to do:

if ! cmd | { while read spid; do ... if ... exit 1; ... done; ... exit 0; }; then
   exit
fi

If the subshell exits non-zero, the entire shell will exit.