问:
Button not executing Django/Python script
In my home.html template:

```<code>  <button type="button" class="btn btn-dark"
          method = 'GET' action = '/action_name/' name="audio_record">Record Audio</button>
</code>```

In my views.py:

```<code>def audio_functions(request):
    print('called function')
</code>```

In my urls.py:

```<code>path('/action_name/', views.audio_functions, name='audio-record'),
</code>```

what am i doing wrong?

Edit: I replaced the button with the suggested version below:

```<code>  <a href="{% url 'audio-record' %}" class="btn btn-dark"
    >Record Audio</a>
</code>```

But I have a new problem. I actually don't want to redirect to by url/action_name. I just want to trigger the python script within the browser. How can I do this?

答:
In your urls.py you do not need the leading forward slash, as django adds this in automatically. Replace it with this and it should work:

```<code>path('action_name/', views.audio_functions, name='audio-record'),
</code>```

Also the method and action attribues would normally go in the <form> tag, and not the button one. Also change type to submit on your button.

As @SALAHEDDINEELGHARBI says, you should really be using {% url 'audio-record' %} rather than hard-coding the url, however this is not the problem in this case (you shouldn't have a leading slash in urls as this would leave to a url with a double slash)

EDIT - In response to your edit:
You can't trigger a python script within the browser. It's a common misconception. Django is a web framework built in python, yes. But anything that happens in the browse has to happen in javascript. If you want to use python, you'll need to make a call to some django endpoint, do the python, and the send it back.

Body:
In my home.html template:

  <button type="button" class="btn btn-dark"
          method = 'GET' action = '/action_name/' name="audio_record">Record Audio</button>

In my views.py:

def audio_functions(request):
    print('called function')

In my urls.py:

path('/action_name/', views.audio_functions, name='audio-record'),

what am i doing wrong?

Edit: I replaced the button with the suggested version below:

  Record Audio

But I have a new problem. I actually don't want to redirect to by url/action_name. I just want to trigger the python script within the browser. How can I do this?

Body:
In your urls.py you do not need the leading forward slash, as django adds this in automatically. Replace it with this and it should work:

path('action_name/', views.audio_functions, name='audio-record'),

Also the method and action attribues would normally go in the <form> tag, and not the button one. Also change type to submit on your button.

As @SALAHEDDINEELGHARBI says, you should really be using {% url 'audio-record' %} rather than hard-coding the url, however this is not the problem in this case (you shouldn't have a leading slash in urls as this would leave to a url with a double slash)

EDIT - In response to your edit:
You can't trigger a python script within the browser. It's a common misconception. Django is a web framework built in python, yes. But anything that happens in the browse has to happen in javascript. If you want to use python, you'll need to make a call to some django endpoint, do the python, and the send it back.


来源: stackexchange

问:
How to Change value of Element using Javascript Selenium C#
I am new to automation.I am trying to automate a web page, there is one text field in which i have to enter some text, I tried driver.FindElement(By.XPath("Xpath of elemnt").SendKeys("Value"); but this is not working so I tried sending value through Javascript driver.ExecuteJavaScript("arguments[0].value='100';", 'Element path'); which is working fine.
But this element require actual keystrokes to Identify value of element is changed or not. In shot even if I have entered text in the field page is still considering field as blank.
Can someone help me with the same.</p>

答:
You can invoke a key press event on the element (or whatever event triggers the element state to change).

Something like this:

```<code>driver.execute_script("arguments[0].dispatchEvent(new KeyboardEvent('keypress', {'key':'a'}));")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can invoke a key press event on the element (or whatever event triggers the element state to change).

Something like this:

driver.execute_script("arguments[0].dispatchEvent(new KeyboardEvent('keypress', {'key':'a'}));")


问:
How can I use regex to get command and arguments from a discord message with the (optional) user at the end
I'm building a bot that will take commands through Discord Channels like "!COMMAND Some Thing With Spaces In The Name <@123412341234>"

I need a regex expression that, while using javascript, will allow me to get the following:

```<code>const args = ["COMMAND", "Some Thing With Spaces In The Name", "<@123412341234>"];
</code>```

OR, in the absence of the user mention at the end:

```<code>const args = ["COMMAND", "Some Thing With Spaces In The Name"];
</code>```

I've tried using (\S+)\s(.+)(\s<@\d+>)? but what I get looks like:

```<code>const args = ["COMMAND", "Some Thing With Spaces In The Name <@123412341234>"];
</code>```

I need the mention separate. What I'm most interested in is the COMMAND and the argument after it without the mention. Which could be in the command or not. I know I can get the mention by doing message.mentions.users.first(). That's not really what I'm after.

Any help would be greatly appreciated. Thank you.

答:
You could use capturing groups, and then reference the capturing groups when constructing your strings.

Regex:

```<code>^!(\w+) (.+?)(?: |$)(<@\d+>)?$
</code>```

Capturing group 1 is "COMMAND"

Capturing group 2 is "Some Thing With Spaces In The Name"

Capturing group 3 is "<@123412341234>" only if it is present, otherwise capturing group 3 is undefined

Body:
I'm building a bot that will take commands through Discord Channels like "!COMMAND Some Thing With Spaces In The Name <@123412341234>"

I need a regex expression that, while using javascript, will allow me to get the following:

const args = ["COMMAND", "Some Thing With Spaces In The Name", "<@123412341234>"];

OR, in the absence of the user mention at the end:

const args = ["COMMAND", "Some Thing With Spaces In The Name"];

I've tried using (\S+)\s(.+)(\s<@\d+>)? but what I get looks like:

const args = ["COMMAND", "Some Thing With Spaces In The Name <@123412341234>"];

I need the mention separate. What I'm most interested in is the COMMAND and the argument after it without the mention. Which could be in the command or not. I know I can get the mention by doing message.mentions.users.first(). That's not really what I'm after.

Any help would be greatly appreciated. Thank you.

Body:
You could use capturing groups, and then reference the capturing groups when constructing your strings.

Regex:

^!(\w+) (.+?)(?: |$)(<@\d+>)?$

Capturing group 1 is "COMMAND"

Capturing group 2 is "Some Thing With Spaces In The Name"

Capturing group 3 is "<@123412341234>" only if it is present, otherwise capturing group 3 is undefined


问:
what does "+incompatible" suffix mean in Go github versions?
I am considering upgrading go-github from v17.0.0+incompatible to v28

I notice some versions that go-github released has a +incompatible suffix, especially for the v1 category. What does that entail? I am guessing version with +incompatible are incompatible with the newer/older version?

In general, when updating a third party dependency, how can I know if upgrading to the newer version is safe? Do I just have to read through the change logs?

答:
Go in general does not want you to use the same import path for multiple incompatible versions of a project.  This is so that one dependency can use one major version of a module and another dependency can use another.

This syntax indicates that the repository is not using a suffix for their module paths for a non-v0, non-v1 version, and bypasses the logic in the module code that does semantic import versioning.  The documentation about this functionality is available on the Go website.

Since going from one major version to another is a breaking change in semantic versioning, you'll need to determine out of band whether or not they're compatible.  The +incompatible suffix doesn't implicitly denote this, but going from v17 to v28 does.  So changelogs might be a good idea, or you could just update and run your tests if you're confident in your testsuite.


问:
simple bookmarklet only working in console
```<code><div id="element.incident.assigned_to" class="form-group " style="">
   <div class="" data-type="label" choice="0" type="reference" id="label.incident.assigned_to" nowrap="true"><label onclick="return labelClicked(this);" for="sys_display.incident.assigned_to" dir="ltr" class=" col-xs-12 col-md-3 col-lg-4 control-label"><span id="status.incident.assigned_to" aria-label="" data-dynamic-title="" mandatory="false" oclass="" class=" label_description"></span><span title="" class="label-text" data-html="false" data-original-title="Person primarily responsible for working this task">Assigned to</span></label></div>
   <div class="col-xs-10 col-sm-9 col-md-6 col-lg-5 form-field input_controls">
      <div ng-non-bindable="" class="hidden"><input type="hidden" id="sys_original.incident.assigned_to" name="sys_original.incident.assigned_to"></div>
      <input type="hidden" id="incident.assigned_to" name="incident.assigned_to" onchange="onChange('incident.assigned_to')" class="" mandatory="false" aria-required="false"><input type="hidden" id="sys_display.original.incident.assigned_to" name="sys_display.original.incident.assigned_to" value="">
      <div class="input-group ref-container "><input id="sys_display.incident.assigned_to" name="sys_display.incident.assigned_to" aria-labelledby="label.incident.assigned_to" type="search" autocomplete="off" autocorrect="off" value="" ac_columns="first_name;last_name;email" ac_order_by="name" data-type="ac_reference_input" data-completer="AJAXTableCompleter" data-dependent="assignment_group" data-dependent-value="781fcb1637ec83006eb3fa7b34990e1f" data-ref-qual="" data-ref="incident.assigned_to" data-ref-key="null" data-ref-dynamic="false" data-name="assigned_to" data-table="sys_user" class="form-control element_reference_input  " style="; " spellcheck="false" onfocus="if (!this.ac) addLoadEvent(function() {var e = gel('sys_display.incident.assigned_to'); if (!e.ac) new AJAXTableCompleter(gel('sys_display.incident.assigned_to'), 'incident.assigned_to', 'assignment_group', ''); e.ac.onFocus();})" aria-required="false"><span class="ref_dynamic_placeholder">A new record with this value will be created automatically</span><span class="input-group-btn"><button id="lookup.incident.assigned_to" name="lookup.incident.assigned_to" type="button" class="btn btn-default" title="Lookup using list" aria-haspopup="true" data-for="sys_display.incident.assigned_to" data-type="ac_reference_input" tabindex="-1" role="button" aria-label="Look up value for field: Assigned to" data-original-title="Lookup using list"><span class="icon icon-search" aria-hidden="true"></span></button></span></div>
      <script type="text/javascript">window.NOW = window.NOW || {};
         window.NOW.useHiddenDependent = 'true'.toLowerCase() === 'true';
      </script>
   </div>
   <div class="col-xs-2 col-sm-3 col-lg-2 form-field-addons">
      <a id="assign_to_me_incident.assigned_to" class="btn btn-default btn-ref icon" onclick="assignToMe('incident.assigned_to')" name="assign_to_me_incident.assigned_to" style="display:visible"><img border="0" src="images/icons/user_obj.gifx" title="Assign to me" alt="Assign to me" data-original-title="Assign to me"></a><script>function assignToMe(reference) {
         // Get the user reference field and populate the current user
         var s = reference.split('.');
         var referenceField = s[1];
         g_form.setValue(referenceField, 'TESTUSER');
         //g_form.setValue('state','2');
         }
      </script><span name=""><button id="viewr.incident.assigned_to" type="button" name="viewr.incident.assigned_to" title="Preview this record" aria-haspopup="true" style="display: none;" class="btn btn-default btn-ref icon icon-info" data-type="reference_popup" data-table="incident" data-form="sys_user.do" data-ref="incident.assigned_to" data-ref-key="null" data-view="" data-new-window="false" tabindex="-1" aria-label="Preview record for field: Assigned to" data-original-title="Preview this record"></button></span>
   </div>
</div>
</code>```

here is a part of above code

```<code> <a id="assign_to_me_incident.assigned_to" class="btn btn-default btn-ref icon" onclick="assignToMe('incident.assigned_to')" name="assign_to_me_incident.assigned_to" style="display:visible"><img border="0" src="images/icons/user_obj.gifx" title="Assign to me" alt="Assign to me" data-original-title="Assign to me"></a>

<script>function assignToMe(reference) {
         // Get the user reference field and populate the current user
         var s = reference.split('.');
         var referenceField = s[1];
         g_form.setValue(referenceField, 'TESTUSER');
         //g_form.setValue('state','2');
         }
</code>```

In the console, this code works after inspecting the element:

```<code>assignToMe('incident.assigned_to')
</code>```

When attempting to click the bookmarklet, I get this:

```<code>VM14031:1 Uncaught ReferenceError: assignToMe is not defined
    at <anonymous>:1:1
(anonymous) @ VM14031:1
</code>```

any hints?

答:
Try this as your bookmarklet.</p>

```<code>javascript:(function(){assignToMe('incident.assigned_to')})();
</code>```

Body:
Assigned to

<input type="hidden" id="sys_original.incident.assigned_to" name="sys_original.incident.assigned_to">

      <input type="hidden" id="incident.assigned_to" name="incident.assigned_to" onchange="onChange('incident.assigned_to')" class="" mandatory="false" aria-required="false"><input type="hidden" id="sys_display.original.incident.assigned_to" name="sys_display.original.incident.assigned_to" value="">

<input id="sys_display.incident.assigned_to" name="sys_display.incident.assigned_to" aria-labelledby="label.incident.assigned_to" type="search" autocomplete="off" autocorrect="off" value="" ac_columns="first_name;last_name;email" ac_order_by="name" data-type="ac_reference_input" data-completer="AJAXTableCompleter" data-dependent="assignment_group" data-dependent-value="781fcb1637ec83006eb3fa7b34990e1f" data-ref-qual="" data-ref="incident.assigned_to" data-ref-key="null" data-ref-dynamic="false" data-name="assigned_to" data-table="sys_user" class="form-control element_reference_input  " style="; " spellcheck="false" onfocus="if (!this.ac) addLoadEvent(function() {var e = gel('sys_display.incident.assigned_to'); if (!e.ac) new AJAXTableCompleter(gel('sys_display.incident.assigned_to'), 'incident.assigned_to', 'assignment_group', ''); e.ac.onFocus();})" aria-required="false">A new record with this value will be created automatically<button id="lookup.incident.assigned_to" name="lookup.incident.assigned_to" type="button" class="btn btn-default" title="Lookup using list" aria-haspopup="true" data-for="sys_display.incident.assigned_to" data-type="ac_reference_input" tabindex="-1" role="button" aria-label="Look up value for field: Assigned to" data-original-title="Lookup using list"></button>

      <button id="viewr.incident.assigned_to" type="button" name="viewr.incident.assigned_to" title="Preview this record" aria-haspopup="true" style="display: none;" class="btn btn-default btn-ref icon icon-info" data-type="reference_popup" data-table="incident" data-form="sys_user.do" data-ref="incident.assigned_to" data-ref-key="null" data-view="" data-new-window="false" tabindex="-1" aria-label="Preview record for field: Assigned to" data-original-title="Preview this record"></button>

here is a part of above code

Body:
Try this as your bookmarklet.

javascript:(function(){assignToMe('incident.assigned_to')})();


问:
raise UnknownBackendException embed_video.backends.UnknownBackendException
I am making my website using django-embed-video package of django.

Since I'm thinking about starting with a configuration that is as simple as possible, I made a website only index.html, then I installed django-embed-video.
Then I added following code base on the tutorial, however, it doesn't display youtube video and display following error message.

My environment is as follows.
django 2.0
python 3.6
django-embed-video 1.1.2

error message

```<code>Backend wasn't recognised (``)
Traceback (most recent call last):
File "F:\django_project\virtualenv2\lib\site-
packages\embed_video\templatetags\embed_video_tags.py", line 111, in render
return self.embed(url, size, context=context, **options)
File "F:\django_project\virtualenv2\lib\site-
packages\embed_video\templatetags\embed_video_tags.py", line 185, in embed
backend = cls.get_backend(url, context=context, **options)
File "F:\django_project\virtualenv2\lib\site-
packages\embed_video\templatetags\embed_video_tags.py", line 164, in
get_backend
else detect_backend(str(backend_or_url))
File "F:\django_project\virtualenv2\lib\site-
packages\embed_video\backends.py", line 62, in detect_backend
raise UnknownBackendException
embed_video.backends.UnknownBackendException
</code>```

stteings.py

```<code>INSTALLED_APPS = [
'embed_video',
 ]
</code>```

It added 'django.template.context_processors.request' by default in 'context_processors' of TEMPLATES.

models.py

```<code>class Item(models.Model):
name = models.CharField('Video name', max_length=100, null=True)
video = models.URLField()  # same like models.URLField()
</code>```

view.py

```<code>from django.shortcuts import render

def index(request):
return render(request, 'app/index.html')
</code>```

admin.py

```<code>from django.contrib import admin
from embed_video.admin import AdminVideoMixin
from .models import Item

class MyModelAdmin(AdminVideoMixin, admin.ModelAdmin):
pass

admin.site.register(Item, MyModelAdmin)
</code>```

Custom backends have not made anything.
What is the cause this problem?

答:
in your case just do this in your templates files

```<code>{% for items in allItems %}
  {% video items.video as my_video %}
    URL: {{ my_video.url }}
    Thumbnail: {{ my_video.thumbnail }}
    Backend: {{ my_video.backend }}
  {% endvideo %}
{% endfor %}

</code>```

and replace URLFIELD by EmbedVideoField()

ContentLicense: CC BY-SA 3.0

Body:
I am making my website using django-embed-video package of django.

Since I'm thinking about starting with a configuration that is as simple as possible, I made a website only index.html, then I installed django-embed-video.
Then I added following code base on the tutorial, however, it doesn't display youtube video and display following error message.

My environment is as follows.
django 2.0
python 3.6
django-embed-video 1.1.2

error message

Backend wasn't recognised (``)
Traceback (most recent call last):
File "F:\django_project\virtualenv2\lib\site-
packages\embed_video\templatetags\embed_video_tags.py", line 111, in render
return self.embed(url, size, context=context, **options)
File "F:\django_project\virtualenv2\lib\site-
packages\embed_video\templatetags\embed_video_tags.py", line 185, in embed
backend = cls.get_backend(url, context=context, **options)
File "F:\django_project\virtualenv2\lib\site-
packages\embed_video\templatetags\embed_video_tags.py", line 164, in
get_backend
else detect_backend(str(backend_or_url))
File "F:\django_project\virtualenv2\lib\site-
packages\embed_video\backends.py", line 62, in detect_backend
raise UnknownBackendException
embed_video.backends.UnknownBackendException

stteings.py

INSTALLED_APPS = [
'embed_video',
 ]

It added 'django.template.context_processors.request' by default in 'context_processors' of TEMPLATES.

models.py

class Item(models.Model):
name = models.CharField('Video name', max_length=100, null=True)
video = models.URLField()  # same like models.URLField()

view.py

from django.shortcuts import render

def index(request):
return render(request, 'app/index.html')

admin.py

from django.contrib import admin
from embed_video.admin import AdminVideoMixin
from .models import Item

class MyModelAdmin(AdminVideoMixin, admin.ModelAdmin):
pass

admin.site.register(Item, MyModelAdmin)

Custom backends have not made anything.
What is the cause this problem?

Body:
in your case just do this in your templates files

{% for items in allItems %}
  {% video items.video as my_video %}
    URL: {{ my_video.url }}
    Thumbnail: {{ my_video.thumbnail }}
    Backend: {{ my_video.backend }}
  {% endvideo %}
{% endfor %}

and replace URLFIELD by EmbedVideoField()


问:
Python Pandas GroupBy: calculating age by subtracting date from the last 10 years
I have dataframe which looks like below:

df:

```<code>   ID             DATE
     KV          26/09/1969 0:00:00
     KV          27/05/1970 0:00:00
     KV          17/01/1989 0:00:00
     KV          27/05/1970 0:00:00
     DV          24/07/1984 0:00:00
     DV          11/03/2015 0:00:00
     DV           4/12/2015 0:00:00
     GV          26/10/2005 0:00:00
     GV          11/10/2017 0:00:00
     GV          11/10/2017 0:00:00
</code>```

Now I want to create an average age column for each ID for the last 10 years (using groupby).

Desired Output:

```<code>Average Age
ID  2020    2019    2018    2017    2016    2015    2014    2013    2012    2011
KV  45.5    44.5    43.5    42.5    41.5    40.5    39.5    38.5    37.5    36.5
DV  15.3    14.3    13.3    12.3    11.3    31       30      29      28      27
GV  3        2       1       0      0        0      0         0       0       0
</code>```

Age can be calculated by the last 10 years subtracting from the date column. I used the following command to calculate the age for the year 2020:

```<code>df.groupby('ID')['Date'].agg(lambda x:pd.datetime('01-04-2020')-x['Date'])
</code>```

However, I am not able to figure out how to calculate the age value for last 10 years with a single command. Could anyone help me how to approach this issue?

答:
Why not get a year column like df['Year'] = pd.to_datetime(df['Date']).dt.year and then do a groupby on both ['ID','Year'] like:

```<code>import pandas as pd

def parse_date(td):
    ### no leap-year in account
    resYear = float(td.days)/365.0
    resMonth = int((resYear - int(resYear))*365/30)
    resYear = int(resYear)
    return str(resYear) + "Y" + str(resMonth) + "m"

df = pd.DataFrame([['KV','26/09/1969 0:00:00'],['KV','26/09/1979 0:00:00'],['KV','26/09/1989 0:00:00'],['DV','26/09/1984 0:00:00'],['GV','26/09/2014 0:00:00']],columns=['id','date'])
df['date'] = pd.to_datetime(df['date'])
df['year'] = df['date'].dt.year
df['age'] = df.groupby(['id','year'])['date'].apply(lambda x:pd.to_datetime('today')-x).reset_index()['date'].apply(parse_date)
df
</code>```

output:

Once that's done pd.pivot_table should allow you to put years into columns.

Body:
I have dataframe which looks like below:

df:

   ID             DATE
     KV          26/09/1969 0:00:00
     KV          27/05/1970 0:00:00
     KV          17/01/1989 0:00:00
     KV          27/05/1970 0:00:00
     DV          24/07/1984 0:00:00
     DV          11/03/2015 0:00:00
     DV           4/12/2015 0:00:00
     GV          26/10/2005 0:00:00
     GV          11/10/2017 0:00:00
     GV          11/10/2017 0:00:00

Now I want to create an average age column for each ID for the last 10 years (using groupby).

Desired Output:

Average Age
ID  2020    2019    2018    2017    2016    2015    2014    2013    2012    2011
KV  45.5    44.5    43.5    42.5    41.5    40.5    39.5    38.5    37.5    36.5
DV  15.3    14.3    13.3    12.3    11.3    31       30      29      28      27
GV  3        2       1       0      0        0      0         0       0       0

Age can be calculated by the last 10 years subtracting from the date column. I used the following command to calculate the age for the year 2020:

df.groupby('ID')['Date'].agg(lambda x:pd.datetime('01-04-2020')-x['Date'])

However, I am not able to figure out how to calculate the age value for last 10 years with a single command. Could anyone help me how to approach this issue?

Body:
Why not get a year column like df['Year'] = pd.to_datetime(df['Date']).dt.year and then do a groupby on both ['ID','Year'] like:

import pandas as pd

def parse_date(td):
    ### no leap-year in account
    resYear = float(td.days)/365.0
    resMonth = int((resYear - int(resYear))*365/30)
    resYear = int(resYear)
    return str(resYear) + "Y" + str(resMonth) + "m"

df = pd.DataFrame([['KV','26/09/1969 0:00:00'],['KV','26/09/1979 0:00:00'],['KV','26/09/1989 0:00:00'],['DV','26/09/1984 0:00:00'],['GV','26/09/2014 0:00:00']],columns=['id','date'])
df['date'] = pd.to_datetime(df['date'])
df['year'] = df['date'].dt.year
df['age'] = df.groupby(['id','year'])['date'].apply(lambda x:pd.to_datetime('today')-x).reset_index()['date'].apply(parse_date)
df

output:

Once that's done pd.pivot_table should allow you to put years into columns.


问:
Why is Print Screen versus what is actually displaying on the monitor are different?
I'm working on an application that screen captures a monitor in real-time, encodes it, sends it over ethernet, decodes it, then displays that monitor in an application.

So I put the decoder application on the same monitor that is being captured. I then open a timer application and put it next to the decoder application. I can then start the timer and see the latency between main instance of the timer and the timer within the application.

What's weird is that if I take a picture of the monitor with a camera, I get one latency measurement (almost always ~100ms) but if I take a Print Screen of the monitor, the latency between the two is much lower (~30-60ms).

Why is that? How does Print Screen work? Why would it result in 40+ ms difference? Which latency measurement should I trust?

答: Print Screen saves the screenshot to your clipboard which is stored on your RAM (highest speed storage system in your computer), whereas what you are doing probably writes the screenshot data to your HDD/SSD and then reads it again to send over the internet, which takes a lot longer to do. </p>


问:
How to populate subsequent rows based on previous row value and value from another column in Python Pandas?
I have the following df.

```<code>cases  percent_change
100    0.01
NaN    0.00
NaN    -0.001
NaN    0.05
</code>```

For the next rows (starting in the second row) from the cases column, it's calculated as next cases = previous cases * (1 + previous percent_change), or for the row below the 100, it is calculated as 100 * (1 + 0.01) = 101. Thus, it should populate like so

```<code>cases  percent_change
100    0.01
101    0.00
101    -0.001
100.899    0.05
</code>```

I want to ignore the first row (or 100). Here is my code which is not working

```<code>df.loc[1:, 'cases'] = df['cases'].shift(1) * (1 + df['percent_change'].shift(1))
</code>```

Tried this as well with no success

```<code>df.loc[1:, 'cases'] = df.loc[1:, 'cases'].shift(1) * (1 + df.loc[1:, 'percent_change'].shift(1))
</code>```

Body:
I have the following df.

cases  percent_change
100    0.01
NaN    0.00
NaN    -0.001
NaN    0.05

For the next rows (starting in the second row) from the cases column, it's calculated as next cases = previous cases * (1 + previous percent_change), or for the row below the 100, it is calculated as 100 * (1 + 0.01) = 101. Thus, it should populate like so

cases  percent_change
100    0.01
101    0.00
101    -0.001
100.899    0.05

I want to ignore the first row (or 100). Here is my code which is not working

df.loc[1:, 'cases'] = df['cases'].shift(1) * (1 + df['percent_change'].shift(1))

Tried this as well with no success

df.loc[1:, 'cases'] = df.loc[1:, 'cases'].shift(1) * (1 + df.loc[1:, 'percent_change'].shift(1))

Body:
df['cases'] = (df.percent_change.shift(1).fillna(0) + 1).cumprod() * df.at[0, 'cases']
print(df)

Prints:

     cases  percent_change
0  100.000           0.010
1  101.000           0.000
2  101.000          -0.001
3  100.899           0.050


问:
How to make a new pandas column that is a list of every value in an index range not including the row value
I was wondering if it was possible to make a new column in a pandas dataframe that is a list of every value NOT including the value of the row itself. For example, in the df below, I have for the first row in columns 'list' values [b, c], and the value of the row itself, 'a'. Is this possible to do per index?

I have tried this, but it returns a list of all values combined per index:

```<code>import pandas as pd
d = {'index': [1, 1, 1, 2, 2, 3], 'col1': ['a', 'b', 'c', 'd', 'e, f', 'g']}
df = pd.DataFrame(d)
df = df.groupby("index")["col1"].apply(list)

</code>```

Whereas I am looking for something that retains the all of the rows and produces each list in a new column without the row value included.

Thank you for any help!!

答:
We can do explode with groupby create the whole list within each index, then do set sub

```<code>df['l']=df.col1.str.split(',')
df['new']=df.explode('l').groupby('index')['l'].agg(list).reindex(df['index']).tolist()
df['List']=(df.new.apply(set)-df['l'].apply(set)).apply(list)
df.loc[~df.List.astype(bool),'List']=df.l
df
   index  col1        l         new     List
0      1     a      [a]   [a, b, c]   [c, b]
1      1     b      [b]   [a, b, c]   [a, c]
2      1     c      [c]   [a, b, c]   [a, b]
3      2     d      [d]  [d, e,  f]  [e,  f]
4      2  e, f  [e,  f]  [d, e,  f]      [d]
5      3     g      [g]         [g]      [g]
</code>```

Update

```<code>l=[]
... for x , y in zip(df.l,df.new):
...     x=x.copy()
...     y=y.copy()
...     for i in x:
...         if i in y:
...             y.remove(i)
...     l.append(y)
...
l
[['b', 'c'], ['a', 'c'], ['a', 'b'], ['e', ' f'], ['d'], []]
df['List']=l
</code>```

Body:
I was wondering if it was possible to make a new column in a pandas dataframe that is a list of every value NOT including the value of the row itself. For example, in the df below, I have for the first row in columns 'list' values [b, c], and the value of the row itself, 'a'. Is this possible to do per index?

I have tried this, but it returns a list of all values combined per index:

import pandas as pd
d = {'index': [1, 1, 1, 2, 2, 3], 'col1': ['a', 'b', 'c', 'd', 'e, f', 'g']}
df = pd.DataFrame(d)
df = df.groupby("index")["col1"].apply(list)

Whereas I am looking for something that retains the all of the rows and produces each list in a new column without the row value included.

Thank you for any help!!

Body:
We can do explode with groupby create the whole list within each index, then do set sub

df['l']=df.col1.str.split(',')
df['new']=df.explode('l').groupby('index')['l'].agg(list).reindex(df['index']).tolist()
df['List']=(df.new.apply(set)-df['l'].apply(set)).apply(list)
df.loc[~df.List.astype(bool),'List']=df.l
df
   index  col1        l         new     List
0      1     a      [a]   [a, b, c]   [c, b]
1      1     b      [b]   [a, b, c]   [a, c]
2      1     c      [c]   [a, b, c]   [a, b]
3      2     d      [d]  [d, e,  f]  [e,  f]
4      2  e, f  [e,  f]  [d, e,  f]      [d]
5      3     g      [g]         [g]      [g]

Update

l=[]
... for x , y in zip(df.l,df.new):
...     x=x.copy()
...     y=y.copy()
...     for i in x:
...         if i in y:
...             y.remove(i)
...     l.append(y)
...
l
[['b', 'c'], ['a', 'c'], ['a', 'b'], ['e', ' f'], ['d'], []]
df['List']=l


问:
Why do I get a DependencyProperty.UnsetValue when converting a value in a MultiBinding?
I have an extremely simple IMultiValueConverter that simply OR's two values. In the example below, I want to invert the first value using an equally simple boolean inverter.

```<code><MultiBinding Converter="{StaticResource multiBoolToVis}">
    <Binding Path="ConditionA" Converter="{StaticResource boolInverter}"/>
    <Binding Path="ConditionB"/>
</MultiBinding>
</code>```

and the inverter:

```<code>public class BoolInverterConverter : IValueConverter
{
    #region IValueConverter Members
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is bool)
        {
            return !((bool)value);
        }
        return null;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
    #endregion
}
</code>```

When I include the boolInverter, the first value in the MultiValueConverter becomes a "DependencyProperty.UnsetValue". There are no problems when I do not use the converter (other than not the logic I am aiming for, of course).

Am I missing something? Stepping through the debugger shows that the InverseBoolConverter is properly inverting the value I pass it, but that value is then not being 'sent' to the MultiValueConverter.

答: If occuring in a datagrid try setting CanUserAddRows="False"</p>

Body:
I have an extremely simple IMultiValueConverter that simply OR's two values. In the example below, I want to invert the first value using an equally simple boolean inverter.

<MultiBinding Converter="{StaticResource multiBoolToVis}">
    <Binding Path="ConditionA" Converter="{StaticResource boolInverter}"/>
    <Binding Path="ConditionB"/>
</MultiBinding>

and the inverter:

public class BoolInverterConverter : IValueConverter
{
    #region IValueConverter Members
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is bool)
        {
            return !((bool)value);
        }
        return null;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
    #endregion
}

When I include the boolInverter, the first value in the MultiValueConverter becomes a "DependencyProperty.UnsetValue". There are no problems when I do not use the converter (other than not the logic I am aiming for, of course).

Am I missing something? Stepping through the debugger shows that the InverseBoolConverter is properly inverting the value I pass it, but that value is then not being 'sent' to the MultiValueConverter.


问:
@PathVariable vs @RequestParam to retrieve an entity
I know the difference between @PathVariable and @RequestParam, that's not the point.

I have also read some articles but I still don't understand when to use one or the other in a simple case.

For a REST API, let's say I have a User entity with  id and username (both are unique).

Now I want to get a user by username.

I have 2 options :

```<code>@GetMapping(path = "/users/{username}")
public ResponseEntity<Object> getUser(@PathVariable String username){
    //Get user
}
</code>```

or

```<code>@GetMapping(path = "/users}")
public ResponseEntity<Object> getUser(@RequestParam String username){
    //Get user
}
</code>```

Which one do I have to use (@RequestParam is not mandatory in the code, I placed it just to be clearer) ?

Thanks

答:
The path part of a URL identifies a resource, and a query string represents a query. While a query can certainly return exactly one item, a collection-resource URL (/users) should return an array of items (from zero to infinity), while a record-resource URL (/users/123) should return exactly one item (and this is the URL that should handle DELETE/PUT requests).

If the username is actually the canonical ID for the user, it should be a path variable; if there is a different canonical ID (such as a UUID), but you're searching by username, then use a query parameter but return a collection of zero or one results. (You can use params=username in the request mapping to only match the controller when that query parameter is present.)

Body:
I know the difference between @PathVariable and @RequestParam, that's not the point.

I have also read some articles but I still don't understand when to use one or the other in a simple case.

For a REST API, let's say I have a User entity with  id and username (both are unique).

Now I want to get a user by username.

I have 2 options :

@GetMapping(path = "/users/{username}")
public ResponseEntity<Object> getUser(@PathVariable String username){
    //Get user
}

or

@GetMapping(path = "/users}")
public ResponseEntity<Object> getUser(@RequestParam String username){
    //Get user
}

Which one do I have to use (@RequestParam is not mandatory in the code, I placed it just to be clearer) ?

Thanks


问:
Azure data Factory escape character and quote issue - copy activity
I have ADF pipelines exporting (via copy activity) data from Azure SQL DB to Data Lake (ADLS2) and then from there to another Azure SQL DB. It was working fine until some characters appeared.

This is how the culprit record looks in the first Azure SQL DB:
"Gasunie\

This is how the dataset is set up in ADF to export it into ADLS:
Column delimiter - pipe
Row delimiter - autodetect
Encoding - Default(UTF-8)
Escape character - Backslash()
Quote character - Double quote (")

This is how the exported file looks like in notepad++ (it's a pipe-delimited file):
""Gasunie"

These are the settings for the adls dataset in ADF when loading it from adls to azure SQL DB:
Column delimiter - comma
Row delimiter - autodetect
Encoding - Default(UTF-8)
Escape character - Backslash()
Quote character - Double quote (")

Note it's comma-delimited now but that is not causing any problems.

But this is how it looks once loaded:
"Gasunie"|1|||||||||||...
The backslash that was originally there has somehow caused it to stop the delimiting for the next few columns.

I have tried many, many various different settings for the quotes and escape characters but they create more problems for other data in the dataset.

Does anyone know how I can correct it without having to ask for the source to be corrected?

Note: there is a reason why it's stored in adls so it can't be a copy from Azure sql DB to another Azure Sql DB.

It's built from a template by consultants, and highly parameterized so inserting dataflows to process the files in adls would be a very lengthy process.

Any help is appreciated. Thank you.

答:
I faced a similar problem.

What I think happens for you is this.

The data is 9 characters, like so "Gasunie\

The output is written "quoted" and uses \ as the escape character.

So the output will be "your_text", but any quotes in your_text are replaced with \"

So the output is "\"Gasunie\" - the outside quotes enclose your text and the
inside one has been escaped with \

Now we come to read this back in: it seems to be parsed like this.

The first quote is the start of your quoted field value, so from here on I'm reading your text field value.

Then I see \" which is a quote character (that has been escaped).

Then I see Gasunie

Then I see \" which is a quote character (that has been escaped).

Then I see field delimiters but as I'm still thinking I'm inside a quoted field then they are just text, so are included in my output "Gasunie"|1|||||||||||...

I keep reading characters into this field until I reach the next double quote at which point I'm expecting a new delimiter to start the next field.

So the problem is that ADF is putting quotes round whatever string it has in hand and writing this to the output; while on input it's parsing left to right so any string ending in the escape character is a problem.  I'm not sure if you'd call that a bug.

What can you do?

In your case, just change the escape character to something that's never seen in your input (maybe @ or { or something).  Then the \" at the end of your output text is no longer an escaped quote.

My similar case - when is the escape character not an escape character?

I have a field that contains a comma, but comma is also the field separator.  My data comes from a third party and they have handily escaped this comma for me, using a backslash, thus:

Field One, Field\,Two, Field Three

I have \ as my escape character so you'd think this will give me three output fields:

| Field One | Field,Two | Field Three |

Wrong.  The escape character only works when it's inside the quoted field.  My input is not quoted, so the backslash is just treated as text and the comma is a field separator meaning my output has four fields

| Field One | Field\ | Two | Field Three |

Solution:  tell my ADF dataset there are no quote characters around my input - then it treats anything after a comma as the text field and applies the escape character as expected.

You might also be interested in this https://feedback.azure.com/forums/270578-data-factory/suggestions/35482144-text-format-escape-char-only-if-needed-or-per-fiel.

So if you're looking for "escaped comma in csv is creating extra field", I hope this saves you a bit of time!


答:
in html :

```<code>   <a href="{% url 'audio-record' %}" class="btn btn-dark"
        >Record Audio</a>
</code>```

and  urls.py

```<code>path('action_name', views.audio_functions, name='audio-record'),
</code>```

Title: Button not executing Django/Python script

Body:
In my home.html template:

  <button type="button" class="btn btn-dark"
          method = 'GET' action = '/action_name/' name="audio_record">Record Audio</button>

In my views.py:

def audio_functions(request):
    print('called function')

In my urls.py:

path('/action_name/', views.audio_functions, name='audio-record'),

what am i doing wrong?

Edit: I replaced the button with the suggested version below:

  Record Audio

But I have a new problem. I actually don't want to redirect to by url/action_name. I just want to trigger the python script within the browser. How can I do this?

Body:
in html :

   <a href="{% url 'audio-record' %}" class="btn btn-dark"
        >Record Audio</a>

and  urls.py

path('action_name', views.audio_functions, name='audio-record'),


问:
Input/If statement - correct way of writing
I am currently taking part of a beginner Python code challenge and whilst my code runs how it should, the solution is written differently to my program.

As I am just starting out, I was wondering which way is more preferable to write the program,

The solution is:

```<code># Prompt user if they want to proceed. Y/N?
should_proceed = input("Do you want to proceed? Y/N ")

# If they want to proceed
if should_proceed.lower() == "y":
    # print out to the screen "SOLD!" to confirm purchase
    # TODO: Gatjer credit card information and process it.
    print("SOLD!")
    # and then decrement the tickets remaining by the number of tickets purchased
    tickets_remaining -= num_tickets
# Otherwise...
else:
    # Thank them by name
    print("Thank you anyways, {}!".format(name))
</code>```

Whereas, I have put:

```<code># Prompt user if they want to proceed. Y/N?
proceed = input("Would you like to proceed? Y/N ").upper()

# If they want to proceed
if proceed == "Y":
    # print out to the screen "SOLD!" to confirm purchase
    # TODO: Gatjer credit card information and process it.
    print("SOLD!")
    # and then decrement the tickets remaining by the number of tickets purchased
    tickets_remaining = tickets_remaining - ticket_request
    print(tickets_remaining)
# Otherwise...
elif proceed == "N":
    # Thank them by name
    print("Thank you for your time, {}".format(customer_name))
</code>```

Was it incorrect to call upper() on the input?

Is there any other errors I have done?

Many thanks,

答:
Both ways are fine with one caveat. Because you are specifically checking for both Y and N, your way is probably better in that case since you would otherwise have to call upper() twice:

```<code>proceed = input("Would you like to proceed? Y/N ")
if proceed.upper() == "Y":
    doSomething()
elif proceed.upper() == "N":
    doSomethingElse()
</code>```

On that enhanced checking, your code is slightly different in that it does nothing if the input is neither Y nor N (the other code treats anything that's not y as n). In that case, you're probably wise to ensure it is one of those values, with something like:

```<code>proceed = ""
while proceed != "Y" and proceed != "N":
    proceed = input("Would you like to proceed (Y/N)? ").upper()
</code>```

Body:
I am currently taking part of a beginner Python code challenge and whilst my code runs how it should, the solution is written differently to my program.

As I am just starting out, I was wondering which way is more preferable to write the program,

The solution is:

# Prompt user if they want to proceed. Y/N?
should_proceed = input("Do you want to proceed? Y/N ")

# If they want to proceed
if should_proceed.lower() == "y":
    # print out to the screen "SOLD!" to confirm purchase
    # TODO: Gatjer credit card information and process it.
    print("SOLD!")
    # and then decrement the tickets remaining by the number of tickets purchased
    tickets_remaining -= num_tickets
# Otherwise...
else:
    # Thank them by name
    print("Thank you anyways, {}!".format(name))

Whereas, I have put:

# Prompt user if they want to proceed. Y/N?
proceed = input("Would you like to proceed? Y/N ").upper()

# If they want to proceed
if proceed == "Y":
    # print out to the screen "SOLD!" to confirm purchase
    # TODO: Gatjer credit card information and process it.
    print("SOLD!")
    # and then decrement the tickets remaining by the number of tickets purchased
    tickets_remaining = tickets_remaining - ticket_request
    print(tickets_remaining)
# Otherwise...
elif proceed == "N":
    # Thank them by name
    print("Thank you for your time, {}".format(customer_name))

Was it incorrect to call upper() on the input?

Is there any other errors I have done?

Many thanks,

Body:
Both ways are fine with one caveat. Because you are specifically checking for both Y and N, your way is probably better in that case since you would otherwise have to call upper() twice:

proceed = input("Would you like to proceed? Y/N ")
if proceed.upper() == "Y":
    doSomething()
elif proceed.upper() == "N":
    doSomethingElse()

On that enhanced checking, your code is slightly different in that it does nothing if the input is neither Y nor N (the other code treats anything that's not y as n). In that case, you're probably wise to ensure it is one of those values, with something like:

proceed = ""
while proceed != "Y" and proceed != "N":
    proceed = input("Would you like to proceed (Y/N)? ").upper()


问:
Merge PDF files
Is it possible to merge a fillable pdf file with a regular pdf file in asp.net C# using itextsharp. Any help would be greatly appreciated.</p>

答:
Yep.

PdfCopyFields sounds just about right.  That way even if your "regular pdf file" has annotations of whatever sort (links, flash, whatever), they'll still work fine.

Alternatively, you could open the form with a PdfStamper, and add PdfImportedPages from the "regular" PDF.  This would preserve everything about the original PDF (metadata, structure, doc-level scripts, etc), and suck in the pages (sans anything that wasn't page contents) from the "regular pdf".

There's no perfect answer here sadly, but there are a at least two viable options to choose from.

Title: Merge PDF files


问:
how awoid 2 times re render in react-native
i have tried to do routing according to user check and i did but my method worked two times. i understand it from my log

i'm using redux and here is my "useeffect" in mainrouter.js

```<code>// currentUser : null // in  initialState for users

useEffect(() => {
    if(states.currentUser== null)
    {
        console.log("Checking user for routing");
        actions.getCurrentUserACT();
    }
    else{
        console.log("Logged in")
    }
},[]);
</code>```

my mainrouter.js return

```<code> return (
    <NavigationContainer>
        {
            states.currentUser == null ?
                (this.SignStackScreen()) :
                (this.MainTabNavigator())
        }
    </NavigationContainer>
);
</code>```

here is my "getCurrentUserAct" method in redux actions

```<code>export function getCurrentUserACT() {
return function (dispatch) {

    firebase.auth().onAuthStateChanged(user => {
        if (user) {
            console.log("User authed..");
            dispatch({type:actionTypes.CURRENT_USER,payload:user})
        } else {
            console.log("User notauthed..");
            dispatch({type:actionTypes.CURRENT_USER,payload:null})
        }
    });
}
</code>```

when my app start, logs are .. (if i logged in before)

Checking user for routing

User authed

User authed

i think the reason for this, useeffect worked first time and state changed which use in return and rerender"
but then i removed to condition, logs were same.

so how i can avoid this?
is there a way to run method before from useeffect and avoid second render? or wait data in useeffect?

答:
```<code>export function getCurrentUserACT() {
return function (dispatch) {

    firebase.auth().onAuthStateChanged(user => {
        dispatch(setCurrentUserACT(user))
        console.log("control point" + user);
        // if (user) {
        //     console.log("User authed..");
        //     dispatch({type:actionTypes.CURRENT_USER,payload:user})
        // } else {
        //     console.log("User notauthed..");
        //     dispatch({type:actionTypes.CURRENT_USER,payload:null})
        // }
    });
}
</code>```

Logs were double

Checking user for routing

control point[object Object]

control point[object Object]

______________________Edited 31.05______________________

I change my code a little bit like below

```<code>const dispatch = useDispatch();
const currentUser = useSelector(state => state.currentUserReducer);
useEffect(() => {
    console.log(JSON.stringify(currentUser));
    if (currentUser == null) {
        console.log("Checking user for routing");
        //dispatch(getCurrentUserACT());
    }
    else {
        console.log("Logged in")
    }
}, []);
</code>```

I found something like hint but I can't fix because i dont know
When app start logs are

null

Checking user for routing

I didnt dispatch getCurrentUserAct(), so logs are right. If i dispatch, user will be checking (user already logged in), component rerender and here is double logs from double render.

I need dispatch before useeffect, not in useeffect

Is there a way?

Body:
i have tried to do routing according to user check and i did but my method worked two times. i understand it from my log

i'm using redux and here is my "useeffect" in mainrouter.js

// currentUser : null // in  initialState for users

useEffect(() => {
    if(states.currentUser== null)
    {
        console.log("Checking user for routing");
        actions.getCurrentUserACT();
    }
    else{
        console.log("Logged in")
    }
},[]);

my mainrouter.js return

 return (
    <NavigationContainer>
        {
            states.currentUser == null ?
                (this.SignStackScreen()) :
                (this.MainTabNavigator())
        }
    </NavigationContainer>
);

here is my "getCurrentUserAct" method in redux actions

export function getCurrentUserACT() {
return function (dispatch) {

    firebase.auth().onAuthStateChanged(user => {
        if (user) {
            console.log("User authed..");
            dispatch({type:actionTypes.CURRENT_USER,payload:user})
        } else {
            console.log("User notauthed..");
            dispatch({type:actionTypes.CURRENT_USER,payload:null})
        }
    });
}

when my app start, logs are .. (if i logged in before)

Checking user for routing

User authed

User authed

i think the reason for this, useeffect worked first time and state changed which use in return and rerender"
but then i removed to condition, logs were same.

so how i can avoid this?
is there a way to run method before from useeffect and avoid second render? or wait data in useeffect?

Body:
export function getCurrentUserACT() {
return function (dispatch) {

    firebase.auth().onAuthStateChanged(user => {
        dispatch(setCurrentUserACT(user))
        console.log("control point" + user);
        // if (user) {
        //     console.log("User authed..");
        //     dispatch({type:actionTypes.CURRENT_USER,payload:user})
        // } else {
        //     console.log("User notauthed..");
        //     dispatch({type:actionTypes.CURRENT_USER,payload:null})
        // }
    });
}

Logs were double

Checking user for routing

control point[object Object]

control point[object Object]

______________________Edited 31.05______________________

I change my code a little bit like below

const dispatch = useDispatch();
const currentUser = useSelector(state => state.currentUserReducer);
useEffect(() => {
    console.log(JSON.stringify(currentUser));
    if (currentUser == null) {
        console.log("Checking user for routing");
        //dispatch(getCurrentUserACT());
    }
    else {
        console.log("Logged in")
    }
}, []);

I found something like hint but I can't fix because i dont know
When app start logs are

null

Checking user for routing

I didnt dispatch getCurrentUserAct(), so logs are right. If i dispatch, user will be checking (user already logged in), component rerender and here is double logs from double render.

I need dispatch before useeffect, not in useeffect

Is there a way?


问:
tar: ./03-Castaway\ on\ the\ Moon\ (Hae-jun\ Lee\ -\ 2009): Cannot stat: No such file or directory
I'm trying to "copy" some files and folder from a external HD to my mac but before that I wanna copy them compressed
almost is ok except when the folders or files names has names with whitespaces.
I can't edit that names because the external HD is mounted for read only (in my Mac).

There is the code:

```<code>#!/bin/bash
rar='.*\.(rar)$'
docx='.*\.(docx)$'
ITER=1
cd /Volumes/TDT/PC/Vídeos/peliculas/
for dir in ./*
do
  if [[ "$dir" =~ rar || "$dir" =~ docx ]]; then
    echo ""
  else
    echo "tar cz ${dir//\ /\ } | gzip > /Users/william/toUpload/movies/${ITER}.tar.gz"
    echo "..."
    tar cz "${dir//\ /\ }" | gzip > "/Users/william/toUpload/movies/${ITER}.tar.gz"
    ITER=$(expr $ITER + 1)
  fi
done
</code>```

There is the error

```<code>tar: ./03-on\ the\ Moon: Cannot stat: No such file or directory
</code>```

Of course the folder exist and have something inside and if I do ls ./03-on\ the\ Moon the folder show me their contain.

答:
I change "$dir" instead ${dir//\ /\ } and it works!
    tar cz "$dir" | gzip > "/Users/william/toUpload/movies/${ITER}.tar.gz"

Thank you!

Body:
I'm trying to "copy" some files and folder from a external HD to my mac but before that I wanna copy them compressed
almost is ok except when the folders or files names has names with whitespaces.
I can't edit that names because the external HD is mounted for read only (in my Mac).

There is the code:

#!/bin/bash
rar='.*\.(rar)$'
docx='.*\.(docx)$'
ITER=1
cd /Volumes/TDT/PC/Vídeos/peliculas/
for dir in ./*
do
  if [[ "$dir" =~ rar || "$dir" =~ docx ]]; then
    echo ""
  else
    echo "tar cz ${dir//\ /\ } | gzip > /Users/william/toUpload/movies/${ITER}.tar.gz"
    echo "..."
    tar cz "${dir//\ /\ }" | gzip > "/Users/william/toUpload/movies/${ITER}.tar.gz"
    ITER=$(expr $ITER + 1)
  fi
done

There is the error

tar: ./03-on\ the\ Moon: Cannot stat: No such file or directory

Of course the folder exist and have something inside and if I do ls ./03-on\ the\ Moon the folder show me their contain.


问:
Problem extracting model covariates for model summary table
I'm a graduate student using a linear regression (count) model to understand drivers of fish movement into and out of tidal wetlands. I am currently trying to generate a publication-worthy model summary table in r. I've been using the sel.table function which has been working well for this purpose.

However, I've been unable to generate a column that contains the individual model formulas. Below is my code which is based off of some nice instructions for using the MuMIn package. https://sites.google.com/site/rforfishandwildlifegrads/home/mumin_usage_examples

So to recap, my question pertains to the last line of code below,

How can I insert model formulas into a model selection table.**

```<code>install.packages("MuMIn")
library(MuMIn)

data = mtcars

models = list(
  model1 <- lm(mpg ~ cyl, data = data),
  model2 <- lm(mpg ~ cyl + hp, data = data),
  model3 <- lm(mpg ~ cyl * hp, data = data)
)

#create an object “out.put” that contains all of the model selection information
out.put <- model.sel(models)

#coerce the object out.put into a data frame
sel.table <-as.data.frame(out.put)[6:10]

#add a column for model names
sel.table$Model <- rownames(sel.table)

#replace model name with formulas
for(i in 1:nrow(sel.table)) sel.table$Model[i]<- as.character(formula(paste(sel.table$Model[i])))[3]

#Any help on this topic would be greatly appreciated!
</code>```

UPDATED CODE

My method of pulling out model names is pretty clunky but otherwise this code seems to generate what I intended (a complete model selection table). Also, I'm not sure if the model coefficients are displayed properly but I hope to follow up on this for my final answer.

```<code>data = mtcars

#write linear models
models = list(
  model1 <- lm(mpg ~ cyl, data = data),
  model2 <- lm(mpg ~ cyl + hp, data = data),
  model3 <- lm(mpg ~ cyl * hp + disp, data = data),
  model4 <- lm(mpg ~ cyl * hp + disp + wt + drat, data = data)
)

#create an object “out.put” that contains all of the model selection information
out.put <- model.sel(models)

#coerce the object out.put into a data frame
sel.table <-as.data.frame(out.put)

#slightly rename intercept column
names(sel.table)[1]="Intercept"

#select variables to display in model summary table
sel.table <- sel.table %>%
 select(Intercept,cyl,hp,disp,wt,drat,df,logLik,AICc,delta)

#round numerical coumns
sel.table[,1:6]<- round(sel.table[,1:6],2)

sel.table[,8:10]<-round(sel.table[,8:10],2)

#add a column for model (row) names
sel.table$Model <- rownames(sel.table)

#extract model formulas
form <- data.frame(name = as.character(lapply(models, `[[`, c(10,2))))

#generate a column with model (row) numbers (beside associated model formulas)
form <- form %>%
  mutate(Model=(1:4))

#merge model table and model formulas
sum_table <- merge (form,sel.table,by="Model")

#rename model equation column
names(sum_table)[2]="Formula"

print <- flextable(head(sum_table))
print <- autofit(print)
print
</code>```

6/1/20 UPDATE:

Below is an image that describes two issues that I'm having with the code. I've found a workaround to the first question but I'm still investigating the second.
see details here

Models end up being misnumbered

Model formula columns are being generated for each model

答:
Since your question isn't reproducible, i'll try with something else and maybe that's what you're looking for:

data = mtcars

models = list(
  model1 = lm(mpg ~ cyl, data = data),
  model2 = lm(mpg ~ cyl + hp, data = data)
  )

data.frame(name = as.character(lapply(models, `[[`, c(10,2))),
           other.column = NA)
#>             name other.column
#> 1      mpg ~ cyl           NA
#> 2 mpg ~ cyl + hp           NA
```

<p><sup>Created on 2020-05-28 by the reprex package (v0.3.0)</sup></p>

<p>The formula (call) of a lm object is on position 10 of the list. You can actually count when you type <code>model1$</code>. You can use <code>rownames()</code> instead of a column, but that's not recommended.</p>

<h1>EDIT AFTER REPRODUCIBLE EXAMPLE</h1>

<pre class="lang-r prettyprint-override"><code>library(MuMIn)

data = mtcars

models = list(
  model1 <- lm(mpg ~ cyl, data = data),
  model2 <- lm(mpg ~ cyl + hp, data = data),
  model3 <- lm(mpg ~ cyl * hp, data = data)
)

# create an object that contains all of the model selection information
out.put <- model.sel(models)

#coerce the object out.put into a data frame
sel.table <-as.data.frame(out.put)[6:10]

# formulas as names
sel.table$name = as.character(lapply(models, `[[`, c(10,2)))

# reordering
sel.table = sel.table[, c(6,1,2,3,4,5)]

sel.table
#>             name df    logLik     AICc    delta    weight
#> 3      mpg ~ cyl  5 -78.14329 168.5943 0.000000 0.5713716
#> 1 mpg ~ cyl + hp  3 -81.65321 170.1636 1.569298 0.2607054
#> 2 mpg ~ cyl * hp  4 -80.78092 171.0433 2.449068 0.1679230
</code>```

Created on 2020-05-31 by the reprex package (v0.3.0)

Body:
I'm a graduate student using a linear regression (count) model to understand drivers of fish movement into and out of tidal wetlands. I am currently trying to generate a publication-worthy model summary table in r. I've been using the sel.table function which has been working well for this purpose.

However, I've been unable to generate a column that contains the individual model formulas. Below is my code which is based off of some nice instructions for using the MuMIn package. https://sites.google.com/site/rforfishandwildlifegrads/home/mumin_usage_examples

So to recap, my question pertains to the last line of code below,

How can I insert model formulas into a model selection table.**

install.packages("MuMIn")
library(MuMIn)

data = mtcars

models = list(
  model1 <- lm(mpg ~ cyl, data = data),
  model2 <- lm(mpg ~ cyl + hp, data = data),
  model3 <- lm(mpg ~ cyl * hp, data = data)
)

#create an object “out.put” that contains all of the model selection information
out.put <- model.sel(models)

#coerce the object out.put into a data frame
sel.table <-as.data.frame(out.put)[6:10]

#add a column for model names
sel.table$Model <- rownames(sel.table)

#replace model name with formulas
for(i in 1:nrow(sel.table)) sel.table$Model[i]<- as.character(formula(paste(sel.table$Model[i])))[3]

#Any help on this topic would be greatly appreciated!

UPDATED CODE

My method of pulling out model names is pretty clunky but otherwise this code seems to generate what I intended (a complete model selection table). Also, I'm not sure if the model coefficients are displayed properly but I hope to follow up on this for my final answer.

data = mtcars

#write linear models
models = list(
  model1 <- lm(mpg ~ cyl, data = data),
  model2 <- lm(mpg ~ cyl + hp, data = data),
  model3 <- lm(mpg ~ cyl * hp + disp, data = data),
  model4 <- lm(mpg ~ cyl * hp + disp + wt + drat, data = data)
)

#create an object “out.put” that contains all of the model selection information
out.put <- model.sel(models)

#coerce the object out.put into a data frame
sel.table <-as.data.frame(out.put)

#slightly rename intercept column
names(sel.table)[1]="Intercept"

#select variables to display in model summary table
sel.table <- sel.table %>%
 select(Intercept,cyl,hp,disp,wt,drat,df,logLik,AICc,delta)

#round numerical coumns
sel.table[,1:6]<- round(sel.table[,1:6],2)

sel.table[,8:10]<-round(sel.table[,8:10],2)

#add a column for model (row) names
sel.table$Model <- rownames(sel.table)

#extract model formulas
form <- data.frame(name = as.character(lapply(models, `[[`, c(10,2))))

#generate a column with model (row) numbers (beside associated model formulas)
form <- form %>%
  mutate(Model=(1:4))

#merge model table and model formulas
sum_table <- merge (form,sel.table,by="Model")

#rename model equation column
names(sum_table)[2]="Formula"

print <- flextable(head(sum_table))
print <- autofit(print)
print

6/1/20 UPDATE:

Below is an image that describes two issues that I'm having with the code. I've found a workaround to the first question but I'm still investigating the second.
see details here

Models end up being misnumbered

Model formula columns are being generated for each model

Body:
Since your question isn't reproducible, i'll try with something else and maybe that's what you're looking for:

data = mtcars

models = list(
  model1 = lm(mpg ~ cyl, data = data),
  model2 = lm(mpg ~ cyl + hp, data = data)
  )

data.frame(name = as.character(lapply(models, `[[`, c(10,2))),
           other.column = NA)
#>             name other.column
#> 1      mpg ~ cyl           NA
#> 2 mpg ~ cyl + hp           NA

Created on 2020-05-28 by the reprex package (v0.3.0)

The formula (call) of a lm object is on position 10 of the list. You can actually count when you type model1$. You can use rownames() instead of a column, but that's not recommended.

EDIT AFTER REPRODUCIBLE EXAMPLE

library(MuMIn)

data = mtcars

models = list(
  model1 <- lm(mpg ~ cyl, data = data),
  model2 <- lm(mpg ~ cyl + hp, data = data),
  model3 <- lm(mpg ~ cyl * hp, data = data)
)

# create an object that contains all of the model selection information
out.put <- model.sel(models)

#coerce the object out.put into a data frame
sel.table <-as.data.frame(out.put)[6:10]

# formulas as names
sel.table$name = as.character(lapply(models, `[[`, c(10,2)))

# reordering
sel.table = sel.table[, c(6,1,2,3,4,5)]

sel.table
#>             name df    logLik     AICc    delta    weight
#> 3      mpg ~ cyl  5 -78.14329 168.5943 0.000000 0.5713716
#> 1 mpg ~ cyl + hp  3 -81.65321 170.1636 1.569298 0.2607054
#> 2 mpg ~ cyl * hp  4 -80.78092 171.0433 2.449068 0.1679230

Created on 2020-05-31 by the reprex package (v0.3.0)


问:
Error in running the volumes in docker toolbox
This is the docker-compose file I have already set the folder to share by Virtual Box VM but it is still not working.

```<code>version: '3'
    services:
      postgres:
        image: 'postgres:latest'
        deploy:
          restart_policy:
            condition: on-failure
            window: 15m
      redis:
        image: 'redis:latest'
      nginx:
        restart: always
        build:
          dockerfile: Dockerfile.dev
          context: ./nginx
        ports:
          - '3050:80'
      api:
        build:
          dockerfile: Dockerfile.dev
          context: ./server
        volumes:
          - /usr/src/app/node_modules
          - ./server:/usr/src/app
        environment:
          - REDIS_HOST=redis
          - REDIS_PORT=6379
          - PGUSER=postgres
          - PGHOST=postgres
          - PGDATABASE=postgres
          - PGPASSWORD=postgres_password
          - PGPORT=5432
      client:
        build:
          dockerfile: Dockerfile.dev
          context: ./client
        volumes:
          - /usr/src/app/node_modules
          - ./client:/usr/src/app
      worker:
        build:
          dockerfile: Dockerfile.dev
          context: ./worker
        volumes:
          - /usr/src/app/node_modules
          - ./worker:/usr/src/app
</code>```

I am running it on Windows 7 sp1. Whenever I run docker-compose up - I get an error:

```<code>api_1       | npm ERR! code ENOENT
api_1       | npm ERR! syscall open
api_1       | npm ERR! path /usr/src/app/package.json
api_1       | npm ERR! errno -2
api_1       | npm ERR! enoent ENOENT: no such file or directory, open '/usr/src/
app/package.json'
api_1       | npm ERR! enoent This is related to npm not being able to find a fi
le.
api_1       | npm ERR! enoent
api_1       |
api_1       | npm ERR! A complete log of this run can be found in:
api_1       | npm ERR!     /root/.npm/_logs/2020-05-28T04_06_56_121Z-debug.log
complex_api_1 exited with code 254
</code>```

Thanks in advance, please help.
I am trying to run a Fibonacci project from the Udemy course of Docker and Kubernetes complete guide.

Each service has its own package.json and other files.

Server Docker File :

```<code>FROM node:alpine

WORKDIR /usr/src/app
COPY package.json .
RUN npm install

COPY . .

CMD ["npm", "run", "dev"]
</code>```

Worker Docker File :

```<code>FROM node:alpine

WORKDIR /usr/src/app
COPY package.json .
RUN npm install

COPY . .

CMD ["npm", "run", "dev"]
</code>```

Client Docker File :

```<code>FROM node:alpine

WORKDIR /usr/src/app
COPY package.json .
RUN npm install

COPY . .

CMD ["npm", "run", "start"]
</code>```

答: I had the same error! Actually I solved moving my project to /c/Users/currentUser from c/Program Files/Docker Toolbox. Maybe you have your project folder inside Program Files directory and not inside Users one, is It right? Try with this, Just Copy your project folder inside users and running your docker-compose from there. Let me know!</p>

Body:
This is the docker-compose file I have already set the folder to share by Virtual Box VM but it is still not working.

version: '3'
    services:
      postgres:
        image: 'postgres:latest'
        deploy:
          restart_policy:
            condition: on-failure
            window: 15m
      redis:
        image: 'redis:latest'
      nginx:
        restart: always
        build:
          dockerfile: Dockerfile.dev
          context: ./nginx
        ports:
          - '3050:80'
      api:
        build:
          dockerfile: Dockerfile.dev
          context: ./server
        volumes:
          - /usr/src/app/node_modules
          - ./server:/usr/src/app
        environment:
          - REDIS_HOST=redis
          - REDIS_PORT=6379
          - PGUSER=postgres
          - PGHOST=postgres
          - PGDATABASE=postgres
          - PGPASSWORD=postgres_password
          - PGPORT=5432
      client:
        build:
          dockerfile: Dockerfile.dev
          context: ./client
        volumes:
          - /usr/src/app/node_modules
          - ./client:/usr/src/app
      worker:
        build:
          dockerfile: Dockerfile.dev
          context: ./worker
        volumes:
          - /usr/src/app/node_modules
          - ./worker:/usr/src/app

I am running it on Windows 7 sp1. Whenever I run docker-compose up - I get an error:

api_1       | npm ERR! code ENOENT
api_1       | npm ERR! syscall open
api_1       | npm ERR! path /usr/src/app/package.json
api_1       | npm ERR! errno -2
api_1       | npm ERR! enoent ENOENT: no such file or directory, open '/usr/src/
app/package.json'
api_1       | npm ERR! enoent This is related to npm not being able to find a fi
le.
api_1       | npm ERR! enoent
api_1       |
api_1       | npm ERR! A complete log of this run can be found in:
api_1       | npm ERR!     /root/.npm/_logs/2020-05-28T04_06_56_121Z-debug.log
complex_api_1 exited with code 254

Thanks in advance, please help.
I am trying to run a Fibonacci project from the Udemy course of Docker and Kubernetes complete guide.

Each service has its own package.json and other files.

Server Docker File :

FROM node:alpine

WORKDIR /usr/src/app
COPY package.json .
RUN npm install

COPY . .

CMD ["npm", "run", "dev"]

Worker Docker File :

FROM node:alpine

WORKDIR /usr/src/app
COPY package.json .
RUN npm install

COPY . .

CMD ["npm", "run", "dev"]

Client Docker File :

FROM node:alpine

WORKDIR /usr/src/app
COPY package.json .
RUN npm install

COPY . .

CMD ["npm", "run", "start"]


问:
printing of xml
I want to print the array into xml format but i am unable to print it.
Here is the code

```<code>if(!empty($recordsArray)){
print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>");
print("<joblist>\n");
foreach ($recordsArray as $data){
</code>```

print("".$data['user_id']."".$data['$task_id']."\n");

```<code>}
print("</joblist>\n");

}
}
</code>```

even i am unable to see

```<code><?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>
</code>```

when i am doing view source its showing

```<code><?xml version="1.0" encoding="UTF-8" ?>
<joblist>
<job><id>123</id><taskid>14</taskid></job>
</joblist>
</code>```

now what to be done to display on the web page

答: What happens if you run print_r($recordsArray)?  It is possible that it is empty.</p>

Title: printing of xml

Body:
I want to print the array into xml format but i am unable to print it.
Here is the code

if(!empty($recordsArray)){
print("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>");
print("<joblist>\n");
foreach ($recordsArray as $data){

print("".$data['user_id']."".$data['$task_id']."\n");

}
print("</joblist>\n");

}
}

even i am unable to see

<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n>

when i am doing view source its showing

<?xml version="1.0" encoding="UTF-8" ?>
<joblist>
<job><id>123</id><taskid>14</taskid></job>
</joblist>

now what to be done to display on the web page


问:
AWS DMS-Oracle to S3
Hi what are the steps needed to  migrate my database(Oracle) to AWS using DMS.
 i want to migrate in S3 and then using glue i will migrate it into postgres.
can anyone suggest step by step process or some link or video which can help.
thanks in advance.</p>

答:
If you want to migrate from Oracle to RDS PostgreSQL the most simple way is to use AWS DMS (Data Migration Services) and the AWS Schema Conversion Tool (AWS SCT).

I will suggest you to take a look at DMS, it will simplify your tasks.

Using S3 and Glue is a lot more complex, you will need to deal with the schema conversion manually, with the datatypes, the loading and so on; that is not the way to handle this task.

I used DMS/SCT several times with great success.

Title: AWS DMS-Oracle to S3