问:
C++ language design: child calls all virtual ancestor constructors
This question's content hinges upon my understanding of how virtual inheritance works in C++. Correct me if any of this is wrong.

In C++, virtual inheritance requires (either implicit or explicit) calls to the constructors of all ancestor classes in a subclass, which also prevents any ancestor from calling another ancestor's constructor. In other words:

```<code>class Grandparent{
public:
    Grandparent(string const& message) {
        std::cerr << "Grandparent says " << message << '\n';
    }
};

class Parent : virtual Grandparent{
public:
    Parent(string const& message)
        : Grandparent(string("hello parent. Parent says ") + message)
    {}
}

class Child : virtual Parent{
public:
    Child(void)
        : Grandparent(""), // Required, since Grandparent has no default ctor
          Parent("hello child. Child says are we there yet"?)
    {}
}
</code>```

In this example, constructing an instance of Child should simply print out "Grandparent says\n" to standard error, since the Parent constructor's call to the Grandparent constructor gets removed. In other words, the "effective" Parent constructor that gets executed by the child looks like this:

```<code>Parent(string const& message) {}
</code>```

But this seems counterintuitive and problematic. Why should the child class have to explicitly call the grandparent's constructor when the parent already does that? I'm aware of the diamond problem, it doesn't apply here because the child class has only one direct parent. The language guarantees that the parent already calls its grandparent's constructor, so why should this task be delegated to the child?

Furthermore, the erasure of the parent's calls to the grandparent constructor hinders the effectiveness of inheritance. The child must duplicate some of the parent's initialization code if it wants to truly inherit the parent's behavior. For example:

```<code>Parent::Parent(string const& msg)
    : Grandparent(some_parent_logic(msg))
    {}
Child::Child(string const& msg)
    : Parent("doesn't matter anymore"),
      GrandParent(some_child_logic(some_parent_logic(msg))) // Can't inherit implicit use of parent logic
</code>```

This isn't a huge problem if you don't use complicated logic when making calls to ancestor constructors, but the redundancy problem tends to grow as the inheritance chain grows longer. And it seems a tad blasphemous (from an OO perspective) for the child to be required to manually address all of its ancestors when only inheriting directly from one of them.

I suppose what I'm asking at the end of the day is:

Is there any reason the language can't delegate ancestor initialization to the parent when there is only one parent?

Why doesn't the language allow delegation of ancestor constructors? e.g. Child::Child(void): Parent1(), Parent2() {} causes Parent1 to initialize Grandparent, while Child::Child(void): Parent2(), Parent1() {} causes Parent2 to initialize Grandparent, while Child::Child(void): Grandparent("The child overrides."), Parent1(), Parent2() explicitly initializes Grandparent.

Are there any plans floating around the Standards Committee regarding changes to C++ virtual inheritance in future versions?

答:
Perhaps the language designers could have done better (honestly, I have only found a couple cases where virtual inheritance made sense in 15 years of c++ development), but the rule we have simply requires that the most derived class construct the virtually inherited base. It does make some sense in that it is only when the most-derived type is constructed that we actually know where the virtual base is going to 'live'.

Any rule that a type other than the most-derived would construct the virtual base would make an already complicated business quite a bit more so.

Body:
This question's content hinges upon my understanding of how virtual inheritance works in C++. Correct me if any of this is wrong.

In C++, virtual inheritance requires (either implicit or explicit) calls to the constructors of all ancestor classes in a subclass, which also prevents any ancestor from calling another ancestor's constructor. In other words:

class Grandparent{
public:
    Grandparent(string const& message) {
        std::cerr << "Grandparent says " << message << '\n';
    }
};

class Parent : virtual Grandparent{
public:
    Parent(string const& message)
        : Grandparent(string("hello parent. Parent says ") + message)
    {}
}

class Child : virtual Parent{
public:
    Child(void)
        : Grandparent(""), // Required, since Grandparent has no default ctor
          Parent("hello child. Child says are we there yet"?)
    {}
}

In this example, constructing an instance of Child should simply print out "Grandparent says\n" to standard error, since the Parent constructor's call to the Grandparent constructor gets removed. In other words, the "effective" Parent constructor that gets executed by the child looks like this:

Parent(string const& message) {}

But this seems counterintuitive and problematic. Why should the child class have to explicitly call the grandparent's constructor when the parent already does that? I'm aware of the diamond problem, it doesn't apply here because the child class has only one direct parent. The language guarantees that the parent already calls its grandparent's constructor, so why should this task be delegated to the child?

Furthermore, the erasure of the parent's calls to the grandparent constructor hinders the effectiveness of inheritance. The child must duplicate some of the parent's initialization code if it wants to truly inherit the parent's behavior. For example:

Parent::Parent(string const& msg)
    : Grandparent(some_parent_logic(msg))
    {}
Child::Child(string const& msg)
    : Parent("doesn't matter anymore"),
      GrandParent(some_child_logic(some_parent_logic(msg))) // Can't inherit implicit use of parent logic

This isn't a huge problem if you don't use complicated logic when making calls to ancestor constructors, but the redundancy problem tends to grow as the inheritance chain grows longer. And it seems a tad blasphemous (from an OO perspective) for the child to be required to manually address all of its ancestors when only inheriting directly from one of them.

I suppose what I'm asking at the end of the day is:

Is there any reason the language can't delegate ancestor initialization to the parent when there is only one parent?

Why doesn't the language allow delegation of ancestor constructors? e.g. Child::Child(void): Parent1(), Parent2() {} causes Parent1 to initialize Grandparent, while Child::Child(void): Parent2(), Parent1() {} causes Parent2 to initialize Grandparent, while Child::Child(void): Grandparent("The child overrides."), Parent1(), Parent2() explicitly initializes Grandparent.

Are there any plans floating around the Standards Committee regarding changes to C++ virtual inheritance in future versions?


来源: stackexchange

问:
laravel excel getting only current data
I just started using this excel pakage maatwebsite/excel and I manage to download the excel out. But when creating the excel I run into some difficulties

How can I change the date format printed out in excel? I saw people using something like this but why can't mine work?

$sheet->setColumnFormat(array('E' => 'd/m/y'));

How to get data that are from today? For example, I have entered some data and save into database and when I download the excel it will only show that data and not the past data. How do I do that?

Is it possible to change the title of the excel? For example created_at change to Date

Currently here is my code:

```<code> public function downloadExcel($type)
    {

        $data = personal_info::join('qualifications', 'qualifications.user_id', '=', 'personal_infos.id')
        ->select(
          'personal_infos.id',
          'personal_infos.name',
          'personal_infos.email',
          'qualifications.qualification',
          'personal_infos.created_at')
        ->get()
        ->sortByDesc('created_at');
        return Excel::create('test', function($excel) use ($data) {
            $excel->sheet('mySheet', function($sheet) use ($data)
            {
                $sheet->fromArray($data);
                $sheet->setColumnFormat(array('E' => 'd/m/y'));
            });
        })->download($type);
    }
</code>```

答:
If you want today data then add where condition in your query like that :-

```<code>$todaydate = date('Y-m-d');
$data = personal_info::join('qualifications', 'qualifications.user_id', '=', 'personal_infos.id')
    ->select(
      'personal_infos.id',
      'personal_infos.name',
      'personal_infos.email',
      'qualifications.qualification',
      'personal_infos.created_at')
    ->where('personal_infos.created_at',$todaydate) // or you can use whereDate() of laravel like :- whereDate('personal_infos.created_at', '=', date('Y-m-d'));
    ->get();
</code>```

Yes it is possible to change created_at to Date you need to give alias like that :-

```<code>enter code here
$data = personal_info::join('qualifications', 'qualifications.user_id', '=', 'personal_infos.id')
    ->select(
      'personal_infos.id',
      'personal_infos.name',
      'personal_infos.email',
      'qualifications.qualification',
      'personal_infos.created_at as Date') //here you can change the name
     ->where('Date',$todaydate) // then you need to change in where condition also
     ->get();
</code>```

Hope it helps you!

ContentLicense: CC BY-SA 3.0

Title: laravel excel getting only current data

Body:
I just started using this excel pakage maatwebsite/excel and I manage to download the excel out. But when creating the excel I run into some difficulties

How can I change the date format printed out in excel? I saw people using something like this but why can't mine work?

$sheet->setColumnFormat(array('E' => 'd/m/y'));

How to get data that are from today? For example, I have entered some data and save into database and when I download the excel it will only show that data and not the past data. How do I do that?

Is it possible to change the title of the excel? For example created_at change to Date

Currently here is my code:

 public function downloadExcel($type)
    {

        $data = personal_info::join('qualifications', 'qualifications.user_id', '=', 'personal_infos.id')
        ->select(
          'personal_infos.id',
          'personal_infos.name',
          'personal_infos.email',
          'qualifications.qualification',
          'personal_infos.created_at')
        ->get()
        ->sortByDesc('created_at');
        return Excel::create('test', function($excel) use ($data) {
            $excel->sheet('mySheet', function($sheet) use ($data)
            {
                $sheet->fromArray($data);
                $sheet->setColumnFormat(array('E' => 'd/m/y'));
            });
        })->download($type);
    }

Body:
If you want today data then add where condition in your query like that :-

$todaydate = date('Y-m-d');
$data = personal_info::join('qualifications', 'qualifications.user_id', '=', 'personal_infos.id')
    ->select(
      'personal_infos.id',
      'personal_infos.name',
      'personal_infos.email',
      'qualifications.qualification',
      'personal_infos.created_at')
    ->where('personal_infos.created_at',$todaydate) // or you can use whereDate() of laravel like :- whereDate('personal_infos.created_at', '=', date('Y-m-d'));
    ->get();

Yes it is possible to change created_at to Date you need to give alias like that :-

enter code here
$data = personal_info::join('qualifications', 'qualifications.user_id', '=', 'personal_infos.id')
    ->select(
      'personal_infos.id',
      'personal_infos.name',
      'personal_infos.email',
      'qualifications.qualification',
      'personal_infos.created_at as Date') //here you can change the name
     ->where('Date',$todaydate) // then you need to change in where condition also
     ->get();

Hope it helps you!


问:
Include check value of bean in struts jsp file
I have an iterator in my jsp defined like so -

```<code><s:iterator value="eventList" var="event">
</code>```

How can I check the value of eventList ?

Something like -

```<code>if(eventList.size > 0){

}
</code>```

Thanks

答:
```<code><s:if test="eventList.size() > 0">
</s:if>
</code>```

Body:
I have an iterator in my jsp defined like so -

<s:iterator value="eventList" var="event">

How can I check the value of eventList ?

Something like -

if(eventList.size > 0){

}

Thanks

ContentLicense: CC BY-SA 2.5


问:
Why this strange behavior in python instance creation with array property happened?

I was working on my project and encountered this strange behavior. The following code shows how to reproduce it.

```<code>class TestClass:
    def __init__(self, arr=[]):
        self.arr = arr

if __name__ == '__main__':
    for i in range(3):
        test = TestClass()
        test.arr.append('x')
        print(test.arr)
</code>```

I would expect the following output:

```<code>['x']
['x']
['x']
</code>```

since new TestClass instance is created inside the loop. But instead, I got:

```<code>['x']
['x', 'x']
['x', 'x', 'x']
</code>```

Did I misunderstand something?

python --version output:

```<code>Python 3.6.3 :: Anaconda, Inc.
</code>```

答:
A default value in Python is not reassigned everytime the function is called, it is assigned once and everytime you call the function you will access the same object. Thus if your default value is a mutable object such as a list or a dict, it can be mutated every call.

The common way around this is to do the following:

```<code>class TestClass:
    def __init__(self, arr=None):
        self.arr = [] if arr is None else arr
</code>```

Body:
I was working on my project and encountered this strange behavior. The following code shows how to reproduce it.

class TestClass:
    def __init__(self, arr=[]):
        self.arr = arr

if __name__ == '__main__':
    for i in range(3):
        test = TestClass()
        test.arr.append('x')
        print(test.arr)

I would expect the following output:

['x']
['x']
['x']

since new TestClass instance is created inside the loop. But instead, I got:

['x']
['x', 'x']
['x', 'x', 'x']

Did I misunderstand something?

python --version output:

Python 3.6.3 :: Anaconda, Inc.

Body:
A default value in Python is not reassigned everytime the function is called, it is assigned once and everytime you call the function you will access the same object. Thus if your default value is a mutable object such as a list or a dict, it can be mutated every call.

The common way around this is to do the following:

class TestClass:
    def __init__(self, arr=None):
        self.arr = [] if arr is None else arr

ContentLicense: CC BY-SA 4.0


问:
Grand Central Dispatch async vs sync
I'm reading the docs on dispatch queues for GCD, and in it they say that the queues are FIFO, so I am woundering what effect this has on async / sync dispatches?

from my understand async executes things in the order that it gets things while sync executes things serial..

but when you write your GCD code you decide the order in which things happen.. so as long as your know whats going on in your code you should know the order in which things execute..

my questions are, wheres the benefit of async here? am I missing something in my understanding of these two things.

答:
Tasks can be performed synchronously or asynchronously.

Synchronous function returns the control on the current queue only after task is finished. It blocks the queue and waits until the task is finished.

Asynchronous function returns control on the current queue right after task has been sent to be performed on the different queue. It doesn't wait until the task is finished. It doesn't block the queue.

Only in Asynchronous we can add delay -> asyncAfter(deadline: 10..

Title: Grand Central Dispatch async vs sync


问:
Is there a way to align scrolling text around an image?
I am looking to align my text with this skewed image, but the problem is the text is scrolling. Is there a way to combat this or no?

My goal is to keep the bolded "TITLE HERE" straight across the image but the placeholder text to continue to scroll, but aligning it with the large image to the left. Is this possible? Thanks for your help in advance.

      /*BODY STUFF HERE*/

body {
  background: WHITE;
  background-attachment: fixed;
  font-family: montserrat;
}

a {
  text-decoration: none;
  color: #999;
}

a:hover {
  color: indianred;
}

.title {
  font-family: montserrat;
  font-weight: 900;
  font-size: 6vw;
  position: relative;
  width: 90%;
  left: 200px;
  margin-top: 0%;
}

.title2 {
  font-family: montserrat;
  font-weight: 900;
  font-size: 1.10vw;
  position: static;
  width: 90%;
  margin-left: 45%;
}

.scrollingtext p {
  width: 100%;
  padding: 0 10%;
  font-size: 13px;
}

/*LEFT PROFILE IMAGE HERE*/

.image {
  z-index: -1;
}

.image img {
  position: fixed;
  width: 50%;
  left: -3.5%;
  z-index: -1;
  -webkit-clip-path: polygon(25% 0%, 100% 0%, 71% 100%, 0% 100%);
  clip-path: polygon(25% 0%, 100% 0%, 71% 100%, 0% 100%);
}

/*CELL TABLE STUFF*/

.tablerow {
  display: table-row;
  width: 100%;
}

.table {
  display: table;
}

.cell {
  display: table-cell;
}

.right {
  width: 50%;
}

.left {
  width: 40%;
}

.mobile {
  display: none;
}

@media screen and (max-width: 1024px) {
  .image img {
    width: 100%;
    position: relative;
    padding: px 5% 0;
    margin: 0;
    top: 0;
    left: 0;
  }
  h1 {
    color: #000;
    letter-spacing: normal;
    width: 95%;
    margin-top: 0;
    padding: 0;
    margin: 0;
    font-size: 70PX;
    text-align: center;
    font-style: montserrat;
  }
  .title {
    display: none;
  }
  .cell {
    display: block;
  }
  .desktop {
    display: none;
  }
  .mobile {
    display: inherit;
    text-align: center;
  }
  .right {
    width: 80%;
    margin: 0;
  }
  .farright {
    width: 0;
  }
  #logo {
    height: 25px;
    position: absolute;
  }
  .story {
    color: #FFF;
    font-family: playfair display;
    width: 100%;
    height: 200px;
    text-shadow: 2px 2px 5px #000;
    background-color: #292929;
    display: table;
  }
  .story_inside {
    vertical-align: middle;
    display: table-cell;
  }
  .story h2 {
    font-size: 40px;
    width: 60%;
    padding: 0 15%;
    margin: 0;
    line-height: 35px;
  }
  .story p {
    font-family: montserrat;
    margin: 0;
    width: 70%;
    padding: 10px 15% 0 15%;
  }
  @media screen and (max-width: 400px) {
    h1 {
      color: #000;
      letter-spacing: normal;
      width: 95%;
      margin-top: 0;
      padding: 0;
      margin: 0;
      font-size: 40px;
      text-align: center;
      font-style: montserrat;
    }
    @media screen and (max-width: 1030px) {
      .byline {
        font-size: 16px;
        width: 100%;
        right: 451%;
        float: left;
        position: relative;
        width: 300%;
        bottom: -150px;
      }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--IMAGE GOES HERE-->
<div class="image">
  <img src="http://via.placeholder.com/350x1150">
</div>

<div class="scrollingtext">

  <!--DESKTOP TITLE AND BYLINE HERE-->
  <div class="title">TITLE HERE
    <p>
  </div>

  <div class="title2"><strong>AUTHOR HERE</strong> / TITLE</div>
  <!--MOBILE TITLE HERE-->
  <div class="table">
    <div class="tablerow">
      <div class="cell left desktop"></div>

      <!--DESKTOP TITLE AND BYLINE HERE-->
      <div class="title">
      </div>

      <div class="cell farright"></div>

    </div>

    <div class="tablerow">

      <div class="cell left desktop">
      </div>

      <div class="cell right">

        <!-- BODY TEXT GOES BELOW HERE -->
        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example.</p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

        <p>This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. </p>

      </div>
    </div>
  </div>
</div></code>```

答:
Just addd this css to fix the Title</p>

```<code>.title{font-family: montserrat;
font-weight: 900;
font-size: 6vw;
width: 90%;
position: fixed;
top: 50%;
left: 10%;}
</code>```

Body:
I am looking to align my text with this skewed image, but the problem is the text is scrolling. Is there a way to combat this or no?

My goal is to keep the bolded "TITLE HERE" straight across the image but the placeholder text to continue to scroll, but aligning it with the large image to the left. Is this possible? Thanks for your help in advance.

      /*BODY STUFF HERE*/

body {
  background: WHITE;
  background-attachment: fixed;
  font-family: montserrat;
}

a {
  text-decoration: none;
  color: #999;
}

a:hover {
  color: indianred;
}

.title {
  font-family: montserrat;
  font-weight: 900;
  font-size: 6vw;
  position: relative;
  width: 90%;
  left: 200px;
  margin-top: 0%;
}

.title2 {
  font-family: montserrat;
  font-weight: 900;
  font-size: 1.10vw;
  position: static;
  width: 90%;
  margin-left: 45%;
}

.scrollingtext p {
  width: 100%;
  padding: 0 10%;
  font-size: 13px;
}

/*LEFT PROFILE IMAGE HERE*/

.image {
  z-index: -1;
}

.image img {
  position: fixed;
  width: 50%;
  left: -3.5%;
  z-index: -1;
  -webkit-clip-path: polygon(25% 0%, 100% 0%, 71% 100%, 0% 100%);
  clip-path: polygon(25% 0%, 100% 0%, 71% 100%, 0% 100%);
}

/*CELL TABLE STUFF*/

.tablerow {
  display: table-row;
  width: 100%;
}

.table {
  display: table;
}

.cell {
  display: table-cell;
}

.right {
  width: 50%;
}

.left {
  width: 40%;
}

.mobile {
  display: none;
}

@media screen and (max-width: 1024px) {
  .image img {
    width: 100%;
    position: relative;
    padding: px 5% 0;
    margin: 0;
    top: 0;
    left: 0;
  }
  h1 {
    color: #000;
    letter-spacing: normal;
    width: 95%;
    margin-top: 0;
    padding: 0;
    margin: 0;
    font-size: 70PX;
    text-align: center;
    font-style: montserrat;
  }
  .title {
    display: none;
  }
  .cell {
    display: block;
  }
  .desktop {
    display: none;
  }
  .mobile {
    display: inherit;
    text-align: center;
  }
  .right {
    width: 80%;
    margin: 0;
  }
  .farright {
    width: 0;
  }
  #logo {
    height: 25px;
    position: absolute;
  }
  .story {
    color: #FFF;
    font-family: playfair display;
    width: 100%;
    height: 200px;
    text-shadow: 2px 2px 5px #000;
    background-color: #292929;
    display: table;
  }
  .story_inside {
    vertical-align: middle;
    display: table-cell;
  }
  .story h2 {
    font-size: 40px;
    width: 60%;
    padding: 0 15%;
    margin: 0;
    line-height: 35px;
  }
  .story p {
    font-family: montserrat;
    margin: 0;
    width: 70%;
    padding: 10px 15% 0 15%;
  }
  @media screen and (max-width: 400px) {
    h1 {
      color: #000;
      letter-spacing: normal;
      width: 95%;
      margin-top: 0;
      padding: 0;
      margin: 0;
      font-size: 40px;
      text-align: center;
      font-style: montserrat;
    }
    @media screen and (max-width: 1030px) {
      .byline {
        font-size: 16px;
        width: 100%;
        right: 451%;
        float: left;
        position: relative;
        width: 300%;
        bottom: -150px;
      }

TITLE HERE

AUTHOR HERE / TITLE

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example. This is a set of placeholder text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder text to show an example. This is a set of placeholder
          text to show an example.

Body:
Just addd this css to fix the Title

.title{font-family: montserrat;
font-weight: 900;
font-size: 6vw;
width: 90%;
position: fixed;
top: 50%;
left: 10%;}


问:
Drupal 7 Taxonomy display parent
I was wondering if anyone might know how to get the taxonomy content pages in Drupal 7 to display their children's content as well.

For example given a vocabulary like:

```<code>-Animal
--Dog
--Cat
</code>```

The Animal taxonomy page should display the dog and cats content as well.

Thank!

If it's any help, here's an exported copy of the view I'm using:

```<code>$view = new view;
$view->name = 'taxonomy_term';
$view->description = 'A view to emulate Drupal core\'s handling of taxonomy/term; it also emulates Views 1\'s handling by having two possible feeds.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = '';
$view->core = 0;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Sort criterion: Node: Sticky */
$handler->display->display_options['sorts']['sticky']['id'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['table'] = 'node';
$handler->display->display_options['sorts']['sticky']['field'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['order'] = 'DESC';
/* Sort criterion: Node: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Argument: Taxonomy: Term ID (with depth) */
$handler->display->display_options['arguments']['term_node_tid_depth']['id'] = 'term_node_tid_depth';
$handler->display->display_options['arguments']['term_node_tid_depth']['table'] = 'node';
$handler->display->display_options['arguments']['term_node_tid_depth']['field'] = 'term_node_tid_depth';
$handler->display->display_options['arguments']['term_node_tid_depth']['default_action'] = 'not found';
$handler->display->display_options['arguments']['term_node_tid_depth']['style_plugin'] = 'default_summary';
$handler->display->display_options['arguments']['term_node_tid_depth']['title'] = '%1';
$handler->display->display_options['arguments']['term_node_tid_depth']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['term_node_tid_depth']['validate_type'] = 'taxonomy_term';
$handler->display->display_options['arguments']['term_node_tid_depth']['validate_options']['type'] = 'tids';
$handler->display->display_options['arguments']['term_node_tid_depth']['validate_options']['transform'] = 0;
$handler->display->display_options['arguments']['term_node_tid_depth']['depth'] = '10';
$handler->display->display_options['arguments']['term_node_tid_depth']['break_phrase'] = 1;
$handler->display->display_options['arguments']['term_node_tid_depth']['set_breadcrumb'] = 0;
$handler->display->display_options['arguments']['term_node_tid_depth']['use_taxonomy_term_path'] = 0;
/* Argument: Taxonomy: Term ID depth modifier */
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['id'] = 'term_node_tid_depth_modifier';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['table'] = 'node';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['field'] = 'term_node_tid_depth_modifier';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['style_plugin'] = 'default_summary';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['default_argument_type'] = 'fixed';
/* Filter: Node: Published or admin */
$handler->display->display_options['filters']['status_extra']['id'] = 'status_extra';
$handler->display->display_options['filters']['status_extra']['table'] = 'node';
$handler->display->display_options['filters']['status_extra']['field'] = 'status_extra';
$handler->display->display_options['filters']['status_extra']['group'] = 0;
$handler->display->display_options['filters']['status_extra']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'taxonomy/term/%';

/* Display: Core feed */
$handler = $view->new_display('feed', 'Core feed', 'feed');
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = 15;
$handler->display->display_options['style_plugin'] = 'rss';
$handler->display->display_options['row_plugin'] = 'node_rss';
$handler->display->display_options['path'] = 'taxonomy/term/%/%/feed';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);

/* Display: Views 1 feed */
$handler = $view->new_display('feed', 'Views 1 feed', 'feed_1');
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = 15;
$handler->display->display_options['style_plugin'] = 'rss';
$handler->display->display_options['row_plugin'] = 'node_rss';
$handler->display->display_options['path'] = 'taxonomy/term/%/feed';
$translatables['taxonomy_term'] = array(
  t('Defaults'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort By'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('All'),
  t('%1'),
  t('Page'),
  t('Core feed'),
  t('Views 1 feed'),
);
</code>```

答:
Figured it out. </p>

<p>Using the Views 'taxonomy_term' view, I set the Depth property of the 'Taxonomy: Term ID (with depth)' argument to the max (10.) </p>

Title: Drupal 7 Taxonomy display parent

Body:
I was wondering if anyone might know how to get the taxonomy content pages in Drupal 7 to display their children's content as well.

For example given a vocabulary like:

-Animal
--Dog
--Cat

The Animal taxonomy page should display the dog and cats content as well.

Thank!

If it's any help, here's an exported copy of the view I'm using:

$view = new view;
$view->name = 'taxonomy_term';
$view->description = 'A view to emulate Drupal core\'s handling of taxonomy/term; it also emulates Views 1\'s handling by having two possible feeds.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = '';
$view->core = 0;
$view->api_version = '3.0-alpha1';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Sort criterion: Node: Sticky */
$handler->display->display_options['sorts']['sticky']['id'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['table'] = 'node';
$handler->display->display_options['sorts']['sticky']['field'] = 'sticky';
$handler->display->display_options['sorts']['sticky']['order'] = 'DESC';
/* Sort criterion: Node: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Argument: Taxonomy: Term ID (with depth) */
$handler->display->display_options['arguments']['term_node_tid_depth']['id'] = 'term_node_tid_depth';
$handler->display->display_options['arguments']['term_node_tid_depth']['table'] = 'node';
$handler->display->display_options['arguments']['term_node_tid_depth']['field'] = 'term_node_tid_depth';
$handler->display->display_options['arguments']['term_node_tid_depth']['default_action'] = 'not found';
$handler->display->display_options['arguments']['term_node_tid_depth']['style_plugin'] = 'default_summary';
$handler->display->display_options['arguments']['term_node_tid_depth']['title'] = '%1';
$handler->display->display_options['arguments']['term_node_tid_depth']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['term_node_tid_depth']['validate_type'] = 'taxonomy_term';
$handler->display->display_options['arguments']['term_node_tid_depth']['validate_options']['type'] = 'tids';
$handler->display->display_options['arguments']['term_node_tid_depth']['validate_options']['transform'] = 0;
$handler->display->display_options['arguments']['term_node_tid_depth']['depth'] = '10';
$handler->display->display_options['arguments']['term_node_tid_depth']['break_phrase'] = 1;
$handler->display->display_options['arguments']['term_node_tid_depth']['set_breadcrumb'] = 0;
$handler->display->display_options['arguments']['term_node_tid_depth']['use_taxonomy_term_path'] = 0;
/* Argument: Taxonomy: Term ID depth modifier */
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['id'] = 'term_node_tid_depth_modifier';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['table'] = 'node';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['field'] = 'term_node_tid_depth_modifier';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['style_plugin'] = 'default_summary';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['default_argument_type'] = 'fixed';
/* Filter: Node: Published or admin */
$handler->display->display_options['filters']['status_extra']['id'] = 'status_extra';
$handler->display->display_options['filters']['status_extra']['table'] = 'node';
$handler->display->display_options['filters']['status_extra']['field'] = 'status_extra';
$handler->display->display_options['filters']['status_extra']['group'] = 0;
$handler->display->display_options['filters']['status_extra']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'taxonomy/term/%';

/* Display: Core feed */
$handler = $view->new_display('feed', 'Core feed', 'feed');
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = 15;
$handler->display->display_options['style_plugin'] = 'rss';
$handler->display->display_options['row_plugin'] = 'node_rss';
$handler->display->display_options['path'] = 'taxonomy/term/%/%/feed';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);

/* Display: Views 1 feed */
$handler = $view->new_display('feed', 'Views 1 feed', 'feed_1');
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = 15;
$handler->display->display_options['style_plugin'] = 'rss';
$handler->display->display_options['row_plugin'] = 'node_rss';
$handler->display->display_options['path'] = 'taxonomy/term/%/feed';
$translatables['taxonomy_term'] = array(
  t('Defaults'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort By'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('All'),
  t('%1'),
  t('Page'),
  t('Core feed'),
  t('Views 1 feed'),
);

Body:
Figured it out.

Using the Views 'taxonomy_term' view, I set the Depth property of the 'Taxonomy: Term ID (with depth)' argument to the max (10.)


问:
How do I implement session affinity with a Ingress controller using GCE load balancer
I have the following ingress config:

ingressProd.yaml

```<code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: wordpress
  annotations:
    kubernetes.io/ingress.class: "gce"
spec:
  tls:
  - hosts:
    - ***.net
    secretName: production-tls
  rules:
    - host: ***.net
      http:
        paths:
        - path: /*
          backend:
            serviceName: wordpress
            servicePort: 80
</code>```

I'm having difficulty finding resources on how to enable session affinity for the above. Having previously used a LoadBalancer service which worked as intended previously.

What do I need to investigate?

答:
The current GCE ingress controller doesn't support session affinity. This is because it is not capable of load balancing the pods directly (It uses the nodeport service).

If you really need session affinity, the current solution is to deploy an ngnix-controller in GKE. This link contains the deployment steps.

Body:
I have the following ingress config:

ingressProd.yaml

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: wordpress
  annotations:
    kubernetes.io/ingress.class: "gce"
spec:
  tls:
  - hosts:
    - ***.net
    secretName: production-tls
  rules:
    - host: ***.net
      http:
        paths:
        - path: /*
          backend:
            serviceName: wordpress
            servicePort: 80

I'm having difficulty finding resources on how to enable session affinity for the above. Having previously used a LoadBalancer service which worked as intended previously.

What do I need to investigate?


问:
Nodejs once every eight hours
I am trying to impliment into my nodejs script a function to allow once per 8 hours a select command.

example:

!hug <--- would let bot respond with a hug but only once every 8 hours

I've been scouring online but cannot find what I need... I am trying to get it as simplified as possible.. (i.e without mongo... etc)

答:
You can use node-schedule for this and for more versatility where you can configure days, hours and minutes and cancel on particular conditions being met this also gives you to use cron expressions as well.</p>

```<code>var schedule = require("node-schedule");

var rule = new schedule.RecurrenceRule();
//Will run at 1am 9am and 5pm
rule.hour = [1, 9, 17];

var task = schedule.scheduleJob(rule, function(){
     //Do Stuff
     console.log("Scheduled Task Running...")
     /*
     if(condition met)
        task.cancel();
     */
});
</code>```

Title: Nodejs once every eight hours

Body:
You can use node-schedule for this and for more versatility where you can configure days, hours and minutes and cancel on particular conditions being met this also gives you to use cron expressions as well.

var schedule = require("node-schedule");

var rule = new schedule.RecurrenceRule();
//Will run at 1am 9am and 5pm
rule.hour = [1, 9, 17];

var task = schedule.scheduleJob(rule, function(){
     //Do Stuff
     console.log("Scheduled Task Running...")
     /*
     if(condition met)
        task.cancel();
     */
});


问:
Sorting Python list with exception
How can I sort a python list alphabetically, taking into consideration the numbering at the back of the list items. See example below and code used to sort.
Note that it is not possible to insert a zero into the code if the number is below 10.

original list:

['drawing-n-3', 'drawing-n-2', 'drawing-n-1', 'drawing-n-7',
  'drawing-n-6', 'drawing-n-5', 'drawing-n-4', 'drawing-n-9',
  'drawing-n-8', 'drawing-n-16', 'drawing-n-15', 'drawing-n-14',
  'drawing-n-13', 'drawing-n-12', 'drawing-n-11', 'drawing-n-10',
  'drawing-n-17']

Sorted list:

['drawing-n-1', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12',
  'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16',
  'drawing-n-17', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4',
  'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8',
  'drawing-n-9']

Desired List output:

['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4',
  'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8',
  'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12',
  'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16',
  'drawing-n-17']

Code:

```<code>dwg_number_keys = [key for key in kwargs if key.startswith("drawing-n-")]
print dwg_number_keys
print sorted(dwg_number_keys, key=str.lower)
</code>```

答:
Like this:

```<code>>>> my_list = ['drawing-n-3', 'drawing-n-2', 'drawing-n-1', 'drawing-n-7', 'drawing-n-6', 'drawing-n-5', 'drawing-n-4', 'drawing-n-9', 'drawing-n-8', 'drawing-n-16', 'drawing-n-15', 'drawing-n-14', 'drawing-n-13', 'drawing-n-12', 'drawing-n-11', 'drawing-n-10', 'drawing-n-17']
>>> sorted(my_list, key=lambda s:int(s[s.rindex('-')+1:]))
['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4', 'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8', 'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12', 'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16', 'drawing-n-17']
</code>```

The key lambda is just parsing the integer found at the last of each string after the '-' mark.

Title: Sorting Python list with exception

Body:
How can I sort a python list alphabetically, taking into consideration the numbering at the back of the list items. See example below and code used to sort.
Note that it is not possible to insert a zero into the code if the number is below 10.

original list:

['drawing-n-3', 'drawing-n-2', 'drawing-n-1', 'drawing-n-7',
  'drawing-n-6', 'drawing-n-5', 'drawing-n-4', 'drawing-n-9',
  'drawing-n-8', 'drawing-n-16', 'drawing-n-15', 'drawing-n-14',
  'drawing-n-13', 'drawing-n-12', 'drawing-n-11', 'drawing-n-10',
  'drawing-n-17']

Sorted list:

['drawing-n-1', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12',
  'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16',
  'drawing-n-17', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4',
  'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8',
  'drawing-n-9']

Desired List output:

['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4',
  'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8',
  'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12',
  'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16',
  'drawing-n-17']

Code:

dwg_number_keys = [key for key in kwargs if key.startswith("drawing-n-")]
print dwg_number_keys
print sorted(dwg_number_keys, key=str.lower)

Body:
Like this:

>>> my_list = ['drawing-n-3', 'drawing-n-2', 'drawing-n-1', 'drawing-n-7', 'drawing-n-6', 'drawing-n-5', 'drawing-n-4', 'drawing-n-9', 'drawing-n-8', 'drawing-n-16', 'drawing-n-15', 'drawing-n-14', 'drawing-n-13', 'drawing-n-12', 'drawing-n-11', 'drawing-n-10', 'drawing-n-17']
>>> sorted(my_list, key=lambda s:int(s[s.rindex('-')+1:]))
['drawing-n-1', 'drawing-n-2', 'drawing-n-3', 'drawing-n-4', 'drawing-n-5', 'drawing-n-6', 'drawing-n-7', 'drawing-n-8', 'drawing-n-9', 'drawing-n-10', 'drawing-n-11', 'drawing-n-12', 'drawing-n-13', 'drawing-n-14', 'drawing-n-15', 'drawing-n-16', 'drawing-n-17']

The key lambda is just parsing the integer found at the last of each string after the '-' mark.


问:
Java - How to use call a method from another class
For a class project I am trying to access a method from a different class but my code gives the error "non-static method printArrayList() cannot be referenced from a static context." I am a a beginner to java so any help is appreciated.
I have simplified the code down a bit.

Here is the first class:

```<code>public class classOne
{
    private classTwo[] arrayList;
    public void printArray()
        {
            classTwo.printArrayList();
        }
}
</code>```

And the second:

```<code>public class classTwo
{
    public void printArrayList()
    {
        System.out.println(arrayList);
    }
}
</code>```

答:
Change the Method modifier to static and access that method to another class with the help of that parent class name

eg.classname.staticmethodname();

Body:
For a class project I am trying to access a method from a different class but my code gives the error "non-static method printArrayList() cannot be referenced from a static context." I am a a beginner to java so any help is appreciated.
I have simplified the code down a bit.

Here is the first class:

public class classOne
{
    private classTwo[] arrayList;
    public void printArray()
        {
            classTwo.printArrayList();
        }
}

And the second:

public class classTwo
{
    public void printArrayList()
    {
        System.out.println(arrayList);
    }
}


问:
Two integer is equal but i am getting false

When I give some input for two values if they are equal ,it prints "True" in the terminal.But when both input is 128 I get false. Why?

```<code>public static void main(String[] args) {
    Scanner reader=new Scanner(System.in);
    System.out.println("Enter your first number :");
    Integer number1 = reader.nextInt();
    System.out.println("Enter your second number: ");
    Integer number2 = reader.nextInt();
    if (number1 == number2)
    {
        System.out.println("True");
    }
    else{
        System.out.println("False");
    }
}
</code>```

Input:

128

128

Output:(Should be)
True

But I get:

False

答:
use equals instead of ==:

```<code>if (number1.equals(number2)) {
    System.out.println("True");
}
else {
    System.out.println("False");
}
</code>```

Body:
When I give some input for two values if they are equal ,it prints "True" in the terminal.But when both input is 128 I get false. Why?

public static void main(String[] args) {
    Scanner reader=new Scanner(System.in);
    System.out.println("Enter your first number :");
    Integer number1 = reader.nextInt();
    System.out.println("Enter your second number: ");
    Integer number2 = reader.nextInt();
    if (number1 == number2)
    {
        System.out.println("True");
    }
    else{
        System.out.println("False");
    }
}

Input:

128

128

Output:(Should be)
True

But I get:

False

Body:
use equals instead of ==:

if (number1.equals(number2)) {
    System.out.println("True");
}
else {
    System.out.println("False");
}


答:
This will get you what you want if the format is as consistent as you made it out to be

lambda x: int(x.split('-')[-1])

Title: Sorting Python list with exception


答:
A simple way to do it would be to make your image float with CSS in the same element as your text.

Like this example;

#my_container {
  width: 400px;
  text-align: justify;
}

#my_image {
  width: 100px;
  height: 100px;
  float: right;
  border: 1px solid #000;
  margin: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="my_container">
  <div id="my_image">image here</div>
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.

<div></code>```

Title: Is there a way to align scrolling text around an image?

Body:
A simple way to do it would be to make your image float with CSS in the same element as your text.

Like this example;

#my_container {
  width: 400px;
  text-align: justify;
}

#my_image {
  width: 100px;
  height: 100px;
  float: right;
  border: 1px solid #000;
  margin: 10px;
}

<div id="my_container">
  <div id="my_image">image here</div>
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.
  And a lot of copy and paste to fill this example.

<div>


答:
Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

This answer provides a detailed info:

How to interpret "loss" and "accuracy" for a machine learning model

Title: Test score vs test accuracy when evaluating model using Keras

Body:
Im using a neural network implemented with the Keras library and below is the results during training. At the end it prints a test score and a test accuracy. I can't figure out exactly what the score represents, but the accuracy I assume to be the number of predictions that was correct when running the test.

Epoch 1/15 1200/1200 [==============================] - 4s - loss:
  0.6815 - acc: 0.5550 - val_loss: 0.6120 - val_acc: 0.7525

Epoch 2/15 1200/1200 [==============================] - 3s - loss:
  0.5481 - acc: 0.7250 - val_loss: 0.4645 - val_acc: 0.8025

Epoch 3/15 1200/1200 [==============================] - 3s - loss:
  0.5078 - acc: 0.7558 - val_loss: 0.4354 - val_acc: 0.7975

Epoch 4/15 1200/1200 [==============================] - 3s - loss:
  0.4603 - acc: 0.7875 - val_loss: 0.3978 - val_acc: 0.8350

Epoch 5/15 1200/1200 [==============================] - 3s - loss:
  0.4367 - acc: 0.7992 - val_loss: 0.3809 - val_acc: 0.8300

Epoch 6/15 1200/1200 [==============================] - 3s - loss:
  0.4276 - acc: 0.8017 - val_loss: 0.3884 - val_acc: 0.8350

Epoch 7/15 1200/1200 [==============================] - 3s - loss:
  0.3975 - acc: 0.8167 - val_loss: 0.3666 - val_acc: 0.8400

Epoch 8/15 1200/1200 [==============================] - 3s - loss:
  0.3916 - acc: 0.8183 - val_loss: 0.3753 - val_acc: 0.8450

Epoch 9/15 1200/1200 [==============================] - 3s - loss:
  0.3814 - acc: 0.8233 - val_loss: 0.3505 - val_acc: 0.8475

Epoch 10/15 1200/1200 [==============================] - 3s - loss:
  0.3842 - acc: 0.8342 - val_loss: 0.3672 - val_acc: 0.8450

Epoch 11/15 1200/1200 [==============================] - 3s - loss:
  0.3674 - acc: 0.8375 - val_loss: 0.3383 - val_acc: 0.8525

Epoch 12/15 1200/1200 [==============================] - 3s - loss:
  0.3624 - acc: 0.8367 - val_loss: 0.3423 - val_acc: 0.8650

Epoch 13/15 1200/1200 [==============================] - 3s - loss:
  0.3497 - acc: 0.8475 - val_loss: 0.3069 - val_acc: 0.8825

Epoch 14/15 1200/1200 [==============================] - 3s - loss:
  0.3406 - acc: 0.8500 - val_loss: 0.2993 - val_acc: 0.8775

Epoch 15/15 1200/1200 [==============================] - 3s - loss:
  0.3252 - acc: 0.8600 - val_loss: 0.2960 - val_acc: 0.8775

400/400 [==============================] - 0s

Test score: 0.299598811865

Test accuracy: 0.88

Looking at the Keras documentation, I still don't understand what score is. For the evaluate function, it says:

Returns the loss value & metrics values for the model in test mode.

One thing I noticed is that when the test accuracy is lower, the score is higher, and when accuracy is higher, the score is lower.


问:
get the count for different data in single column as set
I am having table "Activation" with the columns account ID and email and product name

product name column is having data like this below

```<code> Platform
 Access
 Onboard
 OnGuard
 Platform
 Access
 Onboard
 OnGuard
</code>```

when user activated we will insert the data as a set like this ( Platform
     ,Access
     ,Onboard
     ,OnGuard)
and i need to give a warning to the user  if he is inserting more than one set (Platform,Access,Onboard,OnGuard)

I can get the count for single product name insertion like (platform or access), but i need to get the count for single set insertion here ..

Could any one please help on this query how to get count for single set insertion and i am using sql server as a DB for these insertions.

Many thanks in advance..

UPDATE

sorry for confusion i need to give a warning to user if  he inserted more than one time any of the product name defined in the set not as a single set ..

答:
Assuming that unique products count is 4, you can check it using aggregation along with having.

```<code>select accountid
from activation
group by accountid
having count(distinct productname) = 4
</code>```

Or you can reverse the logic according to your need(if you want to get the users against whom not all products are defined by changing = to <>

DEMO

Body:
I am having table "Activation" with the columns account ID and email and product name

product name column is having data like this below

 Platform
 Access
 Onboard
 OnGuard
 Platform
 Access
 Onboard
 OnGuard

when user activated we will insert the data as a set like this ( Platform
     ,Access
     ,Onboard
     ,OnGuard)
and i need to give a warning to the user  if he is inserting more than one set (Platform,Access,Onboard,OnGuard)

I can get the count for single product name insertion like (platform or access), but i need to get the count for single set insertion here ..

Could any one please help on this query how to get count for single set insertion and i am using sql server as a DB for these insertions.

Many thanks in advance..

UPDATE

sorry for confusion i need to give a warning to user if  he inserted more than one time any of the product name defined in the set not as a single set ..

Body:
Assuming that unique products count is 4, you can check it using aggregation along with having.

select accountid
from activation
group by accountid
having count(distinct productname) = 4

Or you can reverse the logic according to your need(if you want to get the users against whom not all products are defined by changing = to <>

DEMO


问:
Android Window title showing after requested not to show
```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        Intent i = new Intent(this, BaseActivity.class);
        startActivity(i);
    }
</code>```

and my next activity:

```<code>public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_base);
    }
</code>```

I still see blue bar with application name at top.
I tried changing my application manifest to use a no-title theme and the program crashed because the activities inherit from AppCompatActivity.

How do I inherit from AppCompatActivity and get rid of the application title name up top?

答:
Try this...

If you don't want the action bar in your activity then,

Create a style

```<code><style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
</style>
</code>```

and apply this style for the activity in Manifest for which you don't need action bar,

```<code><activity android:name=".BaseActivity"
          android:theme="@style/AppTheme.NoActionBar"></activity>
</code>```

Body:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        Intent i = new Intent(this, BaseActivity.class);
        startActivity(i);
    }

and my next activity:

public class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_base);
    }

I still see blue bar with application name at top.
I tried changing my application manifest to use a no-title theme and the program crashed because the activities inherit from AppCompatActivity.

How do I inherit from AppCompatActivity and get rid of the application title name up top?

Body:
Try this...

If you don't want the action bar in your activity then,

Create a style

<style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
</style>

and apply this style for the activity in Manifest for which you don't need action bar,

<activity android:name=".BaseActivity"
          android:theme="@style/AppTheme.NoActionBar"></activity>


问:
No signature of method: static com.mongodb.MongoCredential.createCredential()
MongoCredential.createCredential() is throwing error response for arguments that seem valid according to the documentation (Groovy with gmongo).

The code I'm trying to execute:

```<code>@Grab(group='com.gmongo', module='gmongo', version='1.5')

import java.util.*;
import com.gmongo.GMongo
import com.gmongo.GMongoClient
import com.mongodb.MongoCredential
import com.mongodb.MongoClientOptions
import com.mongodb.client.MongoDatabase;
import com.mongodb.*
import com.mongodb.ServerAddress
import com.gmongo.*
import com.mongodb.MongoURI
import com.mongodb.DBCursor;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBList

def mongoendpoint = context.expand( '${#Project#mongoendpoint}' )
def mongocollection=context.expand( '${#Project#mongocollection_ignition}' )
char[] password = 'password'.toCharArray();

 def credentials = MongoCredential.createCredential(
           context.expand('${#Project#MongoUser}'),
           context.expand('${#Project#MongoDatabase}'),
           password
           // "password" as char[] doesn't work either
           )
</code>```

Getting the following error:

groovy.lang.MissingMethodException: No signature of method: static com.mongodb.MongoCredential.createCredential() is applicable for argument types: (java.lang.String, java.lang.String, [C) values: [elenalenenko, test, p7Aqmlt9FF!] Possible solutions: createPlainCredential(java.lang.String, java.lang.String, [C) error at line: 34

Documentation says syntax is

```<code>static MongoCredential  createCredential(String userName, String database, char[] password)
</code>```

答:
Seems like it's a problem with ReadyAPI 2.2.0
Rolled back to ReadyAPI 2.1.0 and everything works perfectly. Raised a support ticket with SmartBear</p>

Body:
MongoCredential.createCredential() is throwing error response for arguments that seem valid according to the documentation (Groovy with gmongo).

The code I'm trying to execute:

@Grab(group='com.gmongo', module='gmongo', version='1.5')

import java.util.*;
import com.gmongo.GMongo
import com.gmongo.GMongoClient
import com.mongodb.MongoCredential
import com.mongodb.MongoClientOptions
import com.mongodb.client.MongoDatabase;
import com.mongodb.*
import com.mongodb.ServerAddress
import com.gmongo.*
import com.mongodb.MongoURI
import com.mongodb.DBCursor;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBList

def mongoendpoint = context.expand( '${#Project#mongoendpoint}' )
def mongocollection=context.expand( '${#Project#mongocollection_ignition}' )
char[] password = 'password'.toCharArray();

 def credentials = MongoCredential.createCredential(
           context.expand('${#Project#MongoUser}'),
           context.expand('${#Project#MongoDatabase}'),
           password
           // "password" as char[] doesn't work either
           )

Getting the following error:

groovy.lang.MissingMethodException: No signature of method: static com.mongodb.MongoCredential.createCredential() is applicable for argument types: (java.lang.String, java.lang.String, [C) values: [elenalenenko, test, p7Aqmlt9FF!] Possible solutions: createPlainCredential(java.lang.String, java.lang.String, [C) error at line: 34

Documentation says syntax is

static MongoCredential  createCredential(String userName, String database, char[] password)


问:
Globally set dynamic pug variables
I am using express and pug, there are some values that I would like to pass to pug on every request, for example: req.session and req.path. Passing these values to the render() method every time just seems too redundant.

So instead of doing something like this:

```<code>app.get('/', (req, res) => {
    res.render('home', {session: req.session})
})
app.get('/profile', (req, res) => {
    res.render('profile', {session: req.session})
})
</code>```

The more routes that get added, the more of those items I need to manage. Is there a global way that I can set them once other than app.locals so they are unique per request?

答:
You can set variables that are available to every template on each request using a bit of custom middleware and locals. This same approach works for all templating systems that Express can use, not just Pug.

Put the following before your routes.

```<code>app.use((req, res, next) => {
  res.locals.session = req.session
  next()
})
</code>```

Then in your template you can call it like this.

```<code>h3= session.name
</code>```

Title: Globally set dynamic pug variables

Body:
I am using express and pug, there are some values that I would like to pass to pug on every request, for example: req.session and req.path. Passing these values to the render() method every time just seems too redundant.

So instead of doing something like this:

app.get('/', (req, res) => {
    res.render('home', {session: req.session})
})
app.get('/profile', (req, res) => {
    res.render('profile', {session: req.session})
})

The more routes that get added, the more of those items I need to manage. Is there a global way that I can set them once other than app.locals so they are unique per request?

Body:
You can set variables that are available to every template on each request using a bit of custom middleware and locals. This same approach works for all templating systems that Express can use, not just Pug.

Put the following before your routes.

app.use((req, res, next) => {
  res.locals.session = req.session
  next()
})

Then in your template you can call it like this.

h3= session.name


问:
How do you authenticate against Thrift HBase from .NET?
We have a .NET application talking to HBase using Thrift.  The Thrift server is configured to do pass through authentication (Kerberos).  We have a keytab.

How do we implement the authentication from the .NET application?  All the examples I've seen are in Java.  Has anyone done this from .NET?

答:
There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, so it is cross-platform.

you can use its client

```<code>[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

ThriftSerializer s = new ThriftSerializer(ThriftSerializer.SerializeProtocol.Binary);
byte[] s = s.Serialize<LogEntry>();

s.Deserialize<LogEntry>(s);

[ThriftService("scribe")]
public interface IScribe
{
    [ThriftMethod("getMessages")]
    List<LogEntry> GetMessages();

    [ThriftMethod]
    ResultCode Log(List<LogEntry> messages);
}

public class Scribe : IScribe
{
    public List<LogEntry> GetMessages()
    {
        return new List<LogEntry>
        {
            new LogEntry { Category = "c1", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c2", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c3", Message = Guid.NewGuid().ToString() }
        };
    }

    public ResultCode Log(List<LogEntry> messages)
    {
        return ResultCode.TRY_LATER;
    }
}
</code>```

you can try it: https://github.com/endink/Thrifty

Body:
There is an RPC framework that uses the standard thrift Protocol named "thrifty", and it is the same effect as using thrift IDL to define the service, that is, thrify can be compatible with code that uses thrift IDL, so it is cross-platform.

you can use its client

[ThriftStruct]
public class LogEntry
{

    [ThriftConstructor]
    public LogEntry([ThriftField(1)]String category, [ThriftField(2)]String message)
    {
        this.Category = category;
        this.Message = message;
    }

    [ThriftField(1)]
    public String Category { get; }

    [ThriftField(2)]
    public String Message { get; }
}

ThriftSerializer s = new ThriftSerializer(ThriftSerializer.SerializeProtocol.Binary);
byte[] s = s.Serialize<LogEntry>();

s.Deserialize<LogEntry>(s);

[ThriftService("scribe")]
public interface IScribe
{
    [ThriftMethod("getMessages")]
    List<LogEntry> GetMessages();

    [ThriftMethod]
    ResultCode Log(List<LogEntry> messages);
}

public class Scribe : IScribe
{
    public List<LogEntry> GetMessages()
    {
        return new List<LogEntry>
        {
            new LogEntry { Category = "c1", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c2", Message = Guid.NewGuid().ToString() },
            new LogEntry { Category = "c3", Message = Guid.NewGuid().ToString() }
        };
    }

    public ResultCode Log(List<LogEntry> messages)
    {
        return ResultCode.TRY_LATER;
    }
}

you can try it: https://github.com/endink/Thrifty


问:
How do you query property values with SQL Server JSON without knowing the parent object keys?
Given the following JSON in SQL Server, how do you get the "Foo" values without knowing the parent keys ("John" and "Jane")?</p>
```<code>declare @json nvarchar(max) = '{
    "John" : {
        "favoriteMovie": "Star Wars",
        "Foo": 42
    },
    "Jane" : {
        "favoriteMovie": "Caddyshack",
        "Foo": 66
    }
}'
</code>```

答:
Here is one way is to use XML node method to get the desired result. However, the method is odd but it would helps

```<code>select
          ltrim(replace(replace(a.value('.', 'nvarchar(max)'), char(10), ''), '}', '')) json from
(
    select cast('<m>'+replace(@json, ',', '</m><m>')+'</m>' as xml) as json
)a cross apply json.nodes ('/m') as json(a)
where a.value('.', 'varchar(max)') like '%foo%'
</code>```

Result :

```<code>json
"Foo": 42
"Foo": 66
</code>```

Body:
Given the following JSON in SQL Server, how do you get the "Foo" values without knowing the parent keys ("John" and "Jane")?

declare @json nvarchar(max) = '{
    "John" : {
        "favoriteMovie": "Star Wars",
        "Foo": 42
    },
    "Jane" : {
        "favoriteMovie": "Caddyshack",
        "Foo": 66
    }
}'

Body:
Here is one way is to use XML node method to get the desired result. However, the method is odd but it would helps

select
          ltrim(replace(replace(a.value('.', 'nvarchar(max)'), char(10), ''), '}', '')) json from
(
    select cast('<m>'+replace(@json, ',', '</m><m>')+'</m>' as xml) as json
)a cross apply json.nodes ('/m') as json(a)
where a.value('.', 'varchar(max)') like '%foo%'

Result :

json
"Foo": 42
"Foo": 66


问:
Designing for "Pretty" URLs
I'm aware of mod_rewrite methods to convert ugly URLs to pretty. My question is preceding this conversion.

I have not yet developed my website. I would like to design all pages such that the pretty URLs are also pretty on the server side.

I would like to come up with a general rule for ALL pages. Normally all pages are slightly different...

```<code>/news/12345                        =>    /news.php?id=1234
/members/Mikhail                   =>    /members.php?name=Mikhail
/subsection/page/banned-members    =>    /subsection/page.php?view=banned-members
</code>```

In the three examples above the GET variable name is different for each case, and the third example could ALSO be developed to be interpreted as /subsection.php?file=page&view=banned-members

So my question is: What can I do, from the design point, do have an elegant solution on the client AND server side to create pretty URLs?

Thanks!

答:
Using the ASP.NET MVC framework is the poster-child of "pretty URL" designs

EDIT: Sorry, didn't notice your PHP files... there are a number of PHP MVC frameworks too (though I have no experience with how pretty the URLs look)

Title: Designing for "Pretty" URLs

Body:
I'm aware of mod_rewrite methods to convert ugly URLs to pretty. My question is preceding this conversion.

I have not yet developed my website. I would like to design all pages such that the pretty URLs are also pretty on the server side.

I would like to come up with a general rule for ALL pages. Normally all pages are slightly different...

/news/12345                        =>    /news.php?id=1234
/members/Mikhail                   =>    /members.php?name=Mikhail
/subsection/page/banned-members    =>    /subsection/page.php?view=banned-members

In the three examples above the GET variable name is different for each case, and the third example could ALSO be developed to be interpreted as /subsection.php?file=page&view=banned-members

So my question is: What can I do, from the design point, do have an elegant solution on the client AND server side to create pretty URLs?

Thanks!


问:
Get Value from HTML select box
I want to receive the selected Value from the Selectbox. I tried this. When I'm doing this i receive an empty String.

Html:

```<code><div class="selector">

    <select id="values" name="values" runat="server">

        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>

    </select>

</div>
</code>```

C#:

```<code>String value = Request.Form["values"];
</code>```

答:
HTML

```<code>    <div class="selector">
      <form runat="server">
        <select id="values" name="val" runat="server">
          <option value="--">----</option>
       </select>
     </form>
   </div>
</code>```

C#

```<code>  int selectop=Page.Request.Form["values"].ToString();
</code>```

Title: Get Value from HTML select box

Body:
I want to receive the selected Value from the Selectbox. I tried this. When I'm doing this i receive an empty String.

Html:

    <select id="values" name="values" runat="server">

        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>

    </select>

C#:

String value = Request.Form["values"];

Body:
HTML

    <div class="selector">
      <form runat="server">
        <select id="values" name="val" runat="server">
          <option value="--">----</option>
       </select>
     </form>
   </div>

C#

  int selectop=Page.Request.Form["values"].ToString();


问:
Selecting a span without a specific attribute, then adding an onclick function hosted from another file
I'm currently trying to write a userscript on Tampermonkey for a web based game. Using jQuery or JS, I would like to make a span with id='#notification-static-woodcutting'  a clickable link that runs a pre-written function that the host made. The function is openTab('woodcutting').

Here's the catch:

I only want the link to happen when the game removes the style "display:none;".

I don't have acccess to the openTab() function, nor can I edit the HTML.

```<code>$(document).ready(function() {
var woodcuttingNotification = document.getElementById('notification-static-woodcutting');

while( $(woodcuttingNotification).css('display') === null )  {
    $(woodcuttingNotification).css('cursor','pointer');
    $(woodcuttingNotification).click(function() {
        $(woodcuttingNotification).attr('onClick',"openTab('woodcutting')");
    });
  }
});
</code>```

Ideally, I am trying to produce

```<code><span style id="notification-static-woodcutting" onclick="openTab('woodcutting')">
</code>```

If the game takes away the style="display:none;"... the game automatically adds and takes away the style.

The cursor doesn't change, nor does anything happen when I click, which leads me to believe that my if(selector) is wrong?

答:
I am still not 100% clear of the question, but here is a try,

Have kept a flag to check the display status of the span, and I have a kept jquery event handler where we can check the state of the flag.

```<code>var flag = false;
$(document).ready(function() {

    $(document).on('click','#notification-static-woodcutting',function(){
          if(flag == true)
             openTab('woodcutting');
    });

    setInterval(function(){
        if($('#notification-static-woodcutting').css('display') == 'none')
            flag = false;
        else
            flag = true;
    },100);
});
</code>```

Adjust the time interval as required.

Body:
I'm currently trying to write a userscript on Tampermonkey for a web based game. Using jQuery or JS, I would like to make a span with id='#notification-static-woodcutting'  a clickable link that runs a pre-written function that the host made. The function is openTab('woodcutting').

Here's the catch:

I only want the link to happen when the game removes the style "display:none;".

I don't have acccess to the openTab() function, nor can I edit the HTML.

$(document).ready(function() {
var woodcuttingNotification = document.getElementById('notification-static-woodcutting');

while( $(woodcuttingNotification).css('display') === null )  {
    $(woodcuttingNotification).css('cursor','pointer');
    $(woodcuttingNotification).click(function() {
        $(woodcuttingNotification).attr('onClick',"openTab('woodcutting')");
    });
  }
});

Ideally, I am trying to produce

If the game takes away the style="display:none;"... the game automatically adds and takes away the style.

The cursor doesn't change, nor does anything happen when I click, which leads me to believe that my if(selector) is wrong?

Body:
I am still not 100% clear of the question, but here is a try,

Have kept a flag to check the display status of the span, and I have a kept jquery event handler where we can check the state of the flag.

var flag = false;
$(document).ready(function() {

    $(document).on('click','#notification-static-woodcutting',function(){
          if(flag == true)
             openTab('woodcutting');
    });

    setInterval(function(){
        if($('#notification-static-woodcutting').css('display') == 'none')
            flag = false;
        else
            flag = true;
    },100);
});

Adjust the time interval as required.


问:
Is there any way to pass only 1 time Buffer string and only 1 time Regex check
My string representation of byte buffer Encoding.UTF8.GetString(b.Buffer) is "Foo:Foo1".

I would like to parse the string against Regex and then bind with 2 different property (Message1 and Message2) of class RemoteData.

```<code>public class RemoteData
{
    private string _message1;
    private string _message2;

    public RemoteData(string Message1, string Message2)
    {
        this.Message1 = Message1;
        this.Message2 = Message2;
    }

    public string Message1
    {
        get
        {
            if (IsValidMessage(_message1))
                return _message1 = _message1.Split(':')[0].ToString();
            return _message1;
        }
        set
        {
            _message1 = value;
        }
    }

    public string Message2
    {
        get
        {
            if (IsValidMessage(_message2))
                return _message2 = _message2.Split(':')[1].ToString();
            return _message2;
        }
        set
        {
            _message2 = value;
        }
    }

    private static bool IsValidMessage(string value)
    {
        const string expression = (@"([\w]+):([\w]+)");

        return Regex.IsMatch(value, expression, RegexOptions.IgnoreCase);
    }
}
</code>```

I am returning IObservable of class RemoteData and below code is working good.

```<code> public static IObservable<RemoteData> UdpStream(IPEndPoint endpoint)
    {
        return Observable.Using(() => new UdpClient(endpoint),
            udpClient => Observable.Defer(() =>
                udpClient.ReceiveAsync().ToObservable()).Repeat().Select(b => new RemoteData(Encoding.UTF8.GetString(b.Buffer), Encoding.UTF8.GetString(b.Buffer))));
    }
</code>```

Question: Is there any way that,

I can pass only one time Encoding.UTF8.GetString(b.Buffer) in Observable Select?

I have to do only one time regex check and convert the string and assign to various properties of class RemoteData?

Thanks!

答:
As a solution, I am using another class SplitData and checking Regex at RemoteData constructor.

```<code>public class SplitData
{
    public string Message1 { get; set; }
    public string Message2 { get; set; }
}
public class RemoteData
{
    private SplitData _SplitData;

    public RemoteData(string Message)
    {
        this.Message = Message;
        if (IsValidMessage(this.Message))
        {
            _SplitData = new SplitData
            {
                Message1 = Message.Split(':')[0].ToString(),
                Message2 = Message.Split(':')[1].ToString()
            };
        }
    }

    public string Message { get; }
    public SplitData SplitData
    {
        get
        {
            return _SplitData;
        }
        set
        {
            _SplitData = value;
        }
    }
    private static bool IsValidMessage(string value)
    {
        const string expression = (@"([\w]+):([\w]+)");

        return Regex.IsMatch(value, expression, RegexOptions.IgnoreCase);
    }
}
</code>```

and passing one parameter to UdpStream method,

```<code>public static IObservable<RemoteData> UdpStream(IPEndPoint endpoint)
    {
        return Observable.Using(() => new UdpClient(endpoint),
            udpClient => Observable.Defer(() =>
                udpClient.ReceiveAsync().ToObservable()).Repeat().Select(b => new RemoteData(Encoding.UTF8.GetString(b.Buffer))));
    }
</code>```

Please let me know if any other better way. Thanks!

Body:
My string representation of byte buffer Encoding.UTF8.GetString(b.Buffer) is "Foo:Foo1".

I would like to parse the string against Regex and then bind with 2 different property (Message1 and Message2) of class RemoteData.

public class RemoteData
{
    private string _message1;
    private string _message2;

    public RemoteData(string Message1, string Message2)
    {
        this.Message1 = Message1;
        this.Message2 = Message2;
    }

    public string Message1
    {
        get
        {
            if (IsValidMessage(_message1))
                return _message1 = _message1.Split(':')[0].ToString();
            return _message1;
        }
        set
        {
            _message1 = value;
        }
    }

    public string Message2
    {
        get
        {
            if (IsValidMessage(_message2))
                return _message2 = _message2.Split(':')[1].ToString();
            return _message2;
        }
        set
        {
            _message2 = value;
        }
    }

    private static bool IsValidMessage(string value)
    {
        const string expression = (@"([\w]+):([\w]+)");

        return Regex.IsMatch(value, expression, RegexOptions.IgnoreCase);
    }
}

I am returning IObservable of class RemoteData and below code is working good.

 public static IObservable<RemoteData> UdpStream(IPEndPoint endpoint)
    {
        return Observable.Using(() => new UdpClient(endpoint),
            udpClient => Observable.Defer(() =>
                udpClient.ReceiveAsync().ToObservable()).Repeat().Select(b => new RemoteData(Encoding.UTF8.GetString(b.Buffer), Encoding.UTF8.GetString(b.Buffer))));
    }

Question: Is there any way that,

I can pass only one time Encoding.UTF8.GetString(b.Buffer) in Observable Select?

I have to do only one time regex check and convert the string and assign to various properties of class RemoteData?

Thanks!

Body:
As a solution, I am using another class SplitData and checking Regex at RemoteData constructor.

public class SplitData
{
    public string Message1 { get; set; }
    public string Message2 { get; set; }
}
public class RemoteData
{
    private SplitData _SplitData;

    public RemoteData(string Message)
    {
        this.Message = Message;
        if (IsValidMessage(this.Message))
        {
            _SplitData = new SplitData
            {
                Message1 = Message.Split(':')[0].ToString(),
                Message2 = Message.Split(':')[1].ToString()
            };
        }
    }

    public string Message { get; }
    public SplitData SplitData
    {
        get
        {
            return _SplitData;
        }
        set
        {
            _SplitData = value;
        }
    }
    private static bool IsValidMessage(string value)
    {
        const string expression = (@"([\w]+):([\w]+)");

        return Regex.IsMatch(value, expression, RegexOptions.IgnoreCase);
    }
}

and passing one parameter to UdpStream method,

public static IObservable<RemoteData> UdpStream(IPEndPoint endpoint)
    {
        return Observable.Using(() => new UdpClient(endpoint),
            udpClient => Observable.Defer(() =>
                udpClient.ReceiveAsync().ToObservable()).Repeat().Select(b => new RemoteData(Encoding.UTF8.GetString(b.Buffer))));
    }

Please let me know if any other better way. Thanks!


问:
Consolidate / Manipulate array of objects
I have an array of objects like the following:

```<code>[{
  animal: "cat",
  dateString: "2017-01-03"
},{
  animal: "dog",
  dateString: "2017-02-05"
},{
  animal: "cat",
  dateString: "2017-03-04"
}]
</code>```

and I'd like to create a new array that looks like:

```<code>[{
  animal: "cat",
  values: [
    "2017-01-03",
    "2017-03-04"
  ]
},{
  animal: "dog",
  values: [
    "2017-02-05"
  ]
}]
</code>```

How can I consolidate the individual object properties into an array of values?

答:
Here you first create a new, empty array and a for-loop. From there you either create a brand new object with of the animal type or just push the dateString value of the other if it does:

const animals = [{
  animal: "cat",
  dateString: "2017-01-03"
}, {
  animal: "dog",
  dateString: "2017-02-05"
}, {
  animal: "cat",
  dateString: "2017-03-04"
}];

const combined = [];

for (let i = 0; i < animals.length; i++) {
  const { animal, dateString } = animals[i];

  const animalIndex = combined.findIndex(obj => {
    return obj['animal'] === animal;
  });

  if (animalIndex === -1) {
    combined.push({ animal, values: [dateString] });
  } else {
    combined[animalIndex]['values'].push(dateString);
  }
}

console.log(combined);```

Body:
I have an array of objects like the following:

[{
  animal: "cat",
  dateString: "2017-01-03"
},{
  animal: "dog",
  dateString: "2017-02-05"
},{
  animal: "cat",
  dateString: "2017-03-04"
}]

and I'd like to create a new array that looks like:

[{
  animal: "cat",
  values: [
    "2017-01-03",
    "2017-03-04"
  ]
},{
  animal: "dog",
  values: [
    "2017-02-05"
  ]
}]

How can I consolidate the individual object properties into an array of values?


问:
Are parentheses around the result significant in a return statement?
Is there a difference between these two statements inside a function?

```<code>bool returnValue = true;
// Code that does something
return(returnValue);
</code>```

and this?

```<code>bool returnValue = true;
// Code
return returnValue;
</code>```

The former has parentheses around returnValue.

答:
There is no difference.

One reason to use parenthesis would be if you wanted to evaluate an expression before returning but in your example, there would be no reason.  See:

Parenthesis surrounding return values

for further discussion.

Body:
Is there a difference between these two statements inside a function?

bool returnValue = true;
// Code that does something
return(returnValue);

and this?

bool returnValue = true;
// Code
return returnValue;

The former has parentheses around returnValue.


问:
Weka java accuracy different compared to weka explorer

I am working with weka's java api and I am tyring to find accuracy with J48.

```<code>    J48 J48_classifier = new new J48();
    J48_classifier.buildClassifier(data);   // build classifier
    eval.crossValidateModel(J48_classifier, data, 10, new Random(1));
    System.out.println(eval.pctCorrect());
</code>```

I am getting 76% accuracy with using the Java API. Though when I use explorer I get 99% accuracy that is a large difference.

What could I be doing wrong I hear its the random value produced for the java but its noticeable for a lot of the other classifiers as well. I don't know where to start or has anybody else dealt with this.

答:
I was able to figure it out what you need to do is build your own cross-validation for java this can be done by the examples provided by weka. The link is below it was able to give me the same results as the explorer.

https://weka.wikispaces.com/Generating+cross-validation+folds+%28Java+approach%29

This only works for classifier-based recognition, not clustering.

Body:
I am working with weka's java api and I am tyring to find accuracy with J48.

    J48 J48_classifier = new new J48();
    J48_classifier.buildClassifier(data);   // build classifier
    eval.crossValidateModel(J48_classifier, data, 10, new Random(1));
    System.out.println(eval.pctCorrect());

I am getting 76% accuracy with using the Java API. Though when I use explorer I get 99% accuracy that is a large difference.

What could I be doing wrong I hear its the random value produced for the java but its noticeable for a lot of the other classifiers as well. I don't know where to start or has anybody else dealt with this.


问:
How to shape train and test data for sklearn svm
I m using the pandas library to extract the data and use it to feed svc classifier like this :

```<code>from sklearn.svm import SVC
import pandas as pd

train = pd.read_csv('train.csv')
X_train = train['FunctionalWordPercent']
Y_train  = train['openness']

test = pd.read_csv('test.csv')
X_test = test['FunctionalWordPercent']
Y_test  = test['openness']

clf = SVC()
clf.fit(X_train, Y_train)
SVC(kernel="linear", c=1.0)

print(clf.score(X_test,Y_test))
</code>```

But I keep getting the following error :

```<code>Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
</code>```

答:
Looks like you are using a single column (feature) for X. For this code to work, you need to do this:</p>

```<code>X_train = train['FunctionalWordPercent']
X_train = X_train.reshape(-1,1)

X_test = test['FunctionalWordPercent']
X_test = X_test.reshape(-1,1)
</code>```

Body:
I m using the pandas library to extract the data and use it to feed svc classifier like this :

from sklearn.svm import SVC
import pandas as pd

train = pd.read_csv('train.csv')
X_train = train['FunctionalWordPercent']
Y_train  = train['openness']

test = pd.read_csv('test.csv')
X_test = test['FunctionalWordPercent']
Y_test  = test['openness']

clf = SVC()
clf.fit(X_train, Y_train)
SVC(kernel="linear", c=1.0)

print(clf.score(X_test,Y_test))

But I keep getting the following error :

Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

Body:
Looks like you are using a single column (feature) for X. For this code to work, you need to do this:

X_train = train['FunctionalWordPercent']
X_train = X_train.reshape(-1,1)

X_test = test['FunctionalWordPercent']
X_test = X_test.reshape(-1,1)


问:
How can I use several media queries?
I have this code and I have tried to figure out why it's not working. I have read several answers to quite similar questions, but I just don't get any wiser. Is the code in let us say (max-width:480) applying to all the other larger media queries? The only thing I can see working is the (max-width:1000)

@media screen and (max-width: 1000px) {
  .figur {
    display: none;
  }
  #about {
    width: 100%;
  }
  #map {
    width: 100%;
  }
}
@media screen and (max-width: 720px) {
  .parallax {
    background-image: url("../img/bamseLiten.jpeg");
  }
  .row .column {
    width: 100%;
    height: 200px;
  }
}
@media all and (max-width: 480px) {
  #logo {
    display: block;
    width: 70%;
    align-self: center;
  }
  .menu li {
    display: block;
    width: 100%;
  }
}```

答:
How are you testing this?

You need to make sure you are able to change the screen size... chrome offers decent ability to do this with inspect.

You may want to try using a min-width along with the max?

```<code>@media only screen and (min-width: 768px) and (max-width: 990px) {
  .class {
     position: fixed;
     top: 0;
     height:40px;
  }
}
</code>```

Title: How can I use several media queries?

Body:
How are you testing this?

You need to make sure you are able to change the screen size... chrome offers decent ability to do this with inspect.

You may want to try using a min-width along with the max?

@media only screen and (min-width: 768px) and (max-width: 990px) {
  .class {
     position: fixed;
     top: 0;
     height:40px;
  }
}


问:
How to use boto3 to send custom EC2 metrics to a CloudWatch Dashboard?
How to send custom CloudWatch metrics of EC2 instances to a CloudWatch Dashboard using boto3? Custom CloudWatch metrics like : DiskSpaceUsed, PercentFileDescriptorUsed. </p>

答:
Use put_metric_data

I use it extensively to push custom metrics to CloudWatch. Pretty straightforward. Push one metric and check CloudWatch dashboard before pushing other values.

```<code>import boto3
client = boto3.client('cloudwatch')
response = client.put_metric_data(Namespace=..., MetricData=[..])
</code>```

Body:
Use put_metric_data

I use it extensively to push custom metrics to CloudWatch. Pretty straightforward. Push one metric and check CloudWatch dashboard before pushing other values.

import boto3
client = boto3.client('cloudwatch')
response = client.put_metric_data(Namespace=..., MetricData=[..])


答: No, there are no difference in your code.</p>

Title: Are parentheses around the result significant in a return statement?