问:
VHDL: can't infer register for "c[0]" because its behavior does not match any supported register model
Hi I'm having problems with this one. this is supposed to be a counter that recives signals from two ports, a incriases it by one with a maximum of 30 and b decreases it by one with a maximum of 0, if the counter is at 30 the output should be x <= 0 and y <=1, otherwise x<=1 and y<=0. What am i doing wrong? Is it a good idea to use an integer for the cariable? This is my code, sorry if it looks dumb this is my first semester with VHDL

```<code>Library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;

entity contador is
    port (a, b : in std_logic;
          x, y : out std_logic);

end entity;

architecture func of contador is

begin
    process(a,b)
        variable c : integer := 0;
    begin
        if rising_edge(a) then
            if c<31 then
                c := c+1;
            end if;
        end if;
        if rising_edge(b) then
            if c>0 then
                c := c-1;
            end if;
        end if;

        if c = 30 then
            x <= '0';
            y <= '1';
        else
            x <= '1';
            y <= '0';
        end if;

    end process;

end func;
</code>```

Error message:

Error (10821): HDL error at contador.vhd(22): can't infer register for "c[0]" because its behavior does not match any supported register model

Error (10821): HDL error at contador.vhd(22): can't infer register for "c[1]" because its behavior does not match any supported register model

.

.

.

Error (10821): HDL error at contador.vhd(22): can't infer register for "c[18]" because its behavior does not match any supported register model

Error (12153): Can't elaborate top-level user hierarchy

Error: Quartus II 64-Bit Analysis & Synthesis was unsuccessful. 20 errors, 4 warnings
    Error: Peak virtual memory: 4629 megabytes
    Error: Processing ended: Mon Jun 01 17:16:02 2020
    Error: Elapsed time: 00:00:02
    Error: Total CPU time (on all processors): 00:00:02
Error (293001): Quartus II Full Compilation was unsuccessful. 22 errors, 4 warnings

答:
Well first you haven't explained what exactly your input signals are and how they behave, which is very important.
Second, what you are basically doing is trying to implement a register with 2 clocks, in other words doing more than 1 clocked condition in a single process, the development tools usually don't like it and will warn you about it.

Also, you haven't specified the range of your variable.
Although most likely that the synthesis tool will ignore the unused bits,it is still good practice to exactly specify the range of your signals/variables.
Like so:

```<code>variable c : integer range 0 to 32 := 0;
</code>```

Your code can still be simulated or maybe even synthesized and i'm not sure why you are getting this error. You should put your exact error massage.

I think that most likely is that the device you are using in Quartus does not have the building block to support a 2 clocked input therefore you have the error that you are getting.

Try to create a separate process for each input, a and b, and then combine them with some logic.

Also, i made a small change in your code, try it and maybe it will help:

```<code>Library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;

entity contador is
port (a, b : in std_logic;
      x, y : out std_logic);

end entity;

architecture func of contador is

 begin
  process(a,b)
      variable c : integer range 0 to 32 := 0;
  begin
    if rising_edge(a) then
        if c<31 then
            c := c+1;
        end if;
    elsif rising_edge(b) then
        if c>0 then
            c := c-1;
        end if;
    end if;

    if c = 30 then
        x <= '0';
        y <= '1';
    else
        x <= '1';
        y <= '0';
    end if;

end process;

end func;
</code>```

Body:
Hi I'm having problems with this one. this is supposed to be a counter that recives signals from two ports, a incriases it by one with a maximum of 30 and b decreases it by one with a maximum of 0, if the counter is at 30 the output should be x <= 0 and y <=1, otherwise x<=1 and y<=0. What am i doing wrong? Is it a good idea to use an integer for the cariable? This is my code, sorry if it looks dumb this is my first semester with VHDL

Library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;

entity contador is
    port (a, b : in std_logic;
          x, y : out std_logic);

end entity;

architecture func of contador is

begin
    process(a,b)
        variable c : integer := 0;
    begin
        if rising_edge(a) then
            if c<31 then
                c := c+1;
            end if;
        end if;
        if rising_edge(b) then
            if c>0 then
                c := c-1;
            end if;
        end if;

        if c = 30 then
            x <= '0';
            y <= '1';
        else
            x <= '1';
            y <= '0';
        end if;

    end process;

end func;

Error message:

Error (10821): HDL error at contador.vhd(22): can't infer register for "c[0]" because its behavior does not match any supported register model

Error (10821): HDL error at contador.vhd(22): can't infer register for "c[1]" because its behavior does not match any supported register model

.

.

.

Error (10821): HDL error at contador.vhd(22): can't infer register for "c[18]" because its behavior does not match any supported register model

Error (12153): Can't elaborate top-level user hierarchy

Error: Quartus II 64-Bit Analysis & Synthesis was unsuccessful. 20 errors, 4 warnings
    Error: Peak virtual memory: 4629 megabytes
    Error: Processing ended: Mon Jun 01 17:16:02 2020
    Error: Elapsed time: 00:00:02
    Error: Total CPU time (on all processors): 00:00:02
Error (293001): Quartus II Full Compilation was unsuccessful. 22 errors, 4 warnings

Body:
Well first you haven't explained what exactly your input signals are and how they behave, which is very important.
Second, what you are basically doing is trying to implement a register with 2 clocks, in other words doing more than 1 clocked condition in a single process, the development tools usually don't like it and will warn you about it.

Also, you haven't specified the range of your variable.
Although most likely that the synthesis tool will ignore the unused bits,it is still good practice to exactly specify the range of your signals/variables.
Like so:

variable c : integer range 0 to 32 := 0;

Your code can still be simulated or maybe even synthesized and i'm not sure why you are getting this error. You should put your exact error massage.

I think that most likely is that the device you are using in Quartus does not have the building block to support a 2 clocked input therefore you have the error that you are getting.

Try to create a separate process for each input, a and b, and then combine them with some logic.

Also, i made a small change in your code, try it and maybe it will help:

Library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;

entity contador is
port (a, b : in std_logic;
      x, y : out std_logic);

end entity;

architecture func of contador is

 begin
  process(a,b)
      variable c : integer range 0 to 32 := 0;
  begin
    if rising_edge(a) then
        if c<31 then
            c := c+1;
        end if;
    elsif rising_edge(b) then
        if c>0 then
            c := c-1;
        end if;
    end if;

    if c = 30 then
        x <= '0';
        y <= '1';
    else
        x <= '1';
        y <= '0';
    end if;

end process;

end func;


来源: stackexchange

问:
Python FuzzyWuzzy ratio: how does it work?
Inside the FuzzyWuzzy ratio description it says:

The FuzzyWuzzy ratio raw score is a measure of the strings similarity as an int in the range [0, 100]. For two strings X and Y, the score is defined by int(round((2.0 * M / T) * 100)) where T is the total number of characters in both strings, and M is the number of matches in the two strings. The FuzzyWuzzy ratio sim score is a float in the range [0, 1] and is obtained by dividing the raw score by 100.

Then how come this score appears to be different when I change the order of the words?

```<code> from fuzzywuzzy import fuzz

 fuzz.ratio('EMRE MERT', 'OMER CAN') / 100 = 0.35

 fuzz.ratio('EMRE MERT', 'CAN OMER') / 100 = 0.47
</code>```

答:
The definition you're using comes from the Ratio function in the py_stringmatching module, but the function you're using is from the fuzzywuzzy module which uses the Levenshtein distance.

From the recursive implementation of Levenshtein you can see that the algorithm considers the strings character-by-character, and so changing the order of the characters will change the output value.

ContentLicense: CC BY-SA 4.0

Body:
Inside the FuzzyWuzzy ratio description it says:

The FuzzyWuzzy ratio raw score is a measure of the strings similarity as an int in the range [0, 100]. For two strings X and Y, the score is defined by int(round((2.0 * M / T) * 100)) where T is the total number of characters in both strings, and M is the number of matches in the two strings. The FuzzyWuzzy ratio sim score is a float in the range [0, 1] and is obtained by dividing the raw score by 100.

Then how come this score appears to be different when I change the order of the words?

 from fuzzywuzzy import fuzz

 fuzz.ratio('EMRE MERT', 'OMER CAN') / 100 = 0.35

 fuzz.ratio('EMRE MERT', 'CAN OMER') / 100 = 0.47


问:
How to get the image URL from LPLinkMetadata in Swift
I am trying to get the URL for the image associated with a given URL. Using Apple's LPLinkMetadata, I am able to get the URL's title and description, but I cannot figure out how to access the metadata's image URL. I have access to data.imageProvider but I am not sure how to use it.

```<code>import LinkPresentation

final class URLHelper {

    @available(iOS 13.0, *)
    static func fetchURLPreview(url: URL) {

        let metadataProvider = LPMetadataProvider()

        metadataProvider.startFetchingMetadata(for: url) { (metadata, error) in

            DispatchQueue.main.async {

                if let _ = error {
                    // handle error
                } else if let data = metadata {
                    let urlTitle = data.title
                    let urlImageUrl = data.????????
                }
            }
        }
    }
}
</code>```

答:
```<code>let _ = md.imageProvider?.loadObject(ofClass: UIImage.self, completionHandler: { image, err in
                            DispatchQueue.main.async {
                                self?.imageViewWebSite.image = image as? UIImage
                            }
                        })
</code>```

Body:
I am trying to get the URL for the image associated with a given URL. Using Apple's LPLinkMetadata, I am able to get the URL's title and description, but I cannot figure out how to access the metadata's image URL. I have access to data.imageProvider but I am not sure how to use it.

import LinkPresentation

final class URLHelper {

    @available(iOS 13.0, *)
    static func fetchURLPreview(url: URL) {

        let metadataProvider = LPMetadataProvider()

        metadataProvider.startFetchingMetadata(for: url) { (metadata, error) in

            DispatchQueue.main.async {

                if let _ = error {
                    // handle error
                } else if let data = metadata {
                    let urlTitle = data.title
                    let urlImageUrl = data.????????
                }
            }
        }
    }
}


问:
Comparing list values and select maximum from each day - Python
I am using Python 3.6. I have a below list(capturing start time through a json object) and would like to capture the most recent date/time value in the list for each day.

mytimelist =[2020-05-30T19:21:36.124Z, 2020-05-31T10:34:06.137Z, 2020-05-31T17:14:06.117Z,2020-05-31T23:06:21.131Z, 2020-06-01T19:21:36.108Z, 2020-06-01T21:55:11.137Z]

I would want the below list.

myfinallist = [2020-05-30T19:21:36.124Z, 2020-05-31T23:06:21.131Z, 2020-06-01T21:55:11.137Z]

Could anybody please help me here.

答:
I'm assuming you can get the dates as strings in Python?  Then you can use datetime to convert them into datetime objects, and loop over the unique dates, checking the max as you go.

```<code>import datetime as dt

mytimelist =['2020-05-30T19:21:36.124Z',
             '2020-05-31T10:34:06.137Z',
             '2020-05-31T17:14:06.117Z',
             '2020-05-31T23:06:21.131Z',
             '2020-06-01T19:21:36.108Z',
             '2020-06-01T21:55:11.137Z']

#see https://strftime.org/ for the syntax
date_format = "%Y-%m-%dT%H:%M:%S.%fZ"
datetimes = [dt.datetime.strptime(t,date_format) for t in mytimelist]

output = {}
for time in datetimes:
    date = time.date()
    if date not in output:
        output[date] = time
    else:
        if time > output[date]:
            output[date] = time

for key in sorted(output.keys()):
    print(str(key) + ': ' + str(output[key]))
</code>```

Output:

```<code>2020-05-30: 2020-05-30 19:21:36.124000
2020-05-31: 2020-05-31 23:06:21.131000
2020-06-01: 2020-06-01 21:55:11.137000
</code>```

Body:
I'm assuming you can get the dates as strings in Python?  Then you can use datetime to convert them into datetime objects, and loop over the unique dates, checking the max as you go.

import datetime as dt

mytimelist =['2020-05-30T19:21:36.124Z',
             '2020-05-31T10:34:06.137Z',
             '2020-05-31T17:14:06.117Z',
             '2020-05-31T23:06:21.131Z',
             '2020-06-01T19:21:36.108Z',
             '2020-06-01T21:55:11.137Z']

#see https://strftime.org/ for the syntax
date_format = "%Y-%m-%dT%H:%M:%S.%fZ"
datetimes = [dt.datetime.strptime(t,date_format) for t in mytimelist]

output = {}
for time in datetimes:
    date = time.date()
    if date not in output:
        output[date] = time
    else:
        if time > output[date]:
            output[date] = time

for key in sorted(output.keys()):
    print(str(key) + ': ' + str(output[key]))

Output:

2020-05-30: 2020-05-30 19:21:36.124000
2020-05-31: 2020-05-31 23:06:21.131000
2020-06-01: 2020-06-01 21:55:11.137000


问:
Android Recycler Adapter position not working properly: onClick handling doesn't work properly
I have a recycler view where I fetch details from my database. An ArrayList of FriendEntity is given by the room database which works fine. I want to first have an unchecked box image for the whole list, and if I tap the image, it should change into a checked box image. But when I am achieving this, when I click on 1st item of recyclerView, my 16th item of recyclerView gets changed from unchecked to checked itself and the same goes with the 2nd and 17th, 3rd, and 18th and so on. I don't know if this is a problem with a recycler view adapter or something else.

Data Class FriendEntity :

     @Entity(tableName = "Friends")
     data class FriendEntity (
     @PrimaryKey val friend_name: String ,
     @ColumnInfo(name = "debt") val debt: Float )
```

<p>ExpenseActivity.xml for RecyclerView:</p>

<pre class="lang-xml prettyprint-override"><code>       <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
</code>```

ExpenseActivity.kt:

    class ExpenseActivity : AppCompatActivity() {
    private lateinit var binding: ActivityExpenseBinding
    private lateinit var layoutManager: LinearLayoutManager
    private lateinit var recyclerAdapter: FriendListAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this@ExpenseActivity,R.layout.activity_expense)
        layoutManager = LinearLayoutManager(this@ExpenseActivity)
        val friendsList = GetFriends(applicationContext).execute().get()
        binding.txtDef.visibility = if(friendsList.size==0) View.VISIBLE else View.GONE
        binding.recyclerList.visibility = if(friendsList.size!=0) View.VISIBLE else View.GONE
        recyclerAdapter = FriendListAdapter(this@ExpenseActivity,friendsList)
        binding.recyclerList.layoutManager = layoutManager
        binding.recyclerList.adapter = recyclerAdapter
     } }
```

<p>I have tested my GetFriends it works fine.</p>

<p>FriendListAdapter.kt:</p>

<pre class="lang-kotlin prettyprint-override"><code>    class FriendListAdapter(val context: Context, private val itemList: ArrayList<FriendEntity>):
    RecyclerView.Adapter<FriendListAdapter.FriendViewHolder>() {
    private var checkList: ArrayList<FriendEntity> = arrayListOf()

    class FriendViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val txtFriendName: TextView = view.findViewById(R.id.txtFriendName)
        val imgCheck: ImageView = view.findViewById(R.id.imgCheck)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendViewHolder {
        val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.recycler_single_friend,parent,false)
        return FriendViewHolder(view)
    }
    override fun getItemCount() = itemList.size
    override fun onBindViewHolder(holder: FriendViewHolder, position: Int) {
        val itemObject = itemList[position]
        holder.txtFriendName.text = itemObject.friend_name
        holder.imgCheck.setOnClickListener {
            if(checkList.contains(itemObject)) {
                holder.imgCheck.setImageResource(R.drawable.ic_cb_empty)
                checkList.remove(itemObject)
            } else {
                holder.imgCheck.setImageResource(R.drawable.ic_cb_full)
                checkList.add(itemObject)
            }
        }
     } }
</code>```

The problem I get is :

I tap on 1st element

The 16th automatically changes

I tap 2nd image

The 17th gets automatically clicked

Also, the behavior is so much problematic that when I tap on the 16th image, it doesn't respond.2nd time clicking makes it unchecked. Same with the 17th image. I guess there is some problem with the adapter.

Then I tried having a small view for individual items so that my screen gets a total of 20 items altogether. Now when I tap on the 1st image, the 24th gets selected, 2nd click changes the 25th. It means it clicks items who are not in the view right now but how?

I paste a GDriveLink for the video here if anyone doesn't understand it till now: Link to video of the problem

I want to know how to remove this error?

答:
The answer provided by Aashit Shah is a good answer surely and would do the work perfectly. But just in case, if anyone doesn't wanna change the entity class (in my case, I didn't want to do any changes in my POJO/data class because I am sending whole object of FriendEntity to Room Database) so you can have a work around.

You can add an Array of Boolean as a member variable of the adapter class like this

```<code>private val boolArray = ArrayList(Collections.nCopies(itemCount,false))
</code>```

This boolArray will keep records of boolean status locally.
And hence we can use it onBindViewHolder in the same manner as above:

```<code>override fun onBindViewHolder(holder: FriendViewHolder, position: Int) {
    val itemObject = itemList[holder.adapterPosition]
    holder.txtFriendName.text = itemObject.friend_name
    holder.imgCheck.setImageResource(if(boolArray[holder.adapterPosition]) R.drawable.ic_cb_full else R.drawable.ic_cb_empty)
    holder.imgCheck.setOnClickListener {
        if(boolArray[holder.adapterposition]) {
            holder.imgCheck.setImageResource(R.drawable.ic_cb_empty)
            checkList.remove(itemObject)
            boolArray[holder.adapterPosition] = false
        } else {
            holder.imgCheck.setImageResource(R.drawable.ic_cb_full)
            checkList.add(itemObject)
            boolArray[holder.adapterPosition] = true
        }
    }
}
</code>```

The advantage of using this work around is that it won't change your previous database and this boolArray will be having a lifecycle of just an object and hence space efficiency.

Body:
I have a recycler view where I fetch details from my database. An ArrayList of FriendEntity is given by the room database which works fine. I want to first have an unchecked box image for the whole list, and if I tap the image, it should change into a checked box image. But when I am achieving this, when I click on 1st item of recyclerView, my 16th item of recyclerView gets changed from unchecked to checked itself and the same goes with the 2nd and 17th, 3rd, and 18th and so on. I don't know if this is a problem with a recycler view adapter or something else.

Data Class FriendEntity :

     @Entity(tableName = "Friends")
     data class FriendEntity (
     @PrimaryKey val friend_name: String ,
     @ColumnInfo(name = "debt") val debt: Float )

ExpenseActivity.xml for RecyclerView:

       <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

ExpenseActivity.kt:

    class ExpenseActivity : AppCompatActivity() {
    private lateinit var binding: ActivityExpenseBinding
    private lateinit var layoutManager: LinearLayoutManager
    private lateinit var recyclerAdapter: FriendListAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this@ExpenseActivity,R.layout.activity_expense)
        layoutManager = LinearLayoutManager(this@ExpenseActivity)
        val friendsList = GetFriends(applicationContext).execute().get()
        binding.txtDef.visibility = if(friendsList.size==0) View.VISIBLE else View.GONE
        binding.recyclerList.visibility = if(friendsList.size!=0) View.VISIBLE else View.GONE
        recyclerAdapter = FriendListAdapter(this@ExpenseActivity,friendsList)
        binding.recyclerList.layoutManager = layoutManager
        binding.recyclerList.adapter = recyclerAdapter
     } }

I have tested my GetFriends it works fine.

FriendListAdapter.kt:

    class FriendListAdapter(val context: Context, private val itemList: ArrayList<FriendEntity>):
    RecyclerView.Adapter<FriendListAdapter.FriendViewHolder>() {
    private var checkList: ArrayList<FriendEntity> = arrayListOf()

    class FriendViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val txtFriendName: TextView = view.findViewById(R.id.txtFriendName)
        val imgCheck: ImageView = view.findViewById(R.id.imgCheck)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendViewHolder {
        val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.recycler_single_friend,parent,false)
        return FriendViewHolder(view)
    }
    override fun getItemCount() = itemList.size
    override fun onBindViewHolder(holder: FriendViewHolder, position: Int) {
        val itemObject = itemList[position]
        holder.txtFriendName.text = itemObject.friend_name
        holder.imgCheck.setOnClickListener {
            if(checkList.contains(itemObject)) {
                holder.imgCheck.setImageResource(R.drawable.ic_cb_empty)
                checkList.remove(itemObject)
            } else {
                holder.imgCheck.setImageResource(R.drawable.ic_cb_full)
                checkList.add(itemObject)
            }
        }
     } }

The problem I get is :

I tap on 1st element

The 16th automatically changes

I tap 2nd image

The 17th gets automatically clicked

Also, the behavior is so much problematic that when I tap on the 16th image, it doesn't respond.2nd time clicking makes it unchecked. Same with the 17th image. I guess there is some problem with the adapter.

Then I tried having a small view for individual items so that my screen gets a total of 20 items altogether. Now when I tap on the 1st image, the 24th gets selected, 2nd click changes the 25th. It means it clicks items who are not in the view right now but how?

I paste a GDriveLink for the video here if anyone doesn't understand it till now: Link to video of the problem

I want to know how to remove this error?

Body:
The answer provided by Aashit Shah is a good answer surely and would do the work perfectly. But just in case, if anyone doesn't wanna change the entity class (in my case, I didn't want to do any changes in my POJO/data class because I am sending whole object of FriendEntity to Room Database) so you can have a work around.

You can add an Array of Boolean as a member variable of the adapter class like this

private val boolArray = ArrayList(Collections.nCopies(itemCount,false))

This boolArray will keep records of boolean status locally.
And hence we can use it onBindViewHolder in the same manner as above:

override fun onBindViewHolder(holder: FriendViewHolder, position: Int) {
    val itemObject = itemList[holder.adapterPosition]
    holder.txtFriendName.text = itemObject.friend_name
    holder.imgCheck.setImageResource(if(boolArray[holder.adapterPosition]) R.drawable.ic_cb_full else R.drawable.ic_cb_empty)
    holder.imgCheck.setOnClickListener {
        if(boolArray[holder.adapterposition]) {
            holder.imgCheck.setImageResource(R.drawable.ic_cb_empty)
            checkList.remove(itemObject)
            boolArray[holder.adapterPosition] = false
        } else {
            holder.imgCheck.setImageResource(R.drawable.ic_cb_full)
            checkList.add(itemObject)
            boolArray[holder.adapterPosition] = true
        }
    }
}

The advantage of using this work around is that it won't change your previous database and this boolArray will be having a lifecycle of just an object and hence space efficiency.


问:
Do source maps work for Chrome extensions?
I'm using the Closure compiler to create a Chrome extension and I'd like to get source maps to work for debugging.  I can get source maps to work just fine by pointing the browser directly to a page in my source tree with the special sourceMappingURL added to the end of the compiled javascript file (everything is in a single directory):

```<code>debugger;document.getElementById("hello").innerHTML="Hello, world!";
//@ sourceMappingURL=background-compiled.map
</code>```

But when I access the same script as an extension, I can only see the compiled javascript and not the original source.  I do have the Chrome debugger configured to enable source maps in both cases, and otherwise they both execute identically with no errors.  Do source maps just not work in extensions or is there something I'm missing in setting things up?

I've tried Chrome 25 stable and Chrome 27 canary, same behavior in both.

答:
Chrome supports an extension source maps out of the box. No need to have them inline or adding these to web_accessible_resources in your manifest.json file.

Mapped files are allocated under "Content scripts" tab within "Sources" tab under Developer Tools.

There is a source code of all enabled extensions, plus webpack:// files (if source maps are created with Webpack).

It's also possible to find mapped files using Cmd + P.

ContentLicense: CC BY-SA 3.0

Body:
I'm using the Closure compiler to create a Chrome extension and I'd like to get source maps to work for debugging.  I can get source maps to work just fine by pointing the browser directly to a page in my source tree with the special sourceMappingURL added to the end of the compiled javascript file (everything is in a single directory):

debugger;document.getElementById("hello").innerHTML="Hello, world!";
//@ sourceMappingURL=background-compiled.map

But when I access the same script as an extension, I can only see the compiled javascript and not the original source.  I do have the Chrome debugger configured to enable source maps in both cases, and otherwise they both execute identically with no errors.  Do source maps just not work in extensions or is there something I'm missing in setting things up?

I've tried Chrome 25 stable and Chrome 27 canary, same behavior in both.


问:
Why this function acts like loop when it executed couple times
Why is this function acts like loop when it executed couple times did this counter stored in the add function or not

let counter = 0;

function add() {
  return counter++;
}

console.log(add());
console.log(add());
console.log(add());
console.log(add());
```
<p>if it increments I don't understand its difference from this while loop</p>
```let i = 0;
while(i <= 3){
  console.log(i)
  i++;
}
```

答:
I am not sure whether I understand your question correctly but both of these code examples should give the same output.

Your add function uses the counter variable that is declared outside of it. That means each time your function is called from your console.log() lines, it will add 1 to the counter.
Since you don't reset the counter within your function, it will use the already stored value which would be 1 after the first console.log() statement, and so on.

Body:
Why is this function acts like loop when it executed couple times did this counter stored in the add function or not

let counter = 0;

function add() {
  return counter++;
}

console.log(add());
console.log(add());
console.log(add());
console.log(add());

if it increments I don't understand its difference from this while loop

let i = 0;
while(i <= 3){
  console.log(i)
  i++;
}


问:
How to parallelize RNN function in Pytorch with DataParallel
Here's an RNN model to run character based language generation:

```<code>class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size, n_layers):
        super(RNN, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.n_layers = n_layers

        self.encoder = nn.Embedding(input_size, hidden_size)
        self.GRU = nn.GRU(hidden_size, hidden_size, n_layers, batch_first=True)
        self.decoder = nn.Linear(hidden_size, output_size)

    def forward(self, input, batch_size):
        self.init_hidden(batch_size)
        input = self.encoder(input)
        output, self.hidden = self.GRU(input, self.hidden)
        output = self.decoder(output.view(batch_size, self.hidden_size))
        return output

    def init_hidden(self, batch_size):
        self.hidden = Variable(torch.randn(self.n_layers, batch_size, self.hidden_size).cuda())
</code>```

I instantiate the model using DataParallel, to split the batch of inputs across my 4 GPUs:

```<code>net = torch.nn.DataParallel(RNN(n_chars, hidden_size, n_chars, n_layers)).cuda()
</code>```

Here's the full code.

Unfortunately, DataParallel requires the inputs to have batch_size as the first dimension, but GRU function expects hidden tensor to have batch_size as second dimension:

```<code>output, self.hidden = self.GRU(input, self.hidden)
</code>```

The code as is throws the following error (note the printouts showing that encoder is correctly executed on 4 GPUs):

```<code>...
forward function: encoding input of shape: (16L, 1L)
forward function: encoding input of shape: (16L, 1L)
forward function: encoding input of shape: (16L,
forward function: encoding input of shape:

forward function: GRU processing input of shape:
1L)
 ( (16L, 16L1L, 1L), 100L)
forward function: GRU processing input of shape:
 (16L, 1L,
forward function: GRU processing input of shape:100L)
 (16L
forward function: GRU processing input of shape:, 1L, 100L) (
16L, 1L, 100L)

Traceback (most recent call last):
  File "gru2.py", line 166, in <module>
    output = net(c, batch_size)
  File "/root/miniconda2/lib/python2.7/site-packages/torch/nn/modules/module.py", line 206, in __call__
    result = self.forward(*input, **kwargs)
  File "/root/miniconda2/lib/python2.7/site-packages/torch/nn/parallel/data_parallel.py", line 61, in forward
    outputs = self.parallel_apply(replicas, inputs, kwargs)
  File "/root/miniconda2/lib/python2.7/site-packages/torch/nn/parallel/data_parallel.py", line 71, in parallel_apply
    return parallel_apply(replicas, inputs, kwargs)
  File "/root/miniconda2/lib/python2.7/site-packages/torch/nn/parallel/parallel_apply.py", line 45, in parallel_apply
    raise output
RuntimeError: Expected hidden size (2, 16L, 100), got (2L, 64L, 100L)
</code>```

Here the model has 2 layers, batch_size=64, and hidden_size = 100.

How do I parallelize the GRU operation in the forward function?

答:
PyTorch 1.5 has completely fixed the issues with RNN training and DataParallel.
It seems it has done so quite seamlessly.
No more gerrymandering being required.
I confirmed this today, in a project involving bi-dir GRUS on speech mfccs.

```<code>
class PEncoder(nn.Module):
    def __init__(self, args, encoder):
        super(PEncoder, self).__init__()
        self.gpu_ids = args.gpu_ids
        self.model = encoder

    def forward(self, input):
        if len(self.gpu_ids) > 1:
            return nn.parallel.data_parallel(self.model, (input), self.gpu_ids)
        else:
            return self.model(input)

</code>```

It is that simple.
This does wrap your model in another model, and effectively produces a slightly different compute graph. So, if you have earlier trained models, you may have to load them in a special manner and create some setters for this parallel wrap. Give it a try, and you'll see. (I've not confirmed this aspect of it.)

Body:
Here's an RNN model to run character based language generation:

class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size, n_layers):
        super(RNN, self).__init__()
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.n_layers = n_layers

        self.encoder = nn.Embedding(input_size, hidden_size)
        self.GRU = nn.GRU(hidden_size, hidden_size, n_layers, batch_first=True)
        self.decoder = nn.Linear(hidden_size, output_size)

    def forward(self, input, batch_size):
        self.init_hidden(batch_size)
        input = self.encoder(input)
        output, self.hidden = self.GRU(input, self.hidden)
        output = self.decoder(output.view(batch_size, self.hidden_size))
        return output

    def init_hidden(self, batch_size):
        self.hidden = Variable(torch.randn(self.n_layers, batch_size, self.hidden_size).cuda())

I instantiate the model using DataParallel, to split the batch of inputs across my 4 GPUs:

net = torch.nn.DataParallel(RNN(n_chars, hidden_size, n_chars, n_layers)).cuda()

Here's the full code.

Unfortunately, DataParallel requires the inputs to have batch_size as the first dimension, but GRU function expects hidden tensor to have batch_size as second dimension:

output, self.hidden = self.GRU(input, self.hidden)

The code as is throws the following error (note the printouts showing that encoder is correctly executed on 4 GPUs):

...
forward function: encoding input of shape: (16L, 1L)
forward function: encoding input of shape: (16L, 1L)
forward function: encoding input of shape: (16L,
forward function: encoding input of shape:

forward function: GRU processing input of shape:
1L)
 ( (16L, 16L1L, 1L), 100L)
forward function: GRU processing input of shape:
 (16L, 1L,
forward function: GRU processing input of shape:100L)
 (16L
forward function: GRU processing input of shape:, 1L, 100L) (
16L, 1L, 100L)

Traceback (most recent call last):
  File "gru2.py", line 166, in <module>
    output = net(c, batch_size)
  File "/root/miniconda2/lib/python2.7/site-packages/torch/nn/modules/module.py", line 206, in __call__
    result = self.forward(*input, **kwargs)
  File "/root/miniconda2/lib/python2.7/site-packages/torch/nn/parallel/data_parallel.py", line 61, in forward
    outputs = self.parallel_apply(replicas, inputs, kwargs)
  File "/root/miniconda2/lib/python2.7/site-packages/torch/nn/parallel/data_parallel.py", line 71, in parallel_apply
    return parallel_apply(replicas, inputs, kwargs)
  File "/root/miniconda2/lib/python2.7/site-packages/torch/nn/parallel/parallel_apply.py", line 45, in parallel_apply
    raise output
RuntimeError: Expected hidden size (2, 16L, 100), got (2L, 64L, 100L)

Here the model has 2 layers, batch_size=64, and hidden_size = 100.

How do I parallelize the GRU operation in the forward function?

Body:
PyTorch 1.5 has completely fixed the issues with RNN training and DataParallel.
It seems it has done so quite seamlessly.
No more gerrymandering being required.
I confirmed this today, in a project involving bi-dir GRUS on speech mfccs.

class PEncoder(nn.Module):
    def __init__(self, args, encoder):
        super(PEncoder, self).__init__()
        self.gpu_ids = args.gpu_ids
        self.model = encoder

    def forward(self, input):
        if len(self.gpu_ids) > 1:
            return nn.parallel.data_parallel(self.model, (input), self.gpu_ids)
        else:
            return self.model(input)

It is that simple.
This does wrap your model in another model, and effectively produces a slightly different compute graph. So, if you have earlier trained models, you may have to load them in a special manner and create some setters for this parallel wrap. Give it a try, and you'll see. (I've not confirmed this aspect of it.)


问:
Dynamic loading of react components
I need to load a react component dynamically.

I get name of the component to load as a string from user. I'm using webpack.

How do I load the component dynamically instead of having a static import statement. It seems Require.Ensure doesn't evaluate expressions . What I want to achieve is something like this.

```<code>require.ensure([ "./widgets/" + componentName ] ,(require) => {
    let Component = require("./widgets/" + componentName);
});
</code>```

But this doesn't seem to work.

答:
```<code>import React, { Component } from "react";

class DynamicLoader extends Component {

  render() {
    const COMPONENTS = {
      CompA: require('./CompA'),
      CompB: require('./CompB'),
    }
    if(this.props.component && COMPONENTS[this.props.component]) {
      let Component = COMPONENTS[this.props.component].default;
      return <Component />
    }
  }
}

export default DynamicLoader;
</code>```

```<code><DynamicLoader component="CompA" />
</code>```

Title: Dynamic loading of react components

Body:
I need to load a react component dynamically.

I get name of the component to load as a string from user. I'm using webpack.

How do I load the component dynamically instead of having a static import statement. It seems Require.Ensure doesn't evaluate expressions . What I want to achieve is something like this.

require.ensure([ "./widgets/" + componentName ] ,(require) => {
    let Component = require("./widgets/" + componentName);
});

But this doesn't seem to work.

Body:
import React, { Component } from "react";

class DynamicLoader extends Component {

  render() {
    const COMPONENTS = {
      CompA: require('./CompA'),
      CompB: require('./CompB'),
    }
    if(this.props.component && COMPONENTS[this.props.component]) {
      let Component = COMPONENTS[this.props.component].default;
      return <Component />
    }
  }
}

export default DynamicLoader;

<DynamicLoader component="CompA" />


问:
Oracle provider for .NET 4
HI,

I'm developing a website on ASP.NET. The database is Oracle 10 g. When I deploy the website I get an exception message "System.Data.OracleClient requires Oracle client software version 8.1.7 or greater.".The environment is Visual Studio 2010.I downloaded and installed ODAC 11.2 Release 3 (11.2.0.2.1) but I still get the exception.I'd also installed Oracle client 10 g.But it failed too. Any suggestions?

答: Resolved. I could fix this problem by installing a patch provided by Oracle. If one uses typed Datasets they shoud install the patch as well after installing the ODP itself.Thanks whoever tried to answer. </p>

Title: Oracle provider for .NET 4


问:
Firestore wont retrieve my data when I use where
I am trying to retrieve data from my database using where. The user inputs an email they would like to invite and then an invite is sent. However no document is being returned. This is the code I'm using to retrieve:

```<code>await props.firestore
    .collection("users")
    .where("email", "==", state.inviteEmail)
    .get()
    .then((doc) => {
      if (!doc.exists) {
        props.showMsg(
          "No user with that email exists. Make sure you've entered it correctly"
        );
      } else {
        // This is where it goes if it works
        alert("It works");
      }
    });
</code>```

I've tried replacing the where with .doc(any id) and it works so I know the database is connected properly. This is the view of the database:

I'm using Reactjs and the database is using Firebase

EDIT: For anyone else having the same issue, this was the change I made:

```<code>await props.firestore
    .collection("users")
    .where("email", "==", state.inviteEmail)
    .get()
    .then((doc) => {
      if (doc.empty) {
        props.showMsg(
          "No user with that email exists. Make sure you've entered it correctly"
        );
      } else {
        alert("This emails username: "+doc.docs[0].data().username);
      }
    });
</code>```

The data is being returned as a QuerySnapshot which is like an array so instead of doc.Data() it needed to be doc.docs[0].data. As I only have one guaranteed returned document I just grabbed the first element, but if I had multiples I would have to use a foreach.

答:
When you add a where clause, you are essentially getting a QuerySnapshot object in return instead of a DocumentSnapshot. So the problem in your code is that QuerySnapshot object does not have an exists field as the DocumentSnapshot object. Thus doc.exists will always be equal to undefined in this case and the if statement will always evaluate to true.

You may convert your if condition to look for the empty property instead, so the code will look like this:

```<code>firestore
.collection("users")
.where("email", "==", state.inviteEmail)
.get()
.then((snap) => {
  if (snap.empty) {
    props.showMsg(
      "No user with that email exists. Make sure you've entered it correctly"
    );
  } else {
    // This is where it goes if it works
    alert("It works");
  }
});
</code>```

Body:
I am trying to retrieve data from my database using where. The user inputs an email they would like to invite and then an invite is sent. However no document is being returned. This is the code I'm using to retrieve:

await props.firestore
    .collection("users")
    .where("email", "==", state.inviteEmail)
    .get()
    .then((doc) => {
      if (!doc.exists) {
        props.showMsg(
          "No user with that email exists. Make sure you've entered it correctly"
        );
      } else {
        // This is where it goes if it works
        alert("It works");
      }
    });

I've tried replacing the where with .doc(any id) and it works so I know the database is connected properly. This is the view of the database:

I'm using Reactjs and the database is using Firebase

EDIT: For anyone else having the same issue, this was the change I made:

await props.firestore
    .collection("users")
    .where("email", "==", state.inviteEmail)
    .get()
    .then((doc) => {
      if (doc.empty) {
        props.showMsg(
          "No user with that email exists. Make sure you've entered it correctly"
        );
      } else {
        alert("This emails username: "+doc.docs[0].data().username);
      }
    });

The data is being returned as a QuerySnapshot which is like an array so instead of doc.Data() it needed to be doc.docs[0].data. As I only have one guaranteed returned document I just grabbed the first element, but if I had multiples I would have to use a foreach.

Body:
When you add a where clause, you are essentially getting a QuerySnapshot object in return instead of a DocumentSnapshot. So the problem in your code is that QuerySnapshot object does not have an exists field as the DocumentSnapshot object. Thus doc.exists will always be equal to undefined in this case and the if statement will always evaluate to true.

You may convert your if condition to look for the empty property instead, so the code will look like this:

firestore
.collection("users")
.where("email", "==", state.inviteEmail)
.get()
.then((snap) => {
  if (snap.empty) {
    props.showMsg(
      "No user with that email exists. Make sure you've entered it correctly"
    );
  } else {
    // This is where it goes if it works
    alert("It works");
  }
});


问:
context is slow or being called twice
I have an issue with the Context I am using for my auth. If I console.log when logged in, first I get false, and then a second later it logs again with the token etc. So, something is wrong with my code.

Here is my auth hook:

```<code>import { useState, useCallback, useEffect } from "react";

export const useAuth = () => {
  const [token, setToken] = useState(false);
  const [userId, setUserId] = useState(false);

  const login = useCallback((uid, token) => {
    setToken(token);
    setUserId(uid);
    localStorage.setItem(
      "userData",
      JSON.stringify({
        userId: uid,
        token: token,
      })
    );
  }, []);

  const logout = useCallback(() => {
    setToken(null);
    setUserId(null);
    localStorage.removeItem("userData");
  }, []);

  useEffect(() => {
    const storedData = JSON.parse(localStorage.getItem("userData"));
    if (storedData && storedData.token) {
      login(storedData.userId, storedData.token);
    }
  }, [login]);

  return { token, login, logout, userId };
};
</code>```

The auth context:

```<code>import { createContext } from "react";

export const AuthContext = createContext({
  isLoggedIn: false,
  userId: null,
  token: null,
  login: () => {},
  logout: () => {},
});
</code>```

Example of the component where I have the issue (basically in all components I am using this auth context)

```<code>import React, { useContext, useState } from "react";
import AdminCard from "../components/adminCards/AdminCard";
import { AuthContext } from "../../shared/context/auth-context";

const Dashboard = () => {
  const auth = useContext(AuthContext);
  console.log(auth);
  return (
    <div className="admin-wrapper">
      <div className="main-panel">
        <div className="row">
          <div className="wrapper">
            <div className="col-3">
              <AdminCard title="Contact Enquiries" />
              <AdminCard title="Card 2" />
              <AdminCard title="Card 3" />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Dashboard;
</code>```

In console I first see 'false' and then a second later I see the contents of 'auth'.

Example of App.js

```<code>const App = () => {
   const { token, login, logout, userId } = useAuth();
  return (
    <>
      <AuthContext.Provider
        value={{
          isLoggedIn: !!token,
          token: token,
          userId: userId,
          login: login,
          logout: logout,
        }}
      >
 <Router>
<Switch>
   <Route path="/" exact>
    <Dashboard />
   </Route>
</Switch>
</Router>
</AuthContext.Provider>
</>
};

export default App;
</code>```

An example of the issue is if I log in and navigate to the dashboard via clicking on a link I have no problem. If I am on the dashboard and I refresh the browser, I get a 403 error and the request fails because the token was not available yet when sending the request.

```<code>  useEffect(() => {
    const getItems = async () => {
      const config = {
        method: "get",
        url: "http://localhost:8000/api/admin/somedata",
        headers: { Authorization: "Bearer " + auth.token },
      };
      const responseData = await Axios(config);
      setItems(responseData.data);
      console.log(responseData.data);
    };
    getItems();
  }, []);
</code>```

To clarify, I only have this issue if I refresh the browser.

答:
you can streamline your useAuth hook a bit so that it immediately returns a result not just on rerender.

```<code>export const useAuth = () => {
  const [{
    // normalize undefined -> null
    userId = null,
    token = null
  // init state from localStorage
  }, setUserData] = useState(() => JSON.parse(localStorage.getItem("userData") || "{}"));

  // only update the context if userId or token changed
  return useMemo(() => {
    if (userId || token) {
      localStorage.setItem("userData", JSON.stringify({ userId, token }));
    } else {
      localStorage.removeItem("userData");
    }

    // There's no point of putting these functions into useCallback,
    // unless you use them somewhere as deps.

    // TODO: validate login? disable login while logged in?
    const login = (userId, token) => setUserData({ userId, token });
    const logout = () => setUserData({});

    return {
      userId,
      token,
      isLoggedIn: !!token,
      login,
      logout
    };
  }, [userId, token]);
};
</code>```

then App becomes

```<code>const App = () => {
  const authContext = useAuth();
  return (
    <AuthContext.Provider value={authContext}>
      <Router>
        <Switch>
          <Route path="/" exact>
            <Dashboard />
          </Route>
        </Switch>
      </Router>
    </AuthContext.Provider>
  );
};
</code>```

Then, your useEffect clearly depends on the token; at least its existance. You need to put it in the deps.

At least like this:

```<code>useEffect(() => {
  const getItems = async () => {
    const config = {
      method: "get",
      url: "http://localhost:8000/api/admin/somedata",
      headers: { Authorization: "Bearer " + auth.token },
    };
    const responseData = await Axios(config);
    setItems(responseData.data);
    console.log(responseData.data);
  };
  auth.token && getItems();
}, [!!auth.token]);
</code>```

Title: context is slow or being called twice

Body:
I have an issue with the Context I am using for my auth. If I console.log when logged in, first I get false, and then a second later it logs again with the token etc. So, something is wrong with my code.

Here is my auth hook:

import { useState, useCallback, useEffect } from "react";

export const useAuth = () => {
  const [token, setToken] = useState(false);
  const [userId, setUserId] = useState(false);

  const login = useCallback((uid, token) => {
    setToken(token);
    setUserId(uid);
    localStorage.setItem(
      "userData",
      JSON.stringify({
        userId: uid,
        token: token,
      })
    );
  }, []);

  const logout = useCallback(() => {
    setToken(null);
    setUserId(null);
    localStorage.removeItem("userData");
  }, []);

  useEffect(() => {
    const storedData = JSON.parse(localStorage.getItem("userData"));
    if (storedData && storedData.token) {
      login(storedData.userId, storedData.token);
    }
  }, [login]);

  return { token, login, logout, userId };
};

The auth context:

import { createContext } from "react";

export const AuthContext = createContext({
  isLoggedIn: false,
  userId: null,
  token: null,
  login: () => {},
  logout: () => {},
});

Example of the component where I have the issue (basically in all components I am using this auth context)

import React, { useContext, useState } from "react";
import AdminCard from "../components/adminCards/AdminCard";
import { AuthContext } from "../../shared/context/auth-context";

const Dashboard = () => {
  const auth = useContext(AuthContext);
  console.log(auth);
  return (

              <AdminCard title="Contact Enquiries" />
              <AdminCard title="Card 2" />
              <AdminCard title="Card 3" />

  );
};

export default Dashboard;

In console I first see 'false' and then a second later I see the contents of 'auth'.

Example of App.js

const App = () => {
   const { token, login, logout, userId } = useAuth();
  return (
    <>
      <AuthContext.Provider
        value={{
          isLoggedIn: !!token,
          token: token,
          userId: userId,
          login: login,
          logout: logout,
        }}
      >
 <Router>
<Switch>
   <Route path="/" exact>
    <Dashboard />
   </Route>
</Switch>
</Router>
</AuthContext.Provider>
</>
};

export default App;

An example of the issue is if I log in and navigate to the dashboard via clicking on a link I have no problem. If I am on the dashboard and I refresh the browser, I get a 403 error and the request fails because the token was not available yet when sending the request.

  useEffect(() => {
    const getItems = async () => {
      const config = {
        method: "get",
        url: "http://localhost:8000/api/admin/somedata",
        headers: { Authorization: "Bearer " + auth.token },
      };
      const responseData = await Axios(config);
      setItems(responseData.data);
      console.log(responseData.data);
    };
    getItems();
  }, []);

To clarify, I only have this issue if I refresh the browser.

Body:
you can streamline your useAuth hook a bit so that it immediately returns a result not just on rerender.

export const useAuth = () => {
  const [{
    // normalize undefined -> null
    userId = null,
    token = null
  // init state from localStorage
  }, setUserData] = useState(() => JSON.parse(localStorage.getItem("userData") || "{}"));

  // only update the context if userId or token changed
  return useMemo(() => {
    if (userId || token) {
      localStorage.setItem("userData", JSON.stringify({ userId, token }));
    } else {
      localStorage.removeItem("userData");
    }

    // There's no point of putting these functions into useCallback,
    // unless you use them somewhere as deps.

    // TODO: validate login? disable login while logged in?
    const login = (userId, token) => setUserData({ userId, token });
    const logout = () => setUserData({});

    return {
      userId,
      token,
      isLoggedIn: !!token,
      login,
      logout
    };
  }, [userId, token]);
};

then App becomes

const App = () => {
  const authContext = useAuth();
  return (
    <AuthContext.Provider value={authContext}>
      <Router>
        <Switch>
          <Route path="/" exact>
            <Dashboard />
          </Route>
        </Switch>
      </Router>
    </AuthContext.Provider>
  );
};

Then, your useEffect clearly depends on the token; at least its existance. You need to put it in the deps.

At least like this:

useEffect(() => {
  const getItems = async () => {
    const config = {
      method: "get",
      url: "http://localhost:8000/api/admin/somedata",
      headers: { Authorization: "Bearer " + auth.token },
    };
    const responseData = await Axios(config);
    setItems(responseData.data);
    console.log(responseData.data);
  };
  auth.token && getItems();
}, [!!auth.token]);


问:
Using stdlib.h on xcode
How do I use system ("cls") or system ("pause") commands on xcode? Obviously he does not interpret them as they are not system commands, how can I do it?</p>

答:
When i use system(), the compilator can't run that command because it's a windows one.
So.. i saw that i could use CMD+K but i need that command in the code
E.g.

```<code>system("cls");

cout<<"Hello"<<endl;

system("pause");

system("cls");
</code>```

That's all...
I need to make the command works

Title: Using stdlib.h on xcode

Body:
When i use system(), the compilator can't run that command because it's a windows one.
So.. i saw that i could use CMD+K but i need that command in the code
E.g.

system("cls");

cout<<"Hello"<<endl;

system("pause");

system("cls");

That's all...
I need to make the command works


问:
What's the benefit of assigning non-scalars to scalars?
I sometimes see code that (to me) uses the wrong sigil in front of the variable

```<code>my $arr  = [1, 2, 3, 4, 5];      # an array
my $lst  = (1, 2, 3, 4, 5);      # a list
my $hash = {a => '1', b => '2'}; # a hash
my $func = -> $foo { say $foo }; # a callable
</code>```

And it all just works exactly as expected

```<code>say $arr[0];    # 1
say $lst[1];    # 2
say $hash<a>;   # 1
say $hash{'b'}; # 2
$func('hello'); # hello
</code>```

Q1: What are the benefits of using the scalar container for this, rather than just using the 'correct' one?

I know that Perl only let collections store scalars, requiring things like multi-dimensional arrays be done via array references, with [...] and {...} being array and hash reference literals respectively.

To expand and clarify what I mean here, there's basically two ways to define things, by value and by reference:

# "values"
my @arr = (1, 2, 3, 4);
my %hash = (1 => 2, 3 => 4);

# which are accessed like this:
my $result1 = $arr[0];
my $result2 = $hash{1};

# references (note how the braces canged)
my $aref = [1, 2, 3, 4];
my $href = {1 => 2, 3 => 4};

# or making a reference to existing collections
my $aref2 = \@arr;
my $href2 = \%hash;

# which are accessed like this:
my $result3 = $aref->[0];
my $result4 = $href->{1};
```

The reasoning behind this madness is that Perl collections only really accept scalars, and references are just that.
Using references is essentially a way to enable multidimensional arrays.

TL;DR, the distinction makes sense in Perl because they serve two distinctly different purposes.

Q2: Are we dealing with Perl 5-like reference literals again, or is something else at play?

答:
TL;DR For computers, and humans, and therefore Raku too, a non-scalar (plural thing) is also a scalar (singular thing). (Whereas the converse may not be true.) For example, an Array is both a plural thing (an array of elements) and a single thing, an Array. When you wish to syntactically and statically emphasize a datum's most generic singular nature, use $.

Here's an opening example based on @sid_com++'s comment:

```<code>my @a = ( 1, 2 ), 42, { :a, :b }
for @a -> $b {say $b}            # (1 2)␤42␤{a => True, b => True}␤
for @a -> @b {say @b}            # (1 2)␤Type check failed ...
</code>```

The first loop binds values to $b. It is "fault tolerant" because it accepts any value. The second loop binds to @b. Any value that doesn't do the Positional role leads to a type check failure.

My Raku equivalent of your Perl code

Here's a Raku translation of your Perl code:

```<code>my @arr = (1, 2, 3, 4);
my %hash = (1 => 2, 3 => 4);

my $result1 = @arr[0];                          # <-- Invariant sigil
my $result2 = %hash{1};                         # <-- Invariant sigil

my $aref = [1, 2, 3, 4];
my $href = {1 => 2, 3 => 4};

my $aref2 = @arr;                               # <-- Drop `\`
my $href2 = %hash;                              # <-- Drop `\`

my $result3 = $aref[0];                         # <-- Drop `->`
my $result4 = $href{1};                         # <-- Drop `->`
</code>```

The code is a little shorter. Idiomatic code would probably be a good bit shorter still, dropping:

The ref variables. A variable @foo is a reference. A [...] in term (noun) position is an Array reference literal. There's little or no need to use scalar variables to explicitly store references.

The parens in the first couple lines;

Semi colons after most closing braces that are the last code on a line;

Raku's sigils are invariant. Here are two tables providing an at-a-glance comparison of Perl's sigil variation vs Raku's sigil invariance.

Why bother with sigils?

All the sigil variations directly correspond to embedding "type" info into an identifier's name that's visible to humans, the language, and the compiler:

foo Tells Raku features which pick between a singular and plural way of operating on data should decide based on the run-time type of the data.

$foo Tells Raku to pick singular behavior. A value might be, say, a List containing many values, but its singular nature is being emphasized instead.

&foo Type checks that a bound or assigned value does the Callable role.

@foo Tells Raku to pick Iterable behavior. Also type checks that bound values do the Positional role. A List or Array can be bound, but trying to bind to 42 or a Hash will yield a type error.

%foo Tells Raku to pick Iterable behavior. Also type checks that bound values do the Associative role. A Pair or Bag can be bound, but trying to bind to 42 or a List will yield a type error.

I'll next consider your question for each sigil alternative.

Slashing out sigils

Repeating your examples, but this time "slashing out" sigils:

```<code>my \arr  = [1, 2, 3, 4, 5];      # an array
my \lst  = (1, 2, 3, 4, 5);      # a list
my \hash = {a => '1', b => '2'}; # a hash
my \func = -> \foo { say foo };  # a callable
</code>```

These almost just work exactly as expected:

```<code>say arr[0];     # 1
say lst[1];     # 2
say hash<a>;    # 1
say hash{'b'};  # 2
func.('hello'); # hello
</code>```

See the $ vs & below for why it's func.(...) not just func(...). This last nosigil case is of little consequence because in Raku one normally writes:

```<code>sub func (\foo) { say foo }
func('hello'); # hello
</code>```

Identifiers with their sigils slashed out are SSA form. That is to say, they are permanently bound, once, at compile-time, to their data. Value type data is immutable. A reference is also immutable (although the data it refers to can change), so for example, if it's an array, it will remain the same array.

(See Is there a purpose or benefit in prohibiting sigilless variables from rebinding? for further discussion.)

$foo instead of @foo?

Raku supports:

Lazy lists. (This can be very useful.)

A boolean .is-lazy method that indicates whether list assignment (@foo = ...) should treat an assigned object as lazy or eager. Importantly, a lazy list is allowed to return False. (This too can be very useful.)

Infinite lazy lists. (Yet another thing that can be very useful.)

The above three features are individually useful, and can be useful together. But while it is appropriate that Raku doesn't try to police these features other than the way it does, one needs to follow rules to avoid problems. And the simplest way to do that is to use the right sigil when it matters, as explained next.

Let's say infinite is an infinite lazy list that returns False for .is-lazy:

```<code>my $foo = infinite;
say $foo[10];        # displays 11th element
my @foo = infinite;
</code>```

The first two lines work fine. The third hangs, trying to copy an infinite number of elements into @foo.

Is it one thing or many things? Of course, if it's a list, it's both:

```<code>my $list = <a b c> ;
my @list = <a b c> ;
my \list = <a b c> ;
.say for $list ;      # (a b c)␤   <-- Treat as one thing
.say for @list ;      # a␤b␤c␤    <-- Treat as plural thing
.say for  list ;      # a␤b␤c␤    <-- Go by bound value, not sigil
</code>```

The choice of sigil in the above just indicates what view you want language constructs and readers to take by default. You can reverse yourself if you wish:

```<code>.say for @$list ;     # a␤b␤c␤
.say for $@list ;     # [a b c]␤
.say for $(list)      # (a b c)␤
</code>```

Assignment is different:

```<code>my ($numbers, $letters) = (1, 2, 3), ('a', 'b', 'c');
say $numbers;                                            # (1 2 3)
say $letters;                                            # (a b c)
my (@numbers, @letters) = (1, 2, 3), ('a', 'b', 'c');
say @numbers;                                            # [(1 2 3) (a b c)]
say @letters;                                            # []
</code>```

Assignment to an @ variable "slurps" all remaining arguments. (Binding with := and metaops like Z= invoke scalar semantics, i.e. don't slurp.)

We see another difference here; assigning to a $ variable is going to keep a List a List, but assigning to an @ variable "slurps" its values into whatever container the @ variable is bound to (by default, an Array).

A tiny thing is string interpolation:

```<code>my $list := 1, 2;
my @list := 1, 2;
say "\$list = $list; \@list = @list"; # $list = 1 2; @list = @list
say "@list @list[] @list[1]";         # @list 1 2 2
</code>```

$foo instead of %foo?

Again, is it one thing or many things? If it's a hash, it's both.

```<code>my @arr = (1, 2, 3, 4);
my %hash = (1 => 2, 3 => 4);

my $result1 = @arr[0];                          # <-- Invariant sigil
my $result2 = %hash{1};                         # <-- Invariant sigil

my $aref = [1, 2, 3, 4];
my $href = {1 => 2, 3 => 4};

my $aref2 = @arr;                               # <-- Drop `\`
my $href2 = %hash;                              # <-- Drop `\`

my $result3 = $aref[0];                         # <-- Drop `->`
my $result4 = $href{1};                         # <-- Drop `->`
</code>```0

Assignment and string interpolation are also different in a manner analogous to @.

$foo instead of &foo?

This section is just for completeness. It only shows one reason to use $. And I've just made it up for this answer -- I don't recall seeing anyone using it.

As with the other sigil alternatives, the primary difference would be whether you do or don't want to emphasize the Callable nature of a callable.

As the setup, note that a sub declaration in Raku declares a corresponding constant identifier with an & sigil:

```<code>my @arr = (1, 2, 3, 4);
my %hash = (1 => 2, 3 => 4);

my $result1 = @arr[0];                          # <-- Invariant sigil
my $result2 = %hash{1};                         # <-- Invariant sigil

my $aref = [1, 2, 3, 4];
my $href = {1 => 2, 3 => 4};

my $aref2 = @arr;                               # <-- Drop `\`
my $href2 = %hash;                              # <-- Drop `\`

my $result3 = $aref[0];                         # <-- Drop `->`
my $result4 = $href{1};                         # <-- Drop `->`
</code>```1

Which means that if you declare a mutable routine variable with the & sigil you can call it without the sigil:

```<code>my @arr = (1, 2, 3, 4);
my %hash = (1 => 2, 3 => 4);

my $result1 = @arr[0];                          # <-- Invariant sigil
my $result2 = %hash{1};                         # <-- Invariant sigil

my $aref = [1, 2, 3, 4];
my $href = {1 => 2, 3 => 4};

my $aref2 = @arr;                               # <-- Drop `\`
my $href2 = %hash;                              # <-- Drop `\`

my $result3 = $aref[0];                         # <-- Drop `->`
my $result4 = $href{1};                         # <-- Drop `->`
</code>```2

If you wanted to declare a mutable routine variable and not allow it to be easily called without a sigil you could declare it with $ instead:

```<code>my Callable $baz = { 101 }
say baz;                     # Undeclared routine: baz
say $baz();                  # 101   <-- Need both sigil and parens
</code>```

Btw, this is why you get:

```<code>my \func = -> \foo { say foo }
func('hello');  # Variable '&func' is not declared
</code>```

Reference literals

Q2: Are we dealing with Perl 5-like reference literals again, or is something else at play?

Despite your examples, knowing Perl (at least I did last century), and pondering what you've written, I'm still unclear what you're asking.

A wide range of programming languages adopt [...] in term (noun) position as a reference to a literal array. There are other common conventions for other data structure literals. This is what Raku does.

Thus one can write:

```<code>my $structure =
[ 0, [ 99, [ ( 1, 2, 3), { key => [ 4, 5, | < a b >, c => 42 ] } ], ], ] ;

say $structure[1][1][1]<key>[4]<c> ; # 42
</code>```

Is that the sort of thing you're talking about?

Dereference literals

postcircumfix:< [ ] > is declared as a pile of multi subs that (are supposed to) apply a Positional consistent indexing protocol on their left argument.

All built in types that do the Positional role work.

User defined types that do the Positional role should work because the role defines typed interface stubs that must be implemented by types that do the role.

But ducktyping is also OK; provided a type implements the basics of the interface postcircumfix:< [ ] > it should work.

The same story applies for postcircumfix:< { } > and postcircumfix:« < > », but the relevant role/protocol is Associative consistent indexing.

And a similar story applies for postcircumfix:< ( ) > and Callable.

Body:
I sometimes see code that (to me) uses the wrong sigil in front of the variable

my $arr  = [1, 2, 3, 4, 5];      # an array
my $lst  = (1, 2, 3, 4, 5);      # a list
my $hash = {a => '1', b => '2'}; # a hash
my $func = -> $foo { say $foo }; # a callable

And it all just works exactly as expected

say $arr[0];    # 1
say $lst[1];    # 2
say $hash;   # 1
say $hash{'b'}; # 2
$func('hello'); # hello

Q1: What are the benefits of using the scalar container for this, rather than just using the 'correct' one?

I know that Perl only let collections store scalars, requiring things like multi-dimensional arrays be done via array references, with [...] and {...} being array and hash reference literals respectively.

To expand and clarify what I mean here, there's basically two ways to define things, by value and by reference:

# "values"
my @arr = (1, 2, 3, 4);
my %hash = (1 => 2, 3 => 4);

# which are accessed like this:
my $result1 = $arr[0];
my $result2 = $hash{1};

# references (note how the braces canged)
my $aref = [1, 2, 3, 4];
my $href = {1 => 2, 3 => 4};

# or making a reference to existing collections
my $aref2 = \@arr;
my $href2 = \%hash;

# which are accessed like this:
my $result3 = $aref->[0];
my $result4 = $href->{1};

The reasoning behind this madness is that Perl collections only really accept scalars, and references are just that.
Using references is essentially a way to enable multidimensional arrays.

TL;DR, the distinction makes sense in Perl because they serve two distinctly different purposes.

Q2: Are we dealing with Perl 5-like reference literals again, or is something else at play?

Body:
TL;DR For computers, and humans, and therefore Raku too, a non-scalar (plural thing) is also a scalar (singular thing). (Whereas the converse may not be true.) For example, an Array is both a plural thing (an array of elements) and a single thing, an Array. When you wish to syntactically and statically emphasize a datum's most generic singular nature, use $.

Here's an opening example based on @sid_com++'s comment:

my @a = ( 1, 2 ), 42, { :a, :b }
for @a -> $b {say $b}            # (1 2)␤42␤{a => True, b => True}␤
for @a -> @b {say @b}            # (1 2)␤Type check failed ...

The first loop binds values to $b. It is "fault tolerant" because it accepts any value. The second loop binds to @b. Any value that doesn't do the Positional role leads to a type check failure.

My Raku equivalent of your Perl code

Here's a Raku translation of your Perl code:

my @arr = (1, 2, 3, 4);
my %hash = (1 => 2, 3 => 4);

my $result1 = @arr[0];                          # <-- Invariant sigil
my $result2 = %hash{1};                         # <-- Invariant sigil

my $aref = [1, 2, 3, 4];
my $href = {1 => 2, 3 => 4};

my $aref2 = @arr;                               # <-- Drop `\`
my $href2 = %hash;                              # <-- Drop `\`

my $result3 = $aref[0];                         # <-- Drop `->`
my $result4 = $href{1};                         # <-- Drop `->`

The code is a little shorter. Idiomatic code would probably be a good bit shorter still, dropping:

The ref variables. A variable @foo is a reference. A [...] in term (noun) position is an Array reference literal. There's little or no need to use scalar variables to explicitly store references.

The parens in the first couple lines;

Semi colons after most closing braces that are the last code on a line;

Raku's sigils are invariant. Here are two tables providing an at-a-glance comparison of Perl's sigil variation vs Raku's sigil invariance.

Why bother with sigils?

All the sigil variations directly correspond to embedding "type" info into an identifier's name that's visible to humans, the language, and the compiler:

foo Tells Raku features which pick between a singular and plural way of operating on data should decide based on the run-time type of the data.

$foo Tells Raku to pick singular behavior. A value might be, say, a List containing many values, but its singular nature is being emphasized instead.

&foo Type checks that a bound or assigned value does the Callable role.

@foo Tells Raku to pick Iterable behavior. Also type checks that bound values do the Positional role. A List or Array can be bound, but trying to bind to 42 or a Hash will yield a type error.

%foo Tells Raku to pick Iterable behavior. Also type checks that bound values do the Associative role. A Pair or Bag can be bound, but trying to bind to 42 or a List will yield a type error.

I'll next consider your question for each sigil alternative.

Slashing out sigils

Repeating your examples, but this time "slashing out" sigils:

my \arr  = [1, 2, 3, 4, 5];      # an array
my \lst  = (1, 2, 3, 4, 5);      # a list
my \hash = {a => '1', b => '2'}; # a hash
my \func = -> \foo { say foo };  # a callable

These almost just work exactly as expected:

say arr[0];     # 1
say lst[1];     # 2
say hash<a>;    # 1
say hash{'b'};  # 2
func.('hello'); # hello

See the $ vs & below for why it's func.(...) not just func(...). This last nosigil case is of little consequence because in Raku one normally writes:

sub func (\foo) { say foo }
func('hello'); # hello

Identifiers with their sigils slashed out are SSA form. That is to say, they are permanently bound, once, at compile-time, to their data. Value type data is immutable. A reference is also immutable (although the data it refers to can change), so for example, if it's an array, it will remain the same array.

(See Is there a purpose or benefit in prohibiting sigilless variables from rebinding? for further discussion.)

$foo instead of @foo?

Raku supports:

Lazy lists. (This can be very useful.)

A boolean .is-lazy method that indicates whether list assignment (@foo = ...) should treat an assigned object as lazy or eager. Importantly, a lazy list is allowed to return False. (This too can be very useful.)

Infinite lazy lists. (Yet another thing that can be very useful.)

The above three features are individually useful, and can be useful together. But while it is appropriate that Raku doesn't try to police these features other than the way it does, one needs to follow rules to avoid problems. And the simplest way to do that is to use the right sigil when it matters, as explained next.

Let's say infinite is an infinite lazy list that returns False for .is-lazy:

my $foo = infinite;
say $foo[10];        # displays 11th element
my @foo = infinite;

The first two lines work fine. The third hangs, trying to copy an infinite number of elements into @foo.

Is it one thing or many things? Of course, if it's a list, it's both:

my $list = <a b c> ;
my @list = <a b c> ;
my \list = <a b c> ;
.say for $list ;      # (a b c)␤   <-- Treat as one thing
.say for @list ;      # a␤b␤c␤    <-- Treat as plural thing
.say for  list ;      # a␤b␤c␤    <-- Go by bound value, not sigil

The choice of sigil in the above just indicates what view you want language constructs and readers to take by default. You can reverse yourself if you wish:

.say for @$list ;     # a␤b␤c␤
.say for $@list ;     # [a b c]␤
.say for $(list)      # (a b c)␤

Assignment is different:

my ($numbers, $letters) = (1, 2, 3), ('a', 'b', 'c');
say $numbers;                                            # (1 2 3)
say $letters;                                            # (a b c)
my (@numbers, @letters) = (1, 2, 3), ('a', 'b', 'c');
say @numbers;                                            # [(1 2 3) (a b c)]
say @letters;                                            # []

Assignment to an @ variable "slurps" all remaining arguments. (Binding with := and metaops like Z= invoke scalar semantics, i.e. don't slurp.)

We see another difference here; assigning to a $ variable is going to keep a List a List, but assigning to an @ variable "slurps" its values into whatever container the @ variable is bound to (by default, an Array).

A tiny thing is string interpolation:

my $list := 1, 2;
my @list := 1, 2;
say "\$list = $list; \@list = @list"; # $list = 1 2; @list = @list
say "@list @list[] @list[1]";         # @list 1 2 2

$foo instead of %foo?

Again, is it one thing or many things? If it's a hash, it's both.

my $hash = { :a, :b }
my %hash =   :a, :b ;
my \hash = { :a, :b }
.say for $hash ;      # {a => True, b => True}␤   <-- By sorted keys
.say for %hash ;      # {b => True}␤{a => True}␤  <-- Random order
.say for  hash ;      # {a => True}␤{b => True}␤  <-- Random order

Assignment and string interpolation are also different in a manner analogous to @.

$foo instead of &foo?

This section is just for completeness. It only shows one reason to use $. And I've just made it up for this answer -- I don't recall seeing anyone using it.

As with the other sigil alternatives, the primary difference would be whether you do or don't want to emphasize the Callable nature of a callable.

As the setup, note that a sub declaration in Raku declares a corresponding constant identifier with an & sigil:

sub foo (--> Int) { 42 }
say foo;                     # 42
say &foo.signature;          # ( --> Int)
&foo = 99;                   # Cannot modify an immutable Sub...

Which means that if you declare a mutable routine variable with the & sigil you can call it without the sigil:

my &bar = { 99 }
say bar;                     # 99
&bar = { 100 }
say bar;                     # 100

If you wanted to declare a mutable routine variable and not allow it to be easily called without a sigil you could declare it with $ instead:

my Callable $baz = { 101 }
say baz;                     # Undeclared routine: baz
say $baz();                  # 101   <-- Need both sigil and parens

Btw, this is why you get:

my \func = -> \foo { say foo }
func('hello');  # Variable '&func' is not declared

Reference literals

Q2: Are we dealing with Perl 5-like reference literals again, or is something else at play?

Despite your examples, knowing Perl (at least I did last century), and pondering what you've written, I'm still unclear what you're asking.

A wide range of programming languages adopt [...] in term (noun) position as a reference to a literal array. There are other common conventions for other data structure literals. This is what Raku does.

Thus one can write:

my $structure =
[ 0, [ 99, [ ( 1, 2, 3), { key => [ 4, 5, | < a b >, c => 42 ] } ], ], ] ;

say $structure[1][1][1]<key>[4]<c> ; # 42

Is that the sort of thing you're talking about?

Dereference literals

postcircumfix:< [ ] > is declared as a pile of multi subs that (are supposed to) apply a Positional consistent indexing protocol on their left argument.

All built in types that do the Positional role work.

User defined types that do the Positional role should work because the role defines typed interface stubs that must be implemented by types that do the role.

But ducktyping is also OK; provided a type implements the basics of the interface postcircumfix:< [ ] > it should work.

The same story applies for postcircumfix:< { } > and postcircumfix:« < > », but the relevant role/protocol is Associative consistent indexing.

And a similar story applies for postcircumfix:< ( ) > and Callable.


问:
How can I display Touch Bar Buttons using SwiftUI?
I'm trying to add Touch Bar support for a SwiftUI View. There seems to be SwiftUI API for this using the .touchBar(content: () -> View) function on Views, but documentation is non existent and I can't get my Touch Bar to display anything.

```<code>import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .touchBar {
                Button(action: {

                }) {
                    Text("do something")
                }
        }
    }
}
</code>```

This code does compile and run, but the Touch Bar remains empty. How can I get my touch bar to display content using SwiftUI (not catalyst)?

答:
Using .focusable doesn't work without "Use keyboard navigation to move focus between controls" checked in System Preferences -> Keyboard -> Shortcuts. To work around that, I did this:

```<code>/// Bit of a hack to enable touch bar support.
class FocusNSView: NSView {
    override var acceptsFirstResponder: Bool {
        return true
    }
}

/// Gets the keyboard focus if nothing else is focused.
struct FocusView: NSViewRepresentable {

    func makeNSView(context: NSViewRepresentableContext<FocusView>) -> FocusNSView {
        return FocusNSView()
    }

    func updateNSView(_ nsView: FocusNSView, context: Context) {

        // Delay making the view the first responder to avoid SwiftUI errors.
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            if let window = nsView.window {

                // Only set the focus if nothing else is focused.
                if let _ = window.firstResponder as? NSWindow {
                    window.makeFirstResponder(nsView)
                }
            }
        }
    }
}
</code>```

Body:
I'm trying to add Touch Bar support for a SwiftUI View. There seems to be SwiftUI API for this using the .touchBar(content: () -> View) function on Views, but documentation is non existent and I can't get my Touch Bar to display anything.

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .touchBar {
                Button(action: {

                }) {
                    Text("do something")
                }
        }
    }
}

This code does compile and run, but the Touch Bar remains empty. How can I get my touch bar to display content using SwiftUI (not catalyst)?

Body:
Using .focusable doesn't work without "Use keyboard navigation to move focus between controls" checked in System Preferences -> Keyboard -> Shortcuts. To work around that, I did this:

/// Bit of a hack to enable touch bar support.
class FocusNSView: NSView {
    override var acceptsFirstResponder: Bool {
        return true
    }
}

/// Gets the keyboard focus if nothing else is focused.
struct FocusView: NSViewRepresentable {

    func makeNSView(context: NSViewRepresentableContext<FocusView>) -> FocusNSView {
        return FocusNSView()
    }

    func updateNSView(_ nsView: FocusNSView, context: Context) {

        // Delay making the view the first responder to avoid SwiftUI errors.
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            if let window = nsView.window {

                // Only set the focus if nothing else is focused.
                if let _ = window.firstResponder as? NSWindow {
                    window.makeFirstResponder(nsView)
                }
            }
        }
    }
}


问:
How can I start my Windows service on startup, and prevent users from stopping/restarting it?
i have developed the window service. in this i want to start the service only when starting the computer. user can not start/stop/restart the service.manually these all thing are handle when user start the computer.

or lock the all properties from the user.all working done by coding when we start the computer.

答: Would you want some software installed on your PC to prevent you from starting or stopping it and just automatically forcing it to run....? I don't think so, this is a bad idea and am pretty sure security settings in windows will not allow this...</p>


问:
How can use payment getway in Laravel API
I just made an api with Laravel, and front with ReactJS, but I'm wondering how can I use payment getway in this project, I want to use this getway

What I tried:

```<code>$zarinpal = new Zarinpal('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX');
$zarinpal->isZarinGate(); // active zarinGate mode
$results = $zarinpal->request(
    "example.com/testVerify.php",
    1000,
    'testing',
    'me@example.com',
    '09000000000',
);

if (isset($results['Authority'])) {
    file_put_contents('Authority', $results['Authority']);
    $zarinpal->redirect();
}
</code>```

It successfully get $results['Authority']) but it won't redirect to getway, clearly because I am using laravel as api, right? so how can I do this while I using api?

It give me this error:

Access to XMLHttpRequest at 'http://localhost:8000/api/deposit/agent'
  from origin 'http://localhost:3000' has been blocked by CORS policy:
  No 'Access-Control-Allow-Origin' header is present on the requested
  resource.

POST http://localhost:8000/api/deposit/agent net::ERR_FAILED

But I don't have CORS issue on api request, it just give me this error on this action

答:
It is not the problem of Payment Gate Way. Just the cross-origin header problem.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

An example of a cross-origin request: the front-end JavaScript code served from https://domain-a.com uses XMLHttpRequest to make a request for https://domain-b.com/data.json.

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.

You can still send the header from a PHP script. It's a case of adding the following to your PHP scripts:

```<code> <?php
 header("Access-Control-Allow-Origin: *");
?>
</code>```

Body:
I just made an api with Laravel, and front with ReactJS, but I'm wondering how can I use payment getway in this project, I want to use this getway

What I tried:

$zarinpal = new Zarinpal('XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX');
$zarinpal->isZarinGate(); // active zarinGate mode
$results = $zarinpal->request(
    "example.com/testVerify.php",
    1000,
    'testing',
    'me@example.com',
    '09000000000',
);

if (isset($results['Authority'])) {
    file_put_contents('Authority', $results['Authority']);
    $zarinpal->redirect();
}

It successfully get $results['Authority']) but it won't redirect to getway, clearly because I am using laravel as api, right? so how can I do this while I using api?

It give me this error:

Access to XMLHttpRequest at 'http://localhost:8000/api/deposit/agent'
  from origin 'http://localhost:3000' has been blocked by CORS policy:
  No 'Access-Control-Allow-Origin' header is present on the requested
  resource.

POST http://localhost:8000/api/deposit/agent net::ERR_FAILED

But I don't have CORS issue on api request, it just give me this error on this action

Body:
It is not the problem of Payment Gate Way. Just the cross-origin header problem.
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

An example of a cross-origin request: the front-end JavaScript code served from https://domain-a.com uses XMLHttpRequest to make a request for https://domain-b.com/data.json.

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from unless the response from other origins includes the right CORS headers.

You can still send the header from a PHP script. It's a case of adding the following to your PHP scripts:

 <?php
 header("Access-Control-Allow-Origin: *");
?>


问:
C++ copy construct rvalue reference question
I'm learning the rvalue reference concept in c++.

When testing the following code, I found the "fun" was called despite it not using fun(abc &&) to accept the temporary object(prvalue).

```<code>
class abc
{
};
void fun(abc &)
{
    cout << 1111111 << endl;
}
void main()
{
    fun(abc());
}

</code>```

output: 1111111

If this is allowed due to temporary materialisation

Why does the following code fail to compile?

```<code>void fun(int &)
{
    cout << 1111111 << endl;
}
void main()
{
    fun(5);
}

</code>```

Output: Compiler error!

many thanks

答:
```<code>void fun(int &)
{
    cout << 1111111 << endl;
}
void main()
{
    fun(5);
}
</code>```

doesnt compile because you cannot pass a reference to a literal to a function that expects a reference to a modifiable variable. Although you dont change it, you might

this works

```<code>void fun(const int &)
{
    cout << 1111111 << endl;
}
void main()
{
    fun(5);
}
</code>```

Body:
I'm learning the rvalue reference concept in c++.

When testing the following code, I found the "fun" was called despite it not using fun(abc &&) to accept the temporary object(prvalue).

class abc
{
};
void fun(abc &)
{
    cout << 1111111 << endl;
}
void main()
{
    fun(abc());
}

output: 1111111

If this is allowed due to temporary materialisation

Why does the following code fail to compile?

void fun(int &)
{
    cout << 1111111 << endl;
}
void main()
{
    fun(5);
}

Output: Compiler error!

many thanks

Body:
void fun(int &)
{
    cout << 1111111 << endl;
}
void main()
{
    fun(5);
}

doesnt compile because you cannot pass a reference to a literal to a function that expects a reference to a modifiable variable. Although you dont change it, you might

this works

void fun(const int &)
{
    cout << 1111111 << endl;
}
void main()
{
    fun(5);
}


问:
Issue in creating drop down list using VBA. Code mentioned below creates drop down list but needs repair every time the file is reopened
The code mentioned below is generating dropdown list 0-100 for each cell up to 1500 rows. Although once this excel file is reopened it crashes and shifts to auto-recovery stating "Removed Feature: Data validation from /xl/worksheets/sheet1.xml part". This leads to first saving the recovered file and then proceeding with the work. Please help me to find and resolve the issue. </p>

```<code>Private Sub sSlot_Number()
Dim i, j As Integer
Dim Astr As String
i = 0
j = 0

For j = 0 To 100
   Astr = Astr & "," & j          'To contain 0 to 100 numbers in Astr for creating dropdown list
Next j

Do While i < 1499
With ThisWorkbook.Worksheets(1).Cells(2 + i, 2).Validation
 .Delete
 .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
 Operator:=xlBetween, Formula1:=Astr        'Drop down list with value 0 to 100 for cells upto Row 1500
 .IgnoreBlank = True
 .InCellDropdown = True
 .InputTitle = ""
 .ErrorTitle = ""
 .InputMessage = ""
 .ErrorMessage = ""
 .ShowInput = True
 .ShowError = True
End With
i = i + 1
Loop
End Sub
</code>```

答: The length limit for Formula1 is 256 characters: you have 294 characters in Astr.  You could set up equivalent validation without using a list, or you could point the validation to a list range on a (hidden) worksheet.

Body:
The code mentioned below is generating dropdown list 0-100 for each cell up to 1500 rows. Although once this excel file is reopened it crashes and shifts to auto-recovery stating "Removed Feature: Data validation from /xl/worksheets/sheet1.xml part". This leads to first saving the recovered file and then proceeding with the work. Please help me to find and resolve the issue.

Private Sub sSlot_Number()
Dim i, j As Integer
Dim Astr As String
i = 0
j = 0

For j = 0 To 100
   Astr = Astr & "," & j          'To contain 0 to 100 numbers in Astr for creating dropdown list
Next j

Do While i < 1499
With ThisWorkbook.Worksheets(1).Cells(2 + i, 2).Validation
 .Delete
 .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
 Operator:=xlBetween, Formula1:=Astr        'Drop down list with value 0 to 100 for cells upto Row 1500
 .IgnoreBlank = True
 .InCellDropdown = True
 .InputTitle = ""
 .ErrorTitle = ""
 .InputMessage = ""
 .ErrorMessage = ""
 .ShowInput = True
 .ShowError = True
End With
i = i + 1
Loop
End Sub


问:
AWS Elastic Beanstalk: WSGI path incorrect?
I'm attempting to deploy my first application to EB and am following along with this turorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html

Unfortunately, I'm still getting a 502 error when deploying the final app. I'm confused because I've followed the directions to the tee.

I'm getting the following error

```<code>ImportError: Failed to find application, did you mean 'ebdjango/wsgi:application'?
</code>```

I'm not sure what this means. Per the instructions, I edited the django.config file to include this text:

```<code>option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: ebdjango/wsgi.py
</code>```

This appears to match my file structure:

```<code>- ebdjango
  -.ebextensions
    - django.config
  - .elasticbeanstalk
  - ebdjango
    _ __init__.py
    - settings.py
    - urls.py
    - wsgi.py
  - manage.py
  - requirements.txt
</code>```

So the config file is set up correctly, right?

I'm running Python 3.7 and Django 2.2.

I know that EB searches for application.py, and I thought the config file is supposed to point the server towards my custom app? What am I missing here?

EDIT: I'm also getting this error:

```<code>ModuleNotFoundError: No module named 'ebdjango/wsgi'
</code>```

Is something off about my file structure?

EDIT 2: I forgot to include the init.py file in my post, see Ben's comment.

答:
I had the same issue. It is because of the Amazon Linux 2 machine image. Its configuration files are incompatible with those of the old version. Please see: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.migration-al.html. I ended up using the old version because the documentation says:

If you're using an Amazon Linux 2 platform version that is in beta for
  your evaluation, do not go to production. Wait until we release a
  supported platform version.

You can create an Elastic Beanstalk environment using the Amazon Linux machine image (old version) using the command line tool. Here are the commands (replace <...> with your data):

```<code>eb init -p python-3.6 <ApplicationName> --region <Region>
eb create <EnvironmentName> --elb-type application --platform "64bit Amazon Linux 2018.03 v2.9.10 running Python 3.6"
</code>```

Update 2020-06-02
As I mentioned before, the issue is caused by Amazon Linux 2 platform because it uses Gunicorn, which has a WSGI syntax that is different than the previous version. The WSGIPath must be ebdjango.wsgi:application. Please see https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html#python-namespaces.

Body:
I'm attempting to deploy my first application to EB and am following along with this turorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html

Unfortunately, I'm still getting a 502 error when deploying the final app. I'm confused because I've followed the directions to the tee.

I'm getting the following error

ImportError: Failed to find application, did you mean 'ebdjango/wsgi:application'?

I'm not sure what this means. Per the instructions, I edited the django.config file to include this text:

option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: ebdjango/wsgi.py

This appears to match my file structure:

- ebdjango
  -.ebextensions
    - django.config
  - .elasticbeanstalk
  - ebdjango
    _ __init__.py
    - settings.py
    - urls.py
    - wsgi.py
  - manage.py
  - requirements.txt

So the config file is set up correctly, right?

I'm running Python 3.7 and Django 2.2.

I know that EB searches for application.py, and I thought the config file is supposed to point the server towards my custom app? What am I missing here?

EDIT: I'm also getting this error:

ModuleNotFoundError: No module named 'ebdjango/wsgi'

Is something off about my file structure?

EDIT 2: I forgot to include the init.py file in my post, see Ben's comment.

Body:
I had the same issue. It is because of the Amazon Linux 2 machine image. Its configuration files are incompatible with those of the old version. Please see: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.migration-al.html. I ended up using the old version because the documentation says:

If you're using an Amazon Linux 2 platform version that is in beta for
  your evaluation, do not go to production. Wait until we release a
  supported platform version.

You can create an Elastic Beanstalk environment using the Amazon Linux machine image (old version) using the command line tool. Here are the commands (replace <...> with your data):

eb init -p python-3.6 <ApplicationName> --region <Region>
eb create <EnvironmentName> --elb-type application --platform "64bit Amazon Linux 2018.03 v2.9.10 running Python 3.6"

Update 2020-06-02
As I mentioned before, the issue is caused by Amazon Linux 2 platform because it uses Gunicorn, which has a WSGI syntax that is different than the previous version. The WSGIPath must be ebdjango.wsgi:application. Please see https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-container.html#python-namespaces.