问:
In Gradle, how do I declare common dependencies in a single place?
In Maven there is a very useful feature where you can define a dependency in the <dependencyManagement> section of the parent POM, and reference that dependency from child modules without specifying the version or scope or whatever.

What are the alternatives in Gradle?

答:
As datta said in their answer, Gradle now has something called version catalogs.

Here is an example for Kotlin DSL (*.kts files). Note that I'm using Gradle 7.4.

Defining dependencies in settings.gradle.kts:

// Configure dependencies aspects applied to all projects
dependencyResolutionManagement {
    // By default, repositories declared by a project will override the ones here.
    // You can change this behavior with the repositoriesMode property.
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)

    // Define repositories for all projects
    repositories {
        mavenCentral()
        maven("https://jitpack.io")
    }

    versionCatalogs {
        create("libs") {
            // Versions are useful specially when you have libraries with the same
            // group and version which are updated together with the same version
            version("room", "2.4.1")
            //       │       │
            //       │       └───> The version notation
            //       └───> Your desired name (alias)

            library("material", "com.google.android.material:material:1.4.0")
            //       │           │
            //       │           └───> The dependency notation (coordinates)
            //       ├───> Your desired name (alias); only letters, digits and _ - .
            //       └───> Note that _ - . will all be normalized to .

            // You can configure the version as you would in a regular build file
            // Note that the group and module are separate parameters
            library("junit5", "org.junit.jupiter", "junit-jupiter").version {
                prefer("5.8.0")
            }

            // Using the same version for multiple dependencies
            library("room-ktx", "androidx.room", "room-ktx").versionRef("room")
            library("room-runtime", "androidx.room", "room-runtime").versionRef("room")
        }
    }
}
```
<p>Usage in <em>build.gradle[.kts]</em>:</p>
<pre class="lang-kotlin prettyprint-override"><code>dependencies {
    implementation(libs.material)
    implementation(libs.room.ktx)
    implementation(libs.room.runtime)
    testImplementation(libs.junit5)
}
</code>```

As you can see, not only can you declare dependencies, but also you can declare the repositories here as well (instead of using allprojects block in your top-level build script to define repositories for all subprojects).

For groovy syntax of above solution and for more information about version catalogs and centralizing your repository and dependency configurations, see Gradle official guides.

Body:
As datta said in their answer, Gradle now has something called version catalogs.

Here is an example for Kotlin DSL (*.kts files). Note that I'm using Gradle 7.4.

Defining dependencies in settings.gradle.kts:

// Configure dependencies aspects applied to all projects
dependencyResolutionManagement {
    // By default, repositories declared by a project will override the ones here.
    // You can change this behavior with the repositoriesMode property.
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)

    // Define repositories for all projects
    repositories {
        mavenCentral()
        maven("https://jitpack.io")
    }

    versionCatalogs {
        create("libs") {
            // Versions are useful specially when you have libraries with the same
            // group and version which are updated together with the same version
            version("room", "2.4.1")
            //       │       │
            //       │       └───> The version notation
            //       └───> Your desired name (alias)

            library("material", "com.google.android.material:material:1.4.0")
            //       │           │
            //       │           └───> The dependency notation (coordinates)
            //       ├───> Your desired name (alias); only letters, digits and _ - .
            //       └───> Note that _ - . will all be normalized to .

            // You can configure the version as you would in a regular build file
            // Note that the group and module are separate parameters
            library("junit5", "org.junit.jupiter", "junit-jupiter").version {
                prefer("5.8.0")
            }

            // Using the same version for multiple dependencies
            library("room-ktx", "androidx.room", "room-ktx").versionRef("room")
            library("room-runtime", "androidx.room", "room-runtime").versionRef("room")
        }
    }
}

Usage in build.gradle[.kts]:

dependencies {
    implementation(libs.material)
    implementation(libs.room.ktx)
    implementation(libs.room.runtime)
    testImplementation(libs.junit5)
}

As you can see, not only can you declare dependencies, but also you can declare the repositories here as well (instead of using allprojects block in your top-level build script to define repositories for all subprojects).

For groovy syntax of above solution and for more information about version catalogs and centralizing your repository and dependency configurations, see Gradle official guides.


来源: stackexchange

问:
Python | Find a specific line and save the two lines under it
sorry if the title confused you but what I'm looking for should be simple I think.

So basically I have a big text file that contains a list like this:

```<code>  From: United States, Chicago 2039 Street
  Name: Markus
  Code: 3294
</code>```

It has thousands of lines that contain different cities, names and codes. What I'm trying to do is find every line that contains the word "Chicago" and I want it to save the two lines under it (Name and code) in a different text file.

I have this python code that saves the line that contains a specific word:

```<code>with open("names.txt", encoding='ISO-8859-1') as f: #File that contains the names
with open("home.txt", "a", encoding='ISO-8859-1') as f1: #Second file to save the info on
    for line in f:
        if str("Chicago") in line: #If line contains Chicago
            f1.write(str(line)) #Save the line in the second file
</code>```

Thanks in advance!

答:
You have to iterate your file using index and then fetch the next two indices when your desired line is found indexing gives you more control</p>
```<code>with open("names.txt", encoding='ISO-8859-1') as f: #File that contains the names
    lines = list(f)
    with open("home.txt", "a", encoding='ISO-8859-1') as f1: #Second file to save the info on
        for index in range(len(lines)):
            if str("Chicago") in lines[index]: #If line contains Chicago
                f1.write(str(lines[index + 1])) #Save the line in the second file
                f1.write(str(lines[index + 2])) #Save the line in the second file
</code>```

ContentLicense: CC BY-SA 4.0

Body:
sorry if the title confused you but what I'm looking for should be simple I think.

So basically I have a big text file that contains a list like this:

  From: United States, Chicago 2039 Street
  Name: Markus
  Code: 3294

It has thousands of lines that contain different cities, names and codes. What I'm trying to do is find every line that contains the word "Chicago" and I want it to save the two lines under it (Name and code) in a different text file.

I have this python code that saves the line that contains a specific word:

with open("names.txt", encoding='ISO-8859-1') as f: #File that contains the names
with open("home.txt", "a", encoding='ISO-8859-1') as f1: #Second file to save the info on
    for line in f:
        if str("Chicago") in line: #If line contains Chicago
            f1.write(str(line)) #Save the line in the second file

Thanks in advance!

Body:
You have to iterate your file using index and then fetch the next two indices when your desired line is found indexing gives you more control

with open("names.txt", encoding='ISO-8859-1') as f: #File that contains the names
    lines = list(f)
    with open("home.txt", "a", encoding='ISO-8859-1') as f1: #Second file to save the info on
        for index in range(len(lines)):
            if str("Chicago") in lines[index]: #If line contains Chicago
                f1.write(str(lines[index + 1])) #Save the line in the second file
                f1.write(str(lines[index + 2])) #Save the line in the second file


问:
MySQL doesn't set a default value while adding a new row to the table
I'm writing a web application (that represents online banking work). I have an entity "user" and a corresponding table in the database. Also, I have a registration form that transfers entered data via Thymeleaf.

My entity has two rows that have default values in the database. These are "role" row and "status". I set the default value in the database.

But, when I do input data in the registration form and click "sign up", the data transfers to the database successfully, however, two rows (role and status) that have their own default values are of a null type. Why the default values aren't being set automatically?

My entity class:

```<code>@Data
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "status")
    private Status status;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "role")
    private Role role;
}
</code>```

My settings in the database table:

When I check the property "NOT NULL", I'm receiving an error that tells me that the row "role" cannot be null.

That's how my table looks like when I register new users:

My controller:

```<code>@Controller
@RequestMapping("/auth")
public class AuthController {

    private final UserRepository userRepository;

    @Autowired
    public AuthController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/login")
    public String login() {
        return "/auth/login";
    }

    @GetMapping("/signup")
    public String signUp(User user, Model model) {
        return "/auth/registration";
    }

    @PostMapping("/signup")
    public String signUpProcess(@ModelAttribute User user, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "redirect:/auth/registration";
        }

        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(12);
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        userRepository.save(user);

        return "redirect:/auth/login";
    }

}
</code>```

Registration page:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Registration</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="/static/login.css">

    <form class="form-signin" th:method="post" th:object="${user}">

Registration

 Enter all the required information into the forms below.

            <input type="text" id="inputFirstName" th:field="*{firstName}" class="form-control" placeholder="First Name" required>
            First Name

            <input type="text" id="inputLastName" th:field="*{lastName}" class="form-control" placeholder="Last Name" required>
            Last Name

            <input type="email" id="inputEmail" th:field="*{email}" class="form-control" placeholder="Email address" required autofocus>
            Email address

            <input type="password" id="inputPassword" th:field="*{password}" class="form-control" placeholder="Password" required>
            Password

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>

Already registered? Click to sign in

© BlackBank 2022

    </form>

```
</div>
</div>
</p>
<p>If I haven't specified some valuable information, please, let me know.</p>
<p>Update:</p>
<p>SHOW CREATE TABLE:</p>
```CREATE TABLE `users` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(150) NOT NULL,
  `role` varchar(20) NOT NULL DEFAULT 'USER',
  `status` varchar(20) NOT NULL DEFAULT 'ACTIVE',
  PRIMARY KEY (`id`),
  UNIQUE KEY `users_id_uindex` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
```
<p>My Role and Status classes (enums):</p>
<p>Role.class:</p>
```public enum Role {
    // Each role has a specific set of permissions
    USER(Set.of(Permission.USERS_READ)),
    ADMIN(Set.of(Permission.USERS_READ, Permission.USERS_WRITE, Permission.USERS_UPDATE)),
    OWNER(Set.of(Permission.USERS_READ, Permission.USERS_WRITE, Permission.USERS_UPDATE, Permission.USERS_DELETE));

    private Set<Permission> permissions;

    Role(Set<Permission> permissions) {
        this.permissions = permissions;
    }

    public Set<Permission> getPermissions() {
        return permissions;
    }

    public Set<SimpleGrantedAuthority> getAuthorities() {
        return getPermissions().stream().map(permission -> new SimpleGrantedAuthority(permission.getPermission())).collect(Collectors.toSet());
    }

}
```
<p>Status.class:</p>
```public enum Status {
    ACTIVE, BANNED;
}
```

答:
DEFAULT constraint defined on table will work in case of native query(in hibernate).

"INSERT INTO USERS (id, first_name, last_name, email, password) VALUES (v1, v2,  v3, v5)" --  // in this case the fields(status, role) are not specified and
the db will set default value(ACTIVE, USER)

another solution would be use annotation @PrePersist in your entity class to check the value of the fields and change it if is null(before object is saved).

```<code>  @PrePersist
  public void control() {
    if (status == null)
      setStatus("ACTIVE");
  }
</code>```

Body:
I'm writing a web application (that represents online banking work). I have an entity "user" and a corresponding table in the database. Also, I have a registration form that transfers entered data via Thymeleaf.

My entity has two rows that have default values in the database. These are "role" row and "status". I set the default value in the database.

But, when I do input data in the registration form and click "sign up", the data transfers to the database successfully, however, two rows (role and status) that have their own default values are of a null type. Why the default values aren't being set automatically?

My entity class:

@Data
@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;
    @Column(name = "first_name")
    private String firstName;
    @Column(name = "last_name")
    private String lastName;
    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "status")
    private Status status;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "role")
    private Role role;
}

My settings in the database table:

When I check the property "NOT NULL", I'm receiving an error that tells me that the row "role" cannot be null.

That's how my table looks like when I register new users:

My controller:

@Controller
@RequestMapping("/auth")
public class AuthController {

    private final UserRepository userRepository;

    @Autowired
    public AuthController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @GetMapping("/login")
    public String login() {
        return "/auth/login";
    }

    @GetMapping("/signup")
    public String signUp(User user, Model model) {
        return "/auth/registration";
    }

    @PostMapping("/signup")
    public String signUpProcess(@ModelAttribute User user, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "redirect:/auth/registration";
        }

        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(12);
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        userRepository.save(user);

        return "redirect:/auth/login";
    }

}

Registration page:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Registration</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="/static/login.css">

    <form class="form-signin" th:method="post" th:object="${user}">

Registration

 Enter all the required information into the forms below.

            <input type="text" id="inputFirstName" th:field="*{firstName}" class="form-control" placeholder="First Name" required>
            First Name

            <input type="text" id="inputLastName" th:field="*{lastName}" class="form-control" placeholder="Last Name" required>
            Last Name

            <input type="email" id="inputEmail" th:field="*{email}" class="form-control" placeholder="Email address" required autofocus>
            Email address

            <input type="password" id="inputPassword" th:field="*{password}" class="form-control" placeholder="Password" required>
            Password

        <button class="btn btn-lg btn-primary btn-block" type="submit">Sign up</button>

Already registered? Click to sign in

© BlackBank 2022

    </form>

If I haven't specified some valuable information, please, let me know.

Update:

SHOW CREATE TABLE:

CREATE TABLE `users` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `password` varchar(150) NOT NULL,
  `role` varchar(20) NOT NULL DEFAULT 'USER',
  `status` varchar(20) NOT NULL DEFAULT 'ACTIVE',
  PRIMARY KEY (`id`),
  UNIQUE KEY `users_id_uindex` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

My Role and Status classes (enums):

Role.class:

public enum Role {
    // Each role has a specific set of permissions
    USER(Set.of(Permission.USERS_READ)),
    ADMIN(Set.of(Permission.USERS_READ, Permission.USERS_WRITE, Permission.USERS_UPDATE)),
    OWNER(Set.of(Permission.USERS_READ, Permission.USERS_WRITE, Permission.USERS_UPDATE, Permission.USERS_DELETE));

    private Set<Permission> permissions;

    Role(Set<Permission> permissions) {
        this.permissions = permissions;
    }

    public Set<Permission> getPermissions() {
        return permissions;
    }

    public Set<SimpleGrantedAuthority> getAuthorities() {
        return getPermissions().stream().map(permission -> new SimpleGrantedAuthority(permission.getPermission())).collect(Collectors.toSet());
    }

}

Status.class:

public enum Status {
    ACTIVE, BANNED;
}

Body:
DEFAULT constraint defined on table will work in case of native query(in hibernate).

"INSERT INTO USERS (id, first_name, last_name, email, password) VALUES (v1, v2,  v3, v5)" --  // in this case the fields(status, role) are not specified and
the db will set default value(ACTIVE, USER)

another solution would be use annotation @PrePersist in your entity class to check the value of the fields and change it if is null(before object is saved).

  @PrePersist
  public void control() {
    if (status == null)
      setStatus("ACTIVE");
  }


问:
Forever start angular-http-server is not working
I'm trying to run angular dist in the background and I'm targeting the node_modules folder in the dist correctly and finding the angular-http-server library there.
The terminal is not showing any error but it's not starting. I'm using this command:

```<code>forever start angular-http-server --host 'IP'
</code>```

Is the command wrong? What should I do?

答:
with the command

forever start node_modules/@angular/cli/bin/ng serve --host {ip_address or domain} --prod

Show me an error:

error:   Cannot start forever error:   script /home/ec2-user/angular01/backend-java-angular01/node_modules/@angular/cli/bin/node_modules/@angular/cli/bin/ng does not exist.

Thanks for the help
PD: ng its working fine.
forever is installed
folder @angular/cli/bin/ng exits

Body:
I'm trying to run angular dist in the background and I'm targeting the node_modules folder in the dist correctly and finding the angular-http-server library there.
The terminal is not showing any error but it's not starting. I'm using this command:

forever start angular-http-server --host 'IP'

Is the command wrong? What should I do?


问:
RealityKit – AnchorEntity moves only to Origin
The problem is that it rise to origin... not just rotating itself.

video is youtu.be/hFafOjKN3rg

```<code>anchorEntity.anchoring = AnchoringComponent(anchor)
anchorEntity.addChild(modelEntityClone)
anchorEntity.addChild(downEntity)
anchorEntity.addChild(sideEntity)
anchorEntity.addChild(rightEntity)
anchorEntity.name = name

arView.scene.addAnchor(anchorEntity)
arView.scene.addAnchor(planeEntity)

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    print("after 3 sec")

    let radians = 90.0 * Float.pi / 180.0

    let currentMatrix = anchorEntity.transform.matrix
    let rotation = simd_float4x4(SCNMatrix4MakeRotation(90.0 * .pi/180, 0,1,0))
    let transform = simd_mul(currentMatrix, rotation)
    anchorEntity.move(to: transform, relativeTo: nil, duration: 3.0)
}
</code>```

答:
Apply anchor's rotation relative to model entity:

```<code>let model = ModelEntity(mesh: .generateBox(size: 0.2))
let anchor = AnchorEntity(world: [0, 0.5, 0])
anchor.addChild(model)

let currentMatrix = anchor.transform.matrix
let rotation = simd_float4x4(SCNMatrix4MakeRotation(.pi/2, 0, 1, 0))
let transform = simd_mul(currentMatrix, rotation)
anchor.move(to: transform, relativeTo: model, duration: 3.0)
</code>```

This post is also useful.

Body:
The problem is that it rise to origin... not just rotating itself.

video is youtu.be/hFafOjKN3rg

anchorEntity.anchoring = AnchoringComponent(anchor)
anchorEntity.addChild(modelEntityClone)
anchorEntity.addChild(downEntity)
anchorEntity.addChild(sideEntity)
anchorEntity.addChild(rightEntity)
anchorEntity.name = name

arView.scene.addAnchor(anchorEntity)
arView.scene.addAnchor(planeEntity)

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    print("after 3 sec")

    let radians = 90.0 * Float.pi / 180.0

    let currentMatrix = anchorEntity.transform.matrix
    let rotation = simd_float4x4(SCNMatrix4MakeRotation(90.0 * .pi/180, 0,1,0))
    let transform = simd_mul(currentMatrix, rotation)
    anchorEntity.move(to: transform, relativeTo: nil, duration: 3.0)
}

Body:
Apply anchor's rotation relative to model entity:

let model = ModelEntity(mesh: .generateBox(size: 0.2))
let anchor = AnchorEntity(world: [0, 0.5, 0])
anchor.addChild(model)

let currentMatrix = anchor.transform.matrix
let rotation = simd_float4x4(SCNMatrix4MakeRotation(.pi/2, 0, 1, 0))
let transform = simd_mul(currentMatrix, rotation)
anchor.move(to: transform, relativeTo: model, duration: 3.0)

This post is also useful.


问:
Best practices for link logging in JavaScript?
Basically, onclick will trigger exclusively on left clicks.

Most places recommend onmouseup, because it triggers on left, middle, and right clicks.  The right clicks can of course be filtered out.  However, it is still possible to generate false positives from onmouseup by left or middle click dragging from text to the link.

Is there a more direct way in JavaScript that will be triggered if and only if an external link is followed?  Or is onmouseup the only practical solution?

答:
I prefer onmouseup only.

For onbeforeunload; this method is not supported in Opera. Rest all leading browsers supports it. There is no public specification for it too. onbeforeunload was introduced by Microsoft IE 4 and has subsequently been copied by other browsers.

ContentLicense: CC BY-SA 3.0


问:
Filter out everything before a condition is met, keep all elements after
I was wondering if there was an easy solution to the the following problem. The problem here is that I want to keep every element occurring inside this list after the initial condition is true. The condition here being that I want to remove everything before the condition that a value is greater than 18 is true, but keep everything after. Example

Input:

```<code>p = [4,9,10,4,20,13,29,3,39]
</code>```

Expected output:

```<code>p = [20,13,29,3,39]
</code>```

I know that you can filter over the entire list through

```<code>[x for x in p if x>18]
</code>```

But I want to stop this operation once the first value above 18 is found, and then include the rest of the values regardless if they satisfy the condition or not. It seems like an easy problem but I haven't found the solution to it yet.

答:
In my experience, at least for lists of ints, using enumerate just to find one index and throwing all other indexes away is so wasteful that it's faster to first only find the element and then use list.index to find its index.  Based on some testing, I expect it to be about factor 1.44 faster than the explicit_loop solution (which uses enumerate) in @enke's benchmark.

```<code>def start_over_18(p):
    for x in p:
        if x > 18:
            return p[p.index(x):]
    return []
</code>```

Another solution, using an iterator so I don't have to bother with indexes at all. Seems to be about twice as fast as the explicit_loop solution:

```<code>def start_over_18(p):
    it = iter(p)
    for x in it:
        if x > 18:
            return [x, *it]
    return []
</code>```

Body:
I was wondering if there was an easy solution to the the following problem. The problem here is that I want to keep every element occurring inside this list after the initial condition is true. The condition here being that I want to remove everything before the condition that a value is greater than 18 is true, but keep everything after. Example

Input:

p = [4,9,10,4,20,13,29,3,39]

Expected output:

p = [20,13,29,3,39]

I know that you can filter over the entire list through

[x for x in p if x>18]

But I want to stop this operation once the first value above 18 is found, and then include the rest of the values regardless if they satisfy the condition or not. It seems like an easy problem but I haven't found the solution to it yet.

Body:
In my experience, at least for lists of ints, using enumerate just to find one index and throwing all other indexes away is so wasteful that it's faster to first only find the element and then use list.index to find its index.  Based on some testing, I expect it to be about factor 1.44 faster than the explicit_loop solution (which uses enumerate) in @enke's benchmark.

def start_over_18(p):
    for x in p:
        if x > 18:
            return p[p.index(x):]
    return []

Another solution, using an iterator so I don't have to bother with indexes at all. Seems to be about twice as fast as the explicit_loop solution:

def start_over_18(p):
    it = iter(p)
    for x in it:
        if x > 18:
            return [x, *it]
    return []


问:
AlertDialog like permission dialog in Android TV (Leanback) App
I'm working on an Android TV project which is a leanback project basically.

I want to show an alert dialog similar to the permission dialog in android tv apps. see the image.

I tried adding normal AlertDialog like this:

```<code>AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
AlertDialog alert = alertBuilder.create();
alert.show();
</code>```

but that doesn't help. Can anyone show me the way to show similar AlertDialog in Android TV app?

答:
I didn't find a solution and created a custom DialogFragment, Look at github

And now I can create the dialog I need like this

```<code>val dialogExit = LeanbackDialogFragment(R.string.dialog_exit, R.string.dialog_exit_d, R.drawable.ic_exit)
dialogExit.addButton(R.string.yes) { dialog, which ->
    exitProcess(0)
}
dialogExit.addButton(R.string.no)
dialogExit.addButton("I don't know")
dialogExit.show(requireActivity().supportFragmentManager)
</code>```

Result

Body:
I'm working on an Android TV project which is a leanback project basically.

I want to show an alert dialog similar to the permission dialog in android tv apps. see the image.

I tried adding normal AlertDialog like this:

AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
AlertDialog alert = alertBuilder.create();
alert.show();

but that doesn't help. Can anyone show me the way to show similar AlertDialog in Android TV app?

Body:
I didn't find a solution and created a custom DialogFragment, Look at github

And now I can create the dialog I need like this

val dialogExit = LeanbackDialogFragment(R.string.dialog_exit, R.string.dialog_exit_d, R.drawable.ic_exit)
dialogExit.addButton(R.string.yes) { dialog, which ->
    exitProcess(0)
}
dialogExit.addButton(R.string.no)
dialogExit.addButton("I don't know")
dialogExit.show(requireActivity().supportFragmentManager)

Result


问:
"xx" is get-only property - How to Assign decoded Json Data to class (nested view model) Swift
I have a watchapp that receives parent view model (nested view model) data from iPhone via json/file transfer. I am using "Communicator" library by @KaneCheshire.

The data flow is

Watch App launches - loading empty Parent View Model (ReceivedDayProgViewModel) into the app and showing activity indicator in WatchLoadingView.

WatchLoadingView set-up observer to receive actual json data/file from iPhone

WatchLoadingView's observer receives actual json data, decodes them into ParentViewModel object (ReceivedDayProgViewModel)

After step 3, I am having difficulty actually assigning the decoded object to the initially empty Parent View Model (ReceivedDayProgViewModel). There is a error message saying "**Cannot assign to property: 'receivedDayProgramVM' is a get-only property**"

So I did look up the error and have an idea that my parent View Model is actually a "computed-property" instead of stored property - How do I resolve this build issue - cannot assign to property: 'date' is a get only property But I am still struggling to add codes to ensure "set/write" function is embedded in the Parent View Model(ReceivedDayProgViewModel).

Would appreciate any guidance/advice on how I can change my code to allow "set/write" operation in Parent View Model (ReceivedDayProgViewModel) so below step can be fulfilled.

Assign decoded object (let ReceivedDayProgViewModel = try! decoder.decode(ReceivedDayProgViewModel.self, from: ReceivedDayProgVMData)) (with values/data from iPhone) into the @StateObject in ContentView  (receivedDayProgramVM)

Parent View Model

```<code>import Foundation
import Combine

class ReceivedDayProgViewModel: ObservableObject, Codable {

    @Published var workoutModel = WorkoutModel()
    @Published var watchDayProgramSequence: Int = 0
    @Published var exerciseVM: [WatchExerciseViewModel] = []

    enum CodingKeys: String, CodingKey {

        case dayProgramSeq
        case exerciseVM

    }

    init() {
           //initiliazed empty view model via this function
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        watchDayProgramSequence = try container.decode(Int.self, forKey: .dayProgramSeq)
        exerciseVM = try container.decode([WatchExerciseViewModel].self, forKey: .exerciseVM)

        do {
            watchDayProgramSequence = try container.decode(Int.self, forKey: .dayProgramSeq)
        } catch DecodingError.typeMismatch {
            do {
                watchDayProgramSequence = try Int(container.decode(String.self, forKey: .dayProgramSeq)) ?? 0
            }
        }

    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(watchDayProgramSequence, forKey: .dayProgramSeq)
        try container.encode(exerciseVM, forKey: .exerciseVM)

    }//encode function ends

}
</code>```

WatchApp

```<code>import SwiftUI
import Communicator

@main
struct WatchApp: App {

    @SceneBuilder var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView(selectedTab: 0, receivedDayProgramVM: ReceivedDayProgViewModel())
            }
        }

        WKNotificationScene(controller: NotificationController.self, category: "myCategory")
    }
}

</code>```

ContentView

```<code>import SwiftUI
import WatchKit
import Combine
import Communicator

struct ContentView: View {
    @State var selectedTab = 0

    @StateObject var receivedDayProgramVM = ReceivedDayProgViewModel()

    var body: some View {

        NavigationView {

            //Show WatchLoadingView, if dayprogramVM is being fetched
            if receivedDayProgramVM.exerciseVM.count == 0 {

                   WatchLoadingView()
                    .onAppear {
                        //Add Communicator functions if required
                         Blob.observe { Blob in

                             if Blob.identifier == "dayProgramData" {

                                 let ReceivedDayProgVMData = Blob.content
                                 print("WatchConnectivity blob setData printing \(ReceivedDayProgVMData)")

                                 let decoder = JSONDecoder()

                                 let ReceivedDayProgViewModel = try! decoder.decode(ReceivedDayProgViewModel.self, from: ReceivedDayProgVMData)

                                 //Assign decoded class(parent view model) to environment object in contentView
//This is the line that causes error showing receivedDayProgramVM is get-only property
                                 receivedDayProgramVM = ReceivedDayProgViewModel

                             } //Blob for "dayProgramData" code ends

                         } //Blob observation code ends
                    } else {

                TabView(selection: $selectedTab) {

                    WatchControlView().id(0)
                    SetInformationView().id(1)
                    SetRestDetailView().id(2)
                    //Check if WatchControlView can be vertically scrollable
                    NowPlayingView().id(3)
                }
                .environmentObject(receivedDayProgramVM)
            }

        }
    }
}

</code>```

WatchLoadingView

```<code>import SwiftUI
import Communicator

struct WatchLoadingView: View {

    var body: some View {

        GeometryReader { geometry in

            let rect = geometry.frame(in: .global)

            VStack {
                ProgressView()
                Text("Fetching Data...")
                    .font(.body)
            }
        }
    }
}
</code>```

答:
I am posting my answer after getting the right clue from Joakim & Ptit's comments. As per their advice, I have separated (data) model and view model for the watch app.

It was a little time-consuming, but I managed to update the app design, and it enabled me to store transferred data into appropriate view model class.

See below code extract for future reference.

WatchDayProgram Struct (Data Model)

```<code>import Foundation
import Combine

struct WatchDayProgram: Codable {

    var watchDayProgramSequence: Int = 0
    var exerciseVM: [WatchExercise]

    enum CodingKeys: String, CodingKey {

        case dayProgramSeq
        case exerciseVM

    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        watchDayProgramSequence = try container.decode(Int.self, forKey: .dayProgramSeq)
        exerciseVM = try container.decode([WatchExercise].self, forKey: .exerciseVM)

        do {
            watchDayProgramSequence = try container.decode(Int.self, forKey: .dayProgramSeq)
        } catch DecodingError.typeMismatch {
            do {
                watchDayProgramSequence = try Int(container.decode(String.self, forKey: .dayProgramSeq)) ?? 0
            }
        }

    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(watchDayProgramSequence, forKey: .dayProgramSeq)
        try container.encode(exerciseVM, forKey: .exerciseVM)

    }//encode function ends

}
</code>```

WatchDayProgViewModel

```<code>import Foundation
import Combine

class ReceivedDayProgViewModel: ObservableObject {

    @Published var workoutModel = WorkoutModel()
    @Published var watchDayProgramSequence: Int = 0
    @Published var exerciseVM: [WatchExerciseViewModel] = []

    init() {
           //initiliazed empty view model via this function, so empty view model class can be loaded onto Watch app when it starts while awaiting for the file transfer to be complete
    }

}
</code>```

ContentView

```<code>import SwiftUI
import WatchKit
import Combine
import Communicator

struct ContentView: View {
    @State var selectedTab = 0

    @StateObject var receivedDayProgramVM = ReceivedDayProgViewModel()

    var body: some View {

        NavigationView {

            //Show WatchLoadingView, if dayprogramVM is being fetched
            if receivedDayProgramVM.exerciseVM.isEmpty == true {

                   WatchLoadingView()
                    .onAppear {

                         Blob.observe { Blob in

                             if Blob.identifier == "dayProgramData" {

                                 let ReceivedDayProgVMData = Blob.content
                                 print("WatchConnectivity blob setData printing \(ReceivedDayProgVMData)")

                                 let decoder = JSONDecoder()
                                 let ReceivedDayProgViewModel = try! decoder.decode(WatchDayProgram.self, from: ReceivedDayProgVMData)

                                 for (i, exercise) in ReceivedDayProgViewModel.exerciseVM.enumerated() {

                                     DispatchQueue.main.async {
                                         receivedDayProgramVM.exerciseVM.append(WatchExerciseViewModel(exercise: exercise))
                                     }

                             } //Blob for "dayProgramData" code ends

                         } //Blob observation code ends
                    } else {

                TabView(selection: $selectedTab) {

                    WatchControlView().id(0)
                    SetInformationView().id(1)
                    SetRestDetailView().id(2)
                    //Check if WatchControlView can be vertically scrollable
                    NowPlayingView().id(3)
                }
                .environmentObject(receivedDayProgramVM)
            }

        }
    }
}
</code>```

Body:
I have a watchapp that receives parent view model (nested view model) data from iPhone via json/file transfer. I am using "Communicator" library by @KaneCheshire.

The data flow is

Watch App launches - loading empty Parent View Model (ReceivedDayProgViewModel) into the app and showing activity indicator in WatchLoadingView.

WatchLoadingView set-up observer to receive actual json data/file from iPhone

WatchLoadingView's observer receives actual json data, decodes them into ParentViewModel object (ReceivedDayProgViewModel)

After step 3, I am having difficulty actually assigning the decoded object to the initially empty Parent View Model (ReceivedDayProgViewModel). There is a error message saying "**Cannot assign to property: 'receivedDayProgramVM' is a get-only property**"

So I did look up the error and have an idea that my parent View Model is actually a "computed-property" instead of stored property - How do I resolve this build issue - cannot assign to property: 'date' is a get only property But I am still struggling to add codes to ensure "set/write" function is embedded in the Parent View Model(ReceivedDayProgViewModel).

Would appreciate any guidance/advice on how I can change my code to allow "set/write" operation in Parent View Model (ReceivedDayProgViewModel) so below step can be fulfilled.

Assign decoded object (let ReceivedDayProgViewModel = try! decoder.decode(ReceivedDayProgViewModel.self, from: ReceivedDayProgVMData)) (with values/data from iPhone) into the @StateObject in ContentView  (receivedDayProgramVM)

Parent View Model

import Foundation
import Combine

class ReceivedDayProgViewModel: ObservableObject, Codable {

    @Published var workoutModel = WorkoutModel()
    @Published var watchDayProgramSequence: Int = 0
    @Published var exerciseVM: [WatchExerciseViewModel] = []

    enum CodingKeys: String, CodingKey {

        case dayProgramSeq
        case exerciseVM

    }

    init() {
           //initiliazed empty view model via this function
    }

    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        watchDayProgramSequence = try container.decode(Int.self, forKey: .dayProgramSeq)
        exerciseVM = try container.decode([WatchExerciseViewModel].self, forKey: .exerciseVM)

        do {
            watchDayProgramSequence = try container.decode(Int.self, forKey: .dayProgramSeq)
        } catch DecodingError.typeMismatch {
            do {
                watchDayProgramSequence = try Int(container.decode(String.self, forKey: .dayProgramSeq)) ?? 0
            }
        }

    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(watchDayProgramSequence, forKey: .dayProgramSeq)
        try container.encode(exerciseVM, forKey: .exerciseVM)

    }//encode function ends

}

WatchApp

import SwiftUI
import Communicator

@main
struct WatchApp: App {

    @SceneBuilder var body: some Scene {
        WindowGroup {
            NavigationView {
                ContentView(selectedTab: 0, receivedDayProgramVM: ReceivedDayProgViewModel())
            }
        }

        WKNotificationScene(controller: NotificationController.self, category: "myCategory")
    }
}

ContentView

import SwiftUI
import WatchKit
import Combine
import Communicator

struct ContentView: View {
    @State var selectedTab = 0

    @StateObject var receivedDayProgramVM = ReceivedDayProgViewModel()

    var body: some View {

        NavigationView {

            //Show WatchLoadingView, if dayprogramVM is being fetched
            if receivedDayProgramVM.exerciseVM.count == 0 {

                   WatchLoadingView()
                    .onAppear {
                        //Add Communicator functions if required
                         Blob.observe { Blob in

                             if Blob.identifier == "dayProgramData" {

                                 let ReceivedDayProgVMData = Blob.content
                                 print("WatchConnectivity blob setData printing \(ReceivedDayProgVMData)")

                                 let decoder = JSONDecoder()

                                 let ReceivedDayProgViewModel = try! decoder.decode(ReceivedDayProgViewModel.self, from: ReceivedDayProgVMData)

                                 //Assign decoded class(parent view model) to environment object in contentView
//This is the line that causes error showing receivedDayProgramVM is get-only property
                                 receivedDayProgramVM = ReceivedDayProgViewModel

                             } //Blob for "dayProgramData" code ends

                         } //Blob observation code ends
                    } else {

                TabView(selection: $selectedTab) {

                    WatchControlView().id(0)
                    SetInformationView().id(1)
                    SetRestDetailView().id(2)
                    //Check if WatchControlView can be vertically scrollable
                    NowPlayingView().id(3)
                }
                .environmentObject(receivedDayProgramVM)
            }

        }
    }
}

WatchLoadingView

import SwiftUI
import Communicator

struct WatchLoadingView: View {

    var body: some View {

        GeometryReader { geometry in

            let rect = geometry.frame(in: .global)

            VStack {
                ProgressView()
                Text("Fetching Data...")
                    .font(.body)
            }
        }
    }
}

Body:
I am posting my answer after getting the right clue from Joakim & Ptit's comments. As per their advice, I have separated (data) model and view model for the watch app.

It was a little time-consuming, but I managed to update the app design, and it enabled me to store transferred data into appropriate view model class.

See below code extract for future reference.

WatchDayProgram Struct (Data Model)

import Foundation
import Combine

struct WatchDayProgram: Codable {

    var watchDayProgramSequence: Int = 0
    var exerciseVM: [WatchExercise]

    enum CodingKeys: String, CodingKey {

        case dayProgramSeq
        case exerciseVM

    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)

        watchDayProgramSequence = try container.decode(Int.self, forKey: .dayProgramSeq)
        exerciseVM = try container.decode([WatchExercise].self, forKey: .exerciseVM)

        do {
            watchDayProgramSequence = try container.decode(Int.self, forKey: .dayProgramSeq)
        } catch DecodingError.typeMismatch {
            do {
                watchDayProgramSequence = try Int(container.decode(String.self, forKey: .dayProgramSeq)) ?? 0
            }
        }

    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)

        try container.encode(watchDayProgramSequence, forKey: .dayProgramSeq)
        try container.encode(exerciseVM, forKey: .exerciseVM)

    }//encode function ends

}

WatchDayProgViewModel

import Foundation
import Combine

class ReceivedDayProgViewModel: ObservableObject {

    @Published var workoutModel = WorkoutModel()
    @Published var watchDayProgramSequence: Int = 0
    @Published var exerciseVM: [WatchExerciseViewModel] = []

    init() {
           //initiliazed empty view model via this function, so empty view model class can be loaded onto Watch app when it starts while awaiting for the file transfer to be complete
    }

}

ContentView

import SwiftUI
import WatchKit
import Combine
import Communicator

struct ContentView: View {
    @State var selectedTab = 0

    @StateObject var receivedDayProgramVM = ReceivedDayProgViewModel()

    var body: some View {

        NavigationView {

            //Show WatchLoadingView, if dayprogramVM is being fetched
            if receivedDayProgramVM.exerciseVM.isEmpty == true {

                   WatchLoadingView()
                    .onAppear {

                         Blob.observe { Blob in

                             if Blob.identifier == "dayProgramData" {

                                 let ReceivedDayProgVMData = Blob.content
                                 print("WatchConnectivity blob setData printing \(ReceivedDayProgVMData)")

                                 let decoder = JSONDecoder()
                                 let ReceivedDayProgViewModel = try! decoder.decode(WatchDayProgram.self, from: ReceivedDayProgVMData)

                                 for (i, exercise) in ReceivedDayProgViewModel.exerciseVM.enumerated() {

                                     DispatchQueue.main.async {
                                         receivedDayProgramVM.exerciseVM.append(WatchExerciseViewModel(exercise: exercise))
                                     }

                             } //Blob for "dayProgramData" code ends

                         } //Blob observation code ends
                    } else {

                TabView(selection: $selectedTab) {

                    WatchControlView().id(0)
                    SetInformationView().id(1)
                    SetRestDetailView().id(2)
                    //Check if WatchControlView can be vertically scrollable
                    NowPlayingView().id(3)
                }
                .environmentObject(receivedDayProgramVM)
            }

        }
    }
}


问:
Process Ajax queue code then continue
So, I'm using JQuery AjaxQueue to do stuff, but the problem I have is that I can't figure out how to make it continue only after the entire queue is done. I want it to look through the table checking if stuff is deleted, then after its finished continue. What's happening now is that the stuff in the queue will be processed at the same time as the stuff around it so it doesn't do the ajax calls before continuing.</p>

```<code>    var outputString = "";
    $('#errors').html("");

    $("#deletingitems tbody tr").each(function() {
        if(rowCounter == 1) {
            htmltext.append(TopofHTMLPage());
        }

        var tableValA = $(this).find("td").eq(0).html();
        var tableValB = $(this).find("td").eq(1).html().split("/")[0];

        $.ajaxQueue({
            type: "POST",
            url: "@Url.Content("~/webservices/retrieve.asmx/Get")",
            data: "{'index': '" + tableValA + "', 'identity': '" + tableValB + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

                //http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/
                if (msg.hasOwnProperty("d")) {
                    // Leave the .d behind and pass the rest of
                    //  the JSON object forward.
                    outputString = msg.d;
                    $('#errors').append(outputString);
                    if(obj.valA != null) {
                        htmltext.append('<tr>');
                        htmltext.append('<td>' + obj.valA + '</td>');
                        htmltext.append('<td>' + obj.valB + '</td>');
                        htmltext.append('<td>' + obj.valC + '</td>');
                        htmltext.append('<td>' + obj.valD + '</td>');
                        htmltext.append('<td>' + obj.valE + '</td>');
                        htmltext.append('</tr>');
                    }
                }
            }
            , error: AjaxFailed
        });

        if(rowCounter == 10) {
            htmltext.append(BottomofHTMLPage());
            rowCounter = 1;
        }
        else {
            rowCounter++;
        }
    });
    // Add rows until 10 rows
    while(rowCounter <= 10) {
        htmltext.append('<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>');
        rowCounter++;
    }

    htmltext.append(BottomofHTMLPage());

    htmltext.append('</body>');
    htmltext.append('</html>');
    var page =  window.open('','NewHTMLPage','width=1500,height=600,scrollbars=yes');
    page.document.open();
    page.document.write(htmltext.toString());
    page.document.close();
</code>```

答:
Ajax is asynchronous (as should be ajaxQueue, otherwise it wouldn't be ajax). That means when you make a request, your code continues while ajax fetches the requested data. Your callbacks will be executed when the data is ready, and that will happen after your main-line code is complete (check out Is JavaScript multithreaded?). So that's why your table rows are appearing after the closing html tags.

To solve your problem, you'll need to pull your closing code into the callback and detect when the last request has completed.

```<code>jQuery(function ($) {
    var i = 0;
    $('tr').each(function () {
        i++;
        $.ajax({
            url: 't.html',
            success: function (data) {
                console.log('serving: ' + i);
                if(--i <= 0) {
                    console.log('which was the last');
                }
            }
        });
    });
});
</code>```

The same should apply to ajaxQueue.

Title: Process Ajax queue code then continue

Body:
So, I'm using JQuery AjaxQueue to do stuff, but the problem I have is that I can't figure out how to make it continue only after the entire queue is done. I want it to look through the table checking if stuff is deleted, then after its finished continue. What's happening now is that the stuff in the queue will be processed at the same time as the stuff around it so it doesn't do the ajax calls before continuing.

    var outputString = "";
    $('#errors').html("");

    $("#deletingitems tbody tr").each(function() {
        if(rowCounter == 1) {
            htmltext.append(TopofHTMLPage());
        }

        var tableValA = $(this).find("td").eq(0).html();
        var tableValB = $(this).find("td").eq(1).html().split("/")[0];

        $.ajaxQueue({
            type: "POST",
            url: "@Url.Content("~/webservices/retrieve.asmx/Get")",
            data: "{'index': '" + tableValA + "', 'identity': '" + tableValB + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {

                //http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/
                if (msg.hasOwnProperty("d")) {
                    // Leave the .d behind and pass the rest of
                    //  the JSON object forward.
                    outputString = msg.d;
                    $('#errors').append(outputString);
                    if(obj.valA != null) {
                        htmltext.append('
');
                        htmltext.append('' + obj.valA + '	');
                        htmltext.append('' + obj.valB + '	');
                        htmltext.append('' + obj.valC + '	');
                        htmltext.append('' + obj.valD + '	');
                        htmltext.append('' + obj.valE + '	');
                        htmltext.append('
');
                    }
                }
            }
            , error: AjaxFailed
        });

        if(rowCounter == 10) {
            htmltext.append(BottomofHTMLPage());
            rowCounter = 1;
        }
        else {
            rowCounter++;
        }
    });
    // Add rows until 10 rows
    while(rowCounter <= 10) {
        htmltext.append('

');
        rowCounter++;
    }

    htmltext.append(BottomofHTMLPage());

    htmltext.append('');
    htmltext.append('');
    var page =  window.open('','NewHTMLPage','width=1500,height=600,scrollbars=yes');
    page.document.open();
    page.document.write(htmltext.toString());
    page.document.close();

Body:
Ajax is asynchronous (as should be ajaxQueue, otherwise it wouldn't be ajax). That means when you make a request, your code continues while ajax fetches the requested data. Your callbacks will be executed when the data is ready, and that will happen after your main-line code is complete (check out Is JavaScript multithreaded?). So that's why your table rows are appearing after the closing html tags.

To solve your problem, you'll need to pull your closing code into the callback and detect when the last request has completed.

jQuery(function ($) {
    var i = 0;
    $('tr').each(function () {
        i++;
        $.ajax({
            url: 't.html',
            success: function (data) {
                console.log('serving: ' + i);
                if(--i <= 0) {
                    console.log('which was the last');
                }
            }
        });
    });
});

The same should apply to ajaxQueue.


问:
Kotlin - Iterate over Class properties
Quick question, let's say we have this code:

```<code>fun main() {
    val instance = Random(1, "B", 3)
    for(__?__) {
        println(__?__)
    }
}

class Random(
    val A: Int,
    val B: String,
    val C: Int,
) {}
</code>```

What should I add in places of __?__ so that the program will print out all properities of instance?

答:
You can do this with reflection:

```<code>class Random(
  val A: Int,
  val B: String,
  val C: Int,
) {}

val instance = Random(1, "B", 3)

for(field in instance::class.java.declaredFields) {
  field.isAccessible = true
  println(field.name + ": " + field.get(instance).toString())
}
</code>```

Output:

```<code>A: 1
B: B
C: 3
</code>```

Title: Kotlin - Iterate over Class properties

Body:
Quick question, let's say we have this code:

fun main() {
    val instance = Random(1, "B", 3)
    for(__?__) {
        println(__?__)
    }
}

class Random(
    val A: Int,
    val B: String,
    val C: Int,
) {}

What should I add in places of __?__ so that the program will print out all properities of instance?

Body:
You can do this with reflection:

class Random(
  val A: Int,
  val B: String,
  val C: Int,
) {}

val instance = Random(1, "B", 3)

for(field in instance::class.java.declaredFields) {
  field.isAccessible = true
  println(field.name + ": " + field.get(instance).toString())
}

Output:

A: 1
B: B
C: 3


问:
javascript - How to start update scroll percentage when element is on the top of viewport
When entering the website, this is the first UI you'll see.

Then, if you scroll down to the very beginning of section B

I expect the section B will become sticky and the currentPercentage state will start increasing from 0% gradually if you scroll.

When the currentPercentage state reach 100%, the sticky effect will no longer apply to sectionB, then you can scroll down to section C or the bottom of the page.

It's kind of like circle-ci homepage

You can try to scroll in this section.

I think there are a few things we need to figure out for the solution

How to make section B become sticky when scroll position arrives section B

How to scroll and increase the percentage when arriving section B

I've tried thinking in both css and javascript way, still cannot find the solution

I've also done lots of research for this problem for a few days but still not figuring it out.

I believe a lots of developers would like to know how to do this kind of effect in their frontend, and it will be beneficial for other developers to have quicker solution to deal with this kind of UX in the future, since from what I've noticed no one has mentioned this kind of UX handling.

I would be appreciated if someone can answer this question with an example, for the reference for other developers.

App.js

```<code>import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";

import ProgressBar from "react-bootstrap/ProgressBar";

import { useState } from "react";

export default function App() {
  const [currentProgress, setCurrentProgress] = useState(100);
  return (
    <div className="App">
      <div className="sectionA">Section A</div>
      <div className="sectionB">
        Section B
        <ProgressBar
          now={currentProgress}
          label={`${currentProgress}%`}
          style={{ marginBottom: "16px" }}
        />
      </div>
      <div className="sectionC">Section C</div>
    </div>
  );
}
</code>```

Codesandbox

https://codesandbox.io/s/mutable-fire-sz19b?file=/src/App.js:0-619

Update 1

I updated the code and can be able to make container B sticky, but dont know how to continue for the UX

App.js

```<code>import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";

import ProgressBar from "react-bootstrap/ProgressBar";

import { useState } from "react";

export default function App() {
  const [currentProgress, setCurrentProgress] = useState(3);
  return (
    <div className="App">
      <div className="sectionA">Section A</div>
      <div style={{ position: "sticky", top: 0 }}>
        <div className="sectionB">
          Section B
          <ProgressBar
            now={currentProgress}
            label={`${currentProgress}%`}
            style={{ marginBottom: "16px" }}
          />
        </div>
        <div className="sectionC">Section C</div>
      </div>
      <div style={{ minHeight: "400vh", maxHeight: "calc(200vh - 466px)" }} />
    </div>
  );
}
</code>```

Codesandbox

https://codesandbox.io/s/elated-hawking-n3rvw?file=/src/App.js:0-778

Update 2

Added library react-scroll-percentage to scroll to update
currentProgress

However, when the whole containerB exposed in the viewport, the currentProgress will start updating, which is not what I want

￼

What I want is when SectionB reach the top of the viewport, the scrolling will make user feel sticky and then currentProgress will start updating from 0%

App.js

```<code>import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
import React, { useState, useEffect } from "react";
import { useScrollPercentage } from "react-scroll-percentage";

import ProgressBar from "react-bootstrap/ProgressBar";

export default function App() {
  const [currentProgress, setCurrentProgress] = useState(0);

  const [ref, percentage] = useScrollPercentage({
    threshold: 1.0
  });
  useEffect(() => {
    setCurrentProgress(percentage * 100);
  }, [percentage]);

  return (
    <div className="App">
      <div className="sectionA">Section A</div>
      <div style={{ position: "sticky", top: 0 }}>
        <div className="sectionB" ref={ref}>
          Section B
          <ProgressBar
            now={currentProgress}
            label={`(${currentProgress})%`}
            style={{ marginBottom: "16px" }}
          />
        </div>
        <div className="sectionC">Section C</div>
      </div>
      <div style={{ minHeight: "400vh", maxHeight: "calc(200vh - 466px)" }} />
    </div>
  );
}
</code>```

Codesandbox

https://codesandbox.io/s/elated-hawking-n3rvw?file=/src/App.js:0-1029

答:
You need to listen to scroll events, check scrollTop of the scrolling element, and decide what the css and currentProgress need to be. This is easiest when the height of each section is known and constant. The outer element also needs a large predetermined height, to leave room for scrolling.

The code might just be

```<code>if (scrollTop > heightofSectionA) {
    //set sectionB css to {position: fixed, top: 0, ...}
    currentProgress = (scrollTop-heightofSectionA)/lengthofSectionB*100
} else {
    //set sectionB css to {position: static}
    currentProgress = 0
}
</code>```

There is a number of ways the html and css could look. With position: sticky you might not need to change css at all. But as long as you know what the css at any stage of the scroll should look like, you should have no problems switching between them.

Body:
When entering the website, this is the first UI you'll see.

Then, if you scroll down to the very beginning of section B

I expect the section B will become sticky and the currentPercentage state will start increasing from 0% gradually if you scroll.

When the currentPercentage state reach 100%, the sticky effect will no longer apply to sectionB, then you can scroll down to section C or the bottom of the page.

It's kind of like circle-ci homepage

You can try to scroll in this section.

I think there are a few things we need to figure out for the solution

How to make section B become sticky when scroll position arrives section B

How to scroll and increase the percentage when arriving section B

I've tried thinking in both css and javascript way, still cannot find the solution

I've also done lots of research for this problem for a few days but still not figuring it out.

I believe a lots of developers would like to know how to do this kind of effect in their frontend, and it will be beneficial for other developers to have quicker solution to deal with this kind of UX in the future, since from what I've noticed no one has mentioned this kind of UX handling.

I would be appreciated if someone can answer this question with an example, for the reference for other developers.

App.js

import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";

import ProgressBar from "react-bootstrap/ProgressBar";

import { useState } from "react";

export default function App() {
  const [currentProgress, setCurrentProgress] = useState(100);
  return (

Section A

        Section B
        <ProgressBar
          now={currentProgress}
          label={`${currentProgress}%`}
          style={{ marginBottom: "16px" }}
        />

Section C

  );
}

Codesandbox

https://codesandbox.io/s/mutable-fire-sz19b?file=/src/App.js:0-619

Update 1

I updated the code and can be able to make container B sticky, but dont know how to continue for the UX

App.js

import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";

import ProgressBar from "react-bootstrap/ProgressBar";

import { useState } from "react";

export default function App() {
  const [currentProgress, setCurrentProgress] = useState(3);
  return (

Section A

          Section B
          <ProgressBar
            now={currentProgress}
            label={`${currentProgress}%`}
            style={{ marginBottom: "16px" }}
          />

Section C

  );
}

Codesandbox

https://codesandbox.io/s/elated-hawking-n3rvw?file=/src/App.js:0-778

Update 2

Added library react-scroll-percentage to scroll to update
currentProgress

However, when the whole containerB exposed in the viewport, the currentProgress will start updating, which is not what I want

￼

What I want is when SectionB reach the top of the viewport, the scrolling will make user feel sticky and then currentProgress will start updating from 0%

App.js

import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
import React, { useState, useEffect } from "react";
import { useScrollPercentage } from "react-scroll-percentage";

import ProgressBar from "react-bootstrap/ProgressBar";

export default function App() {
  const [currentProgress, setCurrentProgress] = useState(0);

  const [ref, percentage] = useScrollPercentage({
    threshold: 1.0
  });
  useEffect(() => {
    setCurrentProgress(percentage * 100);
  }, [percentage]);

  return (

Section A

          Section B
          <ProgressBar
            now={currentProgress}
            label={`(${currentProgress})%`}
            style={{ marginBottom: "16px" }}
          />

Section C

  );
}

Codesandbox

https://codesandbox.io/s/elated-hawking-n3rvw?file=/src/App.js:0-1029

Body:
You need to listen to scroll events, check scrollTop of the scrolling element, and decide what the css and currentProgress need to be. This is easiest when the height of each section is known and constant. The outer element also needs a large predetermined height, to leave room for scrolling.

The code might just be

if (scrollTop > heightofSectionA) {
    //set sectionB css to {position: fixed, top: 0, ...}
    currentProgress = (scrollTop-heightofSectionA)/lengthofSectionB*100
} else {
    //set sectionB css to {position: static}
    currentProgress = 0
}

There is a number of ways the html and css could look. With position: sticky you might not need to change css at all. But as long as you know what the css at any stage of the scroll should look like, you should have no problems switching between them.


问:
Bcrypt installation failed on Linux
First, I tried installing bcrypt with npm.

Error :

```<code>/
> bcrypt@0.8.5 install /home/saaggy18/node-projects/10-projects/node_modules/bcrypt
> node-gyp rebuild

/usr/local/lib/node_modules/npm/bin/node-gyp-bin/node-gyp: 3: /usr/local/lib/node_modules/npm/bin/node-gyp-bin/node-gyp: node: Permission denied
npm ERR! Linux 3.19.0-33-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "bcrypt"
npm ERR! node v4.2.2
npm ERR! npm  v2.14.7
npm ERR! code ELIFECYCLE

npm ERR! bcrypt@0.8.5 install: `node-gyp rebuild`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the bcrypt@0.8.5 install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the bcrypt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls bcrypt
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/saaggy18/node-projects/10-projects/npm-debug.log
</code>```

Then I found this question

On the 3rd step that is, node-gyp configure

It's hitting an error :

```<code>Error: Cannot find module 'nan'
    at Function.Module._resolveFilename (module.js:337:15)
    at Function.Module._load (module.js:287:25)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at [eval]:1:1
    at Object.exports.runInThisContext (vm.js:54:17)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:435:26)
    at node.js:578:27
    at doNTCallback0 (node.js:419:9)
gyp: Call to 'node -e "require('nan')"' returned exit status 1 while in binding.gyp. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/node-gyp/lib/configure.js:305:16)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 3.19.0-33-generic
gyp ERR! command "/usr/local/bin/node" "/usr/local/bin/node-gyp" "configure"
gyp ERR! cwd /home/saaggy18/node.bcrypt.js
gyp ERR! node -v v4.2.2
gyp ERR! node-gyp -v v3.2.0
gyp ERR! not ok
</code>```

My OS : Elementary Os Freya, which is basically Ubuntu and
I have python installed.

答: Change Node version and try to install again.</p>

Title: Bcrypt installation failed on Linux

Body:
First, I tried installing bcrypt with npm.

Error :

/
> bcrypt@0.8.5 install /home/saaggy18/node-projects/10-projects/node_modules/bcrypt
> node-gyp rebuild

/usr/local/lib/node_modules/npm/bin/node-gyp-bin/node-gyp: 3: /usr/local/lib/node_modules/npm/bin/node-gyp-bin/node-gyp: node: Permission denied
npm ERR! Linux 3.19.0-33-generic
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "bcrypt"
npm ERR! node v4.2.2
npm ERR! npm  v2.14.7
npm ERR! code ELIFECYCLE

npm ERR! bcrypt@0.8.5 install: `node-gyp rebuild`
npm ERR! Exit status 126
npm ERR!
npm ERR! Failed at the bcrypt@0.8.5 install script 'node-gyp rebuild'.
npm ERR! This is most likely a problem with the bcrypt package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls bcrypt
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/saaggy18/node-projects/10-projects/npm-debug.log

Then I found this question

On the 3rd step that is, node-gyp configure

It's hitting an error :

Error: Cannot find module 'nan'
    at Function.Module._resolveFilename (module.js:337:15)
    at Function.Module._load (module.js:287:25)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at [eval]:1:1
    at Object.exports.runInThisContext (vm.js:54:17)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:435:26)
    at node.js:578:27
    at doNTCallback0 (node.js:419:9)
gyp: Call to 'node -e "require('nan')"' returned exit status 1 while in binding.gyp. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/local/lib/node_modules/node-gyp/lib/configure.js:305:16)
gyp ERR! stack     at emitTwo (events.js:87:13)
gyp ERR! stack     at ChildProcess.emit (events.js:172:7)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Linux 3.19.0-33-generic
gyp ERR! command "/usr/local/bin/node" "/usr/local/bin/node-gyp" "configure"
gyp ERR! cwd /home/saaggy18/node.bcrypt.js
gyp ERR! node -v v4.2.2
gyp ERR! node-gyp -v v3.2.0
gyp ERR! not ok

My OS : Elementary Os Freya, which is basically Ubuntu and
I have python installed.


问:
Tensorflow-gpu only gives the object detection for the first frame
I have done some code for object detection task. I have done this before a long time ago. But now I want to come back and test the code The model only predict the first frame. This ONLY happen when I use GPU, while CPU is normal

My problem is the same with this question
Why Tensorflow-gpu only gives the object prediction once

Tensorflow 2.8

Python 3.8

Cuda 11.2

GPU RTX2060-m

答: I have solve the problem. By downgrade cuda to 10.1 and use Tensorflow 2.2 instead</p>


问:
React-router <Route> tag not rendering component
I'm running into an issue where my route tag in specific is not rendering any components.

Steps I have tried:

Changed import of { Route } from "react-router-dom".

Changed paths to see if other paths render.

Rendered the component within  tags (this worked).

The issue seems to be coming down to something going on with the  tag.

Here is a copy of my code:

```<code>import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <NavBar />
                <Route path="/" exact component={Login} />
            </BrowserRouter>
        )
    }
}

export default App;
</code>```

The versions are:

```<code>├─┬ react-router-dom@6.2.1
│ └── react-router@6.2.1 deduped
└── react-router@6.2.1
</code>```

I tried changing the tags to  as per a suggestion and it still didn't work, but I may have implemented it incorrectly. Here is what I tried:

```<code>import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter, Routes } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <Routes>
                <NavBar />
                <Route path="/" exact component={Login} />
            </Routes>
        )
    }
}

export default App;
</code>```

The errors I am getting on the console are:

```<code>Uncaught Error: useRoutes() may be used only in the context of a <Router> component.
    Choo 3
    React 17
    Choo 2
    Webpack 3
</code>```
```<code>The above error occurred in the <Routes> component:

Routes@http://localhost:3000/static/js/bundle.js:54433:7
App@http://localhost:3000/static/js/bundle.js:42:1
</code>```

Any help would be greatly appreciated!

Solution:

Was resolved by switching the "component" tag to "element" tag and removing the  tag outside as follows:

```<code>            <>
                <NavBar />
                <Routes>
                    <Route path="/" exact element={<Login />} />
                </Routes>
            </>
</code>```

答:
Try this:</p>
```<code>import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { BrowserRouter, Route, Routes } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <NavBar />
                <Routes>
                   <Route path="/" element={<Login/>} exact/>
                </Routes>
            </BrowserRouter>
        )
    }
}

export default App;
</code>```

Body:
I'm running into an issue where my route tag in specific is not rendering any components.

Steps I have tried:

Changed import of { Route } from "react-router-dom".

Changed paths to see if other paths render.

Rendered the component within  tags (this worked).

The issue seems to be coming down to something going on with the  tag.

Here is a copy of my code:

import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <NavBar />
                <Route path="/" exact component={Login} />
            </BrowserRouter>
        )
    }
}

export default App;

The versions are:

├─┬ react-router-dom@6.2.1
│ └── react-router@6.2.1 deduped
└── react-router@6.2.1

I tried changing the tags to  as per a suggestion and it still didn't work, but I may have implemented it incorrectly. Here is what I tried:

import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { Route } from "react-router";
import { BrowserRouter, Routes } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <Routes>
                <NavBar />
                <Route path="/" exact component={Login} />
            </Routes>
        )
    }
}

export default App;

The errors I am getting on the console are:

Uncaught Error: useRoutes() may be used only in the context of a <Router> component.
    Choo 3
    React 17
    Choo 2
    Webpack 3

The above error occurred in the <Routes> component:

Routes@http://localhost:3000/static/js/bundle.js:54433:7
App@http://localhost:3000/static/js/bundle.js:42:1

Any help would be greatly appreciated!

Solution:

Was resolved by switching the "component" tag to "element" tag and removing the  tag outside as follows:

            <>
                <NavBar />
                <Routes>
                    <Route path="/" exact element={<Login />} />
                </Routes>
            </>

Body:
Try this:

import { Component } from "react";
//import all components rendered
import NavBar from "./Nav";
import Orders from "./Orders";
import Cart from "./Cart";
import Menu from "./Menu";
import Login from "./Login.jsx";
import Home from "./Home.jsx";
// for routing
import { BrowserRouter, Route, Routes } from "react-router-dom";

//main App to combine all components and be rendered
class App extends Component {
    render() {
        return (
            <BrowserRouter>
                <NavBar />
                <Routes>
                   <Route path="/" element={<Login/>} exact/>
                </Routes>
            </BrowserRouter>
        )
    }
}

export default App;


问:
How can I send a Firebase Cloud Messaging notification to iOS device without use the Firebase Console?
If I send notification to iOS device from FCM console I am getting the message alert on notification center (swipe down from the Top of the screen to view Notification Centre).

didRecievedRemoteNotification Output is :

```<code>{

    aps =     {

        alert = "From console";

    };

    "gcm.message_id" = "0:1470206236110595%b2c76869b2c76869";

    "gcm.n.e" = 1;

    "google.c.a.c_id" = 2979094970349938289;

    "google.c.a.e" = 1;

    "google.c.a.ts" = 1470206236;

    "google.c.a.udt" = 0;

}
</code>```

But if send notification to iOS device  I am sending using api from my server I am not receiving message alert on notification center (swipe down from the Top of the screen to view Notification Centre).

didRecievedRemoteNotification Output is :

```<code>{

    "collapse_key" = "do_not_collapse";

    from = 67981113117;

    message = "alert from api";

    time = "03-08-2016 12:44:53";

}
</code>```

My API code is which is in C#:

```<code>string RegIDs = "some id";

                var appID = "some id";

                var SenderID = "some id";
                var value = Text1.Text;
                WebRequest tRequest;

            tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");

                tRequest.Method = "POST";
                tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                tRequest.Headers.Add(string.Format("Authorization: key={0}", appID));

                tRequest.Headers.Add(string.Format("Sender: id={0}", SenderID));

                //Data_Post Format
                // string postData = "{'collapse_key' : 'demo', 'registration_id': [ '" + regId + "' ],
                //'data': {'message': '" + Label1.Text + "'},'time_to_live' : '3' }";

            //json for android
                string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
                   + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + RegIDs + "";

            Console.WriteLine(postData);
                Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                tRequest.ContentLength = byteArray.Length;

                Stream dataStream = tRequest.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                WebResponse tResponse = (WebResponse)tRequest.GetResponse();

                dataStream = tResponse.GetResponseStream();

                StreamReader tReader = new StreamReader(dataStream);

                String sResponseFromServer = tReader.ReadToEnd();

                Label3.Text = sResponseFromServer; //printing response from GCM server.
                tReader.Close();
                dataStream.Close();
                tResponse.Close();
</code>```

答:
Another alternative in order to test push notifications without using Firebase console is using Postman. Attached two images with configuration details.

Image 1: Set notification payload

Image 2: Set request headers ( Content-Type and Authorization )

Firebase push notification endpoint: https://fcm.googleapis.com/fcm/send

Body:
If I send notification to iOS device from FCM console I am getting the message alert on notification center (swipe down from the Top of the screen to view Notification Centre).

didRecievedRemoteNotification Output is :

{

    aps =     {

        alert = "From console";

    };

    "gcm.message_id" = "0:1470206236110595%b2c76869b2c76869";

    "gcm.n.e" = 1;

    "google.c.a.c_id" = 2979094970349938289;

    "google.c.a.e" = 1;

    "google.c.a.ts" = 1470206236;

    "google.c.a.udt" = 0;

}

But if send notification to iOS device  I am sending using api from my server I am not receiving message alert on notification center (swipe down from the Top of the screen to view Notification Centre).

didRecievedRemoteNotification Output is :

{

    "collapse_key" = "do_not_collapse";

    from = 67981113117;

    message = "alert from api";

    time = "03-08-2016 12:44:53";

}

My API code is which is in C#:

string RegIDs = "some id";

                var appID = "some id";

                var SenderID = "some id";
                var value = Text1.Text;
                WebRequest tRequest;

            tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");

                tRequest.Method = "POST";
                tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                tRequest.Headers.Add(string.Format("Authorization: key={0}", appID));

                tRequest.Headers.Add(string.Format("Sender: id={0}", SenderID));

                //Data_Post Format
                // string postData = "{'collapse_key' : 'demo', 'registration_id': [ '" + regId + "' ],
                //'data': {'message': '" + Label1.Text + "'},'time_to_live' : '3' }";

            //json for android
                string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
                   + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + RegIDs + "";

            Console.WriteLine(postData);
                Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                tRequest.ContentLength = byteArray.Length;

                Stream dataStream = tRequest.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();

                WebResponse tResponse = (WebResponse)tRequest.GetResponse();

                dataStream = tResponse.GetResponseStream();

                StreamReader tReader = new StreamReader(dataStream);

                String sResponseFromServer = tReader.ReadToEnd();

                Label3.Text = sResponseFromServer; //printing response from GCM server.
                tReader.Close();
                dataStream.Close();
                tResponse.Close();


问:
How to remove the space under the bottom pill gesture bar Android?
How do I get rid of this tiny black space under the bottom "gesture bar"? Most apps extend all the way to the bottom, but I still see this tiny black bar on the bottom.

Main Activity XML

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="com.myProject.fragments.SignUpFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout="@layout/sign_up_fragment" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
How do I get rid of this tiny black space under the bottom "gesture bar"?

To extend the app to the most bottom, you need to make your app full screen with:

```<code>WindowCompat.setDecorFitsSystemWindows(window, false)
</code>```

But this also draws the app over the top status bar; to avoid that you need to handle overlaps using insets by registering OnApplyWindowInsetsListener:

First give your root layout ConstraintLayout an id, say root:

```<code>val root = findViewById<ConstraintLayout>(R.id.root)
val onApplyWindowInsetsListener =
    OnApplyWindowInsetsListener { view: View, windowInsets: WindowInsetsCompat ->
        val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())

        // Apply the insets as a margin to the root view in order to set the layout drawing area
        view.layoutParams = (view.layoutParams as FrameLayout.LayoutParams).apply {
            topMargin = insets.top // to draw below the top status bar
            leftMargin = insets.left
            rightMargin = insets.right
        }

        // Return CONSUMED if you don't want want the window insets to keep being
        // passed down to descendant views.
        WindowInsetsCompat.CONSUMED
    }
ViewCompat.setOnApplyWindowInsetsListener(root, onApplyWindowInsetsListener)
</code>```

Now you need to hide the bottom navigation bar, and enable showing it whenever the user swipes up from the bottom:

```<code>WindowInsetsControllerCompat(window, window.decorView).apply {
    hide(WindowInsetsCompat.Type.navigationBars())
    systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
</code>```

This is working starting from API level 21.

Body:
How do I get rid of this tiny black space under the bottom "gesture bar"? Most apps extend all the way to the bottom, but I still see this tiny black bar on the bottom.

Main Activity XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activities.MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="com.myProject.fragments.SignUpFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:layout="@layout/sign_up_fragment" />
</androidx.constraintlayout.widget.ConstraintLayout>

Body:
How do I get rid of this tiny black space under the bottom "gesture bar"?

To extend the app to the most bottom, you need to make your app full screen with:

WindowCompat.setDecorFitsSystemWindows(window, false)

But this also draws the app over the top status bar; to avoid that you need to handle overlaps using insets by registering OnApplyWindowInsetsListener:

First give your root layout ConstraintLayout an id, say root:

val root = findViewById<ConstraintLayout>(R.id.root)
val onApplyWindowInsetsListener =
    OnApplyWindowInsetsListener { view: View, windowInsets: WindowInsetsCompat ->
        val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())

        // Apply the insets as a margin to the root view in order to set the layout drawing area
        view.layoutParams = (view.layoutParams as FrameLayout.LayoutParams).apply {
            topMargin = insets.top // to draw below the top status bar
            leftMargin = insets.left
            rightMargin = insets.right
        }

        // Return CONSUMED if you don't want want the window insets to keep being
        // passed down to descendant views.
        WindowInsetsCompat.CONSUMED
    }
ViewCompat.setOnApplyWindowInsetsListener(root, onApplyWindowInsetsListener)

Now you need to hide the bottom navigation bar, and enable showing it whenever the user swipes up from the bottom:

WindowInsetsControllerCompat(window, window.decorView).apply {
    hide(WindowInsetsCompat.Type.navigationBars())
    systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}

This is working starting from API level 21.


问:
Need simple modification for Javascript Cookie notice wordpress plugin
I followed a tutorial to create cookie notice popup for my wordpress site, it works as expected, I'm not good at javascript, so I want after user click on X button and accept cookies, to be automatically redirected to the same page with ?ok=3 query

答:
Although I felt bad that some people instead of helping me fix my issue, they decide to give me negative rate. but I'll share the solution which fix my issue, in case other people facing the same issue, the problem wasn't in finding the JS code to navigate to a web page location.href, the problem was where should I add it in this minifyed code.

Anyways, the solution is:

adding ,location.href = window.location.href+"?ok=3";

after localStorage.setItem(cookieLaw.iId,"1"),

and before }},cookieLaw.show({

so the final code will be:

Maybe the solution was easy, but as I mentioned, I'm good at javascript, specially that the code looks minifyed.

Body:
Although I felt bad that some people instead of helping me fix my issue, they decide to give me negative rate. but I'll share the solution which fix my issue, in case other people facing the same issue, the problem wasn't in finding the JS code to navigate to a web page location.href, the problem was where should I add it in this minifyed code.

Anyways, the solution is:

adding ,location.href = window.location.href+"?ok=3";

after localStorage.setItem(cookieLaw.iId,"1"),

and before }},cookieLaw.show({

so the final code will be:

<script>cookieLaw={dId:"cookie-law-div",bId:"cookie-law-button",iId:"cookie-law-item",show:function(e){if(localStorage.getItem(cookieLaw.iId))return!1;var o=document.createElement("div"),i=document.createElement("p"),t=document.createElement("button");i.innerHTML=e.msg,t.id=cookieLaw.bId,t.innerHTML=e.ok,o.id=cookieLaw.dId,o.appendChild(t),o.appendChild(i),document.body.insertBefore(o,document.body.lastChild),t.addEventListener("click",cookieLaw.hide,!1)},hide:function(){document.getElementById(cookieLaw.dId).outerHTML="",localStorage.setItem(cookieLaw.iId,"1"),location.href = window.location.href+"?ok=3";}},cookieLaw.show({msg:"We use cookies to give you the best possible experience. By continuing to visit our website, you agree to the use of cookies as described in our <a href='#'>Cookie Policy</a>",ok:"x"});</script>

Maybe the solution was easy, but as I mentioned, I'm good at javascript, specially that the code looks minifyed.