问:
AddSingleton<>() vs AddSingleton()
I'm implementing dependency injection in my project. I've come across two ways to add a singleton service -

services.AddSingleton(new MyCustomService())
```

<p>and </p>

<pre class="lang-csh prettyprint-override"><code>services.AddSingleton<MyCustomService>()
</code>```

Both methods seem to work. What's the difference between these two methods, and which one should I be using?

答:
When using the generic .AddSingleton<TService>() method (and .AddSingleton<TService, TImplementation>(), the type is created, controlled, and disposed of by the container. When the constructor contains other dependencies, those dependencies are automatically injected (a technique called "Auto-Wiring").

Instances supplied using .AddSingleton<TService>(TService) already exist. In that case, the container will not dispose of that instance when it implements IDisposable or IAsyncDisposable. You are responsible for disposing of that instance yourself.

Since .AddSingleton<TService>(TService) is supplied with an already existing instance, the container can't inject any dependencies, because in order to do that, it must also create the instance.

When instances are registered using the .AddSingleton<TService>(Func<TService>) method, the Func<TService> delegate is in control over the creation of the dependency, but the instance returned by the delegate will still be tracked and disposed by the container.

Title: AddSingleton<>() vs AddSingleton()

Body:
I'm implementing dependency injection in my project. I've come across two ways to add a singleton service -

services.AddSingleton(new MyCustomService())

and

services.AddSingleton<MyCustomService>()

Both methods seem to work. What's the difference between these two methods, and which one should I be using?


来源: stackexchange

问:
Use Excel to optimise KFC order
Don't laugh, but, from time to time, my friends and I host a multiple-course KFC dinner, and I have a spreadsheet to optimise the order. This is to make sure we order the right combination of 'bucket'-type items (i.e. SKUs that contain multiple pieces, often of different types):

to minimise leftover items

to reduce the total cost

Here is the spreadsheet I currently use, and here's a screenshot:

To use it, you first specify the number of participants in A2, and what you want each person to have in E2:E6 (we're really only interested in the chicken, so 'sides' are treated as generic to simplify).

Here's the manual part, that I'd like to improve.

The next step is to look at the ideal totals for each item (F2:F6), and to try to set the right quantities (H12:H20) of the 'bucket'-type SKUs that I have recreated (A11:G20), so that the output totals (H21:M21) match the ideal totals (F2:F6).

The optimisation part is to get the deltas (H22:M22) as close to zero as possible, and to get the total cost (N21) as low as possible.

So, my question is: is there a way to do this better? I think Excel has some sort of Solver functionality, but I'm afraid I don't know how I'd go about even starting to use that, as my Excel skills are pretty rudimentary. Oh, and in case it makes a difference regarding functionality, I'm using Excel for Mac v16.37.

Any thoughts gratefully appreciated! :)

答:
I can't take any credit for this, but am happy to say that GSerg left me a couple of comments that pointed me in the right direction, and I now have Solver set up to organise my chicken parties!

Here are the parameters for anyone who is curious:

ContentLicense: CC BY-SA 4.0

Title: Use Excel to optimise KFC order


问:
const char* vs char* (C++)
For the following program:

```<code>int DivZero(int, int, int);

int main()
{
    try {
        cout << DivZero(1,0,2) << endl;
    }
    catch(char* e)
    {
        cout << "Exception is thrown!" << endl;
        cout << e << endl;
        return 1;
    }
    return 0;
}

int DivZero(int a, int b, int c)
{
    if( a <= 0 || b <= 0 || c <= 0)
        throw "All parameters must be greater than 0.";
    return b/c + a;
}
</code>```

Using char* e will give

terminate called after throwing an
  instance of 'char const*'

According to C++ Exception Handling , the solution is to use const char* instead.

Further reading from function (const char *) vs. function (char *) said that

The type of "String" is char*', not
  const char*'

(this is a C discussion I think...)

Additional reading on Stack Overflow char* vs const char* as a parameter tells me the difference. But none of them address my questions:

It seems like both char* and string* have limit on the numbers of characters. Am I correct?

How does adding the keyword const to char* eliminates that limit? I thought the only purpose of const is to set a flag that said "unmodifiable". I understand that const char* e means " the pointer which points to unmodifiable char type".

The solution to that error is to use const char* e.

Even const string* e doesn't work. (just for the sake of testing...)

Can anyone explain, please? Thank you!

By the way, I am on Ubuntu, compiled by GCC, on Eclipse.

答:
The email you linked to about "String" is wrong (and confusing).

Basically:

char* is a pointer to an unbounded array of characters. Traditionally we consider such an array to be a C-string if it contains a set of valid characters followed by a \0. There's no limit to the size of the array.

const char* is a pointer to an unbounded array of immutable characters.

string* is a pointer to a std::string object, and is entirely different. This is a smart object that encapsulates a string. Using std::string instead of C-strings can make your life loads easier, even though they've got some rough edges and a lot of nasty gotchas; they're well worth looking into, but they're not relevant to the question.

"String" is a special expression that returns a const char* pointing at the specific C-string (note: this is not actually true, but it's a simplification that lets me answer the question concisely).

A char* can be automatically cast to a const char*, but not vice versa. Note that old C++ compilers had a special exception to the type rules to let you do this:

```<code>char* s = "String";
</code>```

...without producing a type error; this was for C compatibility. Modern C++ compilers won't let you do it (such as recent gccs). They require this:

```<code>const char* s = "String";
</code>```

So. The problem here is that you've got:

```<code>throw "All parameters must be greater than 0.";
</code>```

...but then you're trying to catch it with:

```<code>catch(char* e)
</code>```

This doesn't work, because the throw is throwing a const char*, which can't be cast to the type specified in the catch, so it isn't getting caught.

This is why changing the catch to:

```<code>catch (const char* e)
</code>```

...makes it work.

ContentLicense: CC BY-SA 3.0

Title: const char* vs char* (C++)

Body:
For the following program:

int DivZero(int, int, int);

int main()
{
    try {
        cout << DivZero(1,0,2) << endl;
    }
    catch(char* e)
    {
        cout << "Exception is thrown!" << endl;
        cout << e << endl;
        return 1;
    }
    return 0;
}

int DivZero(int a, int b, int c)
{
    if( a <= 0 || b <= 0 || c <= 0)
        throw "All parameters must be greater than 0.";
    return b/c + a;
}

Using char* e will give

terminate called after throwing an
  instance of 'char const*'

According to C++ Exception Handling , the solution is to use const char* instead.

Further reading from function (const char *) vs. function (char *) said that

The type of "String" is char*', not
  const char*'

(this is a C discussion I think...)

Additional reading on Stack Overflow char* vs const char* as a parameter tells me the difference. But none of them address my questions:

It seems like both char* and string* have limit on the numbers of characters. Am I correct?

How does adding the keyword const to char* eliminates that limit? I thought the only purpose of const is to set a flag that said "unmodifiable". I understand that const char* e means " the pointer which points to unmodifiable char type".

The solution to that error is to use const char* e.

Even const string* e doesn't work. (just for the sake of testing...)

Can anyone explain, please? Thank you!

By the way, I am on Ubuntu, compiled by GCC, on Eclipse.

Body:
The email you linked to about "String" is wrong (and confusing).

Basically:

char* is a pointer to an unbounded array of characters. Traditionally we consider such an array to be a C-string if it contains a set of valid characters followed by a \0. There's no limit to the size of the array.

const char* is a pointer to an unbounded array of immutable characters.

string* is a pointer to a std::string object, and is entirely different. This is a smart object that encapsulates a string. Using std::string instead of C-strings can make your life loads easier, even though they've got some rough edges and a lot of nasty gotchas; they're well worth looking into, but they're not relevant to the question.

"String" is a special expression that returns a const char* pointing at the specific C-string (note: this is not actually true, but it's a simplification that lets me answer the question concisely).

A char* can be automatically cast to a const char*, but not vice versa. Note that old C++ compilers had a special exception to the type rules to let you do this:

char* s = "String";

...without producing a type error; this was for C compatibility. Modern C++ compilers won't let you do it (such as recent gccs). They require this:

const char* s = "String";

So. The problem here is that you've got:

throw "All parameters must be greater than 0.";

...but then you're trying to catch it with:

catch(char* e)

This doesn't work, because the throw is throwing a const char*, which can't be cast to the type specified in the catch, so it isn't getting caught.

This is why changing the catch to:

catch (const char* e)

...makes it work.


问:
How to see related objects when a model tried to be deleted in django
in a large database lets say I have Article_A and Article_A has some comments. Comment_1,Comment_2 and Comment_3. When I tried to delete Article_A I want to show a message to the user says that "Article_A has Comment_1, Comment_2 and Comment_3 and you shouldn't delete them". Moreover I want to show all related objects to Article_A(not only Comments). So should I be aware of all related objects to the Article_A query them?</p>

答:
Sorry i don't understand  you but you need in models.py:

if you want when youdelete one other delete on_delete=models.CASCADE

```<code>class Article(models.Model):
    Comment= models.OneToOneField(Comment, on_delete=models.CASCADE)
</code>```

else

```<code>class Article(models.Model):
    Comment= models.OneToOneField(Comment,on_delete=models.SET_NULL)
</code>```

Body:
Sorry i don't understand  you but you need in models.py:

if you want when youdelete one other delete on_delete=models.CASCADE

class Article(models.Model):
    Comment= models.OneToOneField(Comment, on_delete=models.CASCADE)

else

class Article(models.Model):
    Comment= models.OneToOneField(Comment,on_delete=models.SET_NULL)


问:
react hooks : Uncaught TypeError: data.posts.map is not a function
I'm trying to make a list of jokes but it is saying " TypeError: data.posts.map is not a function ".
    I used before same code but different API and it was working.
    In console it is showing those posts but on app i get error saying that " data.posts.map "
    Can anyone help me?
    Thanks
    This is my code:

```<code>   import React, { useState, useEffect } from 'react';
    import axios from 'axios';

    const PostArea = () => {

      const [like, showLike] = useState(false);
      const [color, setColor] = useState('#000');

      const likePrint = () => {
        showLike(!like);
      }

      const [data, setPost] = useState({ posts: [] });

      useEffect(() => {
        const fetchData = async () => {
          const result = await axios('https://sv443.net/jokeapi/v2/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist&idRange=0-40');
          console.log({ posts: result.data });
          setPost({ posts: result.data });
        };
        fetchData();
      }, []);
      return (
        <div>
          {data.posts && data.posts.map(({ id, setup, delivery, category }) => {
            return (
              <div key={id} className="post">
                <div className="header">
                  <a>
                    <img src="https://unsplash.it/40" alt=" title" />
                    <div>
                      <span className="detail">Category :{category}</span>
                    </div>
                  </a>
                </div>
                <div className="content">
                  <p>
                    {setup}
                  </p>
                  <p>
                    {delivery}
                  </p>
                </div>
                <div className="footer">
                  <ul>
                    <li>
                      <a style={{ color: color }} onClick={() => { likePrint(!like); setColor('#2274a5') }}>
                        <i className="fas fa-heart"></i>
                      </a>
                    </li>
                    <li>
                      <a>
                        <i className="fas fa-comment"></i>
                      </a>
                    </li>
                    <li>
                      <a>
                        <i className="fas fa-share-alt-square"></i>
                      </a>
                    </li>
                  </ul>
                </div>
              </div>
            );
          })}
        </div>
      );
    }

    export default PostArea;
</code>```

Error : Uncaught TypeError: data.posts.map is not a function

答:
I was looking at the response from the https://sv443.net/jokeapi/v2/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist&idRange=0-40, and it seems like it is returning an object, rather an array, which is the expected type of data.post.

I guess you would want to include this object as part of the post array?

```<code>const fetchData = async () => {
  const result = await axios('https://sv443.net/jokeapi/v2/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist&idRange=0-40');
  setPost({ posts: [result.data] });
};
</code>```

Body:
I'm trying to make a list of jokes but it is saying " TypeError: data.posts.map is not a function ".
    I used before same code but different API and it was working.
    In console it is showing those posts but on app i get error saying that " data.posts.map "
    Can anyone help me?
    Thanks
    This is my code:

   import React, { useState, useEffect } from 'react';
    import axios from 'axios';

    const PostArea = () => {

      const [like, showLike] = useState(false);
      const [color, setColor] = useState('#000');

      const likePrint = () => {
        showLike(!like);
      }

      const [data, setPost] = useState({ posts: [] });

      useEffect(() => {
        const fetchData = async () => {
          const result = await axios('https://sv443.net/jokeapi/v2/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist&idRange=0-40');
          console.log({ posts: result.data });
          setPost({ posts: result.data });
        };
        fetchData();
      }, []);
      return (

          {data.posts && data.posts.map(({ id, setup, delivery, category }) => {
            return (

                      Category :{category}

                    {setup}

                    {delivery}

                       { likePrint(!like); setColor('#2274a5') }}>

            );
          })}

      );
    }

    export default PostArea;

Error : Uncaught TypeError: data.posts.map is not a function

Body:
I was looking at the response from the https://sv443.net/jokeapi/v2/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist&idRange=0-40, and it seems like it is returning an object, rather an array, which is the expected type of data.post.

I guess you would want to include this object as part of the post array?

const fetchData = async () => {
  const result = await axios('https://sv443.net/jokeapi/v2/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist&idRange=0-40');
  setPost({ posts: [result.data] });
};


问:
Google Add-on script throws server error when calling DriveApp getFolderById or getFileById
I have deployed a spreadsheet bound script as an add-on.
It worked when it was container bound.
But now, as an add-on, I get a server error when I call DriveApp.getFolderById

```<code>function makeMap (){
console.log("start lesmap");
try{var map=DriveApp.getFolderById(DIPmapId); }catch(e){console.log("error map:"+e )}
try{var temp=DriveApp.getFileById(templateId);}catch(e){console.log("error tempfile:"+e) }
}
</code>```

throws errors (in Dutch but meaning: server error, wait a while and try again):

2020-05-23 12:10:11.310 CEST
error map:Exception: Er is helaas een serverfout opgetreden. Wacht enige tijd en probeer het dan nogmaals.
2020-05-23 12:10:11.347 CEST
error tempfile:Exception: Er is helaas een serverfout opgetreden. Wacht enige tijd en probeer het dan nogmaals.

In the manifest file:

```<code>{
"timeZone": "Europe/Paris",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"oauthScopes": [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/script.container.ui"
]
}
</code>```

In the G Suite Marketplace SDK Configuration
OAuth 2.0-scopes

```<code>https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile
https://www.googleapis.com/auth/spreadsheets
https://www.googleapis.com/auth/script.container.ui
https://www.googleapis.com/auth/drive
</code>```

I have it installed and enabled in the spreadsheet.
I run the function in the add-on menu in the spreadsheet, so I guess this is in authmode full?
I have editor rights on the map and the file in Drive.

What am I missing?

答:
This seems to be a bug. You can click on the star next to the issue number to receive updates and to give more priority to the bug. Even thought the bug mentions App Maker, it's also an issue with recent deployments.

A possible workaround would be enabling the Drive API (even thought DriveApp and Drive API are not the same) in the Google Advanced Services. After a successful run, you can disable the Drive API again.

Body:
I have deployed a spreadsheet bound script as an add-on.
It worked when it was container bound.
But now, as an add-on, I get a server error when I call DriveApp.getFolderById

function makeMap (){
console.log("start lesmap");
try{var map=DriveApp.getFolderById(DIPmapId); }catch(e){console.log("error map:"+e )}
try{var temp=DriveApp.getFileById(templateId);}catch(e){console.log("error tempfile:"+e) }
}

throws errors (in Dutch but meaning: server error, wait a while and try again):

2020-05-23 12:10:11.310 CEST
error map:Exception: Er is helaas een serverfout opgetreden. Wacht enige tijd en probeer het dan nogmaals.
2020-05-23 12:10:11.347 CEST
error tempfile:Exception: Er is helaas een serverfout opgetreden. Wacht enige tijd en probeer het dan nogmaals.

In the manifest file:

{
"timeZone": "Europe/Paris",
"dependencies": {
},
"exceptionLogging": "STACKDRIVER",
"oauthScopes": [
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/script.container.ui"
]
}

In the G Suite Marketplace SDK Configuration
OAuth 2.0-scopes

https://www.googleapis.com/auth/userinfo.email
https://www.googleapis.com/auth/userinfo.profile
https://www.googleapis.com/auth/spreadsheets
https://www.googleapis.com/auth/script.container.ui
https://www.googleapis.com/auth/drive

I have it installed and enabled in the spreadsheet.
I run the function in the add-on menu in the spreadsheet, so I guess this is in authmode full?
I have editor rights on the map and the file in Drive.

What am I missing?


问:
Getting error "No templates matched the input template name: blazorwasm."
I'm trying to create a new .net core Blazor WebAssembly App with VS 2019 following this but so far I have had no luck.

As indicated in these docs, I've downloaded the latest preview VS 2019 Professional and typed this on a command window:

```<code>dotnet new blazorwasm --hosted
</code>```

But I keep getting the following error:

```<code>No templates matched the input template name: blazorwasm.
</code>```

This Blazor webAssembly feature is on preview -- it was only released very recently -- and hence understandably prone to errors, but still MS documentation normally is quite accurate, so I'm surprised this is not working as per their explanation.

I would appreciate any help with this.

答:
You need .NET SDK 3.1.300 [C:\Program Files\dotnet\sdk] to use dotnet new blazorwasm --hosted. You can view your installed version by running dotnet --info.

To update, eather download from: https://dotnet.microsoft.com/download/visual-studio-sdks

Or update vistual studio to version 16.6 or greater.

Body:
I'm trying to create a new .net core Blazor WebAssembly App with VS 2019 following this but so far I have had no luck.

As indicated in these docs, I've downloaded the latest preview VS 2019 Professional and typed this on a command window:

dotnet new blazorwasm --hosted

But I keep getting the following error:

No templates matched the input template name: blazorwasm.

This Blazor webAssembly feature is on preview -- it was only released very recently -- and hence understandably prone to errors, but still MS documentation normally is quite accurate, so I'm surprised this is not working as per their explanation.

I would appreciate any help with this.


问:
Testing Android In-App-Purchase: Purchased subscription canccelled automatically instead of auto renew?
I'm implementing an in-app purchase in android. During Testing I purchased a subscription package of 3 months, which would be auto renewed after 10 minutes, but after 5 minutes I'm getting email that that purchased has been cancelled, So not getting renewal after 10 minutes, I checked this for 2 to 3 times.

Does it require any particular settings to get auto renew in Testing flow?
Or How to test purchase>renew>cancel flow?

答:
You should call billingClient.acknowledgePurchase()after you get purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED and after you verify the signature

if not the purchase for both in-app products and subscriptions is refunded/cancelled


问:
React Native upload image to AWS Server not working for Android
I was having some problem when trying to upload image from React Native to AWS Server. Here is my code:

```<code>async function uploadImageAsync(uri) {
  console.log(uri);
  let apiUrl = '...'
  let uriParts = uri.split('.');
  let fileType = uri[uri.length - 1];
  let formData = new FormData();
  formData.append('image', {
    uri,
    name: `image.jpg`,
    filename: `image.jpg`,
  });

  let options = {
    method: 'POST',
    body: formData,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },
  };

  return fetch(apiUrl, options);
}
</code>```

The results that printed out at the console are:

```<code>file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540gh%252Ftp2/ImagePicker/37c89140-2172-4566-98a2-e7393ea72e89.jpg
Object {
  "uploadResponse": undefined,
}
Object {
  "uploadResult": undefined,
}
Object {
  "e": [TypeError: Network request failed],
}
</code>```

What I did is I pick an image from image picker, then I will upload it to AWS server. If success, print out success message. If failed, print out those in the console above.

The strange thing is, it managed to upload on iOS but not Android. Any ideas why is it so?

Thanks!

答:
I was facing the same issue. I was trying to upload images from the phone's camera roll or photo gallery to AWS S3. It was working fine for IOS, but was throwing error TypeError: Network request failed for Android device.

So, I used npm library rn-fetch-blob, instead of fetch() method.

```<code>import RNFetchBlob from 'rn-fetch-blob';

RNFetchBlob.fetch('PUT', AWSPresignedURL, {'Content-Type': 'multipart/form-data'}, Platform.OS === 'ios' ? RNFetchBlob.wrap(filePath) : `RNFetchBlob-${filePath}`)
</code>```

Please note, in my case, I had different file paths for IOS and Android devices. We handle it in different ways using rn-fetch-blob

Sample filePath variable data for

IOS device -

"/Users/Niveditha/Library/Developer/CoreSimulator/Devices/B41EB910-F22B-4236-8286-E6BA3EA75C70/data/Containers/Data/Application/B88777C6-6B10-4095-AB67-BB11E045C1DE/tmp/react-native-image-crop-picker/img.jpg"

Android device -

"file:///storage/emulated/0/Android/data/com.uploadcameraroll/files/Pictures/img.jpg"

Code to generate AWSPreSignedURL -

```<code>let AWS = require('aws-sdk');
let S3 = new AWS.S3();

AWS.config.region = 'ap-south-1';
AWS.config.accessKeyId = 'AKXXXXXXXXXXXXXXXX';
AWS.config.secretAccessKey = 'XIJyXXXXXXXXXXXXXXXXXXXXXXXXXXX+H+GR';

S3.getSignedUrl( 'putObject' ,
        { Bucket: 'upload-app-photos',
          Key: 'upload/' + fileName,
          Expires: 120,
          ACL: 'public-read'
         }, (err,url) => {
            if (err) {
               console.log("error ", err);
               return;
           }
            console.log("AWSPreSignedURL ", url);
      })

</code>```

This issue was officially raised -  https://github.com/facebook/react-native/issues/25244

Body:
I was having some problem when trying to upload image from React Native to AWS Server. Here is my code:

async function uploadImageAsync(uri) {
  console.log(uri);
  let apiUrl = '...'
  let uriParts = uri.split('.');
  let fileType = uri[uri.length - 1];
  let formData = new FormData();
  formData.append('image', {
    uri,
    name: `image.jpg`,
    filename: `image.jpg`,
  });

  let options = {
    method: 'POST',
    body: formData,
    headers: {
      Accept: 'application/json',
      'Content-Type': 'multipart/form-data',
    },
  };

  return fetch(apiUrl, options);
}

The results that printed out at the console are:

file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540gh%252Ftp2/ImagePicker/37c89140-2172-4566-98a2-e7393ea72e89.jpg
Object {
  "uploadResponse": undefined,
}
Object {
  "uploadResult": undefined,
}
Object {
  "e": [TypeError: Network request failed],
}

What I did is I pick an image from image picker, then I will upload it to AWS server. If success, print out success message. If failed, print out those in the console above.

The strange thing is, it managed to upload on iOS but not Android. Any ideas why is it so?

Thanks!

Body:
I was facing the same issue. I was trying to upload images from the phone's camera roll or photo gallery to AWS S3. It was working fine for IOS, but was throwing error TypeError: Network request failed for Android device.

So, I used npm library rn-fetch-blob, instead of fetch() method.

import RNFetchBlob from 'rn-fetch-blob';

RNFetchBlob.fetch('PUT', AWSPresignedURL, {'Content-Type': 'multipart/form-data'}, Platform.OS === 'ios' ? RNFetchBlob.wrap(filePath) : `RNFetchBlob-${filePath}`)

Please note, in my case, I had different file paths for IOS and Android devices. We handle it in different ways using rn-fetch-blob

Sample filePath variable data for

IOS device -

"/Users/Niveditha/Library/Developer/CoreSimulator/Devices/B41EB910-F22B-4236-8286-E6BA3EA75C70/data/Containers/Data/Application/B88777C6-6B10-4095-AB67-BB11E045C1DE/tmp/react-native-image-crop-picker/img.jpg"

Android device -

"file:///storage/emulated/0/Android/data/com.uploadcameraroll/files/Pictures/img.jpg"

Code to generate AWSPreSignedURL -

let AWS = require('aws-sdk');
let S3 = new AWS.S3();

AWS.config.region = 'ap-south-1';
AWS.config.accessKeyId = 'AKXXXXXXXXXXXXXXXX';
AWS.config.secretAccessKey = 'XIJyXXXXXXXXXXXXXXXXXXXXXXXXXXX+H+GR';

S3.getSignedUrl( 'putObject' ,
        { Bucket: 'upload-app-photos',
          Key: 'upload/' + fileName,
          Expires: 120,
          ACL: 'public-read'
         }, (err,url) => {
            if (err) {
               console.log("error ", err);
               return;
           }
            console.log("AWSPreSignedURL ", url);
      })

This issue was officially raised -  https://github.com/facebook/react-native/issues/25244


问:
Is it not possible to clean web crawl without tagging? Is it impossible to make it clean with regular expression?
```<code>data = re.sub('<[^>]*>', '', string=html).lower()
</code>```

I want to crawl random pages. However, since it is impossible to scrape only the desired content, I post a question. Is it valid to delete the html using a regular expression after scratching it?

答: html2text library or pextract lib are valid to question</p>

Body:
data = re.sub('<[^>]*>', '', string=html).lower()

I want to crawl random pages. However, since it is impossible to scrape only the desired content, I post a question. Is it valid to delete the html using a regular expression after scratching it?


问:
For loop crashes program while trying to read array c++
Exercise: The vector A[1 to N] and a value s is given. Build the program that writes backwards every group of s elements. If s divided by N has a remainder, then the remaining values should be unchanged. If s is bigger than N (the nr of elements of the vector) than there will be no modification.

Lets say s = 4 and  A = (1, 2, 3, 4, 5, 6, 7, 8)then after execution the values will be A = (4, 3, 2, 1, 8, 7, 6, 5)

My teacher requires this kind of vector: int n, A[n] where n is a value given by the user. And i think this is what is causing my program to crash when i read the final values. If not, where is the problem?

```<code>#include <iomanip>

using namespace std;

int ordering(int s, int n, int A[]);

int main()
{
    int n, A[n];
    int s;
    cout << "Vlera e s: ";
    cin >> s;

    if (s <= 0)
    {
        return 1;
    }

    cout << "\nN: ";
    cin >> n;

    if (n <= 0)
    {
        return 1;
    }

    cout << "\nVector:";
    for (int i = 0; i < n; i++)
    {
        A[i] = i + 1;
        cout << " " << A[i] << " ";
    }

    if (s > n)
    {
        cout << "\nNo change\n";
        return 0;
    }
    else
    {
        ordering(s, n, A);
    }

    cout << "\nNew vector:";
    for (int i = 0; i < n; i++)
    {
        cout << " " << A[i] << " ";
    }

    return 0;
}

int ordering(int s, int n, int A[])
{
    int counter = 0;
    for (int i = 0, divider = n / s; i < divider; i++)
    {
        int decrease = 0;
        for (int j = counter, a = counter + s; j < a; j++)
        {
            A[j] = a - decrease;
            decrease++;
        }
        counter += s;
    }
    return 0;
}
</code>```

答: Passing variable as array size is not valid you need to use constant const int n or create dinamic array int* arr = new int[n];, that array will be created in runtime, and you can pass variable as it size. Dont forget to delete that array whet it goes out of scope delete[] arr;

Body:
Exercise: The vector A[1 to N] and a value s is given. Build the program that writes backwards every group of s elements. If s divided by N has a remainder, then the remaining values should be unchanged. If s is bigger than N (the nr of elements of the vector) than there will be no modification.

Lets say s = 4 and  A = (1, 2, 3, 4, 5, 6, 7, 8)then after execution the values will be A = (4, 3, 2, 1, 8, 7, 6, 5)

My teacher requires this kind of vector: int n, A[n] where n is a value given by the user. And i think this is what is causing my program to crash when i read the final values. If not, where is the problem?

#include <iomanip>

using namespace std;

int ordering(int s, int n, int A[]);

int main()
{
    int n, A[n];
    int s;
    cout << "Vlera e s: ";
    cin >> s;

    if (s <= 0)
    {
        return 1;
    }

    cout << "\nN: ";
    cin >> n;

    if (n <= 0)
    {
        return 1;
    }

    cout << "\nVector:";
    for (int i = 0; i < n; i++)
    {
        A[i] = i + 1;
        cout << " " << A[i] << " ";
    }

    if (s > n)
    {
        cout << "\nNo change\n";
        return 0;
    }
    else
    {
        ordering(s, n, A);
    }

    cout << "\nNew vector:";
    for (int i = 0; i < n; i++)
    {
        cout << " " << A[i] << " ";
    }

    return 0;
}

int ordering(int s, int n, int A[])
{
    int counter = 0;
    for (int i = 0, divider = n / s; i < divider; i++)
    {
        int decrease = 0;
        for (int j = counter, a = counter + s; j < a; j++)
        {
            A[j] = a - decrease;
            decrease++;
        }
        counter += s;
    }
    return 0;
}


问:
Linux Fultter desktop - unable to run app from compiled executable, flutter run works
Flutter doctor output:

```[✓] Flutter (Channel master, 1.19.0-2.0.pre.193, on Linux, locale pl_PL.UTF-8)
<b>    </b><b>•</b><b> Flutter version 1.19.0-2.0.pre.193 at /home/michal/android/flutter</b>
<b>    </b><b>•</b><b> Framework revision fed18fc433 (3 hours ago), 2020-05-29 03:43:01 -0400</b>
<b>    </b><b>•</b><b> Engine revision 17737e6fd4</b>
<b>    </b><b>•</b><b> Dart version 2.9.0 (build 2.9.0-11.0.dev 6489a0c68d)</b>

[✓] Android toolchain - develop for Android devices (Android SDK version
    29.0.0-rc2)
<b>    </b><b>•</b><b> Android SDK at /home/michal/Android/Sdk</b>
<b>    </b><b>•</b><b> Platform android-29, build-tools 29.0.0-rc2</b>
<b>    </b><b>•</b><b> ANDROID_HOME = /home/michal/Android/Sdk</b>
<b>    </b><b>•</b><b> Java binary at: /home/michal/android/studio/jre/bin/java</b>
<b>    </b><b>•</b><b> Java version OpenJDK Runtime Environment (build</b>
<b>      1.8.0_212-release-1586-b4-5784211)</b>
<b>    </b><b>•</b><b> All Android licenses accepted.</b>

[✓] Chrome - develop for the web
<b>    </b><b>•</b><b> Chrome at google-chrome</b>

[✓] Linux toolchain - develop for Linux desktop
<b>    </b><b>•</b><b> clang version 9.0.1-12</b>
<b>    </b><b>•</b><b> cmake version 3.16.3</b>
<b>    </b><b>•</b><b> ninja version 1.10.0</b>

[✓] Android Studio (version 3.6)
<b>    </b><b>•</b><b> Android Studio at /home/michal/android/studio</b>
<b>    </b><b>•</b><b> Flutter plugin version 45.1.1</b>
<b>    </b><b>•</b><b> Dart plugin version 192.8052</b>
<b>    </b><b>•</b><b> Java version OpenJDK Runtime Environment (build</b>
<b>      1.8.0_212-release-1586-b4-5784211)</b>

[✓] VS Code (version 1.45.1)
<b>    </b><b>•</b><b> VS Code at /usr/share/code</b>
<b>    </b><b>•</b><b> Flutter extension version 3.8.1</b>

[✓] Connected device (4 available)
<b>    </b><b>•</b><b> Android SDK built for x86 64 • emulator-5554 • android-x64    • Android 10</b>
<b>      (API 29) (emulator)</b>
<b>    </b><b>•</b><b> Linux                        • Linux         • linux-x64      • Linux</b>
<b>    </b><b>•</b><b> Web Server                   • web-server    • web-javascript • Flutter</b>
<b>      Tools</b>
<b>    </b><b>•</b><b> Chrome                       • chrome        • web-javascript • Google</b>
<b>      Chrome 84.0.4147.21 dev</b>

• No issues found!```

My app compiles succesfully and I am able to run it without any issues with flutter run -d Linux. However, that does not work when I try to run directly compiled executable, in this case I'm getting error message:

```embedder.cc (781): 'FlutterEngineInitialize' returned 'kInvalidArguments'. Not running in AOT mode but could not resolve the kernel binary.
Failed to start Flutter engine: error 2
Failed to create window.
```

Command to compile:
flutter build linux

Any suggestion how to get it running as standalone app?

答:
It sounds like you are trying to run the executable that's at the top level of the build output. You need to instead run the copy in the bundle subdirectory of the build directory, which has all the supporting files in the correct relative locations.

Once Linux is further along, details of how to use what's in the build directory will be documented somewhere.

Any suggestion how to get it running as standalone app?

The bundle directory as a whole is the standalone app. If you mean having everything in a single executable file without any supporting files needed, that's not possible.

Body:
Flutter doctor output:

[✓] Flutter (Channel master, 1.19.0-2.0.pre.193, on Linux, locale pl_PL.UTF-8)
    • Flutter version 1.19.0-2.0.pre.193 at /home/michal/android/flutter
    • Framework revision fed18fc433 (3 hours ago), 2020-05-29 03:43:01 -0400
    • Engine revision 17737e6fd4
    • Dart version 2.9.0 (build 2.9.0-11.0.dev 6489a0c68d)

[✓] Android toolchain - develop for Android devices (Android SDK version
    29.0.0-rc2)
    • Android SDK at /home/michal/Android/Sdk
    • Platform android-29, build-tools 29.0.0-rc2
    • ANDROID_HOME = /home/michal/Android/Sdk
    • Java binary at: /home/michal/android/studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build
      1.8.0_212-release-1586-b4-5784211)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 9.0.1-12
    • cmake version 3.16.3
    • ninja version 1.10.0

[✓] Android Studio (version 3.6)
    • Android Studio at /home/michal/android/studio
    • Flutter plugin version 45.1.1
    • Dart plugin version 192.8052
    • Java version OpenJDK Runtime Environment (build
      1.8.0_212-release-1586-b4-5784211)

[✓] VS Code (version 1.45.1)
    • VS Code at /usr/share/code
    • Flutter extension version 3.8.1

[✓] Connected device (4 available)
    • Android SDK built for x86 64 • emulator-5554 • android-x64    • Android 10
      (API 29) (emulator)
    • Linux                        • Linux         • linux-x64      • Linux
    • Web Server                   • web-server    • web-javascript • Flutter
      Tools
    • Chrome                       • chrome        • web-javascript • Google
      Chrome 84.0.4147.21 dev

• No issues found!

My app compiles succesfully and I am able to run it without any issues with flutter run -d Linux. However, that does not work when I try to run directly compiled executable, in this case I'm getting error message:

embedder.cc (781): 'FlutterEngineInitialize' returned 'kInvalidArguments'. Not running in AOT mode but could not resolve the kernel binary.
Failed to start Flutter engine: error 2
Failed to create window.

Command to compile:
flutter build linux

Any suggestion how to get it running as standalone app?


问:
Stop Printing double values SQL

Hello Guys!

Oracle SQL

I am trying to find a way to stop my sql Query print duplicate values.

For example Results coming for a table are:

```<code>Nikos
Nikos
Nikos
Tony
Tony
</code>```

The result I want:

```<code>Nikos
Tony
</code>```

Thanks in advance!

答:
Use DISTINCT to remove duplicate values :

```<code>SELECT DISTINCT col
FROM table t;
</code>```

Title: Stop Printing double values SQL

Body:
Hello Guys!

Oracle SQL

I am trying to find a way to stop my sql Query print duplicate values.

For example Results coming for a table are:

Nikos
Nikos
Nikos
Tony
Tony

The result I want:

Nikos
Tony

Thanks in advance!

Body:
Use DISTINCT to remove duplicate values :

SELECT DISTINCT col
FROM table t;


问:
Angular 9 "Error: This constructor was not compatible with Dependency Injection."
This weird error, that I don't remember seeing pre-Ivy, has popped up in the setup of a new app created with the latest Angular 9 CLI. Looks like it could be a bug with Ivy? Any ideas on how to fix would be greatly appreciated.

Error result from ng test

```<code>Error: This constructor was not compatible with Dependency Injection.
    at Module.ɵɵinvalidFactory (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:14150:1)
    at Object.Router_Factory [as factory] (http://localhost:9876/_karma_webpack_/node_modules/@angular/router/__ivy_ngcc__/fesm5/router.js:4404:67)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11425:1)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11247:1)
    at injectInjectorOnly (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:787:1)
    at ɵɵinject (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:792:1)
    at Object.AuthService_Factory [as factory] (ng:///AuthService/ɵfac.js:5:39)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11425:1)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11247:1)
    at NgModuleRef$1.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.NgModuleRef$1.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:24218:1)

Error: Expected undefined to be truthy.
    at <Jasmine>
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/shared/components/header/header.component.spec.ts:25:23)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone.js:396:1)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:305:1)
</code>```

app.component.ts

```<code>import { Component, HostBinding } from '@angular/core';
import { AuthService, ScreenService, AppInfoService } from './shared/services';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  @HostBinding('class') get getClass() {
    return Object.keys(this.screen.sizes)
      .filter(cl => this.screen.sizes[cl])
      .join(' ');
  }

  constructor(
    private authService: AuthService,
    private screen: ScreenService,
    public appInfo: AppInfoService,
  ) {}

  isAuthorized() {
    return this.authService.isLoggedIn;
  }
}
</code>```

app.component.spec.ts

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';

import { AppComponent } from './app.component';
import { AuthService } from './shared/services';

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [AuthService, Router],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
</code>```

package.json dependencies

```<code>  "dependencies": {
    "@angular/animations": "~9.0.2",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "~9.0.2",
    "@angular/compiler": "~9.0.2",
    "@angular/core": "~9.0.2",
    "@angular/forms": "~9.0.2",
    "@angular/platform-browser": "~9.0.2",
    "@angular/platform-browser-dynamic": "~9.0.2",
    "@angular/router": "~9.0.2",
    "devextreme": "latest",
    "devextreme-angular": "latest",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.3",
    "@angular/cli": "~9.0.3",
    "@angular/compiler-cli": "~9.0.2",
    "@angular/language-service": "~9.0.2",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "devextreme-cli": "latest",
    "devextreme-themebuilder": "latest",
    "husky": "^4.2.3",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "prettier": "^1.19.1",
    "pretty-quick": "^2.0.1",
    "protractor": "~5.4.3",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "tslint-config-prettier": "^1.18.0",
    "typescript": "~3.7.5",
    "webpack-bundle-analyzer": "^3.6.0"
  }
</code>```

NOTE: this error appeared after fixing NullInjectorError for both AuthService & Router.

答:
Another source of this error (not related to the OP's question) can be when you have a constructor param with a default arg such as:

constructor(someProp: string = 'propVal') {
    this.someProp = someProp;
}
```
<br>
You can resolve it by doing this instead:
<pre class="lang-js prettyprint-override"><code>constructor(@Inject('propVal') @Optional() someProp: string) {
    this.someProp = someProp;
}
</code>```

Body:
This weird error, that I don't remember seeing pre-Ivy, has popped up in the setup of a new app created with the latest Angular 9 CLI. Looks like it could be a bug with Ivy? Any ideas on how to fix would be greatly appreciated.

Error result from ng test

Error: This constructor was not compatible with Dependency Injection.
    at Module.ɵɵinvalidFactory (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:14150:1)
    at Object.Router_Factory [as factory] (http://localhost:9876/_karma_webpack_/node_modules/@angular/router/__ivy_ngcc__/fesm5/router.js:4404:67)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11425:1)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11247:1)
    at injectInjectorOnly (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:787:1)
    at ɵɵinject (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:792:1)
    at Object.AuthService_Factory [as factory] (ng:///AuthService/ɵfac.js:5:39)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11425:1)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11247:1)
    at NgModuleRef$1.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.NgModuleRef$1.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:24218:1)

Error: Expected undefined to be truthy.
    at <Jasmine>
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/shared/components/header/header.component.spec.ts:25:23)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone.js:396:1)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:305:1)

app.component.ts

import { Component, HostBinding } from '@angular/core';
import { AuthService, ScreenService, AppInfoService } from './shared/services';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  @HostBinding('class') get getClass() {
    return Object.keys(this.screen.sizes)
      .filter(cl => this.screen.sizes[cl])
      .join(' ');
  }

  constructor(
    private authService: AuthService,
    private screen: ScreenService,
    public appInfo: AppInfoService,
  ) {}

  isAuthorized() {
    return this.authService.isLoggedIn;
  }
}

app.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';

import { AppComponent } from './app.component';
import { AuthService } from './shared/services';

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [AuthService, Router],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

package.json dependencies

  "dependencies": {
    "@angular/animations": "~9.0.2",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "~9.0.2",
    "@angular/compiler": "~9.0.2",
    "@angular/core": "~9.0.2",
    "@angular/forms": "~9.0.2",
    "@angular/platform-browser": "~9.0.2",
    "@angular/platform-browser-dynamic": "~9.0.2",
    "@angular/router": "~9.0.2",
    "devextreme": "latest",
    "devextreme-angular": "latest",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.3",
    "@angular/cli": "~9.0.3",
    "@angular/compiler-cli": "~9.0.2",
    "@angular/language-service": "~9.0.2",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "devextreme-cli": "latest",
    "devextreme-themebuilder": "latest",
    "husky": "^4.2.3",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "prettier": "^1.19.1",
    "pretty-quick": "^2.0.1",
    "protractor": "~5.4.3",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "tslint-config-prettier": "^1.18.0",
    "typescript": "~3.7.5",
    "webpack-bundle-analyzer": "^3.6.0"
  }

NOTE: this error appeared after fixing NullInjectorError for both AuthService & Router.

Body:
Another source of this error (not related to the OP's question) can be when you have a constructor param with a default arg such as:

constructor(someProp: string = 'propVal') {
    this.someProp = someProp;
}

You can resolve it by doing this instead:

constructor(@Inject('propVal') @Optional() someProp: string) {
    this.someProp = someProp;
}


问:
Issue with SignalR primary/secondary
I have an asp dotnet core 3.1 application that uses SignalR.  According to this documentation, you can add primary and secondary connections.  I have this working in one of my services, but another service keeps bombing out and I can't figure out why.

Error message:

```<code>Connection string missing required properties endpoint and accesskey. (Parameter 'connectionString')
</code>```

Stack:

```<code>at Microsoft.Azure.SignalR.ConnectionStringParser.Parse(String connectionString)
   at Microsoft.Azure.SignalR.ServiceEndpoint..ctor(String connectionString, EndpointType type, String name)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase.<GetEndpoints>d__16.MoveNext()
   at System.Linq.Enumerable.DistinctIterator`1.MoveNext()
   at System.Linq.Lookup`2.Create(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
   at System.Linq.GroupedEnumerable`2.GetEnumerator()
   at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase.GetValuableEndpoints(IEnumerable`1 endpoints)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase..ctor(IEnumerable`1 endpoints, ILogger logger)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase..ctor(IServiceEndpointOptions options, ILogger logger)
   at Microsoft.Azure.SignalR.ServiceEndpointManager..ctor(IOptionsMonitor`1 optionsMonitor, ILoggerFactory loggerFactory)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Azure.SignalR.ServiceHubDispatcher.Start(Endpoint endpoint, Type hubType, ConnectionDelegate app)
   at Microsoft.Azure.SignalR.AzureSignalRHostedService.Start()
   at Microsoft.Azure.SignalR.AzureSignalRStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.ApplicationInsights.AspNetCore.ApplicationInsightsStartupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__31.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__9.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at SigR.Program.Main(String[] args) in G:\Git_Merc\ms-chat\WebApi\Program.cs:line 13
</code>```

I have this Environment variable:

Azure:SignalR:ConnectionString:Primary

with value

Endpoint=https://<redacted>;AccessKey=<redacted>Version=1.0;

If I remove the :Primary from the key, it works, but it should work with it as well.  I've also tried inserting a , such as

Azure:SignalR:ConnectionString:Test:Primary

And, like I said, I have another service working with that key.  TBH, I'm not even sure why DI is picking this up on app startup?

Edit:

Adding requested code.

```<code>var sigrBuilder = services.AddSignalR().AddNewtonsoftJsonProtocol(options =>
            {
                options.PayloadSerializerSettings.Converters = new List<JsonConverter>
                {
                    new TransferOptionConverter() //converters for data from mercury
                };
            });
sigrBuilder.AddAzureSignalR();
</code>```

答:
As you can see in this example you should specify the primary and secondary instaces when Adding Azure SignalR like:

var sigrBuilder = services.AddSignalR().AddNewtonsoftJsonProtocol(options =>
{
    options.PayloadSerializerSettings.Converters = new List<JsonConverter>
    {
        new TransferOptionConverter() //converters for data from mercury
    };
});

sigrBuilder.AddAzureSignalR(options => options.Endpoints = new ServiceEndpoint[]
{
    new ServiceEndpoint("<connection_string1>", EndpointType.Primary, "region1"),
    new ServiceEndpoint("<connection_string2>", EndpointType.Secondary, "region2"),
});
```

Title: Issue with SignalR primary/secondary

Body:
I have an asp dotnet core 3.1 application that uses SignalR.  According to this documentation, you can add primary and secondary connections.  I have this working in one of my services, but another service keeps bombing out and I can't figure out why.

Error message:

Connection string missing required properties endpoint and accesskey. (Parameter 'connectionString')

Stack:

at Microsoft.Azure.SignalR.ConnectionStringParser.Parse(String connectionString)
   at Microsoft.Azure.SignalR.ServiceEndpoint..ctor(String connectionString, EndpointType type, String name)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase.<GetEndpoints>d__16.MoveNext()
   at System.Linq.Enumerable.DistinctIterator`1.MoveNext()
   at System.Linq.Lookup`2.Create(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
   at System.Linq.GroupedEnumerable`2.GetEnumerator()
   at System.Linq.Enumerable.SelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase.GetValuableEndpoints(IEnumerable`1 endpoints)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase..ctor(IEnumerable`1 endpoints, ILogger logger)
   at Microsoft.Azure.SignalR.ServiceEndpointManagerBase..ctor(IServiceEndpointOptions options, ILogger logger)
   at Microsoft.Azure.SignalR.ServiceEndpointManager..ctor(IOptionsMonitor`1 optionsMonitor, ILoggerFactory loggerFactory)
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitRootCache(ServiceCallSite singletonCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Azure.SignalR.ServiceHubDispatcher.Start(Endpoint endpoint, Type hubType, ConnectionDelegate app)
   at Microsoft.Azure.SignalR.AzureSignalRHostedService.Start()
   at Microsoft.Azure.SignalR.AzureSignalRStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Mvc.Filters.MiddlewareFilterBuilderStartupFilter.<>c__DisplayClass0_0.<Configure>g__MiddlewareFilterBuilder|0(IApplicationBuilder builder)
   at Microsoft.ApplicationInsights.AspNetCore.ApplicationInsightsStartupFilter.<>c__DisplayClass2_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.HostFilteringStartupFilter.<>c__DisplayClass0_0.<Configure>b__0(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.GenericWebHostService.<StartAsync>d__31.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.Internal.Host.<StartAsync>d__9.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.<RunAsync>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost host)
   at SigR.Program.Main(String[] args) in G:\Git_Merc\ms-chat\WebApi\Program.cs:line 13

I have this Environment variable:

Azure:SignalR:ConnectionString:Primary

with value

Endpoint=https://<redacted>;AccessKey=<redacted>Version=1.0;

If I remove the :Primary from the key, it works, but it should work with it as well.  I've also tried inserting a , such as

Azure:SignalR:ConnectionString:Test:Primary

And, like I said, I have another service working with that key.  TBH, I'm not even sure why DI is picking this up on app startup?

Edit:

Adding requested code.

var sigrBuilder = services.AddSignalR().AddNewtonsoftJsonProtocol(options =>
            {
                options.PayloadSerializerSettings.Converters = new List<JsonConverter>
                {
                    new TransferOptionConverter() //converters for data from mercury
                };
            });
sigrBuilder.AddAzureSignalR();


问:
Regular expression to match balanced parentheses
I need a regular expression to select all the text between two outer brackets.

Example:

START_TEXT(text here(possible text)text(possible text(more text)))END_TXT

          ^                                                      ^

Result:

(text here(possible text)text(possible text(more text)))

答:
I didn't use regex since it is difficult to deal with nested code. So this snippet should be able to allow you to grab sections of code with balanced brackets:

```<code>def extract_code(data):
    """ returns an array of code snippets from a string (data)"""
    start_pos = None
    end_pos = None
    count_open = 0
    count_close = 0
    code_snippets = []
    for i,v in enumerate(data):
        if v =='{':
            count_open+=1
            if not start_pos:
                start_pos= i
        if v=='}':
            count_close +=1
            if count_open == count_close and not end_pos:
                end_pos = i+1
        if start_pos and end_pos:
            code_snippets.append((start_pos,end_pos))
            start_pos = None
            end_pos = None

    return code_snippets

</code>```

I used this to extract code snippets from a text file.

OwnerDisplayName: DaveF

LastEditorDisplayName: Chad Birch

Body:
I didn't use regex since it is difficult to deal with nested code. So this snippet should be able to allow you to grab sections of code with balanced brackets:

def extract_code(data):
    """ returns an array of code snippets from a string (data)"""
    start_pos = None
    end_pos = None
    count_open = 0
    count_close = 0
    code_snippets = []
    for i,v in enumerate(data):
        if v =='{':
            count_open+=1
            if not start_pos:
                start_pos= i
        if v=='}':
            count_close +=1
            if count_open == count_close and not end_pos:
                end_pos = i+1
        if start_pos and end_pos:
            code_snippets.append((start_pos,end_pos))
            start_pos = None
            end_pos = None

    return code_snippets

I used this to extract code snippets from a text file.


问:
Why doesn't "case" with "when > 2" work?
Why is this not working?</p>

```<code>case ARGV.length
  when 0
    abort "Error 1"
  when > 2
    abort "Error 2"
end
</code>```

答:
Well, it doesn't work because it's not valid ruby syntax. However, you can do this:</p>

```<code>x = 15
case x
  when 0..9 then puts "good"
  when 10..12 then puts "better"
  when 13..200 then puts "best"
  else
    puts "either great or poor"
end
</code>```

Body:
Why is this not working?

case ARGV.length
  when 0
    abort "Error 1"
  when > 2
    abort "Error 2"
end

Body:
Well, it doesn't work because it's not valid ruby syntax. However, you can do this:

x = 15
case x
  when 0..9 then puts "good"
  when 10..12 then puts "better"
  when 13..200 then puts "best"
  else
    puts "either great or poor"
end


问:
How do I access a prefab and all of its instantiated clones in c# and unity?
I need a little help again please. I'm currently working on powerups and it's setup so that the powerup affectsthe prefab thats put into its prefab slot, so this is means it is currently only affecting one object (in my case, enemy). When the game starts I spawn about 20 enemies and if i pickup the powerup I want it to affect all those spawned enemies and not only the one that is dragged onto the script, does anyone have a solution or alternate method to do this please?</p>

答:
When instantiate them store them in a list and then iterate through all and update their value

In your case e.g.

```<code>// if enemies have a certain Component rather use that type here instead of GameObject
public GameObject enemyPrefab;
// and use the same type here instead of GameObject
private List<GameObject> enemyInstances = new List<GameObject> enemyInstances;

private void Start()
{
    for(int i = 0; i < 20; i++)
    {
        var newEnemy = Instantiate(enemyPrefab);
        enemyInstances.Add(newEnemy);
    }
}
</code>```

and then later

```<code>public void UpdateEnemies()
{
    foreach(var enemy in enemyInstances)
    {
        // skip already destroyed objects
        if(!enemy) continue;

        // whatever to be done to the enemies
    }
}
</code>```

Body:
When instantiate them store them in a list and then iterate through all and update their value

In your case e.g.

// if enemies have a certain Component rather use that type here instead of GameObject
public GameObject enemyPrefab;
// and use the same type here instead of GameObject
private List<GameObject> enemyInstances = new List<GameObject> enemyInstances;

private void Start()
{
    for(int i = 0; i < 20; i++)
    {
        var newEnemy = Instantiate(enemyPrefab);
        enemyInstances.Add(newEnemy);
    }
}

and then later

public void UpdateEnemies()
{
    foreach(var enemy in enemyInstances)
    {
        // skip already destroyed objects
        if(!enemy) continue;

        // whatever to be done to the enemies
    }
}


问:
How to delete last element in array and put new in front?
I have a question concerning Java. I started up new to Java and my google search brought many results but non was the final help.
I created a class to track historical information. I have different values for different days and need to update them un a regular basis. I want to keep track of the last 30 days and created an array with 30 elements. When I call my 'shift' function I want to drop the last n elements and put zeros in front. Here is a minial example for 5 days:

```<code>public class Testclass {

    private int[] histInfo;

    public Element()
    {
        this.histInfo = new int[5];
    }

    public void shift_histInfo(long m)
    {
        //do magic
    }
}
</code>```

What I want shift to do is

```<code>INPUT:
histInfo = [50,21,1,45,901]

OPERATION:
shift_histInfo(2);

RESULT:
histInfo = [0,0,50,21,1]
</code>```

I am thankfull for every kind of help you can support as well for thought-provoking impulses if you think that there is a way more elegant or efficient way.

Best :-)

答:
You can try this :

```<code>public static void shift_histInfo(long m)
{
    int[] myIntArray = {50,21,1,45,901};
    int[] myIntArray2 = {50,21,1,45,901};

    for (int j=0 ;j< myIntArray.length ; j++){
        int temp = (int) (j+m);
        if (temp >= myIntArray.length){
            temp = temp - myIntArray.length;
            myIntArray2[temp] = 0;
        } else {
            myIntArray2[temp] = myIntArray[j];
        }

    }
    for (int j=0 ;j< myIntArray2.length ; j++){
        System.out.println(myIntArray2[j]);
    }

}
</code>```

Output :

when shift_histInfo(2) ,

```<code>[0,0,50,21,1]
</code>```

Body:
I have a question concerning Java. I started up new to Java and my google search brought many results but non was the final help.
I created a class to track historical information. I have different values for different days and need to update them un a regular basis. I want to keep track of the last 30 days and created an array with 30 elements. When I call my 'shift' function I want to drop the last n elements and put zeros in front. Here is a minial example for 5 days:

public class Testclass {

    private int[] histInfo;

    public Element()
    {
        this.histInfo = new int[5];
    }

    public void shift_histInfo(long m)
    {
        //do magic
    }
}

What I want shift to do is

INPUT:
histInfo = [50,21,1,45,901]

OPERATION:
shift_histInfo(2);

RESULT:
histInfo = [0,0,50,21,1]

I am thankfull for every kind of help you can support as well for thought-provoking impulses if you think that there is a way more elegant or efficient way.

Best :-)

Body:
You can try this :

public static void shift_histInfo(long m)
{
    int[] myIntArray = {50,21,1,45,901};
    int[] myIntArray2 = {50,21,1,45,901};

    for (int j=0 ;j< myIntArray.length ; j++){
        int temp = (int) (j+m);
        if (temp >= myIntArray.length){
            temp = temp - myIntArray.length;
            myIntArray2[temp] = 0;
        } else {
            myIntArray2[temp] = myIntArray[j];
        }

    }
    for (int j=0 ;j< myIntArray2.length ; j++){
        System.out.println(myIntArray2[j]);
    }

}

Output :

when shift_histInfo(2) ,

[0,0,50,21,1]


问:
Group By in java 8 with multiple levels of grouping
I have such structure

```<code>| Director1 | Manager1 | Employee1 |
| Director1 | Manager1 | Employee2 |
| Director1 | Manager2 | Employee3 |
| Director2 | Manager3 | Employee4 |
</code>```

I fetch this data from Db to Pojo like this

```<code>@Data
public class Workers {
 private String directorName;
 private String managerName;
 private String employeeName;
}
</code>```

DB is denormalized.

Mow in java code I need to group this response to not to return redundant data. My response data looks like

```<code>@Data
public class WorkersResponse{
 private String directorName;
 ...
 private List<Manager> managers;
}

@Data
public class Manager{
 private String manager;
  ...
 private List<Employee> employee;
}

@Data
public class Employee{
 private String employee;
 ...
}
</code>```

With grouping I want to receive List. For now I figured out how to group directors :

```<code>Map<WorkersResponse, List<Workers >> collect = all.stream()
            .collect(Collectors.groupingBy(v -> {
                WorkersResponse workersResponse= new WorkersResponse();
                workersResponse.setDirector(v.getDirectorName());
                return workersResponse;
            }));
</code>```

But how should then I populate list with Managers and Employees?

答:
Based on the grouping requirement, you should try using nested grouping along with Collectors.mapping such as:

```<code>Map<String, Map<String, List<String>>> groupingRequirement = workersList.stream()
        .collect(Collectors.groupingBy(Workers::getDirectorName,
                Collectors.groupingBy(Workers::getManagerName,
                        Collectors.mapping(Workers::getEmployeeName,
                                Collectors.toList()))));
</code>```

Thereafter mapping to objects of the desired type is the only constraint left while you iterated over the entries of the collected Map -

```<code>List<WorkersResponse> workersResponses = groupingRequirement.entrySet().stream()
        .map(e -> new WorkersResponse(e.getKey(), // director name
                e.getValue().entrySet()
                        .stream()
                        .map(ie -> new Manager(ie.getKey(), // manager name
                                ie.getValue()
                                        .stream()
                                        .map(Employee::new)
                                        .collect(Collectors.toList())))
                        .collect(Collectors.toList())))
        .collect(Collectors.toList());
</code>```

Body:
I have such structure

| Director1 | Manager1 | Employee1 |
| Director1 | Manager1 | Employee2 |
| Director1 | Manager2 | Employee3 |
| Director2 | Manager3 | Employee4 |

I fetch this data from Db to Pojo like this

@Data
public class Workers {
 private String directorName;
 private String managerName;
 private String employeeName;
}

DB is denormalized.

Mow in java code I need to group this response to not to return redundant data. My response data looks like

@Data
public class WorkersResponse{
 private String directorName;
 ...
 private List<Manager> managers;
}

@Data
public class Manager{
 private String manager;
  ...
 private List<Employee> employee;
}

@Data
public class Employee{
 private String employee;
 ...
}

With grouping I want to receive List. For now I figured out how to group directors :

Map<WorkersResponse, List<Workers >> collect = all.stream()
            .collect(Collectors.groupingBy(v -> {
                WorkersResponse workersResponse= new WorkersResponse();
                workersResponse.setDirector(v.getDirectorName());
                return workersResponse;
            }));

But how should then I populate list with Managers and Employees?

Body:
Based on the grouping requirement, you should try using nested grouping along with Collectors.mapping such as:

Map<String, Map<String, List<String>>> groupingRequirement = workersList.stream()
        .collect(Collectors.groupingBy(Workers::getDirectorName,
                Collectors.groupingBy(Workers::getManagerName,
                        Collectors.mapping(Workers::getEmployeeName,
                                Collectors.toList()))));

Thereafter mapping to objects of the desired type is the only constraint left while you iterated over the entries of the collected Map -

List<WorkersResponse> workersResponses = groupingRequirement.entrySet().stream()
        .map(e -> new WorkersResponse(e.getKey(), // director name
                e.getValue().entrySet()
                        .stream()
                        .map(ie -> new Manager(ie.getKey(), // manager name
                                ie.getValue()
                                        .stream()
                                        .map(Employee::new)
                                        .collect(Collectors.toList())))
                        .collect(Collectors.toList())))
        .collect(Collectors.toList());


问:
What does registering a DLL do?
I know how to register dlls but I've never really been sure why I'm doing it or under what conditions a dll must be registered.  Could somebody explain or point me to some documentation?  </p>

答:
When a DLL is registered, the DllRegisterServer method entry point in your DLL is invoked.  Similarly, DllUnregisterServer is invoked when a DLL is unregistered.

As described in this MSDN article:

Instructs an in-process server to
  create its registry entries for all
  classes supported in this server
  module. If this function fails, the
  state of the registry for all its
  classes is indeterminate.

For COM DLLs, you will need to implement your own DllRegisterServer and DllUnregisterServer entry point methods which do the registering/unregistering as appropriate.  Example code for DllRegisterServer can be found here.

The end result of registering a DLL is that all of the CLSIDs for the components in the DLL are registered under HKEY_CLASSES_ROOT\CLSID.  This allows CoCreateInstance to find the correct server when instantiating COM objects from another DLL or application.

DllUnregisterServer will do the reverse, and remove all of the CLSIDs from the registry that were put in there by DllRegisterServer.

More general information about DllRegisterServer can be found here.

OwnerDisplayName: stimms

ContentLicense: CC BY-SA 2.5

Title: What does registering a DLL do?

LastEditorDisplayName: gbjbaanb

OwnerDisplayName: LeopardSkinPillBoxHat

LastEditorDisplayName: LeopardSkinPillBoxHat


答:
```<code>    int[] array={1,2,3,4,5,6};
    int removelength=2;
    int e=1;
    while(e<=removelength) {
        for(int i=1;i<array.length;i++)
        array[array.length-i]=array[array.length-i-1];
        e++;
    }

    for(int i=0;i<removelength;i++) {
        array[i]=0;
    }
    for(int g:array)
    {
      System.out.print(g);
    }
</code>```

Title: How to delete last element in array and put new in front?


问:
How can I delay an observable only if it returns faster than the delay
Take for example:

```<code> this.http.get('/getdata').pipe(delay(2000))
</code>```

I would like this request to take a minimum of 2s to complete, but not any longer than it takes for the request to complete.

In other words:

if the request takes 1s to complete, I want the observable to complete in 2s.

if the request takes 3s to complete, I want the observable to complete in 3s NOT 5s.

Is there some other pipe other than delay() that can achieve this that I don't know about or is there a way to build a custom pipe for this if necessary?

The use case is to show a loader, however if the request completes too fast it doesnt look good when the loader just "flashes" for a split second

答:
Thanks to GregL, I updated this to just use a forkJoin. This will get the latest value of the streams. But if you want to check it on every emmission, you can replace forkJoin with combineLatest and that will work too.
In my working example:</p>
```<code>    this.ibanSubscription = forkJoin({
        iban: this.ibantobicService.getById(Iban),
        timer: timer(1000) //so now the ajax call will take at least 1 second
        }
    ).pipe(
        map( (stream: any) => <BicModel>stream.iban),
        switchMap( (bic: BicModel) => of(this.processIbanData(bic))),
        catchError((error: any) => of(this.messageList.handleError(error))),
        finalize(() => this.loadIbanToBicFinalize())
   ).subscribe();
</code>```

Body:
Take for example:

 this.http.get('/getdata').pipe(delay(2000))

I would like this request to take a minimum of 2s to complete, but not any longer than it takes for the request to complete.

In other words:

if the request takes 1s to complete, I want the observable to complete in 2s.

if the request takes 3s to complete, I want the observable to complete in 3s NOT 5s.

Is there some other pipe other than delay() that can achieve this that I don't know about or is there a way to build a custom pipe for this if necessary?

The use case is to show a loader, however if the request completes too fast it doesnt look good when the loader just "flashes" for a split second

Body:
Thanks to GregL, I updated this to just use a forkJoin. This will get the latest value of the streams. But if you want to check it on every emmission, you can replace forkJoin with combineLatest and that will work too.
In my working example:

    this.ibanSubscription = forkJoin({
        iban: this.ibantobicService.getById(Iban),
        timer: timer(1000) //so now the ajax call will take at least 1 second
        }
    ).pipe(
        map( (stream: any) => <BicModel>stream.iban),
        switchMap( (bic: BicModel) => of(this.processIbanData(bic))),
        catchError((error: any) => of(this.messageList.handleError(error))),
        finalize(() => this.loadIbanToBicFinalize())
   ).subscribe();


问:
How to stop Material dropdown autocomplete selection from triggering another search query in Angular 8/9?
Summary: I have a working as-you-type field dropdown search. When I choose from the dropdown, which happily sets the field to the object I've received in the search, but unhappily registers THAT change and sends the whole object off to be searched.

HTML:

<form [formGroup]="myForm" novalidate>
  <mat-form-field>
    <input matInput
    placeholder="SKU / Item Number"
    [matAutocomplete]="auto"
    formControlName='itemName'>
  </mat-form-field>
  <mat-autocomplete #auto="matAutocomplete" [displayWith]="parseDropDownSelection">
      <mat-option
            *ngFor="let row of searchQueryResult"
            [value]="row"
            (onSelectionChange)="onItemSelection($event)">
        {{ row.Name }}
      </mat-option>
  </mat-autocomplete>
</form>
```

<p>Setup:</p>

<pre class="lang-js prettyprint-override"><code>import {FieldSearchServiceItem}     from './../services/field-search.service';

constructor(
    private dialog: MatDialog,
    private formBuilder: FormBuilder,
    private http: HttpClient,
    private appServiceItem: FieldSearchServiceItem,
    )   {}
</code>```

ngOnInit()

ngOnInit(){
    this.myForm = this.formBuilder.group
        ({
        itemName: '',
        });

this.myForm
  .get('itemName')
  .valueChanges
  .pipe(
    debounceTime(200),
    switchMap(value => this.appServiceItem.search({name: value}, 1))
    )
  .subscribe(serviceResult => this.searchQueryResult = serviceResult.qResult);
}
```

<p>The service:</p>

<pre class="lang-js prettyprint-override"><code>@Injectable()
export class FieldSearchServiceItem
  {
  constructor(private http: HttpClient) {}
  search(filter: {name: string} = {name: ''}, page = 1): Observable<apiQueryResponseForItem>
    {
    var queryResponse;
    return this.http.get<apiQueryResponseForItem>(`example.com/search/item/${filter.name}`)
    .pipe(
      tap((response: apiQueryResponseForItem) =>
        {
        response.qResult = response.qResult
          .map(unit => new ItemUnit(unit.Id, unit.Name))
        return response;
        })
      );
    }
  }
</code>```

The class defs:

export class ItemUnit
    {
    constructor
        (
        public Id:number,
        public Name:string,
        )   {}
    }

export interface apiQueryResponseForItem
    {
    qSuccess: boolean;
    qResult: ItemUnit[];
    }
```

<p>I've seen other answers where the solution has been to use the emitEvent:false when setting the value, like so:</p>

<pre class="lang-js prettyprint-override"><code>this.myForm.get('itemName').patchValue('theDataThatCameBackFromSeach', {emitEvent:false})
</code>```

That makes sense... but I get the feeling that solution doesn't match up with this observable/injectable/Material approach... mainly because I'm not using a call that does a .setValue() or .patchValue(), I'm guessing there's a binding somewhere in the Material stuff that's handling that.

The server ending up seeing calls like this:

```<code>http://example.com/search/item/a                   (when the letter a is typed)
http://example.com/search/item/[object%20Object]   (after clicking the dropdown, JS tries to search 'object' after clumsily falling back to string representation )
</code>```

My onItemSelection() is currently uninvolved, it's working but does nothing other than dump to the console. The .qResult that's coming back from my searchQueryResult service contains {Id:number,Name:string}. How can I have the field-setting action of the autocomplete still do its work of setting the field, but not creating a change event when it does that, while still honoring the onItemSelection() so I can get my other processing done?

答:
I've faced the same issue some time ago, and this is the final solution that I've been using for several inputs in my system.

The steps are:

Realize that there are actually two events here. Something Typed and Value Selected.

Create two observables for the the two events and handle them separately.

class Component {
  ngOnInit() {

    /*       SEPARATE THE EVENTS      */

    // If it's an object, it's been selected.
    // I also don't allow selecting `null` but it's up to you.
    const itemSelected$ = this.myForm.get('itemName').valueChanges.pipe(
      filter(val => typeof val === 'object' && val !== null),
    );
    // If it's a string, it's been typed into the input
    const itemTyped$ = this.myForm.get('itemName').valueChanges.pipe(
      filter(val => typeof val === 'string'),
    );

    /*       HANDLE ITEM SELECTED     */

    itemSelected$.subscribe(item => {
      // If you want, you can also handle "fake" items here.
      // I use this trick to show a placeholder like "Create New Item" in the dropdown
      if (item.id === 0 && item.name === 'Create New Item') {
        this.createNewItem().subscribe(
          newItem => this.myForm.get('itemName').setValue(newItem),
        );
        return;
      }
      // I use this in a custom input component (with ControlValueAccessor)
      // So this is where I notify the parent
      this.onChange(item);
    });

    /*       HANDLE ITEM TYPED        */

    const searchQueryResult$ = itemTyped$.pipe(
      debounce(200),
      tap(value => {/* you could handle starting a loading spinner or smth here */}),
      switchMap(name => this.appServiceItem.search({name}, 1)),
    );

    // now you can either use searchQueryResult$ with async pipe:
    // this.filteredResults$ = searchQueryResult$;
    // or subscribe to it and update a field in your component class:
    searchQueryResult$.subscribe(result => this.searchQueryResult = result);
    // If you subscribe, don't forget to clean up subscriptions onDestroy
  }
}
```

I've taken the liberty to add a few suggestions and tricks, but you get the general idea - create two separate mutually exclusive observables and handle them separately.

Body:
Summary: I have a working as-you-type field dropdown search. When I choose from the dropdown, which happily sets the field to the object I've received in the search, but unhappily registers THAT change and sends the whole object off to be searched.

HTML:

<form [formGroup]="myForm" novalidate>
  <mat-form-field>
    <input matInput
    placeholder="SKU / Item Number"
    [matAutocomplete]="auto"
    formControlName='itemName'>
  </mat-form-field>
  <mat-autocomplete #auto="matAutocomplete" [displayWith]="parseDropDownSelection">
      <mat-option
            *ngFor="let row of searchQueryResult"
            [value]="row"
            (onSelectionChange)="onItemSelection($event)">
        {{ row.Name }}
      </mat-option>
  </mat-autocomplete>
</form>

Setup:

import {FieldSearchServiceItem}     from './../services/field-search.service';

constructor(
    private dialog: MatDialog,
    private formBuilder: FormBuilder,
    private http: HttpClient,
    private appServiceItem: FieldSearchServiceItem,
    )   {}

ngOnInit()

ngOnInit(){
    this.myForm = this.formBuilder.group
        ({
        itemName: '',
        });

this.myForm
  .get('itemName')
  .valueChanges
  .pipe(
    debounceTime(200),
    switchMap(value => this.appServiceItem.search({name: value}, 1))
    )
  .subscribe(serviceResult => this.searchQueryResult = serviceResult.qResult);
}

The service:

@Injectable()
export class FieldSearchServiceItem
  {
  constructor(private http: HttpClient) {}
  search(filter: {name: string} = {name: ''}, page = 1): Observable<apiQueryResponseForItem>
    {
    var queryResponse;
    return this.http.get<apiQueryResponseForItem>(`example.com/search/item/${filter.name}`)
    .pipe(
      tap((response: apiQueryResponseForItem) =>
        {
        response.qResult = response.qResult
          .map(unit => new ItemUnit(unit.Id, unit.Name))
        return response;
        })
      );
    }
  }

The class defs:

export class ItemUnit
    {
    constructor
        (
        public Id:number,
        public Name:string,
        )   {}
    }

export interface apiQueryResponseForItem
    {
    qSuccess: boolean;
    qResult: ItemUnit[];
    }

I've seen other answers where the solution has been to use the emitEvent:false when setting the value, like so:

this.myForm.get('itemName').patchValue('theDataThatCameBackFromSeach', {emitEvent:false})

That makes sense... but I get the feeling that solution doesn't match up with this observable/injectable/Material approach... mainly because I'm not using a call that does a .setValue() or .patchValue(), I'm guessing there's a binding somewhere in the Material stuff that's handling that.

The server ending up seeing calls like this:

http://example.com/search/item/a                   (when the letter a is typed)
http://example.com/search/item/[object%20Object]   (after clicking the dropdown, JS tries to search 'object' after clumsily falling back to string representation )

My onItemSelection() is currently uninvolved, it's working but does nothing other than dump to the console. The .qResult that's coming back from my searchQueryResult service contains {Id:number,Name:string}. How can I have the field-setting action of the autocomplete still do its work of setting the field, but not creating a change event when it does that, while still honoring the onItemSelection() so I can get my other processing done?

Body:
I've faced the same issue some time ago, and this is the final solution that I've been using for several inputs in my system.

The steps are:

Realize that there are actually two events here. Something Typed and Value Selected.

Create two observables for the the two events and handle them separately.

class Component {
  ngOnInit() {

    /*       SEPARATE THE EVENTS      */

    // If it's an object, it's been selected.
    // I also don't allow selecting `null` but it's up to you.
    const itemSelected$ = this.myForm.get('itemName').valueChanges.pipe(
      filter(val => typeof val === 'object' && val !== null),
    );
    // If it's a string, it's been typed into the input
    const itemTyped$ = this.myForm.get('itemName').valueChanges.pipe(
      filter(val => typeof val === 'string'),
    );

    /*       HANDLE ITEM SELECTED     */

    itemSelected$.subscribe(item => {
      // If you want, you can also handle "fake" items here.
      // I use this trick to show a placeholder like "Create New Item" in the dropdown
      if (item.id === 0 && item.name === 'Create New Item') {
        this.createNewItem().subscribe(
          newItem => this.myForm.get('itemName').setValue(newItem),
        );
        return;
      }
      // I use this in a custom input component (with ControlValueAccessor)
      // So this is where I notify the parent
      this.onChange(item);
    });

    /*       HANDLE ITEM TYPED        */

    const searchQueryResult$ = itemTyped$.pipe(
      debounce(200),
      tap(value => {/* you could handle starting a loading spinner or smth here */}),
      switchMap(name => this.appServiceItem.search({name}, 1)),
    );

    // now you can either use searchQueryResult$ with async pipe:
    // this.filteredResults$ = searchQueryResult$;
    // or subscribe to it and update a field in your component class:
    searchQueryResult$.subscribe(result => this.searchQueryResult = result);
    // If you subscribe, don't forget to clean up subscriptions onDestroy
  }
}

I've taken the liberty to add a few suggestions and tricks, but you get the general idea - create two separate mutually exclusive observables and handle them separately.


问:
Keeping testing and production server environments clean, in sync, and consistent
It seems that the company that I work for is always struggling with our customers’ server environments.

Specifically, we almost always encounter problems with testing servers and production servers, and the fact that they always seem to be configured differently. When we test the applications that we develop, the testing servers behave in one way, and thus we tweak and configure our applications to fit that particular behavior. But when we install the same application on the production servers we observe another behavior that is not consistent with the testing servers, thus rendering our tweaks and configurations useless. The most frustrating part is that this happens all the time and that no one seem to know what to do about it.

Of course we have a general idea of why this happens. Every cloned environment starts out the same and works the same the first couple of days, but sooner or later someone reconfigure something in only one of the server environments (be it a database update, an update of a component library, a web file update, or other configurations), thereby leading to discrepancy. And as time goes by, more and more discrepancies builds up. But the question is: what can we do about it?

I’ve tried searching the web but can’t find any good answers on what to do. I’ve also tried to figure out some solutions on my own, but most of my ideas seem to be problematic in some way. New routines, no matter how rigorous, can be circumvented. Regular cloning of the production servers to create testing servers is a tedious and often very slow process. Automatic replication is not always reliable or even possible. So what on Earth should we do about this problem? How can we guarantee that the experience when testing will match the experience when going live?

I imagine that others have this very problem as well. Or do they? Maybe it's just my particular company that is incompetent? Have any of you encountered the problem? If so, what did you do about it?

Sincerely,

Linus, Swedish systems developer

答:
For keeping MySQL databases in sync, I just ran into this tool:

http://schemasync.org/

I haven't actually used it yet so I can't speak to whether it's any good, but we need some way to control schema drift between test and prod so we're going to give it a shot.

OwnerDisplayName: Linus

LastEditorDisplayName: Jeff Atwood