问:
SQL - Counting users that have multiple transactions and have at least one transaction that has been made within 7 days interval of the other one
Dataset Here is the task : Count users that have multiple transactions and have at least one transaction that has been made within 7 days interval of the other one.

Structure of dataset: Row, userId, orderId, date

Date is formatted as YYYY-MM-DDTHH:MM:SS Example: 2016-09-16T11:32:06

I have completed the first part (counting users with multiple transactions), but I do not know how to do the second part in the same query. I will be thankful for help.

Here is the console:

```<code>query = '''
SELECT COUNT(*)
FROM
  (SELECT userId FROM `dataset` GROUP BY userId HAVING COUNT(orderId) > 1)
'''

project_id = 'acdefg'

df = pd.io.gbq.read_gbq(query, project_id=project_id, dialect='standard')
display(df)
</code>```

答:
This may be what you need:</p>
```<code>-- for each order calculate the days since that customer's last order
order_profiler AS (
  SELECT
    orderId,
    orderDate,
    custId,
    DATE_DIFF(orderDate, LAG(orderDate) OVER (PARTITION BY custId ORDER BY orderDate), day) AS order_latency_days,
  FROM
    `dataset.table`
)

SELECT
custId,
FROM order_profiler
WHERE order_latency_days <= 7
GROUP BY custId
</code>```

Body:
Dataset Here is the task : Count users that have multiple transactions and have at least one transaction that has been made within 7 days interval of the other one.

Structure of dataset: Row, userId, orderId, date

Date is formatted as YYYY-MM-DDTHH:MM:SS Example: 2016-09-16T11:32:06

I have completed the first part (counting users with multiple transactions), but I do not know how to do the second part in the same query. I will be thankful for help.

Here is the console:

query = '''
SELECT COUNT(*)
FROM
  (SELECT userId FROM `dataset` GROUP BY userId HAVING COUNT(orderId) > 1)
'''

project_id = 'acdefg'

df = pd.io.gbq.read_gbq(query, project_id=project_id, dialect='standard')
display(df)

Body:
This may be what you need:

-- for each order calculate the days since that customer's last order
order_profiler AS (
  SELECT
    orderId,
    orderDate,
    custId,
    DATE_DIFF(orderDate, LAG(orderDate) OVER (PARTITION BY custId ORDER BY orderDate), day) AS order_latency_days,
  FROM
    `dataset.table`
)

SELECT
custId,
FROM order_profiler
WHERE order_latency_days <= 7
GROUP BY custId


来源: stackexchange

问:
Devexpress xtrareport pivot grid grand total for the percentage column
I have 3 columns like target, sales, percentage (sales/target *100). When i have shown these three columns in the devexperss xtrareport pivot grid the grand total percentage is just taking the sum of the columns. i want to show the percentage of the sum of sales / sum of target in both row and column grand total.
Check the attached excel sheet</p>

答:
I achieved this with the following steps.

Create a new unbounded column

Set the Summary type as "Custom"

Set the Unbound Expression formula as "Sales/Target*100"

Set the Unbound Expression Mode as "Use Summary Value"

Set the Unbound Type as Decimal

Add that new column into the data area.

ContentLicense: CC BY-SA 4.0


问:
WSL VSCode call Windows Python Executable

Context: Running python in VSCode on Windows

Default Terminal is Bash (via WSL)

Using WSL - Debian

Python 3 installed on Windows, not on WSL

I want Bash to call my Windows Python Executable when I run my python files. I am only using WSL so I can replace cmd/powershell with bash. I do not want to install anything on WSL, I want to use existing programs on Windows (in this case Python).

However when I try to run my Python file (Clicking 'play' button) I get the error:

-bash: C:/Users/Connor/AppData/Local/Programs/Python/Python310/python.exe: No such file or directory
```

I believe this can be solved by replacing C: with \mnt\c

How can I achieve this?

答:
I had a same problem as yours. I solved this by following steps.

Open the VSCode

On your left-down side, you can see the the icon that I pointed enter image description here (the name in here is "Open a Remote Window")

Next you can see above the "Reopen Folder in WSL" enter image description here and clicked

Then you can run python with wsl and no more directory errors

Body:
Context: Running python in VSCode on Windows

Default Terminal is Bash (via WSL)

Using WSL - Debian

Python 3 installed on Windows, not on WSL

I want Bash to call my Windows Python Executable when I run my python files. I am only using WSL so I can replace cmd/powershell with bash. I do not want to install anything on WSL, I want to use existing programs on Windows (in this case Python).

However when I try to run my Python file (Clicking 'play' button) I get the error:

-bash: C:/Users/Connor/AppData/Local/Programs/Python/Python310/python.exe: No such file or directory

I believe this can be solved by replacing C: with \mnt\c

How can I achieve this?


问:
How can I push ItemName to my database(SQL) from Select2() dropdown list
i am new on asp.net razor page

this is my Html

                    <select class="form-control" id="itemslist" name="itemName" asp-items="Model.Itemslist">
                        <option value="SSS"></option>
                    </select>
                    <input class="form-control" type="hidden" name="itemName"asp-for="Expiree.ItemName"  />

                    @if (ViewData["Message"] != null)
                    {

                    }

```
<p>this my script section</p>
```@section scripts
{
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" />

}
```
<p>this my page model</p>
```namespace SparkAuto.Pages.Expire
{
    public class CreateeModel : PageModel
    {
        private readonly ApplicationDbContext _db;
        public CreateeModel(ApplicationDbContext db)
        {
            _db = db;
        }
        public SelectList Itemslist { get; set; }
        [BindProperty]
        public Expiree Expiree { get; set; }
        public IActionResult OnGet()
        {
            this.Itemslist = new SelectList(_db.Items, "Id", "Name");

            return Page();
        }
        public async Task<IActionResult> OnPostAsync()
        {

            _db.Expiree.Add(Expiree);
            await _db.SaveChangesAsync();

            return RedirectToPage("Index");
        }
    }
}
```

finally this my error i get Null in itemName in database

this a screenshot from searchable select2 dropdown list i use

I search in 3K items in this dropdown list and need to push the item name after selection

答:
You can use select to bind id of Expiree,and bind ItemName with hidden input:

Expire:

```<code>public class Expiree {
        public int ItemId { get; set; }
        public string ItemName { get; set; }
    }
</code>```

html:

```<code><select class="form-control" id="itemslist" asp-for="Expiree.ItemId" asp-items="Model.Itemslist">
        <option value="SSS"></option>
    </select>
    <input class="form-control" type="hidden" asp-for="Expiree.ItemName" />
</code>```

js:

```<code>@section scripts
{
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#itemslist").select2();
        });
        $("body").on("change", "#itemslist", function () {
            $("#Expiree_ItemName").val($(this).find("option:selected").text());
        });
    </script>

}
</code>```

Body:
i am new on asp.net razor page

this is my Html

                    <select class="form-control" id="itemslist" name="itemName" asp-items="Model.Itemslist">
                        <option value="SSS"></option>
                    </select>
                    <input class="form-control" type="hidden" name="itemName"asp-for="Expiree.ItemName"  />

                    @if (ViewData["Message"] != null)
                    {

                    }

this my script section

@section scripts
{
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" />

}

this my page model

namespace SparkAuto.Pages.Expire
{
    public class CreateeModel : PageModel
    {
        private readonly ApplicationDbContext _db;
        public CreateeModel(ApplicationDbContext db)
        {
            _db = db;
        }
        public SelectList Itemslist { get; set; }
        [BindProperty]
        public Expiree Expiree { get; set; }
        public IActionResult OnGet()
        {
            this.Itemslist = new SelectList(_db.Items, "Id", "Name");

            return Page();
        }
        public async Task<IActionResult> OnPostAsync()
        {

            _db.Expiree.Add(Expiree);
            await _db.SaveChangesAsync();

            return RedirectToPage("Index");
        }
    }
}

finally this my error i get Null in itemName in database

this a screenshot from searchable select2 dropdown list i use

I search in 3K items in this dropdown list and need to push the item name after selection

Body:
You can use select to bind id of Expiree,and bind ItemName with hidden input:

Expire:

public class Expiree {
        public int ItemId { get; set; }
        public string ItemName { get; set; }
    }

html:

<select class="form-control" id="itemslist" asp-for="Expiree.ItemId" asp-items="Model.Itemslist">
        <option value="SSS"></option>
    </select>
    <input class="form-control" type="hidden" asp-for="Expiree.ItemName" />

js:

@section scripts
{
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#itemslist").select2();
        });
        $("body").on("change", "#itemslist", function () {
            $("#Expiree_ItemName").val($(this).find("option:selected").text());
        });
    </script>

}


问:
How to use Reflection in typescript similarly like in java?
I'm using reflection in Java to obtain some information from the TestNG annotation like in the code snippet below:

Reflections reflections = new Reflections("", new MethodAnnotationsScanner())
Set<Method> annotated = reflections.getMethodsAnnotatedWith(Test.class)
```

Currently, I have a jest framework with a jest-decorated plugin to help in using annotations.

How I can replicate the same reflection method in Java but in typescript to collect this information from the annotations?

答:
Try tst-reflect.
It is pretty advanced Reflection system for TypeScript (using custom typescript transformer plugin).

This should be equivalent of your Java code:

import {
    reflect,
    Type
} from "tst-reflect";

// Some decorator...
function test(_, __)
{
}

@reflect()
class A
{
    @test
    foo()
    {
        return 0;
    }

    bar()
    {
        return "lorem ipsum";
    }
}

@reflect()
class B
{
    @test
    bar()
    {
        return "lorem ipsum";
    }
}

@reflect()
class C
{
    baz()
    {
        return "lorem ipsum";
    }
}

const decoratedMethods = Type.getTypes()
    .flatMap(type => type.getMethods().map(method => ({ method, type })))
    .filter(entry => entry.method.getDecorators().some(decorator => decorator.name == "test"));

for (let entry of decoratedMethods)
{
    console.log(entry.method.name, "in", entry.type.name);
}
```
<p><strong>Output</strong></p>
```foo in A
bar in B
```
<p>Check Synopsis.
You are able to create instances of those types (even they are from different files) and call those methods.
Also those decorators can have arguments so you will be able to filter methods with same decorators but different arguments.</p>
<p><code>tst-reflect</code> is still in development so the global look ups of types require those <code>@reflect</code> decorators or custom decorators with <code>@reflect</code> JSDoc tag; reason is size optimization of the generated metadata. But there is an issue to extend configuration by "include" glob patterns which will include all types from all the modules matched by that globs.</p>
<p>PS: Check out configuration wiki and use this configuration:</p>
<blockquote>
<p>tsconfig.json</p>
</blockquote>
```{
    "compilerOptions": {
        // your options...

        // ADD THIS!
        "plugins": [
            {
                "transform": "tst-reflect-transformer"
            }
        ]
    },
    // ADD THIS!
    "reflection": {
        "metadata": {
            "type": "typelib" // this mode will generate and auto-import library with generated reflection metadata
        }
    }
}
```

Body:
I'm using reflection in Java to obtain some information from the TestNG annotation like in the code snippet below:

Reflections reflections = new Reflections("", new MethodAnnotationsScanner())
Set<Method> annotated = reflections.getMethodsAnnotatedWith(Test.class)

Currently, I have a jest framework with a jest-decorated plugin to help in using annotations.

How I can replicate the same reflection method in Java but in typescript to collect this information from the annotations?

Body:
Try tst-reflect.
It is pretty advanced Reflection system for TypeScript (using custom typescript transformer plugin).

This should be equivalent of your Java code:

import {
    reflect,
    Type
} from "tst-reflect";

// Some decorator...
function test(_, __)
{
}

@reflect()
class A
{
    @test
    foo()
    {
        return 0;
    }

    bar()
    {
        return "lorem ipsum";
    }
}

@reflect()
class B
{
    @test
    bar()
    {
        return "lorem ipsum";
    }
}

@reflect()
class C
{
    baz()
    {
        return "lorem ipsum";
    }
}

const decoratedMethods = Type.getTypes()
    .flatMap(type => type.getMethods().map(method => ({ method, type })))
    .filter(entry => entry.method.getDecorators().some(decorator => decorator.name == "test"));

for (let entry of decoratedMethods)
{
    console.log(entry.method.name, "in", entry.type.name);
}

Output

foo in A
bar in B

Check Synopsis.
You are able to create instances of those types (even they are from different files) and call those methods.
Also those decorators can have arguments so you will be able to filter methods with same decorators but different arguments.

tst-reflect is still in development so the global look ups of types require those @reflect decorators or custom decorators with @reflect JSDoc tag; reason is size optimization of the generated metadata. But there is an issue to extend configuration by "include" glob patterns which will include all types from all the modules matched by that globs.

PS: Check out configuration wiki and use this configuration:

tsconfig.json

{
    "compilerOptions": {
        // your options...

        // ADD THIS!
        "plugins": [
            {
                "transform": "tst-reflect-transformer"
            }
        ]
    },
    // ADD THIS!
    "reflection": {
        "metadata": {
            "type": "typelib" // this mode will generate and auto-import library with generated reflection metadata
        }
    }
}


问:
Laravel 5.7 Migration : key was too long
I want to make a multiple unique column, but when i run php artisan migrate, i got this error:

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 1000 bytes

This my code:

```<code>Schema::create('buku', function (Blueprint $table) {
        $table->increments('id');
        $table->string('judul');
        $table->string('pengarang');
        $table->string('penerbit');
        $table->string('thn_terbit',4);
        $table->integer('stok');
        $table->string('kategori');
        $table->timestamps();

        $table->unique(['judul','pengarang','penerbit','thn_terbit'],'unik');
    });
</code>```

this AppServiceProvider.php file

```<code>public function boot()
{
    Schema::defaultStringLength(191);
}
</code>```

An answer will be appreciated

Version: Laravel 5.7

答:
[Solved]

I solved this by adding a $table->engine = 'innoDB'; so the code look like this:

```<code>Schema::create('buku', function (Blueprint $table) {
        $table->engine = 'innoDB';

        $table->increments('id');
        $table->string('judul');
        $table->string('pengarang');
        $table->string('penerbit');
        $table->string('thn_terbit');
        $table->integer('stok');
        $table->string('kategori');
        $table->timestamps();

        $table->unique(['judul','pengarang','penerbit','thn_terbit'],'unik');
    });
</code>```

and then re-migrate it, and everything is good.

Body:
I want to make a multiple unique column, but when i run php artisan migrate, i got this error:

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key
was too long; max key length is 1000 bytes

This my code:

Schema::create('buku', function (Blueprint $table) {
        $table->increments('id');
        $table->string('judul');
        $table->string('pengarang');
        $table->string('penerbit');
        $table->string('thn_terbit',4);
        $table->integer('stok');
        $table->string('kategori');
        $table->timestamps();

        $table->unique(['judul','pengarang','penerbit','thn_terbit'],'unik');
    });

this AppServiceProvider.php file

public function boot()
{
    Schema::defaultStringLength(191);
}

An answer will be appreciated

Version: Laravel 5.7

Body:
[Solved]

I solved this by adding a $table->engine = 'innoDB'; so the code look like this:

Schema::create('buku', function (Blueprint $table) {
        $table->engine = 'innoDB';

        $table->increments('id');
        $table->string('judul');
        $table->string('pengarang');
        $table->string('penerbit');
        $table->string('thn_terbit');
        $table->integer('stok');
        $table->string('kategori');
        $table->timestamps();

        $table->unique(['judul','pengarang','penerbit','thn_terbit'],'unik');
    });

and then re-migrate it, and everything is good.


问:
Change manually placeholder text in input "postalCode" in Stripe from "ZIP" or "Postal Code" to "ZIP/Postal"
I'm using "@stripe/stripe-js": "^1.9.0" in nuxt.js app...and must change text in placeholder <input class="InputElement is-empty Input Input--empty" autocomplete="postal-code" autocorrect="off" spellcheck="false" type="text" name="postal" data-elements-stable-field-name="postalCode" inputmode="numeric" aria-label="ZIP" placeholder="ZIP" aria-invalid="false" value=""> from "ZIP" to "ZIP/Postal" according my current task). But official DOC did not help me with it and STRIPE-support did not help me also...any ideas how can I change placeholder?) and also in future I need to change this text by other languages )

答:
instead of using the all-in-one card element, you can place the individual cardNumber, cardExpiry and cardCvc elements to the your own postal input element, of which you can customize the label as you want.

Remember to include the value of postalCode that you collected from your own postal code input element when confirming the payment.

See https://stripe.com/docs/js/element/other_element


问:
macos SystemExtension install
I am developing on MacOS and have completed development after referencing SystemExtension and NetworkExtension, and I want to install it for distribution.

Also, the structure is shown below.

========================================================================

Applications

------------Group 1 (Type: Application Bundle) , (Framework: NetworkExtension, SystemExtension) , (Embedded Content: Group2 (embed without signing)

------------Group 2 (Type: Plug-in) , (Framework: AppKit, DiskArbiration,NetworkExtension) ,                                (Lib: libbsm.tbd , libEndpointSecurity.tbd

========================================================================

Moved the built app to the PC being distributed.
(Delivered signed app by drag and drop without registering in APP Store)

But currently I am having the following problem:

When SIP is released and installed, network communication works normally. However, after enabling SIP, it is installed, but the network is not always connected (Starting is displayed in the network setting).

I'm new to Xcode and it's my first project, so I don't know where to go further.

答:
The endpoint-security permission must be assigned after making a direct request to apple.
Therefore, it was solved after creating a provisioning profile after being assigned.</p>

Title: macos SystemExtension install


问:
How to fix 'JSX element type 'Component' does not have any construct or call signatures' in ts
I'm using react router like this.

I get the 'Component' from the routes, but ts throw an error, in the js, there is no Error.

import React from "react";
import { Route, Switch, useRouteMatch, withRouter } from "react-router-dom";
import type { MyRoute } from "./types";

const routes: MyRoute[] = [
  {
    path: "overview",
    Component: Index,
    title: "概览",
    name: "index",
    requireAuth: false,
  }
];

const MainRoute: React.FunctionComponent = () => {
  const match = useRouteMatch();
  const filter = (route: MyRoute): JSX.Element => {
    const { Component } = route;
    return (
      <Route
        key={route.path}
        path={`${match.path}/${route.path}`}
        exact
        render={(props) => {
          document.title = route.title;
          // throw error in this line:JSX element type 'Component' does not have any construct or call signatures.
          return <Component {...props} />;
        }}
      />
    );
  };
  return (
        <Switch>{routes.map(filter)}</Switch>);
};

export default withRouter(MainRoute);
```

there is a error:JSX element type 'Component' does not have any construct or call signatures.
how can I fix it

答:
export interface MyRoute {
  path: string;
  Component?: JSX.Element | React.ReactNode | React.FunctionComponent;
  title: string;
  name: string;
  requireAuth?: boolean;
  children?: MyRoute[];
}

```

Body:
I'm using react router like this.

I get the 'Component' from the routes, but ts throw an error, in the js, there is no Error.

import React from "react";
import { Route, Switch, useRouteMatch, withRouter } from "react-router-dom";
import type { MyRoute } from "./types";

const routes: MyRoute[] = [
  {
    path: "overview",
    Component: Index,
    title: "概览",
    name: "index",
    requireAuth: false,
  }
];

const MainRoute: React.FunctionComponent = () => {
  const match = useRouteMatch();
  const filter = (route: MyRoute): JSX.Element => {
    const { Component } = route;
    return (
      <Route
        key={route.path}
        path={`${match.path}/${route.path}`}
        exact
        render={(props) => {
          document.title = route.title;
          // throw error in this line:JSX element type 'Component' does not have any construct or call signatures.
          return <Component {...props} />;
        }}
      />
    );
  };
  return (
        <Switch>{routes.map(filter)}</Switch>);
};

export default withRouter(MainRoute);

there is a error:JSX element type 'Component' does not have any construct or call signatures.
how can I fix it


问:
How can .val return a localtime value?
In the val docs written this description:

.val() Returns: String, Number, Array

I tried to get a Time, but it seems to return string only, Is there any method to parse the val value to localtime?

```<code>$.get(href,function(exam,status){
            $('#startTimeEdit').val(exam.startTime);
            $('#endTimeEdit').val(exam.endTime);
        });
</code>```

Overall, my question will be how to parse the val value to LocalTime datatype?

答:
If you're given a stringified date + time in these values, then this will work:</p>
```<code>$.get(href, (exam, status) => {
    const start = new Date($('#startTimeEdit').val(exam.startTime)).toLocaleTimeString()
    const end = new Date($('#endTimeEdit').val(exam.endTime)).toLocaleTimeString()
    return { start, end }

});
</code>```

Title: How can .val return a localtime value?

Body:
In the val docs written this description:

.val() Returns: String, Number, Array

I tried to get a Time, but it seems to return string only, Is there any method to parse the val value to localtime?

$.get(href,function(exam,status){
            $('#startTimeEdit').val(exam.startTime);
            $('#endTimeEdit').val(exam.endTime);
        });

Overall, my question will be how to parse the val value to LocalTime datatype?

Body:
If you're given a stringified date + time in these values, then this will work:

$.get(href, (exam, status) => {
    const start = new Date($('#startTimeEdit').val(exam.startTime)).toLocaleTimeString()
    const end = new Date($('#endTimeEdit').val(exam.endTime)).toLocaleTimeString()
    return { start, end }

});


问:
Python dictionary not getting updated
Hello I have below code where I am trying to add elements to a dict

```<code>for ent in NACLS:
    set_filter = {'Name': 'network-acl-id', 'Values': [naclID]}
    print(set_filter)
    set_filter.update({'Name': 'entry.rule-number', 'Values': [str(ent[0])]})
    print(set_filter)
</code>```

The output for the above code is

```<code>{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}
{'Name': 'entry.rule-number', 'Values': ['50']}
{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}
{'Name': 'entry.rule-number', 'Values': ['60']}
{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}
{'Name': 'entry.rule-number', 'Values': ['70']}
</code>```

Whereas I was wanting it to update the existing dictionary but somehow it's getting overwritten. Expected output

```<code>{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}, {'Name': 'entry.rule-number', 'Values': ['50']}
{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}, {'Name': 'entry.rule-number', 'Values': ['60']}
{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}, {'Name': 'entry.rule-number', 'Values': ['70']}
</code>```

can someone please guide me on how I can achieve this?

答:
I didn't understand what is the problem here. Do you want to print these dicts like you expected ?

You can write :

for ent in NACLS:
    set_filter = {'Name': 'network-acl-id', 'Values': [naclID]}
    print(set_filter,end=",")
    set_filter.update({'Name': 'entry.rule-number', 'Values': [str(ent[0])]})
    print(set_filter,end="\n")
```

Title: Python dictionary not getting updated

Body:
Hello I have below code where I am trying to add elements to a dict

for ent in NACLS:
    set_filter = {'Name': 'network-acl-id', 'Values': [naclID]}
    print(set_filter)
    set_filter.update({'Name': 'entry.rule-number', 'Values': [str(ent[0])]})
    print(set_filter)

The output for the above code is

{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}
{'Name': 'entry.rule-number', 'Values': ['50']}
{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}
{'Name': 'entry.rule-number', 'Values': ['60']}
{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}
{'Name': 'entry.rule-number', 'Values': ['70']}

Whereas I was wanting it to update the existing dictionary but somehow it's getting overwritten. Expected output

{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}, {'Name': 'entry.rule-number', 'Values': ['50']}
{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}, {'Name': 'entry.rule-number', 'Values': ['60']}
{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}, {'Name': 'entry.rule-number', 'Values': ['70']}

can someone please guide me on how I can achieve this?


答:
The expected output example isn't a valid dictionary:

{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}, {'Name': 'entry.rule-number', 'Values': ['50']}
```
<p>Reformatted:</p>
<pre class="lang-json prettyprint-override"><code>{
    'Name': 'network-acl-id',
    'Values': [ 'acl-08128a2540eb' ]
},
{
    'Name': 'entry.rule-number',
    'Values': [ '50' ]
}
</code>```

To create a list of dictionaries:

for ent in NACLS:
    set_filter = [{'Name': 'network-acl-id', 'Values': [naclID]}]
    #            ^ note square brackets                         ^
    print(set_filter)
    set_filter.append({'Name': 'entry.rule-number', 'Values': [str(ent[0])]})
    print(set_filter)
```
<p>Or to put them all into a list:</p>
<pre class="lang-py prettyprint-override"><code>set_filter = []
for ent in NACLS:
    set_filter.append({'Name': 'network-acl-id', 'Values': [naclID]})
    print(set_filter)
    set_filter.append({'Name': 'entry.rule-number', 'Values': [str(ent[0])]})
    print(set_filter)
</code>```

Title: Python dictionary not getting updated

Body:
The expected output example isn't a valid dictionary:

{'Name': 'network-acl-id', 'Values': ['acl-08128a2540eb']}, {'Name': 'entry.rule-number', 'Values': ['50']}

Reformatted:

{
    'Name': 'network-acl-id',
    'Values': [ 'acl-08128a2540eb' ]
},
{
    'Name': 'entry.rule-number',
    'Values': [ '50' ]
}

To create a list of dictionaries:

for ent in NACLS:
    set_filter = [{'Name': 'network-acl-id', 'Values': [naclID]}]
    #            ^ note square brackets                         ^
    print(set_filter)
    set_filter.append({'Name': 'entry.rule-number', 'Values': [str(ent[0])]})
    print(set_filter)

Or to put them all into a list:

set_filter = []
for ent in NACLS:
    set_filter.append({'Name': 'network-acl-id', 'Values': [naclID]})
    print(set_filter)
    set_filter.append({'Name': 'entry.rule-number', 'Values': [str(ent[0])]})
    print(set_filter)


答:
The update method adds {key:value} pairs to a dictionary unless the key already exists, in which case it just updates the value to the new value.

From the look of your expected output it seems you want a list of dictionaries all with the same keys but different values.

try this:

```<code>set_filter = []
for ent in NACLS:
    set_filter.append({'Name': 'network-acl-id', 'Values': [naclID]})
    set_filter.append({'Name': 'entry.rule-number', 'Values': [str(ent[0])]})
    print(set_filter)
</code>```

Title: Python dictionary not getting updated

Body:
The update method adds {key:value} pairs to a dictionary unless the key already exists, in which case it just updates the value to the new value.

From the look of your expected output it seems you want a list of dictionaries all with the same keys but different values.

try this:

set_filter = []
for ent in NACLS:
    set_filter.append({'Name': 'network-acl-id', 'Values': [naclID]})
    set_filter.append({'Name': 'entry.rule-number', 'Values': [str(ent[0])]})
    print(set_filter)


问:
How do I output custom data in a custom post in wordpress?
I made a custom post type in wordpress which takes extra values like $price, for example. I can save them and recall them in the back-end, but how can I display them on my new single-post.php page?</p>

答:
At http://codex.wordpress.org/Post_Types appears:

In the form of the single-type-template. In the same way that posts
  are shown on their own page with single.php, custom post types will
  use single-{posttype}.php if it's available.

So for the above example, you could create a single-acme_product.php
  file and the product posts would be shown using that template.

This means that you can create a new single template file with the name of you new custom type and display there the specific data for custom type, example:

single-post_with_price.php

ContentLicense: CC BY-SA 3.0


问:
NodeJS: Async function still halts main function
I'm trying to make a function call some code while allowing my main function to continue and not have to wait for it.

So far it's not working:

```<code>function doSomething() {
  return new Promise((resolve, reject) => {
    if(1) {
        console.log("doing something");
        for(let i = 0; i < 10000; i++) {
            for(let j = 0; j < 10000; j++) {
                for(let k = 0; k < 100; k++) {
                 // Do something for a long time to check if async is working
                }
            }
        }
        console.log("finished doing something");
        resolve( {"dummydata": 10} );
    }
    else {
        reject("error!");
    }
  })
}

function main() {
    doSomething()
    .then(data => console.log(data))
    .catch(err => console.error(err))

    console.log("this should print before doSomething() is finished");
}

main();
</code>```

This is the output:

doing something

finished doing something

this should print before doSomething() is finished

{ dummydata: 10 }

Why is my program waiting for doSomething()? I want it to run in parallel / asynchronously. I also tried making main() an async function, same with doSomething(), but that didn't work.

答:
JavaScript is still single-threaded. If you have an expensive segment of code, like your nested loop, and you don't await inside the loop, all other JavaScript processing in your environment will be blocked while the loop iterates - control flow will only yield back once all the synchronous code has finished.

Code put at the top level of the Promise constructor callback runs immediately - doing return new Promise doesn't make the code be put on a separate thread, or something like that.

While you could queue the task so it starts after a delay, and lets the main script continue whatever it needs to do:

```<code>function main() {
  setTimeout(doSomething, 2000);
  // more code
</code>```

To truly run it in parallel, you'll need to use a child_process. Put the expensive section of the script into its own file, and have child_process invoke it via .fork.

Body:
I'm trying to make a function call some code while allowing my main function to continue and not have to wait for it.

So far it's not working:

function doSomething() {
  return new Promise((resolve, reject) => {
    if(1) {
        console.log("doing something");
        for(let i = 0; i < 10000; i++) {
            for(let j = 0; j < 10000; j++) {
                for(let k = 0; k < 100; k++) {
                 // Do something for a long time to check if async is working
                }
            }
        }
        console.log("finished doing something");
        resolve( {"dummydata": 10} );
    }
    else {
        reject("error!");
    }
  })
}

function main() {
    doSomething()
    .then(data => console.log(data))
    .catch(err => console.error(err))

    console.log("this should print before doSomething() is finished");
}

main();

This is the output:

doing something

finished doing something

this should print before doSomething() is finished

{ dummydata: 10 }

Why is my program waiting for doSomething()? I want it to run in parallel / asynchronously. I also tried making main() an async function, same with doSomething(), but that didn't work.

Body:
JavaScript is still single-threaded. If you have an expensive segment of code, like your nested loop, and you don't await inside the loop, all other JavaScript processing in your environment will be blocked while the loop iterates - control flow will only yield back once all the synchronous code has finished.

Code put at the top level of the Promise constructor callback runs immediately - doing return new Promise doesn't make the code be put on a separate thread, or something like that.

While you could queue the task so it starts after a delay, and lets the main script continue whatever it needs to do:

function main() {
  setTimeout(doSomething, 2000);
  // more code

To truly run it in parallel, you'll need to use a child_process. Put the expensive section of the script into its own file, and have child_process invoke it via .fork.


问:
Query function to select all columns of an imported data set, starting from a specific column
I am looking to query specific columns of an imported dataset from a separate google sheet. Ideally, I would like to query all columns after the "product ID" column (refer to "Test Data Set"). The reason why I am doing this is that I need the product ID column to remain in a particular position in the "Final Destination Sheet" since the "Product ID"s will be used as a reference range for the index and match formulas on another tab of that sheet.

The formula I have so far to import and query the original dataset for the "Product ID" column is as so:

=QUERY({IMPORTRANGE("1aPpdSy5venMl97ayn7VwaOo_AcAtcoc6_l4a1loPhNI","Sheet1!A:D")}, "SELECT Col" &MATCH("Product ID", IMPORTRANGE("1aPpdSy5venMl97ayn7VwaOo_AcAtcoc6_l4a1loPhNI","Sheet1!A1:1"),0),1)

However, I am unsure how to make the formula understand to query up all the columns after the "Product ID" column. Do note, the test data set only has 4 columns and a set number of columns but the real data set I am working with will be dynamic so more columns can be added or deleted over time. (So I won't know what the finite column letter will be and if columns are deleted from the left of B then it might shift its position which is why I used the match function in my original formula to ID that specific column's location on the spreadsheet).

Thank you in advance!

Final Destination Sheet (where the data is imported to and where I am trying to query the original data for specific columns): link

Test Data Set (where the data is imported from): link

答:
if you know the headers you can do:

```<code>=TRANSPOSE(QUERY(TRANSPOSE(IMPORTRANGE("1aPpdSy5venMl97ayn7VwaOo_AcAtcoc6_l4a1loPhNI",
 "Sheet1!A:D")), "where lower(Col1) matches 'product id|size'", 0))
</code>```

update:

```<code>=IMPORTRANGE("1aPpdSy5venMl97ayn7VwaOo_AcAtcoc6_l4a1loPhNI",
 "Sheet1!"&ADDRESS(1, MATCH("Product ID",
 IMPORTRANGE("1aPpdSy5venMl97ayn7VwaOo_AcAtcoc6_l4a1loPhNI",
 "Sheet1!1:1"), 0))&":1000")
</code>```

assuming headers are in row 1 this will look for a column called product id and import it and all the columns to the right of it

Body:
if you know the headers you can do:

=TRANSPOSE(QUERY(TRANSPOSE(IMPORTRANGE("1aPpdSy5venMl97ayn7VwaOo_AcAtcoc6_l4a1loPhNI",
 "Sheet1!A:D")), "where lower(Col1) matches 'product id|size'", 0))

update:

=IMPORTRANGE("1aPpdSy5venMl97ayn7VwaOo_AcAtcoc6_l4a1loPhNI",
 "Sheet1!"&ADDRESS(1, MATCH("Product ID",
 IMPORTRANGE("1aPpdSy5venMl97ayn7VwaOo_AcAtcoc6_l4a1loPhNI",
 "Sheet1!1:1"), 0))&":1000")

assuming headers are in row 1 this will look for a column called product id and import it and all the columns to the right of it


问:
Is there a way to get static ip address for Azure Data Factory
I have to transfer data from an on-premise sql server to Azure Sql using Azure Data Factory however sql server owner needs to whitelist the public IP's to provide access to their service. I know that there is a range of IP's that are used by ADF in specific regions but is there a way to set one static IP which not gonna change and which I will be able to provide to my client ?</p>

答:
As rightly mentioned by Nick and wBob, you can get IP addresses that your Azure Integration Runtime uses but that is same for all in the same region and not unique Static IP address for only your integration runtime as Azure Integration Runtime is serverless. You have to set up a self-hosted integration runtime to get a Static IP for Data Factory connectors.

Also checkout simialr Copy data securely from Azure Blob storage to a SQL database by using private endpoints


问:
How to take multiple user text input values, add them together with javascript and return the value on page in a

I am very new to Javascript and am looking for a solution to better understand how this works.

I am making a simple budget app with various user text inputs. What I want to accomplish is to store these user inputs inside variables within JS, have them added, possibly compared, then return a total on the page when the user clicks a button in the empty paragraph element. Here is a sample of the html code (I have only included two of the inputs as they will work the same and just need an understanding of the concept):

```<code><ul>
            <li><p>Money In:</p></li>
            <br>
            <li class="inputHeading">Current Balance</li>
            <li><input type="text" class="input" id="balanceInput"></li>
            <li><p>Money Out:</p></li>
            <br>
            <li class="inputHeading">Rent</li>
            <li><input type="text" class="input" id="rentInput"></li>
            <li><input type="button" class="button" value="AMOUNT LEFT" onclick="calcTotal()"></li>
            <li class="output" id="amountOutput"><p></p></li>
</ul>
</code>```

I have researched various methods but most of what I find is far more complex than I can currently understand. I wanted to see if anyone could both suggest and explain a solution to how to do this. Your help would be much appreciated!

答:
You can store the input in js with document.getElementById("id").value

However this will be stored in string, so you need to change it into integer/float if you want to calculate the total

parseFloat() is the method to parse string text into float values.

In the example you provided, the values is current balance and rent, hence I think it is more suitable to find the difference instead of adding them together.

function calcTotal() {
  var inputbal = parseFloat(document.getElementById("balanceInput").value);
  var inputrent = parseFloat(document.getElementById("rentInput").value);
  var balance = inputbal - inputrent;
  document.getElementById("balance").innerHTML = balance.toFixed(2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>
    <p>Money In:</p>
  </li>
  <br>
  <li class="inputHeading">Current Balance</li>
  <li><input type="text" class="input" id="balanceInput"></li>
  <li>
    <p>Money Out:</p>
  </li>
  <br>
  <li class="inputHeading">Rent</li>
  <li><input type="text" class="input" id="rentInput"></li>
  <li><input type="button" class="button" value="AMOUNT LEFT" onclick="calcTotal()"></li>
  <li class="output" id="amountOutput">
    <p></p>
  </li>
</ul>

<p id="balance"></p></code>```

Title: How to take multiple user text input values, add them together with javascript and return the value on page in a <p>

Body:
I am very new to Javascript and am looking for a solution to better understand how this works.

I am making a simple budget app with various user text inputs. What I want to accomplish is to store these user inputs inside variables within JS, have them added, possibly compared, then return a total on the page when the user clicks a button in the empty paragraph element. Here is a sample of the html code (I have only included two of the inputs as they will work the same and just need an understanding of the concept):

Money In:

Current Balance

<input type="text" class="input" id="balanceInput">

Money Out:

Rent

<input type="text" class="input" id="rentInput">

<input type="button" class="button" value="AMOUNT LEFT" onclick="calcTotal()">

I have researched various methods but most of what I find is far more complex than I can currently understand. I wanted to see if anyone could both suggest and explain a solution to how to do this. Your help would be much appreciated!

Body:
You can store the input in js with document.getElementById("id").value

However this will be stored in string, so you need to change it into integer/float if you want to calculate the total

parseFloat() is the method to parse string text into float values.

In the example you provided, the values is current balance and rent, hence I think it is more suitable to find the difference instead of adding them together.

function calcTotal() {
  var inputbal = parseFloat(document.getElementById("balanceInput").value);
  var inputrent = parseFloat(document.getElementById("rentInput").value);
  var balance = inputbal - inputrent;
  document.getElementById("balance").innerHTML = balance.toFixed(2);
}

<ul>
  <li>
    <p>Money In:</p>
  </li>
  <br>
  <li class="inputHeading">Current Balance</li>
  <li><input type="text" class="input" id="balanceInput"></li>
  <li>
    <p>Money Out:</p>
  </li>
  <br>
  <li class="inputHeading">Rent</li>
  <li><input type="text" class="input" id="rentInput"></li>
  <li><input type="button" class="button" value="AMOUNT LEFT" onclick="calcTotal()"></li>
  <li class="output" id="amountOutput">
    <p></p>
  </li>
</ul>

<p id="balance"></p>


问:
Decoding JSON into model using MVVM
I am unable to decode my JSON data into my model. This is my first time attempting to use MVVM pattern and for some reason I cannot figure out why I cannot get a reference to my model variables such as title or id. Besides the error shown below I also get a message saying 'This property is defined on Movie and may not be available in this context'</p>
```<code>class MovieViewModel {

    let movie: APIResponse

    init(movie: APIResponse) {
        self.movie = movie
    }

    var title: String {
        return movie.data.title // Value of type [Movie] has no member 'title'
    }

         }

       struct APIResponse: Codable {
          var data: [Movie]
     }

       struct Movie: Codable {
           var id: String
           var title: String

       }

      class MovieListViewModel {

    private var movieViewModels = [MovieViewModel]()

    func addMovieViewModels(_ vm: MovieViewModel) {
        movieViewModels.append(vm)
    }

    func numberOfRows(_ section: Int) -> Int {

        return movieViewModels.count
    }

    func modelAtIndex(_ Index: Int) -> GiphyViewModel {

        return movieViewModels[Index]
    }

}
</code>```

答:
I think you should seperate API calls from the view model.
You can take example on this repo to know how to proceed.</p>

Title: Decoding JSON into model using MVVM

Body:
I am unable to decode my JSON data into my model. This is my first time attempting to use MVVM pattern and for some reason I cannot figure out why I cannot get a reference to my model variables such as title or id. Besides the error shown below I also get a message saying 'This property is defined on Movie and may not be available in this context'

class MovieViewModel {

    let movie: APIResponse

    init(movie: APIResponse) {
        self.movie = movie
    }

    var title: String {
        return movie.data.title // Value of type [Movie] has no member 'title'
    }

         }

       struct APIResponse: Codable {
          var data: [Movie]
     }

       struct Movie: Codable {
           var id: String
           var title: String

       }

      class MovieListViewModel {

    private var movieViewModels = [MovieViewModel]()

    func addMovieViewModels(_ vm: MovieViewModel) {
        movieViewModels.append(vm)
    }

    func numberOfRows(_ section: Int) -> Int {

        return movieViewModels.count
    }

    func modelAtIndex(_ Index: Int) -> GiphyViewModel {

        return movieViewModels[Index]
    }

}


问:
Flutter build Appbundle Error:* What went wrong: A problem occurred evaluating project ':app'
This is the error that I'm getting when I'm trying to run "flutter build appbundle" in terminal.
I already search for some solution but none of it has the same error as I get

FAILURE: Build failed with an exception.

Where:
Build file 'C:\Users\User_Name\Desktop\deploy\bahetra\android\app\build.gradle' line: 31

What went wrong:
A problem occurred evaluating project ':app'.

Malformed \uxxxx encoding.

This is the code from my "android\app\build.gradle":

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

    def keystoreProperties = new Properties()
   def keystorePropertiesFile = rootProject.file('key.properties')
   if (keystorePropertiesFile.exists()) {
       keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) // line 31
   }

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.bahetra"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    signingConfigs {
       release {
           keyAlias keystoreProperties['keyAlias']
           keyPassword keystoreProperties['keyPassword']
           storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
           storePassword keystoreProperties['storePassword']
       }
   }
   buildTypes {
       release {
           signingConfig signingConfigs.release
       }
   }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
</code>```

答:
in key.properties file:
must
storeFile=C:\Users\\upload-keystore.jks</p>

Body:
This is the error that I'm getting when I'm trying to run "flutter build appbundle" in terminal.
I already search for some solution but none of it has the same error as I get

FAILURE: Build failed with an exception.

Where:
Build file 'C:\Users\User_Name\Desktop\deploy\bahetra\android\app\build.gradle' line: 31

What went wrong:
A problem occurred evaluating project ':app'.

Malformed \uxxxx encoding.

This is the code from my "android\app\build.gradle":

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

    def keystoreProperties = new Properties()
   def keystorePropertiesFile = rootProject.file('key.properties')
   if (keystorePropertiesFile.exists()) {
       keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) // line 31
   }

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.bahetra"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    signingConfigs {
       release {
           keyAlias keystoreProperties['keyAlias']
           keyPassword keystoreProperties['keyPassword']
           storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null
           storePassword keystoreProperties['storePassword']
       }
   }
   buildTypes {
       release {
           signingConfig signingConfigs.release
       }
   }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}


答:
I come up with another solution:

```<code>sub MAIN() {
    my $fmt = {sprintf "%04d-%02d-%02d %02d:%02d:%02d", .year, .month, .day, .hour, .minute, .second};

    my @dates = gather given Date.today {
        my $current-datetime = .DateTime;
        while $current-datetime <= .succ.DateTime {
            take $current-datetime;
            $current-datetime = $current-datetime + Duration.new(300.0);
        }
    }

    for @dates.rotor(2 => -1) {
        printf("%s, %s\n", .[0].clone(formatter => $fmt), .[1].clone(formatter => $fmt));
    }
}
</code>```

thanks @wamba for the clone method.

Body:
How to generate a DateTime range by step of 5 minutes? The following is the output:

2022-02-13 00:00:00, 2022-02-13 00:05:00
2022-02-13 00:05:00, 2022-02-13 00:10:00
2022-02-13 00:10:00, 2022-02-13 00:15:00
2022-02-13 00:15:00, 2022-02-13 00:20:00
...
2022-02-13 23:45:00, 2022-02-13 23:50:00
2022-02-13 23:50:00, 2022-02-13 23:55:00
2022-02-13 23:55:00, 2022-02-14 00:00:00

Body:
I come up with another solution:

sub MAIN() {
    my $fmt = {sprintf "%04d-%02d-%02d %02d:%02d:%02d", .year, .month, .day, .hour, .minute, .second};

    my @dates = gather given Date.today {
        my $current-datetime = .DateTime;
        while $current-datetime <= .succ.DateTime {
            take $current-datetime;
            $current-datetime = $current-datetime + Duration.new(300.0);
        }
    }

    for @dates.rotor(2 => -1) {
        printf("%s, %s\n", .[0].clone(formatter => $fmt), .[1].clone(formatter => $fmt));
    }
}

thanks @wamba for the clone method.


问:
Finding maximum difference between columns of same name in R
I have the following table in R. I have 2 A columns, 3 B columns and 1 C column. I need to calculate the maximum difference possible between any columns of the same name and return the column name as output.

For row 1

The max difference between A is 2

The max difference between B is 4

I need the output as B

For row 2

The max difference between A is 3

The max difference between B is 2

I need the output as A

```<code>| A  | A | B | B | B | C |
| 2  | 4 |5  |2  |1  |0  |
| -3 |0  |2  |3  |4  |2  |
</code>```

答:
First of all, it's a bit dangerous (and not allowed in some cases) to have non-unique column names, so the first thing I did was to uniqueify the names using base::make.unique(). From there, I used tidyr::pivot_longer() so that the grouping information contained in the column names could be accessed more easily. Here I use a regex inside names_pattern to discard the differentiating parts of the column names so they will be the same again. Then we use dplyr::group_by() followed by dplyr::summarize() to get the largest difference in each id and grp which corresponds to your rows and similar columns in the original data. Finally we use dplyr::slice_max() to return only the largest difference per group.

library(tidyverse)

d <- structure(list(A = c(2L, -3L), A = c(4L, 0L), B = c(5L, 2L), B = 2:3, B = c(1L, 4L), C = c(0L, 2L)), row.names = c(NA, -2L), class = "data.frame")

# give unique names
names(d) <- make.unique(names(d), sep = "_")

d %>%
  mutate(id = row_number()) %>%
  pivot_longer(-id, names_to = "grp", names_pattern = "([A-Z])*") %>%
  group_by(id, grp) %>%
  summarise(max_diff = max(value) - min(value)) %>%
  slice_max(order_by = max_diff, n = 1, with_ties = F)

#> `summarise()` has grouped output by 'id'. You can override using the `.groups` argument.
#> # A tibble: 2 x 3
#> # Groups:   id [2]
#>      id grp   max_diff
#>   <int> <chr>    <int>
#> 1     1 B            4
#> 2     2 A            3
```

Created on 2022-02-14 by the reprex package (v2.0.1)

Body:
I have the following table in R. I have 2 A columns, 3 B columns and 1 C column. I need to calculate the maximum difference possible between any columns of the same name and return the column name as output.

For row 1

The max difference between A is 2

The max difference between B is 4

I need the output as B

For row 2

The max difference between A is 3

The max difference between B is 2

I need the output as A

| A  | A | B | B | B | C |
| 2  | 4 |5  |2  |1  |0  |
| -3 |0  |2  |3  |4  |2  |

Body:
First of all, it's a bit dangerous (and not allowed in some cases) to have non-unique column names, so the first thing I did was to uniqueify the names using base::make.unique(). From there, I used tidyr::pivot_longer() so that the grouping information contained in the column names could be accessed more easily. Here I use a regex inside names_pattern to discard the differentiating parts of the column names so they will be the same again. Then we use dplyr::group_by() followed by dplyr::summarize() to get the largest difference in each id and grp which corresponds to your rows and similar columns in the original data. Finally we use dplyr::slice_max() to return only the largest difference per group.

library(tidyverse)

d <- structure(list(A = c(2L, -3L), A = c(4L, 0L), B = c(5L, 2L), B = 2:3, B = c(1L, 4L), C = c(0L, 2L)), row.names = c(NA, -2L), class = "data.frame")

# give unique names
names(d) <- make.unique(names(d), sep = "_")

d %>%
  mutate(id = row_number()) %>%
  pivot_longer(-id, names_to = "grp", names_pattern = "([A-Z])*") %>%
  group_by(id, grp) %>%
  summarise(max_diff = max(value) - min(value)) %>%
  slice_max(order_by = max_diff, n = 1, with_ties = F)

#> `summarise()` has grouped output by 'id'. You can override using the `.groups` argument.
#> # A tibble: 2 x 3
#> # Groups:   id [2]
#>      id grp   max_diff
#>   <int> <chr>    <int>
#> 1     1 B            4
#> 2     2 A            3

Created on 2022-02-14 by the reprex package (v2.0.1)


问:
How to deliver instance of object to instance of SocketServer.BaseRequestHandler?
This is problem.
My primary work is : deliver "s" object to "handle" method in TestRequestHandler class.
My first step was : deliver "s" object through "point" method to TestServer class, but here im stuck. How to deliver "s" object to TestRequestHandler? Some suggestions?</p>

```<code>import threading
import SocketServer
from socket import *

class TestRequestHandler(SocketServer.BaseRequestHandler):

    def __init__(self, request, client_address, server):
        SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
        return

    def setup(self):
        return SocketServer.BaseRequestHandler.setup(self)

    def handle(self):
        data = self.request.recv(1024)

        if (data):
            self.request.send(data)
            print data

    def finish(self):
        return SocketServer.BaseRequestHandler.finish(self)

class TestServer(SocketServer.TCPServer):

    def __init__(self, server_address, handler_class=TestRequestHandler):
        print "__init__"
        SocketServer.TCPServer.__init__(self, server_address, handler_class)
        return

    def point(self,obj):
        self.obj = obj
        print "point"

    def server_activate(self):
        SocketServer.TCPServer.server_activate(self)
        return

    def serve_forever(self):
        print "serve_forever"
        while True:
            self.handle_request()
        return

    def handle_request(self):
        return SocketServer.TCPServer.handle_request(self)

if __name__ == '__main__':

    s = socket(AF_INET, SOCK_STREAM)

    address = ('localhost', 6666)
    server = TestServer(address, TestRequestHandler)
    server.point(s)
    t = threading.Thread(target=server.serve_forever())
    t.setDaemon(True)
    t.start()
</code>```

答:
If the value of s is set once, and not reinitialized - you could make it a class variable as opposed to an instance variable of TestServer, and then have the handler retrieve it via a class method of TestServer in the handler's constructor.

eg: TestServer._mySocket = s

OwnerDisplayName: Ozymet

ContentLicense: CC BY-SA 2.5

Body:
This is problem.
My primary work is : deliver "s" object to "handle" method in TestRequestHandler class.
My first step was : deliver "s" object through "point" method to TestServer class, but here im stuck. How to deliver "s" object to TestRequestHandler? Some suggestions?

import threading
import SocketServer
from socket import *

class TestRequestHandler(SocketServer.BaseRequestHandler):

    def __init__(self, request, client_address, server):
        SocketServer.BaseRequestHandler.__init__(self, request, client_address, server)
        return

    def setup(self):
        return SocketServer.BaseRequestHandler.setup(self)

    def handle(self):
        data = self.request.recv(1024)

        if (data):
            self.request.send(data)
            print data

    def finish(self):
        return SocketServer.BaseRequestHandler.finish(self)

class TestServer(SocketServer.TCPServer):

    def __init__(self, server_address, handler_class=TestRequestHandler):
        print "__init__"
        SocketServer.TCPServer.__init__(self, server_address, handler_class)
        return

    def point(self,obj):
        self.obj = obj
        print "point"

    def server_activate(self):
        SocketServer.TCPServer.server_activate(self)
        return

    def serve_forever(self):
        print "serve_forever"
        while True:
            self.handle_request()
        return

    def handle_request(self):
        return SocketServer.TCPServer.handle_request(self)

if __name__ == '__main__':

    s = socket(AF_INET, SOCK_STREAM)

    address = ('localhost', 6666)
    server = TestServer(address, TestRequestHandler)
    server.point(s)
    t = threading.Thread(target=server.serve_forever())
    t.setDaemon(True)
    t.start()

OwnerDisplayName: Max


问:
Why is my hdfs capacity not remainng constant?
I am running a pyspark job on dataproc and my total hdfs capacity is not remaining constant.

As you can see in the first chart that the remaining hdfs capacity is falling even though the used hdfs capacity is minimal. Why is remaining + used not constant?

答:
The "used" in the monitoring graph is actually "DFS used", and it didn't show "non-DFS used". If you open the HDFS UI in the component gateway web interfaces you should be able to see something like:

```<code>Configured Capacity  :   232.5 GB
DFS Used     :   38.52 GB
Non DFS Used     :   45.35 GB
DFS Remaining    :   148.62 GB
DFS Used%    :   16.57 %
DFS Remaining%   :   63.92 %
</code>```

The formula is :

DFS Remaining = Total Disk Space - max(Reserved Space, Non-DFS Used) - DFS Used

Configured capacity = Total Disk Space - Reserved Space

Reserved Space is controlled by the dfs.datanode.du.reserved 1 property which defaults to 0. So in your case it is the non-DFS used that gets deducted. Here is a similar question.

Body:
The "used" in the monitoring graph is actually "DFS used", and it didn't show "non-DFS used". If you open the HDFS UI in the component gateway web interfaces you should be able to see something like:

Configured Capacity  :   232.5 GB
DFS Used     :   38.52 GB
Non DFS Used     :   45.35 GB
DFS Remaining    :   148.62 GB
DFS Used%    :   16.57 %
DFS Remaining%   :   63.92 %

The formula is :

DFS Remaining = Total Disk Space - max(Reserved Space, Non-DFS Used) - DFS Used

Configured capacity = Total Disk Space - Reserved Space

Reserved Space is controlled by the dfs.datanode.du.reserved 1 property which defaults to 0. So in your case it is the non-DFS used that gets deducted. Here is a similar question.


问:
Remove surrounded quotes in vscode or toggle between quote and no quote
Is there any shortcut or extension for vscode which can help to remove surrounded quotes (single ' or double " ) around a selected text?

See example below

'hello' ==> hello

In other words, is it possible to have a feature which will toggle current selection between quotes and no quotes?

I have tried es quotes for vscode which is very nice while switching the quotes between single and double quotes.

答:
Say you were given the following JSON and you want the researchers value to be an array instead of a string. We need to remove the quotes that are wrapping the array. In version 1.64 of VSCode, you can do this search and replace using the built-in search and replace regex capture groups (no extension needed).

[
  {
    "id": 2,
    "description": "Project 1",
    "researchers": "[12,5,22]"
  },
  {
    "id": 3,
    "description": "Project 2",
    "researchers": "[1,44,22]"
  }
]
```
<p><img src="https://i.stack.imgur.com/L8Ey1.png" alt="screenshot of search string in VS Code" /></p>
<p>In the search field you will want to use a regular expression of
<code>"researchers": "\[(.+)\]"</code>, where the <code>(.+)</code> part of the expression being the first group we want to preserve or leave unchanged when we perform the replace. Then in the replace field we use <code>"researchers": [$1]</code>, with <code>$1</code> corresponding to the <code>(.+)</code> first group we are preserving in the search string. What this means is that we take the values that were found in the first search group (which in the first instance is <code>12,5,22</code>, then wrap it with <code>"researchers": [</code>12,5,22<code>]</code>.
The replaced JSON becomes:</p>
<pre class="lang-js prettyprint-override"><code>[
  {
    "id": 2,
    "description": "Project 1",
    "researchers": [12,5,22]
  },
  {
    "id": 3,
    "description": "Project 2",
    "researchers": [1,44,22]
  }
]
</code>```

The following video is also helpful. https://www.youtube.com/watch?v=6AsSfyHWWls

Body:
Say you were given the following JSON and you want the researchers value to be an array instead of a string. We need to remove the quotes that are wrapping the array. In version 1.64 of VSCode, you can do this search and replace using the built-in search and replace regex capture groups (no extension needed).

[
  {
    "id": 2,
    "description": "Project 1",
    "researchers": "[12,5,22]"
  },
  {
    "id": 3,
    "description": "Project 2",
    "researchers": "[1,44,22]"
  }
]

In the search field you will want to use a regular expression of
"researchers": "\[(.+)\]", where the (.+) part of the expression being the first group we want to preserve or leave unchanged when we perform the replace. Then in the replace field we use "researchers": [$1], with $1 corresponding to the (.+) first group we are preserving in the search string. What this means is that we take the values that were found in the first search group (which in the first instance is 12,5,22, then wrap it with "researchers": [12,5,22].
The replaced JSON becomes:

[
  {
    "id": 2,
    "description": "Project 1",
    "researchers": [12,5,22]
  },
  {
    "id": 3,
    "description": "Project 2",
    "researchers": [1,44,22]
  }
]

The following video is also helpful. https://www.youtube.com/watch?v=6AsSfyHWWls


问:
how can redirect domain to https except internal IP (192.168.1.10) in IIS
for example :
URL : http://test.com or www.test.com
redirect to https://test.com

but URL is : 192.168.1.10
open 192.168.1.10

in IIS rewrite URL

答:
You can negate a pattern using the negate attribute of the  element. when using this property, the rule action will only be performed if the current URL does not match the specified pattern. Here are the rules you can use as a reference:

```<code><rule name="test" enabled="true" stopProcessing="true">
  <match url="(.*)" />
     <conditions>
       <add input="{HTTPS}" pattern="^OFF$" />
       <add input="{HTTP_HOST}" pattern="192.168.1.10" negate="true" />
     </conditions>
  <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</code>```

Body:
You can negate a pattern using the negate attribute of the  element. when using this property, the rule action will only be performed if the current URL does not match the specified pattern. Here are the rules you can use as a reference:

<rule name="test" enabled="true" stopProcessing="true">
  <match url="(.*)" />
     <conditions>
       <add input="{HTTPS}" pattern="^OFF$" />
       <add input="{HTTP_HOST}" pattern="192.168.1.10" negate="true" />
     </conditions>
  <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>


答:
You need to change:

```<code>  Component?: JSX.Element | React.ReactNode | React.FunctionComponent;
</code>```

to:

```<code>  Component?: React.FunctionComponent;
</code>```

in MyRoute type.

Why? JSX.Element it is something like,
jsx element
 but your component must be a React component, e. g. function.

Title: How to fix 'JSX element type 'Component' does not have any construct or call signatures' in ts

Body:
I'm using react router like this.

I get the 'Component' from the routes, but ts throw an error, in the js, there is no Error.

import React from "react";
import { Route, Switch, useRouteMatch, withRouter } from "react-router-dom";
import type { MyRoute } from "./types";

const routes: MyRoute[] = [
  {
    path: "overview",
    Component: Index,
    title: "概览",
    name: "index",
    requireAuth: false,
  }
];

const MainRoute: React.FunctionComponent = () => {
  const match = useRouteMatch();
  const filter = (route: MyRoute): JSX.Element => {
    const { Component } = route;
    return (
      <Route
        key={route.path}
        path={`${match.path}/${route.path}`}
        exact
        render={(props) => {
          document.title = route.title;
          // throw error in this line:JSX element type 'Component' does not have any construct or call signatures.
          return <Component {...props} />;
        }}
      />
    );
  };
  return (
        <Switch>{routes.map(filter)}</Switch>);
};

export default withRouter(MainRoute);

there is a error:JSX element type 'Component' does not have any construct or call signatures.
how can I fix it

Body:
You need to change:

  Component?: JSX.Element | React.ReactNode | React.FunctionComponent;

to:

  Component?: React.FunctionComponent;

in MyRoute type.

Why? JSX.Element it is something like, <div>jsx element<div> but your component must be a React component, e. g. function.


问:
How to loop code for metaspades assembler through a number of samples?
I have a number of samples in the following format;

```<code>CUH001T1_unclassified_unpaired_R1

CUH001T1_unclassified_unpaired_R2

CUH002T2_unclassified_unpaired_R1

CUH002_T2_unclassified_unpaired_R2
</code>```

etc

I am assembling using metaspades and the following code;

spades.py --meta \
    --pe1-1 CUH001T1_unclassified_paired_R1.fastq \
    --pe1-2 CUH001T1_unclassified_paired_R2.fastq \
    -m 400 -o ../metaspades/CUH001T1
```
<p>I want to be able to loop this through all the samples. I have something like this;</p>
<pre class="lang-sh prettyprint-override"><code>for i in $(ls *.fastq | sort | uniq); do
    echo "spades.py --meta --pe1-1 "$i".fastq --pe1-2 "$i".fastq -o ../metaspades/"$i" >> metaspades.sh
done
</code>```

The desired output is the sample name for each

I know I need to do something to sort through the unclassified_paired part but I'm very new to bioinformatics and I'm unsure of what to do. Can anyone help?

答:
It's not clear to me what you are trying to do.  Your example "samples" are strings containing the string _unpaired_ and with no suffix.  Your example code involves files with names that contain _paired_  and have a suffix .fastq.

I guess you may have a directory containing multiple pairs of files like

```<code>XXX_unclassified_paired_R1.fastq
XXX_unclassified_paired_R2.fastq
</code>```

and for each of those pairs you want to run a command like

```<code>spades.py --meta \
    --pe1-1 XXX_unclassified_paired_R1.fastq \
    --pe1-2 XXX_unclassified_paired_R2.fastq \
    -m 400 -o ../metaspades/XXX
</code>```

If that is what you want, this Shellcheck-clean Bash program will print a list of the required commands if it is run in the directory containing the .fastq files:

```<code>#! /bin/bash -p

for pe1_1_file in *_unclassified_paired_R1.fastq; do
    base=${pe1_1_file%_unclassified_paired_R1.fastq}
    pe1_2_file=${base}_unclassified_paired_R2.fastq
    if [[ -e $pe1_2_file ]]; then
        printf 'spades.py --meta --pe1-1 %q --pe1-2 %q -m 400 -o ../metaspades/%q\n' \
            "$pe1_1_file" "$pe1_2_file" "$base"
    else
        printf "WARNING: '%s' does not exist\\n" "$pe1_2_file" >&2
    fi
done
</code>```

See Removing part of a string (BashFAQ/100 (How do I do string manipulation in bash?)) for an explanation of base=${pe1_1_file%_unclassified_paired_R1.fastq}.

The %q specifiers in the printf format string are to ensure that the generated commands will work even if the file names contain unusual characters.

Body:
I have a number of samples in the following format;

CUH001T1_unclassified_unpaired_R1

CUH001T1_unclassified_unpaired_R2

CUH002T2_unclassified_unpaired_R1

CUH002_T2_unclassified_unpaired_R2

etc

I am assembling using metaspades and the following code;

spades.py --meta \
    --pe1-1 CUH001T1_unclassified_paired_R1.fastq \
    --pe1-2 CUH001T1_unclassified_paired_R2.fastq \
    -m 400 -o ../metaspades/CUH001T1

I want to be able to loop this through all the samples. I have something like this;

for i in $(ls *.fastq | sort | uniq); do
    echo "spades.py --meta --pe1-1 "$i".fastq --pe1-2 "$i".fastq -o ../metaspades/"$i" >> metaspades.sh
done

The desired output is the sample name for each

I know I need to do something to sort through the unclassified_paired part but I'm very new to bioinformatics and I'm unsure of what to do. Can anyone help?

Body:
It's not clear to me what you are trying to do.  Your example "samples" are strings containing the string _unpaired_ and with no suffix.  Your example code involves files with names that contain _paired_  and have a suffix .fastq.

I guess you may have a directory containing multiple pairs of files like

XXX_unclassified_paired_R1.fastq
XXX_unclassified_paired_R2.fastq

and for each of those pairs you want to run a command like

spades.py --meta \
    --pe1-1 XXX_unclassified_paired_R1.fastq \
    --pe1-2 XXX_unclassified_paired_R2.fastq \
    -m 400 -o ../metaspades/XXX

If that is what you want, this Shellcheck-clean Bash program will print a list of the required commands if it is run in the directory containing the .fastq files:

#! /bin/bash -p

for pe1_1_file in *_unclassified_paired_R1.fastq; do
    base=${pe1_1_file%_unclassified_paired_R1.fastq}
    pe1_2_file=${base}_unclassified_paired_R2.fastq
    if [[ -e $pe1_2_file ]]; then
        printf 'spades.py --meta --pe1-1 %q --pe1-2 %q -m 400 -o ../metaspades/%q\n' \
            "$pe1_1_file" "$pe1_2_file" "$base"
    else
        printf "WARNING: '%s' does not exist\\n" "$pe1_2_file" >&2
    fi
done

See Removing part of a string (BashFAQ/100 (How do I do string manipulation in bash?)) for an explanation of base=${pe1_1_file%_unclassified_paired_R1.fastq}.

The %q specifiers in the printf format string are to ensure that the generated commands will work even if the file names contain unusual characters.


问:
Gridsplitter not showing
I am new to WPF.  I declared my Grid as so:

```<code><Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
    <ColumnDefinition Width="5"></ColumnDefinition>
    <ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
     <Grid.RowDefinitions>
         <RowDefinition Height="*"></RowDefinition>
         <RowDefinition Height="*"></RowDefinition>
         <RowDefinition Height="*"></RowDefinition>
     </Grid.RowDefinitions>
</Grid>
</code>```

I basically want that 3rd column of width 5 to be the GridSplitter and to be resizeable for the left and right columns.  So I have this code for the splitter:

```<code><GridSplitter Grid.Column="1" Grid.RowSpan="3" ResizeDirection="Columns" Height="Auto"
              VerticalAlignment="Stretch" HorizontalAlignment="Center"
              Margin="0" Background="Black"/>
</code>```

I do not see the GridSplitter in the column.  Did I set it up right?  Thanks.

答:
I just ran this XAML and it works fine

```<code><Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"></ColumnDefinition>
        <ColumnDefinition Width="5"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <TextBox Grid.Column="0" MinWidth="100" />
    <GridSplitter Grid.Column="1" Grid.RowSpan="3" ResizeDirection="Columns" HorizontalAlignment="Stretch" />

    <TextBox Grid.Column="2" MinWidth="100" />
</Grid>
</code>```

Are you sure you want to put three rows inside 0th column? because it doesn't make much sense

And you are doing this

```<code><GridSplitter Grid.Column="1" Grid.RowSpan="3" ResizeDirection="Columns" Height="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Center"
                            Margin="0" Background="Black"/>
</code>```

But apparently first column don't have three rows which I think you have mistakenly placed in column 0.

I think what you want to do is first XAML I wrote

Title: Gridsplitter not showing

Body:
I am new to WPF.  I declared my Grid as so:

<Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto"></ColumnDefinition>
    <ColumnDefinition Width="5"></ColumnDefinition>
    <ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
     <Grid.RowDefinitions>
         <RowDefinition Height="*"></RowDefinition>
         <RowDefinition Height="*"></RowDefinition>
         <RowDefinition Height="*"></RowDefinition>
     </Grid.RowDefinitions>
</Grid>

I basically want that 3rd column of width 5 to be the GridSplitter and to be resizeable for the left and right columns.  So I have this code for the splitter:

<GridSplitter Grid.Column="1" Grid.RowSpan="3" ResizeDirection="Columns" Height="Auto"
              VerticalAlignment="Stretch" HorizontalAlignment="Center"
              Margin="0" Background="Black"/>

I do not see the GridSplitter in the column.  Did I set it up right?  Thanks.

Body:
I just ran this XAML and it works fine

<Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"></ColumnDefinition>
        <ColumnDefinition Width="5"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="*"></RowDefinition>
    </Grid.RowDefinitions>

    <TextBox Grid.Column="0" MinWidth="100" />
    <GridSplitter Grid.Column="1" Grid.RowSpan="3" ResizeDirection="Columns" HorizontalAlignment="Stretch" />

    <TextBox Grid.Column="2" MinWidth="100" />
</Grid>

Are you sure you want to put three rows inside 0th column? because it doesn't make much sense

And you are doing this

<GridSplitter Grid.Column="1" Grid.RowSpan="3" ResizeDirection="Columns" Height="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Center"
                            Margin="0" Background="Black"/>

But apparently first column don't have three rows which I think you have mistakenly placed in column 0.

I think what you want to do is first XAML I wrote


问:
how to double array size (error on second time)
Some help here, trying to double the array in cpp

on the second resize I got this (messy output)

```<code>% ./sample
[5] 1 2 3 4 5
[20] 1 2 3 4 0 6 7 -1610612736 1 2 3 4 14 0 0 0 0 -1610612736 0 0
</code>```

the same removing the memset (to zero's the remaining positions)

```<code>#include <iostream>
#include <cstdlib>

using namespace std;

void resize(int* v, int* size){ // double the array size
    int newSize = (*size) * 2;
    v = (int *) realloc(v, (size_t) newSize);
    memset(v+(*size), 0, sizeof(int) * (newSize - *size) );
    *size = newSize;
}

int main(){
    int size = 5;
    int* v = new(nothrow) int[size]();

    v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    resize(v, &size);
    resize(v, &size);   // <- messy output

    v[5] = 6; v[6] = 7;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    return 0;
}
</code>```

thanks for the help,

答:
Use malloc() with realloc() or new and delete[] - not both

Your immediate problem is you pass a pointer to your function and the function receives a copy -- so any changes made to v in the function are made to a local copy of the pointer (which has its own and very different address than the pointer v in main())

Another problem is mixing new and realloc() which results in undefined behavior. Either use malloc() in main() or manually create and copy in your function using new and call delete[] on the original before assigning the new block.

Since this is C++, you can solve the problem easily by passing a pointer reference to the function (e.g. int*& v) so realloc() operates on the original pointer address instead of a copy.

NOTE: as JL mentioned in the comment, whenever you call realloc() you must assign the result to a temporary pointer which you validate realloc() succeeded before assigning to the original. When (not if) realloc() fails, it will return NULL overwriting your original pointer with NULL leaving that block of memory unable to be freed creating a memory leak.

To use a temporary pointer with realloc(), you would do:

void resize(int*& v, int *size){ // double the array size
    int newSize = (*size) * 2;

    /* always realloc with temporary pointer so if realloc fails
     * you don't overwrite your orignal pointer with NULL creating
     * a memory leak.
     */
    int *tmp = (int *)realloc (v, (size_t) newSize * sizeof *v);
    if (!tmp) {   /* validate every allocation */
        perror ("realloc-v");
        return;
    }
    v = tmp;      /* successful realloc(), assign tmp to v */

    memset (v+(*size), 0, sizeof(int) * *size );
    *size = newSize;
}
```
<p>Also, in <code>main()</code> to use <code>realloc()</code> you must originally allocate with <code>malloc()</code> (or <code>calloc()</code>, or <code>realloc()</code>, but not <code>new</code>). Further, guard your loop scopes or if you are not going to guard the scope with <code>{...}</code> then at least properly indent so your intent is clear, e.g.</p>
<pre class="lang-cpp prettyprint-override"><code>int main(){
    int size = 5;
    int *v = (int*)malloc(size * sizeof *v);

    v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5;

    cout << "[" << size << "] ";
    for (int i = 0; i < size; i++)
        cout << v[i] << " ";
    cout << endl;

    resize(v, &size);
    resize(v, &size);

    if (size > 6) {     /* validate size / protect memory bounds */
        v[5] = 6;
        v[6] = 7;
    }

    cout << "[" << size << "] ";
    for (int i = 0; i < size; i++)
        cout << v[i] << " ";
    cout << endl;

    return 0;
}
</code>```

(you should also add #include <cstring> for memset())

Using new and delete[]

You can leave your allocation in main() as is, if you create a new block in your function with double the size using new, copy values to the new block (and initialize the rest to 0) and call delete[] on the original block before assigning your new block to the original pointer.

In that case you would do something like:

void resize(int*& v, int *size){ // double the array size
    int newSize = (*size) * 2;

    /* create a new block of newSize */
    int *tmp = new(nothrow) int[newSize]();
    /* copy/initialize */
    for (int i = 0; i < newSize; i++) {
        if (i < *size)
            tmp[i] = v[i];
        else
            tmp[i] = 0;
    }
    delete[] v;   /* free original block */
    v = tmp;      /* assign tmp to v */

    *size = newSize;
}
```
<p><strong>Example Use/Output</strong></p>
<p>In either case (<code>malloc()</code>, <code>realloc()</code>) or (<code>new</code>, <code>delete[]</code>) the results are the same:</p>
<pre class="lang-none prettyprint-override"><code>$ ./bin/realloc_arr
[5] 1 2 3 4 5
[20] 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0 0 0 0 0 0
</code>```

In both cases you will want to verify your memory use with valgrind or similar memory use/error check for your OS. You will need to add either free(v) or delete[] v at the end of main() to handle freeing all memory you allocate for the purpose of the memory check (it will be freed after the program exits, but without an explicity free in main() it will still be shown as in use on program exit.

To use valgrind, just run your program through it. After making the changes above, you would have:

$  valgrind ./bin/realloc_arr
==22674== Memcheck, a memory error detector
==22674== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==22674== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==22674== Command: ./bin/realloc_arr
==22674==
[5] 1 2 3 4 5
[20] 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0 0 0 0 0 0
==22674==
==22674== HEAP SUMMARY:
==22674==     in use at exit: 0 bytes in 0 blocks
==22674==   total heap usage: 5 allocs, 5 frees, 73,868 bytes allocated
==22674==
==22674== All heap blocks were freed -- no leaks are possible
==22674==
==22674== For counts of detected and suppressed errors, rerun with: -v
==22674== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
```

Always ensure all blocks are freed and there are no memory errors.

Body:
Some help here, trying to double the array in cpp

on the second resize I got this (messy output)

% ./sample
[5] 1 2 3 4 5
[20] 1 2 3 4 0 6 7 -1610612736 1 2 3 4 14 0 0 0 0 -1610612736 0 0

the same removing the memset (to zero's the remaining positions)

#include <iostream>
#include <cstdlib>

using namespace std;

void resize(int* v, int* size){ // double the array size
    int newSize = (*size) * 2;
    v = (int *) realloc(v, (size_t) newSize);
    memset(v+(*size), 0, sizeof(int) * (newSize - *size) );
    *size = newSize;
}

int main(){
    int size = 5;
    int* v = new(nothrow) int[size]();

    v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    resize(v, &size);
    resize(v, &size);   // <- messy output

    v[5] = 6; v[6] = 7;

    cout << "[" << size << "] ";
    for(int i = 0; i < size; i++) cout << v[i] << " "; cout << endl;

    return 0;
}

thanks for the help,

Body:
Use malloc() with realloc() or new and delete[] - not both

Your immediate problem is you pass a pointer to your function and the function receives a copy -- so any changes made to v in the function are made to a local copy of the pointer (which has its own and very different address than the pointer v in main())

Another problem is mixing new and realloc() which results in undefined behavior. Either use malloc() in main() or manually create and copy in your function using new and call delete[] on the original before assigning the new block.

Since this is C++, you can solve the problem easily by passing a pointer reference to the function (e.g. int*& v) so realloc() operates on the original pointer address instead of a copy.

NOTE: as JL mentioned in the comment, whenever you call realloc() you must assign the result to a temporary pointer which you validate realloc() succeeded before assigning to the original. When (not if) realloc() fails, it will return NULL overwriting your original pointer with NULL leaving that block of memory unable to be freed creating a memory leak.

To use a temporary pointer with realloc(), you would do:

void resize(int*& v, int *size){ // double the array size
    int newSize = (*size) * 2;

    /* always realloc with temporary pointer so if realloc fails
     * you don't overwrite your orignal pointer with NULL creating
     * a memory leak.
     */
    int *tmp = (int *)realloc (v, (size_t) newSize * sizeof *v);
    if (!tmp) {   /* validate every allocation */
        perror ("realloc-v");
        return;
    }
    v = tmp;      /* successful realloc(), assign tmp to v */

    memset (v+(*size), 0, sizeof(int) * *size );
    *size = newSize;
}

Also, in main() to use realloc() you must originally allocate with malloc() (or calloc(), or realloc(), but not new). Further, guard your loop scopes or if you are not going to guard the scope with {...} then at least properly indent so your intent is clear, e.g.

int main(){
    int size = 5;
    int *v = (int*)malloc(size * sizeof *v);

    v[0] = 1; v[1] = 2; v[2] = 3; v[3] = 4; v[4] = 5;

    cout << "[" << size << "] ";
    for (int i = 0; i < size; i++)
        cout << v[i] << " ";
    cout << endl;

    resize(v, &size);
    resize(v, &size);

    if (size > 6) {     /* validate size / protect memory bounds */
        v[5] = 6;
        v[6] = 7;
    }

    cout << "[" << size << "] ";
    for (int i = 0; i < size; i++)
        cout << v[i] << " ";
    cout << endl;

    return 0;
}

(you should also add #include <cstring> for memset())

Using new and delete[]

You can leave your allocation in main() as is, if you create a new block in your function with double the size using new, copy values to the new block (and initialize the rest to 0) and call delete[] on the original block before assigning your new block to the original pointer.

In that case you would do something like:

void resize(int*& v, int *size){ // double the array size
    int newSize = (*size) * 2;

    /* create a new block of newSize */
    int *tmp = new(nothrow) int[newSize]();
    /* copy/initialize */
    for (int i = 0; i < newSize; i++) {
        if (i < *size)
            tmp[i] = v[i];
        else
            tmp[i] = 0;
    }
    delete[] v;   /* free original block */
    v = tmp;      /* assign tmp to v */

    *size = newSize;
}

Example Use/Output

In either case (malloc(), realloc()) or (new, delete[]) the results are the same:

$ ./bin/realloc_arr
[5] 1 2 3 4 5
[20] 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0 0 0 0 0 0

In both cases you will want to verify your memory use with valgrind or similar memory use/error check for your OS. You will need to add either free(v) or delete[] v at the end of main() to handle freeing all memory you allocate for the purpose of the memory check (it will be freed after the program exits, but without an explicity free in main() it will still be shown as in use on program exit.

To use valgrind, just run your program through it. After making the changes above, you would have:

$  valgrind ./bin/realloc_arr
==22674== Memcheck, a memory error detector
==22674== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==22674== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==22674== Command: ./bin/realloc_arr
==22674==
[5] 1 2 3 4 5
[20] 1 2 3 4 5 6 7 0 0 0 0 0 0 0 0 0 0 0 0 0
==22674==
==22674== HEAP SUMMARY:
==22674==     in use at exit: 0 bytes in 0 blocks
==22674==   total heap usage: 5 allocs, 5 frees, 73,868 bytes allocated
==22674==
==22674== All heap blocks were freed -- no leaks are possible
==22674==
==22674== For counts of detected and suppressed errors, rerun with: -v
==22674== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always ensure all blocks are freed and there are no memory errors.


问:
how to using jq command to Delete the specified multi-line field
I want to use the jq command to filter out the architecture I want in the manifest file of docker

```<code>cat manifest.json |jq -r
{
  "schemaVersion": 2,
  "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
  "manifests": [
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1785,
      "digest": "sha256:34860ea294a018d392e61936f19a7862d5e92039d196cac9176da14b2bbd0fe3",
      "platform": {
        "architecture": "amd64",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1996,
      "digest": "sha256:93d5f2293f6faf76fc3f2ff30628cf2100b68e3cf16901f39f01d449e67f67d9",
      "platform": {
        "architecture": "arm",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1996,
      "digest": "sha256:a0000b627744766025f552c4db171a00b055d5d709f22aec8be96b6375b220cf",
      "platform": {
        "architecture": "arm64",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1995,
      "digest": "sha256:227c06dc0468dacfcfc04cc0aad3f5138a51bb2afa4d8252c6e83ca39beb8c6f",
      "platform": {
        "architecture": "ppc64le",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1996,
      "digest": "sha256:e7cfbfe13f7a179277f55a835abc0b01f9c6c21892c1ae1b0007f2e09777bca0",
      "platform": {
        "architecture": "s390x",
        "os": "linux"
      }
    }
  ]
}
</code>```
```<code>cat manifest.json |jq -r 'del(.manifests[] |select(.platform.architecture=="arm" and .platform.architecture=="ppc64le"))'
</code>```

The above command does not take effect. If I only want to keep the amd64 and arm64 architectures in the manifest file, how should I write this command?

答:
You should use or instead of and since a field can only have one of those options (if at all), never both.

According to "I only want to keep the amd64 and arm64 architectures",  instead of deleting you can simply go the keeping route:

jq '
  .manifests |= map(select(
    .platform.architecture == "arm64" or .platform.architecture == "amd64"
  ))
'
```
<p>Demo</p>
<p>If you're using jq 1.6 or later, you can simplify this using the <code>IN</code> filter:</p>
<pre class="lang-sh prettyprint-override"><code>jq '
  .manifests |= map(select(
    IN(.platform.architecture; "arm64", "amd64")
  ))
'
</code>```

Demo

Output

{
  "schemaVersion": 2,
  "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
  "manifests": [
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1785,
      "digest": "sha256:34860ea294a018d392e61936f19a7862d5e92039d196cac9176da14b2bbd0fe3",
      "platform": {
        "architecture": "amd64",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1996,
      "digest": "sha256:a0000b627744766025f552c4db171a00b055d5d709f22aec8be96b6375b220cf",
      "platform": {
        "architecture": "arm64",
        "os": "linux"
      }
    }
  ]
}
```

Body:
I want to use the jq command to filter out the architecture I want in the manifest file of docker

cat manifest.json |jq -r
{
  "schemaVersion": 2,
  "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
  "manifests": [
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1785,
      "digest": "sha256:34860ea294a018d392e61936f19a7862d5e92039d196cac9176da14b2bbd0fe3",
      "platform": {
        "architecture": "amd64",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1996,
      "digest": "sha256:93d5f2293f6faf76fc3f2ff30628cf2100b68e3cf16901f39f01d449e67f67d9",
      "platform": {
        "architecture": "arm",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1996,
      "digest": "sha256:a0000b627744766025f552c4db171a00b055d5d709f22aec8be96b6375b220cf",
      "platform": {
        "architecture": "arm64",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1995,
      "digest": "sha256:227c06dc0468dacfcfc04cc0aad3f5138a51bb2afa4d8252c6e83ca39beb8c6f",
      "platform": {
        "architecture": "ppc64le",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1996,
      "digest": "sha256:e7cfbfe13f7a179277f55a835abc0b01f9c6c21892c1ae1b0007f2e09777bca0",
      "platform": {
        "architecture": "s390x",
        "os": "linux"
      }
    }
  ]
}

cat manifest.json |jq -r 'del(.manifests[] |select(.platform.architecture=="arm" and .platform.architecture=="ppc64le"))'

The above command does not take effect. If I only want to keep the amd64 and arm64 architectures in the manifest file, how should I write this command?

Body:
You should use or instead of and since a field can only have one of those options (if at all), never both.

According to "I only want to keep the amd64 and arm64 architectures",  instead of deleting you can simply go the keeping route:

jq '
  .manifests |= map(select(
    .platform.architecture == "arm64" or .platform.architecture == "amd64"
  ))
'

Demo

If you're using jq 1.6 or later, you can simplify this using the IN filter:

jq '
  .manifests |= map(select(
    IN(.platform.architecture; "arm64", "amd64")
  ))
'

Demo

Output

{
  "schemaVersion": 2,
  "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",
  "manifests": [
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1785,
      "digest": "sha256:34860ea294a018d392e61936f19a7862d5e92039d196cac9176da14b2bbd0fe3",
      "platform": {
        "architecture": "amd64",
        "os": "linux"
      }
    },
    {
      "mediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "size": 1996,
      "digest": "sha256:a0000b627744766025f552c4db171a00b055d5d709f22aec8be96b6375b220cf",
      "platform": {
        "architecture": "arm64",
        "os": "linux"
      }
    }
  ]
}