问:
string index out of range? in django post request
I'm getting error string index out of range when I getting simple text from post request and want to show data in array.

```<code>[["daveen brewster 218 tokay drive \u25aa fayetteville nc 28301 \u25aa 910 527 2739 email divineb79@gmail.com professional profile customer service orient professional with healthcare industry experience accustom to work in environment where accuracy and accountability be essential consistently model and inspire high level of integrity follow policy procedure and guideline to assure consistent quality \u25aa \u25aa \u25aa adaptable adapt to change situation and expectation and accept new idea and concept time management manage time and priority to meet goal deadline and objective problem solver identify and define a problem generate solution and determine appropriate strategy microsoft office application word excel outlook and powerpoint key qualification medical administrative assistant \u25aa medical terminology \u25aa medical transcription patient processing \u25aa patient registration \u25aa medical record management \u25aa check in \u25aa check out \u25aa datum entry release of information \u25aa hipaa compliance \u25aa medical law ethic \u25aa cms 1500 claim form \u25aa billing cycle claim appeal process \u25aa medical billing knowledge \u25aa third party billing \u25aa medicare \u25aa medicaid \u25aa hmo \u25aa ppo basic code skill for icd-10 cpt \u25aa insurance verification \u25aa anatomy physiology education ultimate medical academy \u2502 associate of science degree health science medical administrative assistant 2021 ultimate medical academy \u2502 hipaa essential for healthcare professional certificate north carolina department of health and human service | nurse aide 1 training professional experience alorica irvin ca 10/2020 present customer service representative temporarily remote call center \u25aa receive inbound phone call and interact with customer to resolve question and concern \u25aa track call relate information maintain and update account and cancel policy \u25aa enroll prospective customer in insurance policy blue cross blue shield humana aetna \u25aa utilize webrtc and vmware system add payment information on customer account and transfer to billing department to process payment private duty care fayetteville nc 01/2016 01/2019 inman home health care fayetteville nc 05/2007 02/2013 certify nursing assistant \u25aa assist with activity of daily living personal hygiene mobility and feeding \u25aa take and record vital sign and perform service in a timely and professional manner \u25aa document and report change in patient habit condition and activity \u25aa help patient with medication and monitor change in behavior \u25aa schedule appointment for patient transport to and from appoin tment and communicate with doctor additional professional experience include 1 + year of experience as a patient care liaison certify nursing assistant kitchen manager volunteer experience alive ministry fayetteville nc youth counselor \u25aa assist youth with schoolwork and personal issue \u25aa facilitated trip and assist with college and job application 01/2004 01/2020 \u25aa maintain positive attitude show respect to all those with whom there be contact while perform duty", {"entities": [[667, 685, "SKILL"], [686, 690, "SKILL"], [746, 760, "SKILL"], [795, 816, "SKILL"], [838, 858, "SKILL"], [949, 965, "SKILL"], [1075, 1094, "SKILL"], [1108, 1116, "SKILL"], [1135, 1139, "SKILL"], [1150, 1156, "SKILL"], [1157, 1160, "SKILL"], [1163, 1185, "SKILL"], [1188, 1195, "SKILL"], [1196, 1206, "SKILL"], [1746, 1753, "SKILL"], [1868, 1874, "SKILL"], [2104, 2111, "SKILL"], [2170, 2177, "SKILL"], [2178, 2186, "SKILL"]]}]]
</code>```

when i run this query in jupyter notebook then working fine and getting data from this array but when i getting with the help of post request in django and getting in views then getting string index out of range
This is code which I'm using.

```<code><form action="{% url 'text_extracted' %}" method="POST">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="comment">Json:</label>
                            <textarea class="form-control" rows="10" id="json_text" name="json_text" required></textarea>
                        </div>
                        <input type="submit" class="btn btn-block btn-primary">
                    </form>
</code>```
```<code>def text_extracted(request):

    if request.method == 'POST':
        json_text = request.POST['json_text']
        for span in json_text:
            for ent in span[1]['entities']:
                print(json_text[0][0][ent[0]:ent[1]])

    return HttpResponse("Ok")
</code>```

Update:
I'm getting this in request
print(request.POST['json_text'])

```<code>[
        ["daveen brewster 218 tokay drive \u25aa fayetteville nc 28301 \u25aa 910 527 2739 email divineb79@gmail.com professional profile customer service orient professional with healthcare industry experience accustom to work in environment where accuracy and accountability be essential consistently model and inspire high level of integrity follow policy procedure and guideline to assure consistent quality \u25aa \u25aa \u25aa adaptable adapt to change situation and expectation and accept new idea and concept time management manage time and priority to meet goal deadline and objective problem solver identify and define a problem generate solution and determine appropriate strategy microsoft office application word excel outlook and powerpoint key qualification medical administrative assistant \u25aa medical terminology \u25aa medical transcription patient processing \u25aa patient registration \u25aa medical record management \u25aa check in \u25aa check out \u25aa datum entry release of information \u25aa hipaa compliance \u25aa medical law ethic \u25aa cms 1500 claim form \u25aa billing cycle claim appeal process \u25aa medical billing knowledge \u25aa third party billing \u25aa medicare \u25aa medicaid \u25aa hmo \u25aa ppo basic code skill for icd-10 cpt \u25aa insurance verification \u25aa anatomy physiology education ultimate medical academy \u2502 associate of science degree health science medical administrative assistant 2021 ultimate medical academy \u2502 hipaa essential for healthcare professional certificate north carolina department of health and human service | nurse aide 1 training professional experience alorica irvin ca 10/2020 present customer service representative temporarily remote call center \u25aa receive inbound phone call and interact with customer to resolve question and concern \u25aa track call relate information maintain and update account and cancel policy \u25aa enroll prospective customer in insurance policy blue cross blue shield humana aetna \u25aa utilize webrtc and vmware system add payment information on customer account and transfer to billing department to process payment private duty care fayetteville nc 01/2016 01/2019 inman home health care fayetteville nc 05/2007 02/2013 certify nursing assistant \u25aa assist with activity of daily living personal hygiene mobility and feeding \u25aa take and record vital sign and perform service in a timely and professional manner \u25aa document and report change in patient habit condition and activity \u25aa help patient with medication and monitor change in behavior \u25aa schedule appointment for patient transport to and from appoin tment and communicate with doctor additional professional experience include 1 + year of experience as a patient care liaison certify nursing assistant kitchen manager volunteer experience alive ministry fayetteville nc youth counselor \u25aa assist youth with schoolwork and personal issue \u25aa facilitated trip and assist with college and job application 01/2004 01/2020 \u25aa maintain positive attitude show respect to all those with whom there be contact while perform duty", {
                "entities": [
                        [667, 685, "SKILL"],
                        [686, 690, "SKILL"],
                        [746, 760, "SKILL"],
                        [795, 816, "SKILL"],
                        [838, 858, "SKILL"],
                        [949, 965, "SKILL"],
                        [1075, 1094, "SKILL"],
                        [1108, 1116, "SKILL"],
                        [1135, 1139, "SKILL"],
                        [1150, 1156, "SKILL"],
                        [1157, 1160, "SKILL"],
                        [1163, 1185, "SKILL"],
                        [1188, 1195, "SKILL"],
                        [1196, 1206, "SKILL"],
                        [1746, 1753, "SKILL"],
                        [1868, 1874, "SKILL"],
                        [2104, 2111, "SKILL"],
                        [2170, 2177, "SKILL"],
                        [2178, 2186, "SKILL"]
                ]
        }]
]
</code>```

答:
I believe the response is coming back in plain text and not a ready to use dictionary.
Try the following using json.loads:

def text_extracted(request):
    import json
    if request.method == 'POST':
        json_text = json.loads(request.POST['json_text'])
        for span in json_text:
            for ent in span[1]['entities']:
                print(json_text[0][0][ent[0]:ent[1]])

    return HttpResponse("Ok")
```

Body:
I'm getting error string index out of range when I getting simple text from post request and want to show data in array.

[["daveen brewster 218 tokay drive \u25aa fayetteville nc 28301 \u25aa 910 527 2739 email divineb79@gmail.com professional profile customer service orient professional with healthcare industry experience accustom to work in environment where accuracy and accountability be essential consistently model and inspire high level of integrity follow policy procedure and guideline to assure consistent quality \u25aa \u25aa \u25aa adaptable adapt to change situation and expectation and accept new idea and concept time management manage time and priority to meet goal deadline and objective problem solver identify and define a problem generate solution and determine appropriate strategy microsoft office application word excel outlook and powerpoint key qualification medical administrative assistant \u25aa medical terminology \u25aa medical transcription patient processing \u25aa patient registration \u25aa medical record management \u25aa check in \u25aa check out \u25aa datum entry release of information \u25aa hipaa compliance \u25aa medical law ethic \u25aa cms 1500 claim form \u25aa billing cycle claim appeal process \u25aa medical billing knowledge \u25aa third party billing \u25aa medicare \u25aa medicaid \u25aa hmo \u25aa ppo basic code skill for icd-10 cpt \u25aa insurance verification \u25aa anatomy physiology education ultimate medical academy \u2502 associate of science degree health science medical administrative assistant 2021 ultimate medical academy \u2502 hipaa essential for healthcare professional certificate north carolina department of health and human service | nurse aide 1 training professional experience alorica irvin ca 10/2020 present customer service representative temporarily remote call center \u25aa receive inbound phone call and interact with customer to resolve question and concern \u25aa track call relate information maintain and update account and cancel policy \u25aa enroll prospective customer in insurance policy blue cross blue shield humana aetna \u25aa utilize webrtc and vmware system add payment information on customer account and transfer to billing department to process payment private duty care fayetteville nc 01/2016 01/2019 inman home health care fayetteville nc 05/2007 02/2013 certify nursing assistant \u25aa assist with activity of daily living personal hygiene mobility and feeding \u25aa take and record vital sign and perform service in a timely and professional manner \u25aa document and report change in patient habit condition and activity \u25aa help patient with medication and monitor change in behavior \u25aa schedule appointment for patient transport to and from appoin tment and communicate with doctor additional professional experience include 1 + year of experience as a patient care liaison certify nursing assistant kitchen manager volunteer experience alive ministry fayetteville nc youth counselor \u25aa assist youth with schoolwork and personal issue \u25aa facilitated trip and assist with college and job application 01/2004 01/2020 \u25aa maintain positive attitude show respect to all those with whom there be contact while perform duty", {"entities": [[667, 685, "SKILL"], [686, 690, "SKILL"], [746, 760, "SKILL"], [795, 816, "SKILL"], [838, 858, "SKILL"], [949, 965, "SKILL"], [1075, 1094, "SKILL"], [1108, 1116, "SKILL"], [1135, 1139, "SKILL"], [1150, 1156, "SKILL"], [1157, 1160, "SKILL"], [1163, 1185, "SKILL"], [1188, 1195, "SKILL"], [1196, 1206, "SKILL"], [1746, 1753, "SKILL"], [1868, 1874, "SKILL"], [2104, 2111, "SKILL"], [2170, 2177, "SKILL"], [2178, 2186, "SKILL"]]}]]

when i run this query in jupyter notebook then working fine and getting data from this array but when i getting with the help of post request in django and getting in views then getting string index out of range
This is code which I'm using.

<form action="{% url 'text_extracted' %}" method="POST">
                        {% csrf_token %}

                            Json:
                            <textarea class="form-control" rows="10" id="json_text" name="json_text" required></textarea>

                        <input type="submit" class="btn btn-block btn-primary">
                    </form>

def text_extracted(request):

    if request.method == 'POST':
        json_text = request.POST['json_text']
        for span in json_text:
            for ent in span[1]['entities']:
                print(json_text[0][0][ent[0]:ent[1]])

    return HttpResponse("Ok")

Update:
I'm getting this in request
print(request.POST['json_text'])

[
        ["daveen brewster 218 tokay drive \u25aa fayetteville nc 28301 \u25aa 910 527 2739 email divineb79@gmail.com professional profile customer service orient professional with healthcare industry experience accustom to work in environment where accuracy and accountability be essential consistently model and inspire high level of integrity follow policy procedure and guideline to assure consistent quality \u25aa \u25aa \u25aa adaptable adapt to change situation and expectation and accept new idea and concept time management manage time and priority to meet goal deadline and objective problem solver identify and define a problem generate solution and determine appropriate strategy microsoft office application word excel outlook and powerpoint key qualification medical administrative assistant \u25aa medical terminology \u25aa medical transcription patient processing \u25aa patient registration \u25aa medical record management \u25aa check in \u25aa check out \u25aa datum entry release of information \u25aa hipaa compliance \u25aa medical law ethic \u25aa cms 1500 claim form \u25aa billing cycle claim appeal process \u25aa medical billing knowledge \u25aa third party billing \u25aa medicare \u25aa medicaid \u25aa hmo \u25aa ppo basic code skill for icd-10 cpt \u25aa insurance verification \u25aa anatomy physiology education ultimate medical academy \u2502 associate of science degree health science medical administrative assistant 2021 ultimate medical academy \u2502 hipaa essential for healthcare professional certificate north carolina department of health and human service | nurse aide 1 training professional experience alorica irvin ca 10/2020 present customer service representative temporarily remote call center \u25aa receive inbound phone call and interact with customer to resolve question and concern \u25aa track call relate information maintain and update account and cancel policy \u25aa enroll prospective customer in insurance policy blue cross blue shield humana aetna \u25aa utilize webrtc and vmware system add payment information on customer account and transfer to billing department to process payment private duty care fayetteville nc 01/2016 01/2019 inman home health care fayetteville nc 05/2007 02/2013 certify nursing assistant \u25aa assist with activity of daily living personal hygiene mobility and feeding \u25aa take and record vital sign and perform service in a timely and professional manner \u25aa document and report change in patient habit condition and activity \u25aa help patient with medication and monitor change in behavior \u25aa schedule appointment for patient transport to and from appoin tment and communicate with doctor additional professional experience include 1 + year of experience as a patient care liaison certify nursing assistant kitchen manager volunteer experience alive ministry fayetteville nc youth counselor \u25aa assist youth with schoolwork and personal issue \u25aa facilitated trip and assist with college and job application 01/2004 01/2020 \u25aa maintain positive attitude show respect to all those with whom there be contact while perform duty", {
                "entities": [
                        [667, 685, "SKILL"],
                        [686, 690, "SKILL"],
                        [746, 760, "SKILL"],
                        [795, 816, "SKILL"],
                        [838, 858, "SKILL"],
                        [949, 965, "SKILL"],
                        [1075, 1094, "SKILL"],
                        [1108, 1116, "SKILL"],
                        [1135, 1139, "SKILL"],
                        [1150, 1156, "SKILL"],
                        [1157, 1160, "SKILL"],
                        [1163, 1185, "SKILL"],
                        [1188, 1195, "SKILL"],
                        [1196, 1206, "SKILL"],
                        [1746, 1753, "SKILL"],
                        [1868, 1874, "SKILL"],
                        [2104, 2111, "SKILL"],
                        [2170, 2177, "SKILL"],
                        [2178, 2186, "SKILL"]
                ]
        }]
]


来源: stackexchange

问:
How to convert multiple rows with same ID to single rows
I have a dataset1 which is as follows (table 1) :

```<code>structure(list(TCODE = c("T1", "T1", "T1", "T2", "T2", "T2",
"T2", "T2", "T3", "T4", "T4", "T4", "T4"), MATERIAL = c("M105",
"M100", "M102", "M345", "M400", "M100", "M220", "M260", "M400",
"M390", "M400", "M100", "M700")), class = "data.frame", row.names = c(NA,
-13L))

   TCODE MATERIAL
1     T1     M105
2     T1     M100
3     T1     M102
4     T2     M345
5     T2     M400
6     T2     M100
7     T2     M220
8     T2     M260
9     T3     M400
10    T4     M390
11    T4     M400
12    T4     M100
13    T4     M700
</code>```

How to convert multiple rows into a single row based on first column?
The desired output is : table 2

1     2       3       4       5

1   M105,   M100,   M102

2   M345,   M400,   M100,   M220,   M260

3   M400

4   M390,   M400,   M100,   M700

Thanks.

ContentLicense: CC BY-SA 4.0

Body:
I have a dataset1 which is as follows (table 1) :

structure(list(TCODE = c("T1", "T1", "T1", "T2", "T2", "T2",
"T2", "T2", "T3", "T4", "T4", "T4", "T4"), MATERIAL = c("M105",
"M100", "M102", "M345", "M400", "M100", "M220", "M260", "M400",
"M390", "M400", "M100", "M700")), class = "data.frame", row.names = c(NA,
-13L))

   TCODE MATERIAL
1     T1     M105
2     T1     M100
3     T1     M102
4     T2     M345
5     T2     M400
6     T2     M100
7     T2     M220
8     T2     M260
9     T3     M400
10    T4     M390
11    T4     M400
12    T4     M100
13    T4     M700

How to convert multiple rows into a single row based on first column?
The desired output is : table 2

1     2       3       4       5

1   M105,   M100,   M102

2   M345,   M400,   M100,   M220,   M260

3   M400

4   M390,   M400,   M100,   M700

Thanks.

Body:
Using toString in aggregate.

aggregate(. ~ TCODE, dat, toString)
#   TCODE                     MATERIAL
# 1    T1             M105, M100, M102
# 2    T2 M345, M400, M100, M220, M260
# 3    T3                         M400
# 4    T4       M390, M400, M100, M700

Data:

dat <- structure(list(TCODE = c("T1", "T1", "T1", "T2", "T2", "T2",
"T2", "T2", "T3", "T4", "T4", "T4", "T4"), MATERIAL = c("M105",
"M100", "M102", "M345", "M400", "M100", "M220", "M260", "M400",
"M390", "M400", "M100", "M700")), class = "data.frame", row.names = c(NA,
-13L))


问:
googletrans stopped working with error 'NoneType' object has no attribute 'group'
I was trying googletrans and it was working quite well. Since this morning I started getting below error. I went through multiple posts from stackoverflow and other sites and found probably my ip is banned to use the service for sometime. I tried using multiple service provider internet that has different ip and stil facing the same issue ? I also tried to use googletrans on different laptops , still same issue ..Is googletrans package broken or something google did at their end ?

```<code>>>> from googletrans import Translator
>>> translator = Translator()
>>> translator.translate('안녕하세요.')

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    translator.translate('안녕하세요.')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 172, in translate
    data = self._translate(text, dest, src)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 75, in _translate
    token = self.token_acquirer.do(text)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 180, in do
    self._update()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 59, in _update
    code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'
</code>```

答:
Use the translators package from here

It works (;

Supports more then google

Installation:

pip install translators --upgrade

Usage:

    >>> import translators as ts
    Using Israel server backend.
    >>> ts.google('שלום' , to_language = 'es')
    'Hola'

```

Body:
I was trying googletrans and it was working quite well. Since this morning I started getting below error. I went through multiple posts from stackoverflow and other sites and found probably my ip is banned to use the service for sometime. I tried using multiple service provider internet that has different ip and stil facing the same issue ? I also tried to use googletrans on different laptops , still same issue ..Is googletrans package broken or something google did at their end ?

>>> from googletrans import Translator
>>> translator = Translator()
>>> translator.translate('안녕하세요.')

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    translator.translate('안녕하세요.')
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 172, in translate
    data = self._translate(text, dest, src)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/client.py", line 75, in _translate
    token = self.token_acquirer.do(text)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 180, in do
    self._update()
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/googletrans/gtoken.py", line 59, in _update
    code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'


问:
I cant find odd or even in rails
i.e "20200612", this program execute 2+2+0+1, all I want is 2+2+6+2 the sum of all even  numbers</p>
```<code>(task.year.to_s +
 task.month.to_s +
 task.numberofemployer.to_s).split(//)
                            .map{|p|   p.to_i}
                            .select.each_with_index { |_, p| p.even? }.sum
</code>```

答:
It seems every method of chars, map, select and sum, does an own loop, so, I think is too much, talking about accepted solution.

The ugly is that the below solution is Two lines, but only a loop, check with a benchmark:

```<code>@a = 0
'20200612'.gsub(/[2468]/) { |v| @a += v.to_i; ''}
# puts @a => 12
</code>```

This another one, is faster too:

```<code>'20200612'.chars.inject(0) { |sum, v| v.to_i.even? ? sum + v.to_i : sum }
# 12
</code>```

And this is another good way:

```<code>@a = 0
'20200612'.chars.each { |v| @a += v.to_i.even? ? v.to_i : 0 }
# puts @a => 12
</code>```

In my tests, the last one is the fastest.

Title: I cant find odd or even in rails

Body:
i.e "20200612", this program execute 2+2+0+1, all I want is 2+2+6+2 the sum of all even  numbers

(task.year.to_s +
 task.month.to_s +
 task.numberofemployer.to_s).split(//)
                            .map{|p|   p.to_i}
                            .select.each_with_index { |_, p| p.even? }.sum

Body:
It seems every method of chars, map, select and sum, does an own loop, so, I think is too much, talking about accepted solution.

The ugly is that the below solution is Two lines, but only a loop, check with a benchmark:

@a = 0
'20200612'.gsub(/[2468]/) { |v| @a += v.to_i; ''}
# puts @a => 12

This another one, is faster too:

'20200612'.chars.inject(0) { |sum, v| v.to_i.even? ? sum + v.to_i : sum }
# 12

And this is another good way:

@a = 0
'20200612'.chars.each { |v| @a += v.to_i.even? ? v.to_i : 0 }
# puts @a => 12

In my tests, the last one is the fastest.


问:
How do I pass a Treeview's SelectedItem to another command?
I created a treeview in WPF MVVM with a hierarchical DAtaTemplate property.

Outside of the Treeview, I have an "EDIT" button. On press of edit button I want to pass the Treeview's selectedItem to the RelayCommand in the viewmodel.

I am implementing the same functionality within the TreeviewItem on double click of the node. However I want to know what is the best way to accomplish this outside.

My code structure is as follows

MainView -> MainViewModel

StateViewItem -> StateViewModel (HierarchicalDataTemplate inheriting from TreeViewItemViewModel)

RegionViewItem -> RegionViewModel (DataTemplate inheriting from TreeViewItemViewModel)

The RegionViewModel handles the double click for the node and accomplishes the Edit functionality.

However the "EDIT" button is outside of the treeview, how do I pass the selected RegionViewItem to the Command bound so I can load it for editing?

thanks in advance for help

答:
Does the RegionViewModel have access to the StateViewModel? Or more importantly, to StateViewModel.SelectedItem? (Some code would be helpful)

If not, you may have to implement an event system where whenever StateViewModel.SelectedItem changes, it broadcasts a StateChanged event, and RegionViewModel subscribes to that event and keeps track of the SelectedState

ContentLicense: CC BY-SA 3.0


问:
Codeigniter 4 - route now working / 404 / Controller or its method is not found
Here are a couple of my routes;

This one works:

```<code>$routes->get('/admin/users', 'Admin/User/User_Controller::user_index');
</code>```

This one doesn't work:

```<code>$routes->get('/admin/toggle_user_is_active/(:num)','Admin/User/User_Controller::toggle_user_is_active/$1');
</code>```

As you can see, it is calling the same method.  The passed in value is a userid like 72.  If active is 1 in the db it then sets it to 0 and vice verse, thus the name toggle_user_is_active($id).

If I put directly in URL as follows:

```<code>https://example.com/admin/toggle_user_is_active/72
</code>```

I get the following error:

```<code>404 file not found
Controller or its method is not found: \App\Controllers\Admin::index
</code>```

The toggle in the view is as follows:

```<code><a href="<?= site_url('admin/users/toggle_user_is_active/'.$user->id)?>"> Toggle </a>
</code>```

When clicked it produces:

```<code>https://example.com/admin/toggle_user_is_active/72
</code>```

Scratching my head!  Any pointers appreciated.

答:
Namespaces are defined using backslashes (\), not forward slashes (/).

Instead of:

'Admin/User/User_Controller::toggle_user_is_active/$1'

Use this:

'Admin\User\User_Controller::toggle_user_is_active/$1'

Name resolution rules

Qualified name

This is an identifier with a namespace separator,
such as Foo\Bar

Setting your own routing rules

The controller and method should be listed in the same way that you
would use a static method, by separating the fully-namespaced
class and its method with a double-colon, like Users::list.

Body:
Here are a couple of my routes;

This one works:

$routes->get('/admin/users', 'Admin/User/User_Controller::user_index');

This one doesn't work:

$routes->get('/admin/toggle_user_is_active/(:num)','Admin/User/User_Controller::toggle_user_is_active/$1');

As you can see, it is calling the same method.  The passed in value is a userid like 72.  If active is 1 in the db it then sets it to 0 and vice verse, thus the name toggle_user_is_active($id).

If I put directly in URL as follows:

https://example.com/admin/toggle_user_is_active/72

I get the following error:

404 file not found
Controller or its method is not found: \App\Controllers\Admin::index

The toggle in the view is as follows:

<a href="<?= site_url('admin/users/toggle_user_is_active/'.$user->id)?>"> Toggle

When clicked it produces:

https://example.com/admin/toggle_user_is_active/72

Scratching my head!  Any pointers appreciated.


答:
We could do it this way:</p>
```<code>library(dplyr)
library(tidyr)

df %>%
  group_by(TCODE) %>%
  mutate(MATERIAL = toString(MATERIAL)) %>%
  slice(1) %>%
  mutate(MATERIAL = str_split(MATERIAL, ', ')) %>%
  unnest_wider(MATERIAL)
</code>```
```<code>  TCODE ...1  ...2  ...3  ...4  ...5
  <chr> <chr> <chr> <chr> <chr> <chr>
1 T1    M105  M100  M102  NA    NA
2 T2    M345  M400  M100  M220  M260
3 T3    M400  NA    NA    NA    NA
4 T4    M390  M400  M100  M700  NA
</code>```

Title: How to convert multiple rows with same ID to single rows

Body:
We could do it this way:

library(dplyr)
library(tidyr)

df %>%
  group_by(TCODE) %>%
  mutate(MATERIAL = toString(MATERIAL)) %>%
  slice(1) %>%
  mutate(MATERIAL = str_split(MATERIAL, ', ')) %>%
  unnest_wider(MATERIAL)

  TCODE ...1  ...2  ...3  ...4  ...5
  <chr> <chr> <chr> <chr> <chr> <chr>
1 T1    M105  M100  M102  NA    NA
2 T2    M345  M400  M100  M220  M260
3 T3    M400  NA    NA    NA    NA
4 T4    M390  M400  M100  M700  NA


问:
How post raw gson using retrofit android and how to create a model class for this
```<code>{
    "cart":[
        {
        "id": 6083,"ProductId": 27,"UserRegistrationId": 44,"TotalQuantity": 2,"Status":"CheckOut","Price": 1800
        },
        {
        "id": 6085,"ProductId": 26, "UserRegistrationId":44, "TotalQuantity":2, "Status":"CheckOut", "Price":1800
        }
    ]
}
</code>```

This my postman raw gson object now i want how call from retrofit android

答:
Create a class to accept the Cart array

```<code>public class ResponseObject {

 public Data[] cart;

}
</code>```

Then create a class Data to get the fields inside the array and create its getter methods.

```<code>public class Data{

    public String id;
    public String ProductId;
    public String UserRegistrationId;

 public String getId() {
        return id;
    }

    public String getProductId() {
        return ProductId;
    }

    public String getUserRegistrationId() {
        return UserRegistrationId;
    }
}
</code>```

Create a Api class to store your services in as follows:

```<code>
public interface AllApi {

    @FormUrlEncoded
    @POST("<your php / api url here>")
    Call<ReturnedResponsePojo> getCartItems(@Field("Order_Id") String Order_Id);
}
</code>```

Then Accept the data from server using retrofit like

```<code>    Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.APP_SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        AllApi mApiService = retrofit.create(AllApi.class);
        Call<ResponseObject> mService = mApiService.getCartItems("<Order ID here>");
        mService.enqueue(new Callback<ResponseObject>() {
            @Override
            public void onResponse(Call<ResponseObject> call, Response<ResponseObject> response) {

                ResponseObject jsonResponse = response.body();

                ArrayList<Data> dataArray = new ArrayList<>(Arrays.asList(jsonResponse.getCart()));

                *** Write your required code here ***

            }

            @Override
            public void onFailure(Call<ResponseObject> call, Throwable t) {

            }
        });
</code>```

Body:
{
    "cart":[
        {
        "id": 6083,"ProductId": 27,"UserRegistrationId": 44,"TotalQuantity": 2,"Status":"CheckOut","Price": 1800
        },
        {
        "id": 6085,"ProductId": 26, "UserRegistrationId":44, "TotalQuantity":2, "Status":"CheckOut", "Price":1800
        }
    ]
}

This my postman raw gson object now i want how call from retrofit android

Body:
Create a class to accept the Cart array

public class ResponseObject {

 public Data[] cart;

}

Then create a class Data to get the fields inside the array and create its getter methods.

public class Data{

    public String id;
    public String ProductId;
    public String UserRegistrationId;

 public String getId() {
        return id;
    }

    public String getProductId() {
        return ProductId;
    }

    public String getUserRegistrationId() {
        return UserRegistrationId;
    }
}

Create a Api class to store your services in as follows:

public interface AllApi {

    @FormUrlEncoded
    @POST("<your php / api url here>")
    Call<ReturnedResponsePojo> getCartItems(@Field("Order_Id") String Order_Id);
}

Then Accept the data from server using retrofit like

    Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Config.APP_SERVER_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        AllApi mApiService = retrofit.create(AllApi.class);
        Call<ResponseObject> mService = mApiService.getCartItems("<Order ID here>");
        mService.enqueue(new Callback<ResponseObject>() {
            @Override
            public void onResponse(Call<ResponseObject> call, Response<ResponseObject> response) {

                ResponseObject jsonResponse = response.body();

                ArrayList<Data> dataArray = new ArrayList<>(Arrays.asList(jsonResponse.getCart()));

                *** Write your required code here ***

            }

            @Override
            public void onFailure(Call<ResponseObject> call, Throwable t) {

            }
        });


问:
jQuery each function, skip a specific element
I'm trying to use the jQuery each function: http://api.jquery.com/each/

I have a list of things, and I want to perform different javascript for different list elements.

Here's  the  html code:

```<code><ul id="list-with-stuff">
    <li class='non-stuff'>foo</li>
    <li>bar</li>
</ul>
</code>```

And here's the javascript:

```<code>jQuery.fn.stuffplaylist = function() {

    return this.each(function() {

        if ($(this).hasClass('non-stuff')) {
            alert("TRUE. Has non-stuff class");
            return true;
        }
        else {
            alert("FALSE. Has not got non-stuff class");
            return false;
        };
    });
};

$(document).ready(function() {
    $("#list-with-stuff").stuffplaylist();
});
</code>```

Check it out on jsfiddle here: http://jsfiddle.net/73gB9/

The problem I am having is not being able to work out how to determine what list element is selected, and thus run different javascript. For example I want to run the "TRUE" alert for the first element in the list, however it only runs the "FALSE" alert in it's current state.

I know it must be possible, however I'm inexperienced with Javascript & jQuery and haven't been able to work out from searching the internet.

With the above code if you make ul have the class 'non-stuff' then it does output the "TRUE" alert message, otherwise the "FALSE" alert pops up.

So if you know the best practice way of doing it then I am keen to hear your answer. Particularly if it helps me along with learning Javascript :-)

Thank you.

答:
Just modify the selector so it looks at the children in this case.</p>

```<code>return $('#list-with-stuff li').each(function() {

    if ($(this).hasClass('non-stuff')) {
        alert("TRUE. Has non-stuff class");
        return true;
    }
    else {
        alert("FALSE. Has not got non-stuff class");
        return false;
    };
});
</code>```

Body:
I'm trying to use the jQuery each function: http://api.jquery.com/each/

I have a list of things, and I want to perform different javascript for different list elements.

Here's  the  html code:

foo

bar

And here's the javascript:

jQuery.fn.stuffplaylist = function() {

    return this.each(function() {

        if ($(this).hasClass('non-stuff')) {
            alert("TRUE. Has non-stuff class");
            return true;
        }
        else {
            alert("FALSE. Has not got non-stuff class");
            return false;
        };
    });
};

$(document).ready(function() {
    $("#list-with-stuff").stuffplaylist();
});

Check it out on jsfiddle here: http://jsfiddle.net/73gB9/

The problem I am having is not being able to work out how to determine what list element is selected, and thus run different javascript. For example I want to run the "TRUE" alert for the first element in the list, however it only runs the "FALSE" alert in it's current state.

I know it must be possible, however I'm inexperienced with Javascript & jQuery and haven't been able to work out from searching the internet.

With the above code if you make ul have the class 'non-stuff' then it does output the "TRUE" alert message, otherwise the "FALSE" alert pops up.

So if you know the best practice way of doing it then I am keen to hear your answer. Particularly if it helps me along with learning Javascript :-)

Thank you.

Body:
Just modify the selector so it looks at the children in this case.

return $('#list-with-stuff li').each(function() {

    if ($(this).hasClass('non-stuff')) {
        alert("TRUE. Has non-stuff class");
        return true;
    }
    else {
        alert("FALSE. Has not got non-stuff class");
        return false;
    };
});


问:
How to build Slack clone using socket.io
We are building a slack clone, where could be many organizations, which each organization have multiple rooms or channels like slack.

I have 2-3 mongo models to save messages:

```<code>model conversations{
    id: Int
    participants:[userIds]
    date:Date
    lastMessage:Message
}

model message {
    id:Int
    body:String
    conversationId: Conversation
    date:Date
}

model User {
   id:Int
   name:Sting
   organisationId:Organisation
}

model Organisation {
  id:Int
  name:String
}
</code>```

Each organization can have many rooms/ channel and the user can be in that room/channel.

I'm thinking to use new socket.io namespace for each organization.  Each namespace im using socket.io rooms as channels, where users can subscribe to rooms and communicate

I'm not sure how the client will create namespace for each organization, how in each namespace can create rooms as there is no room concept in socket.io client side.

I just want someone who can help me understand how can i implement namespaces and rooms in socket from client and also on server side.

I know how to listen to events and and send to events in general, but not sure how to go about this.

答:
I remember I made an online game with socket.io.
The flow was simple, some user was able to create their own room and some of them was able to join their rooms.
I think you should use this method. By creating a channel by an Organization or a user, you should start listening to the room.
the namespace should be the name of the room.</p>

Body:
We are building a slack clone, where could be many organizations, which each organization have multiple rooms or channels like slack.

I have 2-3 mongo models to save messages:

model conversations{
    id: Int
    participants:[userIds]
    date:Date
    lastMessage:Message
}

model message {
    id:Int
    body:String
    conversationId: Conversation
    date:Date
}

model User {
   id:Int
   name:Sting
   organisationId:Organisation
}

model Organisation {
  id:Int
  name:String
}

Each organization can have many rooms/ channel and the user can be in that room/channel.

I'm thinking to use new socket.io namespace for each organization.  Each namespace im using socket.io rooms as channels, where users can subscribe to rooms and communicate

I'm not sure how the client will create namespace for each organization, how in each namespace can create rooms as there is no room concept in socket.io client side.

I just want someone who can help me understand how can i implement namespaces and rooms in socket from client and also on server side.

I know how to listen to events and and send to events in general, but not sure how to go about this.


问:
How to return an object with its functions from API?
Considering following C# class in .NET

public class Person
{
    public string name { get; set; }
    public string surname { get; set; }

    public string Fullname()
    {
        return this.name + " " + this.surname;
    }
}
```
<p>and the endpoint</p>
<pre class="lang-cs prettyprint-override"><code>[HttpGet("getperson/")]
public ActionResult<Person> getPerson()
{
    ...
    return person;
}
</code>```

In my Angular app, I have the function

getPerson(){
    this.http.get(this.api + "getPerson").subscribe(person => {
        person.fullname() // is it possible to do this if the function is not implemented in the frontend?
    }
}
```

Could I somehow also pass the function with the object to use it without implementing it in the frontend?

答:
No, you can not.

Think about it as TypeScript code must be compiled. And if you receive code from outside, that code will be not compiled.

Body:
Considering following C# class in .NET

public class Person
{
    public string name { get; set; }
    public string surname { get; set; }

    public string Fullname()
    {
        return this.name + " " + this.surname;
    }
}

and the endpoint

[HttpGet("getperson/")]
public ActionResult<Person> getPerson()
{
    ...
    return person;
}

In my Angular app, I have the function

getPerson(){
    this.http.get(this.api + "getPerson").subscribe(person => {
        person.fullname() // is it possible to do this if the function is not implemented in the frontend?
    }
}

Could I somehow also pass the function with the object to use it without implementing it in the frontend?


问:
Fastest way to search a word into Dictionary in R
I want to search a word from a Dictionary using R. I used grepl for searching word, x from dictionary dutch. Finally I made this in such way, it will return how many words in a sentence are from this dictionary. My script as follow:

```<code>tw_copy$token <- tokenize_tweets(tw_copy$text)

count = function(x){
  de = c()
  other = c()
    for (token in x){
      if (grepl(token, dutch)==TRUE){
        de <- c(de, token)
      }
      else{
        other <- c(other, token)
      }
    }
  return (c(length(de)/length(x), length(other)/length(x)))
}

result <- lapply(tw_copy$token, FUN = count)

tw_copy$de =  lapply(result, "[[", 1)
</code>```

Now, the output is right. But It is really slow and can not get output for bigger dataset.

Can anyone suggest me to write it other way for faster performance?

答:
First, some observations about the approach:

grepl and sum are vectorized,

the loop is growing a vector (bad practice),

Every word is separated by a space, i.e. the delimiter is fixed.

Making a sample dictionary, roughly 11k Dutch words:

```<code>library(rvest)
library(stringi)
l <- list(
  c("Natuurlijk we kunnen niet anders"),
  c("wil jij honderden kinderen de"),
  c("van alle geestelijke leiders is")
)

dutch <- read_html("https://cooljugator.com/nl/list/all") %>%
  html_elements("a") %>%
  html_attr("href") %>%
  stri_extract_all_words(simplify = TRUE) %>%
  .[,2] %>%
  stri_remove_empty() %>%
  .[7:length(.)]
</code>```

lapply speed diminishes if the list grows, use vapply or a loop that writes to a correctly initialized vector instead. Further, Base R %in% can be optimized, as is done in the fastmatch package.

```<code>library(fastmatch)
f <- function(data, dictionary) {
  vapply(data, \(x){
    sum(fmatch(
        strsplit(x, " ", fixed = TRUE)[[1]],
        dictionary, nomatch = 0L) > 0L
    )
  }, 1L)
}
f(l, dutch)
#> [1] 1 2 0
</code>```

After an optimization, a customary benchmark:

```<code>library(data.table)
tw_copy = data.table(
  author=c("a","b","c"),
  text = c("Natuurlijk we kunnen niet anders",
           "wil jij honderden kinderen de",
           "van alle geestelijke leiders is")
)

bench::mark(
  x = f(l, dutch),
  y = {
    tw_copy[, token:=list(strsplit(text," "))]
    tw_copy[, num_dutch_words:=sum(token[[1]] %in% dutch), by=1:nrow(tw_copy)]
  }, check = F
)[c(1,3,5,7,9)]

  expression median mem_alloc n_itr total_time
  <bch:expr>  <dbl> <bch:byt> <int>      <dbl>
1 x          0.0141        0B  9999       168.
2 y          3.65       706KB   127       459.
</code>```

Note that the output is not the same, so the benchmark is just an indication, actual result will depend on your input and desired output. Other optimizations could be done to the data structure, for example removing stopwords prior to looping through dictionary that contains verbs.

For optimization it is useful to go through a checklist.

Is there a vectorized approach?

Is my data structure suitable for the task?

Is my loop properly initializing vectors?

If the speed is still slow, other approaches can be considered.

Splitting up the dictionary

Joins?

Use hashed environments?

Body:
I want to search a word from a Dictionary using R. I used grepl for searching word, x from dictionary dutch. Finally I made this in such way, it will return how many words in a sentence are from this dictionary. My script as follow:

tw_copy$token <- tokenize_tweets(tw_copy$text)

count = function(x){
  de = c()
  other = c()
    for (token in x){
      if (grepl(token, dutch)==TRUE){
        de <- c(de, token)
      }
      else{
        other <- c(other, token)
      }
    }
  return (c(length(de)/length(x), length(other)/length(x)))
}

result <- lapply(tw_copy$token, FUN = count)

tw_copy$de =  lapply(result, "[[", 1)

Now, the output is right. But It is really slow and can not get output for bigger dataset.

Can anyone suggest me to write it other way for faster performance?

Body:
First, some observations about the approach:

grepl and sum are vectorized,

the loop is growing a vector (bad practice),

Every word is separated by a space, i.e. the delimiter is fixed.

Making a sample dictionary, roughly 11k Dutch words:

library(rvest)
library(stringi)
l <- list(
  c("Natuurlijk we kunnen niet anders"),
  c("wil jij honderden kinderen de"),
  c("van alle geestelijke leiders is")
)

dutch <- read_html("https://cooljugator.com/nl/list/all") %>%
  html_elements("a") %>%
  html_attr("href") %>%
  stri_extract_all_words(simplify = TRUE) %>%
  .[,2] %>%
  stri_remove_empty() %>%
  .[7:length(.)]

lapply speed diminishes if the list grows, use vapply or a loop that writes to a correctly initialized vector instead. Further, Base R %in% can be optimized, as is done in the fastmatch package.

library(fastmatch)
f <- function(data, dictionary) {
  vapply(data, \(x){
    sum(fmatch(
        strsplit(x, " ", fixed = TRUE)[[1]],
        dictionary, nomatch = 0L) > 0L
    )
  }, 1L)
}
f(l, dutch)
#> [1] 1 2 0

After an optimization, a customary benchmark:

library(data.table)
tw_copy = data.table(
  author=c("a","b","c"),
  text = c("Natuurlijk we kunnen niet anders",
           "wil jij honderden kinderen de",
           "van alle geestelijke leiders is")
)

bench::mark(
  x = f(l, dutch),
  y = {
    tw_copy[, token:=list(strsplit(text," "))]
    tw_copy[, num_dutch_words:=sum(token[[1]] %in% dutch), by=1:nrow(tw_copy)]
  }, check = F
)[c(1,3,5,7,9)]

  expression median mem_alloc n_itr total_time
  <bch:expr>  <dbl> <bch:byt> <int>      <dbl>
1 x          0.0141        0B  9999       168.
2 y          3.65       706KB   127       459.

Note that the output is not the same, so the benchmark is just an indication, actual result will depend on your input and desired output. Other optimizations could be done to the data structure, for example removing stopwords prior to looping through dictionary that contains verbs.

For optimization it is useful to go through a checklist.

Is there a vectorized approach?

Is my data structure suitable for the task?

Is my loop properly initializing vectors?

If the speed is still slow, other approaches can be considered.

Splitting up the dictionary

Joins?

Use hashed environments?


问:
what is the realtionship betweent DDD and Microservices
The microservice architecture is well known and will not be repeated here. When we create microservices, we need to create a microservice with high cohesion and low coupling. The bounded context in DDD perfectly matches the requirements of microservices, and the bounded context can be understood as a microservice process.

The above is to describe the similarities between the two from a more intuitive point of view.

After the system is complicated, we all need to use divide and conquer to disassemble the problem. There are generally two ways, the technical dimension and the business dimension. The technical dimension is similar to MVC, while the business dimension refers to dividing the system by business areas.

The microservice architecture emphasizes dividing and conquering from the business dimension to deal with system complexity, and DDD also focuses on the business perspective. If the goals (business dimensions) pursued by the two achieve the unity of the context, what are the connections and differences in specific practices?

答:
In my opinion, when we think of distributed systems and microservices we think of DDD as well. Both approaches don't live alone, they are a complement of each other.

There are a lot of reasons why we segregate our applications in microservices, which may get for business or technical approach and we always use the DDD concepts to translate the business world for our tech world.


问:
pgAdmin 4 and postgreSQL 10 on Windows: Issue with setting attribute check constraints
I am using pgAdmin 4 along with postgreSQL 10 on Windows 10 and am trying to set some check constraints on one or more attributes of my table called 'parcels2007'. When I right click on 'parcels2007' and go to 'properties', I am seeing a constraints tab and then a 'Check' sub-tab. I clicked on it (see screenshot below).

and create a new check constraints based on attribute 'schdist' being within a list of pre-specified values. However, after I click 'Save' and open the first 100 rows and try to edit the 'schdist' attribute with something wrong, it does NOT throw any error (like it should instead) and it lets me change the field without issues.

Could you please help me understand what I might be doing wrong here and what else I could try?

答:
Use can use the F6 button to save your changes.

So after selecting the View Data/View All Rows press F6 to save changes.


答:
Not possible. You need to write FullName method in the Typescript model.

class Person
{
    name: string;
    surname: string;

    constructor(name: string, surname: string){
        this.name = name;
        this.surname = surname;
    }

    fullName(): string {
        return this.name + " " + this.surname;
    }
}
```

Title: How to return an object with its functions from API?


问:
How can Vims conceal feature be used to simplify code?
After much Googling I have been unable to make Vim's code conceal feature work with Javascript and Typescript (without requiring a plugin).

I have been trying to use lines like the following in my .vimrc to conceal my code but without any luck:

```<code>syntax keyword Normal function conceal cchar=λ
syntax keyword Keyword return conceal cchar=>
</code>```

Aim:

// Actual
function sum(a) {
  return function inner(b) {
    return a + b
  }
}
// Displayed
λ sum a
  > inner b
    > a + b
```

Goals:

Replace function with the lambda symbol

Replace return with the > symbol

Replace [name]([args]) with name args

Conceal the {

Conceal the }

答:
Your snippet appears to work as intended if you enable the "conceal" feature:

See :help 'conceallevel'.

But you may have a kind of race condition with other syntax scripts if you don't execute those :syntax commands at the right time. When in a TypeScript buffer, could you do :scriptnames and add the output of the command to your question?

Body:
After much Googling I have been unable to make Vim's code conceal feature work with Javascript and Typescript (without requiring a plugin).

I have been trying to use lines like the following in my .vimrc to conceal my code but without any luck:

syntax keyword Normal function conceal cchar=λ
syntax keyword Keyword return conceal cchar=>

Aim:

// Actual
function sum(a) {
  return function inner(b) {
    return a + b
  }
}
// Displayed
λ sum a
  > inner b
    > a + b

Goals:

Replace function with the lambda symbol

Replace return with the > symbol

Replace [name]([args]) with name args

Conceal the {

Conceal the }


问:
Should virtual dispatch happen when a virtual method is called within a virtual method using object?
```<code>struct B
{
  virtual void bar () {}
  virtual void foo () { bar(); }
};

struct D : B
{
  virtual void bar () {}
  virtual void foo () {}
};
</code>```

Now we call foo() using an object of B as,

```<code>B obj;
obj.foo();  // calls B::bar()
</code>```

Question:
Should bar() will be resolved through virtual dispatch or it will be resolved using the static type of the object (i.e. B).

答:
Entirely up to the implementation. Nominally it's a virtual call, but you're not entitled to assume that the emitted code will actually perform an indirection through a vtable or similar.

If foo() is called on some arbitrary B*, then of course the code emitted for foo() needs to make a virtual call to bar(), since the referand might belong to a derived class.

This isn't an arbitrary B*, this is an object of dynamic type B. The result of a virtual or non-virtual call is exactly the same, so the compiler can do what it likes ("as-if" rule), and a conforming program can't tell the difference.

Specifically in this case, if the call to foo is inlined, then I'd have thought that the optimizer has every chance of de-virtualizing the call to bar inside it, since it knows exactly what's in the vtable (or equivalent) of obj. If the call isn't inlined, then it's going to use the "vanilla" code of foo(), which of course will need to do some kind of indirection since it's the same code used when the call is made on an arbitrary B*.

Body:
struct B
{
  virtual void bar () {}
  virtual void foo () { bar(); }
};

struct D : B
{
  virtual void bar () {}
  virtual void foo () {}
};

Now we call foo() using an object of B as,

B obj;
obj.foo();  // calls B::bar()

Question:
Should bar() will be resolved through virtual dispatch or it will be resolved using the static type of the object (i.e. B).


问:
VSCode show error after use PHP Intelephense
I am trying to get post data from client, the code working fine until I switch to use PHP intelephense extension. It show that I have error "expected type 'object'. Found 'array'.intelephense(1006)"

my part of code that error is like ->

```<code>if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST)) {
    $_POST = json_decode(file_get_contents('php://input'));
}

$date = $_POST->date;
$branch = $_POST->idBranch;
</code>```

The error part is at $_POST.

Is it error with the extension or is it my code that is not correct.

答:
You are using the $_POST in a wrong way.
The Intelephense think that $_POST should always use like this:</p>
```<code>$_POST['something']
</code>```

Body:
I am trying to get post data from client, the code working fine until I switch to use PHP intelephense extension. It show that I have error "expected type 'object'. Found 'array'.intelephense(1006)"

my part of code that error is like ->

if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST)) {
    $_POST = json_decode(file_get_contents('php://input'));
}

$date = $_POST->date;
$branch = $_POST->idBranch;

The error part is at $_POST.

Is it error with the extension or is it my code that is not correct.

Body:
You are using the $_POST in a wrong way.
The Intelephense think that $_POST should always use like this:

$_POST['something']


问:
Can view the history of powershell OUTPUTS?
It is easy to view the command history of powershell, but sometimes, one might forget to record some important output of the commands, and wish to have a look back into what was on the screen?

Is the history of outputs automatically saved somewhere?

答:
By default, PowerShell records history of commands, but not their output.

You can request PowerShell to record screen output into a file. Use Start-Transcript and Stop-Transcript for this.

Example

```<code>Start-Transcript

'do stuff here'
Get-Service X*
'do some more stuff here'

Stop-Transcript
</code>```

If you want PowerShell to automatically record all your stuff every time, you can add Start-Transcript in your PowerShell profile (use $PROFILE system variable to find path to your profile script, then add Start-Transcript into it)

By default, a new text file is created every time you start transcript. If you want to keep adding output into the same file, then Start-Transcript -Path C:\ExistingTranscript.txt -Append

Body:
By default, PowerShell records history of commands, but not their output.

You can request PowerShell to record screen output into a file. Use Start-Transcript and Stop-Transcript for this.

Example

Start-Transcript

'do stuff here'
Get-Service X*
'do some more stuff here'

Stop-Transcript

If you want PowerShell to automatically record all your stuff every time, you can add Start-Transcript in your PowerShell profile (use $PROFILE system variable to find path to your profile script, then add Start-Transcript into it)

By default, a new text file is created every time you start transcript. If you want to keep adding output into the same file, then Start-Transcript -Path C:\ExistingTranscript.txt -Append


问:
PHPIDS on php 8.1 Deprecated Errors
i got a problem with PHPIDS on a PHP 8.1 Server.

Here the Errors:

```<code>PHP Deprecated: Return type of IDS\Report::count() should either be compatible with Countable::count(): int, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in phpids\ib\IDS\Report.php on line 205

PHP Deprecated: Return type of IDS\Report::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in phpids\lib\IDS\Report.php on line 218
</code>```

I know Deprecated Errors are not that bad, but i want that everything works Perfect.
I Searched in Google several things but no  solution found.
Hopefully you find the problem.

i use the actual PHPIDS version from Github (https://github.com/PHPIDS/PHPIDS)
i know this version is not the newest but i didn't found a newer one.

thx for the help

and here the Script Report.php

```<code><?php
/**
 * PHPIDS
 *
 * Requirements: PHP5, SimpleXML
 *
 * Copyright (c) 2008 PHPIDS group (https://phpids.org)
 *
 * PHPIDS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, version 3 of the License, or
 * (at your option) any later version.
 *
 * PHPIDS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with PHPIDS. If not, see <http://www.gnu.org/licenses/>.
 *
 * PHP version 5.1.6+
 *
 * @category Security
 * @package  PHPIDS
 * @author   Mario Heiderich <mario.heiderich@gmail.com>
 * @author   Christian Matthies <ch0012@gmail.com>
 * @author   Lars Strojny <lars@strojny.net>
 * @license  http://www.gnu.org/licenses/lgpl.html LGPL
 * @link     http://php-ids.org/
 */
namespace IDS;

/**
 * PHPIDS report object
 *
 * The report objects collects a number of events and thereby presents the
 * detected results. It provides a convenient API to work with the results.
 *
 * Note that this class implements Countable, IteratorAggregate and
 * a __toString() method
 *
 * @category  Security
 * @package   PHPIDS
 * @author    Christian Matthies <ch0012@gmail.com>
 * @author    Mario Heiderich <mario.heiderich@gmail.com>
 * @author    Lars Strojny <lars@strojny.net>
 * @copyright 2007-2009 The PHPIDS Group
 * @license   http://www.gnu.org/licenses/lgpl.html LGPL
 * @link      http://php-ids.org/
 */
class Report implements \Countable, \IteratorAggregate
{
    /**
     * Event container
     *
     * @var Event[]|array
     */
    protected $events = array();

    /**
     * List of affected tags
     *
     * This list of tags is collected from the collected event objects on
     * demand when IDS_Report->getTags() is called
     *
     * @var string[]|array
     */
    protected $tags = array();

    /**
     * Impact level
     *
     * The impact level is calculated on demand by adding the results of the
     * event objects on IDS\Report->getImpact()
     *
     * @var integer
     */
    protected $impact = 0;

    /**
     * Centrifuge data
     *
     * This variable - initiated as an empty array - carries all information
     * about the centrifuge data if available
     *
     * @var array
     */
    protected $centrifuge = array();

    /**
     * Constructor
     *
     * @param array $events the events the report should include
     *
     * @return Report
     */
    public function __construct(array $events = null)
    {
        foreach ((array) $events as $event) {
            $this->addEvent($event);
        }
    }

    /**
     * Adds an IDS_Event object to the report
     *
     * @param Event $event IDS_Event
     *
     * @return self $this
     */
    public function addEvent(Event $event)
    {
        $this->clear();
        $this->events[$event->getName()] = $event;

        return $this;
    }

    /**
     * Get event by name
     *
     * In most cases an event is identified by the key of the variable that
     * contained maliciously appearing content
     *
     * @param string|integer $name the event name
     *
     * @throws \InvalidArgumentException if argument is invalid
     * @return Event|null                    IDS_Event object or false if the event does not exist
     */
    public function getEvent($name)
    {
        if (!is_scalar($name)) {
            throw new \InvalidArgumentException('Invalid argument type given');
        }

        return $this->hasEvent($name) ? $this->events[$name] : null;
    }

    /**
     * Returns list of affected tags
     *
     * @return string[]|array
     */
    public function getTags()
    {
        if (!$this->tags) {
            $this->tags = array();

            foreach ($this->events as $event) {
                $this->tags = array_merge($this->tags, $event->getTags());
            }

            $this->tags = array_values(array_unique($this->tags));
        }

        return $this->tags;
    }

    /**
     * Returns total impact
     *
     * Each stored IDS_Event object and its IDS_Filter sub-object are called
     * to calculate the overall impact level of this request
     *
     * @return integer
     */
    public function getImpact()
    {
        if (!$this->impact) {
            $this->impact = 0;
            foreach ($this->events as $event) {
                $this->impact += $event->getImpact();
            }
        }

        return $this->impact;
    }

    /**
     * Checks if a specific event with given name exists
     *
     * @param string|integer $name the event name
     *
     * @throws \InvalidArgumentException if argument is illegal
     * @return boolean
     */
    public function hasEvent($name)
    {
        if (!is_scalar($name)) {
            throw new \InvalidArgumentException('Invalid argument given');
        }

        return isset($this->events[$name]);
    }

    /**
     * Returns total amount of events
     *
     * @return integer
     */

    public function count()
    {
        return @count($this->events);
    }
    /**
     * Return iterator object
     *
     * In order to provide the possibility to directly iterate over the
     * IDS_Event object the IteratorAggregate is implemented. One can easily
     * use foreach() to iterate through all stored IDS_Event objects.
     *
     * @return \Iterator the event collection
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->events);
    }

    /**
     * Checks if any events are registered
     *
     * @return boolean
     */
    public function isEmpty()
    {
        return empty($this->events);
    }

    /**
     * Clears calculated/collected values
     *
     * @return void
     */
    protected function clear()
    {
        $this->impact = 0;
        $this->tags   = array();
    }

    /**
     * This method returns the centrifuge property or null if not
     * filled with data
     *
     * @return array
     */
    public function getCentrifuge()
    {
        return $this->centrifuge;
    }

    /**
     * This method sets the centrifuge property
     *
     * @param array $centrifuge the centrifuge data
     *
     * @throws \InvalidArgumentException if argument is illegal
     * @return void
     */
    public function setCentrifuge(array $centrifuge = array())
    {
        if (!$centrifuge) {
            throw new \InvalidArgumentException('Empty centrifuge given');
        }
        $this->centrifuge = $centrifuge;
    }

    /**
     * Directly outputs all available information
     *
     * @return string
     */
    public function __toString()
    {
        $output = '';
        if (!$this->isEmpty()) {
            $output .= vsprintf(
                "Total impact: %d<br/>\nAffected tags: %s<br/>\n",
                array(
                    $this->getImpact(),
                    implode(', ', $this->getTags())
                )
            );

            foreach ($this->events as $event) {
                $output .= vsprintf(
                    "<br/>\nVariable: %s | Value: %s<br/>\nImpact: %d | Tags: %s<br/>\n",
                    array(
                        htmlspecialchars($event->getName()),
                        htmlspecialchars($event->getValue()),
                        $event->getImpact(),
                        implode(', ', $event->getTags())
                    )
                );

                foreach ($event as $filter) {
                    $output .= vsprintf(
                        "Description: %s | Tags: %s | ID %s<br/>\n",
                        array(
                            $filter->getDescription(),
                            implode(', ', $filter->getTags()),
                            $filter->getId()
                        )
                    );
                }
            }

            $output .= '<br/>';

            if ($centrifuge = $this->getCentrifuge()) {
                $output .= vsprintf(
                    "Centrifuge detection data<br/> Threshold: %s<br/> Ratio: %s",
                    array(
                        isset($centrifuge['threshold']) && $centrifuge['threshold'] ? $centrifuge['threshold'] : '---',
                        isset($centrifuge['ratio']) && $centrifuge['ratio'] ? $centrifuge['ratio'] : '---'
                    )
                );
                if (isset($centrifuge['converted'])) {
                    $output .= '<br/>  Converted: ' . $centrifuge['converted'];
                }
                $output .= "<br/><br/>\n";
            }
        }

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

答:
As of PHP 8.1, you have to fix the return type of the functions count() and getIterator() to match with interfaces.

public count(): int (see Countable)

public getIterator(): Traversable (see IteratorAggregate)

class Report implements \Countable, \IteratorAggregate
{
    protected array $events;

    public function count(): int
    {
        return count($this->events);
    }

    public function getIterator(): \Traversable
    {
        return new \ArrayIterator($this->events);
    }
}
```

Title: PHPIDS on php 8.1 Deprecated Errors

Body:
i got a problem with PHPIDS on a PHP 8.1 Server.

Here the Errors:

PHP Deprecated: Return type of IDS\Report::count() should either be compatible with Countable::count(): int, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in phpids\ib\IDS\Report.php on line 205

PHP Deprecated: Return type of IDS\Report::getIterator() should either be compatible with IteratorAggregate::getIterator(): Traversable, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in phpids\lib\IDS\Report.php on line 218

I know Deprecated Errors are not that bad, but i want that everything works Perfect.
I Searched in Google several things but no  solution found.
Hopefully you find the problem.

i use the actual PHPIDS version from Github (https://github.com/PHPIDS/PHPIDS)
i know this version is not the newest but i didn't found a newer one.

thx for the help

and here the Script Report.php

<?php
/**
 * PHPIDS
 *
 * Requirements: PHP5, SimpleXML
 *
 * Copyright (c) 2008 PHPIDS group (https://phpids.org)
 *
 * PHPIDS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, version 3 of the License, or
 * (at your option) any later version.
 *
 * PHPIDS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with PHPIDS. If not, see <http://www.gnu.org/licenses/>.
 *
 * PHP version 5.1.6+
 *
 * @category Security
 * @package  PHPIDS
 * @author   Mario Heiderich <mario.heiderich@gmail.com>
 * @author   Christian Matthies <ch0012@gmail.com>
 * @author   Lars Strojny <lars@strojny.net>
 * @license  http://www.gnu.org/licenses/lgpl.html LGPL
 * @link     http://php-ids.org/
 */
namespace IDS;

/**
 * PHPIDS report object
 *
 * The report objects collects a number of events and thereby presents the
 * detected results. It provides a convenient API to work with the results.
 *
 * Note that this class implements Countable, IteratorAggregate and
 * a __toString() method
 *
 * @category  Security
 * @package   PHPIDS
 * @author    Christian Matthies <ch0012@gmail.com>
 * @author    Mario Heiderich <mario.heiderich@gmail.com>
 * @author    Lars Strojny <lars@strojny.net>
 * @copyright 2007-2009 The PHPIDS Group
 * @license   http://www.gnu.org/licenses/lgpl.html LGPL
 * @link      http://php-ids.org/
 */
class Report implements \Countable, \IteratorAggregate
{
    /**
     * Event container
     *
     * @var Event[]|array
     */
    protected $events = array();

    /**
     * List of affected tags
     *
     * This list of tags is collected from the collected event objects on
     * demand when IDS_Report->getTags() is called
     *
     * @var string[]|array
     */
    protected $tags = array();

    /**
     * Impact level
     *
     * The impact level is calculated on demand by adding the results of the
     * event objects on IDS\Report->getImpact()
     *
     * @var integer
     */
    protected $impact = 0;

    /**
     * Centrifuge data
     *
     * This variable - initiated as an empty array - carries all information
     * about the centrifuge data if available
     *
     * @var array
     */
    protected $centrifuge = array();

    /**
     * Constructor
     *
     * @param array $events the events the report should include
     *
     * @return Report
     */
    public function __construct(array $events = null)
    {
        foreach ((array) $events as $event) {
            $this->addEvent($event);
        }
    }

    /**
     * Adds an IDS_Event object to the report
     *
     * @param Event $event IDS_Event
     *
     * @return self $this
     */
    public function addEvent(Event $event)
    {
        $this->clear();
        $this->events[$event->getName()] = $event;

        return $this;
    }

    /**
     * Get event by name
     *
     * In most cases an event is identified by the key of the variable that
     * contained maliciously appearing content
     *
     * @param string|integer $name the event name
     *
     * @throws \InvalidArgumentException if argument is invalid
     * @return Event|null                    IDS_Event object or false if the event does not exist
     */
    public function getEvent($name)
    {
        if (!is_scalar($name)) {
            throw new \InvalidArgumentException('Invalid argument type given');
        }

        return $this->hasEvent($name) ? $this->events[$name] : null;
    }

    /**
     * Returns list of affected tags
     *
     * @return string[]|array
     */
    public function getTags()
    {
        if (!$this->tags) {
            $this->tags = array();

            foreach ($this->events as $event) {
                $this->tags = array_merge($this->tags, $event->getTags());
            }

            $this->tags = array_values(array_unique($this->tags));
        }

        return $this->tags;
    }

    /**
     * Returns total impact
     *
     * Each stored IDS_Event object and its IDS_Filter sub-object are called
     * to calculate the overall impact level of this request
     *
     * @return integer
     */
    public function getImpact()
    {
        if (!$this->impact) {
            $this->impact = 0;
            foreach ($this->events as $event) {
                $this->impact += $event->getImpact();
            }
        }

        return $this->impact;
    }

    /**
     * Checks if a specific event with given name exists
     *
     * @param string|integer $name the event name
     *
     * @throws \InvalidArgumentException if argument is illegal
     * @return boolean
     */
    public function hasEvent($name)
    {
        if (!is_scalar($name)) {
            throw new \InvalidArgumentException('Invalid argument given');
        }

        return isset($this->events[$name]);
    }

    /**
     * Returns total amount of events
     *
     * @return integer
     */

    public function count()
    {
        return @count($this->events);
    }
    /**
     * Return iterator object
     *
     * In order to provide the possibility to directly iterate over the
     * IDS_Event object the IteratorAggregate is implemented. One can easily
     * use foreach() to iterate through all stored IDS_Event objects.
     *
     * @return \Iterator the event collection
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->events);
    }

    /**
     * Checks if any events are registered
     *
     * @return boolean
     */
    public function isEmpty()
    {
        return empty($this->events);
    }

    /**
     * Clears calculated/collected values
     *
     * @return void
     */
    protected function clear()
    {
        $this->impact = 0;
        $this->tags   = array();
    }

    /**
     * This method returns the centrifuge property or null if not
     * filled with data
     *
     * @return array
     */
    public function getCentrifuge()
    {
        return $this->centrifuge;
    }

    /**
     * This method sets the centrifuge property
     *
     * @param array $centrifuge the centrifuge data
     *
     * @throws \InvalidArgumentException if argument is illegal
     * @return void
     */
    public function setCentrifuge(array $centrifuge = array())
    {
        if (!$centrifuge) {
            throw new \InvalidArgumentException('Empty centrifuge given');
        }
        $this->centrifuge = $centrifuge;
    }

    /**
     * Directly outputs all available information
     *
     * @return string
     */
    public function __toString()
    {
        $output = '';
        if (!$this->isEmpty()) {
            $output .= vsprintf(
                "Total impact: %d
\nAffected tags: %s
\n",
                array(
                    $this->getImpact(),
                    implode(', ', $this->getTags())
                )
            );

            foreach ($this->events as $event) {
                $output .= vsprintf(
                    "
\nVariable: %s | Value: %s
\nImpact: %d | Tags: %s
\n",
                    array(
                        htmlspecialchars($event->getName()),
                        htmlspecialchars($event->getValue()),
                        $event->getImpact(),
                        implode(', ', $event->getTags())
                    )
                );

                foreach ($event as $filter) {
                    $output .= vsprintf(
                        "Description: %s | Tags: %s | ID %s
\n",
                        array(
                            $filter->getDescription(),
                            implode(', ', $filter->getTags()),
                            $filter->getId()
                        )
                    );
                }
            }

            $output .= '
';

            if ($centrifuge = $this->getCentrifuge()) {
                $output .= vsprintf(
                    "Centrifuge detection data
 Threshold: %s
 Ratio: %s",
                    array(
                        isset($centrifuge['threshold']) && $centrifuge['threshold'] ? $centrifuge['threshold'] : '---',
                        isset($centrifuge['ratio']) && $centrifuge['ratio'] ? $centrifuge['ratio'] : '---'
                    )
                );
                if (isset($centrifuge['converted'])) {
                    $output .= '
  Converted: ' . $centrifuge['converted'];
                }
                $output .= "

\n";
            }
        }

        return $output;
    }
}


答:
Right now it seems that you are cycling through an array, that contains only a list. Try doing it this way:</p>

```<code>$(document).ready(function() {
    $("#list-with-stuff li").each(function(index, element){
        if ($(element).hasClass('non-stuff')) {
            alert("TRUE. Has non-stuff class");
            return true;
        } else {
            alert("FALSE. Has not got non-stuff class");
            return false;
        };
    });
});
</code>```

Title: jQuery each function, skip a specific element

Body:
Right now it seems that you are cycling through an array, that contains only a list. Try doing it this way:

$(document).ready(function() {
    $("#list-with-stuff li").each(function(index, element){
        if ($(element).hasClass('non-stuff')) {
            alert("TRUE. Has non-stuff class");
            return true;
        } else {
            alert("FALSE. Has not got non-stuff class");
            return false;
        };
    });
});


问:
String not recognised in intent.putExtra Unexpected tokens error
enter image description here

fun createBirthdayCard(view: View) {

```<code>     val name = nameInput.editableText.toString()

     val intent = Intent(this, BirthdayGreeting::class.java)
        intent.putExtra(name:"name", name)
     startActivity(intent)
 }
</code>```

}

答:
remove name: from putExtra
i.e

```<code>val intent = Intent(this, BirthdayGreeting::class.java)
intent.putExtra("name", name)
startActivity(intent)
</code>```

Body:
enter image description here

fun createBirthdayCard(view: View) {

     val name = nameInput.editableText.toString()

     val intent = Intent(this, BirthdayGreeting::class.java)
        intent.putExtra(name:"name", name)
     startActivity(intent)
 }

}

Body:
remove name: from putExtra
i.e

val intent = Intent(this, BirthdayGreeting::class.java)
intent.putExtra("name", name)
startActivity(intent)


问:
Blaze persistence UpdatableEntityView as spring boot request body
I am trying to use blaze persistence UpdatableEntityView as the request body with spring boot.
Following is the code for UpdatableEntityView

```<code>@UpdatableEntityView
@EntityView(DealListing.class)
public interface DealListingUpdateView {
    @IdMapping
    Long getId();
    void setId(Long id);

    Instant getListedOn();
    void setListedOn(Instant listedOn);
}
</code>```

Following is the rest controller mapping

```<code>@PutMapping("/deal-listings/sell/{id}")
    public void test(@PathVariable Long id, @RequestBody DealListingUpdateView dealListingUpdateView){
        dealListingService.testUpdate(id, dealListingUpdateView);
}
</code>```

Following is the pom.xml dependency to do the deserialization as specified in the blaze persistence document

```<code>        <dependency>
            <groupId>com.blazebit</groupId>
            <artifactId>blaze-persistence-integration-jackson</artifactId>
            <scope>compile</scope>
        </dependency>
</code>```

But when i submit the request i am getting the following error

```<code>Type definition error: [simple type, class com.ilex.tradeservice.domain.view.blaze.DealListingUpdateView]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.ilex.tradeservice.domain.view.blaze.DealListingUpdateView` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information\n at [Source: (PushbackInputStream); line: 1, column: 1]

</code>```

答:
As you can see in the documentation, you will need the Spring Data WebMvc integration: https://persistence.blazebit.com/documentation/1.6/entity-view/manual/en_US/index.html#spring-data-webmvc-integration

You will also have to additionally annotate your controller parameter with @EntityViewId("id")

```<code>@PutMapping("/deal-listings/sell/{id}")
public void test(@PathVariable Long id, @EntityViewId("id") @RequestBody DealListingUpdateView dealListingUpdateView){
        dealListingService.testUpdate(id, dealListingUpdateView);
}
</code>```

Body:
I am trying to use blaze persistence UpdatableEntityView as the request body with spring boot.
Following is the code for UpdatableEntityView

@UpdatableEntityView
@EntityView(DealListing.class)
public interface DealListingUpdateView {
    @IdMapping
    Long getId();
    void setId(Long id);

    Instant getListedOn();
    void setListedOn(Instant listedOn);
}

Following is the rest controller mapping

@PutMapping("/deal-listings/sell/{id}")
    public void test(@PathVariable Long id, @RequestBody DealListingUpdateView dealListingUpdateView){
        dealListingService.testUpdate(id, dealListingUpdateView);
}

Following is the pom.xml dependency to do the deserialization as specified in the blaze persistence document

        <dependency>
            <groupId>com.blazebit</groupId>
            <artifactId>blaze-persistence-integration-jackson</artifactId>
            <scope>compile</scope>
        </dependency>

But when i submit the request i am getting the following error

Type definition error: [simple type, class com.ilex.tradeservice.domain.view.blaze.DealListingUpdateView]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.ilex.tradeservice.domain.view.blaze.DealListingUpdateView` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information\n at [Source: (PushbackInputStream); line: 1, column: 1]

Body:
As you can see in the documentation, you will need the Spring Data WebMvc integration: https://persistence.blazebit.com/documentation/1.6/entity-view/manual/en_US/index.html#spring-data-webmvc-integration

You will also have to additionally annotate your controller parameter with @EntityViewId("id")

@PutMapping("/deal-listings/sell/{id}")
public void test(@PathVariable Long id, @EntityViewId("id") @RequestBody DealListingUpdateView dealListingUpdateView){
        dealListingService.testUpdate(id, dealListingUpdateView);
}


问:
My user roles returns either list index out of range or takes me back to log in even though the right role is logged in
I have created user roles within my Django application and have designated users their roles within the admin interface but when I log in an try to access the restricted access page using the correct role I am either returned to the log in page or met with a list index out of range error and I am very confused to as why this is.

Models.py

```<code>from pickle import TRUE
from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from django.urls import reverse
from django.utils import timezone

ROLES = (
    ('0','Researcher'),
    ('1','Clinician'),
    ('2','Superuser'),
    )

class UserProfile(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # The additional attributes we wish to include.
    picture = models.ImageField(upload_to='profile_images', default='default/default.jpg', blank=True)
    role = models.CharField(max_length=1000, choices=ROLES, default='0')
    is_active = models.IntegerField(default = 1,
                                   blank = True,
                                    null = True,
                                    help_text ='1->Active, 0->Inactive',
                                    choices =(
                                    (1, 'Active'), (0, 'Inactive')
                                    ))
    created_on = models.DateTimeField(default = timezone.now)
    updated_on = models.DateTimeField(default = timezone.now,
                                    null = True,
                                    blank = True
                                    )
</code>```

Views.py

```<code>from django.shortcuts import render, redirect
from django.urls import reverse
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from parasites_app.models import Contact, UserProfile,Category,Photo
from parasites_app.forms import ContactForm
from django.core.mail import send_mail

from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test

#for the permissions decorators
def find_role(u):
    userprofile = UserProfile.objects.filter(user = u)[0]
    return userprofile.role

#create decorators to dictate permissions
#@clinician_required
def clinician_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'):
    actual_decorator = user_passes_test(
        lambda u: u.is_active and find_role(u) == 'Clinician',
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator

@clinician_required
def Clinician(request):
    category = request.GET.get('category')
    if category == None:
        photos = Photo.objects.all()
    else:
        photos = Photo.objects.filter(
            category__name=category)

    categories = Category.objects.all()
    context = {'categories': categories, 'photos': photos}
    return render(request,'parasites_app/Clinician.html',context)
</code>```

答:
I think the issue might be with find_role(u) == 'Clinician'

The role returned from find_role is the numeric key stored for that tuple of choices.  Perhaps find_role can be rewritten as below:

def find_role(u):
    userprofile = UserProfile.objects.filter(user = u)[0]
    return userprofile.get_role_display()
```

I might also suggest that you move the logic of what determines the user to be a clinitian onto the user model.  e.g. create a is_clinician method that returns true or false and use that in the check for permission perhaps.  Just a suggestion.

I also noticed that the max_length for the role field is 1000, this might take up more space in the DB than you need and you'll feel the pain later when you have thousands of entries and need to shrink the DB, since the role is just one char you can set the max_length to 1 and you should be fine, or even 10 in case you want to expand it at some point, but 1000 off the bat might just cause the DB to be unnecessarily large.

Body:
I have created user roles within my Django application and have designated users their roles within the admin interface but when I log in an try to access the restricted access page using the correct role I am either returned to the log in page or met with a list index out of range error and I am very confused to as why this is.

Models.py

from pickle import TRUE
from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify
from django.urls import reverse
from django.utils import timezone

ROLES = (
    ('0','Researcher'),
    ('1','Clinician'),
    ('2','Superuser'),
    )

class UserProfile(models.Model):
    # This line is required. Links UserProfile to a User model instance.
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # The additional attributes we wish to include.
    picture = models.ImageField(upload_to='profile_images', default='default/default.jpg', blank=True)
    role = models.CharField(max_length=1000, choices=ROLES, default='0')
    is_active = models.IntegerField(default = 1,
                                   blank = True,
                                    null = True,
                                    help_text ='1->Active, 0->Inactive',
                                    choices =(
                                    (1, 'Active'), (0, 'Inactive')
                                    ))
    created_on = models.DateTimeField(default = timezone.now)
    updated_on = models.DateTimeField(default = timezone.now,
                                    null = True,
                                    blank = True
                                    )

Views.py

from django.shortcuts import render, redirect
from django.urls import reverse
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from parasites_app.models import Contact, UserProfile,Category,Photo
from parasites_app.forms import ContactForm
from django.core.mail import send_mail

from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test

#for the permissions decorators
def find_role(u):
    userprofile = UserProfile.objects.filter(user = u)[0]
    return userprofile.role

#create decorators to dictate permissions
#@clinician_required
def clinician_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'):
    actual_decorator = user_passes_test(
        lambda u: u.is_active and find_role(u) == 'Clinician',
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if function:
        return actual_decorator(function)
    return actual_decorator

@clinician_required
def Clinician(request):
    category = request.GET.get('category')
    if category == None:
        photos = Photo.objects.all()
    else:
        photos = Photo.objects.filter(
            category__name=category)

    categories = Category.objects.all()
    context = {'categories': categories, 'photos': photos}
    return render(request,'parasites_app/Clinician.html',context)

Body:
I think the issue might be with find_role(u) == 'Clinician'

The role returned from find_role is the numeric key stored for that tuple of choices.  Perhaps find_role can be rewritten as below:

def find_role(u):
    userprofile = UserProfile.objects.filter(user = u)[0]
    return userprofile.get_role_display()

I might also suggest that you move the logic of what determines the user to be a clinitian onto the user model.  e.g. create a is_clinician method that returns true or false and use that in the check for permission perhaps.  Just a suggestion.

I also noticed that the max_length for the role field is 1000, this might take up more space in the DB than you need and you'll feel the pain later when you have thousands of entries and need to shrink the DB, since the role is just one char you can set the max_length to 1 and you should be fine, or even 10 in case you want to expand it at some point, but 1000 off the bat might just cause the DB to be unnecessarily large.


问:
Rotating the Node chain to left n times and returning the new head of the Node chain not working as expected
I am to write a function called rotate(head, n) that takes the head of a Node chain and an integer, n, as parameters. The function must rotate the Node chain to the left n times and return the new head of the Node chain.

For example, given the following Node chain:
A -> B -> C -> None

Rotating left one time would produce:
B -> C -> A -> None
I am to keep in mind that the node chain will contain at least three elements and n can be any non-negative integer.

Here is my Node class:

```<code>class Node:
    def __init__(self, data, next_node=None):
        self.__data = data
        self.__next = next_node

    def get_data(self):
        return self.__data

    def set_data(self, data):
        self.__data = data

    def get_next(self):
        return self.__next

    def set_next(self, new_next):
        self.__next = new_next

    def __str__(self):
        return f'{self.__data} -> {self.__next}'
</code>```

This is my rotate() function:

```<code>def rotate(head, n):
    if (n == 0):
        return
    current = head
    while (current.get_next() != None):
        current = current.get_next()

    current.next = head
    current = head
    for i in range(n - 1):
        current = current.get_next()

    head = current.get_next()
    current = None
    return head
</code>```

Test:

```<code>chain = from_list(['A', 'B', 'C'])
print(chain)
chain = rotate(chain, 1)
print(chain)
</code>```

Expected Ouput:

```<code>A -> B -> C -> None
B -> C -> A -> None
</code>```

Received Ouput:

```<code>A -> B -> C -> None
B -> C -> None
</code>```

Test2:

```<code>chain = from_list(['A', 'B', 'C'])
print(chain)
chain = rotate(chain, 2)
print(chain)
</code>```

Expected Output2:

```<code>A -> B -> C -> None
C -> A -> B -> None
</code>```

Gotten Ouput2:

```<code>C -> A -> B -> None
A -> B -> C -> None
C -> None
</code>```

TEST:

```<code>chain = from_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(chain)
chain = rotate(chain, 0)
print(chain)
</code>```

EXPECT:

```<code>1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> None
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> None
</code>```

GOT:

```<code>1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> None
None
</code>```

答:
You've got three small bugs, here's the correct version:</p>
```<code>def rotate(head, n):
    if (n == 0):
        return head # fixed
    current = head
    while (current.get_next() != None):
        current = current.get_next()

    current.set_next(head) # fixed
    current = head
    for i in range(n - 1):
        current = current.get_next()

    head = current.get_next()
    current.set_next(None) # fixed
    return head
</code>```

Body:
I am to write a function called rotate(head, n) that takes the head of a Node chain and an integer, n, as parameters. The function must rotate the Node chain to the left n times and return the new head of the Node chain.

For example, given the following Node chain:
A -> B -> C -> None

Rotating left one time would produce:
B -> C -> A -> None
I am to keep in mind that the node chain will contain at least three elements and n can be any non-negative integer.

Here is my Node class:

class Node:
    def __init__(self, data, next_node=None):
        self.__data = data
        self.__next = next_node

    def get_data(self):
        return self.__data

    def set_data(self, data):
        self.__data = data

    def get_next(self):
        return self.__next

    def set_next(self, new_next):
        self.__next = new_next

    def __str__(self):
        return f'{self.__data} -> {self.__next}'

This is my rotate() function:

def rotate(head, n):
    if (n == 0):
        return
    current = head
    while (current.get_next() != None):
        current = current.get_next()

    current.next = head
    current = head
    for i in range(n - 1):
        current = current.get_next()

    head = current.get_next()
    current = None
    return head

Test:

chain = from_list(['A', 'B', 'C'])
print(chain)
chain = rotate(chain, 1)
print(chain)

Expected Ouput:

A -> B -> C -> None
B -> C -> A -> None

Received Ouput:

A -> B -> C -> None
B -> C -> None

Test2:

chain = from_list(['A', 'B', 'C'])
print(chain)
chain = rotate(chain, 2)
print(chain)

Expected Output2:

A -> B -> C -> None
C -> A -> B -> None

Gotten Ouput2:

C -> A -> B -> None
A -> B -> C -> None
C -> None

TEST:

chain = from_list([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(chain)
chain = rotate(chain, 0)
print(chain)

EXPECT:

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> None
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> None

GOT:

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> None
None

Body:
You've got three small bugs, here's the correct version:

def rotate(head, n):
    if (n == 0):
        return head # fixed
    current = head
    while (current.get_next() != None):
        current = current.get_next()

    current.set_next(head) # fixed
    current = head
    for i in range(n - 1):
        current = current.get_next()

    head = current.get_next()
    current.set_next(None) # fixed
    return head