问:
Sending array from URL.Action and getting null in controller
I have a function that after adding items in a for loop calls the controller through the action URL sending the arr parameter (array), I see that it sends the data but null appears in the controller parameter. I wanted to know what could be wrong?

Javscript Function

```<code>function Submit() {
  QRCodeval.forEach((code) => arr.push(code.innerHTML));
  window.location.href = "@Url.Action("ReceivedFromBarCode","PurchaseOrder")?" +arr;
}
</code>```

Link generated by the controller:

http://localhost:56978/PurchaseOrder/ReceivedFromBarCode?JJJKP,RRPRQ,PPLQR

Controller where I get null in the arr parameter.

```<code>public async Task<ActionResult> ReceivedFromBarCode(string[] arr)
{
    return View();
}
</code>```

答:
The MVC model binder expects arrays to be passed in the following format: arr=value1&arr=value2&...

You can use map() and join() to create the correct format. But you'll also need to encode the values since they are parameters in a URL. encodeURIComponent can help with that:

```<code>let urlParams = array.map((val) => {
                         return `arr=${encodeURIComponent(val)}`
                     }).join('&');

window.location.href = "@Url.Action("ReceivedFromBarCode","PurchaseOrder")?"
                         + urlParams;
</code>```

And append the urlParams to your URL. Example output in snippet below:

let array = ["value1", "http://example.com?x=1", "

Body:
I have a function that after adding items in a for loop calls the controller through the action URL sending the arr parameter (array), I see that it sends the data but null appears in the controller parameter. I wanted to know what could be wrong?

Javscript Function

function Submit() {
  QRCodeval.forEach((code) => arr.push(code.innerHTML));
  window.location.href = "@Url.Action("ReceivedFromBarCode","PurchaseOrder")?" +arr;
}

Link generated by the controller:

http://localhost:56978/PurchaseOrder/ReceivedFromBarCode?JJJKP,RRPRQ,PPLQR

Controller where I get null in the arr parameter.

public async Task<ActionResult> ReceivedFromBarCode(string[] arr)
{
    return View();
}

Body:
The MVC model binder expects arrays to be passed in the following format: arr=value1&arr=value2&...

You can use map() and join() to create the correct format. But you'll also need to encode the values since they are parameters in a URL. encodeURIComponent can help with that:

let urlParams = array.map((val) => {
                         return `arr=${encodeURIComponent(val)}`
                     }).join('&');

window.location.href = "@Url.Action("ReceivedFromBarCode","PurchaseOrder")?"
                         + urlParams;

And append the urlParams to your URL. Example output in snippet below:

let array = ["value1", "http://example.com?x=1", "<script>alert('')</sctipt>"];

let urlParams = array.map((val) => {
                       return `arr=${encodeURIComponent(val)}`
                     }).join('&');

console.log(urlParams);


来源: stackexchange

问:
Detect browser's language with i18next-browser-languagedetector for reactJs web app
I have a reactJs application and I want to add localization to it. I have never used i18next before but I am trying to get used to it. My problem is, I cannot detect user's browser's in use language. This is my code could you please help me with some code, I have searched all documents and answers for this topic but I could not find any solution.

This is my i18n.js file and I am importing this in files that I want to use

```<code>import i18next from 'i18next';
import languageDetector from 'i18next-browser-languagedetector';
i18next
    .use(languageDetector)
    .init({
        debug: true,
        fallbackLng: "en",
        resources: {
            en: {
                translation: {
                    "table": {
                        "fortuneId": "FortuneId",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "note": "Note",
                        "topic": "Topic",
                        "question": "Question",
                        "gender": "Gender",
                        "rejected": "Rejected"
                    },

                    "auth": {
                        "signIn": "Sign In",
                        "signOut": "Sign Out",
                        "joinUs": "Join Us",
                        "goBack": "Go Back",
                        "email": "E-mail",
                        "username": "Username",
                        "password": "Password",
                    },

                    "admin": {
                        "employee": "Employees",
                        "moderator": "Moderator",
                        "admin": "Admin",
                        "refreshCounters": "Refresh Counters",
                        "refreshCounter": "Refresh Counter",
                        "setAsEmployee": "Set as Employee",
                        "setAsAdmin": "Set as Admin",
                        "setAsModerator": "Set as Moderator",
                        "email": "E-mail",
                        "password": "Password",
                        "answeredFortunes": "Answered Fortunes",
                        "controlledFortunes": "Controlled Fortunes",
                    },

                    "moderator": {
                        "approve": "Approve",
                        "reject": "Reject",
                        "topic": "Topic",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "gender": "Gender",
                        "answer": "Answer"
                    },

                    "answer": {
                        "fortuneId": "FortuneId",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "note": "Note",
                        "topic": "Topic",
                        "question": "Question",
                        "gender": "Gender",
                        "send": "Send",
                        "rejectionReason": "Rejection Reason",
                        "rejection": "Rejection",
                        "rejectedAnswer": "Rejected Answer",
                        "unassign": "Unassign"
                    },

                    "modal": {
                        "fortuneId": "FortuneId",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "note": "Note",
                        "topic": "Topic",
                        "question": "Question",
                        "gender": "Gender",
                        "assignToMe": "Assign to Me",
                        "cancel": "Cancel"
                    },

                    "profile": {
                        "name": "Name",
                        "age": "Age",
                        "email": "E-mail",
                        "answeredFortunes": "Answered Fortunes",
                        "controlledFortunes": "Controlled Fortunes",
                        "employeeTypeAdmin": "Admin",
                        "employeeTypeModerator": "Moderator",
                        "employeeTypeEmployee": "Employee",
                    },

                    "errors": {},
                }
            },
            tr: {
                translation: {
                    "table": {
                        "fortuneId": "FalId",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "note": "Not",
                        "topic": "Konu",
                        "question": "Soru",
                        "gender": "Cinsiyet",
                        "rejected": "Reddedildi"
                    },

                    "auth": {
                        "signIn": "Giriş Yap",
                        "signOut": "Çıkış Yap",
                        "joinUs": "Bize Katıl",
                        "goBack": "Geri Dön",
                        "email": "E-mail",
                        "username": "Kullanıcı Adı",
                        "password": "Şifre",
                    },

                    "admin": {
                        "employee": "Yorumcu",
                        "moderator": "Moderatör",
                        "admin": "Admin",
                        "refreshCounters": "Sayaçları Sıfırla",
                        "refreshCounter": "Sayacı Sıfırla",
                        "setAsEmployee": "Yorumcu Yap",
                        "setAsAdmin": "Admin Yap",
                        "setAsModerator": "Moderatör Yap",
                        "email": "E-mail",
                        "password": "Şifre",
                        "answeredFortunes": "Gönderilen Fallar",
                        "controlledFortunes": "Kontrol Edilen Fallar",
                    },

                    "moderator": {
                        "approve": "Onayla",
                        "reject": "Reddet",
                        "topic": "Konu",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "gender": "Cinsiyet",
                        "answer": "Fal Gönderi"
                    },

                    "answer": {
                        "fortuneId": "FalId",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "note": "Not",
                        "topic": "Konu",
                        "question": "Soru",
                        "gender": "Cinsiyet",
                        "send": "Gönder",
                        "rejectionReason": "Reddedilme Nedeni",
                        "rejection": "Reddedilme",
                        "rejectedAnswer": "Reddedilen Gönder",
                        "unassign": "Fal'ı Bırak"
                    },

                    "modal": {
                        "fortuneId": "FalId",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "note": "Not",
                        "topic": "Konu",
                        "question": "Soru",
                        "gender": "Yaş",
                        "assignToMe": "Bana Ata",
                        "cancel": "İptal"
                    },

                    "profile": {
                        "name": "Ad",
                        "age": "Yaş",
                        "email": "E-mail",
                        "answeredFortunes": "Gönderilen Fallar",
                        "controlledFortunes": "Kontrol Edilen Fallar",
                        "employeeTypeAdmin": "Admin",
                        "employeeTypeModerator": "Moderatör",
                        "employeeTypeEmployee": "Yorumcu",
                    },

                    "errors": {},
                }
            }
        }
    });

export default i18next;
</code>```

In those files I use this like

```<code>   import i18next from "../../Localization/i18n";
   <div>
     {i18next.t('table.question')}
   </div>
</code>```

This shows me "Question" in web page but if I change my google chrome browser to Turkish, it is still in english. I do not know what I am missing.

Thank you for your help

答:
ran into this issue myself, changing my browser's default language does nothing

But everything make sense after I look into the documentation https://github.com/i18next/i18next-browser-languageDetector

```<code>// order and from where user language should be detected
  order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag', 'path', 'subdomain'],
</code>```

The i18next language detector first check queryString, that's why using http://localhost:3000?lng=es work, since it is the first thing it check.

Then next check cookie, then next I check localStorage and found english is stored.

Deleting this value and refresh the page, I see the page is updated to the new language

ContentLicense: CC BY-SA 4.0

Body:
I have a reactJs application and I want to add localization to it. I have never used i18next before but I am trying to get used to it. My problem is, I cannot detect user's browser's in use language. This is my code could you please help me with some code, I have searched all documents and answers for this topic but I could not find any solution.

This is my i18n.js file and I am importing this in files that I want to use

import i18next from 'i18next';
import languageDetector from 'i18next-browser-languagedetector';
i18next
    .use(languageDetector)
    .init({
        debug: true,
        fallbackLng: "en",
        resources: {
            en: {
                translation: {
                    "table": {
                        "fortuneId": "FortuneId",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "note": "Note",
                        "topic": "Topic",
                        "question": "Question",
                        "gender": "Gender",
                        "rejected": "Rejected"
                    },

                    "auth": {
                        "signIn": "Sign In",
                        "signOut": "Sign Out",
                        "joinUs": "Join Us",
                        "goBack": "Go Back",
                        "email": "E-mail",
                        "username": "Username",
                        "password": "Password",
                    },

                    "admin": {
                        "employee": "Employees",
                        "moderator": "Moderator",
                        "admin": "Admin",
                        "refreshCounters": "Refresh Counters",
                        "refreshCounter": "Refresh Counter",
                        "setAsEmployee": "Set as Employee",
                        "setAsAdmin": "Set as Admin",
                        "setAsModerator": "Set as Moderator",
                        "email": "E-mail",
                        "password": "Password",
                        "answeredFortunes": "Answered Fortunes",
                        "controlledFortunes": "Controlled Fortunes",
                    },

                    "moderator": {
                        "approve": "Approve",
                        "reject": "Reject",
                        "topic": "Topic",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "gender": "Gender",
                        "answer": "Answer"
                    },

                    "answer": {
                        "fortuneId": "FortuneId",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "note": "Note",
                        "topic": "Topic",
                        "question": "Question",
                        "gender": "Gender",
                        "send": "Send",
                        "rejectionReason": "Rejection Reason",
                        "rejection": "Rejection",
                        "rejectedAnswer": "Rejected Answer",
                        "unassign": "Unassign"
                    },

                    "modal": {
                        "fortuneId": "FortuneId",
                        "name": "Name",
                        "age": "Age",
                        "date": "Date",
                        "relationship": "Relationship",
                        "note": "Note",
                        "topic": "Topic",
                        "question": "Question",
                        "gender": "Gender",
                        "assignToMe": "Assign to Me",
                        "cancel": "Cancel"
                    },

                    "profile": {
                        "name": "Name",
                        "age": "Age",
                        "email": "E-mail",
                        "answeredFortunes": "Answered Fortunes",
                        "controlledFortunes": "Controlled Fortunes",
                        "employeeTypeAdmin": "Admin",
                        "employeeTypeModerator": "Moderator",
                        "employeeTypeEmployee": "Employee",
                    },

                    "errors": {},
                }
            },
            tr: {
                translation: {
                    "table": {
                        "fortuneId": "FalId",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "note": "Not",
                        "topic": "Konu",
                        "question": "Soru",
                        "gender": "Cinsiyet",
                        "rejected": "Reddedildi"
                    },

                    "auth": {
                        "signIn": "Giriş Yap",
                        "signOut": "Çıkış Yap",
                        "joinUs": "Bize Katıl",
                        "goBack": "Geri Dön",
                        "email": "E-mail",
                        "username": "Kullanıcı Adı",
                        "password": "Şifre",
                    },

                    "admin": {
                        "employee": "Yorumcu",
                        "moderator": "Moderatör",
                        "admin": "Admin",
                        "refreshCounters": "Sayaçları Sıfırla",
                        "refreshCounter": "Sayacı Sıfırla",
                        "setAsEmployee": "Yorumcu Yap",
                        "setAsAdmin": "Admin Yap",
                        "setAsModerator": "Moderatör Yap",
                        "email": "E-mail",
                        "password": "Şifre",
                        "answeredFortunes": "Gönderilen Fallar",
                        "controlledFortunes": "Kontrol Edilen Fallar",
                    },

                    "moderator": {
                        "approve": "Onayla",
                        "reject": "Reddet",
                        "topic": "Konu",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "gender": "Cinsiyet",
                        "answer": "Fal Gönderi"
                    },

                    "answer": {
                        "fortuneId": "FalId",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "note": "Not",
                        "topic": "Konu",
                        "question": "Soru",
                        "gender": "Cinsiyet",
                        "send": "Gönder",
                        "rejectionReason": "Reddedilme Nedeni",
                        "rejection": "Reddedilme",
                        "rejectedAnswer": "Reddedilen Gönder",
                        "unassign": "Fal'ı Bırak"
                    },

                    "modal": {
                        "fortuneId": "FalId",
                        "name": "Ad",
                        "age": "Yaş",
                        "date": "Tarih",
                        "relationship": "İlişki Durumu",
                        "note": "Not",
                        "topic": "Konu",
                        "question": "Soru",
                        "gender": "Yaş",
                        "assignToMe": "Bana Ata",
                        "cancel": "İptal"
                    },

                    "profile": {
                        "name": "Ad",
                        "age": "Yaş",
                        "email": "E-mail",
                        "answeredFortunes": "Gönderilen Fallar",
                        "controlledFortunes": "Kontrol Edilen Fallar",
                        "employeeTypeAdmin": "Admin",
                        "employeeTypeModerator": "Moderatör",
                        "employeeTypeEmployee": "Yorumcu",
                    },

                    "errors": {},
                }
            }
        }
    });

export default i18next;

In those files I use this like

   import i18next from "../../Localization/i18n";

     {i18next.t('table.question')}

This shows me "Question" in web page but if I change my google chrome browser to Turkish, it is still in english. I do not know what I am missing.

Thank you for your help

Body:
ran into this issue myself, changing my browser's default language does nothing

But everything make sense after I look into the documentation https://github.com/i18next/i18next-browser-languageDetector

// order and from where user language should be detected
  order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag', 'path', 'subdomain'],

The i18next language detector first check queryString, that's why using http://localhost:3000?lng=es work, since it is the first thing it check.

Then next check cookie, then next I check localStorage and found english is stored.

Deleting this value and refresh the page, I see the page is updated to the new language


问:
"TypeError: Assinging value to read-only", but only happens on AOT
I have a relatively old project of mine, originally made in Angular 7, I recently got motivated, updated it to 13, and I was able to make everything work... At least while developing. (I had actually upgraded it to Angular 10 about half a year ago, but I only developed on it, never really tried to compile at that time)

So, with ng serve, the project runs fine and everything works well, so I now needed to compile it to push it all to my server together with the API, and after some fixes here and there, it compiled, and I was able to see the screen and everything! However, I'm getting this console error:

```<code>ERROR TypeError: "count_categories" is read-only
    Dictionary dictionary.ts:8
    set dictionaries.service.ts:34
    getAll dictionaries.service.ts:84
    (..)
</code>```

Well, it also shows the line and everything but... I have no idea how could I fix it? I also found out that this problem seems to be attributed to "Strict Mode", I tried to disable it in many ways, but nothing worked (hence, I have here).

Here is what is happening, a reminder, this code runs fine on serve, but crashes on AOT:

```<code>export class Dictionary {
  public constructor(init?: any) {
    Object.assign(this, init); // The error is here
  }
  id: number;
  name: string;
  language: string;
  dateCreated: Date;
  dateRevision: Date;
  @Optional() changes: boolean;
  @Optional() novel: Novel[];
  // tslint:disable-next-line: variable-name
  @Optional() count_categories: [{count: number}];

  countCategories(): number {
    if (this.count_categories[0]) {
      return this.count_categories[0].count;
    }
    return 0;
  }
}
</code>```

https://github.com/ssj4maiko/mtltools/blob/master/resources/frontend/src/app/_models/dictionary.ts

The value of init comes from an API:

    {
        "id": 1,
        "name": "asd",
        "language": "English",
        "dateCreated": "2019-05-28T01:29:13.000000Z",
        "dateRevision": "2022-01-14T17:56:34.000000Z",
        "count_categories": [
            {
                "idDictionary": 1,
                "count": 14
            }
        ]
    }
```

So, clearly the error comes from Object.assign assigning a value into the optional "count_categories" array of objects, and it works during serving, but on AOT, I get the "read-only" thing error in every screen this API is called... And it should not be read-only, since I do modify this value on the fly.

So, I tried disabling Strict Mode, but didn't work (Maybe I did it wrong), and the variable is not supposed to be on read-only mode.

So I ask for a solution, be it a way to really disable this checking? Or maybe a way to assign the values in a different manner to avoid the problem? Or maybe something that I couldn't think of?

Angular is not my specialty, and it had been a long time since I last saw it, but I do program for life, what I mean is that I'm not aware of all the tricks available here, but I should be able to understand whatever is needed.

答:
Well, so while continuing, although I know that it was fully working when I was using serve, and while I was trying to compile, when I trying serving it again, the problem was replicated, meaning, it also stopped working that way.

At first I thought it could be related to having to assign values onto an object, so I changed the API to give me straight away the sole number I needed (count), and it was still bad. The moment I removed @Optional it worked though...

I went to check and, for my needs, I just confirmed that all calls for this should return the value, meaning, the originally optional value is kinda always there, although this shouldn't be proper, it works on practice. I would still like to learn of a better way to understand better these and a way to deal with such "limitations".

Well, in regards to the parts I thought it would increase and decrease, it seems I forgot to add that on this upgrade, so it's also not affecting me right now, but I already have something in mind to make things a bit more dynamic at least.

Body:
I have a relatively old project of mine, originally made in Angular 7, I recently got motivated, updated it to 13, and I was able to make everything work... At least while developing. (I had actually upgraded it to Angular 10 about half a year ago, but I only developed on it, never really tried to compile at that time)

So, with ng serve, the project runs fine and everything works well, so I now needed to compile it to push it all to my server together with the API, and after some fixes here and there, it compiled, and I was able to see the screen and everything! However, I'm getting this console error:

ERROR TypeError: "count_categories" is read-only
    Dictionary dictionary.ts:8
    set dictionaries.service.ts:34
    getAll dictionaries.service.ts:84
    (..)

Well, it also shows the line and everything but... I have no idea how could I fix it? I also found out that this problem seems to be attributed to "Strict Mode", I tried to disable it in many ways, but nothing worked (hence, I have here).

Here is what is happening, a reminder, this code runs fine on serve, but crashes on AOT:

export class Dictionary {
  public constructor(init?: any) {
    Object.assign(this, init); // The error is here
  }
  id: number;
  name: string;
  language: string;
  dateCreated: Date;
  dateRevision: Date;
  @Optional() changes: boolean;
  @Optional() novel: Novel[];
  // tslint:disable-next-line: variable-name
  @Optional() count_categories: [{count: number}];

  countCategories(): number {
    if (this.count_categories[0]) {
      return this.count_categories[0].count;
    }
    return 0;
  }
}

https://github.com/ssj4maiko/mtltools/blob/master/resources/frontend/src/app/_models/dictionary.ts

The value of init comes from an API:

    {
        "id": 1,
        "name": "asd",
        "language": "English",
        "dateCreated": "2019-05-28T01:29:13.000000Z",
        "dateRevision": "2022-01-14T17:56:34.000000Z",
        "count_categories": [
            {
                "idDictionary": 1,
                "count": 14
            }
        ]
    }

So, clearly the error comes from Object.assign assigning a value into the optional "count_categories" array of objects, and it works during serving, but on AOT, I get the "read-only" thing error in every screen this API is called... And it should not be read-only, since I do modify this value on the fly.

So, I tried disabling Strict Mode, but didn't work (Maybe I did it wrong), and the variable is not supposed to be on read-only mode.

So I ask for a solution, be it a way to really disable this checking? Or maybe a way to assign the values in a different manner to avoid the problem? Or maybe something that I couldn't think of?

Angular is not my specialty, and it had been a long time since I last saw it, but I do program for life, what I mean is that I'm not aware of all the tricks available here, but I should be able to understand whatever is needed.


问:
tf.data.Dataset - delete cache?
Is it possible to delete the in-memory cache that's built after calling tf.data.Dataset.cache()?

Here's what I'd like to do. The augmentation for the dataset is very costly, so the current code is more or less:

data = tf.data.Dataset(...) \
       .map(<expensive_augmentation>) \
       .cache() \
       # .shuffle().batch() etc.
```

However, this means that every iteration over data will see the same augmented versions of the data samples. What I'd like to do instead is to use the cache for a couple of epochs and then start over, or equivalently do something like Dataset.map(<augmentation>).fleeting_cache().repeat(8). Is this possible to achieve?

答:
The cache lifecycle is tied to the dataset, so you can achieve this by re-creating the dataset:

def create_dataset():
  dataset = tf.data.Dataset(...)
  dataset = dataset.map(<expensive_augmentation>)
  dataset = dataset.shuffle(...)
  dataset = dataset.batch(...)
  return dataset

for epoch in range(num_epochs):
  # Drop the cache every 8 epochs.
  if epoch % 8 == 0: dataset = create_dataset()
  for batch in dataset:
    train(batch)
```

Title: tf.data.Dataset - delete cache?

Body:
Is it possible to delete the in-memory cache that's built after calling tf.data.Dataset.cache()?

Here's what I'd like to do. The augmentation for the dataset is very costly, so the current code is more or less:

data = tf.data.Dataset(...) \
       .map(<expensive_augmentation>) \
       .cache() \
       # .shuffle().batch() etc.

However, this means that every iteration over data will see the same augmented versions of the data samples. What I'd like to do instead is to use the cache for a couple of epochs and then start over, or equivalently do something like Dataset.map(<augmentation>).fleeting_cache().repeat(8). Is this possible to achieve?


问:
Could not find a declaration file for module '@editorjs/image'
I am using editorjs in my project and there are no typescript files in my project.
Could not find a declaration file for module '@editorjs/image'. 'node_modules/@editorjs/image/dist/bundle.js' implicitly has an 'any' type.
Try npm i --save-dev @types/editorjs__image if it exists or add a new declaration (.d.ts) file containing declare module '@editorjs/image';ts(7016)
No quick fixes are available. The typescript package is not available and when I am creating .d.ts file in the project
declare module "@editorjs/image"
but it is not referring to the editorjs/image package for the usage.

答:
The problem is that the .d.ts file you've created in the project should also be listed as a part of your project in your tsconfig.json:

  "include": [
    "**/*.ts",
    "**/*.tsx",
    "global.d.ts" // << specify your file here
  ],
```


问:
Why is my csv file not printing after I import it?
```<code>import pandas as pd
tbl1 = pd.import_csv('sample_prices.csv')
tbl1.print()
</code>```

and still not receiving anything? It does not even come up with an error.

答:
The code might be written this way.</p>
```<code>import pandas as pd
tbl1 = pd.read_csv('sample_prices.csv')
print(tbl1)
</code>```

Body:
import pandas as pd
tbl1 = pd.import_csv('sample_prices.csv')
tbl1.print()

and still not receiving anything? It does not even come up with an error.

Body:
The code might be written this way.

import pandas as pd
tbl1 = pd.read_csv('sample_prices.csv')
print(tbl1)


问:
Unity3d integration with android
I need to create an android application which consists of parts written on Unity3d (animation and so on) and on AndroidSDK (by androidSDK I mean few activities written in java, manifest and resources)

In fact I already have those parts (At least mocks are ready=)) And I can't figure out how to communicate between them.

I've read a lot of articles about unity3d android integration (mostly about things called "plugins") and failed to understand how this staff works=( The main thing I understood (everyone exept official refs wrote about that) is that documentation about plugins is very poor... =)

The only way to communicate which I can understand is to make an intent (broadcast) from unity3d script (using AndroidJavaClass and AndroidJavaObject) so my activity (written in java) can handle it. But something tells me it's not the best solution...

What I read about the problem is that I need to use JNI (which is java native interface - WHY?!? - why do I need to use native code?)

Do I need to create some middle-level code on java which purpose is to communicate with my java activity, compile it using AndroidNDK and include into my Unity3d project as a plugin? How can I write that middle layer than? Do I need to use UnityPlayer instead of "Activity" as a base class and why?

答:
the unity3D in 2020 isn't needed android SDK at all nowadays.
you can just click
file -> building setting -> switch platform -> build.

and you can create your android app.

ContentLicense: CC BY-SA 3.0

Title: Unity3d integration with android


问:
Why does the second argument of trigger arrive as an object?
Nevermind, I found out the answer. It is because the first argument of the incScore function is the event, while the second event is the actual passed in argument.

I am trying to increase the score attribute of a Quiz object, but I am having some difficulty. I am using a global trigger event to increase the score after the user correctly answers a question:

```<code>global.trigger('incScore', 300);
</code>```

Here is the incScore function:

```<code>incScore: function(change) {
  alert(JSON.stringify(change));
  this.set({
    score: this.get("score") + change
  });
},
</code>```

I want to increase the score by 300 points, so I send 300 as the second argument of the trigger method. I thought it would pass 300 into the incScore function, but it passes in some sort of object. I am printing out the object's contents, and it is all sorts of garbage. How do I access the 300 that should've been passed into the function?

答:
First you should observe incScore event

```<code>initialize: function() {
    global.bind('incScore', _.bind(this.incScore, this));
},
incScore: function(event, score) {
    console.log(score)
}
</code>```

if you triggering jquery event first argument will be event object and starting from second argument there will be your data.
Link to jquery api

Body:
Nevermind, I found out the answer. It is because the first argument of the incScore function is the event, while the second event is the actual passed in argument.

I am trying to increase the score attribute of a Quiz object, but I am having some difficulty. I am using a global trigger event to increase the score after the user correctly answers a question:

global.trigger('incScore', 300);

Here is the incScore function:

incScore: function(change) {
  alert(JSON.stringify(change));
  this.set({
    score: this.get("score") + change
  });
},

I want to increase the score by 300 points, so I send 300 as the second argument of the trigger method. I thought it would pass 300 into the incScore function, but it passes in some sort of object. I am printing out the object's contents, and it is all sorts of garbage. How do I access the 300 that should've been passed into the function?

Body:
First you should observe incScore event

initialize: function() {
    global.bind('incScore', _.bind(this.incScore, this));
},
incScore: function(event, score) {
    console.log(score)
}

if you triggering jquery event first argument will be event object and starting from second argument there will be your data.
Link to jquery api


问:
Shiny modal that is dependent on fileInput() in shiny app
I have created a modal that is activated when the app is launched and warns the user that he first  needs to upload an excel file. But when I upload it the modal is displayed again which seems to be wrong.</p>
```<code>library(shiny)
library(shinyalert)

ui <- fluidPage(
  useShinyalert(),  # Set up shinyalert
  fileInput('file1', 'Choose xls file',
            accept = c(".xls")
  )
)

server <- function(input, output, session) {
  observeEvent(is.null(input$file1), {
    # Show a modal when the button is pressed
    shinyalert("Oops!", "Something went wrong.", type = "error")
  })
}

shinyApp(ui, server)
</code>```

答:
Perhaps you can try with an if condition.</p>
```<code>observeEvent(input$file1, {
    if (is.null(input$file1))
    # Show a modal when the button is pressed
    shinyalert("Oops!", "Something went wrong.", type = "error")
  }, ignoreNULL = FALSE)
</code>```

Body:
I have created a modal that is activated when the app is launched and warns the user that he first  needs to upload an excel file. But when I upload it the modal is displayed again which seems to be wrong.

library(shiny)
library(shinyalert)

ui <- fluidPage(
  useShinyalert(),  # Set up shinyalert
  fileInput('file1', 'Choose xls file',
            accept = c(".xls")
  )
)

server <- function(input, output, session) {
  observeEvent(is.null(input$file1), {
    # Show a modal when the button is pressed
    shinyalert("Oops!", "Something went wrong.", type = "error")
  })
}

shinyApp(ui, server)

Body:
Perhaps you can try with an if condition.

observeEvent(input$file1, {
    if (is.null(input$file1))
    # Show a modal when the button is pressed
    shinyalert("Oops!", "Something went wrong.", type = "error")
  }, ignoreNULL = FALSE)


答:
It should be writed like this</p>
```<code>import pandas as pd

tbl1 = pd.read_csv('sample_prices.csv')
print(tbl1)
</code>```

Title: Why is my csv file not printing after I import it?

Body:
It should be writed like this

import pandas as pd

tbl1 = pd.read_csv('sample_prices.csv')
print(tbl1)


问:
Java: Subtract '0' from char to get an int... why does this work?
This works fine:

```<code>int foo = bar.charAt(1) - '0';
</code>```

Yet this doesn't - because bar.charAt(x) returns a char:

```<code>int foo = bar.charAt(1);
</code>```

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?

答:
'5' has the int value of 53

if we write '5'-'0' it evaluates to 53-48, or the int 5

if we write char c = 'B'+32; then c stores 'b'

'b' = 98.

Please refer ASCII chart
https://en.cppreference.com/w/cpp/language/ascii

ContentLicense: CC BY-SA 2.5

Body:
This works fine:

int foo = bar.charAt(1) - '0';

Yet this doesn't - because bar.charAt(x) returns a char:

int foo = bar.charAt(1);

It seems that subtracting '0' from the char is casting it to an integer.

Why, or how,  does subtracting the string '0' (or is it a char?) convert another char in to an integer?


问:
Implicit conversion between types in C#
I have the following business objects:

```<code>    public abstract class Product
    {
        public int Id { get; set; }
        public bool OnStock { get; set; }
    }

    public class ProductForImport : Product
    {
        public int ImportId { get; set; }
    }

    public class ProductForExport : Product
    {
        public int ExportId { get; set; }
        public bool IsExportable { get; set; }
        public bool IsUsable { get; set; }
        public string OtherParam {get; set;}

        public static implicit operator ProductForExport(ProductForImport pfi)
        {
            ProductForExport p = new ProductForExport();
            p.Id = pfi.Id;
            p.IsExportable = true;
            p.ExportId = 0;
            return p;
        }
    }
</code>```

so I can convert between the two types:

```<code>    static void Main(string[] args)
    {
        ProductForExport pfe = new ProductForExport();
        pfe.Id = 1;
        pfe.OnStock = true;

        ProductForImport pfi = new ProductForImport();
        pfi.ImportId = 200;

        ProductForExport pfe2 = (ProductForExport)pfi;
    }
</code>```

this works OK.

I have 100.000 ProductsForImport items.
If I understand correctly, if I convert them to ProductsForExport items, I'll have 100.000 +100.000 items in memory - that's reasonable.

My problem is: I have to send these "ProductForExport" objects through JSON services, each service just need some subset of the properties of each type:

servicecall1 should return ProductForExport1{ExportId,IsExportable}

servicecall2 should return ProductForExport2{ExportId,IsUsable}

Question: should I write an implicit conversion similar to the above example for these new types - ProductForExport1 and ProductForExport2 (so basically create 100.000+100.000 new objects)

or

somehow can I just "hide" the unwanted properties with some magic from the original type without the need to create new instances?

thanks,

b.

答:
It took me a few reads but I don't think your problem is about implicit conversion as much as how to send data via json right?

If you have your object collections of Import or Export object you can use the JavaScriptSerilizer and some anonymous types to slice and dice what data you send.

You can use Linq to select specific properties of your object in a collection, and define an anonymous type "on-the-fly" to serialize out as a json string like this:

```<code>List<ProductForExport> exportList; //the list to export
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = string.Empty;

output = jss.Serialize(new
    {
        isExportable = True,                //static named properties
        iTotalProducts = exportList.Count,  //dynamic values
        productDataArray = exportList       //all data in an array object
    });

//Or build the result using just a few properties of the collection:

foreach (ExportProduct exProd in exportList)
{
    output += jss.Serialize(new
    {
        exProd.IsExportable,
        exProd.ExportID
    });
}
</code>```

Title: Implicit conversion between types in C#

Body:
I have the following business objects:

    public abstract class Product
    {
        public int Id { get; set; }
        public bool OnStock { get; set; }
    }

    public class ProductForImport : Product
    {
        public int ImportId { get; set; }
    }

    public class ProductForExport : Product
    {
        public int ExportId { get; set; }
        public bool IsExportable { get; set; }
        public bool IsUsable { get; set; }
        public string OtherParam {get; set;}

        public static implicit operator ProductForExport(ProductForImport pfi)
        {
            ProductForExport p = new ProductForExport();
            p.Id = pfi.Id;
            p.IsExportable = true;
            p.ExportId = 0;
            return p;
        }
    }

so I can convert between the two types:

    static void Main(string[] args)
    {
        ProductForExport pfe = new ProductForExport();
        pfe.Id = 1;
        pfe.OnStock = true;

        ProductForImport pfi = new ProductForImport();
        pfi.ImportId = 200;

        ProductForExport pfe2 = (ProductForExport)pfi;
    }

this works OK.

I have 100.000 ProductsForImport items.
If I understand correctly, if I convert them to ProductsForExport items, I'll have 100.000 +100.000 items in memory - that's reasonable.

My problem is: I have to send these "ProductForExport" objects through JSON services, each service just need some subset of the properties of each type:

servicecall1 should return ProductForExport1{ExportId,IsExportable}

servicecall2 should return ProductForExport2{ExportId,IsUsable}

Question: should I write an implicit conversion similar to the above example for these new types - ProductForExport1 and ProductForExport2 (so basically create 100.000+100.000 new objects)

or

somehow can I just "hide" the unwanted properties with some magic from the original type without the need to create new instances?

thanks,

b.

Body:
It took me a few reads but I don't think your problem is about implicit conversion as much as how to send data via json right?

If you have your object collections of Import or Export object you can use the JavaScriptSerilizer and some anonymous types to slice and dice what data you send.

You can use Linq to select specific properties of your object in a collection, and define an anonymous type "on-the-fly" to serialize out as a json string like this:

List<ProductForExport> exportList; //the list to export
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = string.Empty;

output = jss.Serialize(new
    {
        isExportable = True,                //static named properties
        iTotalProducts = exportList.Count,  //dynamic values
        productDataArray = exportList       //all data in an array object
    });

//Or build the result using just a few properties of the collection:

foreach (ExportProduct exProd in exportList)
{
    output += jss.Serialize(new
    {
        exProd.IsExportable,
        exProd.ExportID
    });
}


问:
How to schedule a BigQuery run through Apps Script
I have a connected sheet that has results of a bigquery query(extract sheet). I created a preview of the results sheet. How do i write an appscript fuction to refresh the results in the extract and preview sheets? Please help.

I tried to use this code to refresh the connected sheet query , but it gave me an error saying : "Exception: The data object does not exist." I would like to write an apps script function if possible.

```<code>function refresh() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('test'), true);
  SpreadsheetApp.enableAllDataSourcesExecution();
  spreadsheet.getCurrentCell().getDataSourceTables()[0].refreshData();
  //DriveApp.getFiles()
};
</code>```

答:
The solution, a macro

1. Record a macro to refresh your data

Open the spreadsheet that contains data connected to BigQuery in Google Sheets.

Record a macro from a different tab then the one you want to refresh.

After you start recording, switch to the tab you want to refresh.

At the bottom left, click Refresh.

Click Save.

2. Schedule your macro

At the top, click Tools > Script editor.

At the top, click Edit > Current project’s triggers.

At the bottom right, click Add trigger and select your options.

Click Save.

Body:
I have a connected sheet that has results of a bigquery query(extract sheet). I created a preview of the results sheet. How do i write an appscript fuction to refresh the results in the extract and preview sheets? Please help.

I tried to use this code to refresh the connected sheet query , but it gave me an error saying : "Exception: The data object does not exist." I would like to write an apps script function if possible.

function refresh() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('A1').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('test'), true);
  SpreadsheetApp.enableAllDataSourcesExecution();
  spreadsheet.getCurrentCell().getDataSourceTables()[0].refreshData();
  //DriveApp.getFiles()
};


问:
Should a <Route> be wrapped in a <Routes>?
After my React code compiles, I'm getting an error that says the following:

Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

Here is my code:

```<code>import { Route } from "react-router-dom";
import AllMeetupsPage from "./pages/AllMeetups";
import NewMeetupsPage from "./pages/NewMeetups";
import FavoritesPage from "./pages/Favorites";

function App() {

  return (
    <div>
      <Route path="/">
        <AllMeetupsPage />
      </Route>
      <Route path="/new-meetups">
        <NewMeetupsPage />
      </Route>
      <Route path="/favorites">
        <FavoritesPage />
      </Route>
    </div>
  );
}

export default App;
</code>```

What am I doing wrong?

答:
I was also coming across the same issue and I think I was following the same tutorial as you here: https://www.youtube.com/watch?v=Dorf8i6lCuk

I read the documentation listed above at https://reactrouter.com/docs/en/v6/getting-started/overview and it looks like they have reworked some of the structure on this.

The following code worked well for me by wrapping the items in <Routes> (since we already have <BrowserRouter> in our index.js file and adding in the element tag.

```<code>import { Routes, Route } from "react-router-dom"; // Changed to add Routes and BrowserRouter - Same with index.js page
import AllMeetupsPage from "./pages/AllMeetups";
import NewMeetupsPage from "./pages/NewMeetups";
import FavoritesPage from "./pages/Favorites";

function App() {

  return (
    <div>
      <Routes>
        <Route path='/' element={<AllMeetupsPage />} />
        <Route path='/new-meetups' element={<NewMeetupsPage />} />
        <Route path='/favourites' element={<FavoritesPage />} />
      </Routes>
    </div>
  );
}

export default App;
</code>```

Body:
After my React code compiles, I'm getting an error that says the following:

Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.

Here is my code:

import { Route } from "react-router-dom";
import AllMeetupsPage from "./pages/AllMeetups";
import NewMeetupsPage from "./pages/NewMeetups";
import FavoritesPage from "./pages/Favorites";

function App() {

  return (

      <Route path="/">
        <AllMeetupsPage />
      </Route>
      <Route path="/new-meetups">
        <NewMeetupsPage />
      </Route>
      <Route path="/favorites">
        <FavoritesPage />
      </Route>

  );
}

export default App;

What am I doing wrong?

Body:
I was also coming across the same issue and I think I was following the same tutorial as you here: https://www.youtube.com/watch?v=Dorf8i6lCuk

I read the documentation listed above at https://reactrouter.com/docs/en/v6/getting-started/overview and it looks like they have reworked some of the structure on this.

The following code worked well for me by wrapping the items in <Routes> (since we already have <BrowserRouter> in our index.js file and adding in the element tag.

import { Routes, Route } from "react-router-dom"; // Changed to add Routes and BrowserRouter - Same with index.js page
import AllMeetupsPage from "./pages/AllMeetups";
import NewMeetupsPage from "./pages/NewMeetups";
import FavoritesPage from "./pages/Favorites";

function App() {

  return (
    <div>
      <Routes>
        <Route path='/' element={<AllMeetupsPage />} />
        <Route path='/new-meetups' element={<NewMeetupsPage />} />
        <Route path='/favourites' element={<FavoritesPage />} />
      </Routes>
    </div>
  );
}

export default App;


问:
How to make a stored procedure in which the parameters are a list of strings [ SQL Server, ASP.NET Core 3.1 ]
I am creating a website where users can filter the data by brand, storage, price, etc. I want to use a stored procedure to get the data. The problem is that I don't know how to make a stored procedure that accepts a list of strings as parameters.

For example, this is my ASP.NET Core controller:

```<code>    private readonly contextItem _context;

    public ItemsController(contextItem context)
    {
        _context = context;
    }

    // GET: api/Items
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Item>>> GetItem(
        string samsung, string iphone, string lg, string _32gb, string _64gb,string _128gb,
        string max, string min)
    {
        List<string> brands = new List<string>(), storage = new List<string>();
        string price_min = null, price_max = null;

        // brands
        if (samsung != null) { brands.Add("samsung"); }
        if (iphone != null) { brands.Add("iphone"); }
        if (lg != null) { brands.Add("lg"); }

        // storage
        if (_32gb != null) { storage.Add("32gb"); }
        if (_64gb != null) { storage.Add("64gb"); }
        if (_128gb != null) { storage.Add("128gb"); }

        // price
        price_max = max != null ? max : "";
        price_min = min != null ? min : "";

        string query = $"EXEC SP_Filter @brand ='{string.Join(",", brands)}',@storage='{string.Join(",", storage)}'," +
            $"@min='{price_min}',@max='{price_max}'";

        return await _context.Item.FromSqlRaw(query).ToListAsync();
    }
</code>```

So the parameters can be more than one, but if they weren't, it would be easy to make a stored procedure like this

```<code>create procedure SP_Filter
    @brands varchar(250),
    @storage varchar(250),
    @min decimal,
    @max decimal
as
    Select *
    From Item
    Where NAME like '%'+@brands+'%'
      and NAME like '%'+@storage+'%'
      and PRICE between @min and @max
</code>```

答:
You can use json or xml. Try this</p>
```<code>/* test

DECLARE @Brands nvarchar(4000) SET @Brands = '{"Brands": [{"Brand": "Samsung"}, {"Brand": "iPhone"}, {"Brand": "LG"}, {"Brand": "Xiaomi"}]}';;

DECLARE @Storages nvarchar(4000) SET @Storages = '{"Storages": [{"Storage": "16"}, {"Storage": "32"}, {"Storage": "64"}, {"Storage": "128"}]}';;

SELECT * FROM OPENJSON(@Brands, '$.Brands') WITH ( Brand varchar(20) '$.Brand' );
SELECT * FROM OPENJSON(@Storages, '$.Storages') WITH ( Storage varchar(20) '$.Storage' );

*/

        create procedure FilterByBrandStoragePrice
            @Brands             nvarchar(4000),
            @Storages           nvarchar(4000),
            @min                decimal,
            @max                decimal
        as
            SELECT *
            FROM Item i
            WHERE i.Brand in (SELECT * FROM OPENJSON(@Brands, '$.Brands') WITH ( Brand varchar(20) '$.Brand' ))
            AND i.Storage in  (SELECT * FROM OPENJSON(@Storages, '$.Storages') WITH ( Storage varchar(20) '$.Storage' ))
              AND i.PRICE between @min and @max

</code>```

Body:
I am creating a website where users can filter the data by brand, storage, price, etc. I want to use a stored procedure to get the data. The problem is that I don't know how to make a stored procedure that accepts a list of strings as parameters.

For example, this is my ASP.NET Core controller:

    private readonly contextItem _context;

    public ItemsController(contextItem context)
    {
        _context = context;
    }

    // GET: api/Items
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Item>>> GetItem(
        string samsung, string iphone, string lg, string _32gb, string _64gb,string _128gb,
        string max, string min)
    {
        List<string> brands = new List<string>(), storage = new List<string>();
        string price_min = null, price_max = null;

        // brands
        if (samsung != null) { brands.Add("samsung"); }
        if (iphone != null) { brands.Add("iphone"); }
        if (lg != null) { brands.Add("lg"); }

        // storage
        if (_32gb != null) { storage.Add("32gb"); }
        if (_64gb != null) { storage.Add("64gb"); }
        if (_128gb != null) { storage.Add("128gb"); }

        // price
        price_max = max != null ? max : "";
        price_min = min != null ? min : "";

        string query = $"EXEC SP_Filter @brand ='{string.Join(",", brands)}',@storage='{string.Join(",", storage)}'," +
            $"@min='{price_min}',@max='{price_max}'";

        return await _context.Item.FromSqlRaw(query).ToListAsync();
    }

So the parameters can be more than one, but if they weren't, it would be easy to make a stored procedure like this

create procedure SP_Filter
    @brands varchar(250),
    @storage varchar(250),
    @min decimal,
    @max decimal
as
    Select *
    From Item
    Where NAME like '%'+@brands+'%'
      and NAME like '%'+@storage+'%'
      and PRICE between @min and @max

Body:
You can use json or xml. Try this

/* test

DECLARE @Brands nvarchar(4000) SET @Brands = '{"Brands": [{"Brand": "Samsung"}, {"Brand": "iPhone"}, {"Brand": "LG"}, {"Brand": "Xiaomi"}]}';;

DECLARE @Storages nvarchar(4000) SET @Storages = '{"Storages": [{"Storage": "16"}, {"Storage": "32"}, {"Storage": "64"}, {"Storage": "128"}]}';;

SELECT * FROM OPENJSON(@Brands, '$.Brands') WITH ( Brand varchar(20) '$.Brand' );
SELECT * FROM OPENJSON(@Storages, '$.Storages') WITH ( Storage varchar(20) '$.Storage' );

*/

        create procedure FilterByBrandStoragePrice
            @Brands             nvarchar(4000),
            @Storages           nvarchar(4000),
            @min                decimal,
            @max                decimal
        as
            SELECT *
            FROM Item i
            WHERE i.Brand in (SELECT * FROM OPENJSON(@Brands, '$.Brands') WITH ( Brand varchar(20) '$.Brand' ))
            AND i.Storage in  (SELECT * FROM OPENJSON(@Storages, '$.Storages') WITH ( Storage varchar(20) '$.Storage' ))
              AND i.PRICE between @min and @max


问:
StackExchange.Redis: No connection is available to service this operation: SET
I created a Console Application running on .NET Core 1.1 and I'm referencing the StackExchange.Redis NuGet package, version 1.2.3

When running the code below, I get the following error:

It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING

```<code>using StackExchange.Redis;
using System;

namespace RedisConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase db = redis.GetDatabase();
            db.StringSet(BitConverter.GetBytes(5), "asdf");
        }
    }
}
</code>```

If I change the Connect string to "localhost,abortConnect=false", then I get this error message:

No connection is available to service this operation: SET \u0005\0\0\0; SocketFailure on localhost:6379/Subscription, origin: Error, input-buffer: 0, outstanding: 0, last-read: 1s ago, last-write: 1s ago, unanswered-write: 27780s ago, keep-alive: 60s, pending: 0, state: Connecting, last-heartbeat: never, last-mbeat: -1s ago, global: 20s ago

I followed the Basics guide to get started using this library but I keep getting the errors above.

Am I missing some code or configuration?

答: Try adding ssl=True,abortConnect=False,sslprotocols=tls12 under your connection string

Body:
I created a Console Application running on .NET Core 1.1 and I'm referencing the StackExchange.Redis NuGet package, version 1.2.3

When running the code below, I get the following error:

It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail. SocketFailure on PING

using StackExchange.Redis;
using System;

namespace RedisConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
            IDatabase db = redis.GetDatabase();
            db.StringSet(BitConverter.GetBytes(5), "asdf");
        }
    }
}

If I change the Connect string to "localhost,abortConnect=false", then I get this error message:

No connection is available to service this operation: SET \u0005\0\0\0; SocketFailure on localhost:6379/Subscription, origin: Error, input-buffer: 0, outstanding: 0, last-read: 1s ago, last-write: 1s ago, unanswered-write: 27780s ago, keep-alive: 60s, pending: 0, state: Connecting, last-heartbeat: never, last-mbeat: -1s ago, global: 20s ago

I followed the Basics guide to get started using this library but I keep getting the errors above.

Am I missing some code or configuration?


问:
How to use variables in dot notation like square bracket notation
I have been using square bracket notation in Javascript to create and call associative arrays.

In this example, I understand that square bracket notation allows you to use a variable to call a certain object in the array.

How would you do something like this in dot notation?

```<code>var item = {};
    item['1'] = 'pen';

var x = 1;

console.log(item[x]);  // console will show 'pen'
</code>```

答:
If you use numbers to access an array you have to use the brackets:

```<code>item[0]

var k = 0;
item[k]
</code>```

as

```<code>item.0
</code>```

doesn't work (wrong syntax).

If you use a string

```<code>item["key"]

var p = "key";
item[p]
</code>```

equals

```<code>item.key
</code>```

In the latter context

```<code>var p = "key";
item.p
</code>```

would cause a wrong output as p is not treated as a variable here.

Body:
I have been using square bracket notation in Javascript to create and call associative arrays.

In this example, I understand that square bracket notation allows you to use a variable to call a certain object in the array.

How would you do something like this in dot notation?

var item = {};
    item['1'] = 'pen';

var x = 1;

console.log(item[x]);  // console will show 'pen'

Body:
If you use numbers to access an array you have to use the brackets:

item[0]

var k = 0;
item[k]

as

item.0

doesn't work (wrong syntax).

If you use a string

item["key"]

var p = "key";
item[p]

equals

item.key

In the latter context

var p = "key";
item.p

would cause a wrong output as p is not treated as a variable here.


问:
Execution failed for task ':app:compileDebugKotlin'. error in Flutter after upgrading to 2.10 version
I upgraded my flutter version to 2.10 and it is giving me this errror while compiling -

```<code>Launching lib\main.dart on sdk gphone64 x86 64 in debug mode...
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/518a28e11257a17211a8fb8a5067b186/jetified-kotlinx-coroutines-core-jvm-1.5.2.jar!/META-INF/kotlinx-coroutines-core.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/6168eafaded8ddacbc73df91bd758ffe/jetified-window-1.0.0-beta04-api.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/6c0671fbb7722afc42898b4178b11de7/jetified-kotlinx-coroutines-android-1.5.2.jar!/META-INF/kotlinx-coroutines-android.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/91667e970d35cee0f38e121291f325a1/jetified-kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/af48bf569b5523ddd7a06285f676a1ca/jetified-kotlin-stdlib-jdk7-1.5.30.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/b560d76b568ab2e29107d94002f1a070/jetified-kotlin-stdlib-1.5.31.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/d0224631d7841d16cd3b5d2fab11c793/jetified-kotlin-stdlib-jdk8-1.5.30.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/e0583c70716c2ce3cdb07beee79fcae0/jetified-window-java-1.0.0-beta04-api.jar!/META-INF/window-java_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 14s
┌─ Flutter Fix ───────────────────────────────────────────────────────────────────────────────────┐
│ [!] Your project requires a newer version of the Kotlin Gradle plugin.                          │
│ Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then    │
│ update                                                                                │
│ C:\Users\Hp\Desktop\Programming\Flutter\flutter_application_notifications\android\build.gradle: │
│ ext.kotlin_version = '<latest-version>'                                                         │
└─────────────────────────────────────────────────────────────────────────────────────────────────┘
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)
</code>```

And I am being honest here, I never have experienced bug free upgradation in Flutter till now, except when they made little changes. Literally. Can someone tell me why is this happening and please give a solution for the above error.

答:
You have to change the ext.kotlin_version in your_flutter_app\android\build.gradle

From

ext.kotlin_version = 'old version'

to

ext.kotlin_version = '1.6.10'

which is the last version.

and you can always see the last version of ext.kotlin_version from the link

```<code>https://kotlinlang.org/docs/gradle.html#plugin-and-versions
</code>```

Body:
I upgraded my flutter version to 2.10 and it is giving me this errror while compiling -

Launching lib\main.dart on sdk gphone64 x86 64 in debug mode...
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/518a28e11257a17211a8fb8a5067b186/jetified-kotlinx-coroutines-core-jvm-1.5.2.jar!/META-INF/kotlinx-coroutines-core.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/6168eafaded8ddacbc73df91bd758ffe/jetified-window-1.0.0-beta04-api.jar!/META-INF/window_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/6c0671fbb7722afc42898b4178b11de7/jetified-kotlinx-coroutines-android-1.5.2.jar!/META-INF/kotlinx-coroutines-android.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/91667e970d35cee0f38e121291f325a1/jetified-kotlin-stdlib-common-1.5.31.jar!/META-INF/kotlin-stdlib-common.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/af48bf569b5523ddd7a06285f676a1ca/jetified-kotlin-stdlib-jdk7-1.5.30.jar!/META-INF/kotlin-stdlib-jdk7.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/b560d76b568ab2e29107d94002f1a070/jetified-kotlin-stdlib-1.5.31.jar!/META-INF/kotlin-stdlib.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/d0224631d7841d16cd3b5d2fab11c793/jetified-kotlin-stdlib-jdk8-1.5.30.jar!/META-INF/kotlin-stdlib-jdk8.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.
e: C:/Users/Hp/.gradle/caches/transforms-2/files-2.1/e0583c70716c2ce3cdb07beee79fcae0/jetified-window-java-1.0.0-beta04-api.jar!/META-INF/window-java_release.kotlin_module: Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15.

FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 14s
┌─ Flutter Fix ───────────────────────────────────────────────────────────────────────────────────┐
│ [!] Your project requires a newer version of the Kotlin Gradle plugin.                          │
│ Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then    │
│ update                                                                                │
│ C:\Users\Hp\Desktop\Programming\Flutter\flutter_application_notifications\android\build.gradle: │
│ ext.kotlin_version = '<latest-version>'                                                         │
└─────────────────────────────────────────────────────────────────────────────────────────────────┘
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

And I am being honest here, I never have experienced bug free upgradation in Flutter till now, except when they made little changes. Literally. Can someone tell me why is this happening and please give a solution for the above error.

Body:
You have to change the ext.kotlin_version in your_flutter_app\android\build.gradle

From

ext.kotlin_version = 'old version'

to

ext.kotlin_version = '1.6.10'

which is the last version.

and you can always see the last version of ext.kotlin_version from the link

https://kotlinlang.org/docs/gradle.html#plugin-and-versions


问:
Is it possible to pass a component as a prop within an object using the spread operator?
Based on the official React documentation, I know that you can pass components as props to other components, in this manner:

```<code>function SplitPane(props) {
  return (
    <div className="SplitPane">
      <div className="SplitPane-left">
        {props.left}
      </div>
      <div className="SplitPane-right">
        {props.right}
      </div>
    </div>
  );
}

function App() {
  return (
    <SplitPane
      left={
        <Contacts />
      }
      right={
        <Chat />
      } />
  );
}
</code>```

My question is, can you pass them within an object, using the spread (...) operator?

Something more like this, based on the above example? I'm just guessing at the syntax here.

```<code>const splitPaneProps = {
  left: {<Contacts />}
  right: {<Chat />}
}

return (<SplitPane {...splitPaneProps} />);

</code>```

I've searched many combinations of "component", "props", "object" and "spread" with no luck, so this question is a last resort before I assume it's not a thing you can do or I'm really bad at searching.

答:
Yes, you just need to change the way you're creating that object:

```<code>const splitPaneProps = {
  left: <Contacts />,
  right: <Chat />
}
</code>```

Curly brackets are used in the middle of JSX to pop you back into plain javascript, but since you're already in plain javascript, there's no need.

Body:
Based on the official React documentation, I know that you can pass components as props to other components, in this manner:

function SplitPane(props) {
  return (

        {props.left}

        {props.right}

  );
}

function App() {
  return (
    <SplitPane
      left={
        <Contacts />
      }
      right={
        <Chat />
      } />
  );
}

My question is, can you pass them within an object, using the spread (...) operator?

Something more like this, based on the above example? I'm just guessing at the syntax here.

const splitPaneProps = {
  left: {<Contacts />}
  right: {<Chat />}
}

return (<SplitPane {...splitPaneProps} />);

I've searched many combinations of "component", "props", "object" and "spread" with no luck, so this question is a last resort before I assume it's not a thing you can do or I'm really bad at searching.

Body:
Yes, you just need to change the way you're creating that object:

const splitPaneProps = {
  left: <Contacts />,
  right: <Chat />
}

Curly brackets are used in the middle of JSX to pop you back into plain javascript, but since you're already in plain javascript, there's no need.


问:
How to select an item in a listbox programatically using its index using c#
I have a listbox which can be edited. Once an item in that listbox is edited and saved, the newly edited item is displayed in the list however its position changes. I want to be able to have that item selected or highlighted even afer its position changes. I can get its new index however I couldnt manage to find a way to have re-selected programitcally after its psoiton changes in the listbox! </p>

<p>Any help here would be greatly appreciated
Thanks </p>

答:
i assume that the itemssource is some kind of collection. why you dont use the SelectedItem property with Mode=TwoWay to select the item you want from your c# code?

```<code><ListBox ItemsSource="{Binding Path=YourItemsCollection}"
         SelectedItem="{Binding Path=MySelectedItem, Mode=TwoWay}" />
</code>```

another way is to use the ICollectionView MoveCurrentTo method. all you have to do is to create a ICollectionView with CollectionViewSource.GetDefaultView(this.YourItemsCollection). if you take this way you do not need binding to SelectedItem but you have to set IsSynchronizedWithCurrentItem=true for your listbox.

Body:
I have a listbox which can be edited. Once an item in that listbox is edited and saved, the newly edited item is displayed in the list however its position changes. I want to be able to have that item selected or highlighted even afer its position changes. I can get its new index however I couldnt manage to find a way to have re-selected programitcally after its psoiton changes in the listbox!

Any help here would be greatly appreciated
Thanks

Body:
i assume that the itemssource is some kind of collection. why you dont use the SelectedItem property with Mode=TwoWay to select the item you want from your c# code?

<ListBox ItemsSource="{Binding Path=YourItemsCollection}"
         SelectedItem="{Binding Path=MySelectedItem, Mode=TwoWay}" />

another way is to use the ICollectionView MoveCurrentTo method. all you have to do is to create a ICollectionView with CollectionViewSource.GetDefaultView(this.YourItemsCollection). if you take this way you do not need binding to SelectedItem but you have to set IsSynchronizedWithCurrentItem=true for your listbox.


问:
Animation deprecated iOS 15
I was trying to make the button go easeInOut but not sure how to do it. I was watching a tutorial but it's out of date and I'm a beginner. Can someone show what the code would look like when implemented?

.animation(.easeInOut(duration:0.25))

```<code>import SwiftUI

typealias OnboardingGetStartedAction = () -> Void

struct OnboardingView: View {

    @Environment(\.presentationMode) private var presentationMode

    let item: OnboardingItem

    let limit: Int
    let handler: OnboardingGetStartedAction

    @Binding var index: Int

    internal init(item: OnboardingItem,
                  limit: Int,
                  index: Binding<Int>,
                  handler: @escaping OnboardingGetStartedAction) {
        self.item = item
        self.limit = limit
        self._index = index
        self.handler = handler
    }

    var body: some View {
        VStack {
            Spacer()

            Image(systemName: item.sfSymbol ?? "")
                .padding(.bottom,50)
                .font(.system(size:120, weight: .bold))

            Text(item.title ?? "")
                .font(.system(size: 32, weight: .bold))
                .multilineTextAlignment(.center)
                .padding(.bottom,2)
                .foregroundColor(.primary)

            Text(item.content ?? "")
                .font(.system(size: 12, weight: .semibold))
                .multilineTextAlignment(.center)
                .padding(.horizontal, 50)
                .foregroundColor(.secondary)

            Button(action: {
                presentationMode.wrappedValue.dismiss()
                handler()
            }, label: {
                Text("Get Started")
            })
                .font(.system(size: 18, weight: .bold))
                .foregroundColor(.white)
                .padding(.horizontal,25)
                .padding(.vertical,10)
                .background(Color.red)
                .clipShape(Capsule())
                .padding(.top, 50)
                .opacity(index == limit ? 1 : 0)
                .allowsHitTesting(index == limit)
                .animation(.easeInOut(duration:0.25))
        }
        .padding(.bottom, 150)
    }
}

struct OnboardingView_Previews: PreviewProvider {
    static var previews: some View {
        //dummy data just to see if this works
        OnboardingView(item: OnboardingItem( title: "Dummy Data!", content: "Dummy Data!", sfSymbol: "building.columns.fill"),
                       limit: 0,
                       index: .constant(0)) {}
    }
}
</code>```

答:
see animation(_:value)

you should animate with an Equatable value.

Title: Animation deprecated iOS 15

Body:
I was trying to make the button go easeInOut but not sure how to do it. I was watching a tutorial but it's out of date and I'm a beginner. Can someone show what the code would look like when implemented?

.animation(.easeInOut(duration:0.25))

import SwiftUI

typealias OnboardingGetStartedAction = () -> Void

struct OnboardingView: View {

    @Environment(\.presentationMode) private var presentationMode

    let item: OnboardingItem

    let limit: Int
    let handler: OnboardingGetStartedAction

    @Binding var index: Int

    internal init(item: OnboardingItem,
                  limit: Int,
                  index: Binding<Int>,
                  handler: @escaping OnboardingGetStartedAction) {
        self.item = item
        self.limit = limit
        self._index = index
        self.handler = handler
    }

    var body: some View {
        VStack {
            Spacer()

            Image(systemName: item.sfSymbol ?? "")
                .padding(.bottom,50)
                .font(.system(size:120, weight: .bold))

            Text(item.title ?? "")
                .font(.system(size: 32, weight: .bold))
                .multilineTextAlignment(.center)
                .padding(.bottom,2)
                .foregroundColor(.primary)

            Text(item.content ?? "")
                .font(.system(size: 12, weight: .semibold))
                .multilineTextAlignment(.center)
                .padding(.horizontal, 50)
                .foregroundColor(.secondary)

            Button(action: {
                presentationMode.wrappedValue.dismiss()
                handler()
            }, label: {
                Text("Get Started")
            })
                .font(.system(size: 18, weight: .bold))
                .foregroundColor(.white)
                .padding(.horizontal,25)
                .padding(.vertical,10)
                .background(Color.red)
                .clipShape(Capsule())
                .padding(.top, 50)
                .opacity(index == limit ? 1 : 0)
                .allowsHitTesting(index == limit)
                .animation(.easeInOut(duration:0.25))
        }
        .padding(.bottom, 150)
    }
}

struct OnboardingView_Previews: PreviewProvider {
    static var previews: some View {
        //dummy data just to see if this works
        OnboardingView(item: OnboardingItem( title: "Dummy Data!", content: "Dummy Data!", sfSymbol: "building.columns.fill"),
                       limit: 0,
                       index: .constant(0)) {}
    }
}


问:
How to send form data through get request in fetch api
I was having an API where I am calling a get request to send to query parameters through form data but I am getting get request doesn't take form data. How to do it

http://ihub-fastapi-solubility.herokuapp.com/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O this is the URL and solute and solvent are the query parameters.

  const onSubmit = (e) => {
    e.preventDefault(); // <-- prevent the default form action

    const formData = new FormData();
    formData.set("solute", solutestate); // <-- local component state
    formData.set("solvent", solventstate); // <-- local component state
    console.log({ formData });

    fetch("http://ihub-fastapi-solubility.herokuapp.com/predict", {
      method: "get",
      body: formData,
    }).catch((err) => {
      setError(err.error);
      console.log(err);
    });
```

When I tried with post I got this error

答:
FormData isn't the best choice here as that is primarily used in constructing multipart/form-data request payloads for use in POST, PUT and PATCH requests.

Use URLSearchParams instead to easily construct query parameters and serialise it into the URL...

const fetch = function fakeFetch(url, init) {
  console.log(init.method, url)
}

const solutestate = "CC(C)(C)Br"
const solventstate = "CC(C)(C)O"

const params = new URLSearchParams({
  solute: solutestate,
  solvent: solventstate
})

fetch(`http://ihub-fastapi-solubility.herokuapp.com/predict?${params}`, {
  method: "GET"
})```

Using URLSearchParams has the added benefit of correctly URL encoding your data.

Body:
I was having an API where I am calling a get request to send to query parameters through form data but I am getting get request doesn't take form data. How to do it

http://ihub-fastapi-solubility.herokuapp.com/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O this is the URL and solute and solvent are the query parameters.

  const onSubmit = (e) => {
    e.preventDefault(); // <-- prevent the default form action

    const formData = new FormData();
    formData.set("solute", solutestate); // <-- local component state
    formData.set("solvent", solventstate); // <-- local component state
    console.log({ formData });

    fetch("http://ihub-fastapi-solubility.herokuapp.com/predict", {
      method: "get",
      body: formData,
    }).catch((err) => {
      setError(err.error);
      console.log(err);
    });

When I tried with post I got this error

Body:
FormData isn't the best choice here as that is primarily used in constructing multipart/form-data request payloads for use in POST, PUT and PATCH requests.

Use URLSearchParams instead to easily construct query parameters and serialise it into the URL...

const fetch = function fakeFetch(url, init) {
  console.log(init.method, url)
}

const solutestate = "CC(C)(C)Br"
const solventstate = "CC(C)(C)O"

const params = new URLSearchParams({
  solute: solutestate,
  solvent: solventstate
})

fetch(`http://ihub-fastapi-solubility.herokuapp.com/predict?${params}`, {
  method: "GET"
})

Using URLSearchParams has the added benefit of correctly URL encoding your data.


问:
Direct tweet reply URL link? URL Query String for Twitter Tweet Reply?
How do I generate an URL that will automatically open the "tweet your reply" compose window?

Example Tweet: https://twitter.com/CanadiensMTL/status/1490808598242512898

What I thought would work (but doesn't): https://twitter.com/compose/tweet/1490808598242512898

Instead of actually making a person click the reply button, it'll just auto-open the compose box for a specific tweet.

Normally, I can just right click copy link, but when I'm on twitter, there is no copy link option when I right click because it's a <button> and not an  I guess... and when I left click the speech bubble reply icon the url bar says https://twitter.com/compose/tweet but I was hoping to specifically  find a "compose tweet reply" link to generate. In a perfect world I thought I would just be able to visit https://twitter.com/compose/tweet/1490808598242512898 but that doesn't work.

I was able to scrape some "specific" urls but nothing that "replies". Any ideas?

https://twitter.com/GameSpot/status/1490844073187442692

https://twitter.com/GameSpot/status/1490844073187442692/likes

https://twitter.com/GameSpot/status/1490844073187442692/retweets

https://twitter.com/GameSpot/status/1490844073187442692/retweets/with_comments

答:
I was able to find answer thanks to another post I found on stackoverflow:

https://twitter.com/intent/tweet?in_reply_to=TWEET_NUMBER

and just replace / swap TWEET_NUMBER


问:
export 'default' (imported as 'Three') was not found in 'three'
Overview
In main.js, add

```<code>import Three from 'three'
</code>```

Vue.use(Three)

Start dev server with npm run dev.
Expected behavior
The Vue project should load without errors.
Actual behavior
The dev server gives this warning:

```<code>warning  in ./src/main.js
    7:8-14 "export 'default' (imported as 'Three') was not found in 'three'
</code>```

And the browser's js console displays the error:

```<code>Uncaught TypeError: Cannot read property 'installed' of undefined
at Function.Vue.use (eval at <anonymous> (app.js:723), <anonymous>:3443:15)
at eval (eval at <anonymous> (app.js:778), <anonymous>:14:45)
at Object.<anonymous> (app.js:778)
at __webpack_require__ (app.js:660)
at fn (app.js:84)
at Object.<anonymous> (app.js:964)
at __webpack_require__ (app.js:660)
at app.js:709
at app.js:712
</code>```

答:
In vscode,You need to set this typescript.disableAutomaticTypeAcquisition

Many popular libraries ship with typings files so you get IntelliSense for them automatically. For libraries that do not include typings, VS Code's Automatic Type Acquisition will automatically install community maintained typings file for you.

or import {Scene, PerspectiveCamera, WebGLRenderer, ...other} from 'three'

Body:
Overview
In main.js, add

import Three from 'three'

Vue.use(Three)

Start dev server with npm run dev.
Expected behavior
The Vue project should load without errors.
Actual behavior
The dev server gives this warning:

warning  in ./src/main.js
    7:8-14 "export 'default' (imported as 'Three') was not found in 'three'

And the browser's js console displays the error:

Uncaught TypeError: Cannot read property 'installed' of undefined
at Function.Vue.use (eval at <anonymous> (app.js:723), <anonymous>:3443:15)
at eval (eval at <anonymous> (app.js:778), <anonymous>:14:45)
at Object.<anonymous> (app.js:778)
at __webpack_require__ (app.js:660)
at fn (app.js:84)
at Object.<anonymous> (app.js:964)
at __webpack_require__ (app.js:660)
at app.js:709
at app.js:712


问:
OpenCV VideoWriter Error "dimensions too large for MPEG-4"
I have some frames (dimensions: 8192x2160) that are generated from concatenating two 4096x2160 frames side by side. When writing these frames to a video file using OpenCV VideoWriter, I get this error: dimensions too large for MPEG-4

Here is my code:

```<code>video_name = "vid.mp4"

images = sorted([img for img in os.listdir(images_folder) if img.endswith(".png")])

frame = cv2.imread(os.path.join(images_folder, images[0]))
height, width, layers = frame.shape

fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(video_name, fourcc, FRAME_RATE, (width, height))

for image in images:
    video.write(cv2.imread(os.path.join(images_folder, image)))

cv2.destroyAllWindows()
video.release()
</code>```

This didn't work either:

```<code>video_name = "output.avi"
video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'DIVX'), 10, (width, height))
</code>```

Does anyone have any suggestions?

答: Use a different codec or scale each frame down with cv2.resize.

Body:
I have some frames (dimensions: 8192x2160) that are generated from concatenating two 4096x2160 frames side by side. When writing these frames to a video file using OpenCV VideoWriter, I get this error: dimensions too large for MPEG-4

Here is my code:

video_name = "vid.mp4"

images = sorted([img for img in os.listdir(images_folder) if img.endswith(".png")])

frame = cv2.imread(os.path.join(images_folder, images[0]))
height, width, layers = frame.shape

fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(video_name, fourcc, FRAME_RATE, (width, height))

for image in images:
    video.write(cv2.imread(os.path.join(images_folder, image)))

cv2.destroyAllWindows()
video.release()

This didn't work either:

video_name = "output.avi"
video = cv2.VideoWriter(video_name, cv2.VideoWriter_fourcc(*'DIVX'), 10, (width, height))

Does anyone have any suggestions?


问:
Error: Cannot find module 'chai.as.promised'
I do see it  in my dependencies,also I event run: npm i chai chai.as.promised again, but still cannot see the modele. Thank you for helping.

After: truffle test

```<code>Compiling your contracts...
===========================
> Compiling ./src/contracts/Token.sol
> Artifacts written to /var/folders/1v/9ln82rd97dqghgyk_7krrwtr0000gn/T/test--22208-ZPVpGBs8ds6D
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

Error: Cannot find module 'chai.as.promised'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/Users/davell/my-blockchain-site/test/Token.test.js:9:21)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at loader (/Users/davell/my-blockchain-site/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/davell/my-blockchain-site/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at /usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:390:36
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles
</code>```

I ran: npm i chai chai.as.promised

```<code> my-blockchain-site git:(master) ✗ npm i chai chai-as-promised
npm WARN @babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.15.4 requires a peer of @babel/core@^7.13.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-proposal-class-static-block@7.15.4 requires a peer of @babel/core@^7.12.0 but none is installed. You must install peer dependencies yourself.
npm WARN bootstrap@4.5.2 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.
npm WARN bootstrap@4.5.2 requires a peer of popper.js@^1.16.1 but none is installed. You must install peer dependencies yourself.
npm WARN postcss-browser-comments@3.0.0 requires a peer of browserslist@^4 but none is installed. You must install peer dependencies yourself.
npm WARN react-apexcharts@1.3.7 requires a peer of apexcharts@^3.18.0 but none is installed. You must install peer dependencies yourself.
npm WARN react-scripts@3.4.3 requires a peer of typescript@^3.2.1 but none is installed. You must install peer dependencies yourself.
npm WARN sass-loader@8.0.2 requires a peer of node-sass@^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN sass-loader@8.0.2 requires a peer of sass@^1.3.0 but none is installed. You must install peer dependencies yourself.
npm WARN sass-loader@8.0.2 requires a peer of fibers@>= 3.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.21.0 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.

+ chai-as-promised@7.1.1
+ chai@4.3.4
updated 2 packages and audited 2401 packages in 11.389s
found 119 vulnerabilities (9 low, 49 moderate, 60 high, 1 critical)
  run `npm audit fix` to fix them, or `npm audit` for details
➜  my-blockchain-site git:(master) ✗

</code>```

But still cannot find it
Thank you

答: I hard the same issue but I install this npm install chai-as-promised  from chai-as-promised

Body:
I do see it  in my dependencies,also I event run: npm i chai chai.as.promised again, but still cannot see the modele. Thank you for helping.

After: truffle test

Compiling your contracts...
===========================
> Compiling ./src/contracts/Token.sol
> Artifacts written to /var/folders/1v/9ln82rd97dqghgyk_7krrwtr0000gn/T/test--22208-ZPVpGBs8ds6D
> Compiled successfully using:
   - solc: 0.5.16+commit.9c3226ce.Emscripten.clang

Error: Cannot find module 'chai.as.promised'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (/Users/davell/my-blockchain-site/test/Token.test.js:9:21)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at loader (/Users/davell/my-blockchain-site/node_modules/babel-register/lib/node.js:144:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/davell/my-blockchain-site/node_modules/babel-register/lib/node.js:154:7)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at /usr/local/lib/node_modules/truffle/node_modules/mocha/lib/mocha.js:390:36
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles

I ran: npm i chai chai.as.promised

 my-blockchain-site git:(master) ✗ npm i chai chai-as-promised
npm WARN @babel/plugin-bugfix-v8-spread-parameters-in-optional-chaining@7.15.4 requires a peer of @babel/core@^7.13.0 but none is installed. You must install peer dependencies yourself.
npm WARN @babel/plugin-proposal-class-static-block@7.15.4 requires a peer of @babel/core@^7.12.0 but none is installed. You must install peer dependencies yourself.
npm WARN bootstrap@4.5.2 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.
npm WARN bootstrap@4.5.2 requires a peer of popper.js@^1.16.1 but none is installed. You must install peer dependencies yourself.
npm WARN postcss-browser-comments@3.0.0 requires a peer of browserslist@^4 but none is installed. You must install peer dependencies yourself.
npm WARN react-apexcharts@1.3.7 requires a peer of apexcharts@^3.18.0 but none is installed. You must install peer dependencies yourself.
npm WARN react-scripts@3.4.3 requires a peer of typescript@^3.2.1 but none is installed. You must install peer dependencies yourself.
npm WARN sass-loader@8.0.2 requires a peer of node-sass@^4.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN sass-loader@8.0.2 requires a peer of sass@^1.3.0 but none is installed. You must install peer dependencies yourself.
npm WARN sass-loader@8.0.2 requires a peer of fibers@>= 3.1.0 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.21.0 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.

+ chai-as-promised@7.1.1
+ chai@4.3.4
updated 2 packages and audited 2401 packages in 11.389s
found 119 vulnerabilities (9 low, 49 moderate, 60 high, 1 critical)
  run `npm audit fix` to fix them, or `npm audit` for details
➜  my-blockchain-site git:(master) ✗

But still cannot find it
Thank you