问:
Auto-increment a value in Firebase
How do I auto increment a value stored in Firebase from an Android client?

Currently: I declare int id = 1. When I increment, I see the values 2, 3 etc. being stored. That's fine, but when I re-run the project, id is set equal to 1 again.

I want it to behave like a static variable, so I can create an id which will go from 1 to infinity without resetting.

UPDATED FAILED

I used the following to pass the Firebase reference and a string to the function incrementCounter.

```<code>if(language_chosen.equalsIgnoreCase("english"))
 {
   Firebase publRef = f.child("Language").child("English").child("Message");
   Firebase newPublRef = publRef.push();
   writeMsgActivity demo = new writeMsgActivity();
   demo.incrementCounter(newPublRef,the_msg_enter);
  }
</code>```

Now I try to use the passed reference and string at   public void incrementCounter(Firebase publref,String my_msg) in the oncomplete method but it gives me an error.

```<code>   public void incrementCounter(Firebase publref,String my_msg) {
    publref.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(final MutableData currentData) {
            if (currentData.getValue() == null) {
                currentData.setValue(1);
            } else {
                currentData.setValue((Long) currentData.getValue() + 1);
            }

            return Transaction.success(currentData);
        }

        public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
            if (firebaseError != null) {
                System.out.println("Firebase counter increment failed.");
            } else {
                System.out.println("Firebase counter increment succeeded.");

                Map<String, Object> publ = new HashMap<String, Object>();
                publ.put("pubMsg", my_msg);
                publ.put("id",currentData);
                publref.setValue(publ);
            }
        }
    });
}
</code>```

UPDATED SOLVED

```<code>                final Firebase upvoteref = new Firebase("https://shareurday.firebaseio.com/Message/"+msg_id+"/upvotes");

            upvoteref.runTransaction(new Transaction.Handler() {
                @Override
                public Transaction.Result doTransaction(final MutableData currentData) {
                    if (currentData.getValue() == null) {
                        currentData.setValue(1);
                    } else {
                        currentData.setValue((Long) currentData.getValue() + 1);
                    }
                    return Transaction.success(currentData);
                }

                public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
                    if (firebaseError != null) {
                        System.out.println("Firebase counter increment failed.");
                    } else {
                        System.out.println("Firebase counter increment succeeded.");
                    }
                }
            });
</code>```

The variable msg_id is the random generated id from push.

答:
A new feature is added to firestore to autoincrement values. As simple as

```<code>document("fitness_teams/Team_1").
  updateData(["step_counter" : FieldValue.increment(500)])
</code>```

refer link:
https://firebase.googleblog.com/2019/03/increment-server-side-cloud-firestore.html

Used below code in my project.

```<code>var firestore = Firestore.instance;
firestore.collection('student').document('attendance').updateData({'total_attendace': FieldValue.increment(1)});
</code>```

Title: Auto-increment a value in Firebase

Body:
How do I auto increment a value stored in Firebase from an Android client?

Currently: I declare int id = 1. When I increment, I see the values 2, 3 etc. being stored. That's fine, but when I re-run the project, id is set equal to 1 again.

I want it to behave like a static variable, so I can create an id which will go from 1 to infinity without resetting.

UPDATED FAILED

I used the following to pass the Firebase reference and a string to the function incrementCounter.

if(language_chosen.equalsIgnoreCase("english"))
 {
   Firebase publRef = f.child("Language").child("English").child("Message");
   Firebase newPublRef = publRef.push();
   writeMsgActivity demo = new writeMsgActivity();
   demo.incrementCounter(newPublRef,the_msg_enter);
  }

Now I try to use the passed reference and string at   public void incrementCounter(Firebase publref,String my_msg) in the oncomplete method but it gives me an error.

   public void incrementCounter(Firebase publref,String my_msg) {
    publref.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(final MutableData currentData) {
            if (currentData.getValue() == null) {
                currentData.setValue(1);
            } else {
                currentData.setValue((Long) currentData.getValue() + 1);
            }

            return Transaction.success(currentData);
        }

        public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
            if (firebaseError != null) {
                System.out.println("Firebase counter increment failed.");
            } else {
                System.out.println("Firebase counter increment succeeded.");

                Map<String, Object> publ = new HashMap<String, Object>();
                publ.put("pubMsg", my_msg);
                publ.put("id",currentData);
                publref.setValue(publ);
            }
        }
    });
}

UPDATED SOLVED

                final Firebase upvoteref = new Firebase("https://shareurday.firebaseio.com/Message/"+msg_id+"/upvotes");

            upvoteref.runTransaction(new Transaction.Handler() {
                @Override
                public Transaction.Result doTransaction(final MutableData currentData) {
                    if (currentData.getValue() == null) {
                        currentData.setValue(1);
                    } else {
                        currentData.setValue((Long) currentData.getValue() + 1);
                    }
                    return Transaction.success(currentData);
                }

                public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
                    if (firebaseError != null) {
                        System.out.println("Firebase counter increment failed.");
                    } else {
                        System.out.println("Firebase counter increment succeeded.");
                    }
                }
            });

The variable msg_id is the random generated id from push.

Body:
A new feature is added to firestore to autoincrement values. As simple as

document("fitness_teams/Team_1").
  updateData(["step_counter" : FieldValue.increment(500)])

refer link:
https://firebase.googleblog.com/2019/03/increment-server-side-cloud-firestore.html

Used below code in my project.

var firestore = Firestore.instance;
firestore.collection('student').document('attendance').updateData({'total_attendace': FieldValue.increment(1)});


来源: stackexchange

问:
i want to get all dates exclude weekends between two dates in python
I want to get all the dates between two dates excluding weekends dates.
Below is the format of dates:</p>

```<code>last_date = '2019-01-21'
curr_date = '2019-02-04'
</code>```

答:
You can do this quite nicely with the dateutil library's rrule.

Example:

from dateutil.parser import parse
from dateutil.rrule import rrule, DAILY, MO, TU, WE, TH, FR

last_date = '2019-01-21'
curr_date = '2019-02-04'

result = rrule(
  DAILY,
  byweekday=(MO,TU,WE,TH,FR),
  dtstart=parse(last_date),
  until=parse(curr_date)
)
print(list(result))
```

<p>Result: </p>

```[datetime.datetime(2019, 1, 21, 0, 0),
 datetime.datetime(2019, 1, 22, 0, 0),
 datetime.datetime(2019, 1, 23, 0, 0),
 datetime.datetime(2019, 1, 24, 0, 0),
 datetime.datetime(2019, 1, 25, 0, 0),
 datetime.datetime(2019, 1, 28, 0, 0),
 datetime.datetime(2019, 1, 29, 0, 0),
 datetime.datetime(2019, 1, 30, 0, 0),
 datetime.datetime(2019, 1, 31, 0, 0),
 datetime.datetime(2019, 2, 1, 0, 0),
 datetime.datetime(2019, 2, 4, 0, 0)]
```

ContentLicense: CC BY-SA 4.0

Body:
I want to get all the dates between two dates excluding weekends dates.
Below is the format of dates:

last_date = '2019-01-21'
curr_date = '2019-02-04'

Body:
You can do this quite nicely with the dateutil library's rrule.

Example:

from dateutil.parser import parse
from dateutil.rrule import rrule, DAILY, MO, TU, WE, TH, FR

last_date = '2019-01-21'
curr_date = '2019-02-04'

result = rrule(
  DAILY,
  byweekday=(MO,TU,WE,TH,FR),
  dtstart=parse(last_date),
  until=parse(curr_date)
)
print(list(result))

Result:

[datetime.datetime(2019, 1, 21, 0, 0),
 datetime.datetime(2019, 1, 22, 0, 0),
 datetime.datetime(2019, 1, 23, 0, 0),
 datetime.datetime(2019, 1, 24, 0, 0),
 datetime.datetime(2019, 1, 25, 0, 0),
 datetime.datetime(2019, 1, 28, 0, 0),
 datetime.datetime(2019, 1, 29, 0, 0),
 datetime.datetime(2019, 1, 30, 0, 0),
 datetime.datetime(2019, 1, 31, 0, 0),
 datetime.datetime(2019, 2, 1, 0, 0),
 datetime.datetime(2019, 2, 4, 0, 0)]


问:
Beautifulsoup4, BS4, Python Parsing Question
I am parsing a webpage using bs4.  There are more then one data type I would like to select, with the same class name.

My parsing code:

```<code>rows_ranking = soup_ranking.select('#current-poll tbody tr .left')
</code>```

The page I want to parse has two different ".left" identifiers in the table rows.  How can I choose which one I would like.  Here is an exmample of two of these table rows (one I would like my program to parse, the other I would like to ignore)

1 - Baylor

2 - Big 12

As you can see they have the same class identifier.  Is there a way I can have bs4 look only for the first of the two?

I hope my question makes sense, thanks in advance!

答:
You have a couple of options:

You can use soup.find_all and loop through your results.

Use the css selector for first.

Inspect and copy the selector for that element.

Body:
I am parsing a webpage using bs4.  There are more then one data type I would like to select, with the same class name.

My parsing code:

rows_ranking = soup_ranking.select('#current-poll tbody tr .left')

The page I want to parse has two different ".left" identifiers in the table rows.  How can I choose which one I would like.  Here is an exmample of two of these table rows (one I would like my program to parse, the other I would like to ignore)

1 - Baylor

2 - Big 12

As you can see they have the same class identifier.  Is there a way I can have bs4 look only for the first of the two?

I hope my question makes sense, thanks in advance!


问:
HTML/CSS Button Hover shifting everything else away?
If I hover over my buttons they shift(?) other elements.

as you can see I already tried to compensate the +4 pixels from the border by subtracting them from the height and the width but the problem remains.

I don't want this. I want it to change appearance without any shifting.

Here a video to visualize my problem

Thank you in advance :)

Here the CSS and HTML

HTML:

```<code><body>
  <nav>
    <img class="logo" src="images/logo-bookmark.svg" alt="Logo nav">
    <div class="navElements">
      <a href="#" class="nav-links">Features</a>
      <a href="#" class="nav-links">Pricing</a>
      <a href="#" class="nav-links">Contact</a>
      <a href="#" class="nav-logo-btn">Login</a>
    </div>
  </nav>

  <section class="header">
    <div class="header-left">
      <h1 class="header-heading">A Simple Bookmark Manager</h1>
      <p class="header-text"> A clean and simple interface to organize your favourite websites. Open a new
        browser tab and see your sites load instantly. Try it for free.</p>
      <a href="#" class="btn-1">Get it on Chrome</a>
      <a href="#" class="btn-2">Get it on Firefox</a>
    </div>
    <img class="header-img" src="images\illustration-hero.svg" alt="Hero image">
</code>```

Login Button:

```<code>.nav-logo-btn {
  text-decoration: none;
  color: white;
  background-color: var(--SoftRed);
  padding: 10px 32px;
  border-radius: 5px;
  text-transform: uppercase;
  font-weight: 500;
  font-family: "Rubik";
  font-size: 12px;
  letter-spacing: 2px;
}

.nav-logo-btn:hover {
  color: var(--SoftRed);
  background-color: white;
  border: solid 2px;
  padding: 8px 30px;
  transition: all 0.3s;
}
</code>```

Chrome/Firefox Buttons:

```<code>.btn-1, .btn-2 {
  display: inline-block;
  text-decoration: none;
  border-radius: 5px;
  text-align: center;
  line-height: 48px;
  height: 48px;
  width: 165px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
  position: relative;
}

.btn-1:hover, .btn-2:hover {
  background-color: white;
  border: solid 2px;
  height: 44px;
  width: 161px;
}

.btn-1 {
  background-color: var(--SoftBlue);
  color: white;

}

.btn-2 {
  background-color: #f7f7f7;
  color: #606068;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.1);
  left: 50px;
}

.btn-1:hover {
  color: var(--SoftBlue);
}

.btn-2:hover {
  color: #606068;
}

</code>```

答:
Another easy option is to simply change the color of the border on hover instead of adding a border that doesn't exist most of the time.

Consider:

.button {
  display:block;
  float: left;
  margin: 20px;
  background: #dadada;
  padding: 10px 15px;
  border-radius: 5px;
  font-size: 12px;
  font-family: Helvetica, Arial, Sans-Serif;
  cursor:pointer;
  transition: all 0.25s ease;
  box-sizing: border-box;
}

.jumpy:hover {
  border: 4px solid blue;
}

.smooth {
  border: 4px solid transparent;
}

.smooth:hover {
  border-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="button jumpy">Jumpy Button</div>
<div class="button smooth">Smooth Button</div></code>```

Body:
If I hover over my buttons they shift(?) other elements.

as you can see I already tried to compensate the +4 pixels from the border by subtracting them from the height and the width but the problem remains.

I don't want this. I want it to change appearance without any shifting.

Here a video to visualize my problem

Thank you in advance :)

Here the CSS and HTML

HTML:

      Features
      Pricing
      Contact
      Login

A Simple Bookmark Manager

 A clean and simple interface to organize your favourite websites. Open a new
        browser tab and see your sites load instantly. Try it for free.

      Get it on Chrome
      Get it on Firefox

Login Button:

.nav-logo-btn {
  text-decoration: none;
  color: white;
  background-color: var(--SoftRed);
  padding: 10px 32px;
  border-radius: 5px;
  text-transform: uppercase;
  font-weight: 500;
  font-family: "Rubik";
  font-size: 12px;
  letter-spacing: 2px;
}

.nav-logo-btn:hover {
  color: var(--SoftRed);
  background-color: white;
  border: solid 2px;
  padding: 8px 30px;
  transition: all 0.3s;
}

Chrome/Firefox Buttons:

.btn-1, .btn-2 {
  display: inline-block;
  text-decoration: none;
  border-radius: 5px;
  text-align: center;
  line-height: 48px;
  height: 48px;
  width: 165px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
  position: relative;
}

.btn-1:hover, .btn-2:hover {
  background-color: white;
  border: solid 2px;
  height: 44px;
  width: 161px;
}

.btn-1 {
  background-color: var(--SoftBlue);
  color: white;

}

.btn-2 {
  background-color: #f7f7f7;
  color: #606068;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.1);
  left: 50px;
}

.btn-1:hover {
  color: var(--SoftBlue);
}

.btn-2:hover {
  color: #606068;
}

Body:
Another easy option is to simply change the color of the border on hover instead of adding a border that doesn't exist most of the time.

Consider:

.button {
  display:block;
  float: left;
  margin: 20px;
  background: #dadada;
  padding: 10px 15px;
  border-radius: 5px;
  font-size: 12px;
  font-family: Helvetica, Arial, Sans-Serif;
  cursor:pointer;
  transition: all 0.25s ease;
  box-sizing: border-box;
}

.jumpy:hover {
  border: 4px solid blue;
}

.smooth {
  border: 4px solid transparent;
}

.smooth:hover {
  border-color: blue;
}

<div class="button jumpy">Jumpy Button</div>
<div class="button smooth">Smooth Button</div>


问:
Rails 3: Show validation errors for simple_form with ajax
I am using rails3 with simple_form gem and :remote=>true (ajax).

How to I show validation error with :remote=>true?

Thanks

答:
Use the javascript rails callbacks to do this.

See how do this here: http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/

ContentLicense: CC BY-SA 3.0


问:
How to send 'Headers' in websocket python
how can i make this

This is my code

```<code>
import  websockets

async def test():
    async with websockets.connect('ws://iqoption.com') as websocket:
        response = await websocket.recv()
        print(response)
# Client async code
</code>```

The cuestion is , can i send this headers to get Authenticated in the server

Headers

```<code>    'Host':'iqoption.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0',
    'Accept' : '*/*',
'Accept-Encoding': 'gzip, deflate',
'Sec-WebSocket-Version' : '13',
'Origin' : 'https://iqoption.com',
    'Sec-WebSocket-Key': 'iExBWv1j6sC1uee2qD+QPQ==',
'Connection' : 'keep-alive, Upgrade',
'Upgrade': 'websocket'}
</code>```

I could do it with this other code but the messages were still encrypted with tls

```<code>proxies = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}
urllib3.disable_warnings()

r = requests.get('https://iqoption.com/echo/websocket', stream=True,headers = Headers, proxies=proxies, verify=False)
#r = requests.get('https://iqoption.com/echo/websocket', stream=True,headers = Headers)
s = socket.fromfd(r.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM)

def receive_and_print():
    #for message in iter(lambda: s.recv(1024).decode("utf-8", errors="replace"), ''):
    for message in iter(lambda: s.recv(1024).decode( errors="replace"), ''):
        print(":", message)
        print("")
import threading
background_thread = threading.Thread(target=receive_and_print)
background_thread.daemon = True
background_thread.start()

while 1:
    s.send(input("Please enter your message: ").encode())
    print("Sent")
    print("")
</code>```

Any advice??

答:
I think you are currently missing a basic understanding of WebSockets as is shown on your previous experiments. WebSockets are not plain sockets. WebSockets are some socket-like think created after a HTTP handshake. You cannot just take the socket from the connection as you've tried after requests but you have to explicitly speak the WebSocket application protocol, defined in RFC 6455.

That said, using a library like websockets is much better. But you still have to use the actual WebSocket endpoint as target and not just some arbitrary URL on the same server. The endpoint in this case is not
ws://iqoption.com but  wss://iqoption.com/echo/websocket, i.e. a longer path and wss:// instead of ws://.

Without the proper URL you get error messages you seem to interpret as authentication problems. But there is no authentication involved here at all. Once you use the proper endpoint it simply works without any need to send specific headers:

```<code>async def test():
    async with websockets.connect("wss://iqoption.com/echo/websocket") as websocket:
        response = await websocket.recv()
        print(response)
</code>```

Body:
how can i make this

This is my code

import  websockets

async def test():
    async with websockets.connect('ws://iqoption.com') as websocket:
        response = await websocket.recv()
        print(response)
# Client async code

The cuestion is , can i send this headers to get Authenticated in the server

Headers

    'Host':'iqoption.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0',
    'Accept' : '*/*',
'Accept-Encoding': 'gzip, deflate',
'Sec-WebSocket-Version' : '13',
'Origin' : 'https://iqoption.com',
    'Sec-WebSocket-Key': 'iExBWv1j6sC1uee2qD+QPQ==',
'Connection' : 'keep-alive, Upgrade',
'Upgrade': 'websocket'}

I could do it with this other code but the messages were still encrypted with tls

proxies = {"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"}
urllib3.disable_warnings()

r = requests.get('https://iqoption.com/echo/websocket', stream=True,headers = Headers, proxies=proxies, verify=False)
#r = requests.get('https://iqoption.com/echo/websocket', stream=True,headers = Headers)
s = socket.fromfd(r.raw.fileno(), socket.AF_INET, socket.SOCK_STREAM)

def receive_and_print():
    #for message in iter(lambda: s.recv(1024).decode("utf-8", errors="replace"), ''):
    for message in iter(lambda: s.recv(1024).decode( errors="replace"), ''):
        print(":", message)
        print("")
import threading
background_thread = threading.Thread(target=receive_and_print)
background_thread.daemon = True
background_thread.start()

while 1:
    s.send(input("Please enter your message: ").encode())
    print("Sent")
    print("")

Any advice??

Body:
I think you are currently missing a basic understanding of WebSockets as is shown on your previous experiments. WebSockets are not plain sockets. WebSockets are some socket-like think created after a HTTP handshake. You cannot just take the socket from the connection as you've tried after requests but you have to explicitly speak the WebSocket application protocol, defined in RFC 6455.

That said, using a library like websockets is much better. But you still have to use the actual WebSocket endpoint as target and not just some arbitrary URL on the same server. The endpoint in this case is not
ws://iqoption.com but  wss://iqoption.com/echo/websocket, i.e. a longer path and wss:// instead of ws://.

Without the proper URL you get error messages you seem to interpret as authentication problems. But there is no authentication involved here at all. Once you use the proper endpoint it simply works without any need to send specific headers:

async def test():
    async with websockets.connect("wss://iqoption.com/echo/websocket") as websocket:
        response = await websocket.recv()
        print(response)


问:
I can't enable slick slider autoplay
I am trying to setup a blog for a friend and it has prebuild slick slider.
I am really not good with Html and Javascript and i was trying to setup autoplay for the slider alla fternoon.

Where should i add a class? How should i setup javascript? I really dont know what i should do in order autoplay to be enabled. It is default false. Please explain to me

Slick classes defined are :

```<code>
/* slicknav */
/*
Mobile Menu Core Style
*/
.slicknav_btn { position: relative; display: block; vertical-align: middle; float: left; padding: 0.438em 0.625em 0.438em 0.625em; line-height: 1.125em; cursor: pointer; }
.slicknav_menu  .slicknav_menutxt { display: block; line-height: 1.188em; float: left; }
.slicknav_menu .slicknav_icon { float: left; padding:3px;}
.slicknav_menu .slicknav_no-text { margin: 0 }
.slicknav_menu .slicknav_icon-bar { display: block; width: 1.125em; height: 0.125em; -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); }
.slicknav_btn .slicknav_icon-bar + .slicknav_icon-bar { margin-top: 0.188em }
.slicknav_nav { clear: both }
.slicknav_nav ul,
.slicknav_nav li { display: block ;line-height: 20px;}
.slicknav_nav .slicknav_arrow { font-size: 0.8em; margin: 0 0 0 0.4em; }
.slicknav_nav .slicknav_item { cursor: pointer; }
.slicknav_nav .slicknav_row { display: block; }
.slicknav_nav a { display: block }
.slicknav_nav .slicknav_item a,
.slicknav_nav .slicknav_parent-link a { display: inline }
.slicknav_menu:before,
.slicknav_menu:after { content: " "; display: table; }
.slicknav_menu:after { clear: both }
/* IE6/7 support */
.slicknav_menu { *zoom: 1 }
/*
User Default Style
Change the following styles to modify the appearance of the menu.
*/
.slicknav_menu {
font-size:16px;
}
/* Button */
.slicknav_btn {
margin: 3px;
text-decoration:none;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
}

.slicknav_menu>a {
    border: 1px solid #eee; background: #fff;

}

/* Button Text */
.slicknav_menu  .slicknav_menutxt {
color: #000;
font-weight: bold;
float:right;
}
/* Button Lines */
.slicknav_menu .slicknav_icon-bar {
background-color: #fff;
}
.slicknav_menu {

padding:0px;
}
.slicknav_nav {
color:#fff;
background:#000;
margin:0;
padding:0;
font-size:0.875em;
}
.slicknav_nav, .slicknav_nav ul {
list-style: none;
overflow:hidden;
}
.slicknav_nav ul {
padding:0;
margin:0 0 0 20px;
}
.slicknav_nav .slicknav_row {
padding:5px 10px;
margin:2px 5px;
}
.slicknav_nav a{
padding:5px 10px;
margin:2px 5px;
text-decoration:none;
color:#fff;
}
.slicknav_nav .slicknav_item a,
.slicknav_nav .slicknav_parent-link a {
padding:0;
margin:0;
}
.slicknav_nav .slicknav_row:hover {
background:#ccc;
color:#fff;
}
.slicknav_nav a:hover{
background:#ccc;
color:#222;
}
.slicknav_nav .slicknav_txtnode {
margin-left:15px;
}
/* slicknav */
.slicknav_menu {
display:none;
}
@media screen and (max-width: 890px) {
/* #masthead is the original menu */
#navtop {
display:none;
}
.slicknav_menu {
display:block;
}
}```

and

    /* Slider */
    .slick-slider
    {
        position: relative;
    margin-bottom:0;
        display: block;
        box-sizing: border-box;

        -webkit-user-select: none;
           -moz-user-select: none;
            -ms-user-select: none;
                user-select: none;

        -webkit-touch-callout: none;
        -khtml-user-select: none;
        -ms-touch-action: pan-y;
            touch-action: pan-y;
        -webkit-tap-highlight-color: transparent;odd-pager
    }

    .slick-list
    {
        position: relative;

        display: block;
        overflow: hidden;

        margin: 0;
        padding: 0;
    }

    .slick-list:focus
    {
        outline: none;
    }
    .slick-list.dragging
    {
        cursor: pointer;
        cursor: hand;
    }

    .slick-slider .slick-track,
    .slick-slider .slick-list
    {
        -webkit-transform: translate3d(0, 0, 0);
           -moz-transform: translate3d(0, 0, 0);
            -ms-transform: translate3d(0, 0, 0);
             -o-transform: translate3d(0, 0, 0);
                transform: translate3d(0, 0, 0);
    }

    .slick-track
    {
        position: relative;
        top: 0;
        left: 0;

        display: block;
        margin-left: auto;
        margin-right: auto;
    }
    .slick-track:before,
    .slick-track:after
    {
        display: table;

        content: '';
    }
    .slick-track:after
    {
        clear: both;
    }
    .slick-loading .slick-track
    {
        visibility: hidden;
    }

    .slick-slide
    {
        display: none;
        float: left;

        height: 100%;
        min-height: 1px;
    }
    [dir='rtl'] .slick-slide
    {
        float: right;
    }
    .slick-slide img
    {
        display: block;
    }
    .slick-slide.slick-loading img
    {
        display: none;
    }
    .slick-slide.dragging img
    {
        pointer-events: none;
    }
    .slick-initialized .slick-slide
    {
        display: block;
    }
    .slick-loading .slick-slide
    {
        visibility: hidden;
    }
    .slick-vertical .slick-slide
    {
        display: block;

        height: auto;

        border: 1px solid transparent;
    }
    .slick-arrow.slick-hidden {
        display: none;
    }

    .slick-next{right:0px;}
    .slick-prev {

        margin-right: 8px;
    left:0px;
    }

    .slick-prev, .slick-next {
        top: 50%;
    z-index:999;
        width: 40px;

        height: 50px;
    }
    .slick-next:before {
        content: "";
    }
    .slick-prev:before {
        content: "";
    }

    .slick-prev:before, .slick-next:before{opacity:0;font-size:40px;transition:300ms;-o-transition:300ms;-moz-transition:300ms;-webkit-transition:300ms;}

    .slick-prev:before {
        color: #fff;text-align: center;
        display: block;
        line-height: 0;
    }

    .slick-next:before {
        color: #fff;text-align: center;
        display: block;
        line-height: 0;
    }

    .slickslider .item-wrap-inner{position:relative;}

    .slickslider .item-info {
            width:100%;font-size: 12px;

    }
    .slickslider .item{position:relative;}
    .slickslider
     .item-image {
        background: #000;
    }

    .slickslider .item-image a {
        opacity: .7!important;
    }
    .itemtopinfo {
        padding: 0;
        position: absolute;
        left: 50%;
        top: 50%;
        width: 55%;
        transform: translate(-50%,-50%);
        -o-transform: translate(-50%,-50%);
        -webkit-transform: translate(-50%,-50%);
        -moz-transform: translate(-50%,-50%);
    }
    .slickslider .item-info {
        width: 100%;
        font-size: 12px;
    }

```

答:
Slick Slider has the autoplay option, which when set to true will play automatically. With the autoplaySpeed option you can set the interval of the autoplay function in milliseconds.
Add both the autoplay: true and autoplaySpeed: 2000 to your initialization in your JavaScript file.

```<code>$('.the-slider-class').slick({
  autoplay: true,
  autoplaySpeed: 2000,
});
</code>```

Otherwise, if you JavaScript file cannot be changed or for any other reason, you can edit the HTML of the slider element and add a data-attribute to the element. The value of the data-attribute is a JSON string with the same settings as your JavaScript counterpart. See example below.

```<code><div class="the-slider-class" data-slick='{"autoplay": true, "autoplaySpeed": 2000}'>
  ...
</div>
</code>```

Either should do the trick.

If you currently have other settings that you use, then make sure that you incorporate those as well in your JavaScript or HTML.

Look for all the options at the documentation and examples of Slick Slider.

Title: I can't enable slick slider autoplay

Body:
I am trying to setup a blog for a friend and it has prebuild slick slider.
I am really not good with Html and Javascript and i was trying to setup autoplay for the slider alla fternoon.

Where should i add a class? How should i setup javascript? I really dont know what i should do in order autoplay to be enabled. It is default false. Please explain to me

Slick classes defined are :

/* slicknav */
/*
Mobile Menu Core Style
*/
.slicknav_btn { position: relative; display: block; vertical-align: middle; float: left; padding: 0.438em 0.625em 0.438em 0.625em; line-height: 1.125em; cursor: pointer; }
.slicknav_menu  .slicknav_menutxt { display: block; line-height: 1.188em; float: left; }
.slicknav_menu .slicknav_icon { float: left; padding:3px;}
.slicknav_menu .slicknav_no-text { margin: 0 }
.slicknav_menu .slicknav_icon-bar { display: block; width: 1.125em; height: 0.125em; -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25); }
.slicknav_btn .slicknav_icon-bar + .slicknav_icon-bar { margin-top: 0.188em }
.slicknav_nav { clear: both }
.slicknav_nav ul,
.slicknav_nav li { display: block ;line-height: 20px;}
.slicknav_nav .slicknav_arrow { font-size: 0.8em; margin: 0 0 0 0.4em; }
.slicknav_nav .slicknav_item { cursor: pointer; }
.slicknav_nav .slicknav_row { display: block; }
.slicknav_nav a { display: block }
.slicknav_nav .slicknav_item a,
.slicknav_nav .slicknav_parent-link a { display: inline }
.slicknav_menu:before,
.slicknav_menu:after { content: " "; display: table; }
.slicknav_menu:after { clear: both }
/* IE6/7 support */
.slicknav_menu { *zoom: 1 }
/*
User Default Style
Change the following styles to modify the appearance of the menu.
*/
.slicknav_menu {
font-size:16px;
}
/* Button */
.slicknav_btn {
margin: 3px;
text-decoration:none;
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
}

.slicknav_menu>a {
    border: 1px solid #eee; background: #fff;

}

/* Button Text */
.slicknav_menu  .slicknav_menutxt {
color: #000;
font-weight: bold;
float:right;
}
/* Button Lines */
.slicknav_menu .slicknav_icon-bar {
background-color: #fff;
}
.slicknav_menu {

padding:0px;
}
.slicknav_nav {
color:#fff;
background:#000;
margin:0;
padding:0;
font-size:0.875em;
}
.slicknav_nav, .slicknav_nav ul {
list-style: none;
overflow:hidden;
}
.slicknav_nav ul {
padding:0;
margin:0 0 0 20px;
}
.slicknav_nav .slicknav_row {
padding:5px 10px;
margin:2px 5px;
}
.slicknav_nav a{
padding:5px 10px;
margin:2px 5px;
text-decoration:none;
color:#fff;
}
.slicknav_nav .slicknav_item a,
.slicknav_nav .slicknav_parent-link a {
padding:0;
margin:0;
}
.slicknav_nav .slicknav_row:hover {
background:#ccc;
color:#fff;
}
.slicknav_nav a:hover{
background:#ccc;
color:#222;
}
.slicknav_nav .slicknav_txtnode {
margin-left:15px;
}
/* slicknav */
.slicknav_menu {
display:none;
}
@media screen and (max-width: 890px) {
/* #masthead is the original menu */
#navtop {
display:none;
}
.slicknav_menu {
display:block;
}
}```

and

    /* Slider */
    .slick-slider
    {
        position: relative;
    margin-bottom:0;
        display: block;
        box-sizing: border-box;

        -webkit-user-select: none;
           -moz-user-select: none;
            -ms-user-select: none;
                user-select: none;

        -webkit-touch-callout: none;
        -khtml-user-select: none;
        -ms-touch-action: pan-y;
            touch-action: pan-y;
        -webkit-tap-highlight-color: transparent;odd-pager
    }

    .slick-list
    {
        position: relative;

        display: block;
        overflow: hidden;

        margin: 0;
        padding: 0;
    }

    .slick-list:focus
    {
        outline: none;
    }
    .slick-list.dragging
    {
        cursor: pointer;
        cursor: hand;
    }

    .slick-slider .slick-track,
    .slick-slider .slick-list
    {
        -webkit-transform: translate3d(0, 0, 0);
           -moz-transform: translate3d(0, 0, 0);
            -ms-transform: translate3d(0, 0, 0);
             -o-transform: translate3d(0, 0, 0);
                transform: translate3d(0, 0, 0);
    }

    .slick-track
    {
        position: relative;
        top: 0;
        left: 0;

        display: block;
        margin-left: auto;
        margin-right: auto;
    }
    .slick-track:before,
    .slick-track:after
    {
        display: table;

        content: '';
    }
    .slick-track:after
    {
        clear: both;
    }
    .slick-loading .slick-track
    {
        visibility: hidden;
    }

    .slick-slide
    {
        display: none;
        float: left;

        height: 100%;
        min-height: 1px;
    }
    [dir='rtl'] .slick-slide
    {
        float: right;
    }
    .slick-slide img
    {
        display: block;
    }
    .slick-slide.slick-loading img
    {
        display: none;
    }
    .slick-slide.dragging img
    {
        pointer-events: none;
    }
    .slick-initialized .slick-slide
    {
        display: block;
    }
    .slick-loading .slick-slide
    {
        visibility: hidden;
    }
    .slick-vertical .slick-slide
    {
        display: block;

        height: auto;

        border: 1px solid transparent;
    }
    .slick-arrow.slick-hidden {
        display: none;
    }

    .slick-next{right:0px;}
    .slick-prev {

        margin-right: 8px;
    left:0px;
    }

    .slick-prev, .slick-next {
        top: 50%;
    z-index:999;
        width: 40px;

        height: 50px;
    }
    .slick-next:before {
        content: "";
    }
    .slick-prev:before {
        content: "";
    }

    .slick-prev:before, .slick-next:before{opacity:0;font-size:40px;transition:300ms;-o-transition:300ms;-moz-transition:300ms;-webkit-transition:300ms;}

    .slick-prev:before {
        color: #fff;text-align: center;
        display: block;
        line-height: 0;
    }

    .slick-next:before {
        color: #fff;text-align: center;
        display: block;
        line-height: 0;
    }

    .slickslider .item-wrap-inner{position:relative;}

    .slickslider .item-info {
            width:100%;font-size: 12px;

    }
    .slickslider .item{position:relative;}
    .slickslider
     .item-image {
        background: #000;
    }

    .slickslider .item-image a {
        opacity: .7!important;
    }
    .itemtopinfo {
        padding: 0;
        position: absolute;
        left: 50%;
        top: 50%;
        width: 55%;
        transform: translate(-50%,-50%);
        -o-transform: translate(-50%,-50%);
        -webkit-transform: translate(-50%,-50%);
        -moz-transform: translate(-50%,-50%);
    }
    .slickslider .item-info {
        width: 100%;
        font-size: 12px;
    }

Body:
Slick Slider has the autoplay option, which when set to true will play automatically. With the autoplaySpeed option you can set the interval of the autoplay function in milliseconds.
Add both the autoplay: true and autoplaySpeed: 2000 to your initialization in your JavaScript file.

$('.the-slider-class').slick({
  autoplay: true,
  autoplaySpeed: 2000,
});

Otherwise, if you JavaScript file cannot be changed or for any other reason, you can edit the HTML of the slider element and add a data-attribute to the element. The value of the data-attribute is a JSON string with the same settings as your JavaScript counterpart. See example below.

<div class="the-slider-class" data-slick='{"autoplay": true, "autoplaySpeed": 2000}'>
  ...
</div>

Either should do the trick.

If you currently have other settings that you use, then make sure that you incorporate those as well in your JavaScript or HTML.

Look for all the options at the documentation and examples of Slick Slider.


问:
How to set Image to take the full size screen with header in react navigation?
I Have screen contain an image and I want to take the full-size screen with header?

I just use position: "absolute" but it's not working to wrap the header, and I can't use header: null because I want the back button to appear!

so how can I handle this?

what I get

what I want

Thanks in advance.

答:
You need hide the header, if you are using react navigation, you can add the navigationOptions for add attributes for hide the header, like these lines.

```<code>static navigationOptions = {
    headerShown: false
  };
</code>```

Body:
You need hide the header, if you are using react navigation, you can add the navigationOptions for add attributes for hide the header, like these lines.

static navigationOptions = {
    headerShown: false
  };


问:
Selenium NoSuchElementException always returns True
```<code>class Errors:
    def __init__(self):
        pass
    def No_Subject(self):
        try:
            x = self.webdriver.find_element_by_xpath('//*[@id="confirmModalBtn"]')
            x.click()
        except NoSuchElementException:
            return False
        else:
            return True
</code>```

I am importing this definition into second class

```<code>        self.error3 = Errors.No_Subject(self)
        print(self.error3)
>>True
</code>```

No matter what XPath I enter(for example I entered data), it returns True. Why this code does not properly work?

答:
You need to understand what the else block actually does. Read here

Your code is working correctly and returning True since there is no error that occurred. You can try passing a random id value in XPath and this should return False

Body:
class Errors:
    def __init__(self):
        pass
    def No_Subject(self):
        try:
            x = self.webdriver.find_element_by_xpath('//*[@id="confirmModalBtn"]')
            x.click()
        except NoSuchElementException:
            return False
        else:
            return True

I am importing this definition into second class

        self.error3 = Errors.No_Subject(self)
        print(self.error3)
>>True

No matter what XPath I enter(for example I entered data), it returns True. Why this code does not properly work?


答:
Your data do not support any evidence of seasonality; your data are consistent with white noise shifted by an offset.

Forcing a specific SARIMA structure and then using that to forecast based on your white noise data is very dangerous.

To demonstrate, let's turn things around and generate white noise data that are shifted by the same offset and that have the same variance as your sample data. Keep in mind that this is white noise by design.

library(forecast)
library(ggplot2)
set.seed(2018)
ts <- ts(
    rnorm(48, mean = 33.8750, sd = 11.15796),
    start = c(2016, 1), frequency = 12)
autoplot(ts) + theme_minimal()
```

<p><img src="https://i.stack.imgur.com/15Oh8.png" alt="enter image description here"></p>

<p>We now fit a SARIMA(0, 0, 0)(0, 1, 0)<sub>12</sub> model to the data.</p>

<pre class="lang-r prettyprint-override"><code>fit <- arima(ts, order = c(0, 0 , 0), seasonal = list(order = c(0, 1, 0), period = 12))
fit
#
#Call:
#arima(x = ts, order = c(0, 0, 0), seasonal = list(order = c(0, 1, 0), period = 12))
#
#
#sigma^2 estimated as 283:  log likelihood = -152.7,  aic = 307.39
</code>```

Again, keep in mind that data was generated from ARIMA(0,0,0) = SARIMA(0,0,0)(0,0,0), i.e. a white-noise model.

We now use fit to forecast

autoplot(forecast(ts, h = 24, model = fit)) + theme_minimal()
```

So what we've done here is to forecast based on white noise data assuming a non-existent seasonality effect.

Yes, you can do that without raising any warnings/flags within forecast. And no, these forecasts will not be meaningful.

Title: small Time Series Analysis

Body:
I need to make a prediction for the next 2 years. However, I have a very small amount of Data.
Data:

   structure(list(BelegDat = structure(c(16801, 16832, 16861, 16892,
    16922, 16953, 16983, 17014, 17045, 17075, 17106, 17136, 17167,
    17198, 17226, 17257, 17287, 17318, 17348, 17379, 17410, 17440,
    17471, 17501, 17532, 17563, 17591, 17622, 17652, 17683, 17713,
    17744, 17775, 17805, 17836, 17866, 17897, 17928, 17956, 17987,
    18017, 18048, 18078, 18109, 18140, 18170, 18201, 18231), class = "Date"),
        Value = c(37, 28, 37, 47, 37, 28, 37, 37, 19, 37, 37, 28,
        40, 30, 40, 50, 40, 30, 40, 40, 20, 40, 40, 30, 30, 40, 30,
        30, 40, 30, 30, 50, 30, 50, 20, 20, 60, 20, 60, 40, 20, 10,
        40, 20, 20, 10, 44, 33)), row.names = c(NA, -48L), class = "data.frame")

I am using ARIMA:

myts <- ts(df_ready[,2], start=c(2016,01), end=c(2019,12), frequency = 12)

fit <- auto.arima(myts)

pred <- forecast(fit, 24) # next 2 years (24 Months)
plot(pred)

My output:
  Output

Could you, please, show me my mistake / suggest some other way how this prediction can be done?

Thank you in advance!

Body:
Your data do not support any evidence of seasonality; your data are consistent with white noise shifted by an offset.

Forcing a specific SARIMA structure and then using that to forecast based on your white noise data is very dangerous.

To demonstrate, let's turn things around and generate white noise data that are shifted by the same offset and that have the same variance as your sample data. Keep in mind that this is white noise by design.

library(forecast)
library(ggplot2)
set.seed(2018)
ts <- ts(
    rnorm(48, mean = 33.8750, sd = 11.15796),
    start = c(2016, 1), frequency = 12)
autoplot(ts) + theme_minimal()

We now fit a SARIMA(0, 0, 0)(0, 1, 0)12 model to the data.

fit <- arima(ts, order = c(0, 0 , 0), seasonal = list(order = c(0, 1, 0), period = 12))
fit
#
#Call:
#arima(x = ts, order = c(0, 0, 0), seasonal = list(order = c(0, 1, 0), period = 12))
#
#
#sigma^2 estimated as 283:  log likelihood = -152.7,  aic = 307.39

Again, keep in mind that data was generated from ARIMA(0,0,0) = SARIMA(0,0,0)(0,0,0), i.e. a white-noise model.

We now use fit to forecast

autoplot(forecast(ts, h = 24, model = fit)) + theme_minimal()

So what we've done here is to forecast based on white noise data assuming a non-existent seasonality effect.

Yes, you can do that without raising any warnings/flags within forecast. And no, these forecasts will not be meaningful.


问:
TfidfVectorizer - Vocabulary wasn't fitted
Code to import a model and run a prediction on a single input

```<code>Tfidf_vect = TfidfVectorizer(max_features=5000) # Same classifier as I used in the model
Train_X_IP = Tfidf_vect.transform(["change in the meaning"]).toarray() #Passing the input
loaded_model = pickle.load(open("finalized_model.sav", 'rb')) #loading the model

predictions_SVM = loaded_model.predict_proba(Train_X_IP)
print(predictions_SVM)

Error I get : TfidfVectorizer - Vocabulary wasn't fitted.
</code>```

I saw many articles suggesting many approaches , so far I tried

Adding fit_transform instead of Tfidf_vect.transform but that did not solve the issue

Second Option I tried , loading Tfidfvectorizer externally

```<code> Tfidf_vect = TfidfVectorizer(max_features=5000)
 import pickle
 pickle.dump(Tfidf_vect, open("vectorizer.pickle", "wb"))
 multilabel_binarizer = joblib.load('vectorizer.pickle')
 Still get the same error : TfidfVectorizer - Vocabulary wasn't fitted.
</code>```

Is this a correct way to use the model and vectorizer. ?

答: You need the same vectorizer that you used to train the model in the first place. I'm assuming you would've used a "fit" or "fit_transform" function during training. Once you do that, save the vectorizer in pickle of joblib format. Then load it back up, and use the transform function on the new data to make predictions.</p>

Body:
Code to import a model and run a prediction on a single input

Tfidf_vect = TfidfVectorizer(max_features=5000) # Same classifier as I used in the model
Train_X_IP = Tfidf_vect.transform(["change in the meaning"]).toarray() #Passing the input
loaded_model = pickle.load(open("finalized_model.sav", 'rb')) #loading the model

predictions_SVM = loaded_model.predict_proba(Train_X_IP)
print(predictions_SVM)

Error I get : TfidfVectorizer - Vocabulary wasn't fitted.

I saw many articles suggesting many approaches , so far I tried

Adding fit_transform instead of Tfidf_vect.transform but that did not solve the issue

Second Option I tried , loading Tfidfvectorizer externally

 Tfidf_vect = TfidfVectorizer(max_features=5000)
 import pickle
 pickle.dump(Tfidf_vect, open("vectorizer.pickle", "wb"))
 multilabel_binarizer = joblib.load('vectorizer.pickle')
 Still get the same error : TfidfVectorizer - Vocabulary wasn't fitted.

Is this a correct way to use the model and vectorizer. ?


问:
How can I fetch data from multiple api endpoints in React-native in the same page
I'm trying to fetch data from two different api-endpoints and trying to show the whole data in the same page in my React native appThis is the snapshot of the error I'm getting with the code snippet</p>

答:
The same exception was coming for me as well...tried a different approach.Chained one fetch method in another and tried to set the value into all the datasource variables in the first fetch block and then used the 2nd variable in the next fetch block again.

The issue got resolved and the values are now coming as required. Don't know if this is the perfect approach but it solved the issue, please try to refer the below example

```<code>fetch(‘endpoint1’, {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json'
        },
        body: JSON.stringify({
            //send the parameters you need to use to fetch the data
 from endpoint
    //e.g.  “id”: this.state.id,
    …
        })
    })
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                isLoading: false,
                dataSource1: responseJson,
                dataSource2: responseJson,
            })

        })
        .then(()=>{
        fetch(‘endpoint2', {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json'
        },
        body: JSON.stringify({
            //send the parameters you need to use to fetch the data
from endpoint
    //e.g.  “id”: this.state.id,
    …
        })
    })
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                isLoading: false,
                dataSource2: responseJson,
            })
        })
        })
        .catch((error) => {
            console.error(error);
        });
</code>```

Body:
The same exception was coming for me as well...tried a different approach.Chained one fetch method in another and tried to set the value into all the datasource variables in the first fetch block and then used the 2nd variable in the next fetch block again.

The issue got resolved and the values are now coming as required. Don't know if this is the perfect approach but it solved the issue, please try to refer the below example

fetch(‘endpoint1’, {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json'
        },
        body: JSON.stringify({
            //send the parameters you need to use to fetch the data
 from endpoint
    //e.g.  “id”: this.state.id,
    …
        })
    })
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                isLoading: false,
                dataSource1: responseJson,
                dataSource2: responseJson,
            })

        })
        .then(()=>{
        fetch(‘endpoint2', {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json'
        },
        body: JSON.stringify({
            //send the parameters you need to use to fetch the data
from endpoint
    //e.g.  “id”: this.state.id,
    …
        })
    })
        .then((response) => response.json())
        .then((responseJson) => {
            this.setState({
                isLoading: false,
                dataSource2: responseJson,
            })
        })
        })
        .catch((error) => {
            console.error(error);
        });


问:
Will not assign values individually to method
Trying to complete an assignment for class and I can get correct output when assigning the parameters together but when trying to assign the values individually I can't get a price. I have a feeling it's an extremely easy fix but I've been doing assignments all day and my brain feels like jello. Not looking for an answer so much as a hint to push my to the correct answer. Thanks!</p>

```<code>using static System.Console;
using System;
class PhotoDemo
{
   static void Main()
   {
      Photo standardPhoto = new Photo();
      standardPhoto.Width = 8;
      standardPhoto.Height = 9;
      WriteLine(standardPhoto.ToString());

      Photo customPhoto = new Photo(10, 12);
      WriteLine(customPhoto.ToString());

      MattedPhoto mattedPhoto = new MattedPhoto(8, 9, "Blue");
      WriteLine(mattedPhoto.ToString());

      FramedPhoto framedPhoto = new FramedPhoto(8, 9, "Wood", "Modern");
      WriteLine(framedPhoto.ToString());
   }
}

public class Photo
{
  public Photo(){}
  public int Width{get; set;}
  public int Height{get; set;}
  protected double Price{get; set;}

  public Photo(int width, int height)
  {
    Width = width;
    Height = height;
    if(width == 8 && height == 10)
    {
      Price = 3.99;
    }
    else if(Width == 10 && Height == 12)
    {
      Price = 5.99;
    }
    else
    {
      Price = 9.99;
    }
  }

  public override string ToString()
  {
    string output = String.Format("Width: {0}, Height: {1}, Price: {2}", Width, Height, Price.ToString("C"));
    return output;
  }
}

public class MattedPhoto : Photo
{
  public MattedPhoto(){}
  public string Color {get; set;}
  public MattedPhoto(int width, int height, string color) : base(width, height)
  {
    width = Width;
    height = Height;
    color = Color;

    if(width == 8 && height == 10)
    {
      Price = 3.99 + 10;
    }
    else if(width == 10 && height == 12)
    {
      Price = 5.99 + 10;
    }
    else
    {
      Price = 9.99 + 10;
    }
  }

  public override string ToString()
  {
    string output = String.Format("Width: {0}, Height: {1}, Price: {2}, Color: {3}", Width, Height, Price.ToString("C"), Color);
    return output;
  }
}

public class FramedPhoto : Photo
{
  public FramedPhoto(){}
  public string Material{get; set;}
  public string Style{get; set;}

  public FramedPhoto(int width, int height, string material, string style) : base(width, height)
  {
    width = Width;
    height = Height;
    material = Material;
    style = Style;

    if(width == 8 && height == 10)
    {
      Price = 3.99 + 25;
    }
    else if(width == 10 && height == 12)
    {
      Price = 5.99 + 25;
    }
    else
    {
      Price = 9.99 + 25;
    }
  }

  public override string ToString()
  {
    string output = String.Format("Width: {0}, Height: {1}, Price: {2}, Material: {3}, Style: {4}", Width, Height, Price.ToString("C"), Material, Style);
    return output;
  }
}```
</code>```

答:
Price calculation is doing only in the constructors with parameters (so only when you create an object). When you use parameter-less one, then the price isn't calculated (even if you set width and height later). You can:

create a separate method which takes width and height as parameters and recalculates price

modify price getter, to automatically recalculate price every time you ask for it

Body:
Trying to complete an assignment for class and I can get correct output when assigning the parameters together but when trying to assign the values individually I can't get a price. I have a feeling it's an extremely easy fix but I've been doing assignments all day and my brain feels like jello. Not looking for an answer so much as a hint to push my to the correct answer. Thanks!

using static System.Console;
using System;
class PhotoDemo
{
   static void Main()
   {
      Photo standardPhoto = new Photo();
      standardPhoto.Width = 8;
      standardPhoto.Height = 9;
      WriteLine(standardPhoto.ToString());

      Photo customPhoto = new Photo(10, 12);
      WriteLine(customPhoto.ToString());

      MattedPhoto mattedPhoto = new MattedPhoto(8, 9, "Blue");
      WriteLine(mattedPhoto.ToString());

      FramedPhoto framedPhoto = new FramedPhoto(8, 9, "Wood", "Modern");
      WriteLine(framedPhoto.ToString());
   }
}

public class Photo
{
  public Photo(){}
  public int Width{get; set;}
  public int Height{get; set;}
  protected double Price{get; set;}

  public Photo(int width, int height)
  {
    Width = width;
    Height = height;
    if(width == 8 && height == 10)
    {
      Price = 3.99;
    }
    else if(Width == 10 && Height == 12)
    {
      Price = 5.99;
    }
    else
    {
      Price = 9.99;
    }
  }

  public override string ToString()
  {
    string output = String.Format("Width: {0}, Height: {1}, Price: {2}", Width, Height, Price.ToString("C"));
    return output;
  }
}

public class MattedPhoto : Photo
{
  public MattedPhoto(){}
  public string Color {get; set;}
  public MattedPhoto(int width, int height, string color) : base(width, height)
  {
    width = Width;
    height = Height;
    color = Color;

    if(width == 8 && height == 10)
    {
      Price = 3.99 + 10;
    }
    else if(width == 10 && height == 12)
    {
      Price = 5.99 + 10;
    }
    else
    {
      Price = 9.99 + 10;
    }
  }

  public override string ToString()
  {
    string output = String.Format("Width: {0}, Height: {1}, Price: {2}, Color: {3}", Width, Height, Price.ToString("C"), Color);
    return output;
  }
}

public class FramedPhoto : Photo
{
  public FramedPhoto(){}
  public string Material{get; set;}
  public string Style{get; set;}

  public FramedPhoto(int width, int height, string material, string style) : base(width, height)
  {
    width = Width;
    height = Height;
    material = Material;
    style = Style;

    if(width == 8 && height == 10)
    {
      Price = 3.99 + 25;
    }
    else if(width == 10 && height == 12)
    {
      Price = 5.99 + 25;
    }
    else
    {
      Price = 9.99 + 25;
    }
  }

  public override string ToString()
  {
    string output = String.Format("Width: {0}, Height: {1}, Price: {2}, Material: {3}, Style: {4}", Width, Height, Price.ToString("C"), Material, Style);
    return output;
  }
}```


答:
Haven't used BS4 or python for awhile, but If I remember correctly something like this should work on getting all elements with data_stat and school_name in the data.

```<code>results = soup.findAll("td", {"data_stat" : "school_name"})
</code>```

Or if you want all results in data with the data_stat attribute and the value doesn't matter use -

```<code>results = soup.findAll("td", {"data_stat" : True})
</code>```

Title: Beautifulsoup4, BS4, Python Parsing Question

Body:
Haven't used BS4 or python for awhile, but If I remember correctly something like this should work on getting all elements with data_stat and school_name in the data.

results = soup.findAll("td", {"data_stat" : "school_name"})

Or if you want all results in data with the data_stat attribute and the value doesn't matter use -

results = soup.findAll("td", {"data_stat" : True})


问:
Display number 0 in excel cell
I'm using a userform to add numbers in my excel sheet.

When someone add 01234  in the userform, I only see 1234  in the excel cell.

So I modified the cell format, it worked but whenever i wanted to only add 1234 , excel would display a 0 so 01234 .

I just want to be able to add the textbox value as it is in excel sheets.

Thank you

EDIT:

This is a part of the code that takes the textbox value and enters in the requested cell :

```<code>Sheets("Sheet3").Range("B4").Select
ActiveCell.Value = UCase(TextBox2)
</code>```

答:
Since you say (in comments) that you don't mind if the resultant cell value is numeric or text, simply use

```<code>Worksheets("Sheet3").Range("B4").Value = "'" & UCase(TextBox2)
</code>```

This will make all entries text.  FWIW, that may become an issue for you later!

Title: Display number 0 in excel cell

Body:
I'm using a userform to add numbers in my excel sheet.

When someone add 01234  in the userform, I only see 1234  in the excel cell.

So I modified the cell format, it worked but whenever i wanted to only add 1234 , excel would display a 0 so 01234 .

I just want to be able to add the textbox value as it is in excel sheets.

Thank you

EDIT:

This is a part of the code that takes the textbox value and enters in the requested cell :

Sheets("Sheet3").Range("B4").Select
ActiveCell.Value = UCase(TextBox2)

Body:
Since you say (in comments) that you don't mind if the resultant cell value is numeric or text, simply use

Worksheets("Sheet3").Range("B4").Value = "'" & UCase(TextBox2)

This will make all entries text.  FWIW, that may become an issue for you later!


问:
Output is NaN , how?
I am trying to code Taylor series but I am getting 'nan' as output in case of large value of n(=100).
Where am I doing things wrong?</p>

```<code>#include<iostream>
#include<cmath>
using namespace std;

 int main(){

    int n;
    double x;

    cin >> n;
    cin >> x;

    long double temp_val = 1;
    int sign = 1;
    int power = 1;
    long long int factorial = 1;

    for(int i = 1 ; i < n ; i++){

        sign = sign* -1 ;
        power =  2*i;
        factorial  = factorial*(2*i)*(2*i-1);

        temp_val += sign*pow(x,power)/factorial;
    }
    cout<<temp_val;

}
</code>```

答:
Calculating the taylor series has a trap that also occurs in other situations: Both the numerator and denominator of the terms to add grow rather fast and overflow easily, but their quotient converges to zero (otherwise adding them up till infinity would not converge to a finite number).

Instead of keeping track of both terms individually you need to update the result and the total increment. I wont provide you a full solution. In pseudo-code

```<code>double res = 0;
double delta = x;
int n = 1;
double sign = -1;
while ( ! stop_condition ) {
    delta *= (x / n);
    res += sign*delta;
    ++n;
    sign *= -1;
}
</code>```

Title: Output is NaN , how?

Body:
I am trying to code Taylor series but I am getting 'nan' as output in case of large value of n(=100).
Where am I doing things wrong?

#include<iostream>
#include<cmath>
using namespace std;

 int main(){

    int n;
    double x;

    cin >> n;
    cin >> x;

    long double temp_val = 1;
    int sign = 1;
    int power = 1;
    long long int factorial = 1;

    for(int i = 1 ; i < n ; i++){

        sign = sign* -1 ;
        power =  2*i;
        factorial  = factorial*(2*i)*(2*i-1);

        temp_val += sign*pow(x,power)/factorial;
    }
    cout<<temp_val;

}

Body:
Calculating the taylor series has a trap that also occurs in other situations: Both the numerator and denominator of the terms to add grow rather fast and overflow easily, but their quotient converges to zero (otherwise adding them up till infinity would not converge to a finite number).

Instead of keeping track of both terms individually you need to update the result and the total increment. I wont provide you a full solution. In pseudo-code

double res = 0;
double delta = x;
int n = 1;
double sign = -1;
while ( ! stop_condition ) {
    delta *= (x / n);
    res += sign*delta;
    ++n;
    sign *= -1;
}


问:
Sequence of datetimes except weekends Python
I'm trying to create a sequence of datetime object but excluding weekends. So far I've successfully created a sequence of dates from any given start date to end date, but I'm having trouble figuring out how to exclude weekends:</p>

```<code># Generate sequence of dates
startDate = datetime.datetime.strptime(start, '%Y-%m-%d').date()
endDate = datetime.datetime.strptime(end, '%Y-%m-%d').date()
nb_days = (endDate - startDate).days + 1  # + 1 because range is exclusive
dates = [startDate + datetime.timedelta(days=x) for x in range(nb_days)]
</code>```

答:
You can do this quite nicely with the dateutil library's rrule.

Example:

from dateutil.parser import parse
from dateutil.rrule import rrule, DAILY, MO, TU, WE, TH, FR

result = rrule(
  DAILY,
  byweekday=(MO,TU,WE,TH,FR),
  dtstart=parse(start),
  until=parse(end)
)
print(list(result))
```

<p>Example output: </p>

```[datetime.datetime(2019, 1, 21, 0, 0),
 datetime.datetime(2019, 1, 22, 0, 0),
 datetime.datetime(2019, 1, 23, 0, 0),
 datetime.datetime(2019, 1, 24, 0, 0),
 datetime.datetime(2019, 1, 25, 0, 0),
 datetime.datetime(2019, 1, 28, 0, 0),
 datetime.datetime(2019, 1, 29, 0, 0),
 datetime.datetime(2019, 1, 30, 0, 0),
 datetime.datetime(2019, 1, 31, 0, 0),
 datetime.datetime(2019, 2, 1, 0, 0),
 datetime.datetime(2019, 2, 4, 0, 0)]
```

Body:
I'm trying to create a sequence of datetime object but excluding weekends. So far I've successfully created a sequence of dates from any given start date to end date, but I'm having trouble figuring out how to exclude weekends:

# Generate sequence of dates
startDate = datetime.datetime.strptime(start, '%Y-%m-%d').date()
endDate = datetime.datetime.strptime(end, '%Y-%m-%d').date()
nb_days = (endDate - startDate).days + 1  # + 1 because range is exclusive
dates = [startDate + datetime.timedelta(days=x) for x in range(nb_days)]

Body:
You can do this quite nicely with the dateutil library's rrule.

Example:

from dateutil.parser import parse
from dateutil.rrule import rrule, DAILY, MO, TU, WE, TH, FR

result = rrule(
  DAILY,
  byweekday=(MO,TU,WE,TH,FR),
  dtstart=parse(start),
  until=parse(end)
)
print(list(result))

Example output:

[datetime.datetime(2019, 1, 21, 0, 0),
 datetime.datetime(2019, 1, 22, 0, 0),
 datetime.datetime(2019, 1, 23, 0, 0),
 datetime.datetime(2019, 1, 24, 0, 0),
 datetime.datetime(2019, 1, 25, 0, 0),
 datetime.datetime(2019, 1, 28, 0, 0),
 datetime.datetime(2019, 1, 29, 0, 0),
 datetime.datetime(2019, 1, 30, 0, 0),
 datetime.datetime(2019, 1, 31, 0, 0),
 datetime.datetime(2019, 2, 1, 0, 0),
 datetime.datetime(2019, 2, 4, 0, 0)]


问:
Python loop iterates after expected termination
The below Python code has an odd behavior, which I can't figure out.

The program calls testQuery, which asks the used to reply 'yes' to call scoreAverager, or 'no' to exit the program. If scoreAverager is called, it then requests the user enter a series of scores, or 'x' to finish, which returns the user to testQuery, where they can chose to average another test or exit.

The weirdness happens if a user averages the results for several tests (e.g. 2 or more).
At that point giving 'no' to testQuery will fail to terminated the program. It will iterate an additional cycle for every test that was averaged. I can't figure out why this would be the case. It looks and behaves like an off-by-one erros, but the conditions to close the loop appear satisfied. It can be solved with a 'break', but I'd rather know what the problem is to solve it more organically.

Can anyone let me know why this odd behavior is happening?

CODE:

```<code>def scoreAverager():
    done=0
    scoreTot=0
    numScores=0
    average=0
    while done == 0:
        score=input("Enter the numerical score, or enter 'x' to finish entering scores:")
        acceptedXs={"X","x"}
        if score in acceptedXs:
            print ("The average of the scores is: ",average)
            #break #this break is necessary for proper function.
            done=1
            testQuery()
        else:
            try:
                score=float(score)
                scoreTot=scoreTot+score
                numScores=numScores+1
                average=scoreTot/numScores
            except ValueError:
                print("EXCEPTION: The entry was invalid, please try again.")

def testQuery():
    done=0
    while done == 0:
        moreTests=input("Do you have a set of score to average? Enter 'Yes' or 'No':")
        acceptedNos=("No","NO","no")
        acceptedYess=("Yes","YES","yes")
        if moreTests in acceptedNos:
            print("Program Complete.")
            done=1
        elif moreTests in acceptedYess:
            scoreAverager()
        else:
            print ("ERROR: The entry was invalid. Please try again.")

def main():
    testQuery()

main()
</code>```

EXAMPLE INPUT/OUTPUT:

```<code>Do you have a set of score to average? Enter 'Yes' or 'No':Yes
Enter the numerical score, or enter 'x' to finish entering scores:1
Enter the numerical score, or enter 'x' to finish entering scores:2
Enter the numerical score, or enter 'x' to finish entering scores:x
The average of the scores is:  1.5
Do you have a set of score to average? Enter 'Yes' or 'No':Yes
Enter the numerical score, or enter 'x' to finish entering scores:1
Enter the numerical score, or enter 'x' to finish entering scores:2
Enter the numerical score, or enter 'x' to finish entering scores:x
The average of the scores is:  1.5
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
</code>```

答:
I trimmed down your code a bit to isolate the problem, nested the ``scoreAvenger()``` and made the scope issue a little more explicit. What you've actually done here, it seems, is indirect recursion: you call a function that doesn't directly call itself, but which calls another function which calls it.  You thus create a complicated recursive call stack which has to unwind itself.</p>

<p>This can be fixed using <code>nonlocal</code> but only if we nest the functions appropriately; then the recursive calls are terminated [Edit: NO! they continue, but the value of <code>done</code> doesn't get set to 0] (because the nested function captures the value of done).  </p>

```def testQuery():
    def scoreAverager():
        nonlocal done       #here is the key: make done nonlocal
        done = 0            #comment out above line to see the problem return
        while done == 0:
            score=input("Enter x")
            acceptedXs={"X","x"}
            if score in acceptedXs:
                print ("Returning to enclosing scope")
                done = True
                testQuery()
                print("stack unwinding in testQuery")

    done = 0
    while done == 0:
        moreTests=input("Want to enter nested scope/make another recursive call?")
        acceptedNos=("No","NO","no")
        if moreTests in acceptedNos:
            print("Program Complete.")
            done = 1
        else:
            scoreAverager()
            print("stack unwinding in scoreAvenger")
def main():
    testQuery()

main()
```

This is pretty tricky, I think that's what's going on anyway.
Edit: added the print functions which execute after as the recursive calls come off the stack.

Body:
The below Python code has an odd behavior, which I can't figure out.

The program calls testQuery, which asks the used to reply 'yes' to call scoreAverager, or 'no' to exit the program. If scoreAverager is called, it then requests the user enter a series of scores, or 'x' to finish, which returns the user to testQuery, where they can chose to average another test or exit.

The weirdness happens if a user averages the results for several tests (e.g. 2 or more).
At that point giving 'no' to testQuery will fail to terminated the program. It will iterate an additional cycle for every test that was averaged. I can't figure out why this would be the case. It looks and behaves like an off-by-one erros, but the conditions to close the loop appear satisfied. It can be solved with a 'break', but I'd rather know what the problem is to solve it more organically.

Can anyone let me know why this odd behavior is happening?

CODE:

def scoreAverager():
    done=0
    scoreTot=0
    numScores=0
    average=0
    while done == 0:
        score=input("Enter the numerical score, or enter 'x' to finish entering scores:")
        acceptedXs={"X","x"}
        if score in acceptedXs:
            print ("The average of the scores is: ",average)
            #break #this break is necessary for proper function.
            done=1
            testQuery()
        else:
            try:
                score=float(score)
                scoreTot=scoreTot+score
                numScores=numScores+1
                average=scoreTot/numScores
            except ValueError:
                print("EXCEPTION: The entry was invalid, please try again.")

def testQuery():
    done=0
    while done == 0:
        moreTests=input("Do you have a set of score to average? Enter 'Yes' or 'No':")
        acceptedNos=("No","NO","no")
        acceptedYess=("Yes","YES","yes")
        if moreTests in acceptedNos:
            print("Program Complete.")
            done=1
        elif moreTests in acceptedYess:
            scoreAverager()
        else:
            print ("ERROR: The entry was invalid. Please try again.")

def main():
    testQuery()

main()

EXAMPLE INPUT/OUTPUT:

Do you have a set of score to average? Enter 'Yes' or 'No':Yes
Enter the numerical score, or enter 'x' to finish entering scores:1
Enter the numerical score, or enter 'x' to finish entering scores:2
Enter the numerical score, or enter 'x' to finish entering scores:x
The average of the scores is:  1.5
Do you have a set of score to average? Enter 'Yes' or 'No':Yes
Enter the numerical score, or enter 'x' to finish entering scores:1
Enter the numerical score, or enter 'x' to finish entering scores:2
Enter the numerical score, or enter 'x' to finish entering scores:x
The average of the scores is:  1.5
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.
Do you have a set of score to average? Enter 'Yes' or 'No':No
Program Complete.

Body:
I trimmed down your code a bit to isolate the problem, nested the ``scoreAvenger()``` and made the scope issue a little more explicit. What you've actually done here, it seems, is indirect recursion: you call a function that doesn't directly call itself, but which calls another function which calls it.  You thus create a complicated recursive call stack which has to unwind itself.

This can be fixed using nonlocal but only if we nest the functions appropriately; then the recursive calls are terminated [Edit: NO! they continue, but the value of done doesn't get set to 0] (because the nested function captures the value of done).

def testQuery():
    def scoreAverager():
        nonlocal done       #here is the key: make done nonlocal
        done = 0            #comment out above line to see the problem return
        while done == 0:
            score=input("Enter x")
            acceptedXs={"X","x"}
            if score in acceptedXs:
                print ("Returning to enclosing scope")
                done = True
                testQuery()
                print("stack unwinding in testQuery")

    done = 0
    while done == 0:
        moreTests=input("Want to enter nested scope/make another recursive call?")
        acceptedNos=("No","NO","no")
        if moreTests in acceptedNos:
            print("Program Complete.")
            done = 1
        else:
            scoreAverager()
            print("stack unwinding in scoreAvenger")
def main():
    testQuery()

main()

This is pretty tricky, I think that's what's going on anyway.
Edit: added the print functions which execute after as the recursive calls come off the stack.


问:
How to find the object in an array where particular object value is max
Hi Below is the JSON array of ojects

```<code>[
  {
    "BookingId": 366024,
    "BookingDetailId": 340708,
    "JobCode" : 13
  },
  {
    "BookingId": 366023,
    "BookingDetailId": 340707,
    "JobCode" : 12
  },
  {
    "BookingId": 366022,
    "BookingDetailId": 340706,
    "JobCode" : 12
   }
]
</code>```

I want to get particular array object where BookingId is Max where JobCode is 12, for eg. In above array I want object {
    "BookingId": 366023,
    "BookingDetailId": 340707,
    "JobCode" : 12
  } whose BookingId is max and JobCode is 12.

How to do it in angular 6

tried code

```<code>var a = this.GridSource.find(x => x.JobCode == 12 &&
x.BookingId == Math.max.apply(Math, this.GridSource.map
(function(o) { return o.BookingId; })));
</code>```

答:
You can use reduce for this. I did an example below, hope this helps. If were are no items that meet conditions, then result of reduce will be null

Also, don't forget about the types :)

```<code>interface GridItem {
  BookingId: number;
  BookingDetailId: number;
  JobCode: number;
}

const GridSource: GridItem[] = [
  {
    BookingId: 366024,
    BookingDetailId: 340708,
    JobCode: 13
  },
  {
    BookingId: 366023,
    BookingDetailId: 340707,
    JobCode: 12
  },
  {
    BookingId: 366022,
    BookingDetailId: 340706,
    JobCode: 12
  }
];

const foundGridItem: GridItem = GridSource.reduce(
  (result: GridItem, value: GridItem) =>
    value.JobCode === 12 &&
    (result === null || value.BookingId > result.BookingId)
      ? value
      : result,
  null
);
</code>```

Body:
Hi Below is the JSON array of ojects

[
  {
    "BookingId": 366024,
    "BookingDetailId": 340708,
    "JobCode" : 13
  },
  {
    "BookingId": 366023,
    "BookingDetailId": 340707,
    "JobCode" : 12
  },
  {
    "BookingId": 366022,
    "BookingDetailId": 340706,
    "JobCode" : 12
   }
]

I want to get particular array object where BookingId is Max where JobCode is 12, for eg. In above array I want object {
    "BookingId": 366023,
    "BookingDetailId": 340707,
    "JobCode" : 12
  } whose BookingId is max and JobCode is 12.

How to do it in angular 6

tried code

var a = this.GridSource.find(x => x.JobCode == 12 &&
x.BookingId == Math.max.apply(Math, this.GridSource.map
(function(o) { return o.BookingId; })));

Body:
You can use reduce for this. I did an example below, hope this helps. If were are no items that meet conditions, then result of reduce will be null

Also, don't forget about the types :)

interface GridItem {
  BookingId: number;
  BookingDetailId: number;
  JobCode: number;
}

const GridSource: GridItem[] = [
  {
    BookingId: 366024,
    BookingDetailId: 340708,
    JobCode: 13
  },
  {
    BookingId: 366023,
    BookingDetailId: 340707,
    JobCode: 12
  },
  {
    BookingId: 366022,
    BookingDetailId: 340706,
    JobCode: 12
  }
];

const foundGridItem: GridItem = GridSource.reduce(
  (result: GridItem, value: GridItem) =>
    value.JobCode === 12 &&
    (result === null || value.BookingId > result.BookingId)
      ? value
      : result,
  null
);


问:
Survey Monkey API: /collectors/{id}/responses/bulk?start_created_at= Returns a Bad Request Error
I'm using python 3.6.4. Trying to retrieve data from Survey Monkey API using the following:

```<code>access_token = 'xxx'
collector_id = 'yyy'

s = requests.session()
s.headers.update({
                  "Authorization": "Bearer %s" % access_token,
                  "Content-Type": "application/json"
                })
url = "https://api.surveymonkey.com/v3/collectors/%s/responses/bulk?start_created_at=2020-
02-11T23:20:00+00:00" % (collector_id)
res = s.get(url)
dat = res.json()
</code>```

Unfortunately this leads to the following error:

```<code>{'error': {'id': '1003',
'name': 'Bad Request',
'docs': 'https://developer.surveymonkey.com/api/v3/#error-codes',
'message': 'Invalid URL parameters.',
'http_status_code': 400}}
</code>```

I found a post that addresses the same issue as here but the solutions provided there didn't work for me. Here is the post:
start_created_at not working with /collectors/{id}/responses

Can someone point me in the right direction regarding how I can format the query string so that my URL parameter I'd like to filter by is valid?

答:
You need to URL encode only the date/time portion of the URL. Try this:</p>

```<code>timedate = '2020-02-11T23:20:00+00:00'
timedate_enc = urllib.parse.quote(timedate)
url = 'https://api.surveymonkey.com/v3/collectors/%s/responses/bulk?start_created_at=%s' % (collector_id, timedate_enc)
</code>```

Body:
I'm using python 3.6.4. Trying to retrieve data from Survey Monkey API using the following:

access_token = 'xxx'
collector_id = 'yyy'

s = requests.session()
s.headers.update({
                  "Authorization": "Bearer %s" % access_token,
                  "Content-Type": "application/json"
                })
url = "https://api.surveymonkey.com/v3/collectors/%s/responses/bulk?start_created_at=2020-
02-11T23:20:00+00:00" % (collector_id)
res = s.get(url)
dat = res.json()

Unfortunately this leads to the following error:

{'error': {'id': '1003',
'name': 'Bad Request',
'docs': 'https://developer.surveymonkey.com/api/v3/#error-codes',
'message': 'Invalid URL parameters.',
'http_status_code': 400}}

I found a post that addresses the same issue as here but the solutions provided there didn't work for me. Here is the post:
start_created_at not working with /collectors/{id}/responses

Can someone point me in the right direction regarding how I can format the query string so that my URL parameter I'd like to filter by is valid?

Body:
You need to URL encode only the date/time portion of the URL. Try this:

timedate = '2020-02-11T23:20:00+00:00'
timedate_enc = urllib.parse.quote(timedate)
url = 'https://api.surveymonkey.com/v3/collectors/%s/responses/bulk?start_created_at=%s' % (collector_id, timedate_enc)


问:
How to sort lines by sed value?
I have multiple urls in a file like this:

```<code>https://private/report-artifact/dsop-pipeline-artifacts/container-scan-reports/anchore/enterprise/enterprise/0.6.1/2020-02-08T004236.092_2801/enterprise-0.6.1.tar
https://private/report-artifact/dsop-pipeline-artifacts/container-scan-reports/atlassian/bamboo-data-center/bamboo-agent/6.10.4/2019-12-17T185400.126_2118/bambo.tar
...
</code>```

I want to them to be sorted A-Z according to the last value, ie:

```<code>https://private/report-artifact/dsop-pipeline-artifacts/container-scan-reports/atlassian/bamboo-data-center/bamboo-agent/6.10.4/2019-12-17T185400.126_2118/bambo.tar
https://private/report-artifact/dsop-pipeline-artifacts/container-scan-reports/anchore/enterprise/enterprise/0.6.1/2020-02-08T004236.092_2801/enterprise-0.6.1.tar
...

</code>```

I can get the sed value of the last parameter with
sed 's|.*/||' , which gives me the A-Z pattern I am looking for:

```<code>bambo.tar
enterprise-0.6.1.tar
</code>```

But not sure how I can "sort" the entire url line like I want?

答:
Duplicate the filename as an additional field, sort by that field, then remove the extra field.</p>

```<code>sed 's/[^/]*$/& &/' | sort -k 2 | cut -d' ' -f1
</code>```

Title: How to sort lines by sed value?

Body:
I have multiple urls in a file like this:

https://private/report-artifact/dsop-pipeline-artifacts/container-scan-reports/anchore/enterprise/enterprise/0.6.1/2020-02-08T004236.092_2801/enterprise-0.6.1.tar
https://private/report-artifact/dsop-pipeline-artifacts/container-scan-reports/atlassian/bamboo-data-center/bamboo-agent/6.10.4/2019-12-17T185400.126_2118/bambo.tar
...

I want to them to be sorted A-Z according to the last value, ie:

https://private/report-artifact/dsop-pipeline-artifacts/container-scan-reports/atlassian/bamboo-data-center/bamboo-agent/6.10.4/2019-12-17T185400.126_2118/bambo.tar
https://private/report-artifact/dsop-pipeline-artifacts/container-scan-reports/anchore/enterprise/enterprise/0.6.1/2020-02-08T004236.092_2801/enterprise-0.6.1.tar
...

I can get the sed value of the last parameter with
sed 's|.*/||' , which gives me the A-Z pattern I am looking for:

bambo.tar
enterprise-0.6.1.tar

But not sure how I can "sort" the entire url line like I want?

Body:
Duplicate the filename as an additional field, sort by that field, then remove the extra field.

sed 's/[^/]*$/& &/' | sort -k 2 | cut -d' ' -f1


问:
How to use draggable sections like on iGoogle?
When viewing iGoogle, each section is able to be drag-and-dropped to anywhere else on the page and then the state of the page is saved. I am curious on how this is done as I would like to provide this functionality as part of a proof of concept?

UPDATE

How do you make it so that the layout you changed to is saved for the next load? I am going to guess this is some sort of cookie?

答: One method not mentioned here is that starting with ASP.NET in the 2.0 framework, Microsoft unveiled something called WebParts which enabled the building of controls which could be dragged and placed in the same way. This was supposed to be an easy method for users to create their own Web 2.0 style portals.</p>

OwnerDisplayName: Ascalonian

OwnerDisplayName: TheTXI

ContentLicense: CC BY-SA 2.5


问:
In Java, is better maintain data in the ResultSet or transform to array?
I have two classes, a server and some clients. The server class make a query to database and retrieve a certain number of rows. The clients request a part of these rows, each one a different part.

In the server class, is better I maintain the result of the query in the ResultSet and transforming in a array of objects when the client class make the request or transforming all in a array of objects and sending him partially when the request occur?

I think that maintain in the ResultSet is more easier to do and control.

答:
Actually I'm not sure if I understood your approach. In typical client/server scenarios with persistance layers, a client (1) calls remote method, this (2) triggers a database operation and the service (3) responds with the requested objects.

In your scenario, it looks like the server reads data from a database, caches it and waits for clients to request chunks.

If I got it right, and the server is caching database objects, then it should transform the data from the result set in objects, I'd prefer a collection or a map to store the "rows". A result set is a rather fragile data structure - like some result sets don't support re-reading of set entries (= you can't iterate twice). I'd always take the data from the set and close it as soon as possible.


问:
shouldInterceptRequest() method is not calling for all the resources
I have implemented webviewclient in my code for accessing some html content in my android code. I have given condition in shouldInterceptRequest() method to get the call of mp3 file so that i can change it on runtime. on the first day it was implemented successfully but now the method is  never calling that mp3 files i haven't changed the code yet but still I am not getting where i am doing wrong

My Html file is stored in local for now i have stored it manually but it will be downloaded from php server. My Implemented WebView Client is below

```<code>    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            MSLogger.msLogD("initSleave", "WebViewClient: " + url + "\nview: " + view);
            view.loadUrl(url);
            return true;
        }

        @Nullable
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String request) {
            if (request.contains(".mp3")) {
                if (prefs.getLanguage().equalsIgnoreCase("Hi")) {
                    try {
                   request= request.replace(".mp3", "_hindi.mp3");
                    request=request.replace("file://","");
                        return new WebResourceResponse("audio/mp3", "UTF-8", new FileInputStream(request));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Log.d("RequestView", "----->" + request);
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Nullable
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            Log.d("RequestView", "----->" + request);
            return super.shouldInterceptRequest(view, request);
        }
    });
</code>```

I want when the webclient will call mp3 resource file mentioned in my Sleave(Html) content. But its only calling all png, ttf,css and xmls now

答:
The MIME type parameter for .mp3 should be changed to audio/mpeg

doc: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types

=O

Body:
I have implemented webviewclient in my code for accessing some html content in my android code. I have given condition in shouldInterceptRequest() method to get the call of mp3 file so that i can change it on runtime. on the first day it was implemented successfully but now the method is  never calling that mp3 files i haven't changed the code yet but still I am not getting where i am doing wrong

My Html file is stored in local for now i have stored it manually but it will be downloaded from php server. My Implemented WebView Client is below

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            MSLogger.msLogD("initSleave", "WebViewClient: " + url + "\nview: " + view);
            view.loadUrl(url);
            return true;
        }

        @Nullable
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String request) {
            if (request.contains(".mp3")) {
                if (prefs.getLanguage().equalsIgnoreCase("Hi")) {
                    try {
                   request= request.replace(".mp3", "_hindi.mp3");
                    request=request.replace("file://","");
                        return new WebResourceResponse("audio/mp3", "UTF-8", new FileInputStream(request));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Log.d("RequestView", "----->" + request);
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Nullable
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            Log.d("RequestView", "----->" + request);
            return super.shouldInterceptRequest(view, request);
        }
    });

I want when the webclient will call mp3 resource file mentioned in my Sleave(Html) content. But its only calling all png, ttf,css and xmls now


问:
Disable access logs per-container in Traefik
We have a very chatty container that is quickly filling the Traefik access logs.

Is there a label which we can apply which will instruct Traefik to not log access for a specific container?

答:
I had this issue as well, and my solution was to send all output to fluentd and then drop lines matching certain criteria. Note that depending on the volume of logs you might consider shipping to a separate machine.

Also, this request seems a good candidate for a feature request.


答:
You can make use of reduce to find the max element and then using it in find.</p>

```<code>var max = array.reduce(function(prev, curr) {
    return prev['BookingId'] > curr['BookingId'] ? prev : curr;
});

var elem = array.find(x => x['JobCode'] == 12 && x['BookingId'] == max['BookingId']);
</code>```

Title: How to find the object in an array where particular object value is max

Body:
You can make use of reduce to find the max element and then using it in find.

var max = array.reduce(function(prev, curr) {
    return prev['BookingId'] > curr['BookingId'] ? prev : curr;
});

var elem = array.find(x => x['JobCode'] == 12 && x['BookingId'] == max['BookingId']);


问:
Simplify EF connection string?
```<code><add name="DemoModelContainer" connectionString="metadata=res://*/DataModel.Demo.csdl|res://*/DataModel.Demo.ssdl|res://*/DataModel.Demo.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\sqlexpress;Initial Catalog=DemoDev;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</code>```

This is just a connection string when I use EF4 in the project. It's ridiculous long. Is there any way to simplify this? To make it short and simple.

答:
You can use just:

```<code><connectionString="metadata=res://*;provider=...
</code>```

to omit specifying of csdl, ssdl, msl names.

Title: Simplify EF connection string?

Body:
<add name="DemoModelContainer" connectionString="metadata=res://*/DataModel.Demo.csdl|res://*/DataModel.Demo.ssdl|res://*/DataModel.Demo.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\sqlexpress;Initial Catalog=DemoDev;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />

This is just a connection string when I use EF4 in the project. It's ridiculous long. Is there any way to simplify this? To make it short and simple.

Body:
You can use just:

<connectionString="metadata=res://*;provider=...

to omit specifying of csdl, ssdl, msl names.


问:
How to copy multiple (specific) selected sheets to new workbook
I have searched for hours but with no luck.
I want to copy multiple sheets from a file to a new workbook.  Not all sheets but just the ones that I have selected. My selection could be different each time I perform this exercise. The scenario is that I have a master reporting file with say 25 sheets each with a different report. I want to open the file and select reports to send to a user.  I will select say 5 specific reports e.g. sheets 1,10,15,18 and 20 I then want to copy them to a new workbook so I can email them to my customer. Ideally I would paste them into new workbook at values only to remove all formulas and links from reports being sent to customer. The following code works great for a single sheet:

```<code>ThisWorkbook.ActiveSheet.Copy _
Before:=Workbooks.Add.Worksheets(1)
</code>```

What I would like to do is to change the word 'ActiveSheet' to 'SelectedSheets' and keep all else the same.  This does not work. Am I missing something simple?

I have tried to:
a: change code as above
b: record a macro copying selected sheets and using the code (but it provides code for specific sheet names such as sheet2 and sheet3.  This will not work as I need to it be code that works with whatever sheets I select.
c: searched internet for hours. Generally provides as advice on working with all sheets, working with a pre-defined set of selected sheets, working with pre-defined selection using arrays, code to select sheets based on common characteristics e.g. select all sheets with name "R1" in it.

答:
If you know the sheet numbers of what you want to copy (Which it seems you do from your post) you can simply copy them which will create a new book:

```<code>Sheets(array(1,3,5)).copy
</code>```

This will copy sheets 1, 3 and 5 to a new workbook.

Alternatively if you want to select them first then run the macro this code will copy them to a new book:

```<code>Activeworkbook.Windows(1).SelectedSheets.copy
</code>```

Then you can loop through the sheets in the new workbook like this:

```<code>Dim WS as worksheet
For each WS in worksheets
    cells.copy
    range("A1").PasteSpecial xlPasteValues
next
</code>```

This will copy then paste as value everything on each sheet.

I note you said in your comments that using Activeworkbook.Windows(1).SelectedSheets will do all sheets but it doesn't. I just created a new workbook, added 5 sheets, selected 1, 3 and 5 and ran this code, the resulting workbook was a new workbook with 3 sheets, Sheet1, Sheet3 and Sheet5.

Body:
I have searched for hours but with no luck.
I want to copy multiple sheets from a file to a new workbook.  Not all sheets but just the ones that I have selected. My selection could be different each time I perform this exercise. The scenario is that I have a master reporting file with say 25 sheets each with a different report. I want to open the file and select reports to send to a user.  I will select say 5 specific reports e.g. sheets 1,10,15,18 and 20 I then want to copy them to a new workbook so I can email them to my customer. Ideally I would paste them into new workbook at values only to remove all formulas and links from reports being sent to customer. The following code works great for a single sheet:

ThisWorkbook.ActiveSheet.Copy _
Before:=Workbooks.Add.Worksheets(1)

What I would like to do is to change the word 'ActiveSheet' to 'SelectedSheets' and keep all else the same.  This does not work. Am I missing something simple?

I have tried to:
a: change code as above
b: record a macro copying selected sheets and using the code (but it provides code for specific sheet names such as sheet2 and sheet3.  This will not work as I need to it be code that works with whatever sheets I select.
c: searched internet for hours. Generally provides as advice on working with all sheets, working with a pre-defined set of selected sheets, working with pre-defined selection using arrays, code to select sheets based on common characteristics e.g. select all sheets with name "R1" in it.

Body:
If you know the sheet numbers of what you want to copy (Which it seems you do from your post) you can simply copy them which will create a new book:

Sheets(array(1,3,5)).copy

This will copy sheets 1, 3 and 5 to a new workbook.

Alternatively if you want to select them first then run the macro this code will copy them to a new book:

Activeworkbook.Windows(1).SelectedSheets.copy

Then you can loop through the sheets in the new workbook like this:

Dim WS as worksheet
For each WS in worksheets
    cells.copy
    range("A1").PasteSpecial xlPasteValues
next

This will copy then paste as value everything on each sheet.

I note you said in your comments that using Activeworkbook.Windows(1).SelectedSheets will do all sheets but it doesn't. I just created a new workbook, added 5 sheets, selected 1, 3 and 5 and ran this code, the resulting workbook was a new workbook with 3 sheets, Sheet1, Sheet3 and Sheet5.


问:
How do I use comparison symbols with input in python
I'm trying to make a program that will respond to someones age but I can't figure out how to use the comparison symbols. Here is the code I'm trying to run,

```<code>age = input('How old are you? \n >>')
if (age < 20):
    print('Hey you are pretty young.')
if (age > 20):
    print('wow you are pretty old')
</code>```

But when I try to run this I get this Error,

```<code>Traceback (most recent call last):
  File "C:/Users/Daniel/Desktop/Computer science/week 6/age.py", line 2, in <module>
    if (age < 20):
TypeError: '<' not supported between instances of 'str' and 'int'
</code>```

答:
What you get as input is a string, you need to cast it to an int before you can compare it:

```<code>age = int(input('How old are you? \n >>'))
</code>```

Better yet, add some error handling, e.g.:

```<code>try:
    age = int(input('How old are you? \n >>'))

except ValueError as ex:
    print("Not a valid age.")
</code>```

Body:
I'm trying to make a program that will respond to someones age but I can't figure out how to use the comparison symbols. Here is the code I'm trying to run,

age = input('How old are you? \n >>')
if (age < 20):
    print('Hey you are pretty young.')
if (age > 20):
    print('wow you are pretty old')

But when I try to run this I get this Error,

Traceback (most recent call last):
  File "C:/Users/Daniel/Desktop/Computer science/week 6/age.py", line 2, in <module>
    if (age < 20):
TypeError: '<' not supported between instances of 'str' and 'int'

Body:
What you get as input is a string, you need to cast it to an int before you can compare it:

age = int(input('How old are you? \n >>'))

Better yet, add some error handling, e.g.:

try:
    age = int(input('How old are you? \n >>'))

except ValueError as ex:
    print("Not a valid age.")


问:
get count from multiple tables
I have 3 tables with a common 'type_id' column. its a foreign key from Table_type

Table_1 id,type_id,date...
Table_2 id,type_id,date...
Table_3 id,type_id,date...

Table_Type  id, type_name, description

select type_id, count(*) from Table_1 GROUP BY type_id

gives the count from individual table.

i want to know how many times is a particular type used.

```
type_id, count(from 3 tables)
1      , 10
2      , 5
3 .    , 3
```

答:
Use union all and group by:

```<code>select type_id, count(*)
from ((select type_id from table_1) union all
      (select type_id from table_2) union all
      (select type_id from table_3)
     ) t
group by type_id
</code>```

Title: get count from multiple tables

Body:
I have 3 tables with a common 'type_id' column. its a foreign key from Table_type

Table_1 id,type_id,date...
Table_2 id,type_id,date...
Table_3 id,type_id,date...

Table_Type  id, type_name, description

select type_id, count(*) from Table_1 GROUP BY type_id

gives the count from individual table.

i want to know how many times is a particular type used.

type_id, count(from 3 tables)
1      , 10
2      , 5
3 .    , 3

Body:
Use union all and group by:

select type_id, count(*)
from ((select type_id from table_1) union all
      (select type_id from table_2) union all
      (select type_id from table_3)
     ) t
group by type_id