问:
How can I fix the error: can't mix packed and unpacked types?
I am trying to build a 4:1 multiplexer using 2:1 multiplexers that I've built. I am getting a few errors whenever I try typing the command vsim mux4_test.

Array connection type 'reg$[1:0]' is incompatible with 'wire[1:0]' for
  port (sel): can't mix packed and unpacked types.

Port size (1) does not match connection size (32) for port 'Z'. The
  port definition is at: NOT.sv(3).

Illegal output or inout port connection for port 'Z'.

And here's my attempt in doing it:

For 2:1 mux:

```<code>module mux2 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic sel,         // Select input
    output logic z           // Output
);

logic w1,w2,w3,w4,w5,w6,w7,w8;
NOT # (.Tpdlh(10), .Tpdhl(8)) g1(.Z(w1) , .A(d0));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g4(.Z(w5), .A(w1), .B(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g2(.Z(w2) , .A(d1));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g5(.Z(w6), .A(w2), .B(w3));
NOT # (.Tpdlh(10), .Tpdhl(8)) g3(.Z(w3) , .A(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g6(.Z(w7) , .A(w5));
NOT # (.Tpdlh(10), .Tpdhl(8)) g7(.Z(w8) , .A(w6));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g8(.Z(z) , .A(w7), .B(w8));

endmodule
</code>```

for 4:1 mux:

```<code>module mux4 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic d2,          // Data input 2
    input logic d3,          // Data input 3
    input logic [1:0] sel,   // Select input
    output logic z           // Output
);

logic w1,w2;

mux2 mux2a(
.d0(d0),
.d1(d1),
.sel(sel[0]),
.z(w1)
);

mux2 mux2b(
.d2(d0),
.d3(d1),
.sel(sel[0]),
.z(w2)
);

mux2 mux2c(
.d0(w1),
.d1(w2),
.sel(sel[1]),
.z(z)
);

endmodule
</code>```

and finally my testbench

```<code>module mux4_test;
logic d0,d1,d2,d3,sel[1:0], z;

mux4 m4a(
.d0(d0),
.d1(d1),
.d2(d2),
.d3(d3),
.sel(sel),
.z(z)
);

initial begin
d0=1'b0;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

#20
d0=1'b1;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

end

endmodule
</code>```

答:
Port size (1) does not match connection size (32) for port 'Z'. The port definition is at: NOT.sv(3).

Could you please share the definition of NOT.sv? It appears your problem is there (I note you are using your own implementation of those gates rather than the verilog primitives).  Looks like you may have a port mismatch between NOT.sv and your 2mux.

Body:
I am trying to build a 4:1 multiplexer using 2:1 multiplexers that I've built. I am getting a few errors whenever I try typing the command vsim mux4_test.

Array connection type 'reg$[1:0]' is incompatible with 'wire[1:0]' for
  port (sel): can't mix packed and unpacked types.

Port size (1) does not match connection size (32) for port 'Z'. The
  port definition is at: NOT.sv(3).

Illegal output or inout port connection for port 'Z'.

And here's my attempt in doing it:

For 2:1 mux:

module mux2 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic sel,         // Select input
    output logic z           // Output
);

logic w1,w2,w3,w4,w5,w6,w7,w8;
NOT # (.Tpdlh(10), .Tpdhl(8)) g1(.Z(w1) , .A(d0));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g4(.Z(w5), .A(w1), .B(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g2(.Z(w2) , .A(d1));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g5(.Z(w6), .A(w2), .B(w3));
NOT # (.Tpdlh(10), .Tpdhl(8)) g3(.Z(w3) , .A(w4));
NOT # (.Tpdlh(10), .Tpdhl(8)) g6(.Z(w7) , .A(w5));
NOT # (.Tpdlh(10), .Tpdhl(8)) g7(.Z(w8) , .A(w6));
OR2 # (.Tpdlh(2), .Tpdhl(6)) g8(.Z(z) , .A(w7), .B(w8));

endmodule

for 4:1 mux:

module mux4 (
    input logic d0,          // Data input 0
    input logic d1,          // Data input 1
    input logic d2,          // Data input 2
    input logic d3,          // Data input 3
    input logic [1:0] sel,   // Select input
    output logic z           // Output
);

logic w1,w2;

mux2 mux2a(
.d0(d0),
.d1(d1),
.sel(sel[0]),
.z(w1)
);

mux2 mux2b(
.d2(d0),
.d3(d1),
.sel(sel[0]),
.z(w2)
);

mux2 mux2c(
.d0(w1),
.d1(w2),
.sel(sel[1]),
.z(z)
);

endmodule

and finally my testbench

module mux4_test;
logic d0,d1,d2,d3,sel[1:0], z;

mux4 m4a(
.d0(d0),
.d1(d1),
.d2(d2),
.d3(d3),
.sel(sel),
.z(z)
);

initial begin
d0=1'b0;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

#20
d0=1'b1;
d1=1'b0;
d2=1'b0;
d3=1'b0;
sel[0]=1'b0;
sel[1]=1'b0;

end

endmodule


来源: stackexchange

问:
How do I link a listview element with Firebase object?
In the main activity, there's a listview which shows all the objects pushed to the database using displayAllItems() method:

```<code>private void displayAllItems(){
        ListView listOfItems = (ListView) findViewById(R.id.list_of_items);
        FirebaseListAdapter<Item> adapter = new FirebaseListAdapter<Item>(this, Item.class, R.id.list_item, FirebaseDatabase.getInstance().getReference()) {
            @Override
            protected void populateView(View v, Item model, int position) {
                TextView type, subtype, name;
                type = v.findViewById(R.id.item_type);
                subtype = v.findViewById(R.id.item_subtype);
                name = v.findViewById(R.id.item_name);

                type.setText(model.getType());
                subtype.setText(model.getSubtype());
                name.setText(model.getName());
            }
        };
        listOfItems.setAdapter((adapter));
    }
</code>```

The listview only shows info from 3 fields of Item class objects. How do I get additional information about an item by clicking on it in listview, so I can use this data in a new activity?

答:
Use setOnItemClickListener to click on each item in the listView:

```<code>listOfItems.setOnItemClickListener(new OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?>adapter,View v, int position){
        Item item = (Item) adapter.getItemAtPosition(position);

        Intent intent = new Intent(CurrentActivity.this, NewActivity.class);
        intent.putExtra("type",item.getType());
        startActivity(intent);
    }
});
</code>```

getItemAtPosition() will get data associated with the specified position in the list. Then use the getters of your class to get the data and send it to the next activity using intent

ContentLicense: CC BY-SA 4.0

Body:
In the main activity, there's a listview which shows all the objects pushed to the database using displayAllItems() method:

private void displayAllItems(){
        ListView listOfItems = (ListView) findViewById(R.id.list_of_items);
        FirebaseListAdapter<Item> adapter = new FirebaseListAdapter<Item>(this, Item.class, R.id.list_item, FirebaseDatabase.getInstance().getReference()) {
            @Override
            protected void populateView(View v, Item model, int position) {
                TextView type, subtype, name;
                type = v.findViewById(R.id.item_type);
                subtype = v.findViewById(R.id.item_subtype);
                name = v.findViewById(R.id.item_name);

                type.setText(model.getType());
                subtype.setText(model.getSubtype());
                name.setText(model.getName());
            }
        };
        listOfItems.setAdapter((adapter));
    }

The listview only shows info from 3 fields of Item class objects. How do I get additional information about an item by clicking on it in listview, so I can use this data in a new activity?

Body:
Use setOnItemClickListener to click on each item in the listView:

listOfItems.setOnItemClickListener(new OnItemClickListener(){
    @Override
    public void onItemClick(AdapterView<?>adapter,View v, int position){
        Item item = (Item) adapter.getItemAtPosition(position);

        Intent intent = new Intent(CurrentActivity.this, NewActivity.class);
        intent.putExtra("type",item.getType());
        startActivity(intent);
    }
});

getItemAtPosition() will get data associated with the specified position in the list. Then use the getters of your class to get the data and send it to the next activity using intent


问:
How to read uptill a particular character in a file, without going through the file, character by character?
Want to detect the '\n' without going through each and every character of a text file. Any hints?</p>

答:
How about getline(...) from Iostream?

http://www.cplusplus.com/reference/iostream/istream/getline/

ContentLicense: CC BY-SA 3.0


问:
How to list all directories and files inside docker container?
Following is my dockerfile:

```<code>FROM python:3.6.5-windowsservercore
COPY . /app
WORKDIR /app
RUN pip download -r requirements.txt -d packages
</code>```

To get list of files in the image, I have tried both the following options, but there is error:

```<code>encountered an error during CreateProcess: failure in a Windows system call:
The system cannot find the file specified. (0x2) extra info:
{"CommandLine":"dir","WorkingDirectory":"C:\\app"......
</code>```

Run docker run -it <container_id> dir

Modify the dockerfile and add CMD at end of dockerfile - CMD ["dir"], then run docker run <container_id> dir

How to list all directories and files inside docker?

答:
In your Dockerfile add the below command:

```<code>FROM python:3.6.5-windowsservercore
COPY . /app
WORKDIR /app
RUN dir #Added
RUN pip download -r requirements.txt -d packages
</code>```

Body:
Following is my dockerfile:

FROM python:3.6.5-windowsservercore
COPY . /app
WORKDIR /app
RUN pip download -r requirements.txt -d packages

To get list of files in the image, I have tried both the following options, but there is error:

encountered an error during CreateProcess: failure in a Windows system call:
The system cannot find the file specified. (0x2) extra info:
{"CommandLine":"dir","WorkingDirectory":"C:\\app"......

Run docker run -it <container_id> dir

Modify the dockerfile and add CMD at end of dockerfile - CMD ["dir"], then run docker run <container_id> dir

How to list all directories and files inside docker?

Body:
In your Dockerfile add the below command:

FROM python:3.6.5-windowsservercore
COPY . /app
WORKDIR /app
RUN dir #Added
RUN pip download -r requirements.txt -d packages


问:
MongoDB ObjectID query update
Hey guys i need to write a mongodb query to update a document i,e need to increment a field in docuemnt by 1, so for that i am using $inc operation but i am facing trouble in matching the document's key with the data sent by frontend

my db looks like this

```<code>_id:ObjectID("5ed4a86126663308549f816b")
title:svsbsbsssf
description:wdwwdwd
category:Object
     _id:ObjectID("5ebc1144dde4f2974e209526")
     label:World after Covid
     category_id:1
     url:world-after-covid
     image:https://*****/assets/category-1590699874832.jpg
     value:1
</code>```

so this category is an Object and i am getting my category id from frontend, after converting that to ObjectID, i tried to match it like

```<code>let doc = await req.db
      .collection("webinars")
      .updateOne({category._id: categoryID }, { $inc: { listingViews: 1 } });
</code>```

but the filter inside updateOne gives me error somehow the syntax isnt correct i guess

the error is like

Unexpected token, expected "," (17:26)

15 |     let doc = await req.db   16 |       .collection("webinars")

17 |       .updateOne({category._id: categoryID }, { $inc: { listingViews: 1 } });

答:
There is a syntax error in the updateOne filter object, the nested field path i.e category._id should be a string, something like this

```<code> // Notice the quotes around category._id
 .updateOne({ "category._id": categoryID }, { $inc: { listingViews: 1 } });
</code>```

Title: MongoDB ObjectID query update

Body:
Hey guys i need to write a mongodb query to update a document i,e need to increment a field in docuemnt by 1, so for that i am using $inc operation but i am facing trouble in matching the document's key with the data sent by frontend

my db looks like this

_id:ObjectID("5ed4a86126663308549f816b")
title:svsbsbsssf
description:wdwwdwd
category:Object
     _id:ObjectID("5ebc1144dde4f2974e209526")
     label:World after Covid
     category_id:1
     url:world-after-covid
     image:https://*****/assets/category-1590699874832.jpg
     value:1

so this category is an Object and i am getting my category id from frontend, after converting that to ObjectID, i tried to match it like

let doc = await req.db
      .collection("webinars")
      .updateOne({category._id: categoryID }, { $inc: { listingViews: 1 } });

but the filter inside updateOne gives me error somehow the syntax isnt correct i guess

the error is like

Unexpected token, expected "," (17:26)

15 |     let doc = await req.db   16 |       .collection("webinars")

17 |       .updateOne({category._id: categoryID }, { $inc: { listingViews: 1 } });

Body:
There is a syntax error in the updateOne filter object, the nested field path i.e category._id should be a string, something like this

 // Notice the quotes around category._id
 .updateOne({ "category._id": categoryID }, { $inc: { listingViews: 1 } });


问:
Removing key/value pairs in list of dictionary having None Values
inputs : [{'test1': 'test', 'test2': None}]

Exected output : [{'test1': 'test'}]

答:
This should do the job</p>

```<code>myDict = {key:val for key,val in myDict.items() if val != None}
</code>```

Body:
This should do the job

myDict = {key:val for key,val in myDict.items() if val != None}


问:
Can I control the location of .NET user settings to avoid losing settings on application upgrade?
I'm trying to customize the location of the user.config file. Currently it's stored with a hash and version number

```<code>%AppData%\[CompanyName]\[ExeName]_Url_[some_hash]\[Version]\
</code>```

I want to it be agnostic to the version of the application

```<code>%AppData%\[CompanyName]\[ProductName]\
</code>```

Can this be done and how? What are the implications? Will the user lose their settings from the previous version after upgrading?

答:
The user.config file is stored at

C:\Documents and Settings>\<username>\[Local Settings\]Application Data\<companyname>\<appdomainname>_<eid>_<hash>\<version>

<C:\Documents and Settings> is the user data directory, either non-roaming (Local Settings above) or roaming.

<username> is the user name.

<companyname> is the CompanyNameAttribute value, if available. Otherwise, ignore this element.

<appdomainname> is the AppDomain.CurrentDomain.FriendlyName. This usually defaults to the .exe name.

<eid> is the URL, StrongName, or Path, based on the evidence available to hash.

<hash> is a SHA1 hash of evidence gathered from the CurrentDomain, in the following order of preference:

1. StrongName

2. URL:

If neither of these is available, use the .exe path.

<version> is the AssemblyInfo's AssemblyVersionAttribute setting.

Full description is here http://msdn.microsoft.com/en-us/library/ms379611.aspx

OwnerDisplayName: Muxa

Body:
I'm trying to customize the location of the user.config file. Currently it's stored with a hash and version number

%AppData%\[CompanyName]\[ExeName]_Url_[some_hash]\[Version]\

I want to it be agnostic to the version of the application

%AppData%\[CompanyName]\[ProductName]\

Can this be done and how? What are the implications? Will the user lose their settings from the previous version after upgrading?

LastEditorDisplayName: Muxa

OwnerDisplayName: Amr


问:
Invalid access token (Zoom API)
I am trying to create a meeting on behalf of the logged in, authenticated user.

I've successfully created a user with Devise and Omniauth:

user.rb

```<code>def self.from_omniauth(auth)
      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.email = auth.info.email
        user.name = auth.info.name
        user.phonenumber = auth.info.phone_number
        user.picurl = auth.info.pic_url
        user.timezone = auth.info.timezone
        user.password = Devise.friendly_token[0,20]
        user.refresh_token = auth.credentials.refresh_token
        user.access_token = auth.credentials.token
      end
  end
</code>```

However, when making the request, I'm consistently getting HTTPUnauthorized 401: {\"code\":124,\"message\":\"Invalid access token.\"}"

Here's my controller:

```<code>def create
require 'uri'
    require 'net/http'
    require 'openssl'
    url = URI("https://api.zoom.us/v2/users/me/meetings")
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    request = Net::HTTP::Post.new(url)
    request["content-type"] = 'application/json'
    request["authorization"] = 'Bearer ' + current_user.access_token

    response = http.request(request)
    puts response.read_body
end
</code>```

答:
the problem is simple you just have to change the userid, use your username appears in zoom profile page as sign-in email instead of me in the uri.
your current url : "https://api.zoom.us/v2/users/me/meetings"
change with this : "https://api.zoom.us/v2/users/your_email/meetings".
once you change this just make sure you'vr been created token not expired or create it again after doing this changes and make it valid for atleast 1 day to test and then you can set its expiry custom.

Title: Invalid access token (Zoom API)

Body:
I am trying to create a meeting on behalf of the logged in, authenticated user.

I've successfully created a user with Devise and Omniauth:

user.rb

def self.from_omniauth(auth)
      where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
        user.provider = auth.provider
        user.uid = auth.uid
        user.email = auth.info.email
        user.name = auth.info.name
        user.phonenumber = auth.info.phone_number
        user.picurl = auth.info.pic_url
        user.timezone = auth.info.timezone
        user.password = Devise.friendly_token[0,20]
        user.refresh_token = auth.credentials.refresh_token
        user.access_token = auth.credentials.token
      end
  end

However, when making the request, I'm consistently getting HTTPUnauthorized 401: {\"code\":124,\"message\":\"Invalid access token.\"}"

Here's my controller:

def create
require 'uri'
    require 'net/http'
    require 'openssl'
    url = URI("https://api.zoom.us/v2/users/me/meetings")
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    request = Net::HTTP::Post.new(url)
    request["content-type"] = 'application/json'
    request["authorization"] = 'Bearer ' + current_user.access_token

    response = http.request(request)
    puts response.read_body
end


问:
Question about the difference between Integer triple pointer and float triple pointer
I'm doing a project for school and they force us to use a type float triple pointer in a function that multiply two matrices,
and for the last day i can't figure out why when I'm using int triple pointer I get the numbers needed but when I'm using float I get zeros.
I wrote something simple just for example for the problem.
Thank you !!

```<code>    int ***ptr3;
    int Matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
    int i;

    ptr3 = malloc(sizeof(int));
    ptr3 = Matrix;
    for (i = 0; i < 9; i++) {printf_s("%d ", ptr3[i]);}

    printf_s("\n");

    float ***ptr3_f;
    float Matrix_f[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    ptr3_f = malloc(sizeof(float));
    ptr3_f = Matrix_f;
    for (i = 0; i < 9; i++) {printf_s("%.1f ", ptr3_f[i]);}

</code>```

enter image description here

答:
There is a whole lot of misconceptions here and your teacher does unfortunately not seem to know C very well. You simply can't use a type*** and it doesn't make any sense to use either.

A pointer of the type type*** cannot point at a 3D array of type. Nor can it point at a 2D array. It cannot point at any array type at all.

Sometimes when using dynamic memory allocation, we allocate an array of type*, each pointing at the first item in an array. A type** can then be used to point at the first type* element, to emulate the syntax of a 2D array with [i][j] access.

This does however not magically make the array of type* an array type[] at the same time. Nor does it magically make type** an array type[][]. If someone taught you that, they are confused.

Most of the time, we should not use type** to emulate a 2D array in the first place, because doing so is horribly inefficient. See Correctly allocating multi-dimensional arrays.

Thus when you attempt ptr3 = Matrix;, you get a C language constraint violation error by the compiler. Some lax compilers "only" give you a warning, but that doesn't make the code valid C. The type*** cannot be used to point at a 3D array, period.

If you somehow got the correct output in some scenario, that's by luck, since the behavior of your code isn't well-defined. On some system, int happened to have the same size as the pointer or such.

ptr3 = malloc(sizeof(int)); ptr3 = ... is senseless, since all that you achieve with the malloc is a memory leak. Because the first thing you do is to overwrite the pointer address to the data you just allocated. I'm not sure why you want to allocate a single int to begin with.

Getting rid of all misconceptions, you can perhaps salvage the program in the following manner:

```<code>#include <stdio.h>
#include <stdlib.h>

int main (void)
{

  int (*iptr)[3];
  int imatrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

  iptr = imatrix;
  for (int i=0; i<3; i++)
  {
    for (int j=0; j<3; j++)
    {
      printf_s("%d ", iptr[i][j]);
    }
    printf("\n");
  }

  printf("\n");

  float (*fptr)[3];
  float fmatrix [3][3] = { {1.0f,2.0f,3.0f},{4.0f,5.0f,6.0f},{7.0f,8.0f,9.0f} };

  fptr = fmatrix;
  for (int i=0; i<3; i++)
  {
    for (int j=0; j<3; j++)
    {
      printf_s("%.1f ", fptr[i][j]);
    }
    printf("\n");
  }
}
</code>```

Body:
I'm doing a project for school and they force us to use a type float triple pointer in a function that multiply two matrices,
and for the last day i can't figure out why when I'm using int triple pointer I get the numbers needed but when I'm using float I get zeros.
I wrote something simple just for example for the problem.
Thank you !!

    int ***ptr3;
    int Matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
    int i;

    ptr3 = malloc(sizeof(int));
    ptr3 = Matrix;
    for (i = 0; i < 9; i++) {printf_s("%d ", ptr3[i]);}

    printf_s("\n");

    float ***ptr3_f;
    float Matrix_f[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    ptr3_f = malloc(sizeof(float));
    ptr3_f = Matrix_f;
    for (i = 0; i < 9; i++) {printf_s("%.1f ", ptr3_f[i]);}

enter image description here

Body:
There is a whole lot of misconceptions here and your teacher does unfortunately not seem to know C very well. You simply can't use a type*** and it doesn't make any sense to use either.

A pointer of the type type*** cannot point at a 3D array of type. Nor can it point at a 2D array. It cannot point at any array type at all.

Sometimes when using dynamic memory allocation, we allocate an array of type*, each pointing at the first item in an array. A type** can then be used to point at the first type* element, to emulate the syntax of a 2D array with [i][j] access.

This does however not magically make the array of type* an array type[] at the same time. Nor does it magically make type** an array type[][]. If someone taught you that, they are confused.

Most of the time, we should not use type** to emulate a 2D array in the first place, because doing so is horribly inefficient. See Correctly allocating multi-dimensional arrays.

Thus when you attempt ptr3 = Matrix;, you get a C language constraint violation error by the compiler. Some lax compilers "only" give you a warning, but that doesn't make the code valid C. The type*** cannot be used to point at a 3D array, period.

If you somehow got the correct output in some scenario, that's by luck, since the behavior of your code isn't well-defined. On some system, int happened to have the same size as the pointer or such.

ptr3 = malloc(sizeof(int)); ptr3 = ... is senseless, since all that you achieve with the malloc is a memory leak. Because the first thing you do is to overwrite the pointer address to the data you just allocated. I'm not sure why you want to allocate a single int to begin with.

Getting rid of all misconceptions, you can perhaps salvage the program in the following manner:

#include <stdio.h>
#include <stdlib.h>

int main (void)
{

  int (*iptr)[3];
  int imatrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

  iptr = imatrix;
  for (int i=0; i<3; i++)
  {
    for (int j=0; j<3; j++)
    {
      printf_s("%d ", iptr[i][j]);
    }
    printf("\n");
  }

  printf("\n");

  float (*fptr)[3];
  float fmatrix [3][3] = { {1.0f,2.0f,3.0f},{4.0f,5.0f,6.0f},{7.0f,8.0f,9.0f} };

  fptr = fmatrix;
  for (int i=0; i<3; i++)
  {
    for (int j=0; j<3; j++)
    {
      printf_s("%.1f ", fptr[i][j]);
    }
    printf("\n");
  }
}


问:
Java char to bytes and back is converted wrongly (UTF-8)
While programming I encountered a weird behavior of Strings that are converted to bytes and then back to Strings again. Some chars are converted wrongly, and therefore the hashCode of the String is also changed. The length of the Strings remain the same.
The problem seems to occur with chars from 55296 - 57343 (U+D800 to U+DFFF). Other chars work fine. Is it because they are surrogates?

String string = new String(new char[] { 56000 });
System.out.println((int)string.charAt(0));
System.out.println((int)new String(string.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8).charAt(0));
```

<p>The console output is:</p>

<pre class="lang-java prettyprint-override"><code>56000
63
</code>```

What is going on here? Is this a java bug, or am I misunderstanding something?

答:
That's because these values are not characters but surrogates. Two of these values form a surrogate pair that in turn represents one character. If you have just one low or high surrogate value this is an invalid encoding and not a character.

Since this is an invalid encoding, it is replaced by a "?" character when you convert it to UTF-8.

You can read more about it for example here https://en.wikipedia.org/wiki/UTF-16

Body:
While programming I encountered a weird behavior of Strings that are converted to bytes and then back to Strings again. Some chars are converted wrongly, and therefore the hashCode of the String is also changed. The length of the Strings remain the same.
The problem seems to occur with chars from 55296 - 57343 (U+D800 to U+DFFF). Other chars work fine. Is it because they are surrogates?

String string = new String(new char[] { 56000 });
System.out.println((int)string.charAt(0));
System.out.println((int)new String(string.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8).charAt(0));

The console output is:

56000
63

What is going on here? Is this a java bug, or am I misunderstanding something?


问:
Why can the compiler not optimize floating point addition with 0?
I have four identity functions which do essentially nothing. Only multiplication with 1 could be optimized by clang to a single ret statement.

float id0(float x) {
    return x + 1 - 1;
}

float id1(float x) {
    return x + 0;
}

float id2(float x) {
    return x * 2 / 2;
}

float id3(float x) {
    return x * 1;
}
```

<p>And the following compiler output is: (clang 10, at -O3)</p>

```.LCPI0_0:
        .long   1065353216              # float 1
.LCPI0_1:
        .long   3212836864              # float -1
id0(float):                                # @id0(float)
        addss   xmm0, dword ptr [rip + .LCPI0_0]
        addss   xmm0, dword ptr [rip + .LCPI0_1]
        ret
id1(float):                                # @id1(float)
        xorps   xmm1, xmm1
        addss   xmm0, xmm1
        ret
.LCPI2_0:
        .long   1056964608              # float 0.5
id2(float):                                # @id2(float)
        addss   xmm0, xmm0
        mulss   xmm0, dword ptr [rip + .LCPI2_0]
        ret
id3(float):                                # @id3(float)
        ret
```

I can understand why id0 and id2 can't be optimized. They increase the value which could then turn into positive infinity and the second operation would not change it back.

But why can't id1 be optimized? Additon with infinity would yield infinity, addition with any regular number would yield that number and addition with NaN would yield NaN. So why is it not a "true" identity operation like * 1.

Example with Compiler Explorer

答:
"I have four identity functions which do essentially nothing."

That's not true.

For floating-point numbers x + 1 - 1 is not equal x + 0, it is equal (x + 1) - 1. So if you have e.g. a very small x then you will lose that very small portion in the x + 1 step, and the compiler can't know if that was your intent or not.

And in the case of x * 2 / 2, the x * 2 might not be exact either, due to floating-point precision, so you have a similar case here, the compiler does not know if you for some reason want to change the value of x in that manner.

So these would be equal:

```<code>float id0(float x) {
    return x + (1. - 1.);
}

float id1(float x) {
    return x + 0;
}
</code>```

And these would be equal:

```<code>float id2(float x) {
    return x * (2. / 2.);
}

float id3(float x) {
    return x * 1;
}
</code>```

The desired behavior could for sure be defined in another way. But as already mentioned by Nelfeal this optimization has to be explicitly activated using -ffast-math

Enable fast-math mode. This option lets the compiler make aggressive, potentially-lossy assumptions about floating-point math. These include:

Floating-point math obeys regular algebraic rules for real numbers (e.g. + and * are associative, x/y == x * (1/y), and (a + b) * c == a * c + b * c),

Operands to floating-point operations are not equal to NaN and Inf, and

+0 and -0 are interchangeable.

fast-math is for clang and gcc a collection of flags (here the one listed by clang):

-fno-honor-infinities

-fno-honor-nans

-fno-math-errno

-ffinite-math

-fassociative-math

-freciprocal-math

-fno-signed-zeros

-fno-trapping-math

-ffp-contract=fast

Body:
I have four identity functions which do essentially nothing. Only multiplication with 1 could be optimized by clang to a single ret statement.

float id0(float x) {
    return x + 1 - 1;
}

float id1(float x) {
    return x + 0;
}

float id2(float x) {
    return x * 2 / 2;
}

float id3(float x) {
    return x * 1;
}

And the following compiler output is: (clang 10, at -O3)

.LCPI0_0:
        .long   1065353216              # float 1
.LCPI0_1:
        .long   3212836864              # float -1
id0(float):                                # @id0(float)
        addss   xmm0, dword ptr [rip + .LCPI0_0]
        addss   xmm0, dword ptr [rip + .LCPI0_1]
        ret
id1(float):                                # @id1(float)
        xorps   xmm1, xmm1
        addss   xmm0, xmm1
        ret
.LCPI2_0:
        .long   1056964608              # float 0.5
id2(float):                                # @id2(float)
        addss   xmm0, xmm0
        mulss   xmm0, dword ptr [rip + .LCPI2_0]
        ret
id3(float):                                # @id3(float)
        ret

I can understand why id0 and id2 can't be optimized. They increase the value which could then turn into positive infinity and the second operation would not change it back.

But why can't id1 be optimized? Additon with infinity would yield infinity, addition with any regular number would yield that number and addition with NaN would yield NaN. So why is it not a "true" identity operation like * 1.

Example with Compiler Explorer

Body:
"I have four identity functions which do essentially nothing."

That's not true.

For floating-point numbers x + 1 - 1 is not equal x + 0, it is equal (x + 1) - 1. So if you have e.g. a very small x then you will lose that very small portion in the x + 1 step, and the compiler can't know if that was your intent or not.

And in the case of x * 2 / 2, the x * 2 might not be exact either, due to floating-point precision, so you have a similar case here, the compiler does not know if you for some reason want to change the value of x in that manner.

So these would be equal:

float id0(float x) {
    return x + (1. - 1.);
}

float id1(float x) {
    return x + 0;
}

And these would be equal:

float id2(float x) {
    return x * (2. / 2.);
}

float id3(float x) {
    return x * 1;
}

The desired behavior could for sure be defined in another way. But as already mentioned by Nelfeal this optimization has to be explicitly activated using -ffast-math

Enable fast-math mode. This option lets the compiler make aggressive, potentially-lossy assumptions about floating-point math. These include:

Floating-point math obeys regular algebraic rules for real numbers (e.g. + and * are associative, x/y == x * (1/y), and (a + b) * c == a * c + b * c),

Operands to floating-point operations are not equal to NaN and Inf, and

+0 and -0 are interchangeable.

fast-math is for clang and gcc a collection of flags (here the one listed by clang):

-fno-honor-infinities

-fno-honor-nans

-fno-math-errno

-ffinite-math

-fassociative-math

-freciprocal-math

-fno-signed-zeros

-fno-trapping-math

-ffp-contract=fast


问:
Angular 8 drop down selected option not showing, how come?
This question has been asked frequently. My situation is apparently different from all the others as I can't find a solution for it from the existing answers.

I have this code:

```<code><form (ngSubmit)="getExceptions(f)" #f="ngForm">
          <div class="row">
            <div class="form-group col-xs-3 col-sm-3">
              <label class="col-form-label" for="aantal">Aantal meldingen per pagina?</label>
              <select name="selectedQuantity" id="aantal" class="form-control" ngModel>
                <option *ngFor="let option of options" [value]="option">{{option}}</option>

              </select>
            </div>
.
.
.
</form>
</code>```

options is defined as:

```<code>private options: string[] = ['10', '20', '50'];
</code>```

I would like to show "10" as the default selected value but whatever I do the drop down keeps showing a blank for the selected value. Clicking the drop down shows the values 10, 20 and 30. So it is filled properly.

What did I try:

```<code><option *ngFor="let option of options" [value]="option" [selected]="option==10">{{option}}
</option>
</code>```

and

```<code><option [value]="10" [selected]="true == true">10</option>
<option [value]="20">20</option>
<option [value]="50">50</option>
</code>```

and

```<code><option [value]="10" selected>10</option>
<option [value]="20">20</option>
<option [value]="50">50</option>
</code>```

It has something to do with the binding because if I remove the 'ngModel' from the select tag it shows the value I want to use as the default value (10). Sort of. I can't read the selected value anymore but the default value is showing.

I have never done anything with plunkr but will try to get an example working there and then paste a link to that in here.

答:
If you are doing model binding, just the option like that your model:

```<code>    export class MyModel
    {
       public field1: number = 0;
    }
</code>```

    <select [(ngModel)]="myModel.field1">
      <option value="" > your value 1 < /option >
      <option value="">your value 2</option>
    </select>
```

So the trick is that you need to set the default value in your model which is zero set in the field1 in above model and will set the value1 as selected option

Body:
This question has been asked frequently. My situation is apparently different from all the others as I can't find a solution for it from the existing answers.

I have this code:

<form (ngSubmit)="getExceptions(f)" #f="ngForm">

              Aantal meldingen per pagina?
              <select name="selectedQuantity" id="aantal" class="form-control" ngModel>
                <option *ngFor="let option of options" [value]="option">{{option}}</option>

              </select>

.
.
.
</form>

options is defined as:

private options: string[] = ['10', '20', '50'];

I would like to show "10" as the default selected value but whatever I do the drop down keeps showing a blank for the selected value. Clicking the drop down shows the values 10, 20 and 30. So it is filled properly.

What did I try:

<option *ngFor="let option of options" [value]="option" [selected]="option==10">{{option}}
</option>

and

<option [value]="10" [selected]="true == true">10</option>
<option [value]="20">20</option>
<option [value]="50">50</option>

and

<option [value]="10" selected>10</option>
<option [value]="20">20</option>
<option [value]="50">50</option>

It has something to do with the binding because if I remove the 'ngModel' from the select tag it shows the value I want to use as the default value (10). Sort of. I can't read the selected value anymore but the default value is showing.

I have never done anything with plunkr but will try to get an example working there and then paste a link to that in here.

Body:
If you are doing model binding, just the option like that your model:

    export class MyModel
    {
       public field1: number = 0;
    }

    <select [(ngModel)]="myModel.field1">
      <option value="" > your value 1 < /option >
      <option value="">your value 2</option>
    </select>

So the trick is that you need to set the default value in your model which is zero set in the field1 in above model and will set the value1 as selected option


问:
Making a child process with redirected standard input/output to a pipe
I am trying to create a child process with redirected stdin/stdout.
I am creating a pipe to redirect  the stdin and write the stdout to a file.

Here is what I have tried

#include <Windows.h>
#include <iostream>

int main()
{
    STARTUPINFOA sInfo;
    PROCESS_INFORMATION pInfo;
    SECURITY_ATTRIBUTES sAttr;
    ZeroMemory(&sInfo, sizeof(sInfo));
    ZeroMemory(&pInfo, sizeof(pInfo));
    ZeroMemory(&sAttr, sizeof(sAttr));
    sInfo.cb = sizeof(sInfo);
    sAttr.bInheritHandle = true;
    HANDLE fileTest = CreateFileA("hello.txt", GENERIC_READ | GENERIC_WRITE, 0, &sAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    HANDLE stdinPipe = CreateNamedPipeA("\\\\.\\pipe\\DokiDokiIn", PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 1024, 1024, NMPWAIT_USE_DEFAULT_WAIT, &sAttr);
    sInfo.hStdInput = stdinPipe;
    sInfo.hStdOutput = fileTest;
    sInfo.hStdError = fileTest;
    sInfo.dwFlags |= STARTF_USESTDHANDLES;
    char cmdLine[] = "cmd.exe";
    bool success = CreateProcessA("C:\\WINDOWS\\system32\\cmd.exe", NULL, &sAttr, NULL, NULL, NULL, NULL, NULL, &sInfo, &pInfo);
    if (!success) {
        std::cout << "CreateProcessA() failed with error " << GetLastError() << "\n";
    }
    std::cout << GetLastError() << "\n";
    return 0;
}
```

This doesn't seem to be working, whenever I specify STARTF_USESTDHANDLES as dwFlags the opened process instantly closes (or doesn't open at all, not sure). It works when I don't specify flags but I/O aren't redirected.
Also, as expected writing to it using my pipe client doesn't work, it can't get a handle to that pipe.
CreateFile is always true and the handle values seem valid, GetLastError() returns 0 but the program just exits and there is no popup with a child process, and even if it was running in the background I cannot write to it.

答:
Based on your represented code, two issues are found:

Set bInheritHandles parameter of CreateProcessA to TRUE instead of NULL to make each inheritable handle in the calling process is inherited by the new process (here is cmd.exe).

cmd.exe shows version information after launched and exits. You can set command line for cmd.exe to make it running continuously if you want to prevent it from exiting.

A tip:

Call GetLastError() immediately after the function fails otherwise the error code may be set to zero by other functions.

The following is an example work for me. You can have a try.

```<code>int main()
{
    STARTUPINFOA sInfo;
    PROCESS_INFORMATION pInfo;
    SECURITY_ATTRIBUTES sAttr;
    ZeroMemory(&sInfo, sizeof(sInfo));
    ZeroMemory(&pInfo, sizeof(pInfo));
    ZeroMemory(&sAttr, sizeof(sAttr));
    sInfo.cb = sizeof(sInfo);
    sAttr.bInheritHandle = true;
    HANDLE fileTest = CreateFileA("hello.txt", GENERIC_READ | GENERIC_WRITE, 0, &sAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    HANDLE stdinPipe = CreateNamedPipeA("\\\\.\\pipe\\DokiDokiIn", PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 1024, 1024, NMPWAIT_USE_DEFAULT_WAIT, &sAttr);
    sInfo.hStdInput = stdinPipe;
    sInfo.hStdOutput = fileTest;
    sInfo.hStdError = fileTest;
    sInfo.dwFlags |= STARTF_USESTDHANDLES;

    char input[] = "ping www.google.com -t";
    char cmd[] = "cmd.exe";
    // initialize cmd
    char cmdline[MAX_PATH];
    sprintf_s(cmdline, sizeof(cmdline), "%s /c %s", cmd, input);
    bool success = CreateProcessA("C:\\WINDOWS\\system32\\cmd.exe", cmdline, &sAttr, NULL, TRUE, NULL, NULL, NULL, &sInfo, &pInfo);
    if (!success) {
        DWORD errCode = GetLastError();
        std::cout << "CreateProcessA() failed with error " << errCode << "\n";
    }

    return 0;
}
</code>```

Body:
I am trying to create a child process with redirected stdin/stdout.
I am creating a pipe to redirect  the stdin and write the stdout to a file.

Here is what I have tried

#include <Windows.h>
#include <iostream>

int main()
{
    STARTUPINFOA sInfo;
    PROCESS_INFORMATION pInfo;
    SECURITY_ATTRIBUTES sAttr;
    ZeroMemory(&sInfo, sizeof(sInfo));
    ZeroMemory(&pInfo, sizeof(pInfo));
    ZeroMemory(&sAttr, sizeof(sAttr));
    sInfo.cb = sizeof(sInfo);
    sAttr.bInheritHandle = true;
    HANDLE fileTest = CreateFileA("hello.txt", GENERIC_READ | GENERIC_WRITE, 0, &sAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    HANDLE stdinPipe = CreateNamedPipeA("\\\\.\\pipe\\DokiDokiIn", PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 1024, 1024, NMPWAIT_USE_DEFAULT_WAIT, &sAttr);
    sInfo.hStdInput = stdinPipe;
    sInfo.hStdOutput = fileTest;
    sInfo.hStdError = fileTest;
    sInfo.dwFlags |= STARTF_USESTDHANDLES;
    char cmdLine[] = "cmd.exe";
    bool success = CreateProcessA("C:\\WINDOWS\\system32\\cmd.exe", NULL, &sAttr, NULL, NULL, NULL, NULL, NULL, &sInfo, &pInfo);
    if (!success) {
        std::cout << "CreateProcessA() failed with error " << GetLastError() << "\n";
    }
    std::cout << GetLastError() << "\n";
    return 0;
}

This doesn't seem to be working, whenever I specify STARTF_USESTDHANDLES as dwFlags the opened process instantly closes (or doesn't open at all, not sure). It works when I don't specify flags but I/O aren't redirected.
Also, as expected writing to it using my pipe client doesn't work, it can't get a handle to that pipe.
CreateFile is always true and the handle values seem valid, GetLastError() returns 0 but the program just exits and there is no popup with a child process, and even if it was running in the background I cannot write to it.

Body:
Based on your represented code, two issues are found:

Set bInheritHandles parameter of CreateProcessA to TRUE instead of NULL to make each inheritable handle in the calling process is inherited by the new process (here is cmd.exe).

cmd.exe shows version information after launched and exits. You can set command line for cmd.exe to make it running continuously if you want to prevent it from exiting.

A tip:

Call GetLastError() immediately after the function fails otherwise the error code may be set to zero by other functions.

The following is an example work for me. You can have a try.

int main()
{
    STARTUPINFOA sInfo;
    PROCESS_INFORMATION pInfo;
    SECURITY_ATTRIBUTES sAttr;
    ZeroMemory(&sInfo, sizeof(sInfo));
    ZeroMemory(&pInfo, sizeof(pInfo));
    ZeroMemory(&sAttr, sizeof(sAttr));
    sInfo.cb = sizeof(sInfo);
    sAttr.bInheritHandle = true;
    HANDLE fileTest = CreateFileA("hello.txt", GENERIC_READ | GENERIC_WRITE, 0, &sAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    HANDLE stdinPipe = CreateNamedPipeA("\\\\.\\pipe\\DokiDokiIn", PIPE_ACCESS_INBOUND, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 1024, 1024, NMPWAIT_USE_DEFAULT_WAIT, &sAttr);
    sInfo.hStdInput = stdinPipe;
    sInfo.hStdOutput = fileTest;
    sInfo.hStdError = fileTest;
    sInfo.dwFlags |= STARTF_USESTDHANDLES;

    char input[] = "ping www.google.com -t";
    char cmd[] = "cmd.exe";
    // initialize cmd
    char cmdline[MAX_PATH];
    sprintf_s(cmdline, sizeof(cmdline), "%s /c %s", cmd, input);
    bool success = CreateProcessA("C:\\WINDOWS\\system32\\cmd.exe", cmdline, &sAttr, NULL, TRUE, NULL, NULL, NULL, &sInfo, &pInfo);
    if (!success) {
        DWORD errCode = GetLastError();
        std::cout << "CreateProcessA() failed with error " << errCode << "\n";
    }

    return 0;
}


问:
How to clear basic authentication details in chrome
I'm working on a site that uses basic authentication. Using Chrome I've logged in using the basic auth. I now want to remove the basic authentication details from the browser and try a different login.

How do you clear the current basic authentication details when using Chrome?

答:
I am using Chrome Version 83 and this is how I did it. Before following the steps make sure the tab of the site, whose Auth Details you want to delete is closed.

First, go to Settings >> Privacy and security.

Then click on Site settings option

Then click on View permissions and data stored across sites option

Search for the site whose Auth info you want to delete. In this example, I am using Stack Overflow.

Now click on the site and then click the Clear data button.

Now restart your browser and you will be asked for a fresh login. For restarting you can type chrome://restart in the address bar.


问:
How can i use angular interpolation as index in an array?
I am trying to make an exam type true or false simulator with angular 9, but when i try to correct each question i cant interpolate the index of the correction. I have this error:

```<code>ERROR in Template parse errors:
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
             </p>
           </form>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
             </p>
           </form>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
             </p>
           </form>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
             </p>
           </form>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
           <span [ERROR ->]*ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
         </div>
       </div>
</code>```

The issue is about the way of interpolate the index of the correccion array
Here is my ts code:

```<code>    import { Component, OnInit } from '@angular/core';
import { PreguntaService } from '../../services/pregunta.service';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'app-examen',
  templateUrl: './examen.component.html',
  styleUrls: ['./examen.component.css'],
  providers: [PreguntaService]
})
export class ExamenComponent implements OnInit {

  public numeroPreguntas: any;
  public preguntas: any;
  public status: boolean;
  public timeLeft: number;
  public interval;
  public subscribeTimer: any;
  public timerStatus: boolean;
  public correccion: any;
  public iteracion: number;
  public respuesta: boolean;

  constructor(private _preguntaService: PreguntaService) {
    this.numeroPreguntas = 10;
    this.status = false;
    this.timeLeft = this.numeroPreguntas * 40;
    this.correccion = new Array;
  }

  ngOnInit(): void {
    this.status = false;
    console.log(this.preguntas);

  }

  generateExam() {
    this.preguntas = new Array;
    for (let i = 0; i < this.numeroPreguntas; i++) {
    this._preguntaService.getRandomPregunta().subscribe(response=>{
        this.preguntas.push(response.pregunta);
      },
      error=>{
        console.log(<any>error);

      }
    );

    }

    console.log(this.preguntas);

    this.status = true;
  }
  changeNumber($event) {
    this.numeroPreguntas = $event;
    this.preguntas = new Array(this.numeroPreguntas);
    this.timeLeft = this.numeroPreguntas * 40;
  }

  changeRadio($event){
    this.respuesta = $event;
  }
  onSubmit(responseForm: NgForm) {
      this.respuesta=responseForm.controls['respuesta'].value;
      this.iteracion = responseForm.controls['iteracion2'].value;

    console.log('hola');
    console.log(this.iteracion);
    console.log(this.respuesta);

    if (this.preguntas[this.iteracion].response == this.respuesta ) {
      this.correccion = true;
    }else{
      this.correccion[this.iteracion] = false;
    }
  }
  startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timerStatus = false;
      }
    },1000)
  }

  pauseTimer() {
      clearInterval(this.interval);
    }
  }
</code>```

And my template:

```<code><div class="">
  <label>Introduce el numero de preguntas</label>
  <input type="number" [ngModel]="numeroPreguntas" (ngModelChange)="changeNumber($event)" min="1" max="40">
</div>

<div class="">
  <button type="button" (click)="generateExam()">Generar examen</button>
</div>
<div class="sticky-top container bg-warning d-flex flex-row justify-content-around">
  <div class="botones">
    <button (click)='startTimer()' class="btn">Start Timer</button>
    <button (click)='pauseTimer()' class="btn">Pause</button>
  </div>
  <div class="timer">
    <p>{{timeLeft}} Seconds Left....</p>
  </div>
</div>

<div class="" *ngIf="status == true">
  <div class="jumbotron" *ngFor="let pregunta of preguntas; index as i">
    <h3>{{pregunta.title}}</h3>
    <p>{{pregunta.text}}</p>
    <form #responseForm="ngForm" (ngSubmit)="onSubmit(responseForm)">
      <select class="" ngModel name="respuesta" #respuesta="ngModel">
        <option value="true">True</option>
        <option value="false">False</option>
      </select>
      <label>No cambiar uwu</label>
      <input type="text" name="iteracion2" ngModel #iteracion2="ngModel" value="{{i}}">
      <p>
        <input type="submit" value="Corregir">
      </p>
    </form>
    <span *ngIf="correccion[{{iteracion}}] == true">Correcto</span>
    <span *ngIf="correccion[{{iteracion}}] == false">Incorrecto</span>
  </div>
</div>
</code>```

Sorry for the mix of spanish and english at my code.

答:
It should be used like :-</p>

```<code><span *ngIf="correccion[iteracion] == true">Correcto</span>
</code>```

Body:
I am trying to make an exam type true or false simulator with angular 9, but when i try to correct each question i cant interpolate the index of the correction. I have this error:

ERROR in Template parse errors:
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("

           </form>
           ]*ngIf="correccion[{{iteracion}}] == true">Correcto
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("

           </form>
           ]*ngIf="correccion[{{iteracion}}] == true">Correcto
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("

           </form>
           ]*ngIf="correccion[{{iteracion}}] == true">Correcto
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("

           </form>
           ]*ngIf="correccion[{{iteracion}}] == true">Correcto
           <span *ngIf="correccion[{{iteracion}}] "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == true] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@33:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token {, expected identifier, keyword, or string at column 13 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected : at column 23 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Unexpected token } at column 23 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

       "): /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10
       Parser Error: Missing expected ] at column 24 in [correccion[{{iteracion}}] == false] in /tmp/build_7e740f28deaf7d36c5b5df82ff65204c/src/app/components/examen/examen.component.html@34:10 ("
           </form>
           Correcto
           ]*ngIf="correccion[{{iteracion}}] == false">Incorrecto

The issue is about the way of interpolate the index of the correccion array
Here is my ts code:

    import { Component, OnInit } from '@angular/core';
import { PreguntaService } from '../../services/pregunta.service';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'app-examen',
  templateUrl: './examen.component.html',
  styleUrls: ['./examen.component.css'],
  providers: [PreguntaService]
})
export class ExamenComponent implements OnInit {

  public numeroPreguntas: any;
  public preguntas: any;
  public status: boolean;
  public timeLeft: number;
  public interval;
  public subscribeTimer: any;
  public timerStatus: boolean;
  public correccion: any;
  public iteracion: number;
  public respuesta: boolean;

  constructor(private _preguntaService: PreguntaService) {
    this.numeroPreguntas = 10;
    this.status = false;
    this.timeLeft = this.numeroPreguntas * 40;
    this.correccion = new Array;
  }

  ngOnInit(): void {
    this.status = false;
    console.log(this.preguntas);

  }

  generateExam() {
    this.preguntas = new Array;
    for (let i = 0; i < this.numeroPreguntas; i++) {
    this._preguntaService.getRandomPregunta().subscribe(response=>{
        this.preguntas.push(response.pregunta);
      },
      error=>{
        console.log(<any>error);

      }
    );

    }

    console.log(this.preguntas);

    this.status = true;
  }
  changeNumber($event) {
    this.numeroPreguntas = $event;
    this.preguntas = new Array(this.numeroPreguntas);
    this.timeLeft = this.numeroPreguntas * 40;
  }

  changeRadio($event){
    this.respuesta = $event;
  }
  onSubmit(responseForm: NgForm) {
      this.respuesta=responseForm.controls['respuesta'].value;
      this.iteracion = responseForm.controls['iteracion2'].value;

    console.log('hola');
    console.log(this.iteracion);
    console.log(this.respuesta);

    if (this.preguntas[this.iteracion].response == this.respuesta ) {
      this.correccion = true;
    }else{
      this.correccion[this.iteracion] = false;
    }
  }
  startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timerStatus = false;
      }
    },1000)
  }

  pauseTimer() {
      clearInterval(this.interval);
    }
  }

And my template:

  Introduce el numero de preguntas
  <input type="number" [ngModel]="numeroPreguntas" (ngModelChange)="changeNumber($event)" min="1" max="40">

  <button type="button" (click)="generateExam()">Generar examen</button>

    <button (click)='startTimer()' class="btn">Start Timer</button>
    <button (click)='pauseTimer()' class="btn">Pause</button>

{{timeLeft}} Seconds Left....

{{pregunta.title}}

{{pregunta.text}}

    <form #responseForm="ngForm" (ngSubmit)="onSubmit(responseForm)">
      <select class="" ngModel name="respuesta" #respuesta="ngModel">
        <option value="true">True</option>
        <option value="false">False</option>
      </select>
      No cambiar uwu
      <input type="text" name="iteracion2" ngModel #iteracion2="ngModel" value="{{i}}">

        <input type="submit" value="Corregir">

    </form>
    Correcto
    Incorrecto

Sorry for the mix of spanish and english at my code.

Body:
It should be used like :-

<span *ngIf="correccion[iteracion] == true">Correcto</span>


问:
How much Google limits CD2M?
The C2DM documentation states that

Google limits the number of messages a sender sends in aggregate, and the number of messages a sender sends to a specific device

someone knows specifically how much Google limits that?

答: I have 2 x C2DM accounts. When I asked what my limit was (for each) they stated 100,000.. That's not 100k / year ? That's 100k per day!</p>

Title: How much Google limits CD2M?


问:
Visual studio 2017 - Memory snapshot empty
I am trying to use the memory profiler in VS 2017 Pro but although I am able to take a memory snapshot, when I try to visualize it, it is just empty, as you can see on the screenshot.

Am I missing something ?

click to enlarge

答:
I am trying to use the memory profiler in VS 2017 Pro but although I
  am able to take a memory snapshot, when I try to visualize it, it is
  just empty, as you can see on the screenshot.

The default Native Window will ignore these Unresolved Allocations.

You should uncheck the checkbox filter called Hide Unresolved Allocations.

Follow these gif's operation and you will see the content later.


问:
combine latest is not triggering properly in Firefox and IE
I have a behavior subject boolean and it is assigned to an observable. I'm using this observable in a combineLatest. In Chrome and other browsers (Except Firefox and IE) this combine latest is triggering whenever the behavior subject value is changed. In Firefox and IE alone this is intermittently working.</p>

答:
The issue you have belongs not to the rxjs but to the functions are used in the code that don't exist in IE and require a polyfill.

For example Map Set Array have methods that aren't present in IE but exist in Edge or Chrome.

If you want to debug it - open developer tools in IE find the error, from the error you can understand which polyfill should be added and then simply update polyfills.ts with something like that:

import '@angular/localize/init';
import 'classlist.js';
import 'core-js/es6/array';
import 'core-js/es6/date';
import 'core-js/es6/function';
import 'core-js/es6/map';
import 'core-js/es6/math';
import 'core-js/es6/number';
import 'core-js/es6/object';
import 'core-js/es6/parse-float';
import 'core-js/es6/parse-int';
import 'core-js/es6/reflect';
import 'core-js/es6/regexp';
import 'core-js/es6/set';
import 'core-js/es6/string';
import 'core-js/es6/symbol';
import 'core-js/es6/weak-map';
import 'core-js/es7/array';
import 'core-js/es7/reflect';
import 'url-polyfill';
import 'web-animations-js';
import 'whatwg-fetch';
import 'zone.js/dist/zone';
```


问:
Load a different form on different pages using the same page template
Kentico 12, not MVC:
I have a page template that is used on several pages.  On some of those pages I want to display a form. (a biz form from the Forms application) I don't necessarily want the same form on each of those pages. I need a way to specify which form to display.  I expect I could create a field in the page type to specify the form name, but it would be nicer to be able to have designers add a page with the form on it, and have a repeater display that page in a webpartzone on the aforementioned page template.  I'm not sure how to do this, though.  Anyone have an example or suggestions?  </p>

答:
If you’re using portal engine, then you should easily be able to add an editor zone to your template. Content editors can then add the online form widget to individual pages. The widgets work at page level rather than template level, so should give the control you

The page from the docs will show how to setup an editor zone:
https://docs.kentico.com/k12/developing-websites/preparing-widgets-for-users/setting-up-widget-zones-on-pages


问:
Select query to remove non-numeric characters
I've got dirty data in a column with variable alpha length. I just want to strip out anything that is not 0-9.

I do not want to run a function or proc. I have a script that is similar that just grabs the numeric value after text, it looks like this:

```<code>Update TableName
set ColumntoUpdate=cast(replace(Columnofdirtydata,'Alpha #','') as int)
where Columnofdirtydata like 'Alpha #%'
And ColumntoUpdate is Null
</code>```

I thought it would work pretty good until I found that some of the data fields I thought would just be in the format Alpha # 12345789 are not.

Examples of data that needs to be stripped

```<code>AB ABCDE # 123
ABCDE# 123
AB: ABC# 123
</code>```

I just want the 123. It is true that all data fields do have the # prior to the number.

I tried substring and PatIndex, but I'm not quite getting the syntax correct or something. Anyone have any advice on the best way to address this?

答:
DECLARE @STR VARCHAR(400)

DECLARE @specialchars VARCHAR(50) = '%[~,@,#,$,%,&,*,(,),!^?:]%'

SET @STR = '1, 45 4,3 68.00-'

WHILE PATINDEX( @specialchars, @STR ) > 0

---Remove special characters using Replace function

SET @STR = Replace(Replace(REPLACE( @STR, SUBSTRING( @STR, PATINDEX( @specialchars, @STR ), 1 ),''),'-',''), ' ','')

SELECT @STR

Body:
I've got dirty data in a column with variable alpha length. I just want to strip out anything that is not 0-9.

I do not want to run a function or proc. I have a script that is similar that just grabs the numeric value after text, it looks like this:

Update TableName
set ColumntoUpdate=cast(replace(Columnofdirtydata,'Alpha #','') as int)
where Columnofdirtydata like 'Alpha #%'
And ColumntoUpdate is Null

I thought it would work pretty good until I found that some of the data fields I thought would just be in the format Alpha # 12345789 are not.

Examples of data that needs to be stripped

AB ABCDE # 123
ABCDE# 123
AB: ABC# 123

I just want the 123. It is true that all data fields do have the # prior to the number.

I tried substring and PatIndex, but I'm not quite getting the syntax correct or something. Anyone have any advice on the best way to address this?


问:
trying Shared-preferences with bool
It’s the first time I’m using Shared-preferences but I can’t switch between true and false when I click on the icon and save the value when I leave the program, does anyone know what’s wrong?</p>
```<code>import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Shared preferences demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Shared preferences demo'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  bool select = true;
  @override
  void initState() {
    super.initState();
    _loadCounter();
  }
  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('select', true);
  }
  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //Return bool
    bool boolValue = prefs.getBool('select');
    return boolValue;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '$select',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          child: Icon(Icons.add),
      ),);}}
</code>```

答:
Modify _incrementCounter method to get bool value which is Future vaue which gets from the shared preference

```<code>class _MyHomePageState extends State<MyHomePage> {
  bool select;

  @override
  void initState() {
    super.initState();
    setInitialValue();
  }

  setInitialValue() async {
    final value = await _incrementCounter();
    setState(() {
      select = value?? true;
    });
  }

  _loadCounter(bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('select', value);
  }

  Future<bool> _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //Return bool
    bool boolValue = prefs.getBool('select');
    return boolValue;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '$select',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          _loadCounter(!select);
          final value = await _incrementCounter();
          setState(() {
            select = value;
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}
</code>```

Title: trying Shared-preferences with bool

Body:
It’s the first time I’m using Shared-preferences but I can’t switch between true and false when I click on the icon and save the value when I leave the program, does anyone know what’s wrong?

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Shared preferences demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Shared preferences demo'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  bool select = true;
  @override
  void initState() {
    super.initState();
    _loadCounter();
  }
  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('select', true);
  }
  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //Return bool
    bool boolValue = prefs.getBool('select');
    return boolValue;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title),),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '$select',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
          onPressed: _incrementCounter,
          child: Icon(Icons.add),
      ),);}}

Body:
Modify _incrementCounter method to get bool value which is Future vaue which gets from the shared preference

class _MyHomePageState extends State<MyHomePage> {
  bool select;

  @override
  void initState() {
    super.initState();
    setInitialValue();
  }

  setInitialValue() async {
    final value = await _incrementCounter();
    setState(() {
      select = value?? true;
    });
  }

  _loadCounter(bool value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('select', value);
  }

  Future<bool> _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    //Return bool
    bool boolValue = prefs.getBool('select');
    return boolValue;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '$select',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          _loadCounter(!select);
          final value = await _incrementCounter();
          setState(() {
            select = value;
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}


问:
CMake + MinGW + Clang on Windows 10
I would like to compile an application with using Clang 4.0, CMake 3.8.1, MinGW x86_64 6.3.0. I've tried:

```<code>cmake -G "MinGW Makefiles" -DCMAKE_C_COMPILER=clang.exe -DCMAKE_CXX_COMPILER=clang++ ..\code
</code>```

but a compilation of a test program failed because of passing Visual Studio's compiler arguments. I'd like to not use Visual Studio at all.
Output:

```<code>-- The C compiler identification is Clang 4.0.0
-- The CXX compiler identification is Clang 4.0.0
-- Check for working C compiler: C:/Program Files/LLVM/bin/clang.exe
-- Check for working C compiler: C:/Program Files/LLVM/bin/clang.exe -- broken
CMake Error at C:/Program Files/CMake/share/cmake-3.8/Modules/CMakeTestCCompiler.cmake:51 (message):
The C compiler "C:/Program Files/LLVM/bin/clang.exe" is not able to compile a simple test program.
clang.exe: error: no such file or directory: '/nologo'
clang.exe: error: no such file or directory: '/DWIN32'
clang.exe: error: no such file or directory: '/D_WINDOWS'
</code>```

I also tried:

```<code>cmake -G "MinGW Makefiles"  -DCMAKE_C_COMPILER="C:/Program Files/LLVM/msbuild-bin/cl.exe" -DCMAKE_CXX_COMPILER="C:/Program Files/LLVM/msbuild-bin/cl.exe" -DCMAKE_LINKER="C:/Program Files/LLVM/bin/lld-link.exe" ..\code
</code>```

and it also failed while compilation a test program:

```<code> C:\PROGRA~1\LLVM\bin\lld-link.exe /nologo
 @CMakeFiles\cmTC_afe59.dir\objects1.rsp /out:cmTC_afe59.exe
 /implib:cmTC_afe59.lib
 /pdb:C:\...........\_build\CMakeFiles\CMakeTmp\cmTC_afe59.pdb
 /version:0.0 /machine:x64 /debug /pdbtype:sept /INCREMENTAL:YES
 /subsystem:console kernel32.lib user32.lib gdi32.lib winspool.lib
 comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib
 odbc32.lib odbccp32.lib

 error: could not open /pdbtype:sept: no such file or directory
</code>```

Is it possible to force Clang with MinGw on Windows 10?

答:
Those are MSVC parameters. I have come across several libraries that assume these work when checking for IF(WIN32) in CMakeLists.txt, while it should be IF(MSVC).

There is a MinGW-w64 available with both GCC and LLVM/CLang at http://winlibs.com/ but as it's not MSVC those parameters still need to be avoided, so I recommend you fix CMakeLists.txt and run cmake again.

Title: CMake + MinGW + Clang on Windows 10

Body:
I would like to compile an application with using Clang 4.0, CMake 3.8.1, MinGW x86_64 6.3.0. I've tried:

cmake -G "MinGW Makefiles" -DCMAKE_C_COMPILER=clang.exe -DCMAKE_CXX_COMPILER=clang++ ..\code

but a compilation of a test program failed because of passing Visual Studio's compiler arguments. I'd like to not use Visual Studio at all.
Output:

-- The C compiler identification is Clang 4.0.0
-- The CXX compiler identification is Clang 4.0.0
-- Check for working C compiler: C:/Program Files/LLVM/bin/clang.exe
-- Check for working C compiler: C:/Program Files/LLVM/bin/clang.exe -- broken
CMake Error at C:/Program Files/CMake/share/cmake-3.8/Modules/CMakeTestCCompiler.cmake:51 (message):
The C compiler "C:/Program Files/LLVM/bin/clang.exe" is not able to compile a simple test program.
clang.exe: error: no such file or directory: '/nologo'
clang.exe: error: no such file or directory: '/DWIN32'
clang.exe: error: no such file or directory: '/D_WINDOWS'

I also tried:

cmake -G "MinGW Makefiles"  -DCMAKE_C_COMPILER="C:/Program Files/LLVM/msbuild-bin/cl.exe" -DCMAKE_CXX_COMPILER="C:/Program Files/LLVM/msbuild-bin/cl.exe" -DCMAKE_LINKER="C:/Program Files/LLVM/bin/lld-link.exe" ..\code

and it also failed while compilation a test program:

 C:\PROGRA~1\LLVM\bin\lld-link.exe /nologo
 @CMakeFiles\cmTC_afe59.dir\objects1.rsp /out:cmTC_afe59.exe
 /implib:cmTC_afe59.lib
 /pdb:C:\...........\_build\CMakeFiles\CMakeTmp\cmTC_afe59.pdb
 /version:0.0 /machine:x64 /debug /pdbtype:sept /INCREMENTAL:YES
 /subsystem:console kernel32.lib user32.lib gdi32.lib winspool.lib
 comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib
 odbc32.lib odbccp32.lib

 error: could not open /pdbtype:sept: no such file or directory

Is it possible to force Clang with MinGw on Windows 10?


问:
Android: EditText in CustomView not behaving as expected when touched
I have a CustomView which contains a LinearLayout that holds an EditText & another custom view element. However, when I run my app and touch the EditText it does not behave as expected (doesn't appear to receive focus & the soft keyboard doesn't open). I've tried setting duplicateParentState="true" on both the EditText & the LinearLayout. I also attached an onTouchEventListener to the EditText that calls a simple toast & the toast did show up.

Here's the code for my CustomView.

form_field.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_marginBottom="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/grey_rounded_borders">

    <EditText
        android:id="@+id/edit_text"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:inputType="text"
        android:padding="10dp"
        android:textColor="#2d6169"
        android:textSize="18sp"
        android:background="@color/transparent" />

    <RelativeLayout
        android:layout_marginStart="5dp"
        android:layout_marginEnd="10dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <com.example.app.ValidationIcon
            android:id="@+id/validation_icon"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            tools:ignore="ContentDescription" />

    </RelativeLayout>

</LinearLayout>
```

<p>FormField.java</p>

<pre class="lang-java prettyprint-override"><code>package com.example.app;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import java.util.ArrayList;

public class FormField extends LinearLayout {

    private EditText editText;
    private ValidationIcon validationIcon;

    private Integer fieldInputType;
    private String fieldInputHint;

    public FormField(Context context)
    {
        super(context);
    }

    public FormField(Context context, AttributeSet attributeSet)
    {
        super(context, attributeSet);

        TypedArray attrs = context.obtainStyledAttributes(attributeSet, R.styleable.FormField, 0, 0);

        fieldInputType = attrs.getInt(
                R.styleable.FormField_fieldInputType,
                InputType.TYPE_TEXT_VARIATION_NORMAL
        );
        fieldInputHint = attrs.getString(
            R.styleable.FormField_fieldInputHint
        );

        attrs.recycle();

        inflate(getContext(), R.layout.form_field, this);

        this.setFocusable(true);
        this.setFocusableInTouchMode(true);

        editText = (EditText)findViewById(R.id.edit_text);
        editText.setInputType(fieldInputType);
        editText.setHint(fieldInputHint);
        editText.setFocusableInTouchMode(true);

        validationIcon = (ValidationIcon)findViewById(R.id.validation_icon);
        validationIcon.setValid(true);

        ArrayList<View> touchables = new ArrayList<View>();
        touchables.add(this);
        touchables.add(editText);

        addTouchables(touchables);
    }

    public FormField(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

}
</code>```

registration_layout.xml

<RelativeLayout android:id="@+id/container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="20dp">

    <RelativeLayout android:id="@+id/account_details"
        android:layout_marginBottom="15dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.example.app.FormField
            android:id="@+id/name_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            custom:fieldInputHint="@string/name_field_hint" />

        <com.example.app.FormField
            android:id="@+id/email_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            custom:fieldInputHint="@string/email_field_hint" />

        <com.example.app.FormField
            android:id="@+id/password_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            custom:fieldInputHint="@string/password_field_hint" />

        <com.example.app.FormField
            android:id="@+id/re_password_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            custom:fieldInputHint="@string/re_password_field_hint" />

    </RelativeLayout>

</RelativeLayout>
```

<p>Min SDK Version is set at 14, target is set at 20. Any help would be greatly appreciated!</p>

<p><strong>EDIT:</strong></p>

<p>I got this logcat message today while testing long presses on my FormFields.</p>

```W/TextView﹕ TextView does not support text selection. Action mode cancelled.
```

I double checked my code and the EditText element is only ever cast as an EditText. If the EditText is being cast to a TextView that would explain my original issues but now I'm confused as to why or how it was cast as a TextView.

答: Make sure have not been setting inputType:'none' or '0X000000'

Body:
I have a CustomView which contains a LinearLayout that holds an EditText & another custom view element. However, when I run my app and touch the EditText it does not behave as expected (doesn't appear to receive focus & the soft keyboard doesn't open). I've tried setting duplicateParentState="true" on both the EditText & the LinearLayout. I also attached an onTouchEventListener to the EditText that calls a simple toast & the toast did show up.

Here's the code for my CustomView.

form_field.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_marginBottom="15dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/grey_rounded_borders">

    <EditText
        android:id="@+id/edit_text"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:inputType="text"
        android:padding="10dp"
        android:textColor="#2d6169"
        android:textSize="18sp"
        android:background="@color/transparent" />

    <RelativeLayout
        android:layout_marginStart="5dp"
        android:layout_marginEnd="10dp"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

        <com.example.app.ValidationIcon
            android:id="@+id/validation_icon"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            tools:ignore="ContentDescription" />

    </RelativeLayout>

</LinearLayout>

FormField.java

package com.example.app;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import java.util.ArrayList;

public class FormField extends LinearLayout {

    private EditText editText;
    private ValidationIcon validationIcon;

    private Integer fieldInputType;
    private String fieldInputHint;

    public FormField(Context context)
    {
        super(context);
    }

    public FormField(Context context, AttributeSet attributeSet)
    {
        super(context, attributeSet);

        TypedArray attrs = context.obtainStyledAttributes(attributeSet, R.styleable.FormField, 0, 0);

        fieldInputType = attrs.getInt(
                R.styleable.FormField_fieldInputType,
                InputType.TYPE_TEXT_VARIATION_NORMAL
        );
        fieldInputHint = attrs.getString(
            R.styleable.FormField_fieldInputHint
        );

        attrs.recycle();

        inflate(getContext(), R.layout.form_field, this);

        this.setFocusable(true);
        this.setFocusableInTouchMode(true);

        editText = (EditText)findViewById(R.id.edit_text);
        editText.setInputType(fieldInputType);
        editText.setHint(fieldInputHint);
        editText.setFocusableInTouchMode(true);

        validationIcon = (ValidationIcon)findViewById(R.id.validation_icon);
        validationIcon.setValid(true);

        ArrayList<View> touchables = new ArrayList<View>();
        touchables.add(this);
        touchables.add(editText);

        addTouchables(touchables);
    }

    public FormField(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

}

registration_layout.xml

<RelativeLayout android:id="@+id/container"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="20dp">

    <RelativeLayout android:id="@+id/account_details"
        android:layout_marginBottom="15dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.example.app.FormField
            android:id="@+id/name_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            custom:fieldInputHint="@string/name_field_hint" />

        <com.example.app.FormField
            android:id="@+id/email_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            custom:fieldInputHint="@string/email_field_hint" />

        <com.example.app.FormField
            android:id="@+id/password_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            custom:fieldInputHint="@string/password_field_hint" />

        <com.example.app.FormField
            android:id="@+id/re_password_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            custom:fieldInputHint="@string/re_password_field_hint" />

    </RelativeLayout>

</RelativeLayout>

Min SDK Version is set at 14, target is set at 20. Any help would be greatly appreciated!

EDIT:

I got this logcat message today while testing long presses on my FormFields.

W/TextView﹕ TextView does not support text selection. Action mode cancelled.

I double checked my code and the EditText element is only ever cast as an EditText. If the EditText is being cast to a TextView that would explain my original issues but now I'm confused as to why or how it was cast as a TextView.


问:
Can you make Python3 give an error when comparing strings to bytes
When converting code from Python 2 to Python 3 one issue is that the behaviour when testing strings and bytes for equality has changed. For example:

```<code>foo = b'foo'
if foo == 'foo':
    print("They match!")
</code>```

prints nothing on Python 3 and "They match!" on Python 2. In this case it is easy to spot but in many cases the check is performed on variables which may have been defined elsewhere so there is no obvious type information.

I would like to make the Python 3 interpreter give an error whenever there is an equality test between string and bytes rather than silently conclude that they are different. Is there any way to accomplish this?

答:
There is an option, -b, you can pass to the Python interpreter to cause it to emit a warning or error when comparing byte / str.

```<code>> python --help
usage: /bin/python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
</code>```

This produces a BytesWarning as seen here:

```<code>> python -bb -i
Python 3.8.0
Type "help", "copyright", "credits" or "license" for more information.
>>> v1 = b'foo'
>>> v2 = 'foo'
>>> v1 == v2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
BytesWarning: Comparison between bytes and string
</code>```

Body:
When converting code from Python 2 to Python 3 one issue is that the behaviour when testing strings and bytes for equality has changed. For example:

foo = b'foo'
if foo == 'foo':
    print("They match!")

prints nothing on Python 3 and "They match!" on Python 2. In this case it is easy to spot but in many cases the check is performed on variables which may have been defined elsewhere so there is no obvious type information.

I would like to make the Python 3 interpreter give an error whenever there is an equality test between string and bytes rather than silently conclude that they are different. Is there any way to accomplish this?

Body:
There is an option, -b, you can pass to the Python interpreter to cause it to emit a warning or error when comparing byte / str.

> python --help
usage: /bin/python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)

This produces a BytesWarning as seen here:

> python -bb -i
Python 3.8.0
Type "help", "copyright", "credits" or "license" for more information.
>>> v1 = b'foo'
>>> v2 = 'foo'
>>> v1 == v2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
BytesWarning: Comparison between bytes and string