问:
Updating two consecutive textviews using threads
I have been reading up about threads in my java book and I wanted to try making updates with two consecutive threads at the same time.

OF course though threads can't update the UI. I have used handlers a little bit but only by passing messengers from one class to another to capture location from a service to an activity.

But this must be simpler than that.

I assume I should use AsyncTask but i want to count 1-10 in each field and I don't want to keep dipping in and out of the asynctask class.

Any pointers appreciated

Stephen

UPDATE

So I did a little more experimenting. I wrote a handler method to handle any messages sent to it. It checks which field it should be updating and then performs a setText on said field. Here is the code

```<code>Handler myHandler = new Handler(){
 public void handleMessage(Message msg){
 msg = Message.obtain();
 Bundle bundle = msg.getData();

 String fieldName = bundle.getString("fieldName");
 int count = bundle.getInt("count");

 if(fieldName=="text1"){
     text1.setText(count);
 }else{
     text2.setText(count);
 }
}
};
</code>```

I then have some code in the onCreate of my activity which launches two threads and each thread passes a messages with my int count to the handler. It also passes in a TextView name so my handler knows which textview it should be updating. Here is the code...

```<code>public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

 text1 = (TextView)findViewById(R.id.text1);
 text2 = (TextView)findViewById(R.id.text2);

 new Thread(){
   public void run(){
   for(int i=1;i<10;i++){
     message = Message.obtain(myHandler);
     Bundle bundle = new Bundle();
     bundle.putCharSequence("fieldName", "text1");
     message.setData(bundle);
     myHandler.sendMessageDelayed(message, 1000);
   }
      }
    }.start();

new Thread(){
   public void run(){
   for(int i=1;i<10;i++){
     message = Message.obtain(myHandler);
     Bundle bundle = new Bundle();
     bundle.putCharSequence("fieldName", "text2");
     message.setData(bundle);
     myHandler.sendMessageDelayed(message, 1000);
   }
 }
   }.start();

}
</code>```

But I am getting an error on the setText

05-17 17:13:00.013: ERROR/AndroidRuntime(966): android.content.res.Resources$NotFoundException: String resource ID #0x0

Any ideas?

答:
Here's what you can do. You are on the right track about using AsyncTask, so extend the class and put your counting in the progress update function. You should have something like this:

```<code>private class BackgroundTask extends AsyncTask<Void, Void, Void> {
    int i;

    protected void onPreExecute() {
        i = 0;
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        i++;
        publishProgress(i);
    }

    protected void onProgressUpdate(Integer... progress) {
        TextView tv1 = (TextView) Main.this.findViewById(R.id.textView1)
        TextView tv2 = (TextView) Main.this.findViewById(R.id.textView2)
        tv1.setText(i);
        tv2.setText(i);
    }

    protected void onPostExecute(Void result) {
        i = null;
    }
}
</code>```

where Main is your activity and textView1 and textView2 are your text views that you are going to update.

Body:
I have been reading up about threads in my java book and I wanted to try making updates with two consecutive threads at the same time.

OF course though threads can't update the UI. I have used handlers a little bit but only by passing messengers from one class to another to capture location from a service to an activity.

But this must be simpler than that.

I assume I should use AsyncTask but i want to count 1-10 in each field and I don't want to keep dipping in and out of the asynctask class.

Any pointers appreciated

Stephen

UPDATE

So I did a little more experimenting. I wrote a handler method to handle any messages sent to it. It checks which field it should be updating and then performs a setText on said field. Here is the code

Handler myHandler = new Handler(){
 public void handleMessage(Message msg){
 msg = Message.obtain();
 Bundle bundle = msg.getData();

 String fieldName = bundle.getString("fieldName");
 int count = bundle.getInt("count");

 if(fieldName=="text1"){
     text1.setText(count);
 }else{
     text2.setText(count);
 }
}
};

I then have some code in the onCreate of my activity which launches two threads and each thread passes a messages with my int count to the handler. It also passes in a TextView name so my handler knows which textview it should be updating. Here is the code...

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

 text1 = (TextView)findViewById(R.id.text1);
 text2 = (TextView)findViewById(R.id.text2);

 new Thread(){
   public void run(){
   for(int i=1;i<10;i++){
     message = Message.obtain(myHandler);
     Bundle bundle = new Bundle();
     bundle.putCharSequence("fieldName", "text1");
     message.setData(bundle);
     myHandler.sendMessageDelayed(message, 1000);
   }
      }
    }.start();

new Thread(){
   public void run(){
   for(int i=1;i<10;i++){
     message = Message.obtain(myHandler);
     Bundle bundle = new Bundle();
     bundle.putCharSequence("fieldName", "text2");
     message.setData(bundle);
     myHandler.sendMessageDelayed(message, 1000);
   }
 }
   }.start();

}

But I am getting an error on the setText

05-17 17:13:00.013: ERROR/AndroidRuntime(966): android.content.res.Resources$NotFoundException: String resource ID #0x0

Any ideas?

Body:
Here's what you can do. You are on the right track about using AsyncTask, so extend the class and put your counting in the progress update function. You should have something like this:

private class BackgroundTask extends AsyncTask<Void, Void, Void> {
    int i;

    protected void onPreExecute() {
        i = 0;
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        i++;
        publishProgress(i);
    }

    protected void onProgressUpdate(Integer... progress) {
        TextView tv1 = (TextView) Main.this.findViewById(R.id.textView1)
        TextView tv2 = (TextView) Main.this.findViewById(R.id.textView2)
        tv1.setText(i);
        tv2.setText(i);
    }

    protected void onPostExecute(Void result) {
        i = null;
    }
}

where Main is your activity and textView1 and textView2 are your text views that you are going to update.


来源: stackexchange

问:
Can I put pragma `Inline` in the body instead of the spec?
Ada Information Clearinghouse states the following:

The use of pragma Inline does have its disadvantages. It can create compilation dependencies on the body; that is, when the specification uses a pragma Inline, both the specification and corresponding body may need to be compiled before the specification can be used.

Does putting pragma Inline in the body avoid this problem?

答:
The advantage is that Inline in the specification allows for cross-unit inlining which can be a very powerful run-time optimization.

The disadvantage you mention matters rather when you compile on a computer which is slow or has few cores.
Then it's a run time vs compile time trade-off.

Note that on GNAT, cross-unit inlining is enabled by a single switch (-gnatn), so don't be afraid by the Inline pragma creating compilation dependencies: you can switch the whole mechanism on or off with that switch.

ContentLicense: CC BY-SA 4.0


问:
Overriding Sphinx autodoc "Alias of" for import of private class?
I have a Python package that I am attempting to document with sphinx-autodoc. My python package has an __init__.py file that imports a class out from a submodule to make it accessible at the package level.

```<code>from a.b.c.d import _Foo as Foo

__all__ = ["Foo"]
</code>```

If I do this, my (html) documentation is as follows:

a.b.c package

Submodules

a.b.c.d module

[snip documentation of irrelevant public classes within the a.b.c.d module]

Module contents

The c module.

a.b.c.Foo

alias of _Foo

Not super useful since _Foo is (rightly) undocumented as it is a private class within the a.b.c.d submodule.

I can add the following to my conf.py which ensures that the private class definition in the module is documented.

```<code>def skip(app, what, name, obj, skip, options):
    if name == "_Foo":
        return False
    return skip
</code>```

Other alternative, but not great things I've tried:

Rename a.b.c.d._Foo to a.b.c.d.Foo (and then update the import to from a.b.c.d import Foo) -- but then I get the class documented twice, once under the a.b.c.d module heading, and once again under the Module contents heading.

Renaming a.b.c.d.Foo to a.b.c.d.MyFoo and then importing (from a.b.c.d import MyFoo as Foo) results in MyFoo being documented, and Foo being listed as an alias of MyFoo.

Ideally I'd like the private definition to remain undocumented, but to have the version imported into the package fully documented. Does anyone know how I might achieve this?

答:
Using the members directive you can show all members except those that start with '_'. You can leave _Foo undocumented in a.b.c.d and document it as Foo in a.b.c. I would import _Foo as from a.b.c.d import _Foo and then add whatever documentation like:

```<code>Foo = _Foo
''' blah blah blah '''
</code>```

If, for some reason, you don't want _Foo in a.b.c's namespace, then you can also do:

```<code>from a.b.c.d import _Foo as Foo
Foo = Foo
''' blah blah blah '''
</code>```

Body:
I have a Python package that I am attempting to document with sphinx-autodoc. My python package has an __init__.py file that imports a class out from a submodule to make it accessible at the package level.

from a.b.c.d import _Foo as Foo

__all__ = ["Foo"]

If I do this, my (html) documentation is as follows:

a.b.c package

Submodules

a.b.c.d module

[snip documentation of irrelevant public classes within the a.b.c.d module]

Module contents

The c module.

a.b.c.Foo

alias of _Foo

Not super useful since _Foo is (rightly) undocumented as it is a private class within the a.b.c.d submodule.

I can add the following to my conf.py which ensures that the private class definition in the module is documented.

def skip(app, what, name, obj, skip, options):
    if name == "_Foo":
        return False
    return skip

Other alternative, but not great things I've tried:

Rename a.b.c.d._Foo to a.b.c.d.Foo (and then update the import to from a.b.c.d import Foo) -- but then I get the class documented twice, once under the a.b.c.d module heading, and once again under the Module contents heading.

Renaming a.b.c.d.Foo to a.b.c.d.MyFoo and then importing (from a.b.c.d import MyFoo as Foo) results in MyFoo being documented, and Foo being listed as an alias of MyFoo.

Ideally I'd like the private definition to remain undocumented, but to have the version imported into the package fully documented. Does anyone know how I might achieve this?

Body:
Using the members directive you can show all members except those that start with '_'. You can leave _Foo undocumented in a.b.c.d and document it as Foo in a.b.c. I would import _Foo as from a.b.c.d import _Foo and then add whatever documentation like:

Foo = _Foo
''' blah blah blah '''

If, for some reason, you don't want _Foo in a.b.c's namespace, then you can also do:

from a.b.c.d import _Foo as Foo
Foo = Foo
''' blah blah blah '''


问:
approximate character matching using R
I have two datafiles. One of the files contains only one column with the name of the company (usually a hospital) and the other one contains a list of companies with the respective adresses. The problem is that the company names do not exactly match. How can i match them approximately ?

```<code>> dput(head(HOSPITALS[130:140,], 10))
</code>```

I would like to obtain one datafile, where the company is matchen with an adress, if available in adress

答:
Check out the fuzzyjoin package and the stringdist_join functions.

Here's a starting point. In your example data ignore_case = TRUE solves the matching problem. Depending on how the full data looks, you will have to experiment with the arguments (e.g. max_dist) and possibly filter the result until your achieve what you want.

```<code>library(dplyr)
library(fuzzyjoin)

HOSPITALS %>%
  stringdist_left_join(GH_MY,
                       by = c("hospital" = "hospital_name"),
                       ignore_case = TRUE,
                       max_dist = 2,
                       distance_col = "dist")
</code>```

Result:

```<code># A tibble: 10 x 6
   hospital             hospital_name    adress                 district   town      dist
   <chr>                <chr>            <chr>                  <chr>      <chr>    <dbl>
 1 HOSPITAL PAPAR       Hospital Papar   Peti Surat No. 6,      Papar      Sabah        0
 2 HOSPITAL PARIT BUNT~ Hospital Parit ~ Jalan Sempadan         Parit Bun~ Perak        0
 3 HOSPITAL PEKAN       Hospital Pekan   26600 Pekan            Pekan      Pahang       0
 4 HOSPITAL PENAWAR SD~ NA               NA                     NA         NA          NA
 5 HOSPITAL PORT DICKS~ Hospital Port D~ KM 11, Jalan Pantai    Port Dick~ Negeri ~     0
 6 HOSPITAL PULAU PINA~ Hospital Pulau ~ Jalan Residensi        Pulau Pin~ Pulau P~     0
 7 HOSPITAL PUSRAWI SD~ NA               NA                     NA         NA          NA
 8 HOSPITAL PUSRAWI SM~ NA               NA                     NA         NA          NA
 9 HOSPITAL PUTRAJAYA   Hospital Putraj~ Pusat Pentadbiran Ker~ Putrajaya  WP Putr~     0
10 HOSPITAL QUEEN ELIZ~ NA               NA                     NA         NA          NA
</code>```

Title: approximate character matching using R

Body:
I have two datafiles. One of the files contains only one column with the name of the company (usually a hospital) and the other one contains a list of companies with the respective adresses. The problem is that the company names do not exactly match. How can i match them approximately ?

> dput(head(HOSPITALS[130:140,], 10))

I would like to obtain one datafile, where the company is matchen with an adress, if available in adress

Body:
Check out the fuzzyjoin package and the stringdist_join functions.

Here's a starting point. In your example data ignore_case = TRUE solves the matching problem. Depending on how the full data looks, you will have to experiment with the arguments (e.g. max_dist) and possibly filter the result until your achieve what you want.

library(dplyr)
library(fuzzyjoin)

HOSPITALS %>%
  stringdist_left_join(GH_MY,
                       by = c("hospital" = "hospital_name"),
                       ignore_case = TRUE,
                       max_dist = 2,
                       distance_col = "dist")

Result:

# A tibble: 10 x 6
   hospital             hospital_name    adress                 district   town      dist
   <chr>                <chr>            <chr>                  <chr>      <chr>    <dbl>
 1 HOSPITAL PAPAR       Hospital Papar   Peti Surat No. 6,      Papar      Sabah        0
 2 HOSPITAL PARIT BUNT~ Hospital Parit ~ Jalan Sempadan         Parit Bun~ Perak        0
 3 HOSPITAL PEKAN       Hospital Pekan   26600 Pekan            Pekan      Pahang       0
 4 HOSPITAL PENAWAR SD~ NA               NA                     NA         NA          NA
 5 HOSPITAL PORT DICKS~ Hospital Port D~ KM 11, Jalan Pantai    Port Dick~ Negeri ~     0
 6 HOSPITAL PULAU PINA~ Hospital Pulau ~ Jalan Residensi        Pulau Pin~ Pulau P~     0
 7 HOSPITAL PUSRAWI SD~ NA               NA                     NA         NA          NA
 8 HOSPITAL PUSRAWI SM~ NA               NA                     NA         NA          NA
 9 HOSPITAL PUTRAJAYA   Hospital Putraj~ Pusat Pentadbiran Ker~ Putrajaya  WP Putr~     0
10 HOSPITAL QUEEN ELIZ~ NA               NA                     NA         NA          NA


问:
Delete line in powershell file
I have a file with the following lines

```<code>Servicetag
P4M8K82
P4M8l582
O5M8K82
</code>```

I wish I had the serial numbers only and not the name ServiceTag.
I would like: Browse the .csv file if the line contains SerivceTag then you don't get the value and copy the rest.

As a result, I wish I had:

```<code>P4M8K82
P4M8l582
O5M8K82
</code>```

Do you think it's possible?

答:
Although not really clear what you are asking, the below line will read the file as string array and write out a new file with all lines containing 'ServiceTag' removed:</p>

```<code>Get-Content -Path 'TheOriginalFile'| Where-Object { $_ -notmatch 'ServiceTag' } | Set-Content -Path 'TheNewFile'
</code>```

Title: Delete line in powershell file

Body:
I have a file with the following lines

Servicetag
P4M8K82
P4M8l582
O5M8K82

I wish I had the serial numbers only and not the name ServiceTag.
I would like: Browse the .csv file if the line contains SerivceTag then you don't get the value and copy the rest.

As a result, I wish I had:

P4M8K82
P4M8l582
O5M8K82

Do you think it's possible?

Body:
Although not really clear what you are asking, the below line will read the file as string array and write out a new file with all lines containing 'ServiceTag' removed:

Get-Content -Path 'TheOriginalFile'| Where-Object { $_ -notmatch 'ServiceTag' } | Set-Content -Path 'TheNewFile'


问:
How To Redirect Browser To New URL in Robotframework After Working on Old URL without Closing Browser
I'm working on a simple project where I launch chrome browser and perform operation on website #1 and once I have done that I logout from website #1 and now I want to launch website #2 on same browser. For e.g.

Step - 1 - Launch facebook and login to it

Step - 2 - Now launch twitter and login to it

```<code>*** Variables ***
${URL1}     http://www.facebook.com
${URL2}     http://www.twitter.com

*** Keywords ***
# 1st Login to facebook
    Open Browser    ${URL1}    chrome
    Login To Facebook

# 2nd Login to twitter
    Open Browser    ${URL2}    chrome
    Login To Twitter

# Now close the browser
    Close Browser
</code>```

Question - Which keyword can I use so that I after Login to Facebook keyword I can change the URL to twitter and then login to twitter and then close the browser ? Which is a better way to open a new tab with twitter or use the same tab and change the URL only.

Please Note :-

With above mentioned code, a new window is opened with, but I don't    want that, all I want to achieve is to change the URL of the existing    opened browser window.

答:
Try Go To keyword:

```<code>Go To    ${URL2}
</code>```

Body:
I'm working on a simple project where I launch chrome browser and perform operation on website #1 and once I have done that I logout from website #1 and now I want to launch website #2 on same browser. For e.g.

Step - 1 - Launch facebook and login to it

Step - 2 - Now launch twitter and login to it

*** Variables ***
${URL1}     http://www.facebook.com
${URL2}     http://www.twitter.com

*** Keywords ***
# 1st Login to facebook
    Open Browser    ${URL1}    chrome
    Login To Facebook

# 2nd Login to twitter
    Open Browser    ${URL2}    chrome
    Login To Twitter

# Now close the browser
    Close Browser

Question - Which keyword can I use so that I after Login to Facebook keyword I can change the URL to twitter and then login to twitter and then close the browser ? Which is a better way to open a new tab with twitter or use the same tab and change the URL only.

Please Note :-

With above mentioned code, a new window is opened with, but I don't    want that, all I want to achieve is to change the URL of the existing    opened browser window.

Body:
Try Go To keyword:

Go To    ${URL2}


问:
Reversing a string operation
So I was fiddling with my encryption algorithms when this problem caught my attention:

Suppose you have a string operation given by the following pseudocode:

```<code>string go_wacky(string input, int reps)
{
    string result = input;
    foreach (0..reps)
    {
        result = insert_substring_at(result, input, random_from_to(0, length(result));
    }
    return result;
}
</code>```

Or, in point-and-click terminology, copy the string, then reps times do the following: move the cursor to a random position within the string and hit paste.

Given the output string and reps, how to extract the input string (other than "reverse brute force" based on reconstructing the character list of the original string using reps and output length)?

答:
I hope this is not too brute-force, but I see no other way:

Take the first character of the output (call it a) and the last character of the output (call it b).

Search the output for substrings of length len(output)/reps starting with a and ending with b. This yields a list of candidates.

For each candidate replace recursively inside the output the candidate with an empty string, i.e. output = output.replace (candidate, '')

If after the last replacement, the result is an empty string you found the plain text.

ContentLicense: CC BY-SA 3.0

Title: Reversing a string operation

Body:
So I was fiddling with my encryption algorithms when this problem caught my attention:

Suppose you have a string operation given by the following pseudocode:

string go_wacky(string input, int reps)
{
    string result = input;
    foreach (0..reps)
    {
        result = insert_substring_at(result, input, random_from_to(0, length(result));
    }
    return result;
}

Or, in point-and-click terminology, copy the string, then reps times do the following: move the cursor to a random position within the string and hit paste.

Given the output string and reps, how to extract the input string (other than "reverse brute force" based on reconstructing the character list of the original string using reps and output length)?


问:
Add Session storage to ASP.NET Core 3.0
We are currently migrating an existing ASP.NET Core 2.2 web application to 3.0 So far we've got most things working, except session storage.

We had this fully working in v2.2 as we used it to hold the current logged in user's details. Now that we've upgraded to v3.0 it no longer works.

Here's the middleware code.

```<code>public void ConfigureServices(IServiceCollection services)
{

    // configure Razor pages, MVC, authentication here

    services.AddDistributedMemoryCache();

     services.AddSession(options =>
     {
        //prevent session storage from being accessed from client script
        //i.e. only server side code (added security)
        options.Cookie.HttpOnly = true;
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseSession();
}
</code>```

N.B. I've removed the rest of the middleware code for clarity.

I've tried moving the app.SetSession() line to the top of the method in case the order of execution was the problem but this has made no difference.

When I hover over the HttpContent.Session property in the debugger I get the following error:

```<code>HttpContext.Session threw an exception of type System.InvalidOperationException
</code>```

How do I enable Session storage in ASP.NET Core 3.0?

答: I've just tried adding the app.UseSession() to the top of the method and it's working now. It definitely didn't work before but it's working now and that's the main thing.

Title: Add Session storage to ASP.NET Core 3.0

Body:
We are currently migrating an existing ASP.NET Core 2.2 web application to 3.0 So far we've got most things working, except session storage.

We had this fully working in v2.2 as we used it to hold the current logged in user's details. Now that we've upgraded to v3.0 it no longer works.

Here's the middleware code.

public void ConfigureServices(IServiceCollection services)
{

    // configure Razor pages, MVC, authentication here

    services.AddDistributedMemoryCache();

     services.AddSession(options =>
     {
        //prevent session storage from being accessed from client script
        //i.e. only server side code (added security)
        options.Cookie.HttpOnly = true;
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseSession();
}

N.B. I've removed the rest of the middleware code for clarity.

I've tried moving the app.SetSession() line to the top of the method in case the order of execution was the problem but this has made no difference.

When I hover over the HttpContent.Session property in the debugger I get the following error:

HttpContext.Session threw an exception of type System.InvalidOperationException

How do I enable Session storage in ASP.NET Core 3.0?


问:
RISC access address greater than largest integer register
Let's say you are running a 32-bit RISC system. What instructions would you use to access a 64-bit memory address?

In a CISC instruction set, you can simply pass the extra word using a multiword instruction. For example:

```<code>1a) JMP
1b) loAddress
1c) hiAddress
</code>```

Given that RISC instructions are only one word each, how would you access a multi-word address?

Assume the ALU is 32-bit and has a carry flag.

Also, in a CISC system (for example the 8080) both the loAddress and hiAddress words would be stored in the program memory. I.e. the JMP instruction knows to look at the next item in program memory to retrieve the loAddress, and the item after that to retrieve the hiAddress. What happens in RISC?

答:
Given that RISC instructions are only one word each

This is not true. Most modern RISC architectures have a variable-width instruction set, or at least a special variable-width mode (ForwardCom, SuperH, MIPS16e, thumb2 in ARM, PowerPC's VLE extension, C instruction set in RISC-V...). That's because although memory has become increasing cheap, CPU speed is still far faster than memory speed and increasing code density to reduce instruction cache footprint is still good for performance. That means you can actually make your RISC architecture uses multiword instructions

Even then it won't help you unless you can use instructions that are wider than 64 bits (which are too big to be practical). With only two 32-bit words you'll still be limited to some offset around the base address instead of the full 64-bit address space. But that shouldn't be a problem because almost no single program can utilize the vast 64-bit address space. That's why there are no instructions receiving a 64-bit immediate address in x86-64 since a 32-bit offset is already enough. So you can do the same: use a small immediate offset for most situations and use a 2-register pair when you need the full 64-bit address

You can also use a wider instruction whose size is not multiple words. For example RISC-V allow any lengths that are a multiple of 16-bit. Since you won't ever need the full 64-bit address space, using 36-48 bits for the address along with a 48 or 64-bit instruction for the immediate would be enough. Even x86-64 CPUs nowadays have only 48-bit physical address space. There's no reason making the address bus so wide

As Peter said, addresses wider than the word size is primarily seen only in 8-bit microcontrollers. Beside AVR, it's also used in 8-bit PIC where the program counter is 13 or 14-bit long. Instructions generally contain only the low bits of the address, the high bits will be taken from the PC or PCLATH register. If you don't want to use an offset like above then replacing the low bits directly like this is an alternative way. Obviously you still need a separate register for the high bits. But if you don't care about orthogonality then just use a dedicated huge register for addressing, like in 8051, 6502 or other older CISC architectures

There are many other ways to support a wider address range than the register size as I described here How can 8-bit processor support more than 256 bytes of RAM?. One of them is to limit virtual address to the register size only (like ARM LPAE or x86 PAE), while allowing physical address to be 64-bit wide. The pages will be mapped in the TLB and you don't need to use 2 registers to address. If you want to access more than 4GB of memory in this mode just use some API similar to Windows AWE, or use multiple processes (like how Adobe Premiere CS4 did)

Body:
Let's say you are running a 32-bit RISC system. What instructions would you use to access a 64-bit memory address?

In a CISC instruction set, you can simply pass the extra word using a multiword instruction. For example:

1a) JMP
1b) loAddress
1c) hiAddress

Given that RISC instructions are only one word each, how would you access a multi-word address?

Assume the ALU is 32-bit and has a carry flag.

Also, in a CISC system (for example the 8080) both the loAddress and hiAddress words would be stored in the program memory. I.e. the JMP instruction knows to look at the next item in program memory to retrieve the loAddress, and the item after that to retrieve the hiAddress. What happens in RISC?


问:
What is the best way to create file folder for specifi user in laravel?
I have a simple dashboard in which users can register and do some stuff, now I would like to generate a file with username and his id; something like widget/obama2030.js in Laravel when a user is registered

my app structure:

myapp

```<code>-app
-bootstrap
-database
-resource
 .....
-widget
 -------
</code>```

in my user registration controller, I have the following.

```<code>protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        ]);

    File::makeDirectory('/widget/'.$user->name.Auth::user()->id, 0755, true);

    return $user;
}
</code>```

Now when user click the button register I am getting the following error

```<code>ErrorException (E_NOTICE)
Trying to get property of non-object
</code>```

what is wrong with my code????

答: Auth::user() isn't returning anything, so it flakes out when you try and access ->id

Body:
I have a simple dashboard in which users can register and do some stuff, now I would like to generate a file with username and his id; something like widget/obama2030.js in Laravel when a user is registered

my app structure:

myapp

-app
-bootstrap
-database
-resource
 .....
-widget
 -------

in my user registration controller, I have the following.

protected function create(array $data)
{
    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        ]);

    File::makeDirectory('/widget/'.$user->name.Auth::user()->id, 0755, true);

    return $user;
}

Now when user click the button register I am getting the following error

ErrorException (E_NOTICE)
Trying to get property of non-object

what is wrong with my code????


问:
Spring Cloud Gateway: map path /a to path /b
I'm starting a new Spring Boot project using Spring Cloud Gateway: I need to implement a proxy application for an existing REST API.

The proxy application will implement new features (endpoints) while forwarding to the "old" application all the requests sent to existing endoints.

(Then I'll gradually move also the existing endpoints to the new application, following an approach similar to Strangler Pattern)

But I also need to rewrite the path of several existing endpoints, something like:

```<code>return routeLocatorBuilder.routes()
    .route(p -> p
        .path("/new-endopint")
        .map("/old-endpoint") // <= is there something like 'map' method?
        .uri("http://old-app-url")).build();
</code>```

Is this possible? Is there some way to map an endpoint to another?

答:
In cloud gateway there is a org.springframework.cloud.gateway.route.RouteDefinition that can map an incoming request to an upstream by applying FilterDefinition and PredicateDefinition.

You can see how this works by having a look at org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator.

So a simple RouteDefinitionLocator e.g. InMemoryRouteDefinitionRepository could solve your use case.

If you want to stay with the high level api, then org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder.RouteSpec#predicateBuilder (org.springframework.cloud.gateway.route.builder.GatewayFilterSpec#rewritePath ...) looks promising.

```<code>return routeLocatorBuilder.routes()
    .routes()
    .route(
        p ->
            p.path("/new-endpoint/**")
                .filters(
                    spec ->
                        spec.rewritePath(
                            "/new-endpoint/(?<segment>.*)", "/old-endpoint/${segment}"))
                .uri("http://old-app-url"))
    .build();
</code>```

Body:
I'm starting a new Spring Boot project using Spring Cloud Gateway: I need to implement a proxy application for an existing REST API.

The proxy application will implement new features (endpoints) while forwarding to the "old" application all the requests sent to existing endoints.

(Then I'll gradually move also the existing endpoints to the new application, following an approach similar to Strangler Pattern)

But I also need to rewrite the path of several existing endpoints, something like:

return routeLocatorBuilder.routes()
    .route(p -> p
        .path("/new-endopint")
        .map("/old-endpoint") // <= is there something like 'map' method?
        .uri("http://old-app-url")).build();

Is this possible? Is there some way to map an endpoint to another?

Body:
In cloud gateway there is a org.springframework.cloud.gateway.route.RouteDefinition that can map an incoming request to an upstream by applying FilterDefinition and PredicateDefinition.

You can see how this works by having a look at org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator.

So a simple RouteDefinitionLocator e.g. InMemoryRouteDefinitionRepository could solve your use case.

If you want to stay with the high level api, then org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder.RouteSpec#predicateBuilder (org.springframework.cloud.gateway.route.builder.GatewayFilterSpec#rewritePath ...) looks promising.

return routeLocatorBuilder.routes()
    .routes()
    .route(
        p ->
            p.path("/new-endpoint/**")
                .filters(
                    spec ->
                        spec.rewritePath(
                            "/new-endpoint/(?<segment>.*)", "/old-endpoint/${segment}"))
                .uri("http://old-app-url"))
    .build();


问:
iPhone Fixed-Position UITableView Background
I'm building an iPhone app without the use of Interface Builder. I have set the background of a grouped UITableView in the following manor:

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"groupedBackground.png"]];

I'm trying to fix this background image so that it doesn't scroll with the table cells. Does anyone know how to do this?

答:
We find that it works exactly as you ask, if instead of using backgroundColor, you assign to backgroundView, like so:

```<code>self.tableView.backgroundView = [[UIImageView alloc] initWithImage:
                 [UIImage imageNamed:@"background.png"]];
</code>```

The table cells then scroll on top of the background, which is stationary.  (This has been available since version 3.2 of the SDK, I believe.)

ContentLicense: CC BY-SA 2.5

Body:
We find that it works exactly as you ask, if instead of using backgroundColor, you assign to backgroundView, like so:

self.tableView.backgroundView = [[UIImageView alloc] initWithImage:
                 [UIImage imageNamed:@"background.png"]];

The table cells then scroll on top of the background, which is stationary.  (This has been available since version 3.2 of the SDK, I believe.)


问:
Accessing a structure in a function type void
I've seen some other posts similar but I can't seem to figure it out. This function has this function definition:

```<code>struct number {
   int one;
   int two;
   int three;
   int four;
};

void foo(int move, struct number *f) {
//....
}

bool tester(void (*fp)(int, struct number *)) {
//...
}
</code>```

Now, in the function 'foo', my function is taking a structure (as seen), but it is changes the values in the structure (that's the purpose of this function 'foo')

Now, inside the function 'tester', I want to be able to access the new structure that 'foo' gives me when I call to it.

For example, if I had this:

```<code>struct number x1 = {1, 2, 3, 4}
</code>```

I was thinking of writing something like this is 'tester':

```<code>foo(1, &x1)
</code>```

But I have no idea how to access the new structure as a result from foo(1, &x1).

答:
I want the function to change the values in of the struct 'x1' and then access them, inside of 'tester'.

You can simply access the changed values by accessing (the now changed) x1, e. g. x1.one.

Body:
I've seen some other posts similar but I can't seem to figure it out. This function has this function definition:

struct number {
   int one;
   int two;
   int three;
   int four;
};

void foo(int move, struct number *f) {
//....
}

bool tester(void (*fp)(int, struct number *)) {
//...
}

Now, in the function 'foo', my function is taking a structure (as seen), but it is changes the values in the structure (that's the purpose of this function 'foo')

Now, inside the function 'tester', I want to be able to access the new structure that 'foo' gives me when I call to it.

For example, if I had this:

struct number x1 = {1, 2, 3, 4}

I was thinking of writing something like this is 'tester':

foo(1, &x1)

But I have no idea how to access the new structure as a result from foo(1, &x1).


问:
Where is correct place to authenticate users from multiple places?
In my first Symfony 4.4 project, I need to authenticate users from database. Unfortunately, before user sign-in I need to check user status in remote API service. If user is active in this service and credentials are same as in my database, I can authenticate user in my app.

Where is best place to check that user is active before authentication in my app? I need to create custom guard? Custom user provider?

I use Lexik JWT authentication, there is my /config/packages/security.yaml

```<code>security:
    providers:

        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        authorization:
            pattern:  ^/api/v1/auth/
            stateless: true
            anonymous: true
            json_login:
                check_path: /api/v1/auth/sign-in/
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
                username_path: email
        api:
            pattern: ^/api/v1/(user|req)/
            stateless: true
            anonymous: false
            provider: app_user_provider
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator

</code>```

答:
I haven't used Symfony after 4.1 so things might have changed recently. You just need to check.

Where is best place to check that user is active before authentication in my app? I need to create custom guard? Custom user provider?

User Provider is the answer. If you look at the UserProviderInterface it says "Internally, a user provider can load users from any source (databases, configuration, web service)."

... before user sign-in I need to check user status in remote API service. If user is active in this service and credentials are same as in my database, I can authenticate user in my app.

So what you can do is to meet your requirement:

Implement a firewall in your serurity.yaml and make it use simple_preauth.

Implement your authenticator class that goes with simple_preauth. authenticator. This wires everything up as far as the authentication goes.

Implement you user provider that calls your remote API first to check if user is active then after that, check agains your local DB so on.

Resources:

Make sure you understand the Symfony Auth flow before everything!

An example of JWT auth flow in Symfony.

There are a lot of Symfony security related examples here.

Also have a look at the Symfony Security doc where you will see plenty of info on whole subject.

Body:
In my first Symfony 4.4 project, I need to authenticate users from database. Unfortunately, before user sign-in I need to check user status in remote API service. If user is active in this service and credentials are same as in my database, I can authenticate user in my app.

Where is best place to check that user is active before authentication in my app? I need to create custom guard? Custom user provider?

I use Lexik JWT authentication, there is my /config/packages/security.yaml

security:
    providers:

        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        authorization:
            pattern:  ^/api/v1/auth/
            stateless: true
            anonymous: true
            json_login:
                check_path: /api/v1/auth/sign-in/
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
                username_path: email
        api:
            pattern: ^/api/v1/(user|req)/
            stateless: true
            anonymous: false
            provider: app_user_provider
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator


问:
p:selectOneMenu not refreshing properly when pressing F5
So before anything just to make it clear this is an issue that happens with firefox even in the showcase https://www.primefaces.org/showcase/ui/input/oneMenu.xhtml to replicate just select any value and hit f5 and the value will remain. Also check forum.primefaces.org/viewtopic.php?t=17525 for the details also check how to do autocomplete="off" at form level in JSF other solutions that didn't work for me

I have a little problem when hitting f5 to refresh page for some reason my selectOneMenu its keeping the previously selected value,I need him to have the default value or first one on the array again... any idea how can I fix this? or why does that happen? every other element of the page is succesfully reseting its value, this is the code of my selectOneMenu:

```<code><p:panel styleClass="cds-panel-reset">
                    <p:selectOneMenu id="somOrigenConsulta" tabindex="1"
                        binding="#{consultaPagoPremiosMB.somOrigenConsulta}"
                        label="Origen" widgetVar="wvSomOrigenconsulta"
                        style="width: 140px !important;">
                        <p:ajax event="change" process="somOrigenConsulta"
                            update=":accordion:tbwPagarPremio:frmConsultapagopremioscod:pnlGrdDatosConsulta
                :accordion:tbwPagarPremio:frmConsultapagopremioscod:dtbPagopremios"
                            listener="#{consultaPagoPremiosMB.mostrarDialogoOrigen()}" />
                        <f:selectItems
                            value="#{consultaPagoPremiosMB.aOrigenConsulta}" />
                        <p:ajax process="@this"
                            render=":accordion:tbwPagarPremio:frmConsultapagopremioscod:pnlGrdDatosConsulta" />
                    </p:selectOneMenu>
                </p:panel>
</code>```

Also it refreshes succesfully if I refresh by using CTRL+SHIFT+R, any idea why F5 doesn't???

could it be cache? https://www.saicharanreddy.com/whats-the-difference-between-f5-ctrlr-ctrlshiftr-ctrlf5-and-shiftf5-in-google-chrome-browser/

how can I deal with that in a selectonemenu holy..

I did some searching the problem seems to be mozilla, https://forum.primefaces.org/viewtopic.php?t=17525

But im not able to implement the autocomplete=off because it just doesn't appear to be an attribute of my selectonemenu (primefaces 7.0) please help another way to implement this

答:
The problem is firefox, it also happens in the showcase.

So I had a headache with this problem and I tried the first solution of this on the selectOneMenu but it didn't work, so I had to use javascript like this:

```<code><script type="text/javascript">
            $(document).ready(function(){
                var oneMenu = document.getElementById('accordion:tbwPagarPremio:frmConsultapagopremioscod:somOrigenConsulta_input');
                oneMenu.value="1";

                })
    </script>
</code>```

and it started having always default value 1 when I hit F5, but I'm not 100% sure if this is a good solution.

Body:
So before anything just to make it clear this is an issue that happens with firefox even in the showcase https://www.primefaces.org/showcase/ui/input/oneMenu.xhtml to replicate just select any value and hit f5 and the value will remain. Also check forum.primefaces.org/viewtopic.php?t=17525 for the details also check how to do autocomplete="off" at form level in JSF other solutions that didn't work for me

I have a little problem when hitting f5 to refresh page for some reason my selectOneMenu its keeping the previously selected value,I need him to have the default value or first one on the array again... any idea how can I fix this? or why does that happen? every other element of the page is succesfully reseting its value, this is the code of my selectOneMenu:

                        <f:selectItems
                            value="#{consultaPagoPremiosMB.aOrigenConsulta}" />

Also it refreshes succesfully if I refresh by using CTRL+SHIFT+R, any idea why F5 doesn't???

could it be cache? https://www.saicharanreddy.com/whats-the-difference-between-f5-ctrlr-ctrlshiftr-ctrlf5-and-shiftf5-in-google-chrome-browser/

how can I deal with that in a selectonemenu holy..

I did some searching the problem seems to be mozilla, https://forum.primefaces.org/viewtopic.php?t=17525

But im not able to implement the autocomplete=off because it just doesn't appear to be an attribute of my selectonemenu (primefaces 7.0) please help another way to implement this

Body:
The problem is firefox, it also happens in the showcase.

So I had a headache with this problem and I tried the first solution of this on the selectOneMenu but it didn't work, so I had to use javascript like this:

<script type="text/javascript">
            $(document).ready(function(){
                var oneMenu = document.getElementById('accordion:tbwPagarPremio:frmConsultapagopremioscod:somOrigenConsulta_input');
                oneMenu.value="1";

                })
    </script>

and it started having always default value 1 when I hit F5, but I'm not 100% sure if this is a good solution.


问:
Automatization Spring Cloud Profile
Actually have a little problem.

I want switch the url of my bootstrap.yml

It looks as follows:

```<code>spring:
  application:
    name: <project-name>
  profiles:
    active: dev
  cloud:
    config:
      uri: http://<git-repository>:8080
      fail-fast: false
</code>```

This works, but i want have an propertie or anything what can switch if are in local or another enviroment.

I try to see this documentation but dont see any work for me.

答:
I would define a bootstrap.yml file by environment.

Define a default bootstrap.yml in src/main/resources and define a specific bootstrap.yml file for each environment.

Then there are multiple ways.

Not exhaustive :

1) For each environment where the configuration file differs, run your spring boot jar by specifying the system property spring.cloud.bootstrap.location with the expected value such as :

java -jar ... -Dspring.cloud.bootstrap.location=bootstrap-dev.yml ....

That overrides the current location of that file.

2) Take advantage of Spring Boot profile feature : bootstrap.yml is compatible with.   For example if the dev profile is enabled, the bootstrap-dev.properties in the classpath will be used.

I tend to use the first way because that is more explicit for non Spring Boot users.

Source : 1.3 Changing the Location of Bootstrap Properties

Title: Automatization Spring Cloud Profile

Body:
Actually have a little problem.

I want switch the url of my bootstrap.yml

It looks as follows:

spring:
  application:
    name: <project-name>
  profiles:
    active: dev
  cloud:
    config:
      uri: http://<git-repository>:8080
      fail-fast: false

This works, but i want have an propertie or anything what can switch if are in local or another enviroment.

I try to see this documentation but dont see any work for me.


问:
How insert records into a table from another table with conditions
I'm working on a program which contains an Insert into statement, and I would like to add some conditions to it.

Let's say that the TARGET_TABLE has 2 primary key columns called A, B and 1 variable C (whose values are "NO" or "YES").

And same for the SOURCE_TABLE.

If the record in the SOURCE_TABLE does not exist in the TARGET_TABLE then insert it

If there is already a record present in the TARGET_TABLE with same values for the primary key columns, and with variable C = "NO", then update the record only if the new record has a variable C = "YES"

If there is already a record present in the TARGET_TABLE with same values for the primary key columns, and with variable C = "YES", then don't insert

Do you have some ideas? I was trying with the "where not exists" then I tried using "Case when" but I can't figure out how to mix the 3 cases in the same program...

答:
```<code>INSERT INTO TARGET_TABLE (pk, a, b)
SELECT pk, a, b
FROM SOURCE_TABLE s
WHERE NOT EXISTS (
    SELECT NULL FROM TARGET_TABLE t WHERE s.pk = t.pk
)

UPDATE t
SET b = s.b
FROM TARGET_TABLE t
    INNER JOIN SOURCE_TABLE s ON t.pk = s.pk
WHERE t.a = 'Yes'
</code>```

or if you want to be flash then

```<code>MERGE
INTO TARGET_TABLE AS t
USING SOURCE_TABLE AS s
    ON t.pk = s.pk
WHEN NOT MATCHED BY TARGET THEN
    INSERT (pk, a, b) VALUES (pk, a, b)
WHEN MATCHED AND s.a = 'yes' THEN
    UPDATE
    SET b = s.b
;
</code>```

Body:
INSERT INTO TARGET_TABLE (pk, a, b)
SELECT pk, a, b
FROM SOURCE_TABLE s
WHERE NOT EXISTS (
    SELECT NULL FROM TARGET_TABLE t WHERE s.pk = t.pk
)

UPDATE t
SET b = s.b
FROM TARGET_TABLE t
    INNER JOIN SOURCE_TABLE s ON t.pk = s.pk
WHERE t.a = 'Yes'

or if you want to be flash then

MERGE
INTO TARGET_TABLE AS t
USING SOURCE_TABLE AS s
    ON t.pk = s.pk
WHEN NOT MATCHED BY TARGET THEN
    INSERT (pk, a, b) VALUES (pk, a, b)
WHEN MATCHED AND s.a = 'yes' THEN
    UPDATE
    SET b = s.b
;


问:
How to download files from URL in Flutter and save them in iOS shared Folder?
Im pretty new to Flutter and I need a solution for the following steps:

Download a zip from an url

Extract the zip

Save the files to a shared folder in the application (iOS)

Remove the downloaded file from downloads

Thanks in advance

答:
There is a a package that will manage downloads for you called flutter_downloader: https://pub.dev/packages/flutter_downloader

There is another package that allows you to compress and decompress files called archive: https://pub.dev/packages/archive


问:
Invalid Spring @Query jpql translation to native sql when using embedded field
Given the following classe hierarchy, I am trying to query for CharacterDisposition that own a dependency on my Charakter object.

```<code>@Entity
@Table(name = "CHARACTER_DISPOSITION")
class CharacterDisposition{
    @OneToMany
    List<CharacterSlot> slots;
}

@Entity
@Table(name = "CHARACTER_SLOT")
class CharacterSlot{
    @Embedded
    SceneCharacter sceneCharacter;
}

@Embeddable
class SceneCharacter{
    @ManyToOne
    Charakter character;
}
</code>```

I am using the following jpql query within my spring repository interface,

```<code>@Query("SELECT cd "
        + "FROM CharacterDisposition cd "
        + "JOIN CharacterSlot cs "
        + "WHERE cs.sceneCharacter.character = :character")
List<CharacterDisposition> findCharacterDispositionWithCharacterDependency(Charakter character);
</code>```

The above call produces the following native sql statement

```<code>select
  characterd0_.id as id1_24_, characterd0_1_.scene_id as scene_id2_24_
from character_disposition characterd0_
    inner join character_slot characterd0_1_ on characterd0_.id=characterd0_1_.id
    inner join character_slot characters1_ on where characters1_.character_id=?
</code>```

Which is faulty because of an erroneous "on" keyword added before the final "where" statement.
I think this may have to do with my SceneCharacter being @Embedded.

I am using spring boot 2.2.1.RELEASE, hibernate and mysql 5 dialect.

答:
Try with the following -</p>

```<code>@Query("SELECT cd "
        + "FROM CharacterDisposition cd "
        + "JOIN cd.slots cs "
        + "WHERE cs.character = :character")
</code>```

Body:
Given the following classe hierarchy, I am trying to query for CharacterDisposition that own a dependency on my Charakter object.

@Entity
@Table(name = "CHARACTER_DISPOSITION")
class CharacterDisposition{
    @OneToMany
    List<CharacterSlot> slots;
}

@Entity
@Table(name = "CHARACTER_SLOT")
class CharacterSlot{
    @Embedded
    SceneCharacter sceneCharacter;
}

@Embeddable
class SceneCharacter{
    @ManyToOne
    Charakter character;
}

I am using the following jpql query within my spring repository interface,

@Query("SELECT cd "
        + "FROM CharacterDisposition cd "
        + "JOIN CharacterSlot cs "
        + "WHERE cs.sceneCharacter.character = :character")
List<CharacterDisposition> findCharacterDispositionWithCharacterDependency(Charakter character);

The above call produces the following native sql statement

select
  characterd0_.id as id1_24_, characterd0_1_.scene_id as scene_id2_24_
from character_disposition characterd0_
    inner join character_slot characterd0_1_ on characterd0_.id=characterd0_1_.id
    inner join character_slot characters1_ on where characters1_.character_id=?

Which is faulty because of an erroneous "on" keyword added before the final "where" statement.
I think this may have to do with my SceneCharacter being @Embedded.

I am using spring boot 2.2.1.RELEASE, hibernate and mysql 5 dialect.

Body:
Try with the following -

@Query("SELECT cd "
        + "FROM CharacterDisposition cd "
        + "JOIN cd.slots cs "
        + "WHERE cs.character = :character")


问:
skipping frame issue (OpenCv)
I am trying to play video on opencv. However, the program just shows the last frame of the video. Could anyone tell me why this is the case? Below is my code.

```<code>#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>

#include<iostream>
#include<conio.h>           // it may be necessary to change or remove this line if not using Windows
</code>```

using namespace cv;
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////////////
int main(void) {

```<code>cv::VideoCapture capVideo; /*add a video capture object*/

cv::Mat imgFrame; /*add  a picture object to capture each frame*/

capVideo.open("768x576.avi"); /*open the video*/

if (!capVideo.isOpened()) {                                                 // if unable to open video file
    std::cout << "\nerror reading video file" << std::endl << std::endl;      // show error message
    _getch();                    // it may be necessary to change or remove this line if not using Windows
    return(0);                                                              // and exit program
}

/*this shows the number of frame will be given*/
if (capVideo.get(CV_CAP_PROP_FRAME_COUNT) < 1) {
    std::cout << "\nerror: video file must have at least one frame";
    _getch();
    return(0);
}

/*printing out the number of frame*/
cout<<"the number of frame:" << capVideo.get(CV_CAP_PROP_FRAME_COUNT) << endl;

char* videoTitle = "this is displaying the video";
cv::namedWindow(videoTitle, WINDOW_AUTOSIZE);
capVideo.read(imgFrame); // it will return a boolean value
int i = 0;
while (1)
{
    if (capVideo.read(imgFrame) == false)
    {
        break;
    }
    imshow(videoTitle, imgFrame);
    //it read every frame of the video

    i++;
    cout << "Frame Number: " << i << endl;
}
cout << "End of the video" << endl;

waitKey(0);
return(0);
</code>```

}

答:
I will modify the while loop as follows. </p>

```<code>while (capVideo.isOpened() && chCheckForEscKey != 27) {

        imshow("imgFrame", imgFrame);// now we prepare for the next iteration

        if ((capVideo.get(CAP_PROP_POS_FRAMES) + 1) < capVideo.get(CAP_PROP_FRAME_COUNT)) {       // if there is at least one more frame
            capVideo.read(imgFrame);                            // read it
        }
        else {                                                  // else
            cout << "end of video\n";                      // show end of video message
            break;                                              // and jump out of while loop
        }

        chCheckForEscKey = waitKey(1);      // get key press in case user pressed esc

    }

    if (chCheckForEscKey != 27) {               // if the user did not press esc (i.e. we reached the end of the video)
        waitKey(0);                         // hold the windows open to allow the "end of video" message to show
    }
    // note that if the user did press esc, we don't need to hold the windows open, we can simply let the program end which will close the windows

    return(0);
}
</code>```

Title: skipping frame issue (OpenCv)

Body:
I am trying to play video on opencv. However, the program just shows the last frame of the video. Could anyone tell me why this is the case? Below is my code.

#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>

#include<iostream>
#include<conio.h>           // it may be necessary to change or remove this line if not using Windows

using namespace cv;
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////////////
int main(void) {

cv::VideoCapture capVideo; /*add a video capture object*/

cv::Mat imgFrame; /*add  a picture object to capture each frame*/

capVideo.open("768x576.avi"); /*open the video*/

if (!capVideo.isOpened()) {                                                 // if unable to open video file
    std::cout << "\nerror reading video file" << std::endl << std::endl;      // show error message
    _getch();                    // it may be necessary to change or remove this line if not using Windows
    return(0);                                                              // and exit program
}

/*this shows the number of frame will be given*/
if (capVideo.get(CV_CAP_PROP_FRAME_COUNT) < 1) {
    std::cout << "\nerror: video file must have at least one frame";
    _getch();
    return(0);
}

/*printing out the number of frame*/
cout<<"the number of frame:" << capVideo.get(CV_CAP_PROP_FRAME_COUNT) << endl;

char* videoTitle = "this is displaying the video";
cv::namedWindow(videoTitle, WINDOW_AUTOSIZE);
capVideo.read(imgFrame); // it will return a boolean value
int i = 0;
while (1)
{
    if (capVideo.read(imgFrame) == false)
    {
        break;
    }
    imshow(videoTitle, imgFrame);
    //it read every frame of the video

    i++;
    cout << "Frame Number: " << i << endl;
}
cout << "End of the video" << endl;

waitKey(0);
return(0);

}

Body:
I will modify the while loop as follows.

while (capVideo.isOpened() && chCheckForEscKey != 27) {

        imshow("imgFrame", imgFrame);// now we prepare for the next iteration

        if ((capVideo.get(CAP_PROP_POS_FRAMES) + 1) < capVideo.get(CAP_PROP_FRAME_COUNT)) {       // if there is at least one more frame
            capVideo.read(imgFrame);                            // read it
        }
        else {                                                  // else
            cout << "end of video\n";                      // show end of video message
            break;                                              // and jump out of while loop
        }

        chCheckForEscKey = waitKey(1);      // get key press in case user pressed esc

    }

    if (chCheckForEscKey != 27) {               // if the user did not press esc (i.e. we reached the end of the video)
        waitKey(0);                         // hold the windows open to allow the "end of video" message to show
    }
    // note that if the user did press esc, we don't need to hold the windows open, we can simply let the program end which will close the windows

    return(0);
}


问:
How to create and construct a class from another class in Java
Is it possible to create a class (starting from nothing) and construct/write his content from another class?

For example, I got a class StartingClass. And with the methods of this class I want to create ConstructClass (that doesn't exist yet). Inside StartingClass methods I want to specify the content of ConstructClass, like the class it extends, its attributes, its methods.

I need to do this because i need to create new classes from generated classes and unmarshalled xml datas.

I thought about editing a file with .java extension but it's not very clean.

答:
It is possible to generate classes dynamically using Java. Javassist is one way to do it. Cglib is another way; there's ASM too and I'm sure there are a few more. However, I'd suggest you to rethink why you need to do this. It's not recommended to do this, because Java is a static language. Are you sure it's the best one to use for your use case? And also, dynamic classes heavily depend on the use of Object and reflection in order for them to work.

If you have any clue what your classes might be like, something like a factory pattern can help you much more to process the XML files. Or else perhaps use an Object[] or Map<Object, Object>

If you must, try looking into Javassist or cglib like solutions.


问:
Objects and copy ctors created without RVO in C++
I am new to C++. Please consider the following code:

```<code>class foo
{
 int f;

 public:
   foo(int f1=0) : f(f1) {
   cout<<"In conversion ctor\n";
 }

foo(const foo & rhs) : f(rhs.f)
{
    cout<<" In copy ctor\n";
}

 foo& operator=(const foo & that)
{
    f=that.f;
    cout<<"In = optor\n";
    return *this;
}

};

 foo rbv()
  {
    foo obj(9);
    return obj;                        //named return by value [def. 1]
  }

   foo caller()
   {
      return rbv();              // return by value [def. 2]
   }

int main(void)
{
   foo box=caller();
   return 0;
 }
</code>```

Are the definitions for RBV and NRBV correct as indicated in the
comments?

Is it mandatory to have an accessible copy ctor defined though it
is not called during RVO?

Without RVO, in the code blocks

```<code>   foo rbv()
    {
     foo obj(9);
     return obj;
    }

    foo ret= rbv();
</code>```

Are the following steps correct in creation of 'ret'

(1) a temporary ( say obj_temp) is created using copy ctor from obj,
 stack object 'obj' destroyed,

(2) ret is copy constructed from obj_temp, obj_temp destroyed later;

which implies there are three objects, 'obj' , 'obj_temp' and 'ret' and two copy ctors involved.

答:
Looks right to me.

You have to have an accessible copy constructor defined if you are going to copy objects.  Even if the copy can be optimized away.

That sounds right to me, though the precise ordering might be implementation defined.  You would have to

Body:
I am new to C++. Please consider the following code:

class foo
{
 int f;

 public:
   foo(int f1=0) : f(f1) {
   cout<<"In conversion ctor\n";
 }

foo(const foo & rhs) : f(rhs.f)
{
    cout<<" In copy ctor\n";
}

 foo& operator=(const foo & that)
{
    f=that.f;
    cout<<"In = optor\n";
    return *this;
}

};

 foo rbv()
  {
    foo obj(9);
    return obj;                        //named return by value [def. 1]
  }

   foo caller()
   {
      return rbv();              // return by value [def. 2]
   }

int main(void)
{
   foo box=caller();
   return 0;
 }

Are the definitions for RBV and NRBV correct as indicated in the
comments?

Is it mandatory to have an accessible copy ctor defined though it
is not called during RVO?

Without RVO, in the code blocks

   foo rbv()
    {
     foo obj(9);
     return obj;
    }

    foo ret= rbv();

Are the following steps correct in creation of 'ret'

(1) a temporary ( say obj_temp) is created using copy ctor from obj,
 stack object 'obj' destroyed,

(2) ret is copy constructed from obj_temp, obj_temp destroyed later;

which implies there are three objects, 'obj' , 'obj_temp' and 'ret' and two copy ctors involved.


问:
How to search for a needle in multi-dimensional array in php?
I have some different type of php arrays which can have sensitive data at any level of nesting. I want to unset this sensitive keys. How should I go about this?

For e.g. sensitive data keys can be account_no, acc_no etc

Sample request array1:

```<code>[
    'ClientCode'   => "abcom",
    'MerchantCode' => "Code1",
    'acc_no'       =>  "12345"
]
</code>```

This array should become

```<code>[
    'ClientCode'   =>  "abcom"
    'MerchantCode' =>  "Code1"

]
</code>```

Sample request array2:

```<code>  [
      'customer_name' => "Umesh",
      'age' => 24,
      'customer_details' => [
          'mob_no' => "989729069",
          'account_no' => '1235'
      ]
  ]
</code>```

This array should become

```<code>[
      'customer_name' => "Umesh",
      'age'           => 24,
      'customer_details' => [
          'mob_no' => "989729069"
      ]
]
</code>```

答:
The best solution for any level of nesting is a recursive function:</p>

```<code>$your_array = array(
  'client'  => '1234',
  'acc_no'  => '12345',
  'test'    => array(
    'acc_no'  => '12',
    'acc'    => '12345'
  )
);

function unset_sensitive_keys( &$array, $delete_keys )  {
  foreach( $array as $key => &$value ) {
    if( is_array( $value ) )  {
      unset_sensitive_keys( $value, $delete_keys );
    } else {
      if( in_array( $key, $delete_keys )  ) {
        unset($array[$key]);
      }
    }
  }
}

unset_sensitive_keys( $your_array, array( 'acc_no', 'account_no' ) );
</code>```

Body:
I have some different type of php arrays which can have sensitive data at any level of nesting. I want to unset this sensitive keys. How should I go about this?

For e.g. sensitive data keys can be account_no, acc_no etc

Sample request array1:

[
    'ClientCode'   => "abcom",
    'MerchantCode' => "Code1",
    'acc_no'       =>  "12345"
]

This array should become

[
    'ClientCode'   =>  "abcom"
    'MerchantCode' =>  "Code1"

]

Sample request array2:

  [
      'customer_name' => "Umesh",
      'age' => 24,
      'customer_details' => [
          'mob_no' => "989729069",
          'account_no' => '1235'
      ]
  ]

This array should become

[
      'customer_name' => "Umesh",
      'age'           => 24,
      'customer_details' => [
          'mob_no' => "989729069"
      ]
]

Body:
The best solution for any level of nesting is a recursive function:

$your_array = array(
  'client'  => '1234',
  'acc_no'  => '12345',
  'test'    => array(
    'acc_no'  => '12',
    'acc'    => '12345'
  )
);

function unset_sensitive_keys( &$array, $delete_keys )  {
  foreach( $array as $key => &$value ) {
    if( is_array( $value ) )  {
      unset_sensitive_keys( $value, $delete_keys );
    } else {
      if( in_array( $key, $delete_keys )  ) {
        unset($array[$key]);
      }
    }
  }
}

unset_sensitive_keys( $your_array, array( 'acc_no', 'account_no' ) );


问:
Why is the Facebook login modal not prompting users for access to their email address?
I'm trying to integrate the Facebook login flow into a website (as per this page: https://developers.facebook.com/docs/facebook-login/web), and I'm having issues with trying to force the login modal to request access to the user's Facebook email address.

Specifically, I'm executing the following code from my JS:

```<code>FB.login((response) => {
    if (response.status === 'connected' &&
        response.authResponse) {
        // Do something with the response here.
    }
}, {
    scope: 'email',
    return_scopes: true
});
</code>```

The response is coming back as connected when the user successfully logs in, and I am getting the user's user ID, access token, etc., but when they click on the button in my UI that calls FB.login, the modal that pops up for Facebook does not ask the user if they want to grant access to their email address. Why?

For the site I'm building, I need access to the user's Facebook email address. If they were to be asked and deny access, that's one thing, but the modal that pops up isn't even asking them for access to their email address, and I don't get their email address back in the response.

Furthermore, if I make a subsequent call to the following, the email permission comes back as declined:

```<code>FB.api(`/${response.authResponse.userID}/permissions`, (response) => {
    console.log(response);
});
</code>```

Does anyone know why I can't prompt the user for access to their email address? Thanks.

Edit: It might be worth mentioning that I'm testing this on localhost, and I wonder if that's having an effect. In the Facebook for Developers dashboard, I did set my localhost virtual host (e.g., site-name.test) as an allowed URL for redirects, and it does let me log in with Facebook and get the user ID, etc., but it just never prompts the user for access to their email address. Thanks.

答:
Thanks again to misorude for the answer. Without that, I would have never figured this out. To sum everything up, the problem was that during testing, I had apparently already once declined the request to provide access to my email address, and after that, it no longer asked me for permission to access it.

As such, you have to pass an extra parameter to FB.login in order to force it to re-ask the user for access to their email address. Specifically, it's the authType parameter, and here's how you pass it:

```<code>FB.login((response) => {
    if (response.status === 'connected' &&
        response.authResponse) {
        // Do something with the response here.
    }
}, {
    scope: 'email',
    authType: 'rerequest'
});
</code>```

That will give you access to the email address (assuming a user has one registered; again, thanks to misorude for noting that), but it doesn't actually return the email address. To get that, you then have to send an API request to /me with a fields parameter requesting the email address to get it. I figured out how to get that via the following SO answer: https://stackoverflow.com/a/31763373/1992973

Specifically, a full solution is something like the following:

```<code>FB.login((response) => {
    if (response.status === 'connected' &&
        response.authResponse) {
        FB.api('/me?fields=email', (response) => {
            // The email should be in the response, assuming the user has one registered with FB.
        });
    }
}, {
    scope: 'email',
    authType: 'rerequest'
});
</code>```

Body:
I'm trying to integrate the Facebook login flow into a website (as per this page: https://developers.facebook.com/docs/facebook-login/web), and I'm having issues with trying to force the login modal to request access to the user's Facebook email address.

Specifically, I'm executing the following code from my JS:

FB.login((response) => {
    if (response.status === 'connected' &&
        response.authResponse) {
        // Do something with the response here.
    }
}, {
    scope: 'email',
    return_scopes: true
});

The response is coming back as connected when the user successfully logs in, and I am getting the user's user ID, access token, etc., but when they click on the button in my UI that calls FB.login, the modal that pops up for Facebook does not ask the user if they want to grant access to their email address. Why?

For the site I'm building, I need access to the user's Facebook email address. If they were to be asked and deny access, that's one thing, but the modal that pops up isn't even asking them for access to their email address, and I don't get their email address back in the response.

Furthermore, if I make a subsequent call to the following, the email permission comes back as declined:

FB.api(`/${response.authResponse.userID}/permissions`, (response) => {
    console.log(response);
});

Does anyone know why I can't prompt the user for access to their email address? Thanks.

Edit: It might be worth mentioning that I'm testing this on localhost, and I wonder if that's having an effect. In the Facebook for Developers dashboard, I did set my localhost virtual host (e.g., site-name.test) as an allowed URL for redirects, and it does let me log in with Facebook and get the user ID, etc., but it just never prompts the user for access to their email address. Thanks.

Body:
Thanks again to misorude for the answer. Without that, I would have never figured this out. To sum everything up, the problem was that during testing, I had apparently already once declined the request to provide access to my email address, and after that, it no longer asked me for permission to access it.

As such, you have to pass an extra parameter to FB.login in order to force it to re-ask the user for access to their email address. Specifically, it's the authType parameter, and here's how you pass it:

FB.login((response) => {
    if (response.status === 'connected' &&
        response.authResponse) {
        // Do something with the response here.
    }
}, {
    scope: 'email',
    authType: 'rerequest'
});

That will give you access to the email address (assuming a user has one registered; again, thanks to misorude for noting that), but it doesn't actually return the email address. To get that, you then have to send an API request to /me with a fields parameter requesting the email address to get it. I figured out how to get that via the following SO answer: https://stackoverflow.com/a/31763373/1992973

Specifically, a full solution is something like the following:

FB.login((response) => {
    if (response.status === 'connected' &&
        response.authResponse) {
        FB.api('/me?fields=email', (response) => {
            // The email should be in the response, assuming the user has one registered with FB.
        });
    }
}, {
    scope: 'email',
    authType: 'rerequest'
});


问:
How can I customize Devise to send password reset emails using PostMark mailer
I'm trying to get all of my system's email notifications under one umbrella using PostMarkApp and utilizing the Rails gems (postmark-rails, postmark-gem, and mail). I have successfully created a mailer that handles sending receipts for purchases but I haven't been able to receive emails for forgotten passwords. My development logs show that Devise sent the message but no email is received in my inbox and the PostMark credits are not decremented.

What's the best or easiest way to have Devise's mailers send through my PostMark account?

Snippet from config/environments/development.rb

```<code>config.action_mailer.delivery_method      = :postmark
config.action_mailer.postmark_settings    = { :api_key => "VALID_API_KEY_WAS_HERE" }
config.postmark_signature                 = VALID_POSTMARK_SIGNATURE_WAS_HERE
</code>```

My Mailer that uses Postmark

```<code>class Notifier < ActionMailer::Base
  # set some sensible defaults
  default :from => MyApp::Application.config.postmark_signature

  def receipt_message(order)
    @order = order
    @billing_address = order.convert_billing_address_to_hash(order.billing_address)

    mail(:to => @order.user.email, :subject => "Your Order Receipt", :tag => 'order-receipt', :content_type => "text/html") do |format|
      format.html
    end
  end
end
</code>```

EDIT: SOLUTION to my question is below

Solved it by having my Notifier mailer extend Devise::Mailer and specifying Devise to use my Notifier as the mailer within config/initializers/devise.rb

snippet from config/initializers/devise.rb

```<code># Configure the class responsible to send e-mails.
config.mailer = "Notifier"
</code>```

My Notifier Mailer now

```<code>class Notifier < Devise::Mailer
  # set some sensible defaults
  default :from => MyApp::Application.config.postmark_signature

  # send a receipt of the Member's purchase
  def receipt_message(order)
    @order = order
    @billing_address = order.convert_billing_address_to_hash(order.billing_address)

    mail(:to => @order.user.email, :subject => "Your Order Receipt", :tag => 'order-receipt', :content_type => "text/html") do |format|
      format.html
    end
  end

  # send password reset instructions
  def reset_password_instructions(user)
     @resource = user
     mail(:to => @resource.email, :subject => "Reset password instructions", :tag => 'password-reset', :content_type => "text/html") do |format|
       format.html { render "devise/mailer/reset_password_instructions" }
     end
   end
end
</code>```

答:
I also had to generate the views for devise and copy the mail templates into the right place for my mailer.  Something like this - </p>

```<code>rails generate devise:views
cp app/views/devise/mailer/* app/views/notification_mailer/
</code>```

Body:
I'm trying to get all of my system's email notifications under one umbrella using PostMarkApp and utilizing the Rails gems (postmark-rails, postmark-gem, and mail). I have successfully created a mailer that handles sending receipts for purchases but I haven't been able to receive emails for forgotten passwords. My development logs show that Devise sent the message but no email is received in my inbox and the PostMark credits are not decremented.

What's the best or easiest way to have Devise's mailers send through my PostMark account?

Snippet from config/environments/development.rb

config.action_mailer.delivery_method      = :postmark
config.action_mailer.postmark_settings    = { :api_key => "VALID_API_KEY_WAS_HERE" }
config.postmark_signature                 = VALID_POSTMARK_SIGNATURE_WAS_HERE

My Mailer that uses Postmark

class Notifier < ActionMailer::Base
  # set some sensible defaults
  default :from => MyApp::Application.config.postmark_signature

  def receipt_message(order)
    @order = order
    @billing_address = order.convert_billing_address_to_hash(order.billing_address)

    mail(:to => @order.user.email, :subject => "Your Order Receipt", :tag => 'order-receipt', :content_type => "text/html") do |format|
      format.html
    end
  end
end

EDIT: SOLUTION to my question is below

Solved it by having my Notifier mailer extend Devise::Mailer and specifying Devise to use my Notifier as the mailer within config/initializers/devise.rb

snippet from config/initializers/devise.rb

# Configure the class responsible to send e-mails.
config.mailer = "Notifier"

My Notifier Mailer now

class Notifier < Devise::Mailer
  # set some sensible defaults
  default :from => MyApp::Application.config.postmark_signature

  # send a receipt of the Member's purchase
  def receipt_message(order)
    @order = order
    @billing_address = order.convert_billing_address_to_hash(order.billing_address)

    mail(:to => @order.user.email, :subject => "Your Order Receipt", :tag => 'order-receipt', :content_type => "text/html") do |format|
      format.html
    end
  end

  # send password reset instructions
  def reset_password_instructions(user)
     @resource = user
     mail(:to => @resource.email, :subject => "Reset password instructions", :tag => 'password-reset', :content_type => "text/html") do |format|
       format.html { render "devise/mailer/reset_password_instructions" }
     end
   end
end

Body:
I also had to generate the views for devise and copy the mail templates into the right place for my mailer.  Something like this -

rails generate devise:views
cp app/views/devise/mailer/* app/views/notification_mailer/


问:
How to get CSV integers read as integers from a string variable
I have a string that I get from sanitizing some values from an xml file.

```<code>$resolutions=strip_tags($resolutions,allow);  // gives me '75 75 300 300 600 600'
</code>```

Then I change the spaces to commas:

```<code>$resolutions = preg_replace('#\s+#',',',trim($resolutions)); // gives me '75,75,300,300,600,600'
</code>```

Then I take that and want to extract min and max values like this

```<code>$resolution_min = min($resolutions);
</code>```

on the page for display

```<code>echo $resolution_min; // still gives me '75,75,300,300,600,600'
</code>```

However when I  change the code where I want it displayed on the page

```<code> echo min(75,75,300,300,600,600);  // it displays '75' as it should
</code>```

I think, the issue is that the CSV values are being interpreted as a single text string and I need them read as CSV integer values.

Is there some way to force these to be read as numeric values by min and max?

I think part of my problem comes from this line or a line like it, jus befor an "explode" command

```<code>$list = "" . substr($scansupportedresolutions, $start,$length) . "";
</code>```

I have never seen this kind of double double quote dot and dot double double quote and have no idea what it means

Is it simply saying the entire string in $list will be

```<code>".<CONTENT HERE>."
</code>```

but specifically in double quotes? Whatever it is i seems crucial to the explode command.

答:
From min:

If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.

You are passing one parameter and it's a string.  Pass an array:

```<code>$resolutions = explode(',', $resolutions);
$resolution_min = min($resolutions);
</code>```

Body:
I have a string that I get from sanitizing some values from an xml file.

$resolutions=strip_tags($resolutions,allow);  // gives me '75 75 300 300 600 600'

Then I change the spaces to commas:

$resolutions = preg_replace('#\s+#',',',trim($resolutions)); // gives me '75,75,300,300,600,600'

Then I take that and want to extract min and max values like this

$resolution_min = min($resolutions);

on the page for display

echo $resolution_min; // still gives me '75,75,300,300,600,600'

However when I  change the code where I want it displayed on the page

 echo min(75,75,300,300,600,600);  // it displays '75' as it should

I think, the issue is that the CSV values are being interpreted as a single text string and I need them read as CSV integer values.

Is there some way to force these to be read as numeric values by min and max?

I think part of my problem comes from this line or a line like it, jus befor an "explode" command

$list = "" . substr($scansupportedresolutions, $start,$length) . "";

I have never seen this kind of double double quote dot and dot double double quote and have no idea what it means

Is it simply saying the entire string in $list will be

".<CONTENT HERE>."

but specifically in double quotes? Whatever it is i seems crucial to the explode command.

Body:
From min:

If the first and only parameter is an array, min() returns the lowest value in that array. If at least two parameters are provided, min() returns the smallest of these values.

You are passing one parameter and it's a string.  Pass an array:

$resolutions = explode(',', $resolutions);
$resolution_min = min($resolutions);


问:
EntityFramework Maps Float to Int
This happens when mapping a stored procedure that pulls data from a table that defines one the fields as 'float'

If I ignore this issue, I end up with the following error:

The 'FieldName' property on 'EOST_GetSome_Result' could not be set to a 'System.Double' value. You must set this property to a non-null value of type 'System.Int32'.

Mapped field:

```<code>   public Nullable<int> FieldName { get; set; }
</code>```

Changing float to int at the database level is not an option, so how to handle this situation at the application level?

答:
I realize this is five years later, but I just ran into exactly this situation yesterday, or at least this error message. Here's what I discovered.

I have a view that combines the results of two other views. The C# model that maps to this view clearly says that my property is an integer, and the "union" view as we'll call it, shows that the column type is an "int" in SSMS. However, the "left" and "right" views that it combines each say that the column is a float for some reason. It's possibly because there's an ISNULL operation going on over the original integer value... I'm not sure.

Anyway, the two sub-views have a column that SQL has, for some unknown reason, decided to think of as a float. They get combined together in a third view that seems to understand that we're expecting an integer. At runtime, however, I think the result is being returned to Entity Framework as a float rather than an int, and this makes EF sad, so it throws this error.

Solution:
I added a CAST(<stuff> AS INT) in each of the two sub-views, and the problem went away.

Title: EntityFramework Maps Float to Int

Body:
This happens when mapping a stored procedure that pulls data from a table that defines one the fields as 'float'

If I ignore this issue, I end up with the following error:

The 'FieldName' property on 'EOST_GetSome_Result' could not be set to a 'System.Double' value. You must set this property to a non-null value of type 'System.Int32'.

Mapped field:

   public Nullable<int> FieldName { get; set; }

Changing float to int at the database level is not an option, so how to handle this situation at the application level?


问:
How to test a checkbox is checked in angular unit test
Hi there I am using a checkbox to be pretend as a toggle button with the help of CSS. The function is simple when the checkbox is true it enables the toggle button and vice versa. I want to check that in my unit test. I know I'm missing something on the below code. Any help would be appreciated

Test

```<code>it('should toggle switch to on if user response equals true', fakeAsync(() => {
    spectator.get(service).user.and.returnValue({});
    spyOn(spectator.get(serivce2), 'method').and.returnValue({Payload: {success: true}});
    tick();
    spectator.detectChanges();
    expect(spectator.query('.toggle-button').getAttribute('checked')).toBeTruthy();
}));
</code>```

答:
try this  by getting the nativeElement

```<code>expect(spectator.query('.toggle-button').nativeElement.getAttribute('checked')).toBeTruthy();
</code>```

Body:
Hi there I am using a checkbox to be pretend as a toggle button with the help of CSS. The function is simple when the checkbox is true it enables the toggle button and vice versa. I want to check that in my unit test. I know I'm missing something on the below code. Any help would be appreciated

Test

it('should toggle switch to on if user response equals true', fakeAsync(() => {
    spectator.get(service).user.and.returnValue({});
    spyOn(spectator.get(serivce2), 'method').and.returnValue({Payload: {success: true}});
    tick();
    spectator.detectChanges();
    expect(spectator.query('.toggle-button').getAttribute('checked')).toBeTruthy();
}));

Body:
try this  by getting the nativeElement

expect(spectator.query('.toggle-button').nativeElement.getAttribute('checked')).toBeTruthy();


问:
How to loop over jq unique array in bash?
I'm trying to loop over unique names and commit messages from a github json object.  However when there are spaces in the arrays bash will treat them as individual array items

```<code>#!/usr/bin/env bash

commits='[
  {
    "author": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "committer": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "message": "commit message 1"
  },
  {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 2"
  },
    {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 3"
  }
]'

authors=$( jq -rc '[.[].author.name] | unique | @sh' <<<"${commits}" )
echo "authors: $authors"

# this works
for author in $authors
do
  echo "author: $author"
done

echo "------------"

# this does not
messages=$( jq -rc '[.[].message] | unique | @sh' <<<"${commits}" )
echo "messages: $messages"

for message in $messages
do
  echo "message: $message"
done
</code>```

Which outputs

```<code>authors: 'Chris' 'John'
author: 'Chris'
author: 'John'
------------
messages: 'commit message 1' 'commit message 2' 'commit message 3'
message: 'commit
message: message
message: 1'
message: 'commit
message: message
message: 2'
message: 'commit
message: message
message: 3'
</code>```

While I expect:

```<code>authors: 'Chris' 'John'
author: 'Chris'
author: 'John'
------------
messages: 'commit message 1' 'commit message 2' 'commit message 3'
message: 'commit message 1'
message: 'commit message 2'
message: 'commit message 3'
</code>```

答:
Use readarray (Bash 4+) to map null delimited output from jq:

#!/usr/bin/env bash

commits='[
  {
    "author": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "committer": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "message": "commit message 1"
  },
  {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 2"
  },
    {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 3"
  }
]'

readarray -d '' authors < <(jq -j '.[].author.name + "\u0000"' <<<"${commits}")

for author in "${authors[@]}"
do
  echo "author: $author"
done

echo "------------"

readarray -d '' messages < <(jq -j '.[].message + "\u0000"' <<<"${commits}")

for message in "${messages[@]}"
do
  echo "message: $message"
done
```

<p>Alternatively, if you have an older Bash version without <code>readarray</code> or <code>mapfile</code> you may separate the strings with the ASCII control character ETX (End of TeXt <code>03</code>) and use <code>read</code> instead like this:</p>

<pre class="lang-sh prettyprint-override"><code>IFS=$'\03' read -d '' -ra authors < <(jq -j '.[].author.name + "\u0003"' <<<"${commits}")

IFS=$'\03' read -d '' -ra messages < <(jq -j '.[].message + "\u0003"' <<<"${commits}")
</code>```

It is also possible to populate both arrays from a single jq call:

# Populates both arrays from a single jq call
{
  IFS=$'\03' read -r -d '' -a authors
  IFS=$'\03' read -r -d '' -a messages
} < <(jq -j '([.[].author.name] | unique | .[] + "\u0003"), "\u0000",  ([.[].message] | unique | .[] + "\u0003")' <<<"${commits}")
```

<p>Explanation:</p>

<ul>
<li><p><code>[.[].author.name] | unique | .[] + "\u0003"</code>:<br>
Output an <code>ETX (03)</code> delimited list of unique author names.</p></li>
<li><p><code>"\u0000"</code>: insert a null delimiter</p></li>
<li><p><code>[.[].message] | unique | .[] + "\u0003"</code>:<br>
Output an <code>ETX (03)</code> delimited list of unique messages.</p></li>
<li><p>Feeds the whole output of <code>jq</code> to a command group with two <code>read</code> commands.<br>
Each <code>read</code> will stop at the null delimiter or end of the stream.  </p></li>
</ul>

<pre class="lang-sh prettyprint-override"><code>{
  IFS=$'\03' read -r -d '' -a authors
  IFS=$'\03' read -r -d '' -a messages
}
</code>```

Body:
I'm trying to loop over unique names and commit messages from a github json object.  However when there are spaces in the arrays bash will treat them as individual array items

#!/usr/bin/env bash

commits='[
  {
    "author": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "committer": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "message": "commit message 1"
  },
  {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 2"
  },
    {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 3"
  }
]'

authors=$( jq -rc '[.[].author.name] | unique | @sh' <<<"${commits}" )
echo "authors: $authors"

# this works
for author in $authors
do
  echo "author: $author"
done

echo "------------"

# this does not
messages=$( jq -rc '[.[].message] | unique | @sh' <<<"${commits}" )
echo "messages: $messages"

for message in $messages
do
  echo "message: $message"
done

Which outputs

authors: 'Chris' 'John'
author: 'Chris'
author: 'John'
------------
messages: 'commit message 1' 'commit message 2' 'commit message 3'
message: 'commit
message: message
message: 1'
message: 'commit
message: message
message: 2'
message: 'commit
message: message
message: 3'

While I expect:

authors: 'Chris' 'John'
author: 'Chris'
author: 'John'
------------
messages: 'commit message 1' 'commit message 2' 'commit message 3'
message: 'commit message 1'
message: 'commit message 2'
message: 'commit message 3'

Body:
Use readarray (Bash 4+) to map null delimited output from jq:

#!/usr/bin/env bash

commits='[
  {
    "author": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "committer": {
      "email": "email@example.com",
      "name": "Chris",
      "username": "chris"
    },
    "message": "commit message 1"
  },
  {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 2"
  },
    {
    "author": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "committer": {
      "email": "email@example.com",
      "name": "John",
      "username": "jdoe"
    },
    "message": "commit message 3"
  }
]'

readarray -d '' authors < <(jq -j '.[].author.name + "\u0000"' <<<"${commits}")

for author in "${authors[@]}"
do
  echo "author: $author"
done

echo "------------"

readarray -d '' messages < <(jq -j '.[].message + "\u0000"' <<<"${commits}")

for message in "${messages[@]}"
do
  echo "message: $message"
done

Alternatively, if you have an older Bash version without readarray or mapfile you may separate the strings with the ASCII control character ETX (End of TeXt 03) and use read instead like this:

IFS=$'\03' read -d '' -ra authors < <(jq -j '.[].author.name + "\u0003"' <<<"${commits}")

IFS=$'\03' read -d '' -ra messages < <(jq -j '.[].message + "\u0003"' <<<"${commits}")

It is also possible to populate both arrays from a single jq call:

# Populates both arrays from a single jq call
{
  IFS=$'\03' read -r -d '' -a authors
  IFS=$'\03' read -r -d '' -a messages
} < <(jq -j '([.[].author.name] | unique | .[] + "\u0003"), "\u0000",  ([.[].message] | unique | .[] + "\u0003")' <<<"${commits}")

Explanation:

[.[].author.name] | unique | .[] + "\u0003":

Output an ETX (03) delimited list of unique author names.

"\u0000": insert a null delimiter

[.[].message] | unique | .[] + "\u0003":

Output an ETX (03) delimited list of unique messages.

Feeds the whole output of jq to a command group with two read commands.

Each read will stop at the null delimiter or end of the stream.

{
  IFS=$'\03' read -r -d '' -a authors
  IFS=$'\03' read -r -d '' -a messages
}