问:
3 column grid in Flexbox
I am currently attempting to create a 3 column grid layout for cards and was wondering if there was a way to do this within Flex Box. I am trying to get Box 4 under Box 1.

HTML Code:

```<code>  <div id="boxes">

    <div class="box">
      <h1>Box 1</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>

    <div class="box">
      <h1>Box 2</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>

    <div class="box">
      <h1>Box 3</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>

    <div class="box">
      <h1>Box 4</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>

  </div>
</code>```

CSS Code:

```<code>#boxes {
  display:flex;
  flex-wrap:wrap;
  .box {
    flex:1;
    border:1px solid black;
  }
}
</code>```

答:
Set the width of the .box element and flex-basis to auto. The flex-basis property defines the default size of an element before the remaining space is distributed. The auto keyword means “look at my width or height property”.

If you don't want the last element to take the available space use flex-grow: 0, that prevents the element to grow, so all your boxes will have the same width.

You can use the flex shorthand property to set all values (flex: 0 1 auto – note that this is the default value for flex), see demo below:

#boxes {
  display: flex;
  flex-wrap: wrap;
}

#boxes .box {
  flex: 0 1 auto;
  width: calc(100% / 3);
  outline: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="boxes">
  <div class="box">
    <h1>Box 1</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
  <div class="box">
    <h1>Box 2</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
  <div class="box">
    <h1>Box 3</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
  <div class="box">
    <h1>Box 4</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
</div></code>```

I also replaced the border property with outline because the border adds to the width.

For learning more about the Flexible Layout module read Chris Coyier’s excellent Guide to Flexbox.

Title: 3 column grid in Flexbox

Body:
I am currently attempting to create a 3 column grid layout for cards and was wondering if there was a way to do this within Flex Box. I am trying to get Box 4 under Box 1.

HTML Code:

Box 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Box 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Box 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Box 4

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

CSS Code:

#boxes {
  display:flex;
  flex-wrap:wrap;
  .box {
    flex:1;
    border:1px solid black;
  }
}

Body:
Set the width of the .box element and flex-basis to auto. The flex-basis property defines the default size of an element before the remaining space is distributed. The auto keyword means “look at my width or height property”.

If you don't want the last element to take the available space use flex-grow: 0, that prevents the element to grow, so all your boxes will have the same width.

You can use the flex shorthand property to set all values (flex: 0 1 auto – note that this is the default value for flex), see demo below:

#boxes {
  display: flex;
  flex-wrap: wrap;
}

#boxes .box {
  flex: 0 1 auto;
  width: calc(100% / 3);
  outline: 1px solid black;
}

<div id="boxes">
  <div class="box">
    <h1>Box 1</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
  <div class="box">
    <h1>Box 2</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
  <div class="box">
    <h1>Box 3</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
  <div class="box">
    <h1>Box 4</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
  </div>
</div>

I also replaced the border property with outline because the border adds to the width.

For learning more about the Flexible Layout module read Chris Coyier’s excellent Guide to Flexbox.


来源: stackexchange

问:
MapStruct mapper not injected in Spring Unit Tests
I'm using one mapper generated with MapStruct:

```<code>@Mapper
public interface CustomerMapper {
   Customer mapBankCustomerToCustomer(BankCustomerData bankCustomer);
}
</code>```

The default component model is spring (set in pom.xml)

```<code><compilerArg>-Amapstruct.defaultComponentModel=spring</compilerArg>
</code>```

I have a service in which I inject the customer mapper and works fine when I run the application

```<code>@Autowired
private CustomerMapper customerMapper;
</code>```

But when I run unit tests that involves @SpringBootTest

```<code>@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class SomeControllerTest {

    @Mock
    private SomeDependency someDependency;

    @InjectMocks
    private SomeController someController;

    @Test
    public void shouldDoSomething() {
        ...
    }

}
</code>```

I get an org.springframework.beans.factory.UnsatisfiedDependencyException

Unsatisfied dependency expressed through field 'customerMapper'

答:
As you are running your tests via the IDE there are 2 possibilities:

Eclipse or IntelliJ is picking up the Annotation Processors, you need to set them up correctly.

Eclipse or IntelliJ does not pick up the compiler options from the maven compiler

To rule out the possibilities do the following for each:

Make sure the IDE is configured to run APT. Have a look here how you can set it up. Run a build from the IDE and check if there are generated mapper classes

If there are they are most probably generated with the default component model. To solve this you have two options:

Use @Mapper(componentModel = "spring"). I personally prefer this option as you are IDE independent. You can also use a @MapperConfig that you can apply

Configure the IDE with the annotation options. For IntelliJ add the compiler argument in Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors, there is a section called Annotation Processor Options there add mapstruct.defaultComponentModel as option name and spring as value. I am not sure how to do it for Eclipse

ContentLicense: CC BY-SA 3.0

Body:
I'm using one mapper generated with MapStruct:

@Mapper
public interface CustomerMapper {
   Customer mapBankCustomerToCustomer(BankCustomerData bankCustomer);
}

The default component model is spring (set in pom.xml)

<compilerArg>-Amapstruct.defaultComponentModel=spring</compilerArg>

I have a service in which I inject the customer mapper and works fine when I run the application

@Autowired
private CustomerMapper customerMapper;

But when I run unit tests that involves @SpringBootTest

@SpringBootTest
@AutoConfigureMockMvc
@RunWith(SpringRunner.class)
public class SomeControllerTest {

    @Mock
    private SomeDependency someDependency;

    @InjectMocks
    private SomeController someController;

    @Test
    public void shouldDoSomething() {
        ...
    }

}

I get an org.springframework.beans.factory.UnsatisfiedDependencyException

Unsatisfied dependency expressed through field 'customerMapper'


问:
python about multiple %s in a string
```<code>str = 'I love %s and %s, he loves %s and %s.'
</code>```

I want to use this format to display

I love apple and pitch, he loves apple and pitch.

Only add two variable please, but need a way to use it twice in one sentence.

答:
Use a dict:

```<code>>>> s = 'I love %(x)s and %(y)s, he loves %(x)s and %(y)s.'
>>> s % {"x" : "apples", "y" : "oranges"}
'I love apples and oranges, he loves apples and oranges.'
</code>```

Or use the newer format function, which was introduced in 2.6:

```<code>>>> s = 'I love {0} and {1}, she loves {0} and {1}'
>>> s.format("apples", "oranges")
'I love apples and oranges, she loves apples and oranges'
</code>```

Note: Calling a variable str would mask the built-in function str([object]).

ContentLicense: CC BY-SA 2.5

Title: python about multiple %s in a string

Body:
str = 'I love %s and %s, he loves %s and %s.'

I want to use this format to display

I love apple and pitch, he loves apple and pitch.

Only add two variable please, but need a way to use it twice in one sentence.

Body:
Use a dict:

>>> s = 'I love %(x)s and %(y)s, he loves %(x)s and %(y)s.'
>>> s % {"x" : "apples", "y" : "oranges"}
'I love apples and oranges, he loves apples and oranges.'

Or use the newer format function, which was introduced in 2.6:

>>> s = 'I love {0} and {1}, she loves {0} and {1}'
>>> s.format("apples", "oranges")
'I love apples and oranges, she loves apples and oranges'

Note: Calling a variable str would mask the built-in function str([object]).


问:
Having Trouble with aligning a Hamburger Menu and Two Images in one header
I am working on creating what I thought was a simple header!

I have my hamburger menu on the far left, one image right next to the hamburger, on the far right side one more image and a header bottom border.

Here is an image of what I am trying to create:

I am having a very difficult time getting all three images on one line with a space in between the two images. I want the three to be scalable so that if it is viewed on a smaller screen they don't just stack up on top of each other. I also want them to be even and vertically centered.

A bonus fix would be if someone knew how to create the layered look of my far right image with the border showing underneath, but this is not my priority at the moment.

Here is my CSS:

```<code>body {
font-family: "Quicksand", sans-serif;
transition: background-color .5s;
}

.sidenav {
height: 100%;
width: 0;
position: absolute;
z-index: 1;
top: 0;
left: 0;
background-color: #ffffff;
overflow-x: hidden;
padding-top: 70px;
transition: 0.5s;
opacity: 0.8;
}

.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 20px;
color: #000000;
display: block;
transition: 0.3s;
}

.sidenav a:hover, .offcanvas a:focus{
color: #E1E0E1;
}

.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
padding-top:40px;
}

.openbtn {
background-color: #fffff;
margin-right: 30px;
margin-top: 0;
padding-top: 0;
height: 55px;
}

.openbtn a:active{
color: #ffffff;
}

header {
border-bottom: 1px solid #E1E0E1;
overflow:auto;
margin-left: 35px;
margin-right: 35px;
height: 90px;

}

h1 {
margin-top: 0;
background-color: #ffffff;
margin-right: 0;
}

h1, h2, .openbtn {
display:inline-block;
vertical-align: middle;
}

@media only screen and (max-device-width: 540px) {
h1 {width: 100%;}
}

@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}
</code>```

Here is my HTML:

```<code><div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">- three</a> <br> <br>
<a href="#">- two</a> <br> <br>
<a href="#">- three</a> <br> <br>
<a href="#">- four</a> <br> <br>
<a href="#">- fivr</a> <br> <br>
</div>

<div style="font-size:30px;cursor:pointer" class="openbtn"
onclick="openNav()">

<img src="hamburger.png"/> </div>

<h1> <img src="lch1.png"/> </h1>

<h2> <img src="lolo1.png"/> </h2>

<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
</script>

</header>
</code>```

答: You can set the hamburger and first image float property to left. and then set the float of the last picture to right. That would do the trick.</p>

Body:
I am working on creating what I thought was a simple header!

I have my hamburger menu on the far left, one image right next to the hamburger, on the far right side one more image and a header bottom border.

Here is an image of what I am trying to create:

I am having a very difficult time getting all three images on one line with a space in between the two images. I want the three to be scalable so that if it is viewed on a smaller screen they don't just stack up on top of each other. I also want them to be even and vertically centered.

A bonus fix would be if someone knew how to create the layered look of my far right image with the border showing underneath, but this is not my priority at the moment.

Here is my CSS:

body {
font-family: "Quicksand", sans-serif;
transition: background-color .5s;
}

.sidenav {
height: 100%;
width: 0;
position: absolute;
z-index: 1;
top: 0;
left: 0;
background-color: #ffffff;
overflow-x: hidden;
padding-top: 70px;
transition: 0.5s;
opacity: 0.8;
}

.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 20px;
color: #000000;
display: block;
transition: 0.3s;
}

.sidenav a:hover, .offcanvas a:focus{
color: #E1E0E1;
}

.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
padding-top:40px;
}

.openbtn {
background-color: #fffff;
margin-right: 30px;
margin-top: 0;
padding-top: 0;
height: 55px;
}

.openbtn a:active{
color: #ffffff;
}

header {
border-bottom: 1px solid #E1E0E1;
overflow:auto;
margin-left: 35px;
margin-right: 35px;
height: 90px;

}

h1 {
margin-top: 0;
background-color: #ffffff;
margin-right: 0;
}

h1, h2, .openbtn {
display:inline-block;
vertical-align: middle;
}

@media only screen and (max-device-width: 540px) {
h1 {width: 100%;}
}

@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}

Here is my HTML:

×
- three

- two

- three

- four

- fivr


问:
What is an abstract data type in object oriented programming?
What is an abstract data type in object oriented programming? I've gone through the wiki for this topic, but I am still unclear about it. Could someone clarify?</p>

答: An ADT defines a set of data values and a set of operations on these values.</p>


问:
C++ - stat(), access() not working under gnu gcc
I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:

```<code>#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  char path[] = "myfolder/";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}
</code>```

I have also tried the access version:

```<code>#include <iostream>
#include <io.h>

using namespace std;

int main() {
  char path[] = "myfolder/";

  if(access(path,0)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}
</code>```

Neither of them find my folder (which is right there in the same directory as the program).  These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps.  I'm sure it's a quick fix - can someone help out?

(Obviously I'm a noob at this so if you need any other information I've left out please let me know).

UPDATE

The problem was with the base directory.  The updated, working program is as follows:

```<code>#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  cout << "Current directory: " << system("cd") << endl;

  char path[] = "./bin/Release/myfolder";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Directory found." << endl; }
  else { cout << "Can't find directory." << endl; } //Doesn't exist

  cin.get();
  return 0;
}
</code>```

ANOTHER UPDATE

Turns out that a trailing backslash on the path is big trouble.

答:
You can find out why stat() failed (which is a C function, not C++, by the way), by checking errno:

```<code>#include <cerrno>

...

if (stat(path,&status) != 0)
{
    std::cout << "stat() failed:" << std::strerror(errno) << endl;
}
</code>```

Body:
I've got a pretty basic console program here, to determine if a folder or file exists or not using stat:

#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  char path[] = "myfolder/";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

I have also tried the access version:

#include <iostream>
#include <io.h>

using namespace std;

int main() {
  char path[] = "myfolder/";

  if(access(path,0)==0) { cout << "Folder found." << endl; }
  else { cout << "Can't find folder." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

Neither of them find my folder (which is right there in the same directory as the program).  These worked on my last compiler (the default one with DevCpp). I switched to CodeBlocks and am compiling with Gnu GCC now, if that helps.  I'm sure it's a quick fix - can someone help out?

(Obviously I'm a noob at this so if you need any other information I've left out please let me know).

UPDATE

The problem was with the base directory.  The updated, working program is as follows:

#include <iostream>
#include <sys/stat.h>

using namespace std;

int main() {
  cout << "Current directory: " << system("cd") << endl;

  char path[] = "./bin/Release/myfolder";
  struct stat status;

  if(stat(path,&status)==0) { cout << "Directory found." << endl; }
  else { cout << "Can't find directory." << endl; } //Doesn't exist

  cin.get();
  return 0;
}

ANOTHER UPDATE

Turns out that a trailing backslash on the path is big trouble.

Body:
You can find out why stat() failed (which is a C function, not C++, by the way), by checking errno:

#include <cerrno>

...

if (stat(path,&status) != 0)
{
    std::cout << "stat() failed:" << std::strerror(errno) << endl;
}


问:
How to fetch array data in json or get property of data in laravel
I'm trying to retrieve data from request, so I'm placing $data = $request->only('user_id', 'clientParticipants', 'event_type','contactParticipants', 'schedule', 'stellarParticipants', 'summaries', 'type', 'venue', 'with_client') the following is the format when I did dd($data) in Laravel:

```<code>array:10 [
  "user_id" => 1
  "clientParticipants" => array:2 [
    0 => array:2 [
      "label" => "Check 2 Contact - Test Company 5"
      "value" => 4
    ]
    1 => array:2 [
      "label" => "Ammy Contact - Test Company 6"
      "value" => 5
    ]
  ]
  "event_type" => 2
  "contactParticipants" => array:3 [
    0 => array:2 [
      "label" => "Check Contact - Test Company 3"
      "value" => 2
    ]
    1 => array:2 [
      "label" => "Check 1 Contact - Test Company 2"
      "value" => 3
    ]
    2 => array:2 [
      "label" => "Check 4 contact - Test Company 8"
      "value" => 6
    ]
  ]
  "schedule" => "2017-06-04 05:02:12"
  "stellarParticipants" => array:1 [
    0 => array:2 [
      "label" => "Analyst"
      "value" => 1
    ]
  ]
  "summaries" => array:2 [
    0 => array:5 [
     "client" => array:2 [
        "label" => "Test Company 4"
        "value" => 7
      ]
      "type" => "1"
      "mention" => array:2 [
        "label" => "Analyst"
        "value" => 1
      ]
      "action" => "Action Test 1"
      "comment" => "Comment Test 1"
    ]
    1 => array:5 [
      "client" => array:2 [
        "label" => "Test Company 5"
        "value" => 8
      ]
      "type" => "1"
      "mention" => array:2 [
        "label" => "Analyst"
        "value" => 1
      ]
      "action" => "Action Test 2"
      "comment" => "Comment Test 2"
    ]
  ]
  "type" => "Meeting"
  "venue" => "Mumbai"
  "with_client" => "0"
]
</code>```

I want to retrieve summaries so for this I'm trying to do following:

```<code>if($data['summaries'])
{
    $container = [];
    foreach($data['summaries'] as $summary)
    {
        $summary = json_encode($summary);
        $user_id = $summary->mention['value'];
        $container[] = new InteractionSummary([
            'company_id' => $summary->client,
            'nature' => $summary->type,
            'user_id' => $user_id,
            'action' => $summary->action,
            'feedback' => $summary->comment
        ]);
    }
    $interaction->meetingSummaries()->saveMany($container);
}
</code>```

I'm getting error while retrieving any data in summaries:

Trying to get property of non-object

Update
My InteractionSummary model is:

```<code>class InteractionSummary extends Model
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'company_id', 'interaction_id', 'nature', 'user_id', 'action', 'feedback'
    ];

    /**

     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at',
    ];
}
</code>```

Database schema:

```<code>public function up()
{
    Schema::create('interaction_summaries', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('company_id')->index();
        $table->integer('interaction_id')->index();
        $table->string('nature');
        $table->integer('user_id')->nullable();
        $table->string('action')->nullable();
        $table->string('feedback')->nullable();
        $table->softDeletes();
        $table->timestamps();
    });
}
</code>```

And Interaction have following relationship:

```<code>/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function meetingSummaries()
{
    return $this->hasMany('App\InteractionSummary');
}
</code>```

答:
You're converting the array to a json string by using json_encode. Judging from your code you probably meant to convert the array to an object.

Change

```<code>$summary = json_encode($summary);
</code>```

To

```<code>$summary = (Object)$summary;
</code>```

Also $summary->client returns an array. You probably meant to use $summary->client['value'].

Edit : Try this

```<code>if($data['summaries']) {
    foreach($data as $summary) {
        $summary = (Object)$summary;

        $interaction->meetingSummaries()->create([
            'company_id' => $summary->client['value'],
            'user_id' => $summary->mention['value'],
            'nature' => $summary->type,
            'action' => $summary->action,
            'feedback' => $summary->comment
        ]);
    }
}
</code>```

Body:
I'm trying to retrieve data from request, so I'm placing $data = $request->only('user_id', 'clientParticipants', 'event_type','contactParticipants', 'schedule', 'stellarParticipants', 'summaries', 'type', 'venue', 'with_client') the following is the format when I did dd($data) in Laravel:

array:10 [
  "user_id" => 1
  "clientParticipants" => array:2 [
    0 => array:2 [
      "label" => "Check 2 Contact - Test Company 5"
      "value" => 4
    ]
    1 => array:2 [
      "label" => "Ammy Contact - Test Company 6"
      "value" => 5
    ]
  ]
  "event_type" => 2
  "contactParticipants" => array:3 [
    0 => array:2 [
      "label" => "Check Contact - Test Company 3"
      "value" => 2
    ]
    1 => array:2 [
      "label" => "Check 1 Contact - Test Company 2"
      "value" => 3
    ]
    2 => array:2 [
      "label" => "Check 4 contact - Test Company 8"
      "value" => 6
    ]
  ]
  "schedule" => "2017-06-04 05:02:12"
  "stellarParticipants" => array:1 [
    0 => array:2 [
      "label" => "Analyst"
      "value" => 1
    ]
  ]
  "summaries" => array:2 [
    0 => array:5 [
     "client" => array:2 [
        "label" => "Test Company 4"
        "value" => 7
      ]
      "type" => "1"
      "mention" => array:2 [
        "label" => "Analyst"
        "value" => 1
      ]
      "action" => "Action Test 1"
      "comment" => "Comment Test 1"
    ]
    1 => array:5 [
      "client" => array:2 [
        "label" => "Test Company 5"
        "value" => 8
      ]
      "type" => "1"
      "mention" => array:2 [
        "label" => "Analyst"
        "value" => 1
      ]
      "action" => "Action Test 2"
      "comment" => "Comment Test 2"
    ]
  ]
  "type" => "Meeting"
  "venue" => "Mumbai"
  "with_client" => "0"
]

I want to retrieve summaries so for this I'm trying to do following:

if($data['summaries'])
{
    $container = [];
    foreach($data['summaries'] as $summary)
    {
        $summary = json_encode($summary);
        $user_id = $summary->mention['value'];
        $container[] = new InteractionSummary([
            'company_id' => $summary->client,
            'nature' => $summary->type,
            'user_id' => $user_id,
            'action' => $summary->action,
            'feedback' => $summary->comment
        ]);
    }
    $interaction->meetingSummaries()->saveMany($container);
}

I'm getting error while retrieving any data in summaries:

Trying to get property of non-object

Update
My InteractionSummary model is:

class InteractionSummary extends Model
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'company_id', 'interaction_id', 'nature', 'user_id', 'action', 'feedback'
    ];

    /**

     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    protected $dates = [
        'created_at',
        'updated_at',
        'deleted_at',
    ];
}

Database schema:

public function up()
{
    Schema::create('interaction_summaries', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('company_id')->index();
        $table->integer('interaction_id')->index();
        $table->string('nature');
        $table->integer('user_id')->nullable();
        $table->string('action')->nullable();
        $table->string('feedback')->nullable();
        $table->softDeletes();
        $table->timestamps();
    });
}

And Interaction have following relationship:

/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function meetingSummaries()
{
    return $this->hasMany('App\InteractionSummary');
}

Body:
You're converting the array to a json string by using json_encode. Judging from your code you probably meant to convert the array to an object.

Change

$summary = json_encode($summary);

To

$summary = (Object)$summary;

Also $summary->client returns an array. You probably meant to use $summary->client['value'].

Edit : Try this

if($data['summaries']) {
    foreach($data as $summary) {
        $summary = (Object)$summary;

        $interaction->meetingSummaries()->create([
            'company_id' => $summary->client['value'],
            'user_id' => $summary->mention['value'],
            'nature' => $summary->type,
            'action' => $summary->action,
            'feedback' => $summary->comment
        ]);
    }
}


问:
Fetching Data from TableView (CoreData)
I am building an app with Swift 3 and so far I have integrated the ability to store the user's location using CoreData and display them in a TableView. Now I want to retrieve each location data (if there is any and up to 20 locations) to continue working with that.

I have trouble doing that, could someone assist me?

答:
Please check the stackOverFlow.

It helps.

When using core data and a tableview, you should use NSFetchedResultsController. This essentially retrieves data from core data and organizes it by section and indexPath so it can easily be set as the data source of the tableView.

Title: Fetching Data from TableView (CoreData)


问:
How to find the length of a "filter" object in python
```<code>>>> n = [1,2,3,4]

>>> filter(lambda x:x>3,n)
<filter object at 0x0000000002FDBBA8>

>>> len(filter(lambda x:x>3,n))
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    len(filter(lambda x:x>3,n))
TypeError: object of type 'filter' has no len()
</code>```

I could not get the length of the list I got. So I tried saving it to a variable, like this...

```<code>>>> l = filter(lambda x:x>3,n)
>>> len(l)
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    len(l)
TypeError: object of type 'filter' has no len()
</code>```

Instead of using a loop, is there any way to get the length of this?

答:
This is an old question, but I think this question needs an answer using the map-reduce ideology.
So here:

```<code>from functools import reduce

def ilen(iterable):
    return reduce(lambda sum, element: sum + 1, iterable, 0)

ilen(filter(lambda x: x > 3, n))
</code>```

This is especially good if n doesn't fit in the computer memory.

Body:
>>> n = [1,2,3,4]

>>> filter(lambda x:x>3,n)
<filter object at 0x0000000002FDBBA8>

>>> len(filter(lambda x:x>3,n))
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    len(filter(lambda x:x>3,n))
TypeError: object of type 'filter' has no len()

I could not get the length of the list I got. So I tried saving it to a variable, like this...

>>> l = filter(lambda x:x>3,n)
>>> len(l)
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    len(l)
TypeError: object of type 'filter' has no len()

Instead of using a loop, is there any way to get the length of this?

Body:
This is an old question, but I think this question needs an answer using the map-reduce ideology.
So here:

from functools import reduce

def ilen(iterable):
    return reduce(lambda sum, element: sum + 1, iterable, 0)

ilen(filter(lambda x: x > 3, n))

This is especially good if n doesn't fit in the computer memory.


问:
Golden section search
I am trying to find the maximum value in function zt between tl=0 and tu=10 but the code is not working to find the maximum value. What is wrong with my code?

```<code>#include <stdio.h>
#include <math.h>

#define e 2.718281828459

double zt(double t)
{
    return (100 + (80 / 15)* (55 + 80*9.81 / 15) * (1 - pow(e, -(15/80)*t)) - (80*9.81 / 15)*t);
}

void Golden(double tl, double tu)
{
    int i;                              //이터레이션 i
    int imax = 100;                 //i가 무한히 반복되지 않도록 max값 설정
    double es = 0.01;   //상대오차가 충분히 작아졌을때 중단하기 위한 es 설정
    long double t1 = tl + (tu - tl)*((pow(5,0.5) - 1) / 2);
    long double t2 = tu - (tu - tl)*((pow(5,0.5) - 1) / 2);
    long double pz;
    long double pzold = 0;
    double pt;
    long double ea;                     // 상대오차

    printf("Golden Section Search \n");

    for (i = 1; i <= imax; i++)
    {

        if (zt(t1) > zt(t2))
        {
            pz = zt(t1);
            pt = t1;
        }

        else if (zt(t2)>zt(t1))
        {
            pz = zt(t2);
            pt = t2;
        }

        ea = fabs((tu - tl) / pt) * 100; //

        printf("iteration=%d Peak altitude=%.10f Peak Time=%.10f Error=%.15f\n", i, pz, pt, ea);

        pzold = pz;                 //xrold 값을 xr 로 설정하여 다음 이터레이션의 상대오차를 구하기위해 정의한다

        if (ea < es)
        {
            break;              //ea가 es보다 작아질 경우 xr이 근에 충분히 근접하였으므로 중단
        }

        if (zt(t1)>zt(t2))          //조건문으로 함수 f(xr)의 음수 양수 판단후 다음 iteration 에서의 xu, xl 값 설정
        {
            tl = t2;
            t2 = t1;
            t1= tl + fabs(tu - tl)*((pow(5,0.5) - 1) / 2);
        }

        else if (zt(t2)>zt(t1))
        {
            tu = t1;
            t1 = t2;
            t2= tu - fabs(tu - tl)*((pow(5,0.5) - 1) / 2);
        }

    }

}

int main(void)
{
    Golden(0, 10);

    return 0;
}
</code>```

答:
My suspicion is that the incorrect results are caused by the integer calculations going on. Let's look at the function zt:

```<code>double zt(double t)
{
    return (100 + (80 / 15)* (55 + 80*9.81 / 15) * (1 - pow(e, -(15/80)*t)) - (80*9.81 / 15)*t);
}
</code>```

Note that most of the numbers there are integer literals (that is, there is no fractional part). This means that integer operations occur until a double value gets involved.

One notable difference between floating-point arithmetic and integer arithmetic in with the division operator /:

```<code>int val_1 = 10 / 4; // 2, because the fractional part is discarded
double val_2 = 10.0 / 4.0; // 2.5
</code>```

To fix this issue in your code, you could change the return statement to:

```<code>return (100.0 + (80.0 / 15.0) * (55.0 + 80.0*9.81 / 15.0)) * (1.0 - pow(e, -(15.0/80.0)*t)) - (80.0*9.81 / 15.0);
</code>```

Another possible issue is that some round brackets are misplaced, causing the results to evaluate to something different. This can be better detected (if it is present) by using variables to hold each notable sub-expression, and then doing calculations with those.

Title: Golden section search

Body:
I am trying to find the maximum value in function zt between tl=0 and tu=10 but the code is not working to find the maximum value. What is wrong with my code?

#include <stdio.h>
#include <math.h>

#define e 2.718281828459

double zt(double t)
{
    return (100 + (80 / 15)* (55 + 80*9.81 / 15) * (1 - pow(e, -(15/80)*t)) - (80*9.81 / 15)*t);
}

void Golden(double tl, double tu)
{
    int i;                              //이터레이션 i
    int imax = 100;                 //i가 무한히 반복되지 않도록 max값 설정
    double es = 0.01;   //상대오차가 충분히 작아졌을때 중단하기 위한 es 설정
    long double t1 = tl + (tu - tl)*((pow(5,0.5) - 1) / 2);
    long double t2 = tu - (tu - tl)*((pow(5,0.5) - 1) / 2);
    long double pz;
    long double pzold = 0;
    double pt;
    long double ea;                     // 상대오차

    printf("Golden Section Search \n");

    for (i = 1; i <= imax; i++)
    {

        if (zt(t1) > zt(t2))
        {
            pz = zt(t1);
            pt = t1;
        }

        else if (zt(t2)>zt(t1))
        {
            pz = zt(t2);
            pt = t2;
        }

        ea = fabs((tu - tl) / pt) * 100; //

        printf("iteration=%d Peak altitude=%.10f Peak Time=%.10f Error=%.15f\n", i, pz, pt, ea);

        pzold = pz;                 //xrold 값을 xr 로 설정하여 다음 이터레이션의 상대오차를 구하기위해 정의한다

        if (ea < es)
        {
            break;              //ea가 es보다 작아질 경우 xr이 근에 충분히 근접하였으므로 중단
        }

        if (zt(t1)>zt(t2))          //조건문으로 함수 f(xr)의 음수 양수 판단후 다음 iteration 에서의 xu, xl 값 설정
        {
            tl = t2;
            t2 = t1;
            t1= tl + fabs(tu - tl)*((pow(5,0.5) - 1) / 2);
        }

        else if (zt(t2)>zt(t1))
        {
            tu = t1;
            t1 = t2;
            t2= tu - fabs(tu - tl)*((pow(5,0.5) - 1) / 2);
        }

    }

}

int main(void)
{
    Golden(0, 10);

    return 0;
}

Body:
My suspicion is that the incorrect results are caused by the integer calculations going on. Let's look at the function zt:

double zt(double t)
{
    return (100 + (80 / 15)* (55 + 80*9.81 / 15) * (1 - pow(e, -(15/80)*t)) - (80*9.81 / 15)*t);
}

Note that most of the numbers there are integer literals (that is, there is no fractional part). This means that integer operations occur until a double value gets involved.

One notable difference between floating-point arithmetic and integer arithmetic in with the division operator /:

int val_1 = 10 / 4; // 2, because the fractional part is discarded
double val_2 = 10.0 / 4.0; // 2.5

To fix this issue in your code, you could change the return statement to:

return (100.0 + (80.0 / 15.0) * (55.0 + 80.0*9.81 / 15.0)) * (1.0 - pow(e, -(15.0/80.0)*t)) - (80.0*9.81 / 15.0);

Another possible issue is that some round brackets are misplaced, causing the results to evaluate to something different. This can be better detected (if it is present) by using variables to hold each notable sub-expression, and then doing calculations with those.


问:
How to delay a JQUERY onload function
I've found some solutions online for this but couldn't make them work for me. Or maybe I was doing it wrong. I am completely newbie in JS, can you please help me to delay this function?</p>

```<code>jQuery(window).on('load', function(){ var $ = jQuery;
var $container = $('.social_container');
$container.masonry({
      columnWidth:350,
      gutterWidth: 355,
      itemSelector: '.masonryImage'
});
});
</code>```

答:
Use setTimer()

```<code>jQuery(window).on('load', function() {
    setTimer(function() {
        var $ = jQuery;
        var $container = $('.social_container');
        $container.masonry({
            columnWidth: 350,
            gutterWidth: 355,
            itemSelector: '.masonryImage'
        });
    }, 1000);
});
</code>```

This will delay it for 1 second.

Title: How to delay a JQUERY onload function

Body:
I've found some solutions online for this but couldn't make them work for me. Or maybe I was doing it wrong. I am completely newbie in JS, can you please help me to delay this function?

jQuery(window).on('load', function(){ var $ = jQuery;
var $container = $('.social_container');
$container.masonry({
      columnWidth:350,
      gutterWidth: 355,
      itemSelector: '.masonryImage'
});
});

Body:
Use setTimer()

jQuery(window).on('load', function() {
    setTimer(function() {
        var $ = jQuery;
        var $container = $('.social_container');
        $container.masonry({
            columnWidth: 350,
            gutterWidth: 355,
            itemSelector: '.masonryImage'
        });
    }, 1000);
});

This will delay it for 1 second.


问:
ending "+" prompt in R
I'm fairly new to R and I made a type-o while entering some code and now instead of getting the ">" prompt I get a "+" prompt. I appear to be stuck in some kind of function that is looking for input, but I can't seem to get out of it. I figure that there must be a better way to fix this problem then closing R and rerunning my script but I haven't been able to find anything on google (likely because I don't know the right search terms).

Thanks for your help, sorry it's a trivial question

The code I entered was as follows:

```<code>> fit = lm(x~`y)
+ fit = lm(x~y)
+ fit
+ summary(fit)
+
+
+ end
+ ;
+ break
+ )
+
+
+
+

+

+ quit()
+
+ quit
+ break()
+ abline(b0hat,b1hat)
+ return(null)
+
</code>```

答: I am using RStudio 3.3.1  and had a the same problem. Press Escape key for worked. Please try this and let me know if I  can help more...</p>

Title: ending "+" prompt in R

Body:
I'm fairly new to R and I made a type-o while entering some code and now instead of getting the ">" prompt I get a "+" prompt. I appear to be stuck in some kind of function that is looking for input, but I can't seem to get out of it. I figure that there must be a better way to fix this problem then closing R and rerunning my script but I haven't been able to find anything on google (likely because I don't know the right search terms).

Thanks for your help, sorry it's a trivial question

The code I entered was as follows:

> fit = lm(x~`y)
+ fit = lm(x~y)
+ fit
+ summary(fit)
+
+
+ end
+ ;
+ break
+ )
+
+
+
+

+

+ quit()
+
+ quit
+ break()
+ abline(b0hat,b1hat)
+ return(null)
+


问:
Where can I download Coldfusion MX 7 for Mac?
It seems like it is no longer downloadable from Adobe, so I was wondering if anyone out there knows where I can download it from. </p>

答:
Time to upgrade to ColdFusion 9. If that is not an option, I would encourage you to download ColdFusion 9 (or an open source CFML engine like Railo) and develop code using only the features and syntax allowed in CF7.

There are many reasons to upgrade from ColdFusion 7 to ColdFusion 9. The improvements can help save many hours from development--and programmers/time usually costs more than the the upgrade fee. If money is a difficulty here, Railo is a good alternative--some would argue an equal one.


问:
Hide action column items in ext js
I want to hide action column items on condition, Please look below code.

```<code>{
 xtype: 'actioncolumn',
 flex: 1,
 sortable: false,
 menuDisabled: true,
 align: 'center',
 items: [{

     icon: (fleet.rolerightscreate.modulerights('Editmanagevehicle', 'Manage Vehicle', 'E') != null) ? FLEET_SERVER_URL + 'images/edit2.png' : '',
     tooltip: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_EDIT_'),
     scope: this,

     handler: function(grid, rowIndex, colIndex) {

         //var data = Vehiclestore.data.items[rowIndex].data;
         var rec = grid.getStore().getAt(rowIndex);
         console.log(rec);
         if (fleet.rolerightscreate.modulerights('Editmanagevehicle', 'Manage Vehicle', 'E') != null) {
             this.fireEvent("ShowVehicleDetails", rec);
         }
     }
 }, {
     xtype: 'spacer'
 }, {
     icon: (Ext.getStore('userStore').first().get('issuperadmin') == 1 ? FLEET_SERVER_URL + 'images/del.png' : ''),
     //(fleet.rolerightscreate.modulerights('Deletemanagevehicle', 'Manage Vehicle', 'D') != null) ? FLEET_SERVER_URL + 'images/del.png' : '',  // Use a URL in the icon config

     tooltip: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_DELETE_'),
     handler: function(grid, rowIndex, colIndex) {
         var rec = grid.getStore().getAt(rowIndex);
         if (fleet.rolerightscreate.modulerights('Deletemanagevehicle', 'Manage Vehicle', 'D') != null) {
             Ext.Msg.show({
                 title: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_REMOVETITLE_'),
                 msg: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_REMOVEMSG_'),
                 buttons: Ext.Msg.YESNO,
                 icon: Ext.Msg.QUESTION,
                 callback: function(button) {
                     if (button == fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_YESBTN_')) {
                         me.removeVehicle(rec);
                     }
                 }
             });
         }
     }
 }]
}
</code>```

In above code, Action column contain 3 Items, Edit, space (i.e.  { xtype: 'spacer' }), and Delete Icons. I want to hide Delete Icon on condition. Means delete option shown only when admin user login.
please look design for this, you can get better idea about problem

Using this code bellow I am able to hide Delete icon but tooltip and click event still fire on click on hidden icon location.

```<code>icon: (Ext.getStore('userStore').first().get('issuperadmin') == 1 ? FLEET_SERVER_URL + 'images/del.png' : ''),
</code>```

答:
I don't think hiding or disabling the icon is the solution here. If the user is not admin why bother with adding the icon at all. I would buildActionColumnItems method that will return the items for the action column based on current user's role.

The action column config:

```<code>{
    xtype: 'actioncolumn',
    flex: 1,
    sortable: false,
    menuDisabled: true,
    align: 'center',
    items: this.buildActionColumnItems()
}
</code>```

The buildActionColumnItems method implementation:

```<code>buildActionColumnItems: function () {
    //set the implicit items
    var columnItems = [{
        icon: (fleet.rolerightscreate.modulerights('Editmanagevehicle', 'Manage Vehicle', 'E') != null) ? FLEET_SERVER_URL + 'images/edit2.png' : '',
        tooltip: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_EDIT_'),
        ...
    }];

    //add aditional items if the user is super admin
    if (Ext.getStore('userStore').first().get('issuperadmin') == 1) {
        columnItems.push({
            xtype: 'spacer'
        });
        columnItems.push({
            icon: FLEET_SERVER_URL + 'images/del.png',
            tooltip: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_DELETE_'),
            ...
        });
    }

    return columnItems;
}
</code>```

Title: Hide action column items in ext js

Body:
I want to hide action column items on condition, Please look below code.

{
 xtype: 'actioncolumn',
 flex: 1,
 sortable: false,
 menuDisabled: true,
 align: 'center',
 items: [{

     icon: (fleet.rolerightscreate.modulerights('Editmanagevehicle', 'Manage Vehicle', 'E') != null) ? FLEET_SERVER_URL + 'images/edit2.png' : '',
     tooltip: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_EDIT_'),
     scope: this,

     handler: function(grid, rowIndex, colIndex) {

         //var data = Vehiclestore.data.items[rowIndex].data;
         var rec = grid.getStore().getAt(rowIndex);
         console.log(rec);
         if (fleet.rolerightscreate.modulerights('Editmanagevehicle', 'Manage Vehicle', 'E') != null) {
             this.fireEvent("ShowVehicleDetails", rec);
         }
     }
 }, {
     xtype: 'spacer'
 }, {
     icon: (Ext.getStore('userStore').first().get('issuperadmin') == 1 ? FLEET_SERVER_URL + 'images/del.png' : ''),
     //(fleet.rolerightscreate.modulerights('Deletemanagevehicle', 'Manage Vehicle', 'D') != null) ? FLEET_SERVER_URL + 'images/del.png' : '',  // Use a URL in the icon config

     tooltip: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_DELETE_'),
     handler: function(grid, rowIndex, colIndex) {
         var rec = grid.getStore().getAt(rowIndex);
         if (fleet.rolerightscreate.modulerights('Deletemanagevehicle', 'Manage Vehicle', 'D') != null) {
             Ext.Msg.show({
                 title: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_REMOVETITLE_'),
                 msg: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_REMOVEMSG_'),
                 buttons: Ext.Msg.YESNO,
                 icon: Ext.Msg.QUESTION,
                 callback: function(button) {
                     if (button == fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_YESBTN_')) {
                         me.removeVehicle(rec);
                     }
                 }
             });
         }
     }
 }]
}

In above code, Action column contain 3 Items, Edit, space (i.e.  { xtype: 'spacer' }), and Delete Icons. I want to hide Delete Icon on condition. Means delete option shown only when admin user login.
please look design for this, you can get better idea about problem

Using this code bellow I am able to hide Delete icon but tooltip and click event still fire on click on hidden icon location.

icon: (Ext.getStore('userStore').first().get('issuperadmin') == 1 ? FLEET_SERVER_URL + 'images/del.png' : ''),

Body:
I don't think hiding or disabling the icon is the solution here. If the user is not admin why bother with adding the icon at all. I would buildActionColumnItems method that will return the items for the action column based on current user's role.

The action column config:

{
    xtype: 'actioncolumn',
    flex: 1,
    sortable: false,
    menuDisabled: true,
    align: 'center',
    items: this.buildActionColumnItems()
}

The buildActionColumnItems method implementation:

buildActionColumnItems: function () {
    //set the implicit items
    var columnItems = [{
        icon: (fleet.rolerightscreate.modulerights('Editmanagevehicle', 'Manage Vehicle', 'E') != null) ? FLEET_SERVER_URL + 'images/edit2.png' : '',
        tooltip: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_EDIT_'),
        ...
    }];

    //add aditional items if the user is super admin
    if (Ext.getStore('userStore').first().get('issuperadmin') == 1) {
        columnItems.push({
            xtype: 'spacer'
        });
        columnItems.push({
            icon: FLEET_SERVER_URL + 'images/del.png',
            tooltip: fleet.Language.get('_FLEET_VEHICLE_VEHICLELIST_DELETE_'),
            ...
        });
    }

    return columnItems;
}


问:
Facebook authentication with new 'Facebook SDK for iOS' vs. old 'Facebook iPhone SDK'
I'm working on integrating Facebook with my iPhone/iOS application and I want to know if I'm understanding the nature of the login procedure correctly.

With the old Facebook SDK ('Facebook iPhone SDK'), when we needed to request authentication permission from a user a UIWebView would be displayed with a login prompt. With the new SDK ('Facebook SDK for iOS'), the SDK uses Apple's fast-app-switching feature to temporarily place the app in background mode and then load the iOS Facebook app or Safari to authenticate. Is this basically the gist of it?

I've experimented with authenticating my app via the new SDK's technique and due to the nature of my app, it just can't support backgrounding. Does this mean I have to use the old SDK to launch a UIWebView-based authentication? I think this implementation is a lot cleaner anyway. Will I run into any major disadvantages from doing this?

答:
Take a look on this page:  https://github.com/facebook/facebook-ios-sdk

And look at Single Sign-On.  That describes the above scenario with fast switching.


问:
Python order filling loop?
Let's say I have a bunch of orders I need to fill

```<code>orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5]
</code>```

I have a starting volume of say 100

```<code>startingvolume = 100
</code>```

I want to iterate through the orders until my volume/order is filled

so the first order would be my initial 100 minus the first order of 39.789032 which leaves 60.2110968 of my order still to be filled. What is the most Pythonic way to fill my order until my starting volume is 0?

答:
NumPy makes this easy.

```<code>import numpy as np

def fill(orders, startingvolume):
    orders = np.asarray(orders)
    return orders[orders.cumsum() <= startingvolume]
</code>```

Given your example inputs, that will return:

```<code>array([ 39.789032 ,  36.023618 ,   3.0539913,  20.       ])
</code>```

Which are the orders you've filled completely.  To get the one remaining one that you partially filled:

```<code>orders[orders.cumsum() >= startingvolume][0]
</code>```

Title: Python order filling loop?

Body:
Let's say I have a bunch of orders I need to fill

orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5]

I have a starting volume of say 100

startingvolume = 100

I want to iterate through the orders until my volume/order is filled

so the first order would be my initial 100 minus the first order of 39.789032 which leaves 60.2110968 of my order still to be filled. What is the most Pythonic way to fill my order until my starting volume is 0?

Body:
NumPy makes this easy.

import numpy as np

def fill(orders, startingvolume):
    orders = np.asarray(orders)
    return orders[orders.cumsum() <= startingvolume]

Given your example inputs, that will return:

array([ 39.789032 ,  36.023618 ,   3.0539913,  20.       ])

Which are the orders you've filled completely.  To get the one remaining one that you partially filled:

orders[orders.cumsum() >= startingvolume][0]


问:
Django serializer classes referencing each other
I need to have two serializer classes referencing each other but I'm getting one of the classes not defined if both classes are referencing each other.  I created a duplicate of one of the class w/ a difference name and this seems to work but is there a better way to do this without making 3 classes?</p>

```<code>class ArtistSerializer(serializers.ModelSerializer):

    name = serializers.CharField()
    class Meta:
        model = Artist
        fields = ('id', 'name',)

class TrackSerializer(serializers.ModelSerializer):

    artist = ArtistSerializer(read_only=True)
    class Meta:
        model = Track
        fields = ('id', 'artist', 'title',)

class ArtistSerializer2(serializers.ModelSerializer):

    name = serializers.CharField()
    tracks = TrackSerializer(many=True, read_only=True)
    class Meta:
        model = Artist
        fields = ('id', 'name', 'slug', 'tracks')
</code>```

答:
This is a circular class dependency. Your solution is one of the work arounds available for it. Another option is to avoid the circular dependecy all together by using a StringRelatedField

StringRelatedField may be used to represent the target of the
  relationship using its unicode method.

```<code>class ArtistSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True)
    name = serializers.CharField()
    class Meta:
        model = Artist
        fields = ('id', 'name', 'slug', 'tracks')

class TrackSerializer(serializers.ModelSerializer):

    artist = StringRelatedField()  # read only by default.
    class Meta:
        model = Track
        fields = ('id', 'artist', 'title',)
</code>```

Body:
I need to have two serializer classes referencing each other but I'm getting one of the classes not defined if both classes are referencing each other.  I created a duplicate of one of the class w/ a difference name and this seems to work but is there a better way to do this without making 3 classes?

class ArtistSerializer(serializers.ModelSerializer):

    name = serializers.CharField()
    class Meta:
        model = Artist
        fields = ('id', 'name',)

class TrackSerializer(serializers.ModelSerializer):

    artist = ArtistSerializer(read_only=True)
    class Meta:
        model = Track
        fields = ('id', 'artist', 'title',)

class ArtistSerializer2(serializers.ModelSerializer):

    name = serializers.CharField()
    tracks = TrackSerializer(many=True, read_only=True)
    class Meta:
        model = Artist
        fields = ('id', 'name', 'slug', 'tracks')

Body:
This is a circular class dependency. Your solution is one of the work arounds available for it. Another option is to avoid the circular dependecy all together by using a StringRelatedField

StringRelatedField may be used to represent the target of the
  relationship using its unicode method.

class ArtistSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True)
    name = serializers.CharField()
    class Meta:
        model = Artist
        fields = ('id', 'name', 'slug', 'tracks')

class TrackSerializer(serializers.ModelSerializer):

    artist = StringRelatedField()  # read only by default.
    class Meta:
        model = Track
        fields = ('id', 'artist', 'title',)


答:
You can use setTimeout() of javascript :-</p>

```<code>jQuery(window).on('load', function() {
    setTimeout(function() {
        var $ = jQuery;
        var $container = $('.social_container');
        $container.masonry({
            columnWidth: 350,
            gutterWidth: 355,
            itemSelector: '.masonryImage'
        });
    }, 2000);
});
</code>```

Title: How to delay a JQUERY onload function

Body:
You can use setTimeout() of javascript :-

jQuery(window).on('load', function() {
    setTimeout(function() {
        var $ = jQuery;
        var $container = $('.social_container');
        $container.masonry({
            columnWidth: 350,
            gutterWidth: 355,
            itemSelector: '.masonryImage'
        });
    }, 2000);
});


问:
How to Transforming origin for painteventargs in a c# winform?
I want to draw some geometric figure as in coordinate geometry. I have written following code in a panels paint event

```<code>Graphics g = e.Graphics;

//Transforming (0,0) origin at center of the panel
g.TranslateTransform(panel1.Width / 2, panel1.Height / 2);

// For Drawing Axes
g.DrawLine(Pens.Red, new Point(-300, 0), new Point(300, 0));
g.DrawLine(Pens.Red, new Point(0,-300), new Point(0,300));

g.DrawEllipse(Pens.Blue, new Rectangle(50,50,100,100));// this circle should come in I-quad
</code>```

Here it is understood that since, my origin is transformed to the center of the panel,
Points below to the horizontal line is +ve and above is -ve. and similarly Points right to the vertical line is +ve and left is -ve.

what should I do to flip horizontal line, so that above values should be +ve and below should be -ve ( As in coordinate plane)?
and my drawn circle should come in 1-quadrant instead of 4-quadrant.

答:
Add the following line to your transformations.</p>

```<code>g.ScaleTransform(1.0F, -1.0F);
</code>```

Body:
I want to draw some geometric figure as in coordinate geometry. I have written following code in a panels paint event

Graphics g = e.Graphics;

//Transforming (0,0) origin at center of the panel
g.TranslateTransform(panel1.Width / 2, panel1.Height / 2);

// For Drawing Axes
g.DrawLine(Pens.Red, new Point(-300, 0), new Point(300, 0));
g.DrawLine(Pens.Red, new Point(0,-300), new Point(0,300));

g.DrawEllipse(Pens.Blue, new Rectangle(50,50,100,100));// this circle should come in I-quad

Here it is understood that since, my origin is transformed to the center of the panel,
Points below to the horizontal line is +ve and above is -ve. and similarly Points right to the vertical line is +ve and left is -ve.

what should I do to flip horizontal line, so that above values should be +ve and below should be -ve ( As in coordinate plane)?
and my drawn circle should come in 1-quadrant instead of 4-quadrant.

Body:
Add the following line to your transformations.

g.ScaleTransform(1.0F, -1.0F);


答:
You can use display:flex at wrapper. it is a great property which help us to align all its child in centet with respect to each other.

You can check sample at the following link

```<code>https://codepen.io/jainaman23/pen/NgWEVW
</code>```

Title: Having Trouble with aligning a Hamburger Menu and Two Images in one header

Body:
I am working on creating what I thought was a simple header!

I have my hamburger menu on the far left, one image right next to the hamburger, on the far right side one more image and a header bottom border.

Here is an image of what I am trying to create:

I am having a very difficult time getting all three images on one line with a space in between the two images. I want the three to be scalable so that if it is viewed on a smaller screen they don't just stack up on top of each other. I also want them to be even and vertically centered.

A bonus fix would be if someone knew how to create the layered look of my far right image with the border showing underneath, but this is not my priority at the moment.

Here is my CSS:

body {
font-family: "Quicksand", sans-serif;
transition: background-color .5s;
}

.sidenav {
height: 100%;
width: 0;
position: absolute;
z-index: 1;
top: 0;
left: 0;
background-color: #ffffff;
overflow-x: hidden;
padding-top: 70px;
transition: 0.5s;
opacity: 0.8;
}

.sidenav a {
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 20px;
color: #000000;
display: block;
transition: 0.3s;
}

.sidenav a:hover, .offcanvas a:focus{
color: #E1E0E1;
}

.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
padding-top:40px;
}

.openbtn {
background-color: #fffff;
margin-right: 30px;
margin-top: 0;
padding-top: 0;
height: 55px;
}

.openbtn a:active{
color: #ffffff;
}

header {
border-bottom: 1px solid #E1E0E1;
overflow:auto;
margin-left: 35px;
margin-right: 35px;
height: 90px;

}

h1 {
margin-top: 0;
background-color: #ffffff;
margin-right: 0;
}

h1, h2, .openbtn {
display:inline-block;
vertical-align: middle;
}

@media only screen and (max-device-width: 540px) {
h1 {width: 100%;}
}

@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}

Here is my HTML:

×
- three

- two

- three

- four

- fivr

Body:
You can use display:flex at wrapper. it is a great property which help us to align all its child in centet with respect to each other.

You can check sample at the following link

https://codepen.io/jainaman23/pen/NgWEVW


问:
clang++ compiling template class with implementation in header
```<code>$ make
clang++ -o build/blist.exe  src/driver.cpp src/BList.h -O0 -g -Wall -Wno-unused-parameter -Wextra -Wconversion -Wold-style-cast -std=c++14 -pedantic -Wold-style-cast
clang: warning: treating 'c-header' input as 'c++-header' when in C++ mode, this behavior is deprecated [-Wdeprecated]
clang: error: cannot specify -o when generating multiple output files
</code>```

My template implementation is in BList.cpp, but BList.h includes BList.cpp. That's why I pass the header in as an object. I don't know how to set clang to compile!

My header must be named "BList.h" according to my professor.

These parameters compiles with GCC, but not with Clang.

答:
The error has nothing to do with including BList.cpp in BList.h (though that's a dubious practice by itself).

The problem is that you pass src/BList.h to Clang as if it was a source file. The build instruction should be:

clang++ -o build/blist.exe  src/driver.cpp -O0 -g -Wall -Wno-unused-parameter -Wextra -Wconversion -Wold-style-cast -std=c++14 -pedantic -Wold-style-cast
```

You should update your makefile accordingly.

Body:
$ make
clang++ -o build/blist.exe  src/driver.cpp src/BList.h -O0 -g -Wall -Wno-unused-parameter -Wextra -Wconversion -Wold-style-cast -std=c++14 -pedantic -Wold-style-cast
clang: warning: treating 'c-header' input as 'c++-header' when in C++ mode, this behavior is deprecated [-Wdeprecated]
clang: error: cannot specify -o when generating multiple output files

My template implementation is in BList.cpp, but BList.h includes BList.cpp. That's why I pass the header in as an object. I don't know how to set clang to compile!

My header must be named "BList.h" according to my professor.

These parameters compiles with GCC, but not with Clang.

Body:
The error has nothing to do with including BList.cpp in BList.h (though that's a dubious practice by itself).

The problem is that you pass src/BList.h to Clang as if it was a source file. The build instruction should be:

clang++ -o build/blist.exe  src/driver.cpp -O0 -g -Wall -Wno-unused-parameter -Wextra -Wconversion -Wold-style-cast -std=c++14 -pedantic -Wold-style-cast

You should update your makefile accordingly.


问:
Difference Between Spark SQL and Hive
Can you please help me to understand the difference between Spark SQl and Hive?</p>

答:
The Apache Hive data warehouse software facilitates reading, writing, and managing large datasets residing in distributed storage and queried using SQL syntax.

Built on top of Apache Hadoop, Hive provides the following features:

Tools to enable easy access to data via SQL, thus enabling data warehousing tasks such as extract/transform/load (ETL), reporting, and data analysis.

Access to files stored either directly in Apache HDFS or in other data storage systems such as Apache HBase

Sub-second query retrieval via Hive LLAP, Apache YARN and Apache Slider.

A mechanism to impose structure on a variety of data formats

Where as, Apache Spark is a fast and general-purpose cluster computing system. It provides high-level APIs in Java, Scala, Python and R, and an optimized engine that supports general execution graphs. It also supports a rich set of higher-level tools including Spark SQL for SQL and structured data processing.

Spark SQL is a Spark module for structured data processing, in which in-memory processing is its core. Using Spark SQL, can read the data from any structured sources, like JSON, CSV, parquet, avro, sequencefiles, jdbc , hive etc.

Spark SQL can also be used to read data from an existing Hive installation. Thus, Spark SQL is the generalized module which can be used to process any structured data-source.

Title: Difference Between Spark SQL and Hive


问:
How to create dynamic route in Laravel?
I create compare page for products,

I need create route for compare page, How to create dynamic route in Laravel 5.3?

For example:

```<code>https://www.mywesite.com/Compare/DKP-181451/DKP-254287/DKP-254282/DKP-227429/DKP-254282
</code>```

This page is 5 product for compare.

Or:

```<code>https://www.mywesite.com/Compare/DKP-181451/DKP-254287
</code>```

This page is 2 product for compare.

答:
The following will probably work:</p>

```<code> Route::get("Compare/{any}", function ($any) {
       $productsToCompare = explode("/",$any);
       // Compare products.

 })->where("any", ".*");
</code>```

Title: How to create dynamic route in Laravel?

Body:
I create compare page for products,

I need create route for compare page, How to create dynamic route in Laravel 5.3?

For example:

https://www.mywesite.com/Compare/DKP-181451/DKP-254287/DKP-254282/DKP-227429/DKP-254282

This page is 5 product for compare.

Or:

https://www.mywesite.com/Compare/DKP-181451/DKP-254287

This page is 2 product for compare.

Body:
The following will probably work:

 Route::get("Compare/{any}", function ($any) {
       $productsToCompare = explode("/",$any);
       // Compare products.

 })->where("any", ".*");


问:
How to create bottom navigation bar similar to instagram
I am an android newbie trying to create a bottom navigation bar for my new android app similar to one there in Instagram. Like this  where clicking on the search icon adds a search bar in action bar.
I am building an app for reminding the user about his medical appointments which has three navigation tabs at the bottom. I have created till this  after this I am stuck. Should I use three activities to display the content of corresponding tabs or fragments and how can I achieve that.

I need a recyclerview to display appointments. How can I display the search bar only when the search icon at bottom is clicked.
 Have searched a lot on achieving this but could not find anything useful.

Any suggestions for code or library which achieves the same would be great help thanks.

答:
you put your bottom navigation in the activity and fill it with whatever you want then you use this

```<code>bottomNavigationView.setOnNavigationItemSelectedListener(this);
</code>```

To add an item select listener. You also implement required method in your activity like this

```<code>@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.action_home:
            //open home fragment
            break;

        case R.id.action_search:
            //open search or whatever
            break;

    }

    return true;
}
</code>```

Now it's up to you to do whatever you want when some item is selected, for example when search item is selected you can show search section and hide it when other items are selected.

Body:
you put your bottom navigation in the activity and fill it with whatever you want then you use this

bottomNavigationView.setOnNavigationItemSelectedListener(this);

To add an item select listener. You also implement required method in your activity like this

@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()){
        case R.id.action_home:
            //open home fragment
            break;

        case R.id.action_search:
            //open search or whatever
            break;

    }

    return true;
}

Now it's up to you to do whatever you want when some item is selected, for example when search item is selected you can show search section and hide it when other items are selected.


问:
How to launch a program from bash script, then close Terminal but keep the program alive
I wanted to have an icon in my desktop to start Redshift with a custom parameter which is read from the command line upon launching.

This is what I came up with:

#!/bin/bash
default_temperature=4500
echo "Default color temperature (Night) is "$default_temperature"K."
read -p "Type in the desired value: " temperature
temperature=${temperature:-$default_temperature}
nohup redshift-gtk -l "-23.9141:-147.6650" -t "6500:"$temperature &
```

<p>The above file is saved as <code>/home/redshift.sh</code>. I also created a desktop entry to launch it, with the following code:</p>

<pre class="lang-none prettyprint-override"><code>#!/usr/bin/env xdg-open
[Desktop Entry]
Name=Redshift (script)
Comment=Custom script to start Redshift with color temperature input
Exec="/home/redshift.sh"
Icon=redshift
Terminal=true
Type=Application
</code>```

(the first line was added automatically).

The expected behaviour is:

User double-clicks the desktop entry

Console opens and asks for (optional) input

Upon user pressing Enter, the script should launch the application named redshift-gtk (which is actually a Python script located at /usr/bin), with the specified arguments.

For now I don't care about checking whether the input is valid, nor if the process is already running.

An example of the (working) command would be:

redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400"
```

<p>And for the moment, I even simplified the launch script to simply this</p>

<pre class="lang-sh prettyprint-override"><code>nohup redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400" &
</code>```

And even tried

nohup redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400" && exit
```

But none of these closes the Terminal window, it will just keep remain open. If I close it manually, the Redshift process is killed (and this is obviosly not desired).

Tried a number of possible solutions found online, none seems to work. Didn't find anything relevant here in SO.

Just how to do it properly?

Thanks

答:
(This suggestion is moot, in view of OP's original question.)

In bash, you can try:

```<code>redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400" &
disown $!
</code>```

Note that, at any rate, & is what you need for spawning the sub-process -- && will wait for it to complete.

EDIT:

I must have been reading your description very carelessly (or missed an update, if there was one,) so I was not taking into consideration the requirement to do input before continuing in the background.  You can do some magic to this effect with a utility called expect, but it's far from an easy ride.  I'd love to be able to give you some more pointers, but I myself have only scratched the surface of using it.

Body:
I wanted to have an icon in my desktop to start Redshift with a custom parameter which is read from the command line upon launching.

This is what I came up with:

#!/bin/bash
default_temperature=4500
echo "Default color temperature (Night) is "$default_temperature"K."
read -p "Type in the desired value: " temperature
temperature=${temperature:-$default_temperature}
nohup redshift-gtk -l "-23.9141:-147.6650" -t "6500:"$temperature &

The above file is saved as /home/redshift.sh. I also created a desktop entry to launch it, with the following code:

#!/usr/bin/env xdg-open
[Desktop Entry]
Name=Redshift (script)
Comment=Custom script to start Redshift with color temperature input
Exec="/home/redshift.sh"
Icon=redshift
Terminal=true
Type=Application

(the first line was added automatically).

The expected behaviour is:

User double-clicks the desktop entry

Console opens and asks for (optional) input

Upon user pressing Enter, the script should launch the application named redshift-gtk (which is actually a Python script located at /usr/bin), with the specified arguments.

For now I don't care about checking whether the input is valid, nor if the process is already running.

An example of the (working) command would be:

redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400"

And for the moment, I even simplified the launch script to simply this

nohup redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400" &

And even tried

nohup redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400" && exit

But none of these closes the Terminal window, it will just keep remain open. If I close it manually, the Redshift process is killed (and this is obviosly not desired).

Tried a number of possible solutions found online, none seems to work. Didn't find anything relevant here in SO.

Just how to do it properly?

Thanks

Body:
(This suggestion is moot, in view of OP's original question.)

In bash, you can try:

redshift-gtk -l "-23.9141:-147.6650" -t "5500:2400" &
disown $!

Note that, at any rate, & is what you need for spawning the sub-process -- && will wait for it to complete.

EDIT:

I must have been reading your description very carelessly (or missed an update, if there was one,) so I was not taking into consideration the requirement to do input before continuing in the background.  You can do some magic to this effect with a utility called expect, but it's far from an easy ride.  I'd love to be able to give you some more pointers, but I myself have only scratched the surface of using it.


答:
Use the for loop.
If you don't know what that is, you should download an app, or search YouTube for the basics of python. I recommend thenewboston's programming tutorials. </p>

Title: Python order filling loop?


问:
Angular + Firebase: how to store/retrieve objects with list properties?
chatroom.service.ts:

```<code>...
export class Message {
  author: string;
  body: string;
}

export class Chatroom {
  title: string;
  messages: Message[];  // <-- seems to be the problem
}

@Injectable()
export class ChatroomService {
  ...
  getChatroom = (chatroomId: string): FirebaseObjectObservable<Chatroom> =>
    this.db.object('/chatrooms/' + chatroomId);
  ...
</code>```

chatroom.component.ts:

```<code>...
export class ChatroomComponent implements OnInit {
  chatroom: Chatroom;

  private sub: any;

  ngOnInit() {
    this.sub = this.route.params
      .subscribe(params => {
        this.sub = this.chatroomService.getChatroom(params['chatroomId'])
          .subscribe(chatroom => this.chatroom = chatroom);
      });
  }
  ...
</code>```

chatroom.component.html

```<code><div *ngIf="chatroom">
  <p *ngFor="let message of chatroom.messages">{{message.author}}: {{message.body}}</p>
</div>
</code>```

error:

```<code>Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.
</code>```

The problem is that the Chatroom object's "message" property is treated by Firebase as an object and whereas I want it to be treated an ngFor-iterable list. Any suggestions on how to make this work?

EDIT: Here is the Firebase data structure:

```<code>{
  "chatrooms" : {
    "chatroom_342768235" : {
      "title" : "a chatroom",
      "messages" : {
        "message_3252253" : {
          "author" : "Joe",
          "body" : "test message"
        },
        "message_2653837" : {
          "author" : "Kim",
          "body" : "another message"
        }
      }
    },
    "chatroom_426482763" : {
      "title" : "another chatroom",
      "messages" : {
        "message_1243525" : {
          "author" : "Tom",
          "body" : "blah blah"
        }
      }
    }
  }
}
</code>```

答:
I think because you listen to the DB ( with subscribe) you get an Observable list, and *ngFor cant work with that kind of lists. You should try to add pipe of |async after the Observable list you want to iterate. Something like this:</p>

```<code><p *ngFor="let message of chatroom.messages | async">{{message.author}}: {{message.body}}</p>
</code>```

Body:
chatroom.service.ts:

...
export class Message {
  author: string;
  body: string;
}

export class Chatroom {
  title: string;
  messages: Message[];  // <-- seems to be the problem
}

@Injectable()
export class ChatroomService {
  ...
  getChatroom = (chatroomId: string): FirebaseObjectObservable<Chatroom> =>
    this.db.object('/chatrooms/' + chatroomId);
  ...

chatroom.component.ts:

...
export class ChatroomComponent implements OnInit {
  chatroom: Chatroom;

  private sub: any;

  ngOnInit() {
    this.sub = this.route.params
      .subscribe(params => {
        this.sub = this.chatroomService.getChatroom(params['chatroomId'])
          .subscribe(chatroom => this.chatroom = chatroom);
      });
  }
  ...

chatroom.component.html

{{message.author}}: {{message.body}}

error:

Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

The problem is that the Chatroom object's "message" property is treated by Firebase as an object and whereas I want it to be treated an ngFor-iterable list. Any suggestions on how to make this work?

EDIT: Here is the Firebase data structure:

{
  "chatrooms" : {
    "chatroom_342768235" : {
      "title" : "a chatroom",
      "messages" : {
        "message_3252253" : {
          "author" : "Joe",
          "body" : "test message"
        },
        "message_2653837" : {
          "author" : "Kim",
          "body" : "another message"
        }
      }
    },
    "chatroom_426482763" : {
      "title" : "another chatroom",
      "messages" : {
        "message_1243525" : {
          "author" : "Tom",
          "body" : "blah blah"
        }
      }
    }
  }
}

Body:
I think because you listen to the DB ( with subscribe) you get an Observable list, and *ngFor cant work with that kind of lists. You should try to add pipe of |async after the Observable list you want to iterate. Something like this:

<p *ngFor="let message of chatroom.messages | async">{{message.author}}: {{message.body}}</p>


问:
Struts 2.0.14 GET parametrs are not URLDecoded, is that a bug?
I've got a problem with the parameters passed in the url.

Let say the request is: /struts/MyAction.action?param=foo%40bar.com

The action field gets the "param" field set to "foo%40bar.com",
is that a bug or I am expecting too much from Struts?

My intuition tells me that I should get the value: "foo@bar.com", as for instance would happen if I passed that parameter as a POST form field.

I am using the default interceptor stack and my action class extends ActionSupport. I get the some behaviour on WebSphere6.1 & GlassFish2.1.

Thanks

Hi Again,

The problem was caused by a bug in the proxy implementation. We've written a custom proxy server that was standing in front of the web application. It was encoding the URL parameters for the second time and that's why in Struts I had %40 instead of @.
Bug has been fixed now and parameters are being passed correctly.

Thanks for all your help

答:
Your intuition is right, you should be getting "foo@bar.com". With the following test of struts version 2.0.14 I could enter !@#$#$^$&%#$%& into a from and display it on another page without issue.

I tested a bare bones struts 2.0.14 application with a form that takes a string:

```<code><s:form action="form-view.action" method="GET">
  <s:textfield label="email" name="email"/>
  <s:submit/>
</s:form>
</code>```

A basic action class (note with stuts2 at this version you don't need setters/getters):

```<code>package struts2;

import com.opensymphony.xwork2.ActionSupport;

public class FormViewAction extends ActionSupport{
   public String email;
}
</code>```

And a very basic display page containing:

```<code><s:property value="email"/>
</code>```

Here is the struts.xml:

```<code><struts>
  <constant name="struts.enable.DynamicMethodInvocation" value="false" />
  <constant name="struts.devMode" value="true" />
  <package namespace="" name="example" extends="struts-default">
    <action name="form-view"  class="struts2.FormViewAction">
      <result>/form-view.jsp</result>
    </action>
  </package>
</struts>
</code>```

There must be a configuration issue...  Are you building with maven? Why are you using version 2.0.14 instead of 2.2.1?  Just as an aside I down-graded a test application from 2.2.1 down to 2.0.14 and this took my about 5 min to do.  I don't think there are any serious impediments from upgrading to the current version which will give you up to date documentation.

I ran this on Glassfish 3.0.1.

If you are not building with maven please list the jars in your library, your web.xml and struts.xml files and if possible a minimal form.jsp, display.jsp and an Action class to reproduce the issue.

Body:
Your intuition is right, you should be getting "foo@bar.com". With the following test of struts version 2.0.14 I could enter !@#$#$^$&%#$%& into a from and display it on another page without issue.

I tested a bare bones struts 2.0.14 application with a form that takes a string:

<s:form action="form-view.action" method="GET">
  <s:textfield label="email" name="email"/>
  <s:submit/>
</s:form>

A basic action class (note with stuts2 at this version you don't need setters/getters):

package struts2;

import com.opensymphony.xwork2.ActionSupport;

public class FormViewAction extends ActionSupport{
   public String email;
}

And a very basic display page containing:

<s:property value="email"/>

Here is the struts.xml:

<struts>
  <constant name="struts.enable.DynamicMethodInvocation" value="false" />
  <constant name="struts.devMode" value="true" />
  <package namespace="" name="example" extends="struts-default">
    <action name="form-view"  class="struts2.FormViewAction">
      <result>/form-view.jsp</result>
    </action>
  </package>
</struts>

There must be a configuration issue...  Are you building with maven? Why are you using version 2.0.14 instead of 2.2.1?  Just as an aside I down-graded a test application from 2.2.1 down to 2.0.14 and this took my about 5 min to do.  I don't think there are any serious impediments from upgrading to the current version which will give you up to date documentation.

I ran this on Glassfish 3.0.1.

If you are not building with maven please list the jars in your library, your web.xml and struts.xml files and if possible a minimal form.jsp, display.jsp and an Action class to reproduce the issue.


问:
How to add X-XSS-Protection: 1; mode=block HTML
I don't know how to add this part of code into my code.
should it be in the header part?

```<code><head>
<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />
<title>TestWebsite</title>
</head>
</code>```

The problem is I have to add it into my code, because I did a security scan and I got that the X-XSS Protection is missing.

答:
This cannot be added on a HTML page.

It has to be added to your server page as a response.

E.g. You can add any of the following options, according to your needs.

PHP

```<code>header("X-XSS-Protection: 0");
</code>```

.htaccess

```<code>Header set x-xss-protection "1; mode=block"
</code>```

Apache configuration files:

```<code><IfModule mod_headers.c>
    Header set X-XSS-Protection: "1; mode=block"
</IfModule>
</code>```

Body:
I don't know how to add this part of code into my code.
should it be in the header part?

<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />
<title>TestWebsite</title>

The problem is I have to add it into my code, because I did a security scan and I got that the X-XSS Protection is missing.

Body:
This cannot be added on a HTML page.

It has to be added to your server page as a response.

E.g. You can add any of the following options, according to your needs.

PHP

header("X-XSS-Protection: 0");

.htaccess

Header set x-xss-protection "1; mode=block"

Apache configuration files:

<IfModule mod_headers.c>
    Header set X-XSS-Protection: "1; mode=block"
</IfModule>

ContentLicense: CC BY-SA 4.0


问:
By using listview see first string array item in List view and detail string array item in second activity
I have two string array . one of string array have listview item and
second array have detail description of listview item. When I clicked
on listitem in listview then I want to show detail description of
that listitem in second activity.

```<code><string-array name="ListItem">
        <item>Gameplay Intro</item>
        <item>Enable the Leaderboard System</item>
        <item>Extra Moves and Features</item>
        <item>Learn work of Super Jewels </item>
        <item>Watch Out from The Dynamite</item>
        <item>Hidden Tricks</item>
    </string-array>

 <string-array name="Description">
        <item>detail 1 </item>
        <item>detail 2 System</item>
        <item>detail 3</item>
        <item>detail 4</item>
        <item>detail 5</item>
        <item>detail 6</item>
    </string-array>
</code>```

ListActivity code:

```<code>public class ListActivity extends AppCompatActivity {
    public static String[] listitems;
    ListView lvStatus;
    private NativeExpressAdView nativeExpressAdView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        lvStatus = (ListView)findViewById(R.id.lvStatus);
        listitems=getResources().getStringArray(R.array.ListItem);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listitems);
        lvStatus.setAdapter(adapter);
        lvStatus.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(ListActivity.this,ShowActivity.class);
                startActivity(intent);
            }
        });
    }
}
</code>```

Description show activity code:

```<code>public class ShowActivity extends AppCompatActivity {
    public static String[] descriptions;
    TextView tvDetail;
    String listitems[];
    int intposition = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        descriptions = getResources().getStringArray(R.array.Description);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.list_content,descriptions);
        intposition = getIntent().getIntExtra("position", 0);
        tvDetail = (TextView) findViewById(R.id.tvDetail);
        tvDetail.setText((CharSequence) adapter);
        tvDetail.setMovementMethod(new ScrollingMovementMethod());
    }
}
</code>```

答:
you  are getting position on click in this method:

```<code>@Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            Intent intent = new Intent(ListActivity.this,ShowActivity.class);
            startActivity(intent);
        }
</code>```

save that position and display data with same position from another array.
there are plenty of ways to do that, one of them is:

i.putExtra("selected_item", position);

Body:
I have two string array . one of string array have listview item and
second array have detail description of listview item. When I clicked
on listitem in listview then I want to show detail description of
that listitem in second activity.

<string-array name="ListItem">
        <item>Gameplay Intro</item>
        <item>Enable the Leaderboard System</item>
        <item>Extra Moves and Features</item>
        <item>Learn work of Super Jewels </item>
        <item>Watch Out from The Dynamite</item>
        <item>Hidden Tricks</item>
    </string-array>

 <string-array name="Description">
        <item>detail 1 </item>
        <item>detail 2 System</item>
        <item>detail 3</item>
        <item>detail 4</item>
        <item>detail 5</item>
        <item>detail 6</item>
    </string-array>

ListActivity code:

public class ListActivity extends AppCompatActivity {
    public static String[] listitems;
    ListView lvStatus;
    private NativeExpressAdView nativeExpressAdView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        lvStatus = (ListView)findViewById(R.id.lvStatus);
        listitems=getResources().getStringArray(R.array.ListItem);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listitems);
        lvStatus.setAdapter(adapter);
        lvStatus.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(ListActivity.this,ShowActivity.class);
                startActivity(intent);
            }
        });
    }
}

Description show activity code:

public class ShowActivity extends AppCompatActivity {
    public static String[] descriptions;
    TextView tvDetail;
    String listitems[];
    int intposition = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        descriptions = getResources().getStringArray(R.array.Description);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.list_content,descriptions);
        intposition = getIntent().getIntExtra("position", 0);
        tvDetail = (TextView) findViewById(R.id.tvDetail);
        tvDetail.setText((CharSequence) adapter);
        tvDetail.setMovementMethod(new ScrollingMovementMethod());
    }
}

Body:
you  are getting position on click in this method:

@Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            Intent intent = new Intent(ListActivity.this,ShowActivity.class);
            startActivity(intent);
        }

save that position and display data with same position from another array.
there are plenty of ways to do that, one of them is:

i.putExtra("selected_item", position);


问:
How do I create a script that does a continous ping?
The output initially is:
Reply from
Reply from
Reply from
Then I'll get, when the connection is lost:
Request timed out.
Request timed out.
Request timed out.
When it's reconnected the response is:
Reply from
Reply from
Reply from
Then I proceed to open a telnet session to my system and run python code.
When I use our utility I get this error below:
    def fin():

```<code>  tb_session.close_connection()
</code>```

conftest.py:38:

答:
```<code>import os
import subprocess
import re

bFlag = True
while bFlag == True:
    a = subprocess.check_output('ping 127.0.0.1')
    b = a.split('\n')

    iReply = 0
    for line in b:
        print line
        if re.search("Reply", line) == None:
            pass
        else:
            iReply+=1

    if iReply == 4:
        print "Total replies are 4"
    else:
        print "Ping broken"
        bFlag = False
</code>```

Body:
The output initially is:
Reply from
Reply from
Reply from
Then I'll get, when the connection is lost:
Request timed out.
Request timed out.
Request timed out.
When it's reconnected the response is:
Reply from
Reply from
Reply from
Then I proceed to open a telnet session to my system and run python code.
When I use our utility I get this error below:
    def fin():

  tb_session.close_connection()

conftest.py:38:


答:
Lots of ways, here's one:

```<code>orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5]
startingvolume = 100

for i in range(len(orders)):
    qty = startingvolume if startingvolume < orders[i] else orders[i]
    orders[i] -= qty
    startingvolume -= qty
    if not startingqty:
        break
</code>```

This will deduct as much as possible from each order until there's nothing left then stop.

Title: Python order filling loop?

Body:
Let's say I have a bunch of orders I need to fill

orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5]

I have a starting volume of say 100

startingvolume = 100

I want to iterate through the orders until my volume/order is filled

so the first order would be my initial 100 minus the first order of 39.789032 which leaves 60.2110968 of my order still to be filled. What is the most Pythonic way to fill my order until my starting volume is 0?

Body:
Lots of ways, here's one:

orders = [39.789032, 36.023618, 3.0539913, 20.0, 1.314, 2.5, 0.401, 1.0, 1.989, 6.3254668, 0.5]
startingvolume = 100

for i in range(len(orders)):
    qty = startingvolume if startingvolume < orders[i] else orders[i]
    orders[i] -= qty
    startingvolume -= qty
    if not startingqty:
        break

This will deduct as much as possible from each order until there's nothing left then stop.