问:
Program to Download all PDF files from webpage
I am trying to write a Python 3 program which will download all the PDF files from this website.
I currently have two codes but none of them work.

```<code>import requests
import urllib.request
import urllib.request
import time
import re
from bs4 import BeautifulSoup
url = 'https://fraser.stlouisfed.org/title/1339#556573.html'
response = requests.get(url)
if response.status_code == 200:
      print("Success")
else:
      print("Failure")

soup = BeautifulSoup(response.text, 'html.parser')
for one_a_tag in soup.findAll('a',href=re.compile(r'(.pdf)')):
    link = one_a_tag['href']
    download_url = 'https://fraser.stlouisfed.org/title/1339'+ link
    urllib.request.urlretrieve(download_url)
    time.sleep(1)
</code>```

The program runs without giving any output or stopping.

An the second program

```<code>from urllib import request
from bs4 import BeautifulSoup
import re
import os
import urllib
url="https://fraser.stlouisfed.org/title/1339#518552"
response = request.urlopen(url).read()
soup= BeautifulSoup(response, "html.parser")
links = soup.find_all('a', href=re.compile(r'(.pdf)'))
url_list = []
for el in links:
    if(el['href'].startswith('http')):
    url_list.append(el['href'])
else:
    url_list.append("https://fraser.stlouisfed.org/title/1339/" + el['href'])

print(url_list)
for url in url_list:
     print(url)
     request.urlretrieve(url, r'C:/Downloads')
</code>```

For both programs if I add a second argument (filename) to urlretrieve where PDF files should download it gives me

[Errno 13] Permission denied: 'C:/Downloads' error.

(I have tried multiple things to solve this error, it does not work, I have Windows). If I do not have the second argument, the second program keeps going on and producing output but does not download.

Could anybody help please?

答:
I have no mistake in using your code, but the PDF is on the next page. Give you an example of using other frameworks for reference only.</p>
```<code>import io
from simplified_scrapy import Spider, SimplifiedDoc
class PdfSpider(Spider):
  name = 'stlouisfed'
  concurrencyPer1s = 5
  allowed_domains = ['stlouisfed.org']
  start_urls = ['https://fraser.stlouisfed.org/title/1339']
  refresh_urls = True

  def afterResponse(self, response, url, error=None, extra=None):
    try:
      # save pdf
      if(response.code==200 and url.find('.pdf')>0):
        name = 'data'+url[url.rindex('/'):]
        file = io.open(name, "wb")
        file.write(response.read())
        file.close()
        return None
      else: # If it's not a pdf, leave it to the frame
        return Spider.afterResponse(self, response, url, error)
    except Exception as err:
      print (err)

  def extract(self,url,html,models,modelNames):
    urls = SimplifiedDoc(html).listA(url=url['url']).containsOr(['/pdf/','.pdf'],attr='url')
    if(urls):
      self.saveUrl(urls)
    return True

from simplified_scrapy.simplified_main import SimplifiedMain
SimplifiedMain.startThread(PdfSpider()) # Start
</code>```

Body:
I am trying to write a Python 3 program which will download all the PDF files from this website.
I currently have two codes but none of them work.

import requests
import urllib.request
import urllib.request
import time
import re
from bs4 import BeautifulSoup
url = 'https://fraser.stlouisfed.org/title/1339#556573.html'
response = requests.get(url)
if response.status_code == 200:
      print("Success")
else:
      print("Failure")

soup = BeautifulSoup(response.text, 'html.parser')
for one_a_tag in soup.findAll('a',href=re.compile(r'(.pdf)')):
    link = one_a_tag['href']
    download_url = 'https://fraser.stlouisfed.org/title/1339'+ link
    urllib.request.urlretrieve(download_url)
    time.sleep(1)

The program runs without giving any output or stopping.

An the second program

from urllib import request
from bs4 import BeautifulSoup
import re
import os
import urllib
url="https://fraser.stlouisfed.org/title/1339#518552"
response = request.urlopen(url).read()
soup= BeautifulSoup(response, "html.parser")
links = soup.find_all('a', href=re.compile(r'(.pdf)'))
url_list = []
for el in links:
    if(el['href'].startswith('http')):
    url_list.append(el['href'])
else:
    url_list.append("https://fraser.stlouisfed.org/title/1339/" + el['href'])

print(url_list)
for url in url_list:
     print(url)
     request.urlretrieve(url, r'C:/Downloads')

For both programs if I add a second argument (filename) to urlretrieve where PDF files should download it gives me

[Errno 13] Permission denied: 'C:/Downloads' error.

(I have tried multiple things to solve this error, it does not work, I have Windows). If I do not have the second argument, the second program keeps going on and producing output but does not download.

Could anybody help please?

Body:
I have no mistake in using your code, but the PDF is on the next page. Give you an example of using other frameworks for reference only.

import io
from simplified_scrapy import Spider, SimplifiedDoc
class PdfSpider(Spider):
  name = 'stlouisfed'
  concurrencyPer1s = 5
  allowed_domains = ['stlouisfed.org']
  start_urls = ['https://fraser.stlouisfed.org/title/1339']
  refresh_urls = True

  def afterResponse(self, response, url, error=None, extra=None):
    try:
      # save pdf
      if(response.code==200 and url.find('.pdf')>0):
        name = 'data'+url[url.rindex('/'):]
        file = io.open(name, "wb")
        file.write(response.read())
        file.close()
        return None
      else: # If it's not a pdf, leave it to the frame
        return Spider.afterResponse(self, response, url, error)
    except Exception as err:
      print (err)

  def extract(self,url,html,models,modelNames):
    urls = SimplifiedDoc(html).listA(url=url['url']).containsOr(['/pdf/','.pdf'],attr='url')
    if(urls):
      self.saveUrl(urls)
    return True

from simplified_scrapy.simplified_main import SimplifiedMain
SimplifiedMain.startThread(PdfSpider()) # Start


来源: stackexchange

问:
Woocommerce - How to hide trailing zeros after the 2nd decimal place?

So I have a question I was hoping somebody might be able to help me out with...
 I have a WordPress website that uses WooCommerce and I'm trying to do something relatively specific. The site has a fair deal of bulk pricing discounts for various products.
Now when it comes to the bulk pricing I kind of need the calculations to be done with four decimal places (i.e. $0.1234), So I have the WooCommerce settings set so that the number of decimals is 4.
The thing is, that on a lot of our products we don't have bulk pricing discounts; in most of these cases the four decimal places are completely unnecessary. (For example: $0.5500 or $12.0000) Is there any way I can trim the trailing the zeros but only if it is after the second decimal place?
For example, if I had $0.5500 it would be displayed as $0.55 and if I had $12.0000 it would be displayed as $12.00

I know a very similar question was asked a few years ago (see here), but unfortunately, the answer that worked in that case does not seem to work for me... That being said, I could be trying to use it the wrong way. I am not very familiar with using regular expressions in a WordPress "functions.php" file.

Any help at all would be greatly appreciated! Thanks!

Edit:

At this point I have something along the lines of:

```<code>add_action('wc_price', 'custom_price_disp');
function custom_price_disp($price) {
    $count = null;
    $resultingPrice = preg_replace('/(?<=\d{2})(0+)$/', '', $price, -1, $count);
    return $resultingPrice;
}
</code>```

But this code does not seem to work. Prices are still displayed the same as they were before.

答:
You can use this function in your functions.php child theme, it works fine and removes .00 from every price:

```<code>add_filter('woocommerce_price_trim_zeros', 'wc_hide_trailing_zeros', 10, 1);
function wc_hide_trailing_zeros( $trim ) {
    // set to false to show trailing zeros
    return true;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have a question I was hoping somebody might be able to help me out with...
 I have a WordPress website that uses WooCommerce and I'm trying to do something relatively specific. The site has a fair deal of bulk pricing discounts for various products.
Now when it comes to the bulk pricing I kind of need the calculations to be done with four decimal places (i.e. $0.1234), So I have the WooCommerce settings set so that the number of decimals is 4.
The thing is, that on a lot of our products we don't have bulk pricing discounts; in most of these cases the four decimal places are completely unnecessary. (For example: $0.5500 or $12.0000) Is there any way I can trim the trailing the zeros but only if it is after the second decimal place?
For example, if I had $0.5500 it would be displayed as $0.55 and if I had $12.0000 it would be displayed as $12.00

I know a very similar question was asked a few years ago (see here), but unfortunately, the answer that worked in that case does not seem to work for me... That being said, I could be trying to use it the wrong way. I am not very familiar with using regular expressions in a WordPress "functions.php" file.

Any help at all would be greatly appreciated! Thanks!

Edit:

At this point I have something along the lines of:

add_action('wc_price', 'custom_price_disp');
function custom_price_disp($price) {
    $count = null;
    $resultingPrice = preg_replace('/(?<=\d{2})(0+)$/', '', $price, -1, $count);
    return $resultingPrice;
}

But this code does not seem to work. Prices are still displayed the same as they were before.

Body:
You can use this function in your functions.php child theme, it works fine and removes .00 from every price:

add_filter('woocommerce_price_trim_zeros', 'wc_hide_trailing_zeros', 10, 1);
function wc_hide_trailing_zeros( $trim ) {
    // set to false to show trailing zeros
    return true;
}

ContentLicense: CC BY-SA 4.0


问:
Flutter: i want to make a row that have two cards with an image and a text like the photo below
Flutter: i want to make a row that have two cards with an image and a text like the photo below

```<code>body: groups.isEmpty
      ? Center(child: Text('No Students'))
      : ListView(
    children: [
      ...groups.map(
            (group) => Card(
            elevation: 7,
            child: ListTile(
              leading: CircleAvatar(
                backgroundImage: AssetImage('assets/01.jpg'),
              ),
              title: Text(group),
              trailing: Icon(Icons.person),

            )
            ),
      )
    ],
        )
</code>```

This is The Full Code!

members image

答:
You can use GridView, set crossAxisCount equal to 2, and place Column inside Card.

```<code> import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: GridView.builder(
          itemCount: 6,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            childAspectRatio: 8.0 / 10.0,
            crossAxisCount: 2,
          ),
          itemBuilder: (BuildContext context, int index) {
            return Padding(
                padding: EdgeInsets.all(5),
                child: Card(
                    semanticContainer: true,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    clipBehavior: Clip.antiAlias,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Expanded(
                            child: Container(
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage('assets/no_image.png'),
                                fit: BoxFit.fill),
                          ),
                        )),
                        Padding(
                            padding: EdgeInsets.all(10.0),
                            child: Text(
                              "Name",
                              style: TextStyle(fontSize: 18.0),
                            )),
                      ],
                    )));
          },
        ));
  }
}
</code>```

Body:
Flutter: i want to make a row that have two cards with an image and a text like the photo below

body: groups.isEmpty
      ? Center(child: Text('No Students'))
      : ListView(
    children: [
      ...groups.map(
            (group) => Card(
            elevation: 7,
            child: ListTile(
              leading: CircleAvatar(
                backgroundImage: AssetImage('assets/01.jpg'),
              ),
              title: Text(group),
              trailing: Icon(Icons.person),

            )
            ),
      )
    ],
        )

This is The Full Code!

members image

Body:
You can use GridView, set crossAxisCount equal to 2, and place Column inside Card.

 import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: GridView.builder(
          itemCount: 6,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            childAspectRatio: 8.0 / 10.0,
            crossAxisCount: 2,
          ),
          itemBuilder: (BuildContext context, int index) {
            return Padding(
                padding: EdgeInsets.all(5),
                child: Card(
                    semanticContainer: true,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                    ),
                    clipBehavior: Clip.antiAlias,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Expanded(
                            child: Container(
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage('assets/no_image.png'),
                                fit: BoxFit.fill),
                          ),
                        )),
                        Padding(
                            padding: EdgeInsets.all(10.0),
                            child: Text(
                              "Name",
                              style: TextStyle(fontSize: 18.0),
                            )),
                      ],
                    )));
          },
        ));
  }
}


问:
Why is SortExpression of GridView getting empty on RowDataBound - C#
I want to show an up/down arrow on the header on my sorting gridview. I have implemented it in the code attached below, but on the row data bound event, sortexpression is coming up empty. Because of this, I can't set the image for sorting direction. </p>

```<code><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CssClass="gridview_alter"  GridLines="Both"
Caption="Submissions today"  CaptionAlign="Top"
AllowSorting="true"
AllowPaging="true"  PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging"
OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound"
OnSorting="GridView1_Sorting">

<Columns>
<asp:BoundField DataField="student_name" HeaderText="student_name"
ReadOnly="True"  SortExpression="student_name">  </asp:BoundField>
<asp:BoundField DataField="Role" HeaderText="Role"
ReadOnly="True"  SortExpression="Role">  </asp:BoundField>
</Columns>

</asp:GridView>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  string imgAsc = @" <img src='~/images/up.png' border='1' title='Ascending' 'width='50' height='50' />";
  string imgDes = @" <img src='~/images/dwn.png' border='1' title='Descendng' 'width='50' height='50' />";
 if (e.Row.RowType == DataControlRowType.Header)
 {
        foreach (TableCell td in e.Row.Cells)
        {
         LinkButton lnkbtn = (LinkButton)td.Controls[0];

        if (lnkbtn.Text == GridView1.SortExpression)//sortexpression is grtting empty here
            {
                if (GridView1.SortDirection == SortDirection.Ascending)
                {
                    lnkbtn.Text += imgAsc;
                }
                else
                    lnkbtn.Text += imgDes;
            }
        }
    }
</code>```

答:
The best place to check for sortexpression (and any work to do based on sorting) will be the Gridview's OnSorting Event.

So, in this OnSorting event you can get the Header Row and apply the ASC / DESC image.

```<code>protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
  {
    // Get the header row.
    GridViewRow headerRow = GridView1.HeaderRow;
    if(headerRow != null)
     {
        foreach (TableCell td in headerRow.Cells)
         {
            LinkButton lnkbtn = (LinkButton)td.Controls[0];

             if (lnkbtn.Text == e.SortExpression)
               {
                  if (GridView1.SortDirection == SortDirection.Ascending)
                  {
                      lnkbtn.Text += imgAsc;
                  }
                  else
                    lnkbtn.Text += imgDes;
               }
         }
     }
  }
</code>```

Body:
I want to show an up/down arrow on the header on my sorting gridview. I have implemented it in the code attached below, but on the row data bound event, sortexpression is coming up empty. Because of this, I can't set the image for sorting direction.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CssClass="gridview_alter"  GridLines="Both"
Caption="Submissions today"  CaptionAlign="Top"
AllowSorting="true"
AllowPaging="true"  PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging"
OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound"
OnSorting="GridView1_Sorting">

<Columns>
<asp:BoundField DataField="student_name" HeaderText="student_name"
ReadOnly="True"  SortExpression="student_name">  </asp:BoundField>
<asp:BoundField DataField="Role" HeaderText="Role"
ReadOnly="True"  SortExpression="Role">  </asp:BoundField>
</Columns>

</asp:GridView>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  string imgAsc = @" ";
  string imgDes = @" ";
 if (e.Row.RowType == DataControlRowType.Header)
 {
        foreach (TableCell td in e.Row.Cells)
        {
         LinkButton lnkbtn = (LinkButton)td.Controls[0];

        if (lnkbtn.Text == GridView1.SortExpression)//sortexpression is grtting empty here
            {
                if (GridView1.SortDirection == SortDirection.Ascending)
                {
                    lnkbtn.Text += imgAsc;
                }
                else
                    lnkbtn.Text += imgDes;
            }
        }
    }

Body:
The best place to check for sortexpression (and any work to do based on sorting) will be the Gridview's OnSorting Event.

So, in this OnSorting event you can get the Header Row and apply the ASC / DESC image.

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
  {
    // Get the header row.
    GridViewRow headerRow = GridView1.HeaderRow;
    if(headerRow != null)
     {
        foreach (TableCell td in headerRow.Cells)
         {
            LinkButton lnkbtn = (LinkButton)td.Controls[0];

             if (lnkbtn.Text == e.SortExpression)
               {
                  if (GridView1.SortDirection == SortDirection.Ascending)
                  {
                      lnkbtn.Text += imgAsc;
                  }
                  else
                    lnkbtn.Text += imgDes;
               }
         }
     }
  }


问:
Unable to implement a floating button in Django template
I am trying to create a floating button as shown in this video. However I am unable to implement the same. I am basically tying to add this to one my django templates.

Here is the code of the HTML:

```<code>{% extends "base.html" %}
{% load bootstrap4 %}
{% block content %}
<button  class="material-icons floating-btnz">Add</button>

Some more code here

{% endblock %}
<style>
    .floating-btnz{
        width: 80px;
        height: 80px;
        background: #009879;
        display: flex;
        border-radius: 50%;
        color: #ffffff;
        font-size: 40px;
        align-items: center;
        justify-content: center;
        text-decoration: none;
        box-shadow: 2px 2px 5px rgba(0,0,0, 0.25);
        outline: blue;
        border: none;
        cursor: pointer;
    }
</style>
</code>```

I have included the material icon cdn in my base.html. It seems to me that the cdn is not working. Upon checking in the web console, the css is loading but not showing up on the button. Where am I going wrong? Any help is appreciated.

答:
If you wrote the
{% endblock %}```

Body:
I am trying to create a floating button as shown in this video. However I am unable to implement the same. I am basically tying to add this to one my django templates.

Here is the code of the HTML:

{% extends "base.html" %}
{% load bootstrap4 %}
{% block content %}
<button  class="material-icons floating-btnz">Add</button>

Some more code here

{% endblock %}

I have included the material icon cdn in my base.html. It seems to me that the cdn is not working. Upon checking in the web console, the css is loading but not showing up on the button. Where am I going wrong? Any help is appreciated.

Body:
If you wrote the <style> outside blocks, then it will not be rendered, so you should render it inside a block.

Note that prior to html-5.2 one could only put the <style> tag to be in the <head> block. As of HTML 5.2 one is allowed to put that in the <body> tag as well, but still it might be better to do this in the <head>, since some older browsers might not accept that.

{% extends "base.html" %}
{% load bootstrap4 %}
{% block header %}
<style>
    .floating-btnz{
        width: 80px;
        height: 80px;
        background: #009879;
        display: flex;
        border-radius: 50%;
        color: #ffffff;
        font-size: 40px;
        align-items: center;
        justify-content: center;
        text-decoration: none;
        box-shadow: 2px 2px 5px rgba(0,0,0, 0.25);
        outline: blue;
        border: none;
        cursor: pointer;
    }
</style>
{% endblock %}


问:
How can I use HATEOAS and Query Parameters for RESTful search?
I would like to design a RESTful search URI using query parameters. For example, this URI returns a list of all users:

GET /users

And the first 25 users with the last name "Harvey":

GET /users?surname=Harvey&maxResults=25

How can I use hypermedia to describe what query parameters are allowed by the "/users" resource? I noticed that the new Google Tasks API just documents all the query parameters in the reference guide. I will document the list, but I would like to do it with HATEOAS too.

Thank you in advance!

答:
The other option is to use an html form:

```<code><form method="get" action="/users">
   <label for="surname">Surname: </label>
     <input type="text" name="surname"/>
   <label for="maxresults">Max Results: </label>
     <input type="text" name="maxresults" value="25"/> <!-- default is 25 -->
   <input type="submit" name="submitbutton" value="submit"/>
</form>
</code>```

A form like this fully documents the available options and any defaults, it creates the specified URL and can be annotated with any further documentation that you care to put there.

Body:
The other option is to use an html form:

<form method="get" action="/users">
   <label for="surname">Surname: </label>
     <input type="text" name="surname"/>
   <label for="maxresults">Max Results: </label>
     <input type="text" name="maxresults" value="25"/> <!-- default is 25 -->
   <input type="submit" name="submitbutton" value="submit"/>
</form>

A form like this fully documents the available options and any defaults, it creates the specified URL and can be annotated with any further documentation that you care to put there.


问:
c: default values for repeated fields with nanopb (protobuf)
I am trying to create a message with a repeated field which has some default values.
I'm starting slow, with a simple int repeated (my final goal is a repeated message which all fields are have some value default)

so, to start my proto is:

```<code>syntax = "proto2"
import "google/protobuf/descriptor.proto";
import "nanopb.proto";

message MyDefault {
  repeated int32 default = 1 [(nanopb).max_count = 3];
}

extend google.protobuf.FieldOptions {
  optional MyDefault my_default = 1234;
}

message M {
  repeated int32 x = 1 [(my_default) = {default: [1, 2, 3]}, (nanopb).max_count = 3];
}
</code>```

protobuf is compiled, but no trace to my default values.

答:
There are no default values for repeated fields in nanopb currently. As far as I know, they don't exist in other protobuf implementations either.

Some other protobuf libraries do provide access to custom field options, but nanopb currently does not.

Body:
I am trying to create a message with a repeated field which has some default values.
I'm starting slow, with a simple int repeated (my final goal is a repeated message which all fields are have some value default)

so, to start my proto is:

syntax = "proto2"
import "google/protobuf/descriptor.proto";
import "nanopb.proto";

message MyDefault {
  repeated int32 default = 1 [(nanopb).max_count = 3];
}

extend google.protobuf.FieldOptions {
  optional MyDefault my_default = 1234;
}

message M {
  repeated int32 x = 1 [(my_default) = {default: [1, 2, 3]}, (nanopb).max_count = 3];
}

protobuf is compiled, but no trace to my default values.


问:
How to correctly use selenium with Firefox?
I am trying to make selenium work with Firefox 71.00 x64 en-US, the code I am entering is:

```<code>from selenium import webdriver
browser = webdriver.Firefox()
</code>```

but the browser doesn't start and I keep getting this error even if I already added to the system path both geckodriver(last version downloadable) and the directory to firefox.exe:

```<code>  File "C:\Users\Tommaso\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\common\service.py", line 72, in start
    self.process = subprocess.Popen(cmd, env=self.env,
  File "C:\Users\Tommaso\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\Tommaso\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] Impossibile trovare il file specificato
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\Tommaso\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\firefox\webdriver.py", line 164, in __init__
    self.service.start()
  File "C:\Users\Tommaso\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\common\service.py", line 81, in start
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
</code>```

答: Fixed it by adding geckodriver.exe to the same directory as python.exe.

Body:
I am trying to make selenium work with Firefox 71.00 x64 en-US, the code I am entering is:

from selenium import webdriver
browser = webdriver.Firefox()

but the browser doesn't start and I keep getting this error even if I already added to the system path both geckodriver(last version downloadable) and the directory to firefox.exe:

  File "C:\Users\Tommaso\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\common\service.py", line 72, in start
    self.process = subprocess.Popen(cmd, env=self.env,
  File "C:\Users\Tommaso\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\Tommaso\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] Impossibile trovare il file specificato
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Users\Tommaso\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\firefox\webdriver.py", line 164, in __init__
    self.service.start()
  File "C:\Users\Tommaso\AppData\Roaming\Python\Python38\site-packages\selenium\webdriver\common\service.py", line 81, in start
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.


问:
Crossoword Visualizer Breadth first search with direction
I'm currently working on a little project of mine, a crossword Solver.

Given an Input of 64 characters, an algorithm displays them on a 8x8 board and then goes on to look if any of the word match.

So far I've written an algorithm that for each word loops through the letters on the board and checks if any of them are equal to the first character of the word. If that's the case, I call a helper function that returns all neighbours of the current character and proceeds checking if any of those neighbours are equal to the second character of the word, and so on.... So basically it is a breadth first search algorithm using a queue and pushing neighbours to that queue :)

So far this works perfectly, however I now realised, that once the algoorithm has matched the second character of a word, the helper funciton should only return the neighbour that has the same direction.

for example, if my board looks like this:

```<code>Y A T
C E V
B X S
</code>```

and I need to look for the word 'YES', the algorithm gets a match at [0][0] and gets all the neightbours (in this case A,C,E). Then it checks if any of those match the second character of the word (here it is E). But now the algorithm should see that the word follows diagnoally and only return the diagonal neighbour (here S).

Do you know any elegant way of passing this information to the helper funciton without having to write thousands of if statements?

For better understanding, here is the code I've written so far:

https://jsfiddle.net/jakob_mayerhofer/84xrfuwL/7/

Of course, if you have any other suggestions how I could write the algorithm leaner/more efficently I'm open to all feedback.

Thanks for your help, appreciate it :)

答:
I would not choose a BFS algorithm for this, because you already know the length of the word to look for. A BFS is what you would choose when you need to find the shortest path among alternatives, but here there are only 4 possible alternatives from a given starting point (north, south, east, west), and they all have equal length. In such a situation, you don't really need a graph-searching algorithm.

So I would change the inner part of your crossWordSolver, and use a loop over the 4 possible directions, and per direction, just scan in that direction immediately up to the length of the word.

Here is how that would look:

```<code>function crosswordSolver(words, grid) {
  let directions = [[-1, 0], [0, -1], [1, 0], [0, 1]];
  for (word of words) {
    let found = false;
    for (let i = 0; i < 8 && !found; i++) { // <-- extra exit condition
      for (let j = 0; j < 8 && !found; j++) { // <-- ... also here.
        if (grid[i][j] == word[0]) { // Simple check for 1st char
          for (let [dx, dy] of directions) { // Four directions to scan.
            found = true;
            for (let k = 0, x = i, y = j; k < word.length; k++, x+=dx, y+=dy) {
              if (x < 0 || y < 0 || x > 7 || y > 7 || word[k] !== grid[x][y]) {
                found = false; // Out of bounds, or mismatch
                break;
              }
            }
            if (found) break;
          }
        }
      }
    }
    if (found) checked.push(word);
  }
  console.log(checked);
}
</code>```

Body:
I'm currently working on a little project of mine, a crossword Solver.

Given an Input of 64 characters, an algorithm displays them on a 8x8 board and then goes on to look if any of the word match.

So far I've written an algorithm that for each word loops through the letters on the board and checks if any of them are equal to the first character of the word. If that's the case, I call a helper function that returns all neighbours of the current character and proceeds checking if any of those neighbours are equal to the second character of the word, and so on.... So basically it is a breadth first search algorithm using a queue and pushing neighbours to that queue :)

So far this works perfectly, however I now realised, that once the algoorithm has matched the second character of a word, the helper funciton should only return the neighbour that has the same direction.

for example, if my board looks like this:

Y A T
C E V
B X S

and I need to look for the word 'YES', the algorithm gets a match at [0][0] and gets all the neightbours (in this case A,C,E). Then it checks if any of those match the second character of the word (here it is E). But now the algorithm should see that the word follows diagnoally and only return the diagonal neighbour (here S).

Do you know any elegant way of passing this information to the helper funciton without having to write thousands of if statements?

For better understanding, here is the code I've written so far:

https://jsfiddle.net/jakob_mayerhofer/84xrfuwL/7/

Of course, if you have any other suggestions how I could write the algorithm leaner/more efficently I'm open to all feedback.

Thanks for your help, appreciate it :)

Body:
I would not choose a BFS algorithm for this, because you already know the length of the word to look for. A BFS is what you would choose when you need to find the shortest path among alternatives, but here there are only 4 possible alternatives from a given starting point (north, south, east, west), and they all have equal length. In such a situation, you don't really need a graph-searching algorithm.

So I would change the inner part of your crossWordSolver, and use a loop over the 4 possible directions, and per direction, just scan in that direction immediately up to the length of the word.

Here is how that would look:

function crosswordSolver(words, grid) {
  let directions = [[-1, 0], [0, -1], [1, 0], [0, 1]];
  for (word of words) {
    let found = false;
    for (let i = 0; i < 8 && !found; i++) { // <-- extra exit condition
      for (let j = 0; j < 8 && !found; j++) { // <-- ... also here.
        if (grid[i][j] == word[0]) { // Simple check for 1st char
          for (let [dx, dy] of directions) { // Four directions to scan.
            found = true;
            for (let k = 0, x = i, y = j; k < word.length; k++, x+=dx, y+=dy) {
              if (x < 0 || y < 0 || x > 7 || y > 7 || word[k] !== grid[x][y]) {
                found = false; // Out of bounds, or mismatch
                break;
              }
            }
            if (found) break;
          }
        }
      }
    }
    if (found) checked.push(word);
  }
  console.log(checked);
}


问:
Setting property to newly alloc'd object using accessor cause memory leak
I just want confirmation on whether or not the following causes a memory leak.

.h file

```<code>@property (nonatomic, retain) MyObject *foo;
</code>```

.m file

```<code>@synthesize foo;
...

self.foo = [[MyObject alloc] init];
</code>```

dealloc is setup as

```<code>[foo release];
</code>```

My understanding is that the implementation of the auto-generated accessor method looks like

```<code>-(void)setFoo:(MyObject *)newObject {
    if (foo != newObject) {
        [foo release];
        foo = [newObject retain];
    }
}
</code>```

Walking through self.foo = [[MyObject alloc] init]; now reads to me as, "allocated a new MyObject object whose retain count will be 1, pass it to setFoo:, foo will never be equal to myObject as it was newly allocated, so release the old value, increment the retain count of newObject making it 2 and assign it to foo"

dealloc releases foo therefore setting its retain count to 1, which means this object is leaked?

To do this safely we should write our code like

```<code>self.foo = [[[MyObject alloc] init] autorelease];
</code>```

Is my understanding correct?

EDIT

I realize this question is not really appropriate for SO, so feel free to point me to a better place to ask this type of question as well.

答:
you could do that.  Alternatively, since we know the setter automatically retains, we could do the following rather than autorelease:

```<code>foo=[[MyObject alloc] init];
</code>```

Which you choose may be a matter of coding style.  If you are trying to get the hang of using self.foo, then by all means use your method for the sake of consistency and bug fixing.  If you are comfortable with using the dot syntax then use the latter.

Body:
I just want confirmation on whether or not the following causes a memory leak.

.h file

@property (nonatomic, retain) MyObject *foo;

.m file

@synthesize foo;
...

self.foo = [[MyObject alloc] init];

dealloc is setup as

[foo release];

My understanding is that the implementation of the auto-generated accessor method looks like

-(void)setFoo:(MyObject *)newObject {
    if (foo != newObject) {
        [foo release];
        foo = [newObject retain];
    }
}

Walking through self.foo = [[MyObject alloc] init]; now reads to me as, "allocated a new MyObject object whose retain count will be 1, pass it to setFoo:, foo will never be equal to myObject as it was newly allocated, so release the old value, increment the retain count of newObject making it 2 and assign it to foo"

dealloc releases foo therefore setting its retain count to 1, which means this object is leaked?

To do this safely we should write our code like

self.foo = [[[MyObject alloc] init] autorelease];

Is my understanding correct?

EDIT

I realize this question is not really appropriate for SO, so feel free to point me to a better place to ask this type of question as well.

Body:
you could do that.  Alternatively, since we know the setter automatically retains, we could do the following rather than autorelease:

foo=[[MyObject alloc] init];

Which you choose may be a matter of coding style.  If you are trying to get the hang of using self.foo, then by all means use your method for the sake of consistency and bug fixing.  If you are comfortable with using the dot syntax then use the latter.


问:
How to get reference to a ViewModel
I have a problem. I use the Navigation Framework and one of the screens manually sets child fragment. Most of the time there is portrait orientation, but there is the case where it goes into full screen and unlocks rotation. When rotation occurs previous fragment still exists and tries to do its onDestroy() function which leads to the crash because ViewModel still not initialized.

I think I did the wrong way (obviously).

This one leads to the crush (child fragment which directly set by the parent fragment):

```<code>private val vm: PlayCardsVm by lazy {
        (parentFragmentManager.findFragmentById(R.id.nav_host_fragment)
                as? PlayCardsFragment)?.vm ?: throw IllegalStateException()
    }
</code>```

Previously I tried to use parentFragment as LifecycleOwner to obtain ViewModel. But it didn't work.
This function from the parent fragment which manages child fragments:

```<code>private fun onCardPage(cardPage: CardPage?) {
        if (cardPage != null) {
            parentFragmentManager.beginTransaction()
                .replace(R.id.card_container, CardFragment.getInstance(cardPage), "tag")
                .commit()
            placeholder.isVisible = false
        } else {
            parentFragmentManager.findFragmentByTag("tag")?.let {
                parentFragmentManager.beginTransaction()
                    .remove(it)
                    .commit()
            }
            placeholder.isVisible = true
        }
    }
</code>```

I thought that there childFragmentManager must be used, but It also didn't work, and I turned to use parent one instead. But I still need ViewModel when onDestroy has occurred in the child fragment.

Please help me.

Edit: Inthe child fragment:

```<code>override fun onDestroy() {
        super.onDestroy()
        vm.stopAudio()
    }
</code>```

答:
Okay so you are not adding null check here. you can do this -

```<code>override fun onDestroy() {
        super.onDestroy()
        vm?.stopAudio()
    }
</code>```

Just add a null check before calling stopAudio() method. It will avoid your crash.

Title: How to get reference to a ViewModel

Body:
I have a problem. I use the Navigation Framework and one of the screens manually sets child fragment. Most of the time there is portrait orientation, but there is the case where it goes into full screen and unlocks rotation. When rotation occurs previous fragment still exists and tries to do its onDestroy() function which leads to the crash because ViewModel still not initialized.

I think I did the wrong way (obviously).

This one leads to the crush (child fragment which directly set by the parent fragment):

private val vm: PlayCardsVm by lazy {
        (parentFragmentManager.findFragmentById(R.id.nav_host_fragment)
                as? PlayCardsFragment)?.vm ?: throw IllegalStateException()
    }

Previously I tried to use parentFragment as LifecycleOwner to obtain ViewModel. But it didn't work.
This function from the parent fragment which manages child fragments:

private fun onCardPage(cardPage: CardPage?) {
        if (cardPage != null) {
            parentFragmentManager.beginTransaction()
                .replace(R.id.card_container, CardFragment.getInstance(cardPage), "tag")
                .commit()
            placeholder.isVisible = false
        } else {
            parentFragmentManager.findFragmentByTag("tag")?.let {
                parentFragmentManager.beginTransaction()
                    .remove(it)
                    .commit()
            }
            placeholder.isVisible = true
        }
    }

I thought that there childFragmentManager must be used, but It also didn't work, and I turned to use parent one instead. But I still need ViewModel when onDestroy has occurred in the child fragment.

Please help me.

Edit: Inthe child fragment:

override fun onDestroy() {
        super.onDestroy()
        vm.stopAudio()
    }

Body:
Okay so you are not adding null check here. you can do this -

override fun onDestroy() {
        super.onDestroy()
        vm?.stopAudio()
    }

Just add a null check before calling stopAudio() method. It will avoid your crash.


问:
Split multiple columns into new rows
I have a problem with splitting two columns into new rows.

My dataframe looks like this

"involved" and "team_player_formation" each have 15 strings, that needs to be assigned into each their row. With the first string of "involved" matching first string of "team_player_formation"

I have tried to follow this: Split (explode) pandas dataframe string entry to separate rows and searching for ways to split multiple columns, but without success

I have been able to split one of my columns with the following at the moment

```<code>df = pd.read_csv('Hello.csv',  delimiter=';')
df = df.assign(involved=df['involved'].str.split(',')).explode('involved')
</code>```

Which gives me something like this:

```<code>     matchId                                contestantId periodId typeId    involved    team_formation  team_player_formation
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  b2492j7qzdo7g3ysxz6gq4g5x   4   1
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  b2492j7qzdo7g3ysxz6gq4g5x   4   1
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  b2492j7qzdo7g3ysxz6gq4g5x   4   1
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  b2492j7qzdo7g3ysxz6gq4g5x   4   1
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  b2492j7qzdo7g3ysxz6gq4g5x   4   1
    ..................

    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  am3509ake84cde1xhb9264i22   4   0
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  am3509ake84cde1xhb9264i22   4   0
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  am3509ake84cde1xhb9264i22   4   0
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  am3509ake84cde1xhb9264i22   4   0
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  am3509ake84cde1xhb9264i22   4   0
</code>```

But that only split "involed" into a new column.

The output should be something like this, where I have only showed the first 3 rows.

Thank you! I hope you can help, and that I explained it well enough.

答:
If I undstand your problem correctly, you can use this MCVE to help with your analysis.

```<code>df = pd.DataFrame({'ID':[1],'string1':['A,B,C'], 'string2':['X,Y,Z']}, index=[0])

df_joined = df.join([df['string1'].str.split(',', expand=True).add_prefix('s1_'),
                     df['string2'].str.split(',', expand=True).add_prefix('s2_')])

pd.wide_to_long(df_joined, ['s1','s2'], 'ID', 'No', sep='_').reset_index()
</code>```

Output:

```<code>   ID  No string1 string2 s1 s2
0   1   0   A,B,C   X,Y,Z  A  X
1   1   1   A,B,C   X,Y,Z  B  Y
2   1   2   A,B,C   X,Y,Z  C  Z
</code>```

Title: Split multiple columns into new rows

Body:
I have a problem with splitting two columns into new rows.

My dataframe looks like this

"involved" and "team_player_formation" each have 15 strings, that needs to be assigned into each their row. With the first string of "involved" matching first string of "team_player_formation"

I have tried to follow this: Split (explode) pandas dataframe string entry to separate rows and searching for ways to split multiple columns, but without success

I have been able to split one of my columns with the following at the moment

df = pd.read_csv('Hello.csv',  delimiter=';')
df = df.assign(involved=df['involved'].str.split(',')).explode('involved')

Which gives me something like this:

     matchId                                contestantId periodId typeId    involved    team_formation  team_player_formation
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  b2492j7qzdo7g3ysxz6gq4g5x   4   1
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  b2492j7qzdo7g3ysxz6gq4g5x   4   1
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  b2492j7qzdo7g3ysxz6gq4g5x   4   1
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  b2492j7qzdo7g3ysxz6gq4g5x   4   1
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  b2492j7qzdo7g3ysxz6gq4g5x   4   1
    ..................

    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  am3509ake84cde1xhb9264i22   4   0
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  am3509ake84cde1xhb9264i22   4   0
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  am3509ake84cde1xhb9264i22   4   0
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  am3509ake84cde1xhb9264i22   4   0
    0   d5321qxmnyf9004i049uf4pre   77tfx9me4aaqhzv78bmgsy9bg   2   40  am3509ake84cde1xhb9264i22   4   0

But that only split "involed" into a new column.

The output should be something like this, where I have only showed the first 3 rows.

Thank you! I hope you can help, and that I explained it well enough.

Body:
If I undstand your problem correctly, you can use this MCVE to help with your analysis.

df = pd.DataFrame({'ID':[1],'string1':['A,B,C'], 'string2':['X,Y,Z']}, index=[0])

df_joined = df.join([df['string1'].str.split(',', expand=True).add_prefix('s1_'),
                     df['string2'].str.split(',', expand=True).add_prefix('s2_')])

pd.wide_to_long(df_joined, ['s1','s2'], 'ID', 'No', sep='_').reset_index()

Output:

   ID  No string1 string2 s1 s2
0   1   0   A,B,C   X,Y,Z  A  X
1   1   1   A,B,C   X,Y,Z  B  Y
2   1   2   A,B,C   X,Y,Z  C  Z


问:
How to avoid Error: $ operator is invalid for atomic vectors using precintcon package in R?
I have a dataframe df,with monthly rainfall

```<code>str(df)
'data.frame':   396 obs. of  21 variables:
 $ year         : int  1986 1986 1986 1986 1986 1986 1986 1986 1986 1986 ...
 $ month        : int  1 2 3 4 5 6 7 8 9 10 ...
 $ stn1         : int  2 42 91 267 482 1282 1207 982 705 259 ...
 $ stn2         : int  0 9 23 61 68 151 196 73 172 59 ...
 $ stn3         : int  0 10 34 52 122 258 349 237 140 154 …
</code>```

I want to calculate Rainfall Anomaly Index (rai) for all the station (stn1, stn2, stn3,....).
I used the following code:

```<code>library(precintcon)
rai(df, granularity = "m")
</code>```

However it gives the following error

```<code>Error: $ operator is invalid for atomic vectors
</code>```

But when I use it for only one station it works

```<code>rai(df[1:3], granularity = "m") #calculating rai for one only station
</code>```

How can I calculate rai for all the station at once without any error?

答:
A solution, not far form the solution proposed by @RonakShah :</p>

```<code>num_stations <- 3
rais <-  lapply(1:num_stations, function(k) {
   dfk <- df[,c(1,2,k+2)]
   rai(dfk, granularity = "m")
})

# Plot rai of the first station
plot(rais[[1]])
</code>```

Body:
I have a dataframe df,with monthly rainfall

str(df)
'data.frame':   396 obs. of  21 variables:
 $ year         : int  1986 1986 1986 1986 1986 1986 1986 1986 1986 1986 ...
 $ month        : int  1 2 3 4 5 6 7 8 9 10 ...
 $ stn1         : int  2 42 91 267 482 1282 1207 982 705 259 ...
 $ stn2         : int  0 9 23 61 68 151 196 73 172 59 ...
 $ stn3         : int  0 10 34 52 122 258 349 237 140 154 …

I want to calculate Rainfall Anomaly Index (rai) for all the station (stn1, stn2, stn3,....).
I used the following code:

library(precintcon)
rai(df, granularity = "m")

However it gives the following error

Error: $ operator is invalid for atomic vectors

But when I use it for only one station it works

rai(df[1:3], granularity = "m") #calculating rai for one only station

How can I calculate rai for all the station at once without any error?

Body:
A solution, not far form the solution proposed by @RonakShah :

num_stations <- 3
rais <-  lapply(1:num_stations, function(k) {
   dfk <- df[,c(1,2,k+2)]
   rai(dfk, granularity = "m")
})

# Plot rai of the first station
plot(rais[[1]])


问:
How to execute commands needed to prepare an artifact
Is there a best practice for executing a preparation command within a CDK stack?

For example, if I was creating a Lambda and I wanted to run serverless package before deployment, is there a way to have the CDK execute that command when necessary? I was reading the documentation and it seems like maybe Construct#prepare would be appropriate?

Basically all I need to run is a child_process.execSync.

Any help appreciated!

答:
Two approaches that I would recommend:

1. Use a wrapper script (e.g. scripts section of package.json):

```<code>{
   "name": "your-app",
   "scripts":{
      "deploy": "serverless package && cdk deploy"
   }
}
</code>```

2. Use cdk.json

```<code>{
  "app": "serverless package && npx ts-node bin/ci.ts"
}
</code>```

Use the first if your project already uses package.json as an entrypoint for common operations. The second one is more generic but I dislike it because it's a bit more "hidden" (people who are new to CDK may never notice that it's there).

Body:
Two approaches that I would recommend:

1. Use a wrapper script (e.g. scripts section of package.json):

{
   "name": "your-app",
   "scripts":{
      "deploy": "serverless package && cdk deploy"
   }
}

2. Use cdk.json

{
  "app": "serverless package && npx ts-node bin/ci.ts"
}

Use the first if your project already uses package.json as an entrypoint for common operations. The second one is more generic but I dislike it because it's a bit more "hidden" (people who are new to CDK may never notice that it's there).


问:
Very different performance (python3 vs dotnet ) of Rabbitmq using the same library apis
I've been trying to figure out what is the best way to use rabbitmq python library (pika/aiopika) while I've noticed I'm getting very different results when I'm doing the same thing using the dotnet library (RabbitMQ.Client).

python:

```<code>import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
exchange_name = "test-load"
channel.exchange_declare(exchange_name, exchange_type="topic", durable=True)
msg = 'WhySoSLow?'
while True:
    channel.basic_publish(exchange=exchange_name,routing_key="random", body=msg)
</code>```

This got me the results of 11K msgs/s with 100% CPU usage

And for the dotnet:

```<code>using RabbitMQ.Client;

var factory = new ConnectionFactory() { HostName = "localhost" };
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
    channel.ExchangeDeclare(exchange: "test-load", durable: true, type: "topic");

    var routingKey = "random";
    var message = "WhySoSLow?";

    var body = Encoding.UTF8.GetBytes(message);
    while(true)
    {
        channel.BasicPublish(   exchange: "test-load",
                                routingKey: routingKey,
                                basicProperties: null,
                                body: body);

    }
}
</code>```

This code produces the results of 100K msgs/s with 30% CPU usage

What am I doing wrong?

答:
Performance differs between languages. C++ would be even faster.

C# has more optimization at both compile- and runtime, while pyton have to deal with boxing and unboxing all the time.

Maybe you can gain some optimization ideas from one of the comment above but with the library you use I doubt.

Body:
I've been trying to figure out what is the best way to use rabbitmq python library (pika/aiopika) while I've noticed I'm getting very different results when I'm doing the same thing using the dotnet library (RabbitMQ.Client).

python:

import pika
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
exchange_name = "test-load"
channel.exchange_declare(exchange_name, exchange_type="topic", durable=True)
msg = 'WhySoSLow?'
while True:
    channel.basic_publish(exchange=exchange_name,routing_key="random", body=msg)

This got me the results of 11K msgs/s with 100% CPU usage

And for the dotnet:

using RabbitMQ.Client;

var factory = new ConnectionFactory() { HostName = "localhost" };
using(var connection = factory.CreateConnection())
using(var channel = connection.CreateModel())
{
    channel.ExchangeDeclare(exchange: "test-load", durable: true, type: "topic");

    var routingKey = "random";
    var message = "WhySoSLow?";

    var body = Encoding.UTF8.GetBytes(message);
    while(true)
    {
        channel.BasicPublish(   exchange: "test-load",
                                routingKey: routingKey,
                                basicProperties: null,
                                body: body);

    }
}

This code produces the results of 100K msgs/s with 30% CPU usage

What am I doing wrong?


问:
Spring POST relationship json not working
I was trying to post an object with relationship to server.
But I got an error.

My entity:

```<code>@Entity
public class District implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(unique = true)
private String name;

@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference
@JsonUnwrapped
private City city;

@JsonManagedReference
@JsonIgnoreProperties
@OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Region> regions = new HashSet<>();

@JsonIgnoreProperties
@OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Drugstore> drugstores = new HashSet<>();

//getter and setters
</code>```

Here is my controller:

```<code>@PostMapping("/admin/district")
ResponseEntity<?> create(@RequestBody District request) {
    service.create(request);
    return null;
}
</code>```

Here is my error:

If I send null json, I get this error again.
Can anybody help?

答:
after i try several minutes i found the solution.

If use @JsonBackReference in project more than twice, should
  distinguish them with a specific Reference name.

so i do like this:

```<code>@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference("district-city")
private City city;

@JsonManagedReference("district-region")
@JsonIgnoreProperties
@OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Region> regions = new HashSet<>();

@JsonIgnoreProperties
@JsonManagedReference("district-drugstore")
@OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Drugstore> drugstores = new HashSet<>();
</code>```

and the solution solved.

hope to help someone ...

Body:
I was trying to post an object with relationship to server.
But I got an error.

My entity:

@Entity
public class District implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(unique = true)
private String name;

@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference
@JsonUnwrapped
private City city;

@JsonManagedReference
@JsonIgnoreProperties
@OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Region> regions = new HashSet<>();

@JsonIgnoreProperties
@OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Drugstore> drugstores = new HashSet<>();

//getter and setters

Here is my controller:

@PostMapping("/admin/district")
ResponseEntity<?> create(@RequestBody District request) {
    service.create(request);
    return null;
}

Here is my error:

If I send null json, I get this error again.
Can anybody help?

Body:
after i try several minutes i found the solution.

If use @JsonBackReference in project more than twice, should
  distinguish them with a specific Reference name.

so i do like this:

@ManyToOne(fetch = FetchType.LAZY)
@JsonBackReference("district-city")
private City city;

@JsonManagedReference("district-region")
@JsonIgnoreProperties
@OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Region> regions = new HashSet<>();

@JsonIgnoreProperties
@JsonManagedReference("district-drugstore")
@OneToMany(mappedBy = "district", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Set<Drugstore> drugstores = new HashSet<>();

and the solution solved.

hope to help someone ...


问:
Calculate how many days have passed since user's input date
I am trying to let the user input a Date in a cell. Using the input date and today's date, I would calculate how many days have passed since the user's input date.

Example: User inputs "2/15/2019" in cell (C4) - The next day it shows "1 Day/s" and so on.

I've searched and tried many things but failed, I am no expert with excel or VBA by any means, so I am not even sure if that is possible.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    If Not Intersect(Target, Range("L:L")) Is Nothing Then
        With ActiveWorkbook.Worksheets("Ended")
            Application.EnableEvents = False
            Target = "Today()" - Target
            Application.EnableEvents = True
        End With
    End If
</code>```

This issue can be solved by this formula, however I can't apply it using VBA to user input date.

```<code>=TODAY()-DATEVALUE("15/2/2020")
</code>```

答:
I don't have enough reputation to comment yet, so I'll try to answer based on what you've said.

You were on the write track, just need to get it to enter a formula using Target.Formula.

I've often struggled with using dates in Excel formulas.  The easiest way is to use the numeric value of the date.  You can do this by converting the date to a Long using CLng().

Complete line of cod reads

```<code>Target.Formula = "=Today() - " & CLng(Target)
</code>```

As others have also mentioned, you are going to be writing back a number into a cell that will have a date format after the user enters the date.  For example, if I enter 01/02/2020 (dd/mm/yyyy is my local date format) into a cell, it will set Target to equal 16/02/2020 - 01/02/2020 which is 15 days, however the cell will have 15/01/1900 (computer dates start at 01/01/1900) unless you change the format of the cell to a number.  You can do this using

```<code>Target.NumberFormat = "0"
</code>```

Body:
I am trying to let the user input a Date in a cell. Using the input date and today's date, I would calculate how many days have passed since the user's input date.

Example: User inputs "2/15/2019" in cell (C4) - The next day it shows "1 Day/s" and so on.

I've searched and tried many things but failed, I am no expert with excel or VBA by any means, so I am not even sure if that is possible.

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next
    If Not Intersect(Target, Range("L:L")) Is Nothing Then
        With ActiveWorkbook.Worksheets("Ended")
            Application.EnableEvents = False
            Target = "Today()" - Target
            Application.EnableEvents = True
        End With
    End If

This issue can be solved by this formula, however I can't apply it using VBA to user input date.

=TODAY()-DATEVALUE("15/2/2020")

Body:
I don't have enough reputation to comment yet, so I'll try to answer based on what you've said.

You were on the write track, just need to get it to enter a formula using Target.Formula.

I've often struggled with using dates in Excel formulas.  The easiest way is to use the numeric value of the date.  You can do this by converting the date to a Long using CLng().

Complete line of cod reads

Target.Formula = "=Today() - " & CLng(Target)

As others have also mentioned, you are going to be writing back a number into a cell that will have a date format after the user enters the date.  For example, if I enter 01/02/2020 (dd/mm/yyyy is my local date format) into a cell, it will set Target to equal 16/02/2020 - 01/02/2020 which is 15 days, however the cell will have 15/01/1900 (computer dates start at 01/01/1900) unless you change the format of the cell to a number.  You can do this using

Target.NumberFormat = "0"


问:
Moving From ASP.Net 3.5 to 4.0 - System.Security.Permissions.FileIOPermission Exception
I'm sure this can't be too hard; but I'm struggling.  The error is

Exception Details:
  System.Security.SecurityException:
  Request for the permission of type
  'System.Security.Permissions.FileIOPermission,
  mscorlib, Version=4.0.0.0,
  Culture=neutral,
  PublicKeyToken=b77a5c561934e089'
  failed.

I'm trying to write to a text file on the server.  Before, I had to modify the web.config file set the trust level to full.  Then it all seemed to work.

I've since updated my site to use ASP.NET 4.0; and now I can't pull it off.  I'm really not doing much at all, just reading/writing a file.  But now I can't get past the error.  From what I've read, it sounds like 'Full' is the default setting in 4.0?

I have a (virtually) empty web.config.  I tried adding the trust level to explicitly set it to full but it didn't seem to help.

EDIT

I'm currently using File.AppendAllText  to write to the file and File.ReadAllText to read the contents.

And this is IIS7.

If it sounds like this isn't programming related, I can take it up with customer support for my host.  But, like I said, if I switch my site back to 3.5 it works great.  When I set it to 4.0 - I get this error.

答:
Here is a whitepaper on many of the breaking changes in ASP.NET 4.0
http://www.asp.net/learn/whitepapers/aspnet4/breaking-changes

It looks like the security model had a significant overhaul...but it looks like the short answer for my problem is to add:

```<code>   <trust level= "Full" legacyCasModel="true" />
</code>```

legacyCasModel should give you the old behavior from previous editions of ASP.NET.  This worked for me.

Body:
Here is a whitepaper on many of the breaking changes in ASP.NET 4.0
http://www.asp.net/learn/whitepapers/aspnet4/breaking-changes

It looks like the security model had a significant overhaul...but it looks like the short answer for my problem is to add:

   <trust level= "Full" legacyCasModel="true" />

legacyCasModel should give you the old behavior from previous editions of ASP.NET.  This worked for me.


问:
ERROR: Failed to resolve: android.support:support.v7:29.0.2
I am new to Android studio. I am facing a problem with the coding part. While running the code it shows an error.
Thw gradle part is shown below

```<code>apply plugin: 'com.android.application'
android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.fallprediction"
        minSdkVersion 14
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'android.support:support.v7:29.0.2'
}
</code>```

The error is
ERROR: Failed to resolve: android.support:support.v7:29.0.2
Show in Project Structure dialog
Affected Modules: app

Please help me to resolve this error

答: Convert this into androidx or remove this dependency   implementation 'android.support:support.v7:29.0.2</p>

Body:
I am new to Android studio. I am facing a problem with the coding part. While running the code it shows an error.
Thw gradle part is shown below

apply plugin: 'com.android.application'
android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.fallprediction"
        minSdkVersion 14
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'android.support:support.v7:29.0.2'
}

The error is
ERROR: Failed to resolve: android.support:support.v7:29.0.2
Show in Project Structure dialog
Affected Modules: app

Please help me to resolve this error


问:
I want to write some css for changing a toggle plus sign colour
I have a Wordpress theme I am trying to customise. I would like to change the colour of my toggle plus signs to white in CSS but I can't work it out. If anyone could help I'd really appreciate it.

This is the URL:
http://dev3.runforthehills.com/wp-admin/customize.php?return=%2Fwp-admin%2Fpost.php%3Fpost%3D74%26action%3Dedit

This is the CSS I tried to write:

```<code>.toggles .icon-plus-sign:before { color:#ffffff; !important;}
</code>```

Thank you.

答:
You should set background color for it:

```<code>.toggles .icon-plus-sign:before { background-color:#ffffff !important;}
</code>```

As you see below it changes nicely!

Edit: also Ihave set background color for ::after property.

Body:
I have a Wordpress theme I am trying to customise. I would like to change the colour of my toggle plus signs to white in CSS but I can't work it out. If anyone could help I'd really appreciate it.

This is the URL:
http://dev3.runforthehills.com/wp-admin/customize.php?return=%2Fwp-admin%2Fpost.php%3Fpost%3D74%26action%3Dedit

This is the CSS I tried to write:

.toggles .icon-plus-sign:before { color:#ffffff; !important;}

Thank you.

Body:
You should set background color for it:

.toggles .icon-plus-sign:before { background-color:#ffffff !important;}

As you see below it changes nicely!

Edit: also Ihave set background color for ::after property.


问:
Trail Renderer in Unity c# script
I have a simple project where I spawn multiple asteroids and they tend to gravitate over a planet. I wanted to add a simple trail to enhance the visual effects. It's very simple when I add the asteroid manually and then add component "trail renderer" and select desired material. But I can't work it out on how to add it to a script. This is my code for now:

```<code>using System.Collections;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(FauxGravityBody))]
public class Spawner : MonoBehaviour {

    public GameObject meteorPrefab;
    public float distance = 20f;
    public float time = 10f;
    private GameObject meteor;
    public TrailRenderer trail;
    void Start ()
    {
        StartCoroutine(SpawnMeteor());
    }

    IEnumerator SpawnMeteor()
    {
        Vector3 pos = Random.onUnitSphere * distance;
        meteor = Instantiate(meteorPrefab, pos, Quaternion.identity);
        meteor.AddComponent<FauxGravityBody>();
        meteor.AddComponent<DestroyMeteor>();
        meteor.AddComponent<SphereCollider>();
        meteor.AddComponent<TrailRenderer>();

        yield return new WaitForSeconds(time);

        StartCoroutine(SpawnMeteor());
    }

}
</code>```

Which indeed adds the trail to the spawned objects, but it's using the default pink trail. My desired trail material is located in folder "Assets/Effects/Trail.mat". How can I specify in the script that I want to use that specific material?

Kind regards.

答:
Note if you need these components -- TrailRenderer, SphereCollider etc. -- on all meteors, you can simply add them to the Prefab itself manually (by dragging them over it). Then they will already be there, right materials and all, once you Instantiate the main prefab.

You can then still adjust specific settings (or disable components) by using getting them via GetComponent<TrailRenderer>() etc. Good luck!

Title: Trail Renderer in Unity c# script

Body:
I have a simple project where I spawn multiple asteroids and they tend to gravitate over a planet. I wanted to add a simple trail to enhance the visual effects. It's very simple when I add the asteroid manually and then add component "trail renderer" and select desired material. But I can't work it out on how to add it to a script. This is my code for now:

using System.Collections;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(FauxGravityBody))]
public class Spawner : MonoBehaviour {

    public GameObject meteorPrefab;
    public float distance = 20f;
    public float time = 10f;
    private GameObject meteor;
    public TrailRenderer trail;
    void Start ()
    {
        StartCoroutine(SpawnMeteor());
    }

    IEnumerator SpawnMeteor()
    {
        Vector3 pos = Random.onUnitSphere * distance;
        meteor = Instantiate(meteorPrefab, pos, Quaternion.identity);
        meteor.AddComponent<FauxGravityBody>();
        meteor.AddComponent<DestroyMeteor>();
        meteor.AddComponent<SphereCollider>();
        meteor.AddComponent<TrailRenderer>();

        yield return new WaitForSeconds(time);

        StartCoroutine(SpawnMeteor());
    }

}

Which indeed adds the trail to the spawned objects, but it's using the default pink trail. My desired trail material is located in folder "Assets/Effects/Trail.mat". How can I specify in the script that I want to use that specific material?

Kind regards.


问:
Changing value in in all rows, but the highest
I have a table i R with aggregated monthly sales. One of the columns includes information on whether the customer is currently active or inactive. The problem I have is that once the customer is inactive, this affects all previous months, and all the values for that customer is inactive.

I want to highlight what month was the first inactive month, and change all previous months' status too active.

The table looks like this:

```<code>CustomerID   Month_Yr   TotalSales   Status
   5          05-2016      2         INACTIVE
   5          06-2016      5         INACTIVE
   5          07-2016      1         INACTIVE
   5          08-2016      2         INACTIVE
   6          05-2016      4         ACTIVE
   6          06-2016      1         ACTIVE
   6          07-2016      2         ACTIVE
</code>```

Any ideas of how to do this?

答:
Do the records end for a customer once the customer becomes Inactive? If so, then this would work.</p>

```<code>library(tidyverse)

df <- data.frame(id = c(5,5,5,5,6),
                 status = c("Inactive", "Inactive", "Inactive", "Inactive", "Active"),
                 stringsAsFactors = FALSE)

df %>% group_by(id) %>%
  mutate(status = if_else(row_number() != n(), "Active", status))
</code>```

Body:
I have a table i R with aggregated monthly sales. One of the columns includes information on whether the customer is currently active or inactive. The problem I have is that once the customer is inactive, this affects all previous months, and all the values for that customer is inactive.

I want to highlight what month was the first inactive month, and change all previous months' status too active.

The table looks like this:

CustomerID   Month_Yr   TotalSales   Status
   5          05-2016      2         INACTIVE
   5          06-2016      5         INACTIVE
   5          07-2016      1         INACTIVE
   5          08-2016      2         INACTIVE
   6          05-2016      4         ACTIVE
   6          06-2016      1         ACTIVE
   6          07-2016      2         ACTIVE

Any ideas of how to do this?

Body:
Do the records end for a customer once the customer becomes Inactive? If so, then this would work.

library(tidyverse)

df <- data.frame(id = c(5,5,5,5,6),
                 status = c("Inactive", "Inactive", "Inactive", "Inactive", "Active"),
                 stringsAsFactors = FALSE)

df %>% group_by(id) %>%
  mutate(status = if_else(row_number() != n(), "Active", status))


问:
How can I reconfigure my cluster's kubelets with kubeadm
I am currently trying to find a way to reconfigure the evicition thresholds of all of my clusters kubelets. The cluster has been initialized with kubeadm init and the worker nodes have been added with kubeadmin join.

Now kubeadm has correctly written the kubelet configuration to the kubelet-config-1.16 configmap in the kube-system namespace and I can see the settings there.

However, what I gather from the documentation, updating it in that configmap will not adjust it for the existing kubelets.

Could someone point me to the right resources?

Thank you!

答:
You can create a new ConfigMap from the old ConfigMap and modify it to have desired configuration for eviction threshold and then edit the node’s reference to point to the new ConfigMap with the following command:

```<code>kubectl edit node ${NODE_NAME}
</code>```

In your text editor, add the following YAML under spec:

```<code>configSource:
    configMap:
        name: CONFIG_MAP_NAME # replace CONFIG_MAP_NAME with the name of the ConfigMap
        namespace: kube-system
        kubeletConfigKey: kubelet
</code>```

This process is well documented here

Body:
You can create a new ConfigMap from the old ConfigMap and modify it to have desired configuration for eviction threshold and then edit the node’s reference to point to the new ConfigMap with the following command:

kubectl edit node ${NODE_NAME}

In your text editor, add the following YAML under spec:

configSource:
    configMap:
        name: CONFIG_MAP_NAME # replace CONFIG_MAP_NAME with the name of the ConfigMap
        namespace: kube-system
        kubeletConfigKey: kubelet

This process is well documented here


问:
gitlab CI docker stalls after 2min
gitlab CI docker stalls after 2min

slight code change and same bug across different repos. Ci/CD used to work on these repos?

```<code>...
Step 4/11 : RUN yarn install
  ---> Using cache
  ---> c75197e0dbaa
 Step 5/11 : COPY babel.config.js babel.config.js
  ---> Using cache
  ---> 482b1ff64322
 Step 6/11 : COPY src src
  ---> d530de056b88
 Step 7/11 : RUN mkdir locales
  ---> Running in f7885ea9a3c3
 ...
</code>```

Link to the GL issue
https://gitlab.com/gitlab-com/support-forum/issues/5202

答:
This is a known issue on gitlab. Change dind service as follows. That should fix your problem.</p>

```<code>services:
    - docker:19.03.5-dind
</code>```

Title: gitlab CI docker stalls after 2min

Body:
gitlab CI docker stalls after 2min

slight code change and same bug across different repos. Ci/CD used to work on these repos?

...
Step 4/11 : RUN yarn install
  ---> Using cache
  ---> c75197e0dbaa
 Step 5/11 : COPY babel.config.js babel.config.js
  ---> Using cache
  ---> 482b1ff64322
 Step 6/11 : COPY src src
  ---> d530de056b88
 Step 7/11 : RUN mkdir locales
  ---> Running in f7885ea9a3c3
 ...

Link to the GL issue
https://gitlab.com/gitlab-com/support-forum/issues/5202

Body:
This is a known issue on gitlab. Change dind service as follows. That should fix your problem.

services:
    - docker:19.03.5-dind


问:
Count and summation of positive and negative number sequences
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
</code>```

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))
</code>```

result

```<code>        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046
</code>```

Body:
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

python

x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}

python

sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))

result

        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046

Body:
Here is a simple tidyverse solution...

library(tidyverse) #or just dplyr and tidyr

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

df <- tibble(x = x) %>%
  mutate(seqno = cumsum(c(1, diff(sign(x)) != 0))) %>% #identify sequence ids
  group_by(seqno) %>%                                  #group by sequences
  mutate(n_of_sequence = row_number(),                 #count row numbers for each group
         sum = cumsum(x)) %>%                          #cumulative sum for each group
  ungroup() %>%
  select(-seqno)                                       #remove sequence id

df
# A tibble: 20 x 3
        x n_of_sequence     sum
    <dbl>         <int>   <dbl>
 1 -0.01              1 -0.01
 2  0.003             1  0.003
 3 -0.002             1 -0.002
 4  0.018             1  0.018
 5  0.002             2  0.0200
 6  0.006             3  0.026
 7 -0.012             1 -0.012
 8  0.014             1  0.014
 9 -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.01              1  0.01
19 -0.018             1 -0.018
20  0.046             1  0.046


问:
JavaScript call default value of class
I'm tyring to give a default value to a JavaScript Class.

i.e.

```<code>class tr{
    constructor(value=null){
        this.type = typeof value;
        this.val = value;
        this.start = new Date();
    }
}
</code>```

Now, if I want to get value I should use something like that:

```<code>let trVar = new tr;
console.log(trVar.val);
</code>```

But I want to call value as default when I call just trVar itself.
I mean:

```<code>console.log(trVar);
</code>```

This should be value.

I don't want to remove type and start.

Thanks.

答:
Note:

I am not sure why you'd want to do that but, let trVar = new tr trVal here is the reference to the instance of tr.

Perhaps:

What you are trying to do is get the val field when you instantiate the tr class. Unfortunately the new keyword creates a new instance of which it's reference is stored  in trVar... So to only get the value out of the instance you could perhaps do this:
let trVar = (new tr).val;.

Title: JavaScript call default value of class

Body:
I'm tyring to give a default value to a JavaScript Class.

i.e.

class tr{
    constructor(value=null){
        this.type = typeof value;
        this.val = value;
        this.start = new Date();
    }
}

Now, if I want to get value I should use something like that:

let trVar = new tr;
console.log(trVar.val);

But I want to call value as default when I call just trVar itself.
I mean:

console.log(trVar);

This should be value.

I don't want to remove type and start.

Thanks.


问:
Sending automatic email on specific day of the month based on day entered in a cell
I am trying to send an email from Google Apps Script on a specific day of the month based on the day that a user enters into a cell on the Sheet.

Currently I use a formula as below to send emails which sends to users based on cell values:

```<code>function sendChangeDetailsEmail() {
  var sh = SpreadsheetApp.getActive().getSheetByName("BALANCE SHEET");
  var data1 = sh.getRange("G2").getValues(); //USED AS DATA IN THE EMAIL BODY from values in the sheet
  var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BALANCE SHEET").getRange("G2");
  var emailRange1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BALANCE SHEET").getRange("G1");
  var emailAddress = emailRange.getValues();
  var recipient = emailRange1.getValues();
  var message = 'Hello ' + recipient + "\r\r" + 'Please see the current amount that needs paying off: ' + data1 + "\r\r" + 'Many Thanks';
  var subject = 'REMINDER - Amount Due';
    MailApp.sendEmail(emailAddress, subject, message);
}
</code>```

As the sheet will be used as a separate doc for each user, the user would enter the date in cell M3 on configuration for when they want the reminder to be sent, and they would only enter the date number of the month e.g. 25

Does anyone know of a way that I could do this please?

答:
I have now got a script as below:

function sendEmail() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName('Sheet1');
  var rng = sh.getDataRange();
  var val = rng.getDisplayValues();
  var lr = rng.getLastRow();
  var compare = sh.getRange('A9').getValue();
  var match = false;
  var body = "Hello, "+"\n\n"+"Please remember the below:";
  for (var i = 1; i < lr; i++) {
    if (val[i][2] == compare) {
      var bodyVal = val[i][0];
      body = body+"\n - "+bodyVal;
      match = true;
      Logger.log(body);
    }
  }
  if(match) {
    MailApp.sendEmail({
      to: "mail@example.com",
      subject: "Reminder",
      body: body
    });
  }
}
```

I hope this helps someone who may be looking for the same thing :)

Body:
I am trying to send an email from Google Apps Script on a specific day of the month based on the day that a user enters into a cell on the Sheet.

Currently I use a formula as below to send emails which sends to users based on cell values:

function sendChangeDetailsEmail() {
  var sh = SpreadsheetApp.getActive().getSheetByName("BALANCE SHEET");
  var data1 = sh.getRange("G2").getValues(); //USED AS DATA IN THE EMAIL BODY from values in the sheet
  var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BALANCE SHEET").getRange("G2");
  var emailRange1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BALANCE SHEET").getRange("G1");
  var emailAddress = emailRange.getValues();
  var recipient = emailRange1.getValues();
  var message = 'Hello ' + recipient + "\r\r" + 'Please see the current amount that needs paying off: ' + data1 + "\r\r" + 'Many Thanks';
  var subject = 'REMINDER - Amount Due';
    MailApp.sendEmail(emailAddress, subject, message);
}

As the sheet will be used as a separate doc for each user, the user would enter the date in cell M3 on configuration for when they want the reminder to be sent, and they would only enter the date number of the month e.g. 25

Does anyone know of a way that I could do this please?

Body:
I have now got a script as below:

function sendEmail() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName('Sheet1');
  var rng = sh.getDataRange();
  var val = rng.getDisplayValues();
  var lr = rng.getLastRow();
  var compare = sh.getRange('A9').getValue();
  var match = false;
  var body = "Hello, "+"\n\n"+"Please remember the below:";
  for (var i = 1; i < lr; i++) {
    if (val[i][2] == compare) {
      var bodyVal = val[i][0];
      body = body+"\n - "+bodyVal;
      match = true;
      Logger.log(body);
    }
  }
  if(match) {
    MailApp.sendEmail({
      to: "mail@example.com",
      subject: "Reminder",
      body: body
    });
  }
}

I hope this helps someone who may be looking for the same thing :)


问:
Regex to validate a twitter url
I'm using the jQuery validation engine to parse my form data:
https://github.com/posabsolute/jQuery-Validation-Engine

What would be the regex to validate a twitter URL (including the http://twitter.com part) Eg:

```<code>http://twitter.com/barackobama
or
http://twitter.com/#!/barackobama
</code>```

Title: Regex to validate a twitter url

Body:
I'm using the jQuery validation engine to parse my form data:
https://github.com/posabsolute/jQuery-Validation-Engine

What would be the regex to validate a twitter URL (including the http://twitter.com part) Eg:

http://twitter.com/barackobama
or
http://twitter.com/#!/barackobama

Body:
You mean

/http(?:s)?:\/\/(?:www\.)?twitter\.com\/([a-zA-Z0-9_]+)/


问:
Reference workbook by path and name error: Subscript out of range
I get the "Subscript out of range" error from the line below:

```<code>Set WBset =  Workbooks("FilePath\PK18 - Unformatted.xls").Worksheets("PK18 - Unformatted")
</code>```

I checked the sheet name and the filename and they are correct. The sheet exists.

答: wrong workbook name, should be the name not the path</p>

Body:
I get the "Subscript out of range" error from the line below:

Set WBset =  Workbooks("FilePath\PK18 - Unformatted.xls").Worksheets("PK18 - Unformatted")

I checked the sheet name and the filename and they are correct. The sheet exists.


问:
How can I create a URL based on controller and action method in Spring MVC?
I am using Spring MVC 3.0

I have a guestbook.jsp page where I want to create a link that points to GuestBookController's login method.

This is a simple task that most web frameworks handle this (e.g grails does it with g:link tag) but I couldn't find any documentation on this in the official SpringMVC docs.

So I am scratching my head - Is this functionality in some tag library? Does the framework expose it? Do I have to extend the framework to get this to work?

Note, I am not taking about hardcoding the url (which is an obvious but weak solution) but rather generating it based on controller and action name.

UPDATE:
Spring MVC doesn't provide this functionality. There is a JIRA ticket though. You can vote here https://jira.springsource.org/browse/SPR-5779

答:
The short answer is no, you can't do this with Spring MVC currently.

It's a shame because you can do this in other frameworks including Grails (which uses Spring MVC under the hood).

See the discussion here which includes a link to a Spring feature request to add this (vote for it!)


问:
Abort insert if the insert date is same day as another row with same id
I'm new to postgresql and dont know what the best way to do this would be.

I have a table with conserts, all conserts have an band id(INTEGER) and a start date(TIMESTAMP).

I want to make sure to only be able to insert a new consert with same band id as other conserts if the time between them is > 24 hours.

Shorter: A band should only be able to play in a consert every 24 hours.

Is it best to create some kinda trigger for this? I also read some about rules for postgresql.

Conserts table

Thank you for help!

答:
If by "24 hours" you mean "calendar date", then you simply need a unique constraint:

```<code>alter table concerts add constraint unq_concerts_bands
    unique (bandid, startdate);
</code>```

If the startdate is a timestamp, you can use a unique index:

```<code>create unique index unq_concerts_bands on concerts(bandid, date_trunc('date', startdate));
</code>```

Body:
If by "24 hours" you mean "calendar date", then you simply need a unique constraint:

alter table concerts add constraint unq_concerts_bands
    unique (bandid, startdate);

If the startdate is a timestamp, you can use a unique index:

create unique index unq_concerts_bands on concerts(bandid, date_trunc('date', startdate));


答:
What you are asking for is an anti pattern to OOP.

When you chose that OOP route, you should use it as intended.

If you'd like to turn an object instance into a single variable simply bind a variable to point to that value you want. or, don't use OOP.

you could create a function that returns only what you want and store whatever you dont want inside it. that would work better for you I guess.

Title: JavaScript call default value of class


问:
Difference between Primitive and non-primitive datatypes in JavaScript
I am not able to understand exactly what is difference between primitive  and non primitive data types in JavaScript even it is declared using same name i.e var.</p>

答:
The latest ECMAScript standard defines eight data types:

String

Boolean

Number

BigInt

Null

Undefined

Symbol

Object

Note :- Arrays do not belong to this list because they are objects as well. This is a common confusion among developers who assume that arrays are a special data type in Javascript.

Now bifurcate the data type

There are two types of data types in JavaScript:

Primitive values (String, Boolean, Number, BigInt, Null, Undefined, Symbol )

Non-primitive values is also called object references (Object,Array)


问:
Search for part of the word in the phrase with full text search in SQL Server 2016
In the Microsoft SQL Server, our searches are limited to starting words when we use a full-text search to search for values. That is, we cannot search contains the word looks like the LIKE operator in the middle.

I try to execute this query but the result is not my opinion.

I want to search for the middle of the term. For example, if my term is "Microsoft" and my query is :

```<code>SELECT *
FROM dbo.SMS_Outbox
WHERE CONTAINS(MessageText, N'"*soft*"')
</code>```

There is no result returned!

答:
The documentation is quite clear that wildcards are allowed only at the end of search terms:

The CONTAINS predicate supports the use of the asterisk (*) as a wildcard character to represent words and phrases. You can add the asterisk only at the end of the word or phrase. The presence of the asterisk enables the prefix-matching mode. In this mode, matches are returned if the column contains the specified search word followed by zero or more other characters.

You cannot do what you want easily.  One simple option is to switch to LIKE and take the performance hit:

```<code>WHERE MessageText LIKE N'%soft%'
</code>```

Another option might be to parse your text in such a way that soft is always at the beginning of a search term.

Body:
In the Microsoft SQL Server, our searches are limited to starting words when we use a full-text search to search for values. That is, we cannot search contains the word looks like the LIKE operator in the middle.

I try to execute this query but the result is not my opinion.

I want to search for the middle of the term. For example, if my term is "Microsoft" and my query is :

SELECT *
FROM dbo.SMS_Outbox
WHERE CONTAINS(MessageText, N'"*soft*"')

There is no result returned!

Body:
The documentation is quite clear that wildcards are allowed only at the end of search terms:

The CONTAINS predicate supports the use of the asterisk (*) as a wildcard character to represent words and phrases. You can add the asterisk only at the end of the word or phrase. The presence of the asterisk enables the prefix-matching mode. In this mode, matches are returned if the column contains the specified search word followed by zero or more other characters.

You cannot do what you want easily.  One simple option is to switch to LIKE and take the performance hit:

WHERE MessageText LIKE N'%soft%'

Another option might be to parse your text in such a way that soft is always at the beginning of a search term.