问:
java.lang.Exception: No tests found matching Method using Intellij IDEA
I am experiencing a strange behavior of Intellij IDEA 2016.3. Having a class with method foo and a JUnit test for the method when I get java.lang.Exception: No tests found matching Method foo when running the test. After I do mvn test it succeeds and then running the unit test right after executing mvn command it suddenly runs green. Seems like IDEA does not compile automatically. How can I fix this?

P.S. No settings were altered after upgrading to v. 2016.3

答:
Make sure you've correct runner mentioned above your class.

I was getting this weird message when I was using runner CucumberWithSerenity.class. When I changed to SerenityRunner.class it got fixed.

```<code>@RunWith(SerenityRunner.class)
//@RunWith(CucumberWithSerenity.class)
public class WordPressAppTest {
</code>```

I'm using Serenity framework for web automation and use below runner class

```<code>import net.serenitybdd.cucumber.CucumberWithSerenity;
import net.serenitybdd.junit.runners.SerenityRunner;
import org.junit.runner.RunWith;
</code>```

I feel IDEA ( 2017.2.6 ) can show some better error message than this

Body:
Make sure you've correct runner mentioned above your class.

I was getting this weird message when I was using runner CucumberWithSerenity.class. When I changed to SerenityRunner.class it got fixed.

@RunWith(SerenityRunner.class)
//@RunWith(CucumberWithSerenity.class)
public class WordPressAppTest {

I'm using Serenity framework for web automation and use below runner class

import net.serenitybdd.cucumber.CucumberWithSerenity;
import net.serenitybdd.junit.runners.SerenityRunner;
import org.junit.runner.RunWith;

I feel IDEA ( 2017.2.6 ) can show some better error message than this


来源: stackexchange

问:
Adding all the values that has same class using jQuery
Here is my html

```<code><input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">
</code>```

I am trying to add all the values that has the same class name tt

So i am doing like this

```<code>$('.tt').each(function(i, obj) {
    var oo = obj;
    console.log(oo)
});
</code>```

When i do console.log(00)

It prints

```<code><input type="hidden" class="tt to_5" value="35">
</code>```

But when I try to do

```<code>console.log(oo.val())
</code>```

It is showing undefined How can I get the value ?

Am using jQuery

答:
If you want to log the values do this:</p>

```<code>$('.tt').each(function(i, obj) {
    var value = $( obj ).val();

    console.log( value );
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is my html

<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">

I am trying to add all the values that has the same class name tt

So i am doing like this

$('.tt').each(function(i, obj) {
    var oo = obj;
    console.log(oo)
});

When i do console.log(00)

It prints

<input type="hidden" class="tt to_5" value="35">

But when I try to do

console.log(oo.val())

It is showing undefined How can I get the value ?

Am using jQuery

Body:
If you want to log the values do this:

$('.tt').each(function(i, obj) {
    var value = $( obj ).val();

    console.log( value );
});


问:
How to draw a line connector between two icons displayed in two different div.
I have displayed one Icons in one Div element. I need to draw a connecting line between those Icons. Please note that the Div is a dynamic element.

I have displayed the current Image below.

Expected image is displayed below.

Please guide me how to do that. Thanks in advance.

答:
Here is a small demo that will help you know how to use jsPlumb achieve what you want.

jsPlumb.ready(function() {
            jsPlumb.connect({
                source:"firstItem",
                target:"secondItem",
                endpoint:"Dot"
            });
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span{
  display:inline-block;
  height:50px;
  width:100px;
  background-color:yellow;
}</code>```

        Smiley1

         Smiley2

```

Hope it helps :)

Body:
Here is a small demo that will help you know how to use jsPlumb achieve what you want.

jsPlumb.ready(function() {
            jsPlumb.connect({
                source:"firstItem",
                target:"secondItem",
                endpoint:"Dot"
            });
        });

span{
  display:inline-block;
  height:50px;
  width:100px;
  background-color:yellow;
}

     <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jsPlumb/1.4.1/jquery.jsPlumb-1.4.1-all-min.js"></script>
 <div id="diagramContainer">
        <div  >
        <span id="firstItem">Smiley1</span>
        </div>
        <div >
         <span style="float:right" id="secondItem">Smiley2</span>
        </div>
    </div>

Hope it helps :)


问:
Flutter TextEditingController does not scroll above keyboard
In android version, Flutter TextEditingController does not scroll above keyboard like default text fields do when you start typing in field. I tried to look in sample apps provided in flutter example directory, but even there are no example of TextEditController with such behaviour.

Is there any way to implement this.

Thanks in advance.

答:
Flutter does not have such thing by default.

Add your TextField in a ListView.
create ScrollController and assign it to the ListView's controller.

When you select the TextField, scroll the ListView using:

```<code>controller.jumpTo(value);
</code>```

or if you wish to to have scrolling animation:

```<code>controller.animateTo(offset, duration: null, curve: null);
</code>```

EDIT: Of course the duration and curve won't be null. I just copied and pasted it here.

Body:
Flutter does not have such thing by default.

Add your TextField in a ListView.
create ScrollController and assign it to the ListView's controller.

When you select the TextField, scroll the ListView using:

controller.jumpTo(value);

or if you wish to to have scrolling animation:

controller.animateTo(offset, duration: null, curve: null);

EDIT: Of course the duration and curve won't be null. I just copied and pasted it here.


问:
how to change WordPress URL on all pages?
how to change WordPress URL on all pages? suppose we have a xyz.com. Now I want something like xyz.com/test when customer visiting to xyz.com. and for all newly created pages must be something like xyz.com/test/Newpage.</p>

答:
Customize Permalink Structure, You can choose "Post name" option.

Post name - An example of the post name structure is http://www.sample.com/sample-post

Hope this will helps you.


问:
Shell : Check if all output strings are same
I have the following code snippet

```<code>$ mount | grep '^/dev'| awk '{print $1}'
 /dev/disk1s1
 /dev/disk1s4
</code>```

Now I need to check if the output lines have the same value or different.
So in the above case it is different. [ disk1s1 and disk1s4 ]. How can this be achieved in shell.

I may have two or more lines in the result.

答:
Not tested, but something like:

```<code>if (( $(mount | grep -o '^/dev[^ ]*' | sort -u | wc -l) > 1 ))
then
  echo different values
fi
</code>```

The -o option in grep together with the slightly modified pattern returns only the first field. The -u option of sort throws away duplicates.

Body:
I have the following code snippet

$ mount | grep '^/dev'| awk '{print $1}'
 /dev/disk1s1
 /dev/disk1s4

Now I need to check if the output lines have the same value or different.
So in the above case it is different. [ disk1s1 and disk1s4 ]. How can this be achieved in shell.

I may have two or more lines in the result.

Body:
Not tested, but something like:

if (( $(mount | grep -o '^/dev[^ ]*' | sort -u | wc -l) > 1 ))
then
  echo different values
fi

The -o option in grep together with the slightly modified pattern returns only the first field. The -u option of sort throws away duplicates.


问:
Best approach to run different modes of clock in testbench
I'm interested in running my current testcases with a different clock frequency without having to recreate new testcases with only the clock periods changed. Would using tcl script be better for something like this?

For example:

```<code>    testcase1 has
    process
    begin
    wait for CLK_PERIOD / 2.0;
    CLK <= not CLK;
    wait forCLK_PERIOD / 2.0;
    NCLK <= not CLK;
    end process;
</code>```

but i want to be able to run testcase1 with

```<code>    process
    begin
    wait for CLK_PERIOD1 / 2.0;
    CLK <= not CLK;
    wait forCLK_PERIOD1 / 2.0;
    NCLK <= not CLK;
    end process;
</code>```

答:
You can pass the clock period as a generic to the testbench entity. Simulators can't handle any type of top-level generics so you can use a string generic and convert that to time. Below is an example for a VUnit testbench (I'm one of the authors so I avoid TCL if I can)

```<code>library vunit_lib;
context vunit_lib.vunit_context;

entity tb_test is
  generic (
    clk_period_as_string : string;
    runner_cfg : runner_cfg_t);
end tb_test;

architecture tb of tb_test is
  constant clk_period : time := time'value(clk_period_as_string);
begin
  test_runner : process
  begin
    test_runner_setup(runner, runner_cfg);

    info("Clock period set to: " & to_string(clk_period));

    test_runner_cleanup(runner);
  end process test_runner;
end;
</code>```

A VUnit script can control this generic by creating several configurations of the testbench

```<code>from os.path import join, dirname
from vunit import VUnit

prj = VUnit.from_argv()

tb_lib = prj.add_library('tb_lib')
tb_lib.add_source_files(join(dirname(__file__), 'test', '*.vhd'))
tb = tb_lib.entity("tb_test")

generics = dict(clk_period_as_string="5 ns")
tb.add_config(name='clock period = 5 ns', generics=generics)

generics = dict(clk_period_as_string="10 ns")
tb.add_config(name='clock period = 10 ns', generics=generics)

prj.main()
</code>```

The result will be

Body:
I'm interested in running my current testcases with a different clock frequency without having to recreate new testcases with only the clock periods changed. Would using tcl script be better for something like this?

For example:

    testcase1 has
    process
    begin
    wait for CLK_PERIOD / 2.0;
    CLK <= not CLK;
    wait forCLK_PERIOD / 2.0;
    NCLK <= not CLK;
    end process;

but i want to be able to run testcase1 with

    process
    begin
    wait for CLK_PERIOD1 / 2.0;
    CLK <= not CLK;
    wait forCLK_PERIOD1 / 2.0;
    NCLK <= not CLK;
    end process;

Body:
You can pass the clock period as a generic to the testbench entity. Simulators can't handle any type of top-level generics so you can use a string generic and convert that to time. Below is an example for a VUnit testbench (I'm one of the authors so I avoid TCL if I can)

library vunit_lib;
context vunit_lib.vunit_context;

entity tb_test is
  generic (
    clk_period_as_string : string;
    runner_cfg : runner_cfg_t);
end tb_test;

architecture tb of tb_test is
  constant clk_period : time := time'value(clk_period_as_string);
begin
  test_runner : process
  begin
    test_runner_setup(runner, runner_cfg);

    info("Clock period set to: " & to_string(clk_period));

    test_runner_cleanup(runner);
  end process test_runner;
end;

A VUnit script can control this generic by creating several configurations of the testbench

from os.path import join, dirname
from vunit import VUnit

prj = VUnit.from_argv()

tb_lib = prj.add_library('tb_lib')
tb_lib.add_source_files(join(dirname(__file__), 'test', '*.vhd'))
tb = tb_lib.entity("tb_test")

generics = dict(clk_period_as_string="5 ns")
tb.add_config(name='clock period = 5 ns', generics=generics)

generics = dict(clk_period_as_string="10 ns")
tb.add_config(name='clock period = 10 ns', generics=generics)

prj.main()

The result will be


问:
How to make html table that perfect even in a small page and width
I have a page who have left and right side who is in all page.

Now I want to make a table in middlecontent but their is very few space I can't make it big.

When I created it it's work but most of part was hidden [go behind right panel].

How  can I make some style then they show all content in a width and height I have means nothing goes hidden. Everything need to show even I show information using many line for particular rows [td].

Any suggestion of how to do this?

答:
I not sure I understand your question.

try use this :

if it doesn't help you, link to your page, or copy the code. so we can understand better the problem.

OwnerDisplayName: Steven Spielberg

Body:
I not sure I understand your question.

try use this :

<table style="width:100%">

if it doesn't help you, link to your page, or copy the code. so we can understand better the problem.

ContentLicense: CC BY-SA 2.5


答:
Here you go with a solution

var total = 0;
$('.tt').each(function(){
  console.log("Current Value:", $(this).attr('value'));
  total += parseInt($(this).attr('value'));
});

console.log("Total: ",total);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25"></code>```

Hope this will help you.

Title: Adding all the values that has same class using jQuery

Body:
Here you go with a solution

var total = 0;
$('.tt').each(function(){
  console.log("Current Value:", $(this).attr('value'));
  total += parseInt($(this).attr('value'));
});

console.log("Total: ",total);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">

Hope this will help you.


问:
Which one is the best WordPress plugin for test system with separate price for every test
I have developed a WordPress website, I am being asked to find and integrate a plugin for the test system. Plugin requirements are as following:

The plugin will have multiple choice questions and will have the option to have more than one test in it.

every test will have a price and payment option with be pay with paypal.

we can change passing percentage.

only logged in user can perform the test. Only user and admin can see the result.

Please tell me if you have this kind of plugin, I am stucked and cant proceed., please please please point me to the solution if you can.,

答:
As per your question,

you have to create new custom wordpress plugin and functionality because you can not get the ready plugin for this requirement.

In case, you can use the ready the plugin then you have to customise custom functionality as per your requirement.

So, I will suggest to you. you can create new plugin then user can easy to use.


问:
Elegant alternatives to the weird multiple inheritance
I can not say that this is a question, but more of an opinion request and I am sure many others could benefit from clarifying this issue.

Here is my practical case:

I have an abstract class called DataExchangeService and a lot of sub-classes that extend this one (this is the base CONTROLLER class in my MVC Framework). The administration modules that handle data definiton (Users,Types,Sections etc) they all have the add,edit,delete,list methods with 100% similarity in most cases. I know that because I replicate them by using only search and replace. Now the thing is not all my DateExchangeService sub-classes handle data definiton so there are enough cases where I don't need the CRUD methods.

Multiple inheritance would define these CRUD methods and their behaviour in another class and would extend both these classes where it is needed, but I really do think it is tricky stuff and I do not use it (+PHP doesn't have such functionality). So what would be the best practice?

Here are the approaches that crossed my mind:

CASE A

Define a CRUDHandler class that has all these methods parametrized.

Create a property of CRUDHandler type where it is needed and also implement the CRUD  interface that will force me to use these methods.

In the bodies of the implemented methods I add something like this:

```
public function edit($params) {
    $this->params = $params;
    $this->CRUDHandler->handle("edit", $this);
}
```

(In PHP this can be done with the __call() magic method.)

CASE B

Define class CRUDHandler as extending the base DataExchangeService.

When defining a specific type of DataExchangeService (for example
UsersExchangeService) instead of extending DataExchangeService you extend CRUDHandler,
this way you get all you want when it is needed.

So, are there any other opinions on this MultiInheritance approach?

Thanks

答:
There is currently a popular style of thinking that says "favour composition over inheritance". There is too much information on Google to really list it all here, but let's just say that with the rare exception of the occasional abstract base class, I haven't used inheritance in 2-3 years.

The main idea is that any given class, rather than extending base classes that allow it to deliver required functionality, will have dependencies on other classes.  In actual fact, to keep things SOLID, it'll have dependencies on interfaces that provide a contract that says they'll perform a function.

You then get to a point where your Controller class has services/components passed-in, which it delegates to in order to get specific jobs done.

Note you can go too far the other way as well. If you have a class that depends on lots of external services especially if not every public method on the class ends up using all of them, you might in fact have two classes after all. I.e. your controller is "violating" the single responsibility principle by doing more than one job. This is especially easy to do by accident with controllers in web frameworks because they kind of encourage it.

At this point, I reckon it's advisable to read up on:

Favour composition over inheritance.

Dependency Injection and Inversion of Control.

Inversion of Control containers (e.g. StructureMap and my personal favourite: Castle Windsor).

Body:
I can not say that this is a question, but more of an opinion request and I am sure many others could benefit from clarifying this issue.

Here is my practical case:

I have an abstract class called DataExchangeService and a lot of sub-classes that extend this one (this is the base CONTROLLER class in my MVC Framework). The administration modules that handle data definiton (Users,Types,Sections etc) they all have the add,edit,delete,list methods with 100% similarity in most cases. I know that because I replicate them by using only search and replace. Now the thing is not all my DateExchangeService sub-classes handle data definiton so there are enough cases where I don't need the CRUD methods.

Multiple inheritance would define these CRUD methods and their behaviour in another class and would extend both these classes where it is needed, but I really do think it is tricky stuff and I do not use it (+PHP doesn't have such functionality). So what would be the best practice?

Here are the approaches that crossed my mind:

CASE A

Define a CRUDHandler class that has all these methods parametrized.

Create a property of CRUDHandler type where it is needed and also implement the CRUD  interface that will force me to use these methods.

In the bodies of the implemented methods I add something like this:

public function edit($params) {
    $this->params = $params;
    $this->CRUDHandler->handle("edit", $this);
}

(In PHP this can be done with the __call() magic method.)

CASE B

Define class CRUDHandler as extending the base DataExchangeService.

When defining a specific type of DataExchangeService (for example
UsersExchangeService) instead of extending DataExchangeService you extend CRUDHandler,
this way you get all you want when it is needed.

So, are there any other opinions on this MultiInheritance approach?

Thanks

ContentLicense: CC BY-SA 4.0


问:
Getter "Snapshot" called on null with StreamBuilder in Flutter
I'm using a Flutter Streambuilder and my stream calls null for a second before it loads.  I'm trying to load a "Loading..." Card but its not working.  My simulator briefly shows a red error screen before displaying my desired card list.  How can I get it to stop doing this? Here is my code...</p>

```<code>new Expanded(
                  child: new StreamBuilder(
                      stream: streamQuery,
                      builder:
                          (BuildContext context, AsyncSnapshot<Event> event) {
                        if (event.data.snapshot.value == null) {
                          return new Card(
                            child: new Text('Loading...',
                                style: new TextStyle(
                                    fontSize: 12.0,
                                    fontWeight: FontWeight.bold,
                                    fontStyle: FontStyle.italic)),
                          );
                        }

                        Map myMap = event.data.snapshot.value; //store each map
                        var titles = myMap.values;

                        List onesTitles = new List();
                        List onesIds = new List();
                        List onesImages = new List();
                        List onesRank = new List();

                        for (var items in titles) {
                          onesTitles.add(items['vidTitle']);
                          onesIds.add(items['vidId']);
                          onesImages.add(items['vidImage']);
                          onesRank.add(items['Value']);
                        }

                        names = onesTitles;
                        ids = onesIds;
                        numbers = onesRank;
                        vidImages = onesImages;

                        switch (event.connectionState) {
                          case ConnectionState.none:
                            return new Card(
                              child: new Text('Loading...',
                                  style: new TextStyle(
                                      fontSize: 12.0,
                                      fontWeight: FontWeight.bold,
                                      fontStyle: FontStyle.italic)),
                            );
                          case ConnectionState.waiting:
                            return new Card(
                              child: new Text('Awaiting Results...',
                                  style: new TextStyle(
                                      fontSize: 12.0,
                                      fontWeight: FontWeight.bold,
                                      fontStyle: FontStyle.italic)),
                            );
                          default:
                            if (event.hasError)
                              return new Card(
                                child: new Text('Error: ${event.error}',
                                    style: new TextStyle(
                                        fontSize: 12.0,
                                        fontWeight: FontWeight.bold,
                                        fontStyle: FontStyle.italic)),
                              );
                            else
                              return new InkWell(
</code>```

答:
You need to explicitly state all your data manipulation inside the else that has the build layout for your if (snapshot!=null) {//do something}

Something like this:

```<code>else //event.data.snapshot.value != null
 {
Map myMap = event.data.snapshot.value; //store each map
                        var titles = myMap.values;

                        List onesTitles = new List();
                        List onesIds = new List();
                        List onesImages = new List();
                        List onesRank = new List();

                        for (var items in titles) {
                          onesTitles.add(items['vidTitle']);
                          onesIds.add(items['vidId']);
                          onesImages.add(items['vidImage']);
                          onesRank.add(items['Value']);
                        }

                        names = onesTitles;
                        ids = onesIds;
                        numbers = onesRank;
                        vidImages = onesImages;

//return my layout
}
</code>```

So do no leave anything that is using your snapshot.value outside your if statement that works when snapshot!=null.

Body:
I'm using a Flutter Streambuilder and my stream calls null for a second before it loads.  I'm trying to load a "Loading..." Card but its not working.  My simulator briefly shows a red error screen before displaying my desired card list.  How can I get it to stop doing this? Here is my code...

new Expanded(
                  child: new StreamBuilder(
                      stream: streamQuery,
                      builder:
                          (BuildContext context, AsyncSnapshot<Event> event) {
                        if (event.data.snapshot.value == null) {
                          return new Card(
                            child: new Text('Loading...',
                                style: new TextStyle(
                                    fontSize: 12.0,
                                    fontWeight: FontWeight.bold,
                                    fontStyle: FontStyle.italic)),
                          );
                        }

                        Map myMap = event.data.snapshot.value; //store each map
                        var titles = myMap.values;

                        List onesTitles = new List();
                        List onesIds = new List();
                        List onesImages = new List();
                        List onesRank = new List();

                        for (var items in titles) {
                          onesTitles.add(items['vidTitle']);
                          onesIds.add(items['vidId']);
                          onesImages.add(items['vidImage']);
                          onesRank.add(items['Value']);
                        }

                        names = onesTitles;
                        ids = onesIds;
                        numbers = onesRank;
                        vidImages = onesImages;

                        switch (event.connectionState) {
                          case ConnectionState.none:
                            return new Card(
                              child: new Text('Loading...',
                                  style: new TextStyle(
                                      fontSize: 12.0,
                                      fontWeight: FontWeight.bold,
                                      fontStyle: FontStyle.italic)),
                            );
                          case ConnectionState.waiting:
                            return new Card(
                              child: new Text('Awaiting Results...',
                                  style: new TextStyle(
                                      fontSize: 12.0,
                                      fontWeight: FontWeight.bold,
                                      fontStyle: FontStyle.italic)),
                            );
                          default:
                            if (event.hasError)
                              return new Card(
                                child: new Text('Error: ${event.error}',
                                    style: new TextStyle(
                                        fontSize: 12.0,
                                        fontWeight: FontWeight.bold,
                                        fontStyle: FontStyle.italic)),
                              );
                            else
                              return new InkWell(

Body:
You need to explicitly state all your data manipulation inside the else that has the build layout for your if (snapshot!=null) {//do something}

Something like this:

else //event.data.snapshot.value != null
 {
Map myMap = event.data.snapshot.value; //store each map
                        var titles = myMap.values;

                        List onesTitles = new List();
                        List onesIds = new List();
                        List onesImages = new List();
                        List onesRank = new List();

                        for (var items in titles) {
                          onesTitles.add(items['vidTitle']);
                          onesIds.add(items['vidId']);
                          onesImages.add(items['vidImage']);
                          onesRank.add(items['Value']);
                        }

                        names = onesTitles;
                        ids = onesIds;
                        numbers = onesRank;
                        vidImages = onesImages;

//return my layout
}

So do no leave anything that is using your snapshot.value outside your if statement that works when snapshot!=null.


问:
Problems with through associations
I'm looking to loop through an association and include a through association as well. I'm getting an undefined method `name' for nil:NilClass error on the below.

I have an account model which has_many sales, which works fine. But sales is linked via previousAgents through previous_agent_id and this is where i'm having the problem.

Account Model

```<code>has_many :sales, primary_key: 'account_id'
</code>```

Sales Model

```<code>belongs_to :previousAgent, primary_key: 'previous_agent_id'
</code>```

Account View

```<code><% @account.sales.each do |p| %>
 <p>Previous Agent <%= p.previousAgent.name %></p>
 <p>Date: <%= p.date.strftime("%d %B, %Y") %></p>
 <p>Comments: <%= p.comment %></p>
<% end %>
</code>```

答:
It's very simple. Since each sale can have only 1 sales agent define your associations as follows,

```<code>Sale.rb

belongs_to :PreviousAgent, foreign_key: previous_agent_id

Agent.rb

has_many :sales
</code>```

Then, in your code since, you are looping through each and every sale that belongs to an account,

```<code><% @account.sales.each do |p| %>
 <p>Previous Agent <%= p.previousAgent.name %></p>
 <p>Date: <%= p.date.strftime("%d %B, %Y") %></p>
 <p>Comments: <%= p.comment %></p>
<% end %>
</code>```

Title: Problems with through associations

Body:
I'm looking to loop through an association and include a through association as well. I'm getting an undefined method `name' for nil:NilClass error on the below.

I have an account model which has_many sales, which works fine. But sales is linked via previousAgents through previous_agent_id and this is where i'm having the problem.

Account Model

has_many :sales, primary_key: 'account_id'

Sales Model

belongs_to :previousAgent, primary_key: 'previous_agent_id'

Account View

<% @account.sales.each do |p| %>

Previous Agent <%= p.previousAgent.name %>

Date: <%= p.date.strftime("%d %B, %Y") %>

Comments: <%= p.comment %>

<% end %>

Body:
It's very simple. Since each sale can have only 1 sales agent define your associations as follows,

Sale.rb

belongs_to :PreviousAgent, foreign_key: previous_agent_id

Agent.rb

has_many :sales

Then, in your code since, you are looping through each and every sale that belongs to an account,

<% @account.sales.each do |p| %>
 <p>Previous Agent <%= p.previousAgent.name %></p>
 <p>Date: <%= p.date.strftime("%d %B, %Y") %></p>
 <p>Comments: <%= p.comment %></p>
<% end %>


问:
FATAL EXCEPTION: main KotlinNullPointerException
This is my first time building an android application. However when i run the app on my Virtual Device, it stopped working and keeps crashing. The error says something about null pointer exception. This is my first time using Kotlin and I coded in Java and changed to Kotlin.

```<code> override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add_sales)

    val date: EditText? = null
    val changeDate: CheckBox? = null
    val yes: RadioButton? = null
    val no: RadioButton? = null

    date!!.setText("15-11-2017")
    date.isEnabled = false

    val button2 = findViewById<View>(R.id.btnSubmit) as Button
    button2.setOnClickListener {
        var name = findViewById<View>(R.id.name) as EditText
        var cost = findViewById<View>(R.id.cost) as EditText
        val itemcost = Integer.parseInt(cost!!.text.toString())
        var price = findViewById<View>(R.id.price) as EditText
        val itemprice = Integer.parseInt(price!!.text.toString())
        var qty = findViewById<View>(R.id.quantity) as EditText
        var chgDate = false
        var discount = false
        val toast = Toast(applicationContext)
        if (itemprice < itemcost) {
            price!!.error = "Selling price cannot be lower than item price!"
        } else {
            if (changeDate!!.isChecked) {
                chgDate = true
                date.isEnabled = true
            }
            if (yes!!.isChecked) {
                discount = true
            }
        }
        Toast.makeText(this@AddSales, "Item Name: " + name!!.text + "\n" + "Cost: " + cost!!.text + "\n" + "Item Price: " + price!!.text + "\n" + "Quantity: " + qty!!.text + "Date: " + date + "Staff Discount: " + discount, Toast.LENGTH_SHORT).show()
    }

}
</code>```

and the error is:

11-17 06:23:34.603 3540-3540/com.example.ruiru.salestracker
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ruiru.salestracker, PID: 3540
                                                                                java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ruiru.salestracker/com.example.ruiru.salestracker.AddSales}:
  kotlin.KotlinNullPointerException
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                                Caused by: kotlin.KotlinNullPointerException
                                                                                at com.example.ruiru.salestracker.AddSales.onCreate(AddSales.kt:25)
                                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

答:
```<code>val date: EditText? = null
val changeDate: CheckBox? = null
val yes: RadioButton? = null
val no: RadioButton? = null
</code>```

Before using these variables, initialize them with findViewById or bind them to the xml view.

Body:
This is my first time building an android application. However when i run the app on my Virtual Device, it stopped working and keeps crashing. The error says something about null pointer exception. This is my first time using Kotlin and I coded in Java and changed to Kotlin.

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_add_sales)

    val date: EditText? = null
    val changeDate: CheckBox? = null
    val yes: RadioButton? = null
    val no: RadioButton? = null

    date!!.setText("15-11-2017")
    date.isEnabled = false

    val button2 = findViewById<View>(R.id.btnSubmit) as Button
    button2.setOnClickListener {
        var name = findViewById<View>(R.id.name) as EditText
        var cost = findViewById<View>(R.id.cost) as EditText
        val itemcost = Integer.parseInt(cost!!.text.toString())
        var price = findViewById<View>(R.id.price) as EditText
        val itemprice = Integer.parseInt(price!!.text.toString())
        var qty = findViewById<View>(R.id.quantity) as EditText
        var chgDate = false
        var discount = false
        val toast = Toast(applicationContext)
        if (itemprice < itemcost) {
            price!!.error = "Selling price cannot be lower than item price!"
        } else {
            if (changeDate!!.isChecked) {
                chgDate = true
                date.isEnabled = true
            }
            if (yes!!.isChecked) {
                discount = true
            }
        }
        Toast.makeText(this@AddSales, "Item Name: " + name!!.text + "\n" + "Cost: " + cost!!.text + "\n" + "Item Price: " + price!!.text + "\n" + "Quantity: " + qty!!.text + "Date: " + date + "Staff Discount: " + discount, Toast.LENGTH_SHORT).show()
    }

}

and the error is:

11-17 06:23:34.603 3540-3540/com.example.ruiru.salestracker
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.ruiru.salestracker, PID: 3540
                                                                                java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.ruiru.salestracker/com.example.ruiru.salestracker.AddSales}:
  kotlin.KotlinNullPointerException
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                                Caused by: kotlin.KotlinNullPointerException
                                                                                at com.example.ruiru.salestracker.AddSales.onCreate(AddSales.kt:25)
                                                                                at android.app.Activity.performCreate(Activity.java:6975)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Body:
val date: EditText? = null
val changeDate: CheckBox? = null
val yes: RadioButton? = null
val no: RadioButton? = null

Before using these variables, initialize them with findViewById or bind them to the xml view.


问:
How to get the id of the td based if the text value matches exactly
How to get the id of the td based if the text value matches exactly?

    George
    George2
    George3
    Georg

```

I want the id of "Georg" td4 to get returned?

答:
Replace "Georg" with your desire text.</p>

```<code>$("#tid1 td:contains(Georg)").each(function(){
        alert(this.id);
    });
</code>```

Body:
How to get the id of the td based if the text value matches exactly?

    George
    George2
    George3
    Georg

I want the id of "Georg" td4 to get returned?

Body:
Replace "Georg" with your desire text.

$("#tid1 td:contains(Georg)").each(function(){
        alert(this.id);
    });


答:
Here, this function adds up all the values and returns the sum.

function getSum() {
   var total = 0;
   $('.tt').each(function(i, obj) {
      total += Number(obj.value);
   });

   return total;
}

console.log(getSum());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25"></code>```

Body:
Here is my html

<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">

I am trying to add all the values that has the same class name tt

So i am doing like this

$('.tt').each(function(i, obj) {
    var oo = obj;
    console.log(oo)
});

When i do console.log(00)

It prints

<input type="hidden" class="tt to_5" value="35">

But when I try to do

console.log(oo.val())

It is showing undefined How can I get the value ?

Am using jQuery

Body:
Here, this function adds up all the values and returns the sum.

function getSum() {
   var total = 0;
   $('.tt').each(function(i, obj) {
      total += Number(obj.value);
   });

   return total;
}

console.log(getSum());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">


问:
How to use expression-templates for specific types?
When using expression templates, how do I create specializations? From the Wikipedia example, I can make a Vector sum template class like so:

```<code>template <typename E1, typename E2>
class VecSum : public VecExpression<VecSum<E1, E2> > {
    E1 const& _u;
    E2 const& _v;
public:
    VecSum(E1 const& u, E2 const& v) : _u(u), _v(v) {
        assert(u.size() == v.size());
    }
    double operator[](size_t i) const { return _u[i] + _v[i]; }
    size_t size()               const { return _v.size(); }
};

template <typename E1, typename E2>
VecSum<E1,E2> const
operator+(E1 const& u, E2 const& v) {
   return VecSum<E1, E2>(u, v);
}
</code>```

According to Wikipedia, if I have a Vector class that extends VecExpression<Vector> and a constructor from the VecExpression class that uses the [] operator and a loop, this will allow loop merging so statements like the following only use a single loop:

```<code>Vector a = ...;
Vector b = ...;
Vector c = ...;
Vector d = a+b+c;
</code>```

I get why this works, but I'm not sure how to extend it to scalars. I want to be able to add a scalar (int, float, or double) to the entire Vector, but I'm not sure how to do this. My best guess is to create specializations for the VecSum class like:

```<code>template<typename E2> VecSum<int, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, int>{ /*stuff goes here*/ }
template<typename E2> VecSum<float, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, float>{ /*stuff goes here*/ }
template<typename E2> VecSum<double, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, double>{ /*stuff goes here*/ }
</code>```

But this seems like its a lot more work than is necessary, is there another solution?

答:
Simply use SFINAE to check if the type is an arithmethic one and specialize as needed.

Example:

```<code>template <typename E1, typename E2, typename Enable = void > class VecSum;

template <typename E1, typename E2>
class VecSum< E1, E2,
      typename std::enable_if_t<!std::is_arithmetic<E1>::value && !std::is_arithmetic<E2>::value>
      > : public VecExpression<VecSum<E1, E2> >
{
    E1 const& _u;
    E2 const& _v;

    public:

    VecSum(E1 const& u, E2 const& v) : _u(u), _v(v)
    {
        assert(u.size() == v.size());
    }

    double operator[](size_t i) const { return _u[i] + _v[i]; }
    size_t size()               const { return _v.size(); }
};

template <typename E1, typename E2>
class VecSum < E1, E2,
      typename std::enable_if_t< std::is_arithmetic<E1>::value && !std::is_arithmetic<E2>::value>
      > : public VecExpression<VecSum<E1, E2> >
{
    E1 const& _u;
    E2 const& _v;

    public:

    VecSum(E1 const& u, E2 const& v) : _u(u), _v(v)
    {
    }

    double operator[](size_t i) const { return _u + _v[i]; }
    size_t size()               const { return _v.size(); }
};

template <typename E1, typename E2>
class VecSum < E1, E2,
      typename std::enable_if_t< !std::is_arithmetic<E1>::value && std::is_arithmetic<E2>::value>
      > : public VecExpression<VecSum<E1, E2> >
{
    E1 const& _u;
    E2 const& _v;

    public:

    VecSum(E1 const& u, E2 const& v) : _u(u), _v(v)
    {
    }

    double operator[](size_t i) const { return _u[i] + _v; }
    size_t size()               const { return _u.size(); }
};

int main(){
    Vec v0 = { 1, 2, 3 ,4 };
    Vec v1 = {10, 20,30,40 };
    Vec v2 = {100,200,300,400 };

    {

        Vec sum = v0+v1+v2;
        Vec v3(4);

        for(int i=0;i<4;++i)
            v3[i]=sum[i];

        for(unsigned int i=0;i<v3.size();++i)
            std::cout << v3[i] << std::endl;
    }

    std::cout << "with lhs skalar" << std::endl;

    {
        Vec sum = 5 + 50 + v1;
        Vec v3(4);

        for(int i=0;i<4;++i)
            v3[i]=sum[i];

        for(unsigned int i=0;i<v3.size();++i)
            std::cout << v3[i] << std::endl;

    }

    std::cout << "with rhs skalar" << std::endl;

    {
        Vec sum = v1 + 5 + 50 ;
        Vec v3(4);

        for(int i=0;i<4;++i)
            v3[i]=sum[i];

        for(unsigned int i=0;i<v3.size();++i)
            std::cout << v3[i] << std::endl;

    }

}
</code>```

Body:
When using expression templates, how do I create specializations? From the Wikipedia example, I can make a Vector sum template class like so:

template <typename E1, typename E2>
class VecSum : public VecExpression<VecSum<E1, E2> > {
    E1 const& _u;
    E2 const& _v;
public:
    VecSum(E1 const& u, E2 const& v) : _u(u), _v(v) {
        assert(u.size() == v.size());
    }
    double operator[](size_t i) const { return _u[i] + _v[i]; }
    size_t size()               const { return _v.size(); }
};

template <typename E1, typename E2>
VecSum<E1,E2> const
operator+(E1 const& u, E2 const& v) {
   return VecSum<E1, E2>(u, v);
}

According to Wikipedia, if I have a Vector class that extends VecExpression<Vector> and a constructor from the VecExpression class that uses the [] operator and a loop, this will allow loop merging so statements like the following only use a single loop:

Vector a = ...;
Vector b = ...;
Vector c = ...;
Vector d = a+b+c;

I get why this works, but I'm not sure how to extend it to scalars. I want to be able to add a scalar (int, float, or double) to the entire Vector, but I'm not sure how to do this. My best guess is to create specializations for the VecSum class like:

template<typename E2> VecSum<int, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, int>{ /*stuff goes here*/ }
template<typename E2> VecSum<float, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, float>{ /*stuff goes here*/ }
template<typename E2> VecSum<double, E2>{ /*stuff goes here*/ }
template<typename E1> VecSum<E1, double>{ /*stuff goes here*/ }

But this seems like its a lot more work than is necessary, is there another solution?

Body:
Simply use SFINAE to check if the type is an arithmethic one and specialize as needed.

Example:

template <typename E1, typename E2, typename Enable = void > class VecSum;

template <typename E1, typename E2>
class VecSum< E1, E2,
      typename std::enable_if_t<!std::is_arithmetic<E1>::value && !std::is_arithmetic<E2>::value>
      > : public VecExpression<VecSum<E1, E2> >
{
    E1 const& _u;
    E2 const& _v;

    public:

    VecSum(E1 const& u, E2 const& v) : _u(u), _v(v)
    {
        assert(u.size() == v.size());
    }

    double operator[](size_t i) const { return _u[i] + _v[i]; }
    size_t size()               const { return _v.size(); }
};

template <typename E1, typename E2>
class VecSum < E1, E2,
      typename std::enable_if_t< std::is_arithmetic<E1>::value && !std::is_arithmetic<E2>::value>
      > : public VecExpression<VecSum<E1, E2> >
{
    E1 const& _u;
    E2 const& _v;

    public:

    VecSum(E1 const& u, E2 const& v) : _u(u), _v(v)
    {
    }

    double operator[](size_t i) const { return _u + _v[i]; }
    size_t size()               const { return _v.size(); }
};

template <typename E1, typename E2>
class VecSum < E1, E2,
      typename std::enable_if_t< !std::is_arithmetic<E1>::value && std::is_arithmetic<E2>::value>
      > : public VecExpression<VecSum<E1, E2> >
{
    E1 const& _u;
    E2 const& _v;

    public:

    VecSum(E1 const& u, E2 const& v) : _u(u), _v(v)
    {
    }

    double operator[](size_t i) const { return _u[i] + _v; }
    size_t size()               const { return _u.size(); }
};

int main(){
    Vec v0 = { 1, 2, 3 ,4 };
    Vec v1 = {10, 20,30,40 };
    Vec v2 = {100,200,300,400 };

    {

        Vec sum = v0+v1+v2;
        Vec v3(4);

        for(int i=0;i<4;++i)
            v3[i]=sum[i];

        for(unsigned int i=0;i<v3.size();++i)
            std::cout << v3[i] << std::endl;
    }

    std::cout << "with lhs skalar" << std::endl;

    {
        Vec sum = 5 + 50 + v1;
        Vec v3(4);

        for(int i=0;i<4;++i)
            v3[i]=sum[i];

        for(unsigned int i=0;i<v3.size();++i)
            std::cout << v3[i] << std::endl;

    }

    std::cout << "with rhs skalar" << std::endl;

    {
        Vec sum = v1 + 5 + 50 ;
        Vec v3(4);

        for(int i=0;i<4;++i)
            v3[i]=sum[i];

        for(unsigned int i=0;i<v3.size();++i)
            std::cout << v3[i] << std::endl;

    }

}


问:
Click on current row for expand details in jQuery
I want to click on particular row to expand that row with some data. I tried with this jQuery but it is not working.

could anybody help, where I missed something.

jQuery

this is working fine but I want to do with current row

```<code>$('.item-id-expand').click(function(){
  $('.item-id-close').css("display", "inline-block");
  $('.item-id-expand').hide();
  $('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $('.item-id-close').hide();
  $('.item-id-expand').show();
  $('.order-details-row1-details').hide();
});
</code>```

Here I tried with this but its not working

```<code>$('.item-id-expand', this).click(function(){
  $(this).find('.item-id-close').css("display", "inline-block");
  $(this).find('.item-id-expand').hide();
  $(this).find('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $(this).find('.item-id-close').hide();
  $(this).find('.item-id-expand').show();
  $(this).find('.order-details-row1-details').hide();
});
</code>```

Html

```<code><div class="order-details">
  <ul class="order-details-head">
    <li>Item ID</li>
    <li>Name</li>
    <li>Qty</li>
    <li>Status</li>
  </ul>
  <ul class="order-details-row1">
    <li><div class="item-id-expand">+</div><div class="item-id-close">-</div>123456</li>
    <li>php 11 echo </li>
    <li>php 12 echo </li>
    <li>php 13 echo </li>
  </ul>
  <div class="order-details-row1-details">
    <ul class="order-details-row1-details-head">
      <li>Date</li>
      <li>Description</li>
    </ul>
    <ul class="order-details-row1-details1">
      <li> echo datetrack</li>
      <li>php echo </li>
    </ul>
  </div>
  <ul class="order-details-row1">
    <li><div class="item-id-expand">+</div><div class="item-id-close">-</div>654321</li>
    <li>php 21 echo </li>
    <li>php 22 echo </li>
    <li>php 23 echo </li>
  </ul>
  <div class="order-details-row1-details">
    <ul class="order-details-row1-details-head">
      <li>Date</li>
      <li>Description</li>
    </ul>
    <ul class="order-details-row1-details1">
      <li> echo datetrack</li>
      <li>php echo </li>
    </ul>
  </div>
</div>
</code>```

答:
Do it like below (use $(this) inside function):-

```<code>$('.item-id-expand').click(function() {
  $(this).siblings('.item-id-close').css("display", "inline-block");
  $(this).hide();
  $(this).closest('.order-details-row1').next('.order-details-row1-details').show();
});
$('.item-id-close').click(function() {
  $(this).hide();
  $(this).closest('.order-details-row1').find('.item-id-expand').show();
  $(this).closest('.order-details-row1').next('.order-details-row1-details').hide();
});
</code>```

Working jsfiddle:- https://jsfiddle.net/wfjv2mhg/

Body:
I want to click on particular row to expand that row with some data. I tried with this jQuery but it is not working.

could anybody help, where I missed something.

jQuery

this is working fine but I want to do with current row

$('.item-id-expand').click(function(){
  $('.item-id-close').css("display", "inline-block");
  $('.item-id-expand').hide();
  $('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $('.item-id-close').hide();
  $('.item-id-expand').show();
  $('.order-details-row1-details').hide();
});

Here I tried with this but its not working

$('.item-id-expand', this).click(function(){
  $(this).find('.item-id-close').css("display", "inline-block");
  $(this).find('.item-id-expand').hide();
  $(this).find('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $(this).find('.item-id-close').hide();
  $(this).find('.item-id-expand').show();
  $(this).find('.order-details-row1-details').hide();
});

Html

Item ID

Name

Qty

Status

+

-
123456

php 11 echo

php 12 echo

php 13 echo

Date

Description

 echo datetrack

php echo

+

-
654321

php 21 echo

php 22 echo

php 23 echo

Date

Description

 echo datetrack

php echo

Body:
Do it like below (use $(this) inside function):-

$('.item-id-expand').click(function() {
  $(this).siblings('.item-id-close').css("display", "inline-block");
  $(this).hide();
  $(this).closest('.order-details-row1').next('.order-details-row1-details').show();
});
$('.item-id-close').click(function() {
  $(this).hide();
  $(this).closest('.order-details-row1').find('.item-id-expand').show();
  $(this).closest('.order-details-row1').next('.order-details-row1-details').hide();
});

Working jsfiddle:- https://jsfiddle.net/wfjv2mhg/


问:
Populate spinner from database content (SQLite)
How can I populate a spinner content from database (SQLite)

I have POJO: categories, contain id and name,
I have the table already, with a function to get the ArrayList like this:

```<code>public List<SetcardCategory> getAllSetcardCategory()
{
    List<SetcardCategory> setcardCategories = new ArrayList<SetcardCategory>();
    String selectQuery = "SELECT  * FROM " + TABLE_SETCARD_CATEGORIES;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (c.moveToFirst()) {
        do {
            SetcardCategory setcardCategory = new SetcardCategory();
            setcardCategory.setId(c.getInt((c.getColumnIndex("id"))));
            setcardCategory.setName(c.getString(c.getColumnIndex("name")));

            // adding to tags list
            setcardCategories.add(setcardCategory);
        } while (c.moveToNext());
    }
    return setcardCategories;
}
</code>```

Then on Activity I call it like this:

```<code>List<SetcardCategory> setcardCategories = db.getAllSetcardCategory();
    ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
            this, android.R.layout.simple_spinner_item, setcardCategories);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Spinner sItems = (Spinner) findViewById(R.id.setcardCategory);
    sItems.setAdapter(arrayAdapter);
</code>```

when I run it, it loads string like this: "schema.SetcardCategory@22293c98"  and many others values similar to that.

How can I populate the spinner to show the name field as a label, and id field as the value that we fetch to save into DB?

答:
Solution 1
Overide the toString method in your SetcardCategory class

```<code>class SetcardCategory {
...
...
@Override
    public String toString() {
        return this.name;
    }
}
</code>```

Solution 2
If you just want to show the name, Just pick name only from DB

```<code>public List<String> getAllSetcardCategory()
    {
        List<String> setcardCategories = new ArrayList<String>();
        String selectQuery = "SELECT  * FROM " + TABLE_SETCARD_CATEGORIES;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                // adding to tags list
                setcardCategories.add(c.getString(c.getColumnIndex("name")));
            } while (c.moveToNext());
        }
        return setcardCategories;
    }
</code>```

And create Array Adapter as

```<code>List<String> setcardCategories = db.getAllSetcardCategory();
    ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
            this, android.R.layout.simple_spinner_item, setcardCategories);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
</code>```

Body:
How can I populate a spinner content from database (SQLite)

I have POJO: categories, contain id and name,
I have the table already, with a function to get the ArrayList like this:

public List<SetcardCategory> getAllSetcardCategory()
{
    List<SetcardCategory> setcardCategories = new ArrayList<SetcardCategory>();
    String selectQuery = "SELECT  * FROM " + TABLE_SETCARD_CATEGORIES;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (c.moveToFirst()) {
        do {
            SetcardCategory setcardCategory = new SetcardCategory();
            setcardCategory.setId(c.getInt((c.getColumnIndex("id"))));
            setcardCategory.setName(c.getString(c.getColumnIndex("name")));

            // adding to tags list
            setcardCategories.add(setcardCategory);
        } while (c.moveToNext());
    }
    return setcardCategories;
}

Then on Activity I call it like this:

List<SetcardCategory> setcardCategories = db.getAllSetcardCategory();
    ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
            this, android.R.layout.simple_spinner_item, setcardCategories);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Spinner sItems = (Spinner) findViewById(R.id.setcardCategory);
    sItems.setAdapter(arrayAdapter);

when I run it, it loads string like this: "schema.SetcardCategory@22293c98"  and many others values similar to that.

How can I populate the spinner to show the name field as a label, and id field as the value that we fetch to save into DB?

Body:
Solution 1
Overide the toString method in your SetcardCategory class

class SetcardCategory {
...
...
@Override
    public String toString() {
        return this.name;
    }
}

Solution 2
If you just want to show the name, Just pick name only from DB

public List<String> getAllSetcardCategory()
    {
        List<String> setcardCategories = new ArrayList<String>();
        String selectQuery = "SELECT  * FROM " + TABLE_SETCARD_CATEGORIES;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                // adding to tags list
                setcardCategories.add(c.getString(c.getColumnIndex("name")));
            } while (c.moveToNext());
        }
        return setcardCategories;
    }

And create Array Adapter as

List<String> setcardCategories = db.getAllSetcardCategory();
    ArrayAdapter<SetcardCategory> arrayAdapter = new ArrayAdapter<SetcardCategory>(
            this, android.R.layout.simple_spinner_item, setcardCategories);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


问:
Oracle SQL - One query gives the correct output while the other, very similar, query does not. Why?
This query is executing and giving correct output:

```<code>select * from emp where hiredate > '15-11-81'
</code>```

But this query is not giving correct output:

```<code>select * from emp where hiredate > '01-01-11'
</code>```

Why?

答:
I think </p>

```<code> select * from emp where hiredate > '01-01-11'
</code>```

<p>have no data. you need to share the Table data with query and table definition. </p>

Body:
This query is executing and giving correct output:

select * from emp where hiredate > '15-11-81'

But this query is not giving correct output:

select * from emp where hiredate > '01-01-11'

Why?

Body:
I think

 select * from emp where hiredate > '01-01-11'

have no data. you need to share the Table data with query and table definition.


问:
Node JS request blocking other requests
I have created Node JS app, i am explicitly downloading more than 100000 records from database. While the request is in proceeding, i try to login in the same application from another browser it wont respond unless the previous request is completed. Any idea ? Anything to do with event loop or threads ??
So here is my logic.
I make a get request to my API in Step 1, API calls database layer in Step 2. Database is returning only 21 records, i am explicitly looping 100000*21 to make heavy rendering just to test the load on json2csv. While doing so, the other requests to server will not respond until the last processing completes.</p>

```<code>Step 1:

router.get('/report/downloadOverdueTrainings/:criteria', function (req, res, next) {
        var overDueTrainings = [];
        var reportManager = new ReportManager();
        var result = reportManager.getOverdueTrainings(JSON.parse(req.params.criteria));
        result.then(function (result) {
            var fields = ['Over Due Trainings'];
            for (var i = 0; i < 100000; i++) { //Testing purpose
                for (var training of result) {
                    overDueTrainings.push({
                        'Over Due Trainings': training.OverDueTrainings
                    })
                }
            }
            json2csv({
                data: overDueTrainings,
                fields: fields
            }, function (err, csv) {
                if (err)
                    throw err;
                res.setHeader('Content-disposition', 'attachment; filename=OverdueTrainings.csv');
                res.set('Content-Type', 'text/csv');
                res.send(csv);
            });
        }).catch(function (err) {
            next(err);
        });
    });

Step 2: Database Logic
var xtrDatabaseConnection =require('./xtrDatabaseConnection').XTRDatabaseConnection;
       ReportData.prototype.getOverdueTrainings = async function (params) {
        var connection = new xtrDatabaseConnection();
        var sequelize = connection.getSequelize();
        try {
            var query = "CALL report_getOverdueTrainings(:p_CourseCode,:p_Revision,:p_RevisionNo,:p_UserGroup,:p_Username,:p_Status,:p_SortColoumnNo,:p_SortColoumnDirection,:p_callType,:p_StartIndex,:p_PageSize)";
            var replacements = {
                p_CourseCode: params.CourseCode,
                p_Revision: params.Revision,
                p_RevisionNo: (params.RevisionNo == '' || params.RevisionNo == null) ? 0 : params.RevisionNo,
                p_UserGroup: params.UserGroup,
                p_Username: params.Username,
                p_Status: params.Status,
                p_SortColoumnNo: params.SortColoumnNo,
                p_SortColoumnDirection: params.SortColoumnDirection,
                p_callType: params.callType,
                p_StartIndex: params.startIndex,
                p_PageSize: params.pageSize
            };
            //console.log(replacements);
            return await connection.executeQuerySequelize(sequelize, query, Sequelize.QueryTypes.RAW, replacements);
        } catch (e) {
            throw (e);
        } finally {
            //To close connections
            sequelize.connectionManager.close().then(() => console.log('Connection Closed'));
        }
    }

XTRDatabaseConnection.prototype.executeQuerySequelize = function (sequelize, query, queryType, replacements) {
    return sequelize.authenticate()
        .then(() => {
            return sequelize.query(query, {
                replacements: replacements,
                type: queryType
            }).
            then(result => result)
                .catch(err => {
                    throw (err);
                });
        })
        .catch(err => {
            xtrUtility.logErrorsToWinstonTransports('Unable to connect to the database or some error occurred while executing your query. ', err);
            throw new AppError(err, "dbError", "Unable to connect to the database or some error occurred while executing your query.");
        });
}
</code>```

答:
This is blocking:

```<code>    for (var i = 0; i < 100000; i++) { //Testing purpose
        for (var training of result) {
            overDueTrainings.push({
                'Over Due Trainings': training.OverDueTrainings
            })
        }
    }
</code>```

until the execution is finished.

also

```<code> var result = reportManager.getOverdueTrainings(JSON.parse(req.params.criteria));
    result.then(function (result) {
 /****/
 return await connection.executeQuerySequelize(sequelize, query, Sequelize.QueryTypes.RAW, replacements);
</code>```

Title: Node JS request blocking other requests

Body:
I have created Node JS app, i am explicitly downloading more than 100000 records from database. While the request is in proceeding, i try to login in the same application from another browser it wont respond unless the previous request is completed. Any idea ? Anything to do with event loop or threads ??
So here is my logic.
I make a get request to my API in Step 1, API calls database layer in Step 2. Database is returning only 21 records, i am explicitly looping 100000*21 to make heavy rendering just to test the load on json2csv. While doing so, the other requests to server will not respond until the last processing completes.

Step 1:

router.get('/report/downloadOverdueTrainings/:criteria', function (req, res, next) {
        var overDueTrainings = [];
        var reportManager = new ReportManager();
        var result = reportManager.getOverdueTrainings(JSON.parse(req.params.criteria));
        result.then(function (result) {
            var fields = ['Over Due Trainings'];
            for (var i = 0; i < 100000; i++) { //Testing purpose
                for (var training of result) {
                    overDueTrainings.push({
                        'Over Due Trainings': training.OverDueTrainings
                    })
                }
            }
            json2csv({
                data: overDueTrainings,
                fields: fields
            }, function (err, csv) {
                if (err)
                    throw err;
                res.setHeader('Content-disposition', 'attachment; filename=OverdueTrainings.csv');
                res.set('Content-Type', 'text/csv');
                res.send(csv);
            });
        }).catch(function (err) {
            next(err);
        });
    });

Step 2: Database Logic
var xtrDatabaseConnection =require('./xtrDatabaseConnection').XTRDatabaseConnection;
       ReportData.prototype.getOverdueTrainings = async function (params) {
        var connection = new xtrDatabaseConnection();
        var sequelize = connection.getSequelize();
        try {
            var query = "CALL report_getOverdueTrainings(:p_CourseCode,:p_Revision,:p_RevisionNo,:p_UserGroup,:p_Username,:p_Status,:p_SortColoumnNo,:p_SortColoumnDirection,:p_callType,:p_StartIndex,:p_PageSize)";
            var replacements = {
                p_CourseCode: params.CourseCode,
                p_Revision: params.Revision,
                p_RevisionNo: (params.RevisionNo == '' || params.RevisionNo == null) ? 0 : params.RevisionNo,
                p_UserGroup: params.UserGroup,
                p_Username: params.Username,
                p_Status: params.Status,
                p_SortColoumnNo: params.SortColoumnNo,
                p_SortColoumnDirection: params.SortColoumnDirection,
                p_callType: params.callType,
                p_StartIndex: params.startIndex,
                p_PageSize: params.pageSize
            };
            //console.log(replacements);
            return await connection.executeQuerySequelize(sequelize, query, Sequelize.QueryTypes.RAW, replacements);
        } catch (e) {
            throw (e);
        } finally {
            //To close connections
            sequelize.connectionManager.close().then(() => console.log('Connection Closed'));
        }
    }

XTRDatabaseConnection.prototype.executeQuerySequelize = function (sequelize, query, queryType, replacements) {
    return sequelize.authenticate()
        .then(() => {
            return sequelize.query(query, {
                replacements: replacements,
                type: queryType
            }).
            then(result => result)
                .catch(err => {
                    throw (err);
                });
        })
        .catch(err => {
            xtrUtility.logErrorsToWinstonTransports('Unable to connect to the database or some error occurred while executing your query. ', err);
            throw new AppError(err, "dbError", "Unable to connect to the database or some error occurred while executing your query.");
        });
}

Body:
This is blocking:

    for (var i = 0; i < 100000; i++) { //Testing purpose
        for (var training of result) {
            overDueTrainings.push({
                'Over Due Trainings': training.OverDueTrainings
            })
        }
    }

until the execution is finished.

also

 var result = reportManager.getOverdueTrainings(JSON.parse(req.params.criteria));
    result.then(function (result) {
 /****/
 return await connection.executeQuerySequelize(sequelize, query, Sequelize.QueryTypes.RAW, replacements);


问:
Reverse a float number C
I am learning C. We use scanf and printf for input and output data.

We have a question in our lesson: Reverse a float number.

My programming skills are good and I can do this easily.

For example one of my ideas is to convert a float number to int by power 10 then reverse it and convert it to float again. There are lots of other ideas too.

But we have a limit in our question. Use scanf features to reverse number.

I ask my teacher to give me a code for this. He gave below code. I am sorry because I don't understand code clearly. This code give 12 and 33 for 12.33 but this code doesnt work for 12.00001 because we get 12 and 1. When we get this number we reverse them and print it. My teacber asks me a way to solve this but I can't find a way. It is not neccesary to exist a way but Is it possible to help me?

My teacher code:

```<code>int main(){
    int a,b;
    scanf("%d.%d", &a, &b);
    printf("a = %d, b = %d", a, b);
}
</code>```

Thanks.

答:
If don't want any calculation then get it in String format and then reverse it.</p>

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

void main(){
  char str[20];

  printf("Enter number: ");
  scanf( "%s" , str );

  printf("\nReverse Number is: %s",strrev(str));

}
</code>```

Title: Reverse a float number C

Body:
I am learning C. We use scanf and printf for input and output data.

We have a question in our lesson: Reverse a float number.

My programming skills are good and I can do this easily.

For example one of my ideas is to convert a float number to int by power 10 then reverse it and convert it to float again. There are lots of other ideas too.

But we have a limit in our question. Use scanf features to reverse number.

I ask my teacher to give me a code for this. He gave below code. I am sorry because I don't understand code clearly. This code give 12 and 33 for 12.33 but this code doesnt work for 12.00001 because we get 12 and 1. When we get this number we reverse them and print it. My teacber asks me a way to solve this but I can't find a way. It is not neccesary to exist a way but Is it possible to help me?

My teacher code:

int main(){
    int a,b;
    scanf("%d.%d", &a, &b);
    printf("a = %d, b = %d", a, b);
}

Thanks.

Body:
If don't want any calculation then get it in String format and then reverse it.

#include<stdio.h>
#include<string.h>

void main(){
  char str[20];

  printf("Enter number: ");
  scanf( "%s" , str );

  printf("\nReverse Number is: %s",strrev(str));

}


问:
Rails : RuntimeError - can't modify frozen Array when running rspec in rails
I recently upgraded to Rails 5.1 from v4.3 and am now getting this error when running tests:

```<code>An error occurred while loading

./spec/controllers/admin/capacity_charges_controller_spec.rb.
Failure/Error: require File.expand_path('../../config/environment', __FILE__)

RuntimeError:
  can't modify frozen Array
</code>```

I get it for every test file. The line that triggers the error comes from rails_helper. I've checked rails 5.1 sample repos and there's nothing substantially different about our version.

The full stack trace is:

```<code>RuntimeError:

can't modify frozen Array
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/actionpack-5.1.0/lib/action_dispatch/middleware/stack.rb:74:in `insert'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/actionpack-5.1.0/lib/action_dispatch/middleware/stack.rb:74:in `insert'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/actionpack-5.1.0/lib/action_dispatch/middleware/stack.rb:81:in `insert_after'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/request_store-1.3.2/lib/request_store/railtie.rb:5:in `block in <class:Railtie>'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/railties-5.1.0/lib/rails/initializable.rb:30:in `instance_exec'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/railties-5.1.0/lib/rails/initializable.rb:30:in `run'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/railties-5.1.0/lib/rails/initializable.rb:59:in `block in run_initializers'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/railties-5.1.0/lib/rails/initializable.rb:58:in `run_initializers'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/railties-5.1.0/lib/rails/application.rb:353:in `initialize!'
# ./config/environment.rb:5:in `<top (required)>'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `require'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `block in require'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:258:in `load_dependency'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `require'
# ./spec/rails_helper.rb:12:in `<top (required)>'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `require'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `block in require'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:258:in `load_dependency'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `require'
# ./spec/controllers/admin/capacity_charges_controller_spec.rb:3:in `<top (required)>'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:286:in `load'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:286:in `block in load'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:258:in `load_dependency'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:286:in `load'
</code>```

答: Turns out this was caused by test failures higher in the stack trace. It was hard to see what the root cause was because there was so much in the console. If you get this issue, I'd suggest using --fail-fast so you don't get overwhelmed with recurrent error messages. Then check what the first error is.

Body:
I recently upgraded to Rails 5.1 from v4.3 and am now getting this error when running tests:

An error occurred while loading

./spec/controllers/admin/capacity_charges_controller_spec.rb.
Failure/Error: require File.expand_path('../../config/environment', __FILE__)

RuntimeError:
  can't modify frozen Array

I get it for every test file. The line that triggers the error comes from rails_helper. I've checked rails 5.1 sample repos and there's nothing substantially different about our version.

The full stack trace is:

RuntimeError:

can't modify frozen Array
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/actionpack-5.1.0/lib/action_dispatch/middleware/stack.rb:74:in `insert'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/actionpack-5.1.0/lib/action_dispatch/middleware/stack.rb:74:in `insert'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/actionpack-5.1.0/lib/action_dispatch/middleware/stack.rb:81:in `insert_after'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/request_store-1.3.2/lib/request_store/railtie.rb:5:in `block in <class:Railtie>'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/railties-5.1.0/lib/rails/initializable.rb:30:in `instance_exec'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/railties-5.1.0/lib/rails/initializable.rb:30:in `run'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/railties-5.1.0/lib/rails/initializable.rb:59:in `block in run_initializers'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/railties-5.1.0/lib/rails/initializable.rb:58:in `run_initializers'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/railties-5.1.0/lib/rails/application.rb:353:in `initialize!'
# ./config/environment.rb:5:in `<top (required)>'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `require'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `block in require'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:258:in `load_dependency'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `require'
# ./spec/rails_helper.rb:12:in `<top (required)>'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `require'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `block in require'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:258:in `load_dependency'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:292:in `require'
# ./spec/controllers/admin/capacity_charges_controller_spec.rb:3:in `<top (required)>'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:286:in `load'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:286:in `block in load'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:258:in `load_dependency'
# /Users/jeremynagel/.rvm/gems/ruby-2.3.1@Rails4.2_EnergyLink/gems/activesupport-5.1.0/lib/active_support/dependencies.rb:286:in `load'


问:
creating a dictionary with two lists when a key should have two values in python
hi I have two lists,

```<code>list1
['PO', 'NA', 'PO']

list2
['Post Office', 'Not Available', 'Post area']
</code>```

Iam trying to get a dictionary using this two lists
I tried, my_dict=dict(zip(list1,list2))
it gives,

```<code> {'NA': 'Not Available', 'PO': 'Post area'}
</code>```

but my expected output is,

```<code> {'NA': 'Not Available', 'PO': ['Post area','Post Office']}
</code>```

pls help

答:
You can define your own custom dict class using dict

```<code>class ListDict(dict):
    def __init__(self, d={}):
        if isinstance(d, zip):
            for i, v in enumerate(d):
                self.__setattr__(v[0], v[1])
        else:
            self.update(d)

    def __setattr__(self, key, val):
        if key in self:
            if not isinstance(self[key], list):
                self[key] = [self[key]]
            self[key].append(val)
        else:
            self[key] = val

list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']
my_dict = ListDict(zip(list1, list2))
print(my_dict)
</code>```

output:

```<code>{'PO': ['Post Office', 'Post area'], 'NA': 'Not Available'}
</code>```

Body:
hi I have two lists,

list1
['PO', 'NA', 'PO']

list2
['Post Office', 'Not Available', 'Post area']

Iam trying to get a dictionary using this two lists
I tried, my_dict=dict(zip(list1,list2))
it gives,

 {'NA': 'Not Available', 'PO': 'Post area'}

but my expected output is,

 {'NA': 'Not Available', 'PO': ['Post area','Post Office']}

pls help

Body:
You can define your own custom dict class using dict

class ListDict(dict):
    def __init__(self, d={}):
        if isinstance(d, zip):
            for i, v in enumerate(d):
                self.__setattr__(v[0], v[1])
        else:
            self.update(d)

    def __setattr__(self, key, val):
        if key in self:
            if not isinstance(self[key], list):
                self[key] = [self[key]]
            self[key].append(val)
        else:
            self[key] = val

list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']
my_dict = ListDict(zip(list1, list2))
print(my_dict)

output:

{'PO': ['Post Office', 'Post area'], 'NA': 'Not Available'}


问:
How to validate time using javascript if the time already past
Can i ask if how to validate time using javascript in combox contain having a choices and it can validate if she/he choose the time that already past</p>

```<code><input type="time" id="time" name="timeval">
</code>```

答:
if you have time in HH:MM:SS (24 hr)format than you can do like as below

```<code>var str1 = "10:20:45",
    str2 = "05:10:10";

if (str1 > str2)
    alert("Time 1 is later than time 2");
else
    alert("Time 2 is later than time 1");
</code>```

get current time as below

```<code>var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();

var curr_sec = d.getSeconds();

document.write(curr_hour + ":" + curr_min + ":"
+ curr_sec);
</code>```

Body:
Can i ask if how to validate time using javascript in combox contain having a choices and it can validate if she/he choose the time that already past

<input type="time" id="time" name="timeval">

Body:
if you have time in HH:MM:SS (24 hr)format than you can do like as below

var str1 = "10:20:45",
    str2 = "05:10:10";

if (str1 > str2)
    alert("Time 1 is later than time 2");
else
    alert("Time 2 is later than time 1");

get current time as below

var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();

var curr_sec = d.getSeconds();

document.write(curr_hour + ":" + curr_min + ":"
+ curr_sec);