问:
How to filter sensitive data server-side for object based on scenario
Scenario:

Class Example, subclassed from PFObject. Some sensitive properties are optional/can be nil.

User A creates examples locally on the client and saves it directly to the server (with ACL set to this user only)

User B should only see a subset of this data.

My approach:

create a cloud code function getExample for User B to call

getExample queries those examples, deletes all sensitive properties on the results (or recreates the object with only allowed properties) and returns those filtered objects.

Problem:

Whats the best approach to tell the parse engine that the return value is actually of type Example and make it parse it automatically? (call to server is via PFCloud.callFunction(inBackground: ...))?

Thank you (also, any architecture advise highly appreciated).

答:
Decoding backend JSON responses in Swift is almost trivial nowadays, with the Decodable protocol and the JSONDecoder class from the Foundation library.

Here's an example with an optional field:

import Foundation

let jsonString1 = """
{
    "stringField" : "stringValue",
    "intField" : 1,
    "floatField" : 1.1
}
"""

let jsonString2 = """
{
    "stringField" : "stringValue",
    "intField" : 1,
    "floatField" : 1.1,
    "optionalField" : "optionalValue"
}
"""

struct Response: Decodable {
    let stringField: String
    let intField: Int
    let floatField: Double
    let optionalField: String?
}

let response1 = try! JSONDecoder().decode(Response.self, from: jsonString1.data(using: .utf8)!)
// Response(stringField: "stringValue", intField: 1, floatField: 1.1, optionalField: nil)

let response2 = try! JSONDecoder().decode(Response.self, from: jsonString2.data(using: .utf8)!)
// Response(stringField: "stringValue", intField: 1, floatField: 1.1, optionalField: Optional("optionalValue"))

```
<p><strong>And one more example, with a nested object:</strong></p>
<pre class="lang-swift prettyprint-override"><code>import Foundation

let jsonString = """
{
    "stringField" : "stringValue",
    "nestedObject" :
        {
            "intValue" : 2
        }
}
"""

struct Response: Decodable {

    struct NestedType: Decodable {
        let intValue: Int
    }

    let stringField: String
    let nestedObject: NestedType

}

let response = try! JSONDecoder().decode(Response.self, from: jsonString.data(using: .utf8)!)
// Response(stringField: "stringValue", nestedObject: __lldb_expr_10.Response.NestedType(intValue: 2))

</code>```

An example with a date:

import Foundation

let jsonString = """
{
    "date" : "2021-02-04 09:38:33.000"
}
"""

struct Response: Decodable {
    let date: Date
}

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)

let response = try! decoder.decode(Response.self, from: jsonString.data(using: .utf8)!)
// Response(date: 2021-02-04 09:38:33 +0000)
```
<p>Find out more here.</p>
<p><strong>UPDATE</strong></p>
<p>After discussion it became clear that the problem is that the object to parse is a dictionary containing objects that cannot be represented in JSON natively (e.g. <code>Data</code>/<code>NSData</code>). In this case it's possible to convert them into something representable (e.g. for dates it can be a formatted <code>String</code>). Here's an example involving <code>NSDate</code> and <code>JSONSerialization</code>:</p>
<pre class="lang-swift prettyprint-override"><code>import Foundation

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

let jsonDict1 = ["stringField" : "stringValue"]
let jsonData1 = try JSONSerialization.data(withJSONObject: jsonDict1)

let date = NSDate()
let jsonDict2: [String : Any] = ["stringField" : "stringValue",
                                 "optionalDate" : dateFormatter.string(from: date as Date)]
let jsonData2 = try JSONSerialization.data(withJSONObject: jsonDict2)

struct Response: Decodable {
  let stringField: String
  let optionalDate: Date?
}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)

let response1 = try! decoder.decode(Response.self, from: jsonData1)
// Response(stringField: "stringValue", optionalDate: nil)

let response2 = try! decoder.decode(Response.self, from: jsonData2)
// Response(stringField: "stringValue", optionalDate: Optional(2022-02-21 13:48:48 +0000))
</code>```

Body:
Decoding backend JSON responses in Swift is almost trivial nowadays, with the Decodable protocol and the JSONDecoder class from the Foundation library.

Here's an example with an optional field:

import Foundation

let jsonString1 = """
{
    "stringField" : "stringValue",
    "intField" : 1,
    "floatField" : 1.1
}
"""

let jsonString2 = """
{
    "stringField" : "stringValue",
    "intField" : 1,
    "floatField" : 1.1,
    "optionalField" : "optionalValue"
}
"""

struct Response: Decodable {
    let stringField: String
    let intField: Int
    let floatField: Double
    let optionalField: String?
}

let response1 = try! JSONDecoder().decode(Response.self, from: jsonString1.data(using: .utf8)!)
// Response(stringField: "stringValue", intField: 1, floatField: 1.1, optionalField: nil)

let response2 = try! JSONDecoder().decode(Response.self, from: jsonString2.data(using: .utf8)!)
// Response(stringField: "stringValue", intField: 1, floatField: 1.1, optionalField: Optional("optionalValue"))

And one more example, with a nested object:

import Foundation

let jsonString = """
{
    "stringField" : "stringValue",
    "nestedObject" :
        {
            "intValue" : 2
        }
}
"""

struct Response: Decodable {

    struct NestedType: Decodable {
        let intValue: Int
    }

    let stringField: String
    let nestedObject: NestedType

}

let response = try! JSONDecoder().decode(Response.self, from: jsonString.data(using: .utf8)!)
// Response(stringField: "stringValue", nestedObject: __lldb_expr_10.Response.NestedType(intValue: 2))

An example with a date:

import Foundation

let jsonString = """
{
    "date" : "2021-02-04 09:38:33.000"
}
"""

struct Response: Decodable {
    let date: Date
}

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)

let response = try! decoder.decode(Response.self, from: jsonString.data(using: .utf8)!)
// Response(date: 2021-02-04 09:38:33 +0000)

Find out more here.

UPDATE

After discussion it became clear that the problem is that the object to parse is a dictionary containing objects that cannot be represented in JSON natively (e.g. Data/NSData). In this case it's possible to convert them into something representable (e.g. for dates it can be a formatted String). Here's an example involving NSDate and JSONSerialization:

import Foundation

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

let jsonDict1 = ["stringField" : "stringValue"]
let jsonData1 = try JSONSerialization.data(withJSONObject: jsonDict1)

let date = NSDate()
let jsonDict2: [String : Any] = ["stringField" : "stringValue",
                                 "optionalDate" : dateFormatter.string(from: date as Date)]
let jsonData2 = try JSONSerialization.data(withJSONObject: jsonDict2)

struct Response: Decodable {
  let stringField: String
  let optionalDate: Date?
}

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(dateFormatter)

let response1 = try! decoder.decode(Response.self, from: jsonData1)
// Response(stringField: "stringValue", optionalDate: nil)

let response2 = try! decoder.decode(Response.self, from: jsonData2)
// Response(stringField: "stringValue", optionalDate: Optional(2022-02-21 13:48:48 +0000))


来源: stackexchange

问:
How to connect Django Rest API to a html CSS JS frontend
I am new to programming and one thing I am very confused about, my boss has told me to create a rest API about an app which I have completed all the signups, login, and other parts. But now I have to create a frontend but all the tutorials on the internet are about create rest API of Django to react or some other frontend framework, is their any tutorial on YouTube about connecting to a html CSS JavaScript on frontend to Rest API. thanks.</p>

答:
If you don't want a frontend just follow the official django tutorial to learn how to serve html/css/js from django.

From there you can either pass the data you need from your api down through the django context, or you can use fetch or something similar to grab it from javascript.

The latter would look like this.

```<code># views.py
def index(request):
    return render(request, 'index.html')

def apiview(request):
    return JsonResponse({'title', 'served from api'})

</code>```
```<code>index.html
<div class="title" token={{csrf_token}}></div>
<script>
function getTitle() {
    const div = document.querySelector('title')
    const csrf_token = div.getAttribute('token')
    fetch('localhost:8000/apiview', {
        method: 'get',
        headers: {'X-CSRFToken': token}
    })
    .then(data => data.json())
    .then(data => div.innerHTML = data.title)
}
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you don't want a frontend just follow the official django tutorial to learn how to serve html/css/js from django.

From there you can either pass the data you need from your api down through the django context, or you can use fetch or something similar to grab it from javascript.

The latter would look like this.

# views.py
def index(request):
    return render(request, 'index.html')

def apiview(request):
    return JsonResponse({'title', 'served from api'})

index.html
<div class="title" token={{csrf_token}}></div>
<script>
function getTitle() {
    const div = document.querySelector('title')
    const csrf_token = div.getAttribute('token')
    fetch('localhost:8000/apiview', {
        method: 'get',
        headers: {'X-CSRFToken': token}
    })
    .then(data => data.json())
    .then(data => div.innerHTML = data.title)
}
</script>


问:
Dynamically building WHERE clauses in SQL statements
I have a question regarding SQL. I have the following SQL statement:

```<code>SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;
</code>```

I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?

Thanks

答:
It depends on how you are going to find out the value of SOMETHING_SHOULD_BE_HERE.

If you are in an Oracle PLS/SQL environment you could build up the WHERE clause using dynamic SQL and then use EXECUTE IMMEDIATE to execute it.

If you have a small set number of possibilities you could use CASE to workaround your problem possibly.

ContentLicense: CC BY-SA 3.0

Body:
I have a question regarding SQL. I have the following SQL statement:

SELECT id, First, Last, E_Mail, Notes
FROM mytable
WHERE SOMETHING_SHOULD_BE_HERE IS NOT NULL;

I know that the SOMETHING_SHOULD_BE_HERE should be a column(attribute) in my table. Is their a way I can put a variable that can refer to the column I'm trying to access? In my case their are 30 columns. Can I have a string for SOMETHING_SHOULD_BE_HERE that can be assigned in my program to the column in which I want to search?

Thanks


问:
Flutter change color of drawer scrim
Is it possible o change the color or transparency of the drawer's scrim in flutter? Something like is Java's drawerLayout.setScrimColor(Color.TRANSPARENT);?

Thanks.

答:
You can change drawerTheme like this:</p>
```<code>return ThemeData(
      drawerTheme: DrawerThemeData(
        scrimColor: Colors.transparent,
      ),
    );
</code>```

Title: Flutter change color of drawer scrim

Body:
You can change drawerTheme like this:

return ThemeData(
      drawerTheme: DrawerThemeData(
        scrimColor: Colors.transparent,
      ),
    );


问:
Does Pandas have a dataframe length limit?
I want to create a system where I load and analyze large amounts of data into pandas. Also, I will later use this to write back to .parquet files

when I try to test this using a simple example, I see that there is some kind of built in limit on the number of rows

```<code>import pandas as pd

# Create file with 100 000 000 rows
contents = """
Tommy;19
Karen;20
"""*50000000

open("person.csv","w").write(
f"""
Name;Age
{contents}
"""
)
print("Test generated")

df = pd.read_csv("person.csv",delimiter=";")
len(df)
</code>```

returns 10 000 000. Not 100 000 000

答: The main bottleneck is your memory, Pandas uses NumPy under the hood. So you can fit 10M rows until it's not an issue for your computer</p>

Body:
I want to create a system where I load and analyze large amounts of data into pandas. Also, I will later use this to write back to .parquet files

when I try to test this using a simple example, I see that there is some kind of built in limit on the number of rows

import pandas as pd

# Create file with 100 000 000 rows
contents = """
Tommy;19
Karen;20
"""*50000000

open("person.csv","w").write(
f"""
Name;Age
{contents}
"""
)
print("Test generated")

df = pd.read_csv("person.csv",delimiter=";")
len(df)

returns 10 000 000. Not 100 000 000


问:
How to add specific values to a list in python?
I want to do a simple plot between x and y where my x is x = np.arange(0,100). My "y" values are mainly 0 but at some places it has a value of 0.5 and 1. Right now I have to write the whole values of y in a list as y = [0,0,0,0,0,0,0,0.5,0.5,0,0,......,1.....0]. Is there a way where I can just write y = np.arange(0,100) to maintain the dimensionality of x and y and then input the specific values of y at the correct place? For example, at 8th position the y value is 0.5. So I want to write y = np.arange(0,100) and then input 0.5 at the 8th position of "y". Otherwise I have to manually write the whole y list. Thank for the help in advance.

答:
You could just use

y = np.zeroes(100)

and then change the specific values just like you would do with lists by

y[position where you would like to change] = 0.5


问:
Pandas not appending values to data frame
I have a file called balance.csv. It contains user data such as their discord ID number, their account balance, and the amount of stocks that they own. I'm trying to create a simple command using discord.py that lets them know their account balance. If they don't have an account, it initializes one for them. However, the values aren't being appended to the CSV file when the code tries to initialize the account. I am not sure where the problem is and why it is occurring. I'm using pandas and discord.py.</p>
```<code>balance_data = pd.read_csv('balance.csv')

def init_account(id):
    global balance_data
    balance_data = balance_data.append({"user_id":id, "account_balance":100, "stocks":0}, ignore_index=True)

@client.command(name='bal')
async def balance(ctx):
    if ctx.author.id not in balance_data["user_id"].values:
        await ctx.send("Creating Account...")
        init_account(ctx.author.id)
        await ctx.send("Account created.")
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")
    else:
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")
</code>```

答: Read data frame with read_csv -> apply some changes (for example append sth)-> Write data frame to file with to_csv</p>

Body:
I have a file called balance.csv. It contains user data such as their discord ID number, their account balance, and the amount of stocks that they own. I'm trying to create a simple command using discord.py that lets them know their account balance. If they don't have an account, it initializes one for them. However, the values aren't being appended to the CSV file when the code tries to initialize the account. I am not sure where the problem is and why it is occurring. I'm using pandas and discord.py.

balance_data = pd.read_csv('balance.csv')

def init_account(id):
    global balance_data
    balance_data = balance_data.append({"user_id":id, "account_balance":100, "stocks":0}, ignore_index=True)

@client.command(name='bal')
async def balance(ctx):
    if ctx.author.id not in balance_data["user_id"].values:
        await ctx.send("Creating Account...")
        init_account(ctx.author.id)
        await ctx.send("Account created.")
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")
    else:
        r_val = balance_data.loc[balance_data["user_id"]==ctx.author.send]
        user_bal = balance_data['account_balance'].iloc[r_val]
        await ctx.send(f"You have {user_bal} credits.")


问:
how to pass JSON object in addSeries() method for Dojo Spider Chart
I am trying to implement a Spider Chart using dojo chart library. I am using a dummy example from dojo: http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/charting/tests/test_spider2d.html

It uses the addSeries method like this:

```<code>chart1.addSeries("China", {data: {"GDP": 2,"area": 6,"population": 2000,"inflation": 15,"growth": 12}}, { fill: "blue" });
chart1.addSeries("France", {data: {"GDP": 6,"area": 15,"population": 500,"inflation": 5,"growth": 6}}, { fill: "red" });
chart1.addSeries("USA", {data: {"GDP": 3,"area": 20,"population": 1500,"inflation": 10,"growth": 3}}, { fill: "green" });
</code>```

..and so on..

```<code>chart1.render();
</code>```

But I want to pass in the data dynamically. I have got my data something like following:

```<code>var obj1 = [{
        "qNo": "THR1",
        "qAns": "3"
    }, {
        "qNo": "THR2",
        "qAns": "3"
    }, {
        "qNo": "THR3",
        "qAns": "1"
    }, {
        "qNo": "THR4",
        "qAns": "3"
    }, {
        "qNo": "THR5",
        "qAns": "3"
    }, {
        "qNo": "THR7",
        "qAns": "3"
    }
];
</code>```

I have got obj2 as well of same structure but with different qAns values.

So I want to use obj1 and obj2 in place of "China" and "France" as given in the example above.

So i want something like

```<code>chart1.addSeries("obj1", {data: {obj1 data needs to go here but how?}}, { fill: "blue" });
chart1.addSeries("obj2", {data: {obj1 data needs to go here but how?}}, { fill: "red" });
</code>```

Can you please help me what syntax shall I use to pass in obj variables in addSeries method? I have a small idea that i need to use it as JSON object and convert it to datastore and pass in the datastore, but I am unable to get the syntax working.

Please help ! thanx a lot.
Regards

答: I have never worked with charts but I would look for some examples related to DataGrids that are a bit more widespread. See for example here: Dojo grid nested json </p>

Body:
I am trying to implement a Spider Chart using dojo chart library. I am using a dummy example from dojo: http://archive.dojotoolkit.org/nightly/dojotoolkit/dojox/charting/tests/test_spider2d.html

It uses the addSeries method like this:

chart1.addSeries("China", {data: {"GDP": 2,"area": 6,"population": 2000,"inflation": 15,"growth": 12}}, { fill: "blue" });
chart1.addSeries("France", {data: {"GDP": 6,"area": 15,"population": 500,"inflation": 5,"growth": 6}}, { fill: "red" });
chart1.addSeries("USA", {data: {"GDP": 3,"area": 20,"population": 1500,"inflation": 10,"growth": 3}}, { fill: "green" });

..and so on..

chart1.render();

But I want to pass in the data dynamically. I have got my data something like following:

var obj1 = [{
        "qNo": "THR1",
        "qAns": "3"
    }, {
        "qNo": "THR2",
        "qAns": "3"
    }, {
        "qNo": "THR3",
        "qAns": "1"
    }, {
        "qNo": "THR4",
        "qAns": "3"
    }, {
        "qNo": "THR5",
        "qAns": "3"
    }, {
        "qNo": "THR7",
        "qAns": "3"
    }
];

I have got obj2 as well of same structure but with different qAns values.

So I want to use obj1 and obj2 in place of "China" and "France" as given in the example above.

So i want something like

chart1.addSeries("obj1", {data: {obj1 data needs to go here but how?}}, { fill: "blue" });
chart1.addSeries("obj2", {data: {obj1 data needs to go here but how?}}, { fill: "red" });

Can you please help me what syntax shall I use to pass in obj variables in addSeries method? I have a small idea that i need to use it as JSON object and convert it to datastore and pass in the datastore, but I am unable to get the syntax working.

Please help ! thanx a lot.
Regards


问:
3D surface reconstruction from a sparse point cloud
I have an equipment which performs radial scan. It scans an object along the green lines showing in the image(three lines in the image, but the equipment can perform more).

Thus, I can get a point cloud, which contains points from the upper and lower surfaces of the object. And I want to make surface reconstruction using the point cloud.
I load the point cloud file(.txt format, xyz coordinates of each point) into Meshlab and it shows like this(yellow points are the points in the point cloud):

I then followed a blog teaching simple usage of Meshlab and clicked "Fiter——>Normals,Curtavures and Oreientation——>Smooths normals on a point set" and "Fiter——>Remeshing Simplication and Reconstruction——>Surface Reconstruction：Ball Pivoting". (both default setting)

However, the results was not I want:

It connects points within a scanned image, but the surface should be reconstructed by connecting points between adjacent scanned images.

I can think about two possible reasons:(1) I did not choose right setting in Meshlab. If so, which setting parameters can make reconstruction for the point cloud. (2)My point cloud is too sparse and I need to interpolate the point cloud to make it have more points and which interpolation method should I use?

————————————————————EDIT———————————————————

The normals computed in this image are computed using Neighbour num 10 and smooth iteration 8.

And, the normals computed in this image are computed using Neighbour num 60 and smooth iteration 8. When Neighbour num is greater than 20, normals are similar to the image below.

答:
It is possible that you are having problems due to inequality directional sampling of the surface. You have high density of points in one direction, then a big gap in the other direction. This is a problem due to 'Compute normals for point sets' filter uses a parameter with the number of Neighbours to each point, so the computer normal will be byassed because there is unlikely to find neighbours in a different scanline.

So my proposal is (I will reuse parts from this tutorial )

Point Cloud Simplification and Normals Computation

Start by increasing the number of orientations in the scan. You want to fill those gaps.

If you need to reduce the number of point samples in the center of the object to reduce noise, go to Filters -> Point Set -> Point Cloud Simplification. Make sure Best Sample Heuristic is checked.

After point cloud simplification, make sure to select Simplified point cloud in the Show Layer Dialog on the right hand side. If not visible, it can be opened by navigating to View -> Show Layer Dialog. Now we need to compute normals for point set.

So go to Filters -> Point Set -> Compute normals for point sets . Enter Neighbour num between 10 - 100. Initially try with 10 and try to get a mesh and later see if this can be improved by increasing the neighbour number. For Smooth Iteration initially try with 0 value and may be later it can be tried with values between 5 - 10. I mostly use value 8.

Make sure if your normals are properly computed by going to  Render -> Show Normal.

Meshing /  Poisson Surface Reconstruction

Next we are going to use Poisson Surface reconstruction to do meshing.

So go to Filters ->Remeshing, Simplification and Reconstruction -> Screened Poisson Surface Reconstruction. Initially try with default parameters then later one can play around with reconstruction depth, number of samples and interpolation weight values.

This will create another mesh layer called Poisson in the Show layer Dialog which has surfaces now. Make sure to select that to peform further operations.

One can observe that it has also created some extra surfaces. To remove them go to Filters -> Selection -> Select Faces with edges longer than .... By default the value is automatically computed, just click on apply. Then click on delete face button (triangle face and three vertex with a cross over it). This will remove extra surfaces.

After this operation, still some noise faces can be seen. To remove them go to Filters -> Cleaning and Repairing -> Remove isolated pieces (wrt Face Num.). Use the default value and make sure Remove unreferenced vertices is checked. This will remove some noise faces.

Even after the above operation some noise faces are seen. To remove them go to Filters -> Selection -> Select non Manifold Vertices. Click apply. Then click on delete face button (triangle and threwe vertex with a cross over it). This will remove remaining extra faces.


问:
dart analysis server terminated vs code
2 days ago, I upgraded Flutter and since then, dart has basically stopped working in VS Code. By that, I mean that VS Code does not identify any error in Flutter app. No Coding error and no package error. Nothing happens if I press Cmd Enter Whenever I start VS Code, I get the same errors and these errors are: 1: The Dart Analysis Server server crashed 5 times in the last 3 minutes. The server will not be restarted.

2: Dart DevTools exited with code 255. Would you like to try reactivating DevTools?

3: The Dart Analyzer has terminated.

So far, I have tried numerous solutions which include downgrading flutter version to 2.8.1, 2.5.0. I have also tried running the command flutter pub global activate devtools -v 2.8.0. I have even tried uninstalling vs code and installing it from scratch.

Is there any solution to this mess? Is there anyone else with this same issue recently?
Thanks!!!

Flutter Version: 2.10.0
macOS Version: 11.4(Big Sur)

P.S. Seems to be a problem in VS Code only since it seems to be working fine in IntelliJ. Still, no solution though.

答:
Ok, so, after searching long and hard for this. I cam across a similar question here on StackOverflow and the answer provided by the person who posted that question, worked for me too. I ran the following command:

 sudo chown -R $(echo $USER):staff $(echo ~)

Whenever, I would try to run the command that started with 'dart', I would get a full stop(.). And this question was exactly about that.

Title: dart analysis server terminated vs code


问:
aws network loadbalancer target type instance but not preserve my source ip
I have an openshift cluster running on AWS with network loadbalancer as my ingress, however I found even though its target type is instance, it still not preserve my client source ip, instead, it use the private ip. This is not the same as describe in this page

My question is since it is not support to associate security group with NLB, but now only the NLB private IP reach my target, how can I limit the access with security group? Tried to associate security group on my target nodes, but in vain, I could only block the NLB private IP access, can someone please shed me some lights?

My NLB target group is instance type, shouldn't it preserv my source ip?

Below is the access log from nginx, it is private ip but with my source ip in the header

答:
NLB does support Client IP preservation. For TCP target groups it is disabled by default:

you can enable or disable client IP preservation for TCP and TLS target groups using the preserve_client_ip.enabled target group attribute.


问:
Flutter on Android 7 CERTIFICATE_VERIFY_FAILED with LetsEncrypt SSL cert after Sept 30, 2021
After Sept 30, 2021, https get/post requests to a website using a Let's Encrypt SSL ceritificate on an old Android 7 device were failing with this error:

```<code>HandshakeException: Handshake error in client (OS Error: CERTIFICATE_VERIFY_FAILED: certificate has expired(handshake.cc:354))
</code>```

This error doesn't occur on newer Android nor Apple devices.

Why did this error suddently start on old Android phones?

How can I resolve this?

答:
Thank you @esty92 and @3xecutor,

Download cert from https://letsencrypt.org/certs/lets-encrypt-r3.pem

Put the root certificate value in assets/ca:

You can also create a file with this name in assets/ca and copy this certificate init.

the file name "lets-encrypt-r3.pem"

```<code>-----BEGIN CERTIFICATE-----
MIIFFjCCAv6gAwIBAgIRAJErCErPDBinU/bWLiWnX1owDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMjAwOTA0MDAwMDAw
WhcNMjUwOTE1MTYwMDAwWjAyMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNTGV0J3Mg
RW5jcnlwdDELMAkGA1UEAxMCUjMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQC7AhUozPaglNMPEuyNVZLD+ILxmaZ6QoinXSaqtSu5xUyxr45r+XXIo9cP
R5QUVTVXjJ6oojkZ9YI8QqlObvU7wy7bjcCwXPNZOOftz2nwWgsbvsCUJCWH+jdx
sxPnHKzhm+/b5DtFUkWWqcFTzjTIUu61ru2P3mBw4qVUq7ZtDpelQDRrK9O8Zutm
NHz6a4uPVymZ+DAXXbpyb/uBxa3Shlg9F8fnCbvxK/eG3MHacV3URuPMrSXBiLxg
Z3Vms/EY96Jc5lP/Ooi2R6X/ExjqmAl3P51T+c8B5fWmcBcUr2Ok/5mzk53cU6cG
/kiFHaFpriV1uxPMUgP17VGhi9sVAgMBAAGjggEIMIIBBDAOBgNVHQ8BAf8EBAMC
AYYwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMBMBIGA1UdEwEB/wQIMAYB
Af8CAQAwHQYDVR0OBBYEFBQusxe3WFbLrlAJQOYfr52LFMLGMB8GA1UdIwQYMBaA
FHm0WeZ7tuXkAXOACIjIGlj26ZtuMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcw
AoYWaHR0cDovL3gxLmkubGVuY3Iub3JnLzAnBgNVHR8EIDAeMBygGqAYhhZodHRw
Oi8veDEuYy5sZW5jci5vcmcvMCIGA1UdIAQbMBkwCAYGZ4EMAQIBMA0GCysGAQQB
gt8TAQEBMA0GCSqGSIb3DQEBCwUAA4ICAQCFyk5HPqP3hUSFvNVneLKYY611TR6W
PTNlclQtgaDqw+34IL9fzLdwALduO/ZelN7kIJ+m74uyA+eitRY8kc607TkC53wl
ikfmZW4/RvTZ8M6UK+5UzhK8jCdLuMGYL6KvzXGRSgi3yLgjewQtCPkIVz6D2QQz
CkcheAmCJ8MqyJu5zlzyZMjAvnnAT45tRAxekrsu94sQ4egdRCnbWSDtY7kh+BIm
lJNXoB1lBMEKIq4QDUOXoRgffuDghje1WrG9ML+Hbisq/yFOGwXD9RiX8F6sw6W4
avAuvDszue5L3sz85K+EC4Y/wFVDNvZo4TYXao6Z0f+lQKc0t8DQYzk1OXVu8rp2
yJMC6alLbBfODALZvYH7n7do1AZls4I9d1P4jnkDrQoxB3UqQ9hVl3LEKQ73xF1O
yK5GhDDX8oVfGKF5u+decIsH4YaTw7mP3GFxJSqv3+0lUFJoi5Lc5da149p90Ids
hCExroL1+7mryIkXPeFM5TgO9r0rvZaBFOvV2z0gp35Z0+L4WPlbuEjN/lxPFin+
HlUjr8gRsI3qfJOQFy/9rKIJR0Y/8Omwt/8oTWgy1mdeHmmjk7j1nYsvC9JSQ6Zv
MldlTTKB3zhThV1+XWYp6rjd5JW1zbVWEkLNxE7GJThEUG3szgBVGP7pSWTUTsqX
nLRbwHOoq7hHwg==
-----END CERTIFICATE-----
</code>```

then add the assets/ca path tp your pubspec.yaml like this

```<code> flutter:
  uses-material-design: true
  assets:
     .
     .
     .
    - assets/ca/
</code>```

Then simply add this in your main.dart:

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  ByteData data = await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem');
  SecurityContext.defaultContext.setTrustedCertificatesBytes(data.buffer.asUint8List());

  runApp(MyApp());
}
</code>```

This method solved my problem and It works for androids with version lower than 7.1.1.

Body:
After Sept 30, 2021, https get/post requests to a website using a Let's Encrypt SSL ceritificate on an old Android 7 device were failing with this error:

HandshakeException: Handshake error in client (OS Error: CERTIFICATE_VERIFY_FAILED: certificate has expired(handshake.cc:354))

This error doesn't occur on newer Android nor Apple devices.

Why did this error suddently start on old Android phones?

How can I resolve this?

Body:
Thank you @esty92 and @3xecutor,

Download cert from https://letsencrypt.org/certs/lets-encrypt-r3.pem

Put the root certificate value in assets/ca:

You can also create a file with this name in assets/ca and copy this certificate init.

the file name "lets-encrypt-r3.pem"

-----BEGIN CERTIFICATE-----
MIIFFjCCAv6gAwIBAgIRAJErCErPDBinU/bWLiWnX1owDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMjAwOTA0MDAwMDAw
WhcNMjUwOTE1MTYwMDAwWjAyMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNTGV0J3Mg
RW5jcnlwdDELMAkGA1UEAxMCUjMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK
AoIBAQC7AhUozPaglNMPEuyNVZLD+ILxmaZ6QoinXSaqtSu5xUyxr45r+XXIo9cP
R5QUVTVXjJ6oojkZ9YI8QqlObvU7wy7bjcCwXPNZOOftz2nwWgsbvsCUJCWH+jdx
sxPnHKzhm+/b5DtFUkWWqcFTzjTIUu61ru2P3mBw4qVUq7ZtDpelQDRrK9O8Zutm
NHz6a4uPVymZ+DAXXbpyb/uBxa3Shlg9F8fnCbvxK/eG3MHacV3URuPMrSXBiLxg
Z3Vms/EY96Jc5lP/Ooi2R6X/ExjqmAl3P51T+c8B5fWmcBcUr2Ok/5mzk53cU6cG
/kiFHaFpriV1uxPMUgP17VGhi9sVAgMBAAGjggEIMIIBBDAOBgNVHQ8BAf8EBAMC
AYYwHQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMBMBIGA1UdEwEB/wQIMAYB
Af8CAQAwHQYDVR0OBBYEFBQusxe3WFbLrlAJQOYfr52LFMLGMB8GA1UdIwQYMBaA
FHm0WeZ7tuXkAXOACIjIGlj26ZtuMDIGCCsGAQUFBwEBBCYwJDAiBggrBgEFBQcw
AoYWaHR0cDovL3gxLmkubGVuY3Iub3JnLzAnBgNVHR8EIDAeMBygGqAYhhZodHRw
Oi8veDEuYy5sZW5jci5vcmcvMCIGA1UdIAQbMBkwCAYGZ4EMAQIBMA0GCysGAQQB
gt8TAQEBMA0GCSqGSIb3DQEBCwUAA4ICAQCFyk5HPqP3hUSFvNVneLKYY611TR6W
PTNlclQtgaDqw+34IL9fzLdwALduO/ZelN7kIJ+m74uyA+eitRY8kc607TkC53wl
ikfmZW4/RvTZ8M6UK+5UzhK8jCdLuMGYL6KvzXGRSgi3yLgjewQtCPkIVz6D2QQz
CkcheAmCJ8MqyJu5zlzyZMjAvnnAT45tRAxekrsu94sQ4egdRCnbWSDtY7kh+BIm
lJNXoB1lBMEKIq4QDUOXoRgffuDghje1WrG9ML+Hbisq/yFOGwXD9RiX8F6sw6W4
avAuvDszue5L3sz85K+EC4Y/wFVDNvZo4TYXao6Z0f+lQKc0t8DQYzk1OXVu8rp2
yJMC6alLbBfODALZvYH7n7do1AZls4I9d1P4jnkDrQoxB3UqQ9hVl3LEKQ73xF1O
yK5GhDDX8oVfGKF5u+decIsH4YaTw7mP3GFxJSqv3+0lUFJoi5Lc5da149p90Ids
hCExroL1+7mryIkXPeFM5TgO9r0rvZaBFOvV2z0gp35Z0+L4WPlbuEjN/lxPFin+
HlUjr8gRsI3qfJOQFy/9rKIJR0Y/8Omwt/8oTWgy1mdeHmmjk7j1nYsvC9JSQ6Zv
MldlTTKB3zhThV1+XWYp6rjd5JW1zbVWEkLNxE7GJThEUG3szgBVGP7pSWTUTsqX
nLRbwHOoq7hHwg==
-----END CERTIFICATE-----

then add the assets/ca path tp your pubspec.yaml like this

 flutter:
  uses-material-design: true
  assets:
     .
     .
     .
    - assets/ca/

Then simply add this in your main.dart:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  ByteData data = await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem');
  SecurityContext.defaultContext.setTrustedCertificatesBytes(data.buffer.asUint8List());

  runApp(MyApp());
}

This method solved my problem and It works for androids with version lower than 7.1.1.


问:
Is there a global "onRequestComplete" event when using ASP.Net Update Panels?
I have a master page with a public ShowWaitingDialog property. When set to true, I simply show a modal "Please wait..." overlay when the form is submitted. This is done by registering a client-side function called ShowWaitingDialog() using the following:

```<code>Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "ShowWaitingDialog", "ShowWaitingDialog()");
</code>```

As a side note, I also have a function the coder can use if linking to a page that may take a while to load:

```<code>public void AttachWaitingDialog(HyperLink HyperLinkControl){
if (this.ShowWaitingDialog)
    HyperLinkControl.Attributes.Add("onclick", "ShowWaitingDialog();");}
</code>```

These work just fine until an UpdatePanel is introduced onto the page. The dialog is correctly shown when a postback happens inside an update panel. However, it never goes away when the request is complete. I was hoping there was some sort of global complete event that the Microsoft ajax framework uses when making update panels requests. That way I could close my modal overflow when executed. Is there?

I haven't tried it yet, but I guess I could use the ScriptManager to always register a startup script which hides the modal overlay, but I was wondering if there was another way.

答:
You can use Javascript and use the PageRequestManager clientside api provided by Microsoft Ajax framework.

```<code><script type='text/javascript'>

var pageMgr = Sys.WebForms.PageRequestManager.getInstance();

pageMgr.add_beginRequest(BeforeAjaxRequest);
pageMgr.add_endRequest(AfterAjaxRequest);

function BeforeAjaxRequest(sender, args)
{
 alert('MyReqeustStart');
}

function AfterAjaxRequest(sender, args)
{
 alert('MyReqeustEnd');
}

</script>
</code>```

More Details here:
http://msdn.microsoft.com/en-us/library/bb311028.aspx

Body:
I have a master page with a public ShowWaitingDialog property. When set to true, I simply show a modal "Please wait..." overlay when the form is submitted. This is done by registering a client-side function called ShowWaitingDialog() using the following:

Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "ShowWaitingDialog", "ShowWaitingDialog()");

As a side note, I also have a function the coder can use if linking to a page that may take a while to load:

public void AttachWaitingDialog(HyperLink HyperLinkControl){
if (this.ShowWaitingDialog)
    HyperLinkControl.Attributes.Add("onclick", "ShowWaitingDialog();");}

These work just fine until an UpdatePanel is introduced onto the page. The dialog is correctly shown when a postback happens inside an update panel. However, it never goes away when the request is complete. I was hoping there was some sort of global complete event that the Microsoft ajax framework uses when making update panels requests. That way I could close my modal overflow when executed. Is there?

I haven't tried it yet, but I guess I could use the ScriptManager to always register a startup script which hides the modal overlay, but I was wondering if there was another way.

Body:
You can use Javascript and use the PageRequestManager clientside api provided by Microsoft Ajax framework.

<script type='text/javascript'>

var pageMgr = Sys.WebForms.PageRequestManager.getInstance();

pageMgr.add_beginRequest(BeforeAjaxRequest);
pageMgr.add_endRequest(AfterAjaxRequest);

function BeforeAjaxRequest(sender, args)
{
 alert('MyReqeustStart');
}

function AfterAjaxRequest(sender, args)
{
 alert('MyReqeustEnd');
}

</script>

More Details here:
http://msdn.microsoft.com/en-us/library/bb311028.aspx


问:
How to rename uploaded images with spaces and special characters?
So here i will share mu clean string function and my upload image code. i need help in using the function to clean the file name before being uploaded if the image file has names for example "credi--  @% sdfdsf..####tcard.jpg" i wish to clean it before upload for which i have a clean string function

```<code>function cleanStr($string) {
   $string = str_replace(' ', '-', $string);
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
   return preg_replace('/-+/', '-', $string);
}
</code>```

and here is my upload image code

```<code>if(isset($_POST['upload'])) {
    $countfiles = count($_FILES['files']['name']);
    $query = "INSERT INTO images (post_id,name,image) VALUES(?,?,?)";
    $statement = $db->prepare($query);
    for($i = 0; $i < $countfiles; $i++) {
        $filename = date('Y-m-d-his').'-'.$_FILES['files']['name'][$i];
        $target_file = 'uploads/documents/'.$filename;
        $file_extension = pathinfo(
            $target_file, PATHINFO_EXTENSION);
        $file_extension = strtolower($file_extension);
        $valid_extension = array("png","jpeg","jpg");
        if(in_array($file_extension, $valid_extension)) {
            if(move_uploaded_file($_FILES['files']['tmp_name'][$i],$target_file)){
                $statement->execute(array($_GET['id'],$filename,$target_file));
            }
        }
    }
header('Location: result.php?id='.$_GET['id'].'&action=UPLOADED');
exit;
}
</code>```

can someone help me out cleaning the image name before being uploaded?

thanks alot

答:
You cannot modify the filename before being uploaded when using PHP because of the fact that PHP runs on the server. Javascript cannot rename a file on the client-side either though it could send a different name with the file being uploaded! What you want to do by the looks of this code is modify the filename after upload but before being saved & logged to database.

In your original code I think you could just change

```<code>$target_file = 'uploads/documents/'.$filename;
</code>```

to

```<code>$target_file = 'uploads/documents/'.cleanStr( $filename );
</code>```

however you might try something like this:

```<code>if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
    $_GET['id'],
    $_FILES['files']['name']
)) {

    function cleanStr($string) {
       $string = str_replace(' ', '-', $string);
       $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
       return preg_replace('/-+/', '-', $string);
    }
    $count=0;

    # Prepare the sql statement.
    $sql = "INSERT INTO `images` ( `post_id`, `name`, `image` ) VALUES ( ?, ?, ? )";
    $stmt = $db->prepare( $sql );

    # Establish the paths needed - one is the full, absolute path
    # for saving and the other a relative path for display
    $basedir = __DIR__ . '/uploads/documents/'
    $displaydir = './uploads/documents/';

    # Permit these file extensions
    $extns = array( 'png', 'jpeg', 'jpg' );

    # iterate through all posted images
    foreach( $_FILES['files']['name'] as $i => $name ) {

        if( !empty( $_FILES['files']['tmp_name'][$i] ) ) {
            # we need the `tmp_name` but will modify the $name later
            $name = $_FILES['files']['name'][$i];
            $tmp  = $_FILES['files']['tmp_name'][$i];
            $error= $_FILES['files']['error'][$i];

            # find the file extension and file name ( without extension )
            $ext  = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
            $name = pathinfo( $name, PATHINFO_FILENAME );

            # rudimentary test to see if the file is an image
            list( $width, $height, $type, $attr ) = getimagesize( $tmp );

            # Proceed if basic tests are passed.
            if( $error==UPLOAD_ERR_OK && isset( $width, $height, $attr ) && in_array( $ext, $extns )){

                # construct the save & display paths using new file name.
                $filename = sprintf('%s-%s.%s', date('Y-m-d-his'), cleanStr( $name ), $ext );
                $savepath=$basedir . $filename;
                $displaypath=$displaydir . $filename;

                # move the file and execute sql cmd.
                if( move_uploaded_file( $tmp, $savepath ) ){
                    $stmt->execute(array(
                        $_GET['id'],
                        $filename,
                        $displaypath
                    ));

                    $count++;
                }
            }
        }
    }
    exit( header('Location: result.php?id='.$_GET['id'].'&action=UPLOADED&total='.  $count) );
}
</code>```

Body:
So here i will share mu clean string function and my upload image code. i need help in using the function to clean the file name before being uploaded if the image file has names for example "credi--  @% sdfdsf..####tcard.jpg" i wish to clean it before upload for which i have a clean string function

function cleanStr($string) {
   $string = str_replace(' ', '-', $string);
   $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
   return preg_replace('/-+/', '-', $string);
}

and here is my upload image code

if(isset($_POST['upload'])) {
    $countfiles = count($_FILES['files']['name']);
    $query = "INSERT INTO images (post_id,name,image) VALUES(?,?,?)";
    $statement = $db->prepare($query);
    for($i = 0; $i < $countfiles; $i++) {
        $filename = date('Y-m-d-his').'-'.$_FILES['files']['name'][$i];
        $target_file = 'uploads/documents/'.$filename;
        $file_extension = pathinfo(
            $target_file, PATHINFO_EXTENSION);
        $file_extension = strtolower($file_extension);
        $valid_extension = array("png","jpeg","jpg");
        if(in_array($file_extension, $valid_extension)) {
            if(move_uploaded_file($_FILES['files']['tmp_name'][$i],$target_file)){
                $statement->execute(array($_GET['id'],$filename,$target_file));
            }
        }
    }
header('Location: result.php?id='.$_GET['id'].'&action=UPLOADED');
exit;
}

can someone help me out cleaning the image name before being uploaded?

thanks alot

Body:
You cannot modify the filename before being uploaded when using PHP because of the fact that PHP runs on the server. Javascript cannot rename a file on the client-side either though it could send a different name with the file being uploaded! What you want to do by the looks of this code is modify the filename after upload but before being saved & logged to database.

In your original code I think you could just change

$target_file = 'uploads/documents/'.$filename;

to

$target_file = 'uploads/documents/'.cleanStr( $filename );

however you might try something like this:

if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
    $_GET['id'],
    $_FILES['files']['name']
)) {

    function cleanStr($string) {
       $string = str_replace(' ', '-', $string);
       $string = preg_replace('/[^A-Za-z0-9\-]/', '', $string);
       return preg_replace('/-+/', '-', $string);
    }
    $count=0;

    # Prepare the sql statement.
    $sql = "INSERT INTO `images` ( `post_id`, `name`, `image` ) VALUES ( ?, ?, ? )";
    $stmt = $db->prepare( $sql );

    # Establish the paths needed - one is the full, absolute path
    # for saving and the other a relative path for display
    $basedir = __DIR__ . '/uploads/documents/'
    $displaydir = './uploads/documents/';

    # Permit these file extensions
    $extns = array( 'png', 'jpeg', 'jpg' );

    # iterate through all posted images
    foreach( $_FILES['files']['name'] as $i => $name ) {

        if( !empty( $_FILES['files']['tmp_name'][$i] ) ) {
            # we need the `tmp_name` but will modify the $name later
            $name = $_FILES['files']['name'][$i];
            $tmp  = $_FILES['files']['tmp_name'][$i];
            $error= $_FILES['files']['error'][$i];

            # find the file extension and file name ( without extension )
            $ext  = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
            $name = pathinfo( $name, PATHINFO_FILENAME );

            # rudimentary test to see if the file is an image
            list( $width, $height, $type, $attr ) = getimagesize( $tmp );

            # Proceed if basic tests are passed.
            if( $error==UPLOAD_ERR_OK && isset( $width, $height, $attr ) && in_array( $ext, $extns )){

                # construct the save & display paths using new file name.
                $filename = sprintf('%s-%s.%s', date('Y-m-d-his'), cleanStr( $name ), $ext );
                $savepath=$basedir . $filename;
                $displaypath=$displaydir . $filename;

                # move the file and execute sql cmd.
                if( move_uploaded_file( $tmp, $savepath ) ){
                    $stmt->execute(array(
                        $_GET['id'],
                        $filename,
                        $displaypath
                    ));

                    $count++;
                }
            }
        }
    }
    exit( header('Location: result.php?id='.$_GET['id'].'&action=UPLOADED&total='.  $count) );
}


问:
Dynamically set mat-select-options when using ngx-mat-select-search in formArray in angular 8
I have a formArray which contains two mat-selects. One of them uses ngx-mat-select-search to search from the values in the options of the mat-select. My problem is that when the form array contains multiple elements, and I search in one of the mat-select from these elements, the value from all the mat-selects disappears while I'm searching and it reappears after a value has been selected.
Here is the portion of my template file:

```<code><ng-container formArrayName='cpUserAccounts'
                        *ngFor='let account of cpUserAccounts.controls; let i=index'>
                        <div class="d-flex align-items-center flex-wrap col-md-12" [formGroupName]='i'>
                            <div class="col-sm-6">
                                <mat-form-field class="task-array">
                                    <mat-label>Client</mat-label>
                                    <mat-select formControlName="clientId" required>
                                        <mat-option>
                                            <ngx-mat-select-search [formControl]="bankFilterCtrl"
                                                placeholderLabel='Search' noEntriesFoundLabel="'No match found'">
                                            </ngx-mat-select-search>
                                        </mat-option>
                                        <mat-option *ngFor="let client of filteredOptions | async" [value]="client.id">
                                            {{client.companyName}}
                                        </mat-option>
                                    </mat-select>
                                    <mat-hint class="error"
                                        *ngIf="findDuplicate(account.controls.clientId.value, 'cpUserAccounts')">
                                        {{constants.errorMessage.duplicateClientLabel}}
                                    </mat-hint>
                                </mat-form-field>
                            </div>
                            <div class="col-sm-4">
                                <mat-form-field class="task-array">
                                    <mat-label>Role</mat-label>
                                    <mat-select formControlName="roleId" required>
                                        <mat-option *ngFor="let role of accountRoles" [value]="role.id">
                                            {{role.name}}
                                        </mat-option>
                                    </mat-select>
                                </mat-form-field>
                            </div>
                            <div class="col-sm-2 d-flex justify-content-end">
                                <mat-icon class="remove-task-button" title="Remove" (click)='removeAccount(i)'
                                    matSuffix>
                                    remove
                                </mat-icon>
                            </div>
                        </div>
                    </ng-container>
</code>```

and the .ts file contains the following code:

```<code>filteredOptions: ReplaySubject<ClientModel[]> = new ReplaySubject<ClientModel[]>(1);
public bankFilterCtrl: FormControl = new FormControl();
protected onDestroy = new Subject<void>();

ngOnInit() {
      this.bankFilterCtrl.valueChanges
      .pipe(takeUntil(this.onDestroy))
      .subscribe(() => {
      this.filterBanks();
            });
    }

getClients() {
        const subscription = this.clientContactService.getClients().subscribe(clients => {
            this.clients = clients.data;
            this.filterBanks();
        });
        this.subscription.push(subscription);
    }

protected filterBanks() {
        if (!this.clients) {
            return;
        }
        // get the search keyword
        let search = this.bankFilterCtrl.value;
        if (!search) {
            this.filteredOptions.next(this.clients.slice());
            return;
        } else {
            search = search.toLowerCase();
        }
        // filter the clients
        this.filteredOptions.next(
            this.clients.filter(client => client.companyName.toLowerCase().indexOf(search) > -1)
        );
   }
</code>```

Here are the images of the flow of what is happening:
In the starting, it is like this:

Then:

The problem is here:

答:
I was stuck in this too and couldn't find any solution anywhere then came up with this on my own. The simplest way to do this is by using a backup FormControl with array as value. and accessing its value in the template array where you want to use the array. Try to undertand this simple code example -

export class FormExampleComponent {
  public formGroup: FormGroup;
  public itemCodesArray: ItemCode[] = [
    { id: 1, name: apple },
    { id: 2, name: banna },
    { id: 3, name: pineapple },
  ];

  constructor(fb: FormBuilder) {}

  public ngOnInit(): void {
    this.createForm();
  }

  private createForm() {
    this.formGroup = this.fb.group({
      formItems: this.fb.array([this.initFormGroup()]),
    });
  }

  private initFormGroup(): FormGroup {
    return this.fb.group({
      description: [null, []],
      formItemsGroup: this.initFormItemsGroup(),
    });
  }

  private initFormItemsGroup(): FormGroup {
    const fg = this.fb.group({
      // id is just to recognize the form array elemnts by trackByfunction
      id: [new Date().getTime() + Math.floor(Math.random() * 100)],
      itemCodeSearch: [null, []],
      // temp array
      filteredItemCodes: [this.itemCodesArray, []],
      itemCodeId: [null, [Validators.required]],
      itemDescription: [null, [Validators.required]],
    });

    fg.get('itemCodeSearch')
      .valueChanges
      .subscribe((searchText) => {
        this.itemCodes$.subscribe((itemCode) => {
          if (searchText) {
            fg.get('filteredItemCodes').setValue(
              itemCode.filter((item) => item.name.toLowerCase().includes(searchText.toLowerCase())),
            );
          } else {
            fg.get('filteredItemCodes').setValue(itemCode);
          }
        });
      });

    return fg;
  }

  public get formItems(): AbstractControl[] {
    return (this.formGroup.get('formItems') as FormArray).controls;
  }

  public trackByFunction(index: number, item: any): number {
    return item.value.formItemsGroup.id;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form [formGroup]="formGroup">
  <div formArrayName="formItems">
    <div *ngFor="let formItem of formItems; let i = index; trackBy: trackByFunction">
      <div [formGroupName]="i">
        <div>
          <div formGroupName="poItemsGroup">

            <mat-form-field appearance="outline">
              <mat-label>Description</mat-label>
              <input type="text" matInput formControlName="description" required />
            </mat-form-field>

            <mat-form-field appearance="outline">
              <mat-label>Item Code</mat-label>
              <mat-select formControlName="itemCodeId" required>
                <mat-option>
                  <ngx-mat-select-search
                    formControlName="itemCodeSearch"
                    placeholderLabel="Search item"
                    noEntriesFoundLabel="No item found"
                  ></ngx-mat-select-search>
                </mat-option>
                <mat-option
                  *ngFor="
                    let item of formItem.get('formItemsGroup').get('filteredItemCodes').value;
                    trackBy: 'id' | trackByKey
                  "
                  [value]="item.id"
                >
                  {{ item.name }}
                </mat-option>
              </mat-select>
            </mat-form-field>

            <mat-form-field appearance="outline">
              <mat-label>Item Description</mat-label>
              <input type="text" matInput formControlName="itemDescription" required />
            </mat-form-field>

          </div>
        </div>
      </div>
    </div>
  </div>
</form></code>```

Since valueChanges fire too often you can use debounceTime to stop it from firing on every single character user enters.

You can also use OnDestroy lifecycle hook along with takeUntil function to unsubscribe every subscription to make it more effecient.

Body:
I have a formArray which contains two mat-selects. One of them uses ngx-mat-select-search to search from the values in the options of the mat-select. My problem is that when the form array contains multiple elements, and I search in one of the mat-select from these elements, the value from all the mat-selects disappears while I'm searching and it reappears after a value has been selected.
Here is the portion of my template file:

<ng-container formArrayName='cpUserAccounts'
                        *ngFor='let account of cpUserAccounts.controls; let i=index'>

                                <mat-form-field class="task-array">
                                    <mat-label>Client</mat-label>
                                    <mat-select formControlName="clientId" required>
                                        <mat-option>
                                            <ngx-mat-select-search [formControl]="bankFilterCtrl"
                                                placeholderLabel='Search' noEntriesFoundLabel="'No match found'">
                                            </ngx-mat-select-search>
                                        </mat-option>
                                        <mat-option *ngFor="let client of filteredOptions | async" [value]="client.id">
                                            {{client.companyName}}
                                        </mat-option>
                                    </mat-select>
                                    <mat-hint class="error"
                                        *ngIf="findDuplicate(account.controls.clientId.value, 'cpUserAccounts')">
                                        {{constants.errorMessage.duplicateClientLabel}}
                                    </mat-hint>
                                </mat-form-field>

                                <mat-form-field class="task-array">
                                    <mat-label>Role</mat-label>
                                    <mat-select formControlName="roleId" required>
                                        <mat-option *ngFor="let role of accountRoles" [value]="role.id">
                                            {{role.name}}
                                        </mat-option>
                                    </mat-select>
                                </mat-form-field>

                                <mat-icon class="remove-task-button" title="Remove" (click)='removeAccount(i)'
                                    matSuffix>
                                    remove
                                </mat-icon>

                    </ng-container>

and the .ts file contains the following code:

filteredOptions: ReplaySubject<ClientModel[]> = new ReplaySubject<ClientModel[]>(1);
public bankFilterCtrl: FormControl = new FormControl();
protected onDestroy = new Subject<void>();

ngOnInit() {
      this.bankFilterCtrl.valueChanges
      .pipe(takeUntil(this.onDestroy))
      .subscribe(() => {
      this.filterBanks();
            });
    }

getClients() {
        const subscription = this.clientContactService.getClients().subscribe(clients => {
            this.clients = clients.data;
            this.filterBanks();
        });
        this.subscription.push(subscription);
    }

protected filterBanks() {
        if (!this.clients) {
            return;
        }
        // get the search keyword
        let search = this.bankFilterCtrl.value;
        if (!search) {
            this.filteredOptions.next(this.clients.slice());
            return;
        } else {
            search = search.toLowerCase();
        }
        // filter the clients
        this.filteredOptions.next(
            this.clients.filter(client => client.companyName.toLowerCase().indexOf(search) > -1)
        );
   }

Here are the images of the flow of what is happening:
In the starting, it is like this:

Then:

The problem is here:

Body:
I was stuck in this too and couldn't find any solution anywhere then came up with this on my own. The simplest way to do this is by using a backup FormControl with array as value. and accessing its value in the template array where you want to use the array. Try to undertand this simple code example -

export class FormExampleComponent {
  public formGroup: FormGroup;
  public itemCodesArray: ItemCode[] = [
    { id: 1, name: apple },
    { id: 2, name: banna },
    { id: 3, name: pineapple },
  ];

  constructor(fb: FormBuilder) {}

  public ngOnInit(): void {
    this.createForm();
  }

  private createForm() {
    this.formGroup = this.fb.group({
      formItems: this.fb.array([this.initFormGroup()]),
    });
  }

  private initFormGroup(): FormGroup {
    return this.fb.group({
      description: [null, []],
      formItemsGroup: this.initFormItemsGroup(),
    });
  }

  private initFormItemsGroup(): FormGroup {
    const fg = this.fb.group({
      // id is just to recognize the form array elemnts by trackByfunction
      id: [new Date().getTime() + Math.floor(Math.random() * 100)],
      itemCodeSearch: [null, []],
      // temp array
      filteredItemCodes: [this.itemCodesArray, []],
      itemCodeId: [null, [Validators.required]],
      itemDescription: [null, [Validators.required]],
    });

    fg.get('itemCodeSearch')
      .valueChanges
      .subscribe((searchText) => {
        this.itemCodes$.subscribe((itemCode) => {
          if (searchText) {
            fg.get('filteredItemCodes').setValue(
              itemCode.filter((item) => item.name.toLowerCase().includes(searchText.toLowerCase())),
            );
          } else {
            fg.get('filteredItemCodes').setValue(itemCode);
          }
        });
      });

    return fg;
  }

  public get formItems(): AbstractControl[] {
    return (this.formGroup.get('formItems') as FormArray).controls;
  }

  public trackByFunction(index: number, item: any): number {
    return item.value.formItemsGroup.id;
  }
}

<form [formGroup]="formGroup">
  <div formArrayName="formItems">
    <div *ngFor="let formItem of formItems; let i = index; trackBy: trackByFunction">
      <div [formGroupName]="i">
        <div>
          <div formGroupName="poItemsGroup">

            <mat-form-field appearance="outline">
              <mat-label>Description</mat-label>
              <input type="text" matInput formControlName="description" required />
            </mat-form-field>

            <mat-form-field appearance="outline">
              <mat-label>Item Code</mat-label>
              <mat-select formControlName="itemCodeId" required>
                <mat-option>
                  <ngx-mat-select-search
                    formControlName="itemCodeSearch"
                    placeholderLabel="Search item"
                    noEntriesFoundLabel="No item found"
                  ></ngx-mat-select-search>
                </mat-option>
                <mat-option
                  *ngFor="
                    let item of formItem.get('formItemsGroup').get('filteredItemCodes').value;
                    trackBy: 'id' | trackByKey
                  "
                  [value]="item.id"
                >
                  {{ item.name }}
                </mat-option>
              </mat-select>
            </mat-form-field>

            <mat-form-field appearance="outline">
              <mat-label>Item Description</mat-label>
              <input type="text" matInput formControlName="itemDescription" required />
            </mat-form-field>

          </div>
        </div>
      </div>
    </div>
  </div>
</form>

Since valueChanges fire too often you can use debounceTime to stop it from firing on every single character user enters.

You can also use OnDestroy lifecycle hook along with takeUntil function to unsubscribe every subscription to make it more effecient.


问:
OAuth Cognito ID token unauthorized
I have a cognito user pool/app client setup with OAuth flow and standard scopes (email, admin, etc.) and several 3rd party providers (google, azure, etc.). I would like to get the identity data in the request context which mean I would need to use the id token but using the id token gets me an unauthorized response from api gateway while the access token works as expected. I remember reading somewhere that custom scopes doesn't allow for id token auth but I don't have custom scopes setup. Any insight into what's going on here?</p>

答:
From Integrate a REST API with an Amazon Cognito user pool:

With the COGNITO_USER_POOLS authorizer, if the OAuth Scopes option
isn't specified, API Gateway treats the supplied token as an identity
token and verifies the claimed identity against the one from the user
pool. Otherwise, API Gateway treats the supplied token as an access
token and verifies the access scopes that are claimed in the token
against the authorization scopes declared on the method.

OAuth Scopes are only present in access tokens. Based on the fact that access tokens work, you have specified one or more OAuth scopes for your endpoint.

If you have a valid access token, you can use its value to get information about the authenticated user using the USERINFO endpoint.

Title: OAuth Cognito ID token unauthorized


问:
Algorithm to get items from nested array structure structured around powers of 2
I have some constraints on how an array would be implemented under the hood. There can only be power-of-two contiguous elements up to 32 elements (1, 2, 4, 8, 16, 32). Therefore, this puts some constraints on how to optimally store the array elements of like 7 or 15 elements, etc.. The full list of examples from 1 to 32 is here, but some examples are next:

```<code>base-3
  a
  b
  c
  null

base-5
  a
  b
  c
  tree
    d
    e

base-6
  a
  b
  c
  d
  e
  f
  null
  null

...

base-10
  a
  b
  c
  d
  e
  f
  g
  tree
    h
    i
    j
    null

...

base-13
  tree
    a
    b
    c
    d
  tree
    e
    f
    g
    h
  tree
    i
    j
    k
    l
  tree
    m

...

base-16
  a
  b
  c
  d
  e
  f
  g
  h
  i
  j
  k
  l
  m
  n
  o
  p

base-17
  a
  b
  c
  d
  e
  f
  g
  h
  i
  j
  k
  l
  m
  n
  o
  tree
    p
    q
</code>```

Null is chosen in a few cases because it would take up less space to just have a null value than to make it into an appropriate tree (or using null would mean less traversal steps).

At 32, it should nest the pattern, like this:

```<code>base-33
  tree
    a
    b
    c
    d
    e
    f
    g
    h
    i
    j
    k
    l
    m
    n
    o
    p
    q
    r
    s
    t
    u
    v
    w
    x
    y
    z
    aa
    ab
    ac
    ad
    ae
    af
  tree
    ag
</code>```

The tree key just shows it is an address linking out to another array.

I started to implement an algorithm to fetch all the values from this tree system below. I didn't find a way of generically making it so I didn't have to write each of 32 functions. If you know of an abstract/generic way to write this, that would be cool to know (doesn't need to exactly match how I divided up the arrays, but it should be close to the same idea). But that is not the main question. The main question is simply how you would make this function repeat for arrays larger than 32. How do you make this algorithm (a loop/iterative algorithm, not using recursion) so that it can fetch up to billions of items from such a tree, and know how to traverse the custom array structure?

```<code>const map = [
  get1,
  get2,
  get3,
  get4,
  get5,
  get6,
  get7,
  get8,
  get9,
  get10,
  get11,
  get12,
  get13,
  get14,
  get15,
  get16,
  get17,
  get18,
  get19,
  get20,
  get21,
  get22,
  get23,
  get24,
  get25,
  get26,
  get27,
  get28,
  get29,
  get30,
  get31,
  get32,
]

// how to make getItems handle arrays larger than 32 in length?
function getItems(array) {
  return map[array.length](array)
}

function get1(array) {
  return [
    array[0]
  ]
}

function get2(array) {
  return [
    array[0],
    array[1],
  ]
}

function get3(array) {
  return [
    array[0],
    array[1],
    array[2],
  ]
}

function get4(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
  ]
}

function get5(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3][0],
    array[3][1],
  ]
}

function get6(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
  ]
}

function get7(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
    array[6],
  ]
}

function get8(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
    array[6],
    array[7],
  ]
}

function get9(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
    array[6],
    array[7][0],
    array[7][1],
  ]
}

function get10(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
    array[6],
    array[7][0],
    array[7][1],
    array[7][2],
  ]
}

function get11(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
    array[6],
    array[7][0],
    array[7][1],
    array[7][2],
    array[7][3],
  ]
}

function get12(array) {
  return [
    array[0][0],
    array[1][1],
    array[2][2],
    array[3][3],
    array[4][4],
    array[5][5],
    array[6][6],
    array[6][7],
    array[7][0],
    array[7][1],
    array[7][2],
    array[7][3],
  ]
}
</code>```

I am lost right at the beginning. It could be implemented with recursion, and perhaps from that I can figure it out as an imperative form.

```<code>function getItemsRecursive(tree) {
  if (tree.size <= 32) {
    return map[tree.size](tree)
  }

  // ... I am lost right at the beginning.

  if (tree.size === 33) {
    return [
      ...getItemsRecursive(tree[0]),
      tree[1][0]
    ]
  } else if (tree.size === 34) {
    // ....?
  }
}
</code>```

The tree.size is just pseudocode. You can just do pseudocode if you'd like, but I am doing this in JavaScript.

答:
In JavaScript you would of course call .flat(Infinity), which would return the completely flattened array. But I'll assume these constraints:

No use of array methods besides push and pop (as you target a custom, simpler language)

No use of recursion

No use of a generator or iterator

I hope the use of a stack is acceptable. I would then think of a stack where each stacked element consists of an array reference and an index in that array. But to avoid "complex" stack elements, we can also use two stacks: one for array references, another for the indices in those arrays.

To implement "iteration", I will use a callback system, so that you can specify what should happen in each iteration. The callback can be console.log, so that the iterated value is just output.

Here is an implementation:

function iterate(arr, callback) {
    let arrayStack = [];
    let indexStack = [];
    let i = 0;
    while (true) {
        if (i >= arr.length || arr[i] === null) {
            if (arrayStack.length == 0) return; // all done
            arr = arrayStack.pop();
            i = indexStack.pop();
        } else if (Array.isArray(arr[i])) {
            arrayStack.push(arr);
            indexStack.push(i + 1);
            arr = arr[i];
            i = 0;
        } else {
            callback(arr[i]);
            i++;
        }
    }
}

let arr = [1, 2, 3, [4, 5]];

iterate(arr, console.log);```

Body:
I have some constraints on how an array would be implemented under the hood. There can only be power-of-two contiguous elements up to 32 elements (1, 2, 4, 8, 16, 32). Therefore, this puts some constraints on how to optimally store the array elements of like 7 or 15 elements, etc.. The full list of examples from 1 to 32 is here, but some examples are next:

base-3
  a
  b
  c
  null

base-5
  a
  b
  c
  tree
    d
    e

base-6
  a
  b
  c
  d
  e
  f
  null
  null

...

base-10
  a
  b
  c
  d
  e
  f
  g
  tree
    h
    i
    j
    null

...

base-13
  tree
    a
    b
    c
    d
  tree
    e
    f
    g
    h
  tree
    i
    j
    k
    l
  tree
    m

...

base-16
  a
  b
  c
  d
  e
  f
  g
  h
  i
  j
  k
  l
  m
  n
  o
  p

base-17
  a
  b
  c
  d
  e
  f
  g
  h
  i
  j
  k
  l
  m
  n
  o
  tree
    p
    q

Null is chosen in a few cases because it would take up less space to just have a null value than to make it into an appropriate tree (or using null would mean less traversal steps).

At 32, it should nest the pattern, like this:

base-33
  tree
    a
    b
    c
    d
    e
    f
    g
    h
    i
    j
    k
    l
    m
    n
    o
    p
    q
    r
    s
    t
    u
    v
    w
    x
    y
    z
    aa
    ab
    ac
    ad
    ae
    af
  tree
    ag

The tree key just shows it is an address linking out to another array.

I started to implement an algorithm to fetch all the values from this tree system below. I didn't find a way of generically making it so I didn't have to write each of 32 functions. If you know of an abstract/generic way to write this, that would be cool to know (doesn't need to exactly match how I divided up the arrays, but it should be close to the same idea). But that is not the main question. The main question is simply how you would make this function repeat for arrays larger than 32. How do you make this algorithm (a loop/iterative algorithm, not using recursion) so that it can fetch up to billions of items from such a tree, and know how to traverse the custom array structure?

const map = [
  get1,
  get2,
  get3,
  get4,
  get5,
  get6,
  get7,
  get8,
  get9,
  get10,
  get11,
  get12,
  get13,
  get14,
  get15,
  get16,
  get17,
  get18,
  get19,
  get20,
  get21,
  get22,
  get23,
  get24,
  get25,
  get26,
  get27,
  get28,
  get29,
  get30,
  get31,
  get32,
]

// how to make getItems handle arrays larger than 32 in length?
function getItems(array) {
  return map[array.length](array)
}

function get1(array) {
  return [
    array[0]
  ]
}

function get2(array) {
  return [
    array[0],
    array[1],
  ]
}

function get3(array) {
  return [
    array[0],
    array[1],
    array[2],
  ]
}

function get4(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
  ]
}

function get5(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3][0],
    array[3][1],
  ]
}

function get6(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
  ]
}

function get7(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
    array[6],
  ]
}

function get8(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
    array[6],
    array[7],
  ]
}

function get9(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
    array[6],
    array[7][0],
    array[7][1],
  ]
}

function get10(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
    array[6],
    array[7][0],
    array[7][1],
    array[7][2],
  ]
}

function get11(array) {
  return [
    array[0],
    array[1],
    array[2],
    array[3],
    array[4],
    array[5],
    array[6],
    array[7][0],
    array[7][1],
    array[7][2],
    array[7][3],
  ]
}

function get12(array) {
  return [
    array[0][0],
    array[1][1],
    array[2][2],
    array[3][3],
    array[4][4],
    array[5][5],
    array[6][6],
    array[6][7],
    array[7][0],
    array[7][1],
    array[7][2],
    array[7][3],
  ]
}

I am lost right at the beginning. It could be implemented with recursion, and perhaps from that I can figure it out as an imperative form.

function getItemsRecursive(tree) {
  if (tree.size <= 32) {
    return map[tree.size](tree)
  }

  // ... I am lost right at the beginning.

  if (tree.size === 33) {
    return [
      ...getItemsRecursive(tree[0]),
      tree[1][0]
    ]
  } else if (tree.size === 34) {
    // ....?
  }
}

The tree.size is just pseudocode. You can just do pseudocode if you'd like, but I am doing this in JavaScript.


问:
jquery button only works for first button?
I have a table of records. each table row has a submit button - when the submit button is clicked it makes a ajax request to the server. The first button works and request is sent to server. The next buttons do not work and the page refreshes each time when it should not. Any reason why this is happening ? I believe it is because i have an id on the button which references all records, but i am not sure.

Here is snippet of code:

```<code>$("#submitBtn").on('click', function(event) {

event.preventDefault();

var registerNo = $('#registerNo').val();
var date = $('#date').val();
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
var refNo = $('#refNo').val();
var attendance = $("#AttendanceValue option:selected").val();

var obj = {
    attendance : attendance,
    refNo : refNo,
    registerNo : registerNo,
    date : date,
    startTime : startTime,
    endTime : endTime
}

/*

$.ajax({
    url: "process.asp",
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(obj),
    success: function (response) {
        alert(JSON.stringify(response));
    },
    error: function(response) {
        alert('There was an error: ' + response.responseText);
    }
});

*/
console.log(obj);
});
</code>```

答:
$("button[name=submitBtn]").on('click', function(event) {
    var registerNo = $(this).closest("tr").find('input[name=registerNo]').val();
    var date = $(this).closest("tr").find('input[name=date]').val();
    var startTime = $(this).closest("tr").find('input[name=startTime]').val();
    var endTime = $(this).closest("tr").find('input[name=endTime]').val();
    var refNo = $(this).closest("tr").find('input[name=refNo]').val();
    var attendance = $(this).closest("tr").find("select[name=AttendanceValue]").val();

    var obj = {
        attendance : attendance,
        refNo : refNo,
        registerNo : registerNo,
        date : date,
        startTime : startTime,
        endTime : endTime
    }

    /*Your AJAX code place here*/
    console.log(obj);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}</code>```

        Reg No
        Date
        Start time
        End time
        Ref no
        Attendence

        <input type="text" name="registerNo">
        <input type="date" name="date">
        <input type="time" name="startTime">
        <input type="time" name="endTime">
        <input type="text" name="refNo">

            <select name="AttendanceValue">
                <option value="">select</option>
                <option value="Present">Present</option>
                <option value="Absent">Absent</option>
            </select>

        <button type="button" name="submitBtn">submit</button>

        <input type="text" name="registerNo">
        <input type="date" name="date">
        <input type="time" name="startTime">
        <input type="time" name="endTime">
        <input type="text" name="refNo">

            <select name="AttendanceValue">
                <option value="">select</option>
                <option value="Present">Present</option>
                <option value="Absent">Absent</option>
            </select>

        <button type="button" name="submitBtn">submit</button>

        <input type="text" name="registerNo">
        <input type="date" name="date">
        <input type="time" name="startTime">
        <input type="time" name="endTime">
        <input type="text" name="refNo">

            <select name="AttendanceValue">
                <option value="">select</option>
                <option value="Present">Present</option>
                <option value="Absent">Absent</option>
            </select>

        <button type="button" name="submitBtn">submit</button>

```

Don't use ID anywhere, because ID is unique for each element, so use either name or class. If don't want to reload page while click button means, don't forgot to give type="button" in the button element.

Body:
I have a table of records. each table row has a submit button - when the submit button is clicked it makes a ajax request to the server. The first button works and request is sent to server. The next buttons do not work and the page refreshes each time when it should not. Any reason why this is happening ? I believe it is because i have an id on the button which references all records, but i am not sure.

Here is snippet of code:

$("#submitBtn").on('click', function(event) {

event.preventDefault();

var registerNo = $('#registerNo').val();
var date = $('#date').val();
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
var refNo = $('#refNo').val();
var attendance = $("#AttendanceValue option:selected").val();

var obj = {
    attendance : attendance,
    refNo : refNo,
    registerNo : registerNo,
    date : date,
    startTime : startTime,
    endTime : endTime
}

/*

$.ajax({
    url: "process.asp",
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(obj),
    success: function (response) {
        alert(JSON.stringify(response));
    },
    error: function(response) {
        alert('There was an error: ' + response.responseText);
    }
});

*/
console.log(obj);
});

Body:
$("button[name=submitBtn]").on('click', function(event) {
    var registerNo = $(this).closest("tr").find('input[name=registerNo]').val();
    var date = $(this).closest("tr").find('input[name=date]').val();
    var startTime = $(this).closest("tr").find('input[name=startTime]').val();
    var endTime = $(this).closest("tr").find('input[name=endTime]').val();
    var refNo = $(this).closest("tr").find('input[name=refNo]').val();
    var attendance = $(this).closest("tr").find("select[name=AttendanceValue]").val();

    var obj = {
        attendance : attendance,
        refNo : refNo,
        registerNo : registerNo,
        date : date,
        startTime : startTime,
        endTime : endTime
    }

    /*Your AJAX code place here*/
    console.log(obj);
});

table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
    <tr>
        <th>Reg No</th>
        <th>Date</th>
        <th>Start time</th>
        <th>End time</th>
        <th>Ref no</th>
        <th>Attendence</th>
    </tr>
    <tr>
        <td><input type="text" name="registerNo"></td>
        <td><input type="date" name="date"></td>
        <td><input type="time" name="startTime"></td>
        <td><input type="time" name="endTime"></td>
        <td><input type="text" name="refNo"></td>
        <td>
            <select name="AttendanceValue">
                <option value="">select</option>
                <option value="Present">Present</option>
                <option value="Absent">Absent</option>
            </select>
        </td>
        <td><button type="button" name="submitBtn">submit</button></td>
    </tr>
    <tr>
        <td><input type="text" name="registerNo"></td>
        <td><input type="date" name="date"></td>
        <td><input type="time" name="startTime"></td>
        <td><input type="time" name="endTime"></td>
        <td><input type="text" name="refNo"></td>
        <td>
            <select name="AttendanceValue">
                <option value="">select</option>
                <option value="Present">Present</option>
                <option value="Absent">Absent</option>
            </select>
        </td>
        <td><button type="button" name="submitBtn">submit</button></td>
    </tr>
    <tr>
        <td><input type="text" name="registerNo"></td>
        <td><input type="date" name="date"></td>
        <td><input type="time" name="startTime"></td>
        <td><input type="time" name="endTime"></td>
        <td><input type="text" name="refNo"></td>
        <td>
            <select name="AttendanceValue">
                <option value="">select</option>
                <option value="Present">Present</option>
                <option value="Absent">Absent</option>
            </select>
        </td>
        <td><button type="button" name="submitBtn">submit</button></td>
    </tr>
</table>

Don't use ID anywhere, because ID is unique for each element, so use either name or class. If don't want to reload page while click button means, don't forgot to give type="button" in the button element.


问:
Make PHP error logs available to CloudWatch and logs bundle
I have a PHP environment in my ElasticBeanstalk application. I receive a HTTP 500 error at some point and I am unable to debug it as I don't see any log of it in the logs bundle.
My environment is configured to stream logs to CloudWatch and still nothing about the 500 error.

I tried adding a configuration file to the .ebextensions directory:

```<code>files:
  "/opt/elasticbeanstalk/tasks/bundlelogs.d/php.conf":
    mode: "000755"
    owner: root
    group: root
    content: |
      /var/log/php/*
      /var/log/php-fpm/*
</code>```

But still there is no php log file in the logs bundle. What can I do about this?
Thanks.

答:
The following is not tested, but should hopefully do the trick.

We should first start with finding where exactly the logs are located (see Where are logs located?). Once we identify that, we note the following (from the AWS docs):

The Elastic Beanstalk integration with CloudWatch Logs doesn't directly support the streaming of custom log files that your application generates. To stream custom logs, use a configuration file to directly install the CloudWatch Logs agent and to configure the files to be pushed.

Example configuration also given in the docs can be found here.

Body:
I have a PHP environment in my ElasticBeanstalk application. I receive a HTTP 500 error at some point and I am unable to debug it as I don't see any log of it in the logs bundle.
My environment is configured to stream logs to CloudWatch and still nothing about the 500 error.

I tried adding a configuration file to the .ebextensions directory:

files:
  "/opt/elasticbeanstalk/tasks/bundlelogs.d/php.conf":
    mode: "000755"
    owner: root
    group: root
    content: |
      /var/log/php/*
      /var/log/php-fpm/*

But still there is no php log file in the logs bundle. What can I do about this?
Thanks.


问:
CSS file got flooded with errors after VSC update
Yesterday I was working on my code as usual and everything was going fine.
Today, however, after turning on VSC I spotted that my CSS file got flooded with errors, I have no idea what happened.

Here's one example of code that worked before and now it's broken:

```<code>.portfolio {
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: (1fr)[6];
      grid-template-columns repeat(6, 1fr);
  grid-auto-rows: 300px 400px;
  grid-row-gap: 10px;
  grid-column-gap: 10px;
  grid-auto-flow: dense;
}
</code>```

I made a screenshot so you guys can see what I mean since it's my first post here and I hope it all seems clear.

https://i.stack.imgur.com/txK0n.png

Also, there is an even weirder occurrence that I can't handle, any ideas?

```<code>.nav {
  display: 0;
  position: fixed;
  z-index: 999;
  width: 66%;
  right: 0;
  top: 0;
  background: none;
  height: 100vh;
  padding: 1em;

  ul.primary-nav {
    margin-top: 5em;
  }

  li {
    color: white
  }

}
</code>```

https://imgur.com/a/ANlezCc - screen in VSC with problems

答:
By Using the solution's given in the comments i have solved my problem as follows:

First problem

```<code>.portfolio {
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
      grid-template-columns: repeat(6, 1fr);
  grid-auto-rows: 300px 400px;
  grid-row-gap: 10px;
  grid-column-gap: 10px;
  grid-auto-flow: dense;
}
</code>```

The second problem

```<code>.nav {
  display: 0;
  position: fixed;
  z-index: 999;
  width: 66%;
  right: 0;
  top: 0;
  background: none;
  height: 100vh;
  padding: 1em;
}

ul.primary-nav {
  margin-top: 5em;
}

li.nav {
  color: white
}
</code>```

Thank's for all the help!

Body:
Yesterday I was working on my code as usual and everything was going fine.
Today, however, after turning on VSC I spotted that my CSS file got flooded with errors, I have no idea what happened.

Here's one example of code that worked before and now it's broken:

.portfolio {
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: (1fr)[6];
      grid-template-columns repeat(6, 1fr);
  grid-auto-rows: 300px 400px;
  grid-row-gap: 10px;
  grid-column-gap: 10px;
  grid-auto-flow: dense;
}

I made a screenshot so you guys can see what I mean since it's my first post here and I hope it all seems clear.

https://i.stack.imgur.com/txK0n.png

Also, there is an even weirder occurrence that I can't handle, any ideas?

.nav {
  display: 0;
  position: fixed;
  z-index: 999;
  width: 66%;
  right: 0;
  top: 0;
  background: none;
  height: 100vh;
  padding: 1em;

  ul.primary-nav {
    margin-top: 5em;
  }

  li {
    color: white
  }

}

https://imgur.com/a/ANlezCc - screen in VSC with problems

Body:
By Using the solution's given in the comments i have solved my problem as follows:

First problem

.portfolio {
  display: -ms-grid;
  display: grid;
  -ms-grid-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
      grid-template-columns: repeat(6, 1fr);
  grid-auto-rows: 300px 400px;
  grid-row-gap: 10px;
  grid-column-gap: 10px;
  grid-auto-flow: dense;
}

The second problem

.nav {
  display: 0;
  position: fixed;
  z-index: 999;
  width: 66%;
  right: 0;
  top: 0;
  background: none;
  height: 100vh;
  padding: 1em;
}

ul.primary-nav {
  margin-top: 5em;
}

li.nav {
  color: white
}

Thank's for all the help!


问:
Getting NaN as output in my display only item oracle
I am getting NaN as output in Display only field..

Below is my query which is in page (function and global variable)

In this i am getting NaN for the item when the value having comma like 1,500.0 :P2510_OUTSTANDING_AMOUNT

答:
how to remove commas from unalloc_value in my Javascript

The same way you already do with match-value -

```<code>    match_value = match_value.replace(/,/g, '');
    match_value = Number(match_value, 10);
    unalloc_value = Number(unalloc_value, 10); // BQ4-5024
</code>```

Just add another replace:

```<code>    match_value = match_value.replace(/,/g, '');
    match_value = Number(match_value, 10);
    unalloc_value = unalloc_value.replace(/,/g, '');
    unalloc_value = Number(unalloc_value, 10); // BQ4-5024
</code>```

Body:
how to remove commas from unalloc_value in my Javascript

The same way you already do with match-value -

    match_value = match_value.replace(/,/g, '');
    match_value = Number(match_value, 10);
    unalloc_value = Number(unalloc_value, 10); // BQ4-5024

Just add another replace:

    match_value = match_value.replace(/,/g, '');
    match_value = Number(match_value, 10);
    unalloc_value = unalloc_value.replace(/,/g, '');
    unalloc_value = Number(unalloc_value, 10); // BQ4-5024


问:
Why does the result of #pragma omp parallel look like this
```<code>    #include<stdio.h>

    int main()
    {
        int a=0, b=0;
        #pragma omp parallel num_threads(16)
        {
            // #pragma omp single
            a++;
            // #pragma omp critical
            b++;
        }
        printf("single: %d -- critical: %d\n", a, b);
    }
</code>```

Why is my output single: 5 -- critical: 5 here?

And why is it output single: 3 -- critical: 3 when num_threads(4)?

I should not code anything like this, right? If the threads are confused here (I guess), why the result is consistent?

答: That's just pure luck, helped by inherent timing of the operation. Since this is the first parallel section in your program, threads are built instead of reused. That occupies the main thread for a while and results in threads starting sequentially. Therefore the chance of overlapping operations is lower. Try adding a #pragma omp barrier in between to increase the chance of race conditions becoming apparent.

Body:
    #include<stdio.h>

    int main()
    {
        int a=0, b=0;
        #pragma omp parallel num_threads(16)
        {
            // #pragma omp single
            a++;
            // #pragma omp critical
            b++;
        }
        printf("single: %d -- critical: %d\n", a, b);
    }

Why is my output single: 5 -- critical: 5 here?

And why is it output single: 3 -- critical: 3 when num_threads(4)?

I should not code anything like this, right? If the threads are confused here (I guess), why the result is consistent?


问:
How to toggle between booleans (in a list or tuple)?

i = True
j = False
t = (i,j)
for i in t:
    if i:
        i = not i

print (t)
(True, False)
```

For example, I want to change all values in a tuple to False, no matter the element was True or False before. How can I realise that?

答:
You can do this with a list comprehension:

t = [False for _ in t]
```
<p>or</p>
<pre class="lang-py prettyprint-override"><code>t = tuple(False for _ in t)
</code>```

if you want a tuple.

Your method doesn’t work because (imprecisely) i = not i does not change the value of i, it makes a new i, with a different value, so the ‘original’ value in your tuple is unaffected.

Body:
i = True
j = False
t = (i,j)
for i in t:
    if i:
        i = not i

print (t)
(True, False)

For example, I want to change all values in a tuple to False, no matter the element was True or False before. How can I realise that?

Body:
You can do this with a list comprehension:

t = [False for _ in t]

or

t = tuple(False for _ in t)

if you want a tuple.

Your method doesn’t work because (imprecisely) i = not i does not change the value of i, it makes a new i, with a different value, so the ‘original’ value in your tuple is unaffected.


问:
Page scrolls up using JQuery fadeIn - fadeOut
Hi I use the following code to create a slideshow with multiple DIV elements:

```<code>var $ = jQuery.noConflict();
function fadeContent() {
  $(".slideshow .asset-abstract:first").fadeIn(500).delay(2000).fadeOut(500, function() {
    $(this).appendTo($(this).parent());
    fadeContent();
  });
}
fadeContent();
</code>```

The slideshow works properly but there's a problem. When the delay(2000) trigger a fadeIn-fadeOut, the page scrolls up!

What can I do to prevent this?

答:
Its because the fadeOut method ends op settings display:none; on the element.

If you force display block in css this will not happen:

Css:

```<code>.slideshow .asset-abstract:first-child {
    display:block;
}
</code>```

Body:
Hi I use the following code to create a slideshow with multiple DIV elements:

var $ = jQuery.noConflict();
function fadeContent() {
  $(".slideshow .asset-abstract:first").fadeIn(500).delay(2000).fadeOut(500, function() {
    $(this).appendTo($(this).parent());
    fadeContent();
  });
}
fadeContent();

The slideshow works properly but there's a problem. When the delay(2000) trigger a fadeIn-fadeOut, the page scrolls up!

What can I do to prevent this?

Body:
Its because the fadeOut method ends op settings display:none; on the element.

If you force display block in css this will not happen:

Css:

.slideshow .asset-abstract:first-child {
    display:block;
}


问:
How can i make a div's right height different from the left
The image below shows exactly what I want to do

I simply want to remake this div. But nothing I have tried is getting me that shape

答:
You can use CSS property clip-path.

Here is a sample code:

```<code><div class='rating-container'>
</div>

.rating-container {
  width: 100px;
  height: 100px;
  background-color: red;
  clip-path: path('M 0 200 L 0,75 A 5,5 0,0,1 150,75 L 200 200 z');
}
</code>```

This is not the shape you want, but just to show you an example.

You can also use online clip generators like https://bennettfeely.com/clippy/

Body:
You can use CSS property clip-path.

Here is a sample code:

<div class='rating-container'>
</div>

.rating-container {
  width: 100px;
  height: 100px;
  background-color: red;
  clip-path: path('M 0 200 L 0,75 A 5,5 0,0,1 150,75 L 200 200 z');
}

This is not the shape you want, but just to show you an example.

You can also use online clip generators like https://bennettfeely.com/clippy/