问:
Orika Object mapper not mapping Lists
I am using an object mapper called Orika, and I have some doubts regarding how it works or am I doing anything wrong here.

Following are the classes

https://googleapis.dev/java/google-cloud-channel/latest/com/google/cloud/channel/v1/Entitlement.html

This is the source class structure, an object comes in this format.

Entitlements.java

```<code>@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Entitlement {

    private String name;
    private String createTime;
    private String updateTime;
    private String offer;
    private String provisioningState;
    private ProvisionedService provisionedService;
    private String purchaseOrderId;
    private List<String> suspensionReasons;
    private CommitmentSettings commitmentSettings;
    private TrialSettings trialSettings;
    private AssociationInfo associationInfo;
    private List<Parameter> parameters;
}
</code>```

Parameter.java

```<code>@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Parameter {
    private String name;
    private Value value;
    private boolean editable;
}
</code>```

My orika mapper code:

```<code>public class OrikaMapper {
    private MapperFactory mapperFactory;
    public <S, D> D map(S s, Class<D> type) {
        return this.mapperFactory.getMapperFacade().map(s, type);
    }
}
</code>```

my method:

```<code>public Entitlement getEntitlement(String credential, String customerId, String entitlementId) {
         CloudChannelServiceClient client = null;
         Entitlement resp = null;
        try {
            client = <<>>;
            String name = "accounts/"+ ACCOUNT_ID +"/customers/"+customerId+"/entitlements/"+entitlementId;
            GetEntitlementRequest request = GetEntitlementRequest.newBuilder().setName(name).build();
            com.google.cloud.channel.v1.Entitlement entitlement = client.getEntitlement(request);
            resp = orikaMapper.map(gson.toJson(entitlement), Entitlement.class);
        } catch (Exception e) {
            throw new ApplicationException("code", e.getMessage());
        }
        return resp;
      }
</code>```

sample response from google API

```<code>{ "name_": "<<>>", "createTime_": { "seconds_": 1615715413, "nanos_": 810000000, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "offer_": "<<>>", "provisioningState_": 5, "provisionedService_": { "provisioningId_": "<<>>", "productId_": "<<>>", "skuId_": "<<>>", "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "suspensionReasons_": [ 4 ], "suspensionReasonsMemoizedSerializedSize": 0, "purchaseOrderId_": "A codelab test", "trialSettings_": { "trial_": false, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "parameters_": [ { "name_": "max_units", "value_": { "kindCase_": 1, "kind_": 4, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "editable_": true, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, { "name_": "assigned_units", "value_": { "kindCase_": 1, "kind_": 1, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "editable_": false, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 } ], "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }
</code>```

Response after mapping in orika

```<code>{ "name": "<<>>", "createTime": "seconds: 1615715413\nnanos: 810000000\n", "updateTime": "", "offer": "<<>>", "provisioningState": "SUSPENDED", "provisionedService": { "provisioningId": "<<>>", "productId": "<<>>", "skuId": "<<>>" }, "purchaseOrderId": "A codelab test", "commitmentSettings": { "startTime": "", "endTime": "", "renewalSettings": { "enableRenewal": false, "resizeUnitCount": false, "paymentPlan": "PAYMENT_PLAN_UNSPECIFIED", "paymentCycle": { "duration": 0, "periodType": "PERIOD_TYPE_UNSPECIFIED" } } }, "trialSettings": { "trial": false, "endTime": "" }, "associationInfo": { "baseEntitlement": "" } }
</code>```

My issue is, the response is not able to map what is in the List<> fields. All the other fields are mapped.
What am i missing here.

答:
Rather late in reply, but if this helps anyone in the future. I was facing the same issue. It seems that you have to explicitly call:
mapper.mapAsList
I.e. in questioner's case:
parameters = orikaMapper.mapAsList(entitlement.getParameters(), Parameter.class);</p>

Title: Orika Object mapper not mapping Lists

Body:
I am using an object mapper called Orika, and I have some doubts regarding how it works or am I doing anything wrong here.

Following are the classes

https://googleapis.dev/java/google-cloud-channel/latest/com/google/cloud/channel/v1/Entitlement.html

This is the source class structure, an object comes in this format.

Entitlements.java

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Entitlement {

    private String name;
    private String createTime;
    private String updateTime;
    private String offer;
    private String provisioningState;
    private ProvisionedService provisionedService;
    private String purchaseOrderId;
    private List<String> suspensionReasons;
    private CommitmentSettings commitmentSettings;
    private TrialSettings trialSettings;
    private AssociationInfo associationInfo;
    private List<Parameter> parameters;
}

Parameter.java

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Parameter {
    private String name;
    private Value value;
    private boolean editable;
}

My orika mapper code:

public class OrikaMapper {
    private MapperFactory mapperFactory;
    public <S, D> D map(S s, Class<D> type) {
        return this.mapperFactory.getMapperFacade().map(s, type);
    }
}

my method:

public Entitlement getEntitlement(String credential, String customerId, String entitlementId) {
         CloudChannelServiceClient client = null;
         Entitlement resp = null;
        try {
            client = <<>>;
            String name = "accounts/"+ ACCOUNT_ID +"/customers/"+customerId+"/entitlements/"+entitlementId;
            GetEntitlementRequest request = GetEntitlementRequest.newBuilder().setName(name).build();
            com.google.cloud.channel.v1.Entitlement entitlement = client.getEntitlement(request);
            resp = orikaMapper.map(gson.toJson(entitlement), Entitlement.class);
        } catch (Exception e) {
            throw new ApplicationException("code", e.getMessage());
        }
        return resp;
      }

sample response from google API

{ "name_": "<<>>", "createTime_": { "seconds_": 1615715413, "nanos_": 810000000, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "offer_": "<<>>", "provisioningState_": 5, "provisionedService_": { "provisioningId_": "<<>>", "productId_": "<<>>", "skuId_": "<<>>", "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "suspensionReasons_": [ 4 ], "suspensionReasonsMemoizedSerializedSize": 0, "purchaseOrderId_": "A codelab test", "trialSettings_": { "trial_": false, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "parameters_": [ { "name_": "max_units", "value_": { "kindCase_": 1, "kind_": 4, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "editable_": true, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, { "name_": "assigned_units", "value_": { "kindCase_": 1, "kind_": 1, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }, "editable_": false, "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 } ], "memoizedIsInitialized": -1, "unknownFields": { "fields": {}, "fieldsDescending": {} }, "memoizedSize": -1, "memoizedHashCode": 0 }

Response after mapping in orika

{ "name": "<<>>", "createTime": "seconds: 1615715413\nnanos: 810000000\n", "updateTime": "", "offer": "<<>>", "provisioningState": "SUSPENDED", "provisionedService": { "provisioningId": "<<>>", "productId": "<<>>", "skuId": "<<>>" }, "purchaseOrderId": "A codelab test", "commitmentSettings": { "startTime": "", "endTime": "", "renewalSettings": { "enableRenewal": false, "resizeUnitCount": false, "paymentPlan": "PAYMENT_PLAN_UNSPECIFIED", "paymentCycle": { "duration": 0, "periodType": "PERIOD_TYPE_UNSPECIFIED" } } }, "trialSettings": { "trial": false, "endTime": "" }, "associationInfo": { "baseEntitlement": "" } }

My issue is, the response is not able to map what is in the List<> fields. All the other fields are mapped.
What am i missing here.


来源: stackexchange

问:
Add more than one item to an Array using the same Javascript Function
I am a student learning basic JS and I am trying to create a webpage that will display an array based on the numbers entered into the input box. So far I have been able to make a function that adds a single item to the array, but it does not work if you try to add a second number to the array. I am not sure if I am formatting it correctly. This is the code I have so far: </p>

```<code>HTML:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Numbers</title>

    <!--Bootstrap and CSS Links-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <section>
        <header class="header m-2">Week 8 Assignment</header>
        <section class="row m-2">
            <label class="inputLabel">Number: <input type="number" id="numInput"></label>
        </section>
        <button class="button m-1" onclick="displayText(); addNum();">Add Number</button>
        <button class="button m-1" disabled>Calculate</button>
        <button class="button m-1">Reset</button>
    </section>

    <section>
        <div class="numLabel m-2" id="numLabel">Numbers Added: </div>
        <p class="m-2 mt-3" id="numValue"></p>
    </section>

<script src="script.js"></script>
</body>
</html>
</code>```

```<code>JS:
//Display "Numbers Added: "
function displayText() {
    document.getElementById("numLabel").style.display = "block";
}

//Add the entered value into the array
function addNum() {
    let num = document.getElementById("numInput").value;

    let numArray = [];
    numArray.push(document.getElementById("numValue").innerHTML = num);
}
</code>```

答:
You have to put the numArray outside the function.

or else it will get reseted whenever the addNum function is called.

like this:

//Display "Numbers Added: "
    let numArray = [];
function displayText() {
    document.getElementById("numLabel").style.display = "block";
}

//Add the entered value into the array
function addNum() {
    let num = document.getElementById("numInput").value;
document.getElementById("numValue").innerHTML = num;
    numArray.push(num);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Numbers</title>

    <!--Bootstrap and CSS Links-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <section>
        <header class="header m-2">Week 8 Assignment</header>
        <section class="row m-2">
            <label class="inputLabel">Number: <input type="number" id="numInput"></label>
        </section>
        <button class="button m-1" onclick="displayText(); addNum();">Add Number</button>
        <button class="button m-1" disabled>Calculate</button>
        <button class="button m-1">Reset</button>
    </section>

    <section>
        <div class="numLabel m-2" id="numLabel">Numbers Added: </div>
        <p class="m-2 mt-3" id="numValue"></p>
    </section>

<script src="script.js"></script>
</body>
</html></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am a student learning basic JS and I am trying to create a webpage that will display an array based on the numbers entered into the input box. So far I have been able to make a function that adds a single item to the array, but it does not work if you try to add a second number to the array. I am not sure if I am formatting it correctly. This is the code I have so far:

HTML:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Numbers</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">

        Week 8 Assignment

            Number: <input type="number" id="numInput">

        <button class="button m-1" onclick="displayText(); addNum();">Add Number</button>
        <button class="button m-1" disabled>Calculate</button>
        <button class="button m-1">Reset</button>

Numbers Added:

JS:
//Display "Numbers Added: "
function displayText() {
    document.getElementById("numLabel").style.display = "block";
}

//Add the entered value into the array
function addNum() {
    let num = document.getElementById("numInput").value;

    let numArray = [];
    numArray.push(document.getElementById("numValue").innerHTML = num);
}

Body:
You have to put the numArray outside the function.

or else it will get reseted whenever the addNum function is called.

like this:

//Display "Numbers Added: "
    let numArray = [];
function displayText() {
    document.getElementById("numLabel").style.display = "block";
}

//Add the entered value into the array
function addNum() {
    let num = document.getElementById("numInput").value;
document.getElementById("numValue").innerHTML = num;
    numArray.push(num);
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Numbers</title>

    <!--Bootstrap and CSS Links-->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <section>
        <header class="header m-2">Week 8 Assignment</header>
        <section class="row m-2">
            <label class="inputLabel">Number: <input type="number" id="numInput"></label>
        </section>
        <button class="button m-1" onclick="displayText(); addNum();">Add Number</button>
        <button class="button m-1" disabled>Calculate</button>
        <button class="button m-1">Reset</button>
    </section>

    <section>
        <div class="numLabel m-2" id="numLabel">Numbers Added: </div>
        <p class="m-2 mt-3" id="numValue"></p>
    </section>

<script src="script.js"></script>
</body>
</html>


问:
how to open a pdf file in silverlight from clientbin folder?
I have a product.pdf in my clientbin(silverlight) folder which contains detail about product on click of button just i want to open that pdf i used following code it's working fine locally after hosting it is giving HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. how can i do that one please help me

** service and calling aspx page in silverlight**

```<code>  Dim uri As New Uri(HtmlPage.Document.DocumentUri, "/ClientBin/product.pdf")
        'HtmlPage.Window.Navigate(uri, "_blank")
        Dim path As String = uri.AbsoluteUri.ToString()
        ' HtmlPage.Window.Eval("window.open('" & path & "')")
        HtmlPage.Window.Eval("document.location.href='" & path & "';")
</code>```

** Error code After hosting **

```<code>HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
</code>```

答:
It seems that you are redirecting to the wrong resource.

So I suggest you throw out thte redirect for the moment and replace it with some logging output.
Just print out the value of path and see where it points to.

CAUTION: only do this if you're on an internal test system

ContentLicense: CC BY-SA 3.0

Body:
I have a product.pdf in my clientbin(silverlight) folder which contains detail about product on click of button just i want to open that pdf i used following code it's working fine locally after hosting it is giving HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. how can i do that one please help me

** service and calling aspx page in silverlight**

  Dim uri As New Uri(HtmlPage.Document.DocumentUri, "/ClientBin/product.pdf")
        'HtmlPage.Window.Navigate(uri, "_blank")
        Dim path As String = uri.AbsoluteUri.ToString()
        ' HtmlPage.Window.Eval("window.open('" & path & "')")
        HtmlPage.Window.Eval("document.location.href='" & path & "';")

** Error code After hosting **

HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.


问:
What is the pricing tier of google sign-in?
There is a note in google identity platform document:

https://developers.google.com/identity/protocols/oauth2/openid-connect

Note: If you want to provide a "Sign-in with Google" button for your website or app, we recommend using Google Sign-In, our sign-in client library that is built on the OpenID Connect protocol and provides OpenID Connect formatted ID Tokens.

As I understand, google using OpenID Connect for sign-in library, which means the pricing tier for this is tier 2 according to this page:

https://cloud.google.com/identity-platform/pricing

and I will have to pay if there are more than 50 people sign in to my site each month,
Please help me to confirm if this is correct.

答:
Google Sign-In and Identity Platform are two separate products (although they can be used in combination).

If you're just using Google Sign-In as described in the OpenID Connect docs, then the Identity Platform pricing doesn't apply.


问:
How do you test for the non-existence of an element using jest and react-testing-library?
I have a component library that I'm writing unit tests for using Jest and react-testing-library. Based on certain props or events I want to verify that certain elements aren't being rendered.

getByText, getByTestId, etc throw and error in react-testing-library if the element isn't found causing the test to fail before the expect function fires.

How do you test for something not existing in jest using react-testing-library?

答:
I recently wrote a method to check visibility of element for a jest cucumber project.

Hope it is useful.

```<code>public async checknotVisibility(page:Page,location:string) :Promise<void>
{
    const element = await page.waitForSelector(location);
    expect(element).not.toBe(location);
}
</code>```

Body:
I recently wrote a method to check visibility of element for a jest cucumber project.

Hope it is useful.

public async checknotVisibility(page:Page,location:string) :Promise<void>
{
    const element = await page.waitForSelector(location);
    expect(element).not.toBe(location);
}


问:
npx create-next-app@latest --ts 3 high severity vulnerabilities [node-fetch is vulnerable to Exposure of Sensitive Information to Unauthorized Actor]
I've just created a new Nextjs + TS project using
npx create-next-app@latest --ts (as per the documentation).

I keep receiving 3 high severity vulnerabilities,
npm audit fix --force, makes it worse by adding around 24 high severity vulnerabilities.

Any way around this? should I be concerned that I might have installed a malicious package?

```<code># npm audit report

node-fetch  <2.6.7
Severity: high
 ---> node-fetch is vulnerable to Exposure of Sensitive Information to an Unauthorized Actor - https://github.com/advisories/GHSA-r683-j2x4-v87g <---
fix available via `npm audit fix --force`
Will install next@10.0.1, which is a breaking change
node_modules/node-fetch
  next  9.0.6-canary.0 - 9.3.4-canary.0 || 10.0.2-canary.0 - 12.0.8
  Depends on vulnerable versions of node-fetch
  node_modules/next
    eslint-config-next  >=10.2.1-canary.2
    Depends on vulnerable versions of next
    node_modules/eslint-config-next
</code>```
```<code>firebasetest
├─┬ https://opencollective.com/eslint
│ │ └── eslint@8.7.0
│ ├── https://github.com/sponsors/epoberezkin
│ │   └── ajv@6.12.6
│ ├─┬ https://github.com/chalk/chalk?sponsor=1
│ │ │ └── chalk@4.1.2
│ │ └── https://github.com/chalk/ansi-styles?sponsor=1
│ │     └── ansi-styles@4.3.0
│ ├── https://github.com/sponsors/sindresorhus
│ │   └── escape-string-regexp@4.0.0, globals@13.12.0, type-fest@0.20.2, import-fresh@3.3.0, strip-json-comments@3.1.1, globby@11.1.0
│ ├── https://github.com/sponsors/mysticatea
│ │   └── eslint-utils@3.0.0, regexpp@3.2.0
│ └── https://github.com/sponsors/isaacs
│     └── rimraf@3.0.2, glob@7.1.7
├── https://opencollective.com/browserslist
│   └── caniuse-lite@1.0.30001301, browserslist@4.19.1
├── https://opencollective.com/postcss/
│   └── postcss@8.2.15
├── https://github.com/chalk/supports-color?sponsor=1
│   └── supports-color@8.1.1
├── https://github.com/sponsors/feross
│   └── safe-buffer@5.2.1, run-parallel@1.2.0, queue-microtask@1.2.3
├── https://opencollective.com/babel
│   └── @babel/core@7.16.12
├── https://opencollective.com/typescript-eslint
│   └── @typescript-eslint/parser@5.10.1, @typescript-eslint/scope-manager@5.10.1, @typescript-eslint/visitor-keys@5.10.1, @typescript-eslint/types@5.10.1, @typescript-eslint/typescript-estree@5.10.1
├── https://github.com/sponsors/ljharb
│   └── resolve@2.0.0-next.3, array-includes@3.1.4, call-bind@1.0.2, es-abstract@1.19.1, es-to-primitive@1.2.1, is-date-object@1.0.5, has-tostringtag@1.0.0, is-symbol@1.0.4, get-symbol-description@1.0.0, has-symbols@1.0.2, is-callable@1.2.4, is-negative-zero@2.0.2, is-regex@1.1.4, is-shared-array-buffer@1.0.1, is-weakref@1.0.2, object-inspect@1.12.0, object.assign@4.1.2, string.prototype.trimend@1.0.4, string.prototype.trimstart@1.0.4, unbox-primitive@1.0.1, has-bigints@1.0.1, which-boxed-primitive@1.0.2, is-bigint@1.0.4, is-boolean-object@1.1.2, is-number-object@1.0.6, side-channel@1.0.4, get-intrinsic@1.1.1, is-string@1.0.7, array.prototype.flat@1.2.5, object.values@1.1.5, array.prototype.flatmap@1.2.5, object.fromentries@2.0.5, object.hasown@1.1.0, string.prototype.matchall@4.0.6, regexp.prototype.flags@1.4.1
└── https://opencollective.com/core-js
    └── core-js-pure@3.20.3
</code>```

答:
I fixed this by running the NextJS update commands mentioned in this article: https://nextjs.org/docs/upgrading

```<code>npm install react@latest react-dom@latest
</code>```

and then this

```<code>npm install next@12
</code>```

I didn't have any errors after upgrade, but you should definitely check your console after running the commands.

NOTE: The updated versions for my project are:

```<code>"next": "^12.0.10",
"react": "^17.0.2",
"react-dom": "^17.0.2",
</code>```

Body:
I've just created a new Nextjs + TS project using
npx create-next-app@latest --ts (as per the documentation).

I keep receiving 3 high severity vulnerabilities,
npm audit fix --force, makes it worse by adding around 24 high severity vulnerabilities.

Any way around this? should I be concerned that I might have installed a malicious package?

# npm audit report

node-fetch  <2.6.7
Severity: high
 ---> node-fetch is vulnerable to Exposure of Sensitive Information to an Unauthorized Actor - https://github.com/advisories/GHSA-r683-j2x4-v87g <---
fix available via `npm audit fix --force`
Will install next@10.0.1, which is a breaking change
node_modules/node-fetch
  next  9.0.6-canary.0 - 9.3.4-canary.0 || 10.0.2-canary.0 - 12.0.8
  Depends on vulnerable versions of node-fetch
  node_modules/next
    eslint-config-next  >=10.2.1-canary.2
    Depends on vulnerable versions of next
    node_modules/eslint-config-next

firebasetest
├─┬ https://opencollective.com/eslint
│ │ └── eslint@8.7.0
│ ├── https://github.com/sponsors/epoberezkin
│ │   └── ajv@6.12.6
│ ├─┬ https://github.com/chalk/chalk?sponsor=1
│ │ │ └── chalk@4.1.2
│ │ └── https://github.com/chalk/ansi-styles?sponsor=1
│ │     └── ansi-styles@4.3.0
│ ├── https://github.com/sponsors/sindresorhus
│ │   └── escape-string-regexp@4.0.0, globals@13.12.0, type-fest@0.20.2, import-fresh@3.3.0, strip-json-comments@3.1.1, globby@11.1.0
│ ├── https://github.com/sponsors/mysticatea
│ │   └── eslint-utils@3.0.0, regexpp@3.2.0
│ └── https://github.com/sponsors/isaacs
│     └── rimraf@3.0.2, glob@7.1.7
├── https://opencollective.com/browserslist
│   └── caniuse-lite@1.0.30001301, browserslist@4.19.1
├── https://opencollective.com/postcss/
│   └── postcss@8.2.15
├── https://github.com/chalk/supports-color?sponsor=1
│   └── supports-color@8.1.1
├── https://github.com/sponsors/feross
│   └── safe-buffer@5.2.1, run-parallel@1.2.0, queue-microtask@1.2.3
├── https://opencollective.com/babel
│   └── @babel/core@7.16.12
├── https://opencollective.com/typescript-eslint
│   └── @typescript-eslint/parser@5.10.1, @typescript-eslint/scope-manager@5.10.1, @typescript-eslint/visitor-keys@5.10.1, @typescript-eslint/types@5.10.1, @typescript-eslint/typescript-estree@5.10.1
├── https://github.com/sponsors/ljharb
│   └── resolve@2.0.0-next.3, array-includes@3.1.4, call-bind@1.0.2, es-abstract@1.19.1, es-to-primitive@1.2.1, is-date-object@1.0.5, has-tostringtag@1.0.0, is-symbol@1.0.4, get-symbol-description@1.0.0, has-symbols@1.0.2, is-callable@1.2.4, is-negative-zero@2.0.2, is-regex@1.1.4, is-shared-array-buffer@1.0.1, is-weakref@1.0.2, object-inspect@1.12.0, object.assign@4.1.2, string.prototype.trimend@1.0.4, string.prototype.trimstart@1.0.4, unbox-primitive@1.0.1, has-bigints@1.0.1, which-boxed-primitive@1.0.2, is-bigint@1.0.4, is-boolean-object@1.1.2, is-number-object@1.0.6, side-channel@1.0.4, get-intrinsic@1.1.1, is-string@1.0.7, array.prototype.flat@1.2.5, object.values@1.1.5, array.prototype.flatmap@1.2.5, object.fromentries@2.0.5, object.hasown@1.1.0, string.prototype.matchall@4.0.6, regexp.prototype.flags@1.4.1
└── https://opencollective.com/core-js
    └── core-js-pure@3.20.3

Body:
I fixed this by running the NextJS update commands mentioned in this article: https://nextjs.org/docs/upgrading

npm install react@latest react-dom@latest

and then this

npm install next@12

I didn't have any errors after upgrade, but you should definitely check your console after running the commands.

NOTE: The updated versions for my project are:

"next": "^12.0.10",
"react": "^17.0.2",
"react-dom": "^17.0.2",


问:
Execution of cmd cells in databricks notebook based on some condition
I have a python 3.5 notebook in databricks. I have a requirement to execute databricks notebook cells based on some conditions. I didn't see any functionality out of the box.

I have tried creating a python egg with the below code and installed it in databricks cluster.

```<code>def skip(line, cell=None):
'''Skips execution of the current line/cell if line evaluates to True.'''
  if eval(line):
    return

  get_ipython().ex(cell)

def load_ipython_extension(shell):

  '''Registers the skip magic when the extension loads.'''
  shell.register_magic_function(skip, 'line_cell')

def unload_ipython_extension(shell):
  '''Unregisters the skip magic when the extension unloads.'''
  del shell.magics_manager.magics['cell']['skip']
</code>```

But while I'm trying to load that with extension using
    %load_ext skip_cell
it's throwing an error saying "The module is not an IPython module". Any help or suggestion is appreciated. Thanks.

答:
Now there is support to run notebooks based on condition

```<code>if <condition>:
    dbutils.notebook.run("notebook-name", 60, {"argument": "data", "argument2": "data2", ...})
</code>```

More details here
https://docs.databricks.com/notebooks/notebook-workflows.html#example

Body:
I have a python 3.5 notebook in databricks. I have a requirement to execute databricks notebook cells based on some conditions. I didn't see any functionality out of the box.

I have tried creating a python egg with the below code and installed it in databricks cluster.

def skip(line, cell=None):
'''Skips execution of the current line/cell if line evaluates to True.'''
  if eval(line):
    return

  get_ipython().ex(cell)

def load_ipython_extension(shell):

  '''Registers the skip magic when the extension loads.'''
  shell.register_magic_function(skip, 'line_cell')

def unload_ipython_extension(shell):
  '''Unregisters the skip magic when the extension unloads.'''
  del shell.magics_manager.magics['cell']['skip']

But while I'm trying to load that with extension using
    %load_ext skip_cell
it's throwing an error saying "The module is not an IPython module". Any help or suggestion is appreciated. Thanks.

Body:
Now there is support to run notebooks based on condition

if <condition>:
    dbutils.notebook.run("notebook-name", 60, {"argument": "data", "argument2": "data2", ...})

More details here
https://docs.databricks.com/notebooks/notebook-workflows.html#example


问:
export data as csv in react
I'm trying to export data as a csv in a react app without a library. My code looks like so:

```<code> const download = () => {
    const dummyData = 'rahul,delhi,accountsdept\n';
    const csvContent = `data:text/csv;charset=utf-8,${dummyData}`;
    const encodedURI = encodeURI(csvContent);
    window.open(encodedURI);
}

</code>```

And then I have a button with this download function as an onclick.

```<code>      <button onClick={download}>
        Generate Vehicle Offer Prices
      </button>
</code>```

This is supposed to work in vanilla javascript, is there a reason it doesn't work in react?

Here's a sandbox with the code not working in react sandbox

Here's a link with it working in vanilla js vanilla

答:
You can use the NPM library: https://www.npmjs.com/package/react-csv

Example

```<code>import {CSVLink, CSVDownload} from 'react-csv';

const csvData =[
  ['rahul', 'delhi', 'accountsdept']
];
<CSVLink data={csvData} >Download me</CSVLink>
</code>```

OR

```<code><CSVDownload data={csvData} target="_blank" />
</code>```

Title: export data as csv in react

Body:
I'm trying to export data as a csv in a react app without a library. My code looks like so:

 const download = () => {
    const dummyData = 'rahul,delhi,accountsdept\n';
    const csvContent = `data:text/csv;charset=utf-8,${dummyData}`;
    const encodedURI = encodeURI(csvContent);
    window.open(encodedURI);
}

And then I have a button with this download function as an onclick.

      <button onClick={download}>
        Generate Vehicle Offer Prices
      </button>

This is supposed to work in vanilla javascript, is there a reason it doesn't work in react?

Here's a sandbox with the code not working in react sandbox

Here's a link with it working in vanilla js vanilla

Body:
You can use the NPM library: https://www.npmjs.com/package/react-csv

Example

import {CSVLink, CSVDownload} from 'react-csv';

const csvData =[
  ['rahul', 'delhi', 'accountsdept']
];
<CSVLink data={csvData} >Download me</CSVLink>

OR

<CSVDownload data={csvData} target="_blank" />


问:
Sublime Find and Replace without having to click save
When I do a global search/replace in a project, Sublime will automatically open all the files involved, and not save them. I then have to manually save every single file.

Is there a way to have Sublime automatically save all the changes that have been done, and not open the files that where not previously open?

Thanks in advance for anyone who can help me with this.

http://www.sublimetext.com/forum/viewtopic.php?f=3&p=40348

答: Just performed a similar task with the free Visual Studio Code.  Replace in Files without opening files and fast.  Just made 60k changes in just a few minutes.</p>


问:
List comprehension with different depth dictionaries
I have two dictionaries with the following structure:

Quantity[week][day][time]

Cost[day][time]

The goal is to multiply over a list comprehension the quantity * cost and then sum it. The Cost is the same for all weeks, however, the quantity will vary from week to week. Before adding the week to the first dictionary I had the following:

```<code>sum([Cost[day][time]*Quantity[day][time] for day,time in zip(df,tf)])
</code>```

And it works as intended.

Is there a way to achieve the same with list comprehension now that the Quantity dictionary has one more level?

Edit

I want to have a different result for each week. It should be

sum(week1)+sum(week2)+...+sum(weekn)

答:
Just add a week variable like so:

```<code>[sum(cost[day][time]*q[week][day][time] for day,time in zip(df,tf)) for week in wf]
</code>```

Here is an example with an output:

```<code>q = {'week1': {'day1': {'time1': 21,
                        'time2': 30},
               'day2': {'time1': 21,
                        'time2': 40}},
     'week2': {'day1': {'time1': 22,
                        'time2': 9},
               'day2': {'time1': 23,
                        'time2': 24}}}

cost = {'day1': {'time1': 21,
                'time2': 24},
        'day2': {'time1': 22,
                 'time2': 23}}

wf = ['week1', 'week2']
df = ['day1', 'day2']
tf = ['time1', 'time2']

output = [sum(cost[day][time]*q[week][day][time] for day,time in zip(df,tf)) for week in wf]

print(output)
</code>```

Output:

```<code>[1361, 1014]
</code>```

The output is a list of the sum for each week so the 'week1' sum is 1361 and the 'week2' sum is 1014.

Body:
I have two dictionaries with the following structure:

Quantity[week][day][time]

Cost[day][time]

The goal is to multiply over a list comprehension the quantity * cost and then sum it. The Cost is the same for all weeks, however, the quantity will vary from week to week. Before adding the week to the first dictionary I had the following:

sum([Cost[day][time]*Quantity[day][time] for day,time in zip(df,tf)])

And it works as intended.

Is there a way to achieve the same with list comprehension now that the Quantity dictionary has one more level?

Edit

I want to have a different result for each week. It should be

sum(week1)+sum(week2)+...+sum(weekn)

Body:
Just add a week variable like so:

[sum(cost[day][time]*q[week][day][time] for day,time in zip(df,tf)) for week in wf]

Here is an example with an output:

q = {'week1': {'day1': {'time1': 21,
                        'time2': 30},
               'day2': {'time1': 21,
                        'time2': 40}},
     'week2': {'day1': {'time1': 22,
                        'time2': 9},
               'day2': {'time1': 23,
                        'time2': 24}}}

cost = {'day1': {'time1': 21,
                'time2': 24},
        'day2': {'time1': 22,
                 'time2': 23}}

wf = ['week1', 'week2']
df = ['day1', 'day2']
tf = ['time1', 'time2']

output = [sum(cost[day][time]*q[week][day][time] for day,time in zip(df,tf)) for week in wf]

print(output)

Output:

[1361, 1014]

The output is a list of the sum for each week so the 'week1' sum is 1361 and the 'week2' sum is 1014.


问:
react web3 parse and store a transaction [receipt value] from returnValues
I have a minting Dapp in progress using Hashlips github repo.
I've successfully minted using the dapp and after the mint transaction is complete, I send the transaction receipt into the console log.

Inside the transaction receipt we have the events > transfer > returnValues.
I want to read a specific return value and store that so I can use this value in another function.

Essentially inside returnValues I have stored a tokenID:'xnumberhere' and I need to use that for putting together images which I'll upload to IPFS.

How do I parse through receipt to save specific object data such as TokenID or even a parent such as blockNumber / blockHash

Current functions - see line 23/24 for logging the receipt

See this image of the console log where I want to retrieve tokenID

const claimNFTs = () => {
    let cost = CONFIG.WEI_COST;
    let gasLimit = CONFIG.GAS_LIMIT;
    let totalCostWei = String(cost * mintAmount);
    let totalGasLimit = String(gasLimit * mintAmount);
    console.log("Cost: ", totalCostWei);
    console.log("Gas limit: ", totalGasLimit);
    setFeedback(`Minting your ${CONFIG.NFT_NAME}...`);
    setClaimingNft(true);
    blockchain.smartContract.methods
      .mintNFT(mintAmount)
      .send({
        gasLimit: String(totalGasLimit),
        to: CONFIG.CONTRACT_ADDRESS,
        from: blockchain.account,
        value: totalCostWei,
      })
      .once("error", (err) => {
        console.log(err);
        setFeedback("Sorry, something went wrong please try again later.");
        setClaimingNft(false);
      })
      .then((receipt) => {
        console.log(receipt);
        setFeedback(
          `WOW, the ${CONFIG.NFT_NAME} is yours! go visit Opensea.io to view it.`
        );
        setClaimingNft(false);
        dispatch(fetchData(blockchain.account));
        getData();
      });
  };
```

答:
To retrieve the events response of my Mint transaction, I used the following:

var tokenId = receipt.events.Transfer.returnValues.tokenId
        console.log("Your NFT ID is: " + receipt.events.Transfer.returnValues.tokenId);
```


问:
Python Dataframe - Can't replace text with a number
I am working Bicycle dataset. I want to replace text values in 'weather' column with numbers 1 to 4. This field is an object field. I tried all of these following ways but none seems to work.
There is another field called 'season'. If I apply same code on 'season', my code works fine. Please help.

Sample data:

```<code>    datetime    season  holiday workingday  weather temp    atemp   humidity    windspeed
0   5/10/2012 11:00 Summer  NaN 1   Clear + Few clouds  21.32   25.000  48  35.0008
1   6/9/2012 7:00   Summer  NaN 0   Clear + Few clouds  23.78   27.275  64  7.0015
2   3/6/2011 20:00  Spring  NaN 0   Light Snow, Light Rain  11.48   12.120  100 27.9993
3   10/13/2011 11:00    Winter  NaN 1   Mist + Cloudy   25.42   28.790  83  0.0000
4   6/2/2012 12:00  Summer  NaN 0   Clear + Few clouds  25.42   31.060  43  23.9994
</code>```

I tried following, none worked on 'weather' but when i use same code on 'season' column it works fine.

```<code>test["weather"] = np.where(test["weather"]=="Clear + Few clouds", 1,
(np.where(test["weather"]=="Mist + Cloudy",2,(np.where(test["weather"]=="Light Snow, Light
Rain",3,(np.where(test["weather"]=="Heavy Rain + Thunderstorm",4,0)))))))

PE_weather = [
    (train['weather'] == ' Clear + Few clouds '),
    (train['weather'] =='Mist + Cloudy') ,
    (train['weather'] >= 'Light Snow, Light Rain'),
    (train['weather'] >= 'Heavy Rain + Thunderstorm')]
PE_weather_value = ['1', '2', '3','4']
train['Weather'] = np.select(PE_weather, PE_weather_value)

test.loc[test.weather =='Clear + Few clouds', 'weather']='1'
</code>```

答:
I suggest you make a dictionary to look up the corresponding values and then apply a lookup to the weather column.

weather_lookup = {
    'Clear + Few clouds': 1,
    'Mist + Cloudy': 2,
    'Light Snow, Light Rain': 3,
    'Heavy Rain + Thunderstorm': 4
}

def lookup(w):
    return weather_lookup.get(w, 0)

test['weather'] = test['weather'].apply(lookup)
```
<p>Output:</p>
```           datetime  season  holiday  workingday  weather   temp   atemp     humidity  windspeed
0   5/10/2012 11:00  Summer      NaN           1        1  21.32  25.000           48    35.0008
1     6/9/2012 7:00  Summer      NaN           0        1  23.78  27.275           64     7.0015
2    3/6/2011 20:00  Spring      NaN           0        3  11.48  12.120  100 27.9993        NaN
3  10/13/2011 11:00  Winter      NaN           1        2  25.42  28.790           83     0.0000
4    6/2/2012 12:00  Summer      NaN           0        1  25.42  31.060           43    23.9994
```

Body:
I am working Bicycle dataset. I want to replace text values in 'weather' column with numbers 1 to 4. This field is an object field. I tried all of these following ways but none seems to work.
There is another field called 'season'. If I apply same code on 'season', my code works fine. Please help.

Sample data:

    datetime    season  holiday workingday  weather temp    atemp   humidity    windspeed
0   5/10/2012 11:00 Summer  NaN 1   Clear + Few clouds  21.32   25.000  48  35.0008
1   6/9/2012 7:00   Summer  NaN 0   Clear + Few clouds  23.78   27.275  64  7.0015
2   3/6/2011 20:00  Spring  NaN 0   Light Snow, Light Rain  11.48   12.120  100 27.9993
3   10/13/2011 11:00    Winter  NaN 1   Mist + Cloudy   25.42   28.790  83  0.0000
4   6/2/2012 12:00  Summer  NaN 0   Clear + Few clouds  25.42   31.060  43  23.9994

I tried following, none worked on 'weather' but when i use same code on 'season' column it works fine.

test["weather"] = np.where(test["weather"]=="Clear + Few clouds", 1,
(np.where(test["weather"]=="Mist + Cloudy",2,(np.where(test["weather"]=="Light Snow, Light
Rain",3,(np.where(test["weather"]=="Heavy Rain + Thunderstorm",4,0)))))))

PE_weather = [
    (train['weather'] == ' Clear + Few clouds '),
    (train['weather'] =='Mist + Cloudy') ,
    (train['weather'] >= 'Light Snow, Light Rain'),
    (train['weather'] >= 'Heavy Rain + Thunderstorm')]
PE_weather_value = ['1', '2', '3','4']
train['Weather'] = np.select(PE_weather, PE_weather_value)

test.loc[test.weather =='Clear + Few clouds', 'weather']='1'

Body:
I suggest you make a dictionary to look up the corresponding values and then apply a lookup to the weather column.

weather_lookup = {
    'Clear + Few clouds': 1,
    'Mist + Cloudy': 2,
    'Light Snow, Light Rain': 3,
    'Heavy Rain + Thunderstorm': 4
}

def lookup(w):
    return weather_lookup.get(w, 0)

test['weather'] = test['weather'].apply(lookup)

Output:

           datetime  season  holiday  workingday  weather   temp   atemp     humidity  windspeed
0   5/10/2012 11:00  Summer      NaN           1        1  21.32  25.000           48    35.0008
1     6/9/2012 7:00  Summer      NaN           0        1  23.78  27.275           64     7.0015
2    3/6/2011 20:00  Spring      NaN           0        3  11.48  12.120  100 27.9993        NaN
3  10/13/2011 11:00  Winter      NaN           1        2  25.42  28.790           83     0.0000
4    6/2/2012 12:00  Summer      NaN           0        1  25.42  31.060           43    23.9994


问:
How to create multidimensional array in nested loop while?
I have nested loop while and I'd like to create multidimensional array with some datas from these loops
Output should be look like:

```<code>'productId'=>1
'productImg'=>some_url
'productContent'=> subarray(
     'question1'=>value1
     'answer1'=>value1,
     'question2'=value2,
     'question2'=>value2
)

</code>```

My code with nested while loops

```<code>    if (have_rows('dodaj_pytania_do_produktu')):

        while (have_rows('dodaj_pytania_do_produktu')) : the_row();
            $counter = 1;
            $productID = get_sub_field('nazwa_produktu_faq');
            $productImage = get_sub_field('dodaj_zdjecie');
            $productsData[] = array(
                'productId' => $productID,
                'productImg' => $productImage,

            );
            $product = wc_get_product($productID);
            $productName = $product->get_title();
            // Loop over sub repeater rows.
            if (have_rows('dodaj_pytanie_i_odpowiedz')):
                while (have_rows('dodaj_pytanie_i_odpowiedz')) : the_row();
                    $question = get_sub_field('dodaj_pytanie');
                    $answer = strip_tags(get_sub_field('dodaj_odpowiedz'));
                    $productsData[] = array(
                        'productDesc'=> array(
                        'question' => $question,
                        'answer' => $answer
                        )
                    );
                endwhile;
            endif;
        endwhile;
    else :
        echo "brak faq";
    endif;

    ?>
</code>```

Now my output create wrong subarray not creating a subarray

答:
There is no hurry to create the array, wait till you have everything, so create the new array at the end of the outer loop, and build a temp array for the productContent array, put it all together at then end

```<code>if (have_rows('dodaj_pytania_do_produktu')):

    while (have_rows('dodaj_pytania_do_produktu')) : the_row();

        $productID = get_sub_field('nazwa_produktu_faq');
        $productImage = get_sub_field('dodaj_zdjecie');

        $product = wc_get_product($productID);
        $productName = $product->get_title();
        // Loop over sub repeater rows.
        if (have_rows('dodaj_pytanie_i_odpowiedz')):
            $x = 1; // counter
            $pc = [];
            while (have_rows('dodaj_pytanie_i_odpowiedz')) :
                the_row();
                $question = get_sub_field('dodaj_pytanie');
                $answer = strip_tags(get_sub_field('dodaj_odpowiedz'));

                // build the inner loop content here
                $pc[] = ["question$x" => $question,
                         "answer$x" => $answer
                         ];
                $x++;
            endwhile;

            // put it all together here
            $productsData[] = [
                        'productId' => $productID,
                        'productImg' => $productImage,
                        'productContent = $pc
                ];

        endif;
    endwhile;
else :
    echo "brak faq";
endif;

</code>```

Body:
I have nested loop while and I'd like to create multidimensional array with some datas from these loops
Output should be look like:

'productId'=>1
'productImg'=>some_url
'productContent'=> subarray(
     'question1'=>value1
     'answer1'=>value1,
     'question2'=value2,
     'question2'=>value2
)

My code with nested while loops

    if (have_rows('dodaj_pytania_do_produktu')):

        while (have_rows('dodaj_pytania_do_produktu')) : the_row();
            $counter = 1;
            $productID = get_sub_field('nazwa_produktu_faq');
            $productImage = get_sub_field('dodaj_zdjecie');
            $productsData[] = array(
                'productId' => $productID,
                'productImg' => $productImage,

            );
            $product = wc_get_product($productID);
            $productName = $product->get_title();
            // Loop over sub repeater rows.
            if (have_rows('dodaj_pytanie_i_odpowiedz')):
                while (have_rows('dodaj_pytanie_i_odpowiedz')) : the_row();
                    $question = get_sub_field('dodaj_pytanie');
                    $answer = strip_tags(get_sub_field('dodaj_odpowiedz'));
                    $productsData[] = array(
                        'productDesc'=> array(
                        'question' => $question,
                        'answer' => $answer
                        )
                    );
                endwhile;
            endif;
        endwhile;
    else :
        echo "brak faq";
    endif;

    ?>

Now my output create wrong subarray not creating a subarray

Body:
There is no hurry to create the array, wait till you have everything, so create the new array at the end of the outer loop, and build a temp array for the productContent array, put it all together at then end

if (have_rows('dodaj_pytania_do_produktu')):

    while (have_rows('dodaj_pytania_do_produktu')) : the_row();

        $productID = get_sub_field('nazwa_produktu_faq');
        $productImage = get_sub_field('dodaj_zdjecie');

        $product = wc_get_product($productID);
        $productName = $product->get_title();
        // Loop over sub repeater rows.
        if (have_rows('dodaj_pytanie_i_odpowiedz')):
            $x = 1; // counter
            $pc = [];
            while (have_rows('dodaj_pytanie_i_odpowiedz')) :
                the_row();
                $question = get_sub_field('dodaj_pytanie');
                $answer = strip_tags(get_sub_field('dodaj_odpowiedz'));

                // build the inner loop content here
                $pc[] = ["question$x" => $question,
                         "answer$x" => $answer
                         ];
                $x++;
            endwhile;

            // put it all together here
            $productsData[] = [
                        'productId' => $productID,
                        'productImg' => $productImage,
                        'productContent = $pc
                ];

        endif;
    endwhile;
else :
    echo "brak faq";
endif;


问:
Ionic 5/Capacitor ERR_CLEARTEXT_NOT_PERMITTED in Android
I'm using Capacitor for building the Ionic app. These are the following commands run in order to open the android app in Android Studio.

```<code>npx cap add android
ionic build
npx cap copy
npx cap open android
</code>```

In Android Studio, I ran the build and click on Run after which I see the error net::ERR_CLEARTEXT_NOT_PERMITTED in my device. I have seen various posts having the same error but those are with Cordova build. In my case, I'm not using Cordova for preparing the android app.

Here are few excerpts from my Ionic App.

capacitor.config.jsonfile

```<code>{
  "appId": "com.abc",
  "appName": "abc",
  "bundledWebRuntime": false,
  "npmClient": "npm",
  "webDir": "www",
  "cordova": {
    "preferences": {
      "ScrollEnabled": "false",
      "android-minSdkVersion": "19",
      "BackupWebStorage": "none",
      "SplashMaintainAspectRatio": "true",
      "FadeSplashScreenDuration": "0",
      "SplashShowOnlyFirstTime": "false",
      "SplashScreen": "none",
      "SplashScreenDelay": "0"
    }
  },
  "server": {
    "url": "http://192.168.1.208:8100"
  }
}

</code>```

I also see this error in LogCat of Android Studio

```<code>W/cr_AwContents: Application attempted to call on a destroyed WebView
    java.lang.Throwable
        at org.chromium.android_webview.AwContents.a(PG:127)
        at org.chromium.android_webview.AwContents.a(PG:209)
        at com.android.webview.chromium.WebViewChromium.evaluateJavaScript(PG:8)
        at android.webkit.WebView.evaluateJavascript(WebView.java:1113)
        at com.getcapacitor.cordova.MockCordovaWebViewImpl$1.run(MockCordovaWebViewImpl.java:203)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6923)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)
</code>```

答:
Go into capacitor.config.json and add the cleartext: true prop:

"server": {
  "cleartext": true
}
```

then, run npx cap copy, start the server, re-compile and run the project from your IDE (Xcode/AndroidStudio) again.

Body:
I'm using Capacitor for building the Ionic app. These are the following commands run in order to open the android app in Android Studio.

npx cap add android
ionic build
npx cap copy
npx cap open android

In Android Studio, I ran the build and click on Run after which I see the error net::ERR_CLEARTEXT_NOT_PERMITTED in my device. I have seen various posts having the same error but those are with Cordova build. In my case, I'm not using Cordova for preparing the android app.

Here are few excerpts from my Ionic App.

capacitor.config.jsonfile

{
  "appId": "com.abc",
  "appName": "abc",
  "bundledWebRuntime": false,
  "npmClient": "npm",
  "webDir": "www",
  "cordova": {
    "preferences": {
      "ScrollEnabled": "false",
      "android-minSdkVersion": "19",
      "BackupWebStorage": "none",
      "SplashMaintainAspectRatio": "true",
      "FadeSplashScreenDuration": "0",
      "SplashShowOnlyFirstTime": "false",
      "SplashScreen": "none",
      "SplashScreenDelay": "0"
    }
  },
  "server": {
    "url": "http://192.168.1.208:8100"
  }
}

I also see this error in LogCat of Android Studio

W/cr_AwContents: Application attempted to call on a destroyed WebView
    java.lang.Throwable
        at org.chromium.android_webview.AwContents.a(PG:127)
        at org.chromium.android_webview.AwContents.a(PG:209)
        at com.android.webview.chromium.WebViewChromium.evaluateJavaScript(PG:8)
        at android.webkit.WebView.evaluateJavascript(WebView.java:1113)
        at com.getcapacitor.cordova.MockCordovaWebViewImpl$1.run(MockCordovaWebViewImpl.java:203)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6923)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)

Body:
Go into capacitor.config.json and add the cleartext: true prop:

"server": {
  "cleartext": true
}

then, run npx cap copy, start the server, re-compile and run the project from your IDE (Xcode/AndroidStudio) again.


问:
How to display installed app icon in jetpack compose
In jetpack compose, you can display drawables easily with the Image composable like this:

```<code>Image(painter = painterResource(id = R.drawable.my_drawable))
</code>```

I'm building an app that requires listing all the apps on the device and I need to display their icons. I managed to get the icons using the PackageManager class:

val packageManager = context.packageManager
val installedPackages = packageManager.getInstalledPackages(0)
val packageInfo = installedPackages[0]
val iconId: Int = packageInfo.applicationInfo.icon
```
<p>Then:</p>
```Image(painter = painterResource(id = iconId))
```
<p>But the app crashes everytime. I don't know where the problem is? Any Idea? Thanks</p>
```android.content.res.Resources$NotFoundException: Resource ID #0x7f030001
```

答:
If you're using the Coil library, rememberImagePainter will accept an Any? as its data argument, allowing you to use the Drawable returned from the PackageManager, like so:

```<code>  Image(
    painter = rememberImagePainter(
      data = LocalContext.current.packageManager.getApplicationIcon("com.package.example")
    )
  )
</code>```

Body:
In jetpack compose, you can display drawables easily with the Image composable like this:

Image(painter = painterResource(id = R.drawable.my_drawable))

I'm building an app that requires listing all the apps on the device and I need to display their icons. I managed to get the icons using the PackageManager class:

val packageManager = context.packageManager
val installedPackages = packageManager.getInstalledPackages(0)
val packageInfo = installedPackages[0]
val iconId: Int = packageInfo.applicationInfo.icon

Then:

Image(painter = painterResource(id = iconId))

But the app crashes everytime. I don't know where the problem is? Any Idea? Thanks

android.content.res.Resources$NotFoundException: Resource ID #0x7f030001

Body:
If you're using the Coil library, rememberImagePainter will accept an Any? as its data argument, allowing you to use the Drawable returned from the PackageManager, like so:

  Image(
    painter = rememberImagePainter(
      data = LocalContext.current.packageManager.getApplicationIcon("com.package.example")
    )
  )


问:
is it possible to have a new file for each new day with log4cXX
I know the rollingPolicy parameter for log4cxx config file, but I can't manage to have the config file which can  tell the logger to create a new file each new day, how could I achieve this result ?</p>

答:
Yes. Using rolling style of Composite like this:

```<code>   <appender name="LogAppender" type="log4net.Appender.RollingFileAppender">
    <file type="log4j.Util.PatternString" value="LogFile.log" />
    <appendToFile value="true" />
    <rollingStyle value="Composite" />
    <datePattern value="yyyyMMdd" />
    <maxSizeRollBackups value="7" />
    <maximumFileSize value="100MB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{ISO8601}: [%2thread] %-5level %logger: '%P{network}.%P{node}' %message%newline" />
    </layout>
    </appender>
</code>```

Ref.:

Short introduction to Apache log4cxx

log4net Config Examples

Body:
Yes. Using rolling style of Composite like this:

   <appender name="LogAppender" type="log4net.Appender.RollingFileAppender">
    <file type="log4j.Util.PatternString" value="LogFile.log" />
    <appendToFile value="true" />
    <rollingStyle value="Composite" />
    <datePattern value="yyyyMMdd" />
    <maxSizeRollBackups value="7" />
    <maximumFileSize value="100MB" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{ISO8601}: [%2thread] %-5level %logger: '%P{network}.%P{node}' %message%newline" />
    </layout>
    </appender>

Ref.:

Short introduction to Apache log4cxx

log4net Config Examples


问:
What is int *(&) declaration in C++
I came across this piece of code

```<code>int a = 10;    ---> i)
int *p = &a;   ---> ii)
int *(&q) = p; ---> iii)
</code>```

Here in statement iii),  q seems to look like a pointer having the same value as p(after resolving)(reason). However, while we are still defining, &q tries to get the address of q which hasn't yet been created. So, how do you logically explain this in pointer terms? Any resources to explain this is also appreciated.

NOTE: I did compile and run the code, q points to a.

答:
int *(&q) declares a reference to a pointer. The parenthesis achieves nothing and it could as well be written as int *&q. It's a rather pointless (pun intended) way of creating a name alias of a pointer. Pretty much the same thing as

```<code>int a;
int& ref = a;
</code>```

But instead *& creates a reference to the pointer itself, rather than at to the data it points at.

Normally one doesn't mix references and pointers in the same context, or at least I can't come up with a sane use-case for this, but it's valid syntax.

Title: What is int *(&) declaration in C++

Body:
I came across this piece of code

int a = 10;    ---> i)
int *p = &a;   ---> ii)
int *(&q) = p; ---> iii)

Here in statement iii),  q seems to look like a pointer having the same value as p(after resolving)(reason). However, while we are still defining, &q tries to get the address of q which hasn't yet been created. So, how do you logically explain this in pointer terms? Any resources to explain this is also appreciated.

NOTE: I did compile and run the code, q points to a.

Body:
int *(&q) declares a reference to a pointer. The parenthesis achieves nothing and it could as well be written as int *&q. It's a rather pointless (pun intended) way of creating a name alias of a pointer. Pretty much the same thing as

int a;
int& ref = a;

But instead *& creates a reference to the pointer itself, rather than at to the data it points at.

Normally one doesn't mix references and pointers in the same context, or at least I can't come up with a sane use-case for this, but it's valid syntax.


问:
What does System.out.printf( "%-15s%03d\n", s1, x) do?
```<code>String s1=sc.next();
int x=sc.nextInt();
System.out.printf( "%-15s%03d\n", s1, x);
</code>```

Can someone explain the part inside the 'printf' braces?

答:
("%-15s%03d%n", s1, x)

%: used as a formatter.

'-': minus sign used for left indentation of the string.

15s: here 15 denotes the string's minimum field width 15.

'0': pads the extra 0s in the integer.

3d: here 3 denotes integers minimum field width 3.

%n: prints the new line.

Hope, this helps!

Body:
String s1=sc.next();
int x=sc.nextInt();
System.out.printf( "%-15s%03d\n", s1, x);

Can someone explain the part inside the 'printf' braces?


问:
Dump raw XML to debug Grails REST calls
We need to dump the raw XML for troubleshooting data dependant issues on a Grails 1.2 app. In the UrlMappings we have "parseRequest:true". The following does not get me what I'm looking for, any other options? Note that we need this on a production machine, so fiddler or similar proxy based solutions suitable for development are not an option</p>

```<code>def beforeInterceptor = {
    println "#"*99
    println "Executing action $actionName with params=$params"
    println request.inputStream.dump()
    //println request.inputStream.text // java.io.IOException: Stream closed
    println request.XML
}
</code>```

答:
Turns out that request.XML is of type groovy.util.slurpersupport.NodeChild and it has a crappy toString() override. So the solution is here, put this in your bootstrap

```<code>NodeChild.metaClass.toXmlString = {
    def self = delegate
    new StreamingMarkupBuilder().bind {
        delegate.mkp.xmlDeclaration() // Use this if you want an XML declaration
        delegate.out << self
    }.toString()
}
</code>```

And this in the controller:

```<code>def beforeInterceptor = {
    println "#"*99
    log.info "REST CALL [${request.serverName}${request.forwardURI}?${request.queryString}] with [$request.method] action [$actionName]"
    println request.XML.toXmlString()
}
</code>```

Title: Dump raw XML to debug Grails REST calls

Body:
We need to dump the raw XML for troubleshooting data dependant issues on a Grails 1.2 app. In the UrlMappings we have "parseRequest:true". The following does not get me what I'm looking for, any other options? Note that we need this on a production machine, so fiddler or similar proxy based solutions suitable for development are not an option

def beforeInterceptor = {
    println "#"*99
    println "Executing action $actionName with params=$params"
    println request.inputStream.dump()
    //println request.inputStream.text // java.io.IOException: Stream closed
    println request.XML
}

Body:
Turns out that request.XML is of type groovy.util.slurpersupport.NodeChild and it has a crappy toString() override. So the solution is here, put this in your bootstrap

NodeChild.metaClass.toXmlString = {
    def self = delegate
    new StreamingMarkupBuilder().bind {
        delegate.mkp.xmlDeclaration() // Use this if you want an XML declaration
        delegate.out << self
    }.toString()
}

And this in the controller:

def beforeInterceptor = {
    println "#"*99
    log.info "REST CALL [${request.serverName}${request.forwardURI}?${request.queryString}] with [$request.method] action [$actionName]"
    println request.XML.toXmlString()
}


问:
Is there a simpler way than to pass a 40-object table?
I'm running these requests for numbers with five sub-cases which have four sub-cases each. There are over 200 of these cases, of which just one is shown below, so it would be several thousand lines of code. (This is example code, the numbers would not all be the same, of course.)

```<code>  elseif case1 then
                      if u <= 0 then if w == 0 then return B(2,3), B(3,4)
                                 elseif w == 1 then return B(2,3), B(3,4)
                                 elseif w == 2 then return B(2,3), B(3,4)
                                 elseif w >= 3 then return B(2,3), B(3,4)
               elseif if u == 1 then return LimitCheck(if w == 0 then return B(2,3), B(3,4)
                                 elseif w == 1 then return B(2,3), B(3,4)
                                 elseif w == 2 then return B(2,3), B(3,4)
                                 elseif w >= 3 then return B(2,3), B(3,4)
               elseif if u == 2 then return LimitCheck(if w == 0 then return B(2,3), B(3,4)
                                 elseif w == 1 then return B(2,3), B(3,4)
                                 elseif w == 2 then return B(2,3), B(3,4)
                                 elseif w >= 3 then return B(2,3), B(3,4)
               elseif if u == 3 then return LimitCheck(if w == 0 then return B(2,3), B(3,4)
                                 elseif w == 1 then return B(2,3), B(3,4)
                                 elseif w == 2 then return B(2,3), B(3,4)
                                 elseif w >= 3 then return B(2,3), B(3,4)
               elseif if u == 4 then return LimitCheck(if w == 0 then return B(2,3), B(3,4)
                                 elseif w == 1 then return B(2,3), B(3,4)
                                 elseif w == 2 then return B(2,3), B(3,4)
                                 elseif w >= 3 then return B(2,3), B(3,4)
</code>```

I thought I'd be clever and compartmentalize the code that repeats, let sub-functions take apart the cases:

```<code>  local function LimitCheck(arg)
    if w <= 0 then return arg[1], arg[2]
    elseif w == 1 then return arg[3], arg[4]
    elseif w == 2 then return arg[5], arg[6]
    elseif w >= 3 then return arg[7], arg[8]
    end
  end
  local function Limits(arg)
    if u == 0 then return LimitCheck({arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],arg[7],arg[8],})
    elseif u == 1 then return LimitCheck({arg[9],arg[10],arg[11],arg[12],arg[13],arg[14],arg[15],arg[16],})
    elseif u == 2 then return LimitCheck({arg[17],arg[18],arg[19],arg[20],arg[21],arg[22],arg[23],arg[24],})
    elseif u == 3 then return LimitCheck({arg[25],arg[26],arg[27],arg[28],arg[29],arg[30],arg[31],arg[32],})
    elseif u == 4 then return LimitCheck({arg[33],arg[34],arg[35],arg[36],arg[37],arg[38],arg[39],arg[40]})
    end
  end
</code>```

And then have the main function return what it needs to know in one bulk:

```<code>  elseif case1 then
    return Limits({B(5,6),B(7,8),   B(5,6),B(5,6),  B(5,6),B(5,6),  B(5,6),B(5,6),
                   B(5,6),B(5,6),   B(5,6),B(5,6),  B(5,6),B(5,6),  B(5,6),B(5,6),
                   B(5,6),B(5,6),   B(5,6),B(5,6),  B(5,6),B(5,6),  B(5,6),B(5,6),
                   B(5,6),B(5,6),   B(5,6),B(5,6),  B(5,6),B(5,6),  B(5,6),B(5,6),
                   B(5,6),B(5,6),   B(5,6),B(5,6),  B(5,6),B(5,6),  B(5,6),B(5,6)})
</code>```

Problem is, this is a 40-entry table object that is passed every time, quite a bulky undertaking for a request that may happen 100 times a second. And it returns a bunch of stuff that isn't used.
I wonder if there is a resource-saving way to do this.

答:
Here's an example of how to do this using a lookup table.
You can hardcode it or build it from code if the structure allows it.</p>
```<code>local LUT = {
  [0] = {
    [0] = "a",
    [1] = "b",
    [2] = "c",
    [3] = "d",
  },
  [1] = {
    [0] = "e",
    [1] = "f",
    [2] = "g",
    [3] = "h",
  },
  [2] = {
    [0] = "i",
    [1] = "j",
    [2] = "k",
    [3] = "l",
  },
  [3] = {
    [0] = "m",
    [1] = "n",
    [2] = "o",
    [3] = "p",
  },
  [4] = {
    [0] = "q",
    [1] = "r",
    [2] = "s",
    [3] = "t",
  },
}

function lookup(u, w)
  -- we only accept u <= 5
  if math.type(u) ~= "integer" or u > 4
   -- and w >= 0
    or math.type(w) ~= "integer" or w < 0 then
    return
  end
  return LUT[math.max(0, u)][math.min(3, w)]
end

print(lookup(-5, 3))
</code>```

Body:
I'm running these requests for numbers with five sub-cases which have four sub-cases each. There are over 200 of these cases, of which just one is shown below, so it would be several thousand lines of code. (This is example code, the numbers would not all be the same, of course.)

  elseif case1 then
                      if u <= 0 then if w == 0 then return B(2,3), B(3,4)
                                 elseif w == 1 then return B(2,3), B(3,4)
                                 elseif w == 2 then return B(2,3), B(3,4)
                                 elseif w >= 3 then return B(2,3), B(3,4)
               elseif if u == 1 then return LimitCheck(if w == 0 then return B(2,3), B(3,4)
                                 elseif w == 1 then return B(2,3), B(3,4)
                                 elseif w == 2 then return B(2,3), B(3,4)
                                 elseif w >= 3 then return B(2,3), B(3,4)
               elseif if u == 2 then return LimitCheck(if w == 0 then return B(2,3), B(3,4)
                                 elseif w == 1 then return B(2,3), B(3,4)
                                 elseif w == 2 then return B(2,3), B(3,4)
                                 elseif w >= 3 then return B(2,3), B(3,4)
               elseif if u == 3 then return LimitCheck(if w == 0 then return B(2,3), B(3,4)
                                 elseif w == 1 then return B(2,3), B(3,4)
                                 elseif w == 2 then return B(2,3), B(3,4)
                                 elseif w >= 3 then return B(2,3), B(3,4)
               elseif if u == 4 then return LimitCheck(if w == 0 then return B(2,3), B(3,4)
                                 elseif w == 1 then return B(2,3), B(3,4)
                                 elseif w == 2 then return B(2,3), B(3,4)
                                 elseif w >= 3 then return B(2,3), B(3,4)

I thought I'd be clever and compartmentalize the code that repeats, let sub-functions take apart the cases:

  local function LimitCheck(arg)
    if w <= 0 then return arg[1], arg[2]
    elseif w == 1 then return arg[3], arg[4]
    elseif w == 2 then return arg[5], arg[6]
    elseif w >= 3 then return arg[7], arg[8]
    end
  end
  local function Limits(arg)
    if u == 0 then return LimitCheck({arg[1],arg[2],arg[3],arg[4],arg[5],arg[6],arg[7],arg[8],})
    elseif u == 1 then return LimitCheck({arg[9],arg[10],arg[11],arg[12],arg[13],arg[14],arg[15],arg[16],})
    elseif u == 2 then return LimitCheck({arg[17],arg[18],arg[19],arg[20],arg[21],arg[22],arg[23],arg[24],})
    elseif u == 3 then return LimitCheck({arg[25],arg[26],arg[27],arg[28],arg[29],arg[30],arg[31],arg[32],})
    elseif u == 4 then return LimitCheck({arg[33],arg[34],arg[35],arg[36],arg[37],arg[38],arg[39],arg[40]})
    end
  end

And then have the main function return what it needs to know in one bulk:

  elseif case1 then
    return Limits({B(5,6),B(7,8),   B(5,6),B(5,6),  B(5,6),B(5,6),  B(5,6),B(5,6),
                   B(5,6),B(5,6),   B(5,6),B(5,6),  B(5,6),B(5,6),  B(5,6),B(5,6),
                   B(5,6),B(5,6),   B(5,6),B(5,6),  B(5,6),B(5,6),  B(5,6),B(5,6),
                   B(5,6),B(5,6),   B(5,6),B(5,6),  B(5,6),B(5,6),  B(5,6),B(5,6),
                   B(5,6),B(5,6),   B(5,6),B(5,6),  B(5,6),B(5,6),  B(5,6),B(5,6)})

Problem is, this is a 40-entry table object that is passed every time, quite a bulky undertaking for a request that may happen 100 times a second. And it returns a bunch of stuff that isn't used.
I wonder if there is a resource-saving way to do this.

Body:
Here's an example of how to do this using a lookup table.
You can hardcode it or build it from code if the structure allows it.

local LUT = {
  [0] = {
    [0] = "a",
    [1] = "b",
    [2] = "c",
    [3] = "d",
  },
  [1] = {
    [0] = "e",
    [1] = "f",
    [2] = "g",
    [3] = "h",
  },
  [2] = {
    [0] = "i",
    [1] = "j",
    [2] = "k",
    [3] = "l",
  },
  [3] = {
    [0] = "m",
    [1] = "n",
    [2] = "o",
    [3] = "p",
  },
  [4] = {
    [0] = "q",
    [1] = "r",
    [2] = "s",
    [3] = "t",
  },
}

function lookup(u, w)
  -- we only accept u <= 5
  if math.type(u) ~= "integer" or u > 4
   -- and w >= 0
    or math.type(w) ~= "integer" or w < 0 then
    return
  end
  return LUT[math.max(0, u)][math.min(3, w)]
end

print(lookup(-5, 3))


问:
Python: flask-sqlalchemy fill table using csv as source without listing every column of table
I want to begin by stating that I know there are a lot of similar questions on this site, and the solutions do work, my issue is that, at least the ones I could find are all variations of something like this:

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Example(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    Column1 = db.Column(db.String(100))
    Column2 = db.Column(db.String(100))
    Column3 = db.Column(db.String(100))

import csv

with open("source_file.csv") as f:
    reader = csv.reader(f)
    next(reader)
    for i in reader:
        new_entry = Example(
        Column1 = i[0],
        Column2 = i[1],
        Column3 = i[2])
        db.session.add(new_entry)
        db.session.commit()

```

This works, but it has a couple of issues, for instance if the table in question has n amount of columns, I need to write nx2 amount of lines, once to define the table and the second to fill the contents of the table.

This is sort of ok with small tables but if you are working with tables that have 100+ columns this gets ridiculous fast.
Also, if for any reason the table structure changes even a little bit, it gets impossible to maintain.

So, I’m asking for help for a better way to do it, if this is still a duplicate question I apologize and ask only for guidance, I found solutions but only for SQLAlchemy, they did not work when I tried them in FlaskSQlAlchemy.

答:
Assuming that source_file.csv header items are the same as column names in the table you can do something like this:

import csv

with open("source_file.csv") as f:
    reader = csv.reader(f)
    header = next(reader)
    for i in reader:
        kwargs = {column: value for column, value in zip(header, i)}
        new_entry = Example(**kwargs)
        db.session.add(new_entry)
        db.session.commit()
```
<p>You can also check whether header item exist in in columns set:</p>
<pre class="lang-py prettyprint-override"><code>columns = [column.key for column in Example.__table__.columns]
kwargs = {header_item: value for header_item, value in zip(header, i) if column in columns}
</code>```

Body:
I want to begin by stating that I know there are a lot of similar questions on this site, and the solutions do work, my issue is that, at least the ones I could find are all variations of something like this:

from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
class Example(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    Column1 = db.Column(db.String(100))
    Column2 = db.Column(db.String(100))
    Column3 = db.Column(db.String(100))

import csv

with open("source_file.csv") as f:
    reader = csv.reader(f)
    next(reader)
    for i in reader:
        new_entry = Example(
        Column1 = i[0],
        Column2 = i[1],
        Column3 = i[2])
        db.session.add(new_entry)
        db.session.commit()

This works, but it has a couple of issues, for instance if the table in question has n amount of columns, I need to write nx2 amount of lines, once to define the table and the second to fill the contents of the table.

This is sort of ok with small tables but if you are working with tables that have 100+ columns this gets ridiculous fast.
Also, if for any reason the table structure changes even a little bit, it gets impossible to maintain.

So, I’m asking for help for a better way to do it, if this is still a duplicate question I apologize and ask only for guidance, I found solutions but only for SQLAlchemy, they did not work when I tried them in FlaskSQlAlchemy.

Body:
Assuming that source_file.csv header items are the same as column names in the table you can do something like this:

import csv

with open("source_file.csv") as f:
    reader = csv.reader(f)
    header = next(reader)
    for i in reader:
        kwargs = {column: value for column, value in zip(header, i)}
        new_entry = Example(**kwargs)
        db.session.add(new_entry)
        db.session.commit()

You can also check whether header item exist in in columns set:

columns = [column.key for column in Example.__table__.columns]
kwargs = {header_item: value for header_item, value in zip(header, i) if column in columns}


问:
How to reduce the size of an application built with Jetpack Compose?
I created an empty application on Jetpack Compose, enabled the minifyEnabled = true flag in it and compiled the release apk. Its size turned out to be 1.7 mb, which, in my opinion, is a lot for an empty application.

Can I somehow reduce the size of the application?

```<code>implementation "androidx.compose.ui:ui:$compose_version"
implementation 'androidx.compose.material:material:1.0.0-alpha10'
implementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.0-alpha06'
</code>```

答:
As highlighted in https://twitter.com/vinaygaba/status/1488561816179331074, Compose apps should use:

```<code>debugImplementation "androidx.compose.ui:ui-tooling:{{ composeVersion }}"
implementation "androidx.compose.ui:ui-tooling-preview:{{ composeVersion }}"
</code>```

Instead of:

```<code>implementation "androidx.compose.ui:ui-tooling:{{ composeVersion }}"
</code>```

By doing so, you are going to save a few hundred kbs from your app size.

Body:
I created an empty application on Jetpack Compose, enabled the minifyEnabled = true flag in it and compiled the release apk. Its size turned out to be 1.7 mb, which, in my opinion, is a lot for an empty application.

Can I somehow reduce the size of the application?

implementation "androidx.compose.ui:ui:$compose_version"
implementation 'androidx.compose.material:material:1.0.0-alpha10'
implementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.0-alpha06'

Body:
As highlighted in https://twitter.com/vinaygaba/status/1488561816179331074, Compose apps should use:

debugImplementation "androidx.compose.ui:ui-tooling:{{ composeVersion }}"
implementation "androidx.compose.ui:ui-tooling-preview:{{ composeVersion }}"

Instead of:

implementation "androidx.compose.ui:ui-tooling:{{ composeVersion }}"

By doing so, you are going to save a few hundred kbs from your app size.


问:
Cookies sent from backend but not set correctly on frontend
I'm running into this issue:

localhost:3000 (React App)

localhost:9000 (Nodejs Backend)

I was able to send the request from postman and receive the cookies there, however in the frontend when I check for the cookies in the browser there is nothing.

The cookies are not visible under the Application > Cookies tab.

The code I use for handing signups and sending the cookie:

```<code>// requirements
const User = require('../models/User');
const jwt = require('jsonwebtoken');

// handle errors
const handleErrors = (err) => {
    console.log(err.message, err.code);
    let errors = { first_name: '', last_name: '', email: '', password: '' };

    // duplicate error code
    if (err.code === 11000) {
        errors.email = 'That email is already registered';
        return errors;
    }

    // validation errors
    if (err.message.includes('User validation failed')) {
        Object.values(err.errors).forEach(({ properties }) => {
            errors[properties.path] = properties.message;
        });
    }
    return errors;
}

const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
    return jwt.sign({ id }, 'Dummy Secret', {
        expiresIn: maxAge
    });
}

// module exporting

module.exports.signup_post = async (req, res) => {
    const { first_name, last_name, email, password } = req.body;

    try {
        const user = await User.create({ first_name, last_name, email, password });
        const token = createToken(user._id);
        res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 });
        res.status(201).json({ user: user._id });
    }
    catch (err) {
        const errors = handleErrors(err);
        res.status(400).json({ errors });
    }
};
</code>```

If anyone could guide me on what to do I'd be grateful

UPDATE:
I did some testing and the results were as follows:
when I ran this code in the main app.js on the backend and send a request from the front end, the cookies were still messed up, so it might very well be the frontend.

```<code>app.get('/set-cookies', (req, res) => {
    res.cookie('newUesr', false);
    res.cookie('isEmployee', true, { maxAge: 1000 * 60 * 60 * 24, httpOnly: true});

    res.send('you got the cookies!');
});

app.get('/read-cookies', (req, res) => {
const

});
</code>```

But when I do it through my controllers in the previously shown code it gets stuck in set cookies as shown in this picture

答:
Here's a helpful link for understanding httpOnly cookies and alternate methods.
How to get HTTP-only cookie in React?</p>

Body:
I'm running into this issue:

localhost:3000 (React App)

localhost:9000 (Nodejs Backend)

I was able to send the request from postman and receive the cookies there, however in the frontend when I check for the cookies in the browser there is nothing.

The cookies are not visible under the Application > Cookies tab.

The code I use for handing signups and sending the cookie:

// requirements
const User = require('../models/User');
const jwt = require('jsonwebtoken');

// handle errors
const handleErrors = (err) => {
    console.log(err.message, err.code);
    let errors = { first_name: '', last_name: '', email: '', password: '' };

    // duplicate error code
    if (err.code === 11000) {
        errors.email = 'That email is already registered';
        return errors;
    }

    // validation errors
    if (err.message.includes('User validation failed')) {
        Object.values(err.errors).forEach(({ properties }) => {
            errors[properties.path] = properties.message;
        });
    }
    return errors;
}

const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
    return jwt.sign({ id }, 'Dummy Secret', {
        expiresIn: maxAge
    });
}

// module exporting

module.exports.signup_post = async (req, res) => {
    const { first_name, last_name, email, password } = req.body;

    try {
        const user = await User.create({ first_name, last_name, email, password });
        const token = createToken(user._id);
        res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 });
        res.status(201).json({ user: user._id });
    }
    catch (err) {
        const errors = handleErrors(err);
        res.status(400).json({ errors });
    }
};

If anyone could guide me on what to do I'd be grateful

UPDATE:
I did some testing and the results were as follows:
when I ran this code in the main app.js on the backend and send a request from the front end, the cookies were still messed up, so it might very well be the frontend.

app.get('/set-cookies', (req, res) => {
    res.cookie('newUesr', false);
    res.cookie('isEmployee', true, { maxAge: 1000 * 60 * 60 * 24, httpOnly: true});

    res.send('you got the cookies!');
});

app.get('/read-cookies', (req, res) => {
const

});

But when I do it through my controllers in the previously shown code it gets stuck in set cookies as shown in this picture


问:
How to show which masks are assign to columns
I'm unable to change a mask because it is assigned to a column, but I'm having an issue identifying that column.

In SNOWFLAKE, how do I show which masks are assign to columns?

答:
To determine the data masking policy usage you could use:

POLICY_REFERENCES function:

Returns a row for each object that has the specified policy assigned to the object or returns a row for each policy assigned to the specified object.

or

POLICY_REFERENCES View:

This Account Usage view can be used to identify the objects and columns on which a masking policy is set or the tables and views in which a row access policy is set.

```<code>select *
from table(information_schema.policy_references(
           policy_name => 'my_db.my_schema.ssn_mask'));

select *
from account_usage.policy_references;
</code>```

Body:
To determine the data masking policy usage you could use:

POLICY_REFERENCES function:

Returns a row for each object that has the specified policy assigned to the object or returns a row for each policy assigned to the specified object.

or

POLICY_REFERENCES View:

This Account Usage view can be used to identify the objects and columns on which a masking policy is set or the tables and views in which a row access policy is set.

select *
from table(information_schema.policy_references(
           policy_name => 'my_db.my_schema.ssn_mask'));

select *
from account_usage.policy_references;


问:
Return a formula with evaluated members
I'm working on a function that returns the formula of its input cell, replacing all references to other cells with the cells' values. My current implementation works fine unless the input cell contains absolute references, which is what I'd like to improve upon.

Currently, I extract the Range.FormulaR1C1 property of the input cell and replace all addresses with values of their respective cells. It's fairly easy to recognize relative addresses, because they contain square brackets, i.e. []. The general format is R[rN]C[cN] with rN and cN denoting relative row or column numbers (integer values) - if either of these equals zero, it gets omitted along with the brackets, so there's two possibilities for a position in a formula to be the start of an address:

Next two characters are "R["

Next three characters are "RC["
(Self referencing is not allowed, so we can exclude "RC".)

When we introduce absolute addresses, the brackets disappear and the general address format becomes RrNCcN. Now it gets more complicated to recognize an address and I'd prefer to stick to the two simple rules R[ and RC[. If I could convert absolute cell references to relative and return them in the R1C1 format, I could leave the current implementation unchanged.

I need to get a cell's formula in the R1C1 format, with all absolute cell references replaced by relative ones. It's theoretically very simple to remove absolute references from an address in the A1 format (Range.Formula property) by just removing all "$" signs. Alas, I don't know how to convert the address back to R1C1 format after doing that. Below is a naive implementation which fails on the penultimate row, but captures the idea I think. I have no clue on how to proceed or if it's even possible to do this as simply as I imagine.

```<code>Function returnRelativeFormulaR1C1(refCell As Range) As String
Dim refAddress As String, addressLength As Integer, posRow As Integer, posCol As Integer, iColNr As Integer
refAddress = refCell.Address(ReferenceStyle:=xlR1C1)
addressLength = Len(refAddress)
iColNr = InStr(2, refAddress, "C")
posRow = Val(Mid(refAddress, 2, iColNr - 1)) ' Begin at 2, because there's always "R" at the beginning
posCol = Val(Mid(refAddress, iColNr + 1, addressLength - iColNr))

Dim formulaText As String
formulaText = Cells(posRow, posCol).Formula ' Get formula in A1 format

Dim formulaTextRelative As String
formulaTextRelative = Replace(formulaText, "$", "") ' Remove "$" signs, i.e. convert absolute references to relative

Dim convRange As Range
Set convRange = refCell
convRange.Cells(1, 1).Formula = formulaTextRelative ' Assign the converted formula to a virtual cell? The code fails here.

returnRelativeFormulaR1C1 = convRange.Cells(1, 1).FormulaR1C1 ' If the previous row worked, this should then take care of the conversion back to R1C1 format.

End Function
</code>```

答:
Many thanks to chris neilsen, ConvertFormula was just what I needed.

Corrected implementation of the conversion:

```<code>Function returnRelativeFormulaR1C1(refCell As Range) As String
Dim refAddress As String, addressLength As Integer, posRow As Integer, posCol As Integer, iColNr As Integer
refAddress = refCell.Address(ReferenceStyle:=xlR1C1)
addressLength = Len(refAddress)
iColNr = InStr(2, refAddress, "C")
posRow = Val(Mid(refAddress, 2, iColNr - 1)) ' Begin at 2, because there's always "R" at the beginning
posCol = Val(Mid(refAddress, iColNr + 1, addressLength - iColNr))

Dim formulaTextA1 As String
formulaTextA1 = Cells(posRow, posCol).Formula ' Get formula in A1 format

Dim formulaTextA1Relative As String
formulaTextA1Relative = Replace(formulaTextA1, "$", "") ' Remove "$" signs, i.e. convert absolute references to relative
returnRelativeFormulaR1C1 = Application.ConvertFormula(Formula:=formulaTextA1Relative, fromReferenceStyle:=xlA1, toReferenceStyle:=xlR1C1, RelativeTo:=refCell) ' Convert back to R1C1

End Function
</code>```

Title: Return a formula with evaluated members

Body:
I'm working on a function that returns the formula of its input cell, replacing all references to other cells with the cells' values. My current implementation works fine unless the input cell contains absolute references, which is what I'd like to improve upon.

Currently, I extract the Range.FormulaR1C1 property of the input cell and replace all addresses with values of their respective cells. It's fairly easy to recognize relative addresses, because they contain square brackets, i.e. []. The general format is R[rN]C[cN] with rN and cN denoting relative row or column numbers (integer values) - if either of these equals zero, it gets omitted along with the brackets, so there's two possibilities for a position in a formula to be the start of an address:

Next two characters are "R["

Next three characters are "RC["
(Self referencing is not allowed, so we can exclude "RC".)

When we introduce absolute addresses, the brackets disappear and the general address format becomes RrNCcN. Now it gets more complicated to recognize an address and I'd prefer to stick to the two simple rules R[ and RC[. If I could convert absolute cell references to relative and return them in the R1C1 format, I could leave the current implementation unchanged.

I need to get a cell's formula in the R1C1 format, with all absolute cell references replaced by relative ones. It's theoretically very simple to remove absolute references from an address in the A1 format (Range.Formula property) by just removing all "$" signs. Alas, I don't know how to convert the address back to R1C1 format after doing that. Below is a naive implementation which fails on the penultimate row, but captures the idea I think. I have no clue on how to proceed or if it's even possible to do this as simply as I imagine.

Function returnRelativeFormulaR1C1(refCell As Range) As String
Dim refAddress As String, addressLength As Integer, posRow As Integer, posCol As Integer, iColNr As Integer
refAddress = refCell.Address(ReferenceStyle:=xlR1C1)
addressLength = Len(refAddress)
iColNr = InStr(2, refAddress, "C")
posRow = Val(Mid(refAddress, 2, iColNr - 1)) ' Begin at 2, because there's always "R" at the beginning
posCol = Val(Mid(refAddress, iColNr + 1, addressLength - iColNr))

Dim formulaText As String
formulaText = Cells(posRow, posCol).Formula ' Get formula in A1 format

Dim formulaTextRelative As String
formulaTextRelative = Replace(formulaText, "$", "") ' Remove "$" signs, i.e. convert absolute references to relative

Dim convRange As Range
Set convRange = refCell
convRange.Cells(1, 1).Formula = formulaTextRelative ' Assign the converted formula to a virtual cell? The code fails here.

returnRelativeFormulaR1C1 = convRange.Cells(1, 1).FormulaR1C1 ' If the previous row worked, this should then take care of the conversion back to R1C1 format.

End Function

Body:
Many thanks to chris neilsen, ConvertFormula was just what I needed.

Corrected implementation of the conversion:

Function returnRelativeFormulaR1C1(refCell As Range) As String
Dim refAddress As String, addressLength As Integer, posRow As Integer, posCol As Integer, iColNr As Integer
refAddress = refCell.Address(ReferenceStyle:=xlR1C1)
addressLength = Len(refAddress)
iColNr = InStr(2, refAddress, "C")
posRow = Val(Mid(refAddress, 2, iColNr - 1)) ' Begin at 2, because there's always "R" at the beginning
posCol = Val(Mid(refAddress, iColNr + 1, addressLength - iColNr))

Dim formulaTextA1 As String
formulaTextA1 = Cells(posRow, posCol).Formula ' Get formula in A1 format

Dim formulaTextA1Relative As String
formulaTextA1Relative = Replace(formulaTextA1, "$", "") ' Remove "$" signs, i.e. convert absolute references to relative
returnRelativeFormulaR1C1 = Application.ConvertFormula(Formula:=formulaTextA1Relative, fromReferenceStyle:=xlA1, toReferenceStyle:=xlR1C1, RelativeTo:=refCell) ' Convert back to R1C1

End Function


问:
how to create a dictionary whose keys are (i,j) integer pairs with i < j
I intend to create thousands of integer pairs, number them and store them in a dictionary. Given a number n, my goal is to generate every (i,j) pair such that i<j.

For instance, if n=4, the pairs will be then the dictionary will look like {(0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 2): 3, (1, 3): 4, (2, 3): 5}.

I can generate this dictionary by using nested for loops, but it is not efficient when n is large. Could someone help me to perform this operation quicker than I currently do?

```<code>d={}
n=4
temp =0

for i in range(n):
    for j in range(n):
        if i <j:
            d.update({(i,j): temp})
            temp+= 1
</code>```

答:
Taking it a step further:

```<code>from itertools import combinations, count

n = 4
out = dict(zip(combinations(range(n), 2), count()))
</code>```

Try it online!

Seems to be slightly faster. Test with n = 1000:

```<code>191.0 ms  mozway
176.2 ms  kelly
186.8 ms  mozway
177.8 ms  kelly
185.2 ms  mozway
178.6 ms  kelly
</code>```

Code (Try it online!):

```<code>from timeit import repeat
from itertools import combinations, count

def mozway():
    return {k:v for v,k in enumerate(combinations(range(n), 2))}

def kelly():
    return dict(zip(combinations(range(n), 2), count()))

n = 1000
for func in [mozway, kelly] * 3:
    t = min(repeat(func, number=1))
    print('%5.1f ms ' % (t * 1e3), func.__name__)
</code>```

Body:
I intend to create thousands of integer pairs, number them and store them in a dictionary. Given a number n, my goal is to generate every (i,j) pair such that i<j.

For instance, if n=4, the pairs will be then the dictionary will look like {(0, 1): 0, (0, 2): 1, (0, 3): 2, (1, 2): 3, (1, 3): 4, (2, 3): 5}.

I can generate this dictionary by using nested for loops, but it is not efficient when n is large. Could someone help me to perform this operation quicker than I currently do?

d={}
n=4
temp =0

for i in range(n):
    for j in range(n):
        if i <j:
            d.update({(i,j): temp})
            temp+= 1

Body:
Taking it a step further:

from itertools import combinations, count

n = 4
out = dict(zip(combinations(range(n), 2), count()))

Try it online!

Seems to be slightly faster. Test with n = 1000:

191.0 ms  mozway
176.2 ms  kelly
186.8 ms  mozway
177.8 ms  kelly
185.2 ms  mozway
178.6 ms  kelly

Code (Try it online!):

from timeit import repeat
from itertools import combinations, count

def mozway():
    return {k:v for v,k in enumerate(combinations(range(n), 2))}

def kelly():
    return dict(zip(combinations(range(n), 2), count()))

n = 1000
for func in [mozway, kelly] * 3:
    t = min(repeat(func, number=1))
    print('%5.1f ms ' % (t * 1e3), func.__name__)


问:
Lisp: How to get the reference (not the value) of an element in a 2D Matrix represented as a List of Lists?
I am trying to reference a specific element in a 2D Matrix represented as list of Lists so I can set that specific element to 0. However, when I run the code below:

```<code>(defvar listOfLists '( (1 3) (2 6) ))
(defvar referenceToTopLeftCorner (nth 0 (nth 0 listOfLists)))
(setq referenceToTopLeftCorner 0)
(print (format nil "listsOfLists = ~a" listOfLists))
</code>```

The following output is:

""listsOfLists = ((1 3) (2 6))"

This seems strange, as I thought that the nth method can be used to get references within a list?

答:
Lisp doesn't have references in that sense.  Except, of course, that it's Lisp: it has whatever you want it to have.

```<code>(defmacro locative (form)               ;in memory of Zetalisp
  `(lambda (&optional (value nil valuep))
     (if valuep
         (setf ,form value)
       ,form)))

(defun valof (locative)                 ;in memory of BCPL
  (funcall locative))

(defun (setf valof) (value locative)
  (funcall locative value))

</code>```

And now

```<code>> (let ((lol (copy-tree '((1 3) (2 6)))))
    (let ((tlc (locative (nth 0 (nth 0 lol)))))
      (print (valof tlc))
      (setf (valof tlc) 8)
      lol))
1
((8 3) (2 6))
</code>```

Body:
I am trying to reference a specific element in a 2D Matrix represented as list of Lists so I can set that specific element to 0. However, when I run the code below:

(defvar listOfLists '( (1 3) (2 6) ))
(defvar referenceToTopLeftCorner (nth 0 (nth 0 listOfLists)))
(setq referenceToTopLeftCorner 0)
(print (format nil "listsOfLists = ~a" listOfLists))

The following output is:

""listsOfLists = ((1 3) (2 6))"

This seems strange, as I thought that the nth method can be used to get references within a list?

Body:
Lisp doesn't have references in that sense.  Except, of course, that it's Lisp: it has whatever you want it to have.

(defmacro locative (form)               ;in memory of Zetalisp
  `(lambda (&optional (value nil valuep))
     (if valuep
         (setf ,form value)
       ,form)))

(defun valof (locative)                 ;in memory of BCPL
  (funcall locative))

(defun (setf valof) (value locative)
  (funcall locative value))

And now

> (let ((lol (copy-tree '((1 3) (2 6)))))
    (let ((tlc (locative (nth 0 (nth 0 lol)))))
      (print (valof tlc))
      (setf (valof tlc) 8)
      lol))
1
((8 3) (2 6))