问:
Gremlin Server as REST API with dynamically created data
Let's say I have the following:
- a node.js server that is able to query a database and receive a (possibly big) JSON
- a gremlin server (configured with gremlin-server-rest-modern.yaml but maybe there must be something more in there)

My question is: is there a way to dynamically and programmatically add a new graph to be served up by the server? I want my node server to query the database and send the JSON response to the gremlin server; there, the response will be converted into a graph; from the node server, the user will be able to send other queries and receive complex responses. How can I achieve that?

I tried to use [1] but I'm not sure how can I do what I want. How do you actually send multiple (chained) commands, like a mini-script? I know how to do it using the console, but not using the server (as a REST service), since there is not an exposed API. Can you give me an advice or some examples? Thanks!

Adrian

[1] https://github.com/jbmusso/gremlin-javascript

Edit:
I managed to send a POST message to the server with some simple commands. It works if I send a POST with all the commands (the graph creation and the query). However, for multiple POSTs, the context is not saved. First, I'm sending a POST with the content:

```<code>{
 "gremlin" : "graph = TinkerGraph.open(); g = graph .traversal(); graph .addVertex('name', 'adrian', 'age', 21); "
}
</code>```

Then, I send another POST with

```<code>{
 "gremlin" : "v2 = graph.addVertex('name', 'gigel', 'age', 22); g.V()"
}
</code>```

However, I get the following error:

```<code>{
    "message": "No such property: graf for class: Script4",
    "Exception-Class": "groovy.lang.MissingPropertyException",
    "exceptions": [
        "groovy.lang.MissingPropertyException"
    ],
    "stackTrace": "groovy.lang.MissingPropertyException: No such property: graf for class: Script4\n\tat org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)\n\tat org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)\n\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)\n\tat Script4.run(Script4.groovy:1)\n\tat org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.eval(GremlinGroovyScriptEngine.java:834)\n\tat org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.eval(GremlinGroovyScriptEngine.java:547)\n\tat javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:233)\n\tat org.apache.tinkerpop.gremlin.groovy.engine.ScriptEngines.eval(ScriptEngines.java:120)\n\tat org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.lambda$eval$2(GremlinExecutor.java:314)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\n\tat java.lang.Thread.run(Thread.java:745)\n"
}
</code>```

The context is not saved on the gremlin server? I must send the entire script to be executed? What if I want to create two graphs and query them later?

Thanks!

答:
Graphs you create in scripts through sessionless requests (like REST) are not maintained. You can create graph instances that are maintained between requests in a session but then they are only maintained in that session and not reachable outside of that session.

If you want to create graphs globally for the server they must be:

configured in the server configuration file

produced as part of an initialization script

constructed by a custom GraphManager instance (which involves writing some Java code)

I suppose it would be also possible to build a custom endpoint that let you manage he graphs in some way, but you'd have to get more than a cursory knowledge of Gremlin Server's code to pull that off (wouldn't be too hard though).

Body:
Let's say I have the following:
- a node.js server that is able to query a database and receive a (possibly big) JSON
- a gremlin server (configured with gremlin-server-rest-modern.yaml but maybe there must be something more in there)

My question is: is there a way to dynamically and programmatically add a new graph to be served up by the server? I want my node server to query the database and send the JSON response to the gremlin server; there, the response will be converted into a graph; from the node server, the user will be able to send other queries and receive complex responses. How can I achieve that?

I tried to use [1] but I'm not sure how can I do what I want. How do you actually send multiple (chained) commands, like a mini-script? I know how to do it using the console, but not using the server (as a REST service), since there is not an exposed API. Can you give me an advice or some examples? Thanks!

Adrian

[1] https://github.com/jbmusso/gremlin-javascript

Edit:
I managed to send a POST message to the server with some simple commands. It works if I send a POST with all the commands (the graph creation and the query). However, for multiple POSTs, the context is not saved. First, I'm sending a POST with the content:

{
 "gremlin" : "graph = TinkerGraph.open(); g = graph .traversal(); graph .addVertex('name', 'adrian', 'age', 21); "
}

Then, I send another POST with

{
 "gremlin" : "v2 = graph.addVertex('name', 'gigel', 'age', 22); g.V()"
}

However, I get the following error:

{
    "message": "No such property: graf for class: Script4",
    "Exception-Class": "groovy.lang.MissingPropertyException",
    "exceptions": [
        "groovy.lang.MissingPropertyException"
    ],
    "stackTrace": "groovy.lang.MissingPropertyException: No such property: graf for class: Script4\n\tat org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)\n\tat org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)\n\tat org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)\n\tat Script4.run(Script4.groovy:1)\n\tat org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.eval(GremlinGroovyScriptEngine.java:834)\n\tat org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.eval(GremlinGroovyScriptEngine.java:547)\n\tat javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:233)\n\tat org.apache.tinkerpop.gremlin.groovy.engine.ScriptEngines.eval(ScriptEngines.java:120)\n\tat org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutor.lambda$eval$2(GremlinExecutor.java:314)\n\tat java.util.concurrent.FutureTask.run(FutureTask.java:266)\n\tat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)\n\tat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)\n\tat java.lang.Thread.run(Thread.java:745)\n"
}

The context is not saved on the gremlin server? I must send the entire script to be executed? What if I want to create two graphs and query them later?

Thanks!


来源: stackexchange

问:
Reduce Border bottom length
Hi I want to know that whether can i reduce length of border bottom. I have a div and i have given border-bottom: 2px to that div i want to reduce the length of border. Is this possible.

I have this nav-bar and i have given css to its div want to reduce length of border. How can i do that.

This is my html

```<code>               <div class="row">
        <div class="col-sm-12 col-xs-12 col-lg-12 col-md-12 welcome">
            <ul class="nav navbar-nav navbar-nav-primary">
                <li class="active">
                    <a href="#one" data-toggle="tab">
                        <i class="fa fa-map-marker" aria-hidden="true"></i> <span class="li-text">Location</span>
                    </a>
                </li>
                <li>
                    <a href="#two" data-toggle="tab">
                        <i class="fa fa-heartbeat" aria-hidden="true"></i> <span class="li-text">Heartbeats</span>
                    </a>
                </li>
                <li>
                    <a href="#three" data-toggle="tab">
                        <i class="fa fa-power-off" aria-hidden="true"></i>
                        <span class="li-text">Reboots</span>
                    </a>
                </li>
                <li>
                    <a href="#four" data-toggle="tab">
                        <i class="fa fa-compress" aria-hidden="true"></i>
                        <span class="li-text">Reconnects</span>
                    </a>
                </li>
                <li>
                    <a href="#five" data-toggle="tab">
                        <i class="fa fa-battery-full" aria-hidden="true"></i>
                        <span class="li-text">Charge</span>
                    </a>
                </li>

            </ul>

        </div>
</code>```

This is my CSS

```<code>        .welcome {
              border-bottom: 2px solid #bcbcbc;
              margin-left: 10px;
             }
</code>```

答: Move the welcome class into the ul tag and it should do what you want :)

ContentLicense: CC BY-SA 3.0

Title: Reduce Border bottom length

Body:
Hi I want to know that whether can i reduce length of border bottom. I have a div and i have given border-bottom: 2px to that div i want to reduce the length of border. Is this possible.

I have this nav-bar and i have given css to its div want to reduce length of border. How can i do that.

This is my html

                         Location

                         Heartbeats

                        Reboots

                        Reconnects

                        Charge

This is my CSS

        .welcome {
              border-bottom: 2px solid #bcbcbc;
              margin-left: 10px;
             }


问:
Unicodedecodeerror with runserver
After setting up all what django requires, I tried the runserver command and I caught an error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position
  8: invalid continuation byte

From:

```<code>c:\sue>python manage.py runserver
Validating models...

0 errors found
April 16, 2014 - 15:02:42
Django version 1.6.2, using settings 'sue.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000003890048>
Traceback (most recent call last):
  File "C:\python34\lib\site-packages\django\utils\autoreload.py", line 93, in wrapper fn(*args, **kwargs)
  File "C:\python34\lib\site-packages\django\core\management\commands\runserver.py", line 127, in inner_run ipv6=self.use_ipv6, threading=threading)
  File "C:\python34\lib\site-packages\django\core\servers\basehttp.py", line 167, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
  File "C:\python34\lib\site-packages\django\core\servers\basehttp.py", line 109, in __init__ super(WSGIServer, self).__init__(*args, **kwargs)
  File "C:\python34\lib\socketserver.py", line 430, in __init__ self.server_bind()
  File "C:\python34\lib\site-packages\django\core\servers\basehttp.py", line 113, in server_bind super(WSGIServer, self).server_bind()
  File "C:\python34\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self)
  File "C:\python34\lib\http\server.py", line 137, in server_bind
    self.server_name = socket.getfqdn(host)
  File "C:\python34\lib\socket.py", line 460, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 8: invalid continuation byte
</code>```

I am using Windows 7 x64, python 3.4 and django 1.6.2. What does this error mean?

答:
I hit this issue on python 3.4 with the following situation :

Server did have an ascii-only hostname (like host1)

The /etc/hosts file did not contain an entry for my hostname

There was no available DNS resolver (offline computer)

After adding the following entry to the /etc/hosts file, no further UnicodeDecodeError exceptions were thrown.

```<code>127.0.0.1 localhost host1
</code>```

Title: Unicodedecodeerror with runserver

Body:
After setting up all what django requires, I tried the runserver command and I caught an error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position
  8: invalid continuation byte

From:

c:\sue>python manage.py runserver
Validating models...

0 errors found
April 16, 2014 - 15:02:42
Django version 1.6.2, using settings 'sue.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000003890048>
Traceback (most recent call last):
  File "C:\python34\lib\site-packages\django\utils\autoreload.py", line 93, in wrapper fn(*args, **kwargs)
  File "C:\python34\lib\site-packages\django\core\management\commands\runserver.py", line 127, in inner_run ipv6=self.use_ipv6, threading=threading)
  File "C:\python34\lib\site-packages\django\core\servers\basehttp.py", line 167, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6)
  File "C:\python34\lib\site-packages\django\core\servers\basehttp.py", line 109, in __init__ super(WSGIServer, self).__init__(*args, **kwargs)
  File "C:\python34\lib\socketserver.py", line 430, in __init__ self.server_bind()
  File "C:\python34\lib\site-packages\django\core\servers\basehttp.py", line 113, in server_bind super(WSGIServer, self).server_bind()
  File "C:\python34\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self)
  File "C:\python34\lib\http\server.py", line 137, in server_bind
    self.server_name = socket.getfqdn(host)
  File "C:\python34\lib\socket.py", line 460, in getfqdn
    hostname, aliases, ipaddrs = gethostbyaddr(name)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 8: invalid continuation byte

I am using Windows 7 x64, python 3.4 and django 1.6.2. What does this error mean?

Body:
I hit this issue on python 3.4 with the following situation :

Server did have an ascii-only hostname (like host1)

The /etc/hosts file did not contain an entry for my hostname

There was no available DNS resolver (offline computer)

After adding the following entry to the /etc/hosts file, no further UnicodeDecodeError exceptions were thrown.

127.0.0.1 localhost host1


问:
Eclipse, JDT: Find a file on the classpath knowing its fully qualified name
Given the name ch/mollusca/sample/snippet.xml, is there an easy way to get a hold of this file in JDT code, when it is located in the projects classpath either as a source file or inside a JAR?

The file may also be inside another project, that is referenced by the one, where I'm trying to get a hold of the actual file behind the name.

This is specific to Java projects, so it's possible to get a hold of the IJavaProject if that helps.

答:
How about this:

IEditorPart activeEditor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if ( activeEditor != null ) {
    IResource activeEditorResource = (IResource)activeEditor.getEditorInput().getAdapter( IResource.class );
    if ( activeEditorResource != null && activeEditorResource.getFullPath() != null ) {
        String activeFileName = activeEditorResource.getFullPath().toOSString();
        //...do something with the active file
    }
}
```

ContentLicense: CC BY-SA 2.5


问:
Formatting JSON data and displaying in a PHP for loop
I have some form data which I'm saving in JSON format using jQuery (this is all working fine).

But I then want to take the JSON data and display it in a PHP for loop. This is where I'm having trouble as jQuery's serializeArray and JSON.stringify just adds each form value in one bit chunk e.g.

```<code>check in, check out, room, adults, children, check in, check out, room, adults, children, check in, check out, room, adults, children
</code>```

But I want to separate each room e.g.

```<code>(Room 1) check in, check out, room, adults, children
(Room 2) check in, check out, room, adults, children
(Room 3) check in, check out, room, adults, children
</code>```

JSFiddle of how the form data is created (everything working fine): https://jsfiddle.net/kuohhm2q/

PHP I'm using to try a display JSON data in for loop (not working):

```<code><?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);

//print_r($data);

foreach($data as $key => $val) { ?>

    <?php echo $key; ?>

<?php } ?>
</code>```

答:
I think this should work</p>

```<code><?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);

//print_r($data);

foreach($data as $key => $val) {
foreach($val as $val_key=>$val_val) {
    echo $val_key.":".$val_val."</br>";
}
}
?>
</code>```

Body:
I have some form data which I'm saving in JSON format using jQuery (this is all working fine).

But I then want to take the JSON data and display it in a PHP for loop. This is where I'm having trouble as jQuery's serializeArray and JSON.stringify just adds each form value in one bit chunk e.g.

check in, check out, room, adults, children, check in, check out, room, adults, children, check in, check out, room, adults, children

But I want to separate each room e.g.

(Room 1) check in, check out, room, adults, children
(Room 2) check in, check out, room, adults, children
(Room 3) check in, check out, room, adults, children

JSFiddle of how the form data is created (everything working fine): https://jsfiddle.net/kuohhm2q/

PHP I'm using to try a display JSON data in for loop (not working):

<?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);

//print_r($data);

foreach($data as $key => $val) { ?>

    <?php echo $key; ?>

<?php } ?>

Body:
I think this should work

<?php

$json_data = '[{"name":"check_in","value":"07/11/2017"},{"name":"check_out","value":"07/26/2017"},{"name":"room_type","value":"option_1"},{"name":"adults","value":"2"},{"name":"children","value":"3"},{"name":"check_in","value":"07/27/2017"},{"name":"check_out","value":"07/29/2017"},{"name":"room_type","value":"option_2"},{"name":"adults","value":"3"},{"name":"children","value":"2"}]';

$data = json_decode($json_data, true);

//print_r($data);

foreach($data as $key => $val) {
foreach($val as $val_key=>$val_val) {
    echo $val_key.":".$val_val."</br>";
}
}
?>


问:
SQL: columns name based on variable
I have a temporary table aaa that I use as an array.

```<code>    USE tempdb
    GO

    IF OBJECT_ID('tempdb..aaa') IS NOT NULL DROP TABLE aaa
    CREATE TABLE aaa (
        #1 char(40),
        #2 char(40),
        #3 char(40)
    );
    insert into aaa values ('aaaa','qqqq','eeee');
    declare @sql varchar(40);
    declare @var varchar(40)='#3';
    set @sql= '(select '+@var +' from aaa)';
       print @sql;
</code>```

What I'm trying to achieve is to store into the variable @sql the executed value of '(select '+@var +' from aaa)' which is: eeee and NOT simply the string (select #3 from aaa)

I know that ''this is not how SQL is supposed to work'' but after 320 questions read on SO(my history tab can prove) I'm out of ideas:)

答:
You can use an sp_executesql with an OUTPUT parameter to assign the scalar result:

```<code>IF OBJECT_ID('tempdb..aaa') IS NOT NULL DROP TABLE aaa
CREATE TABLE aaa (
    #1 char(40),
    #2 char(40),
    #3 char(40)
);
INSERT INTO aaa VALUES ('aaaa','qqqq','eeee');
DECLARE @sql nvarchar(40);
DECLARE @sqlStatement nvarchar(MAX);
DECLARE @var varchar(40)='#3';
SET @sqlStatement = '(SELECT '+@var +' FROM aaa)';
EXEC sp_executesql @sqlStatement, N'@sql varchar(40) OUTPUT', @sql = @sql OUTPUT;
PRINT @sql;
</code>```

I think using a variable named @sql for the result is a bit confusing.

Title: SQL: columns name based on variable

Body:
I have a temporary table aaa that I use as an array.

    USE tempdb
    GO

    IF OBJECT_ID('tempdb..aaa') IS NOT NULL DROP TABLE aaa
    CREATE TABLE aaa (
        #1 char(40),
        #2 char(40),
        #3 char(40)
    );
    insert into aaa values ('aaaa','qqqq','eeee');
    declare @sql varchar(40);
    declare @var varchar(40)='#3';
    set @sql= '(select '+@var +' from aaa)';
       print @sql;

What I'm trying to achieve is to store into the variable @sql the executed value of '(select '+@var +' from aaa)' which is: eeee and NOT simply the string (select #3 from aaa)

I know that ''this is not how SQL is supposed to work'' but after 320 questions read on SO(my history tab can prove) I'm out of ideas:)

Body:
You can use an sp_executesql with an OUTPUT parameter to assign the scalar result:

IF OBJECT_ID('tempdb..aaa') IS NOT NULL DROP TABLE aaa
CREATE TABLE aaa (
    #1 char(40),
    #2 char(40),
    #3 char(40)
);
INSERT INTO aaa VALUES ('aaaa','qqqq','eeee');
DECLARE @sql nvarchar(40);
DECLARE @sqlStatement nvarchar(MAX);
DECLARE @var varchar(40)='#3';
SET @sqlStatement = '(SELECT '+@var +' FROM aaa)';
EXEC sp_executesql @sqlStatement, N'@sql varchar(40) OUTPUT', @sql = @sql OUTPUT;
PRINT @sql;

I think using a variable named @sql for the result is a bit confusing.


问:
Redux React Todo Application has no indication of error but doesn't work
I'm following egghead.io Redux course by Dan.
However I've no idea why my todo app is not working. It doesn't output any error and any warning, just doesn't work.

Can you please give me some hint.

This is my jsbin.
https://jsbin.com/cozecip/33/edit?js,output

```<code>const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false
      };
    case 'TOGGLE_TODO':
      if (state.id !== action.id) {
        return state;
      }

      return {
        id: state.id,
        text: state.text,
        completed: !state.completed
      };
    default:
      return state;
  }
};

const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        todo(undefined, action)
      ];
    case 'TOGGLE_TODO':
      return state.map(t =>
        todo(t, action)
      );
    default:
      return state;
  }
};

const visibilityFilter = (state = 'SHOW_ALL', action) =>
{
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter;
    default:
      return state;
  }
};

const { combineReducers } = Redux;

const todoApp = combineReducers({
  todos,
  visibilityFilter
});

const { createStore } = Redux;
const store = createStore(todoApp);

const { Component } = React;

const FilterLink = ({
    filter,
    currentFilter,
    children,
    onClick
}) => {
    if (filter === currentFilter){
      return <span>{children}</span>
    }

    return (
      <a href="#" onClick ={onClick}>{children}</a>
    );
};

const Todo = ({
  onClick,
  completed,
  text
}) => (
  <li
    onClick={onClick}
    style={{
      textDecoration:
        completed ?
          'line-through' :
          'none'
    }}
  >
    {text}
  </li>
);

const TodoList = ({
  todos,
  onTodoClick
}) => (
  <ul>
    {todos.map(todo =>
      <Todo
        key={todo.id}
        {...todo}
        onClick={() => onTodoClick(todo.id)}
      />
    )}
  </ul>
)

const AddTodo = ({
  onAddClick
}) => {
  let input;

  return (
    <div>
    <input ref={node => {
       input = node;
    }} />
    <button onClick={() => {
      onAddClick(input.value)
      input.value = '';
    }}>
    Add Todo
    </button>
    </div>
  );
}

const Footer = ({
  visibilityFilter,
  onFilterClick
}) => (
        <p>
          Show:
          {' '}
          <FilterLink
            filter='SHOW_ALL'
            currentFilter={visibilityFilter}
            onClick={onFilterClick}>
              All
          </FilterLink>
          {' '}
          <FilterLink
            filter='SHOW_ACTIVE'
            currentFilter={visibilityFilter}
            onClick={onFilterClick}>
            Active
          </FilterLink>
          {' '}
          <FilterLink
            filter='SHOW_COMPLETED'
            currentFilter={visibilityFilter}
            onClick={onFilterClick}>
            Completed
          </FilterLink>
        </p>

)

const getVisibleTodos = (todos, filter) => {
  switch(filter){
    case 'SHOW_ALL':
      return todos;
    case 'SHOW_COMPLETED':
      return todos.filter(t => t.completed);
    case 'SHOW_ACTIVE':
      return todos.filter(t => !t.completed);
    default:
      return todos;
  }
}

let nextTodoId = 0;
const TodoApp = ({
  todos,
  visibilityFilter
}) => {
  return (
  <div>
    <AddTodo
      onAddClick={
        text =>
          store.dispatch({
            type: 'ADD_TODO',
            text: this.input.value,
            id: nextTodoId++
           })
      }
    />
    <TodoList
      todos={
        getVisibleTodos(
               todos,
               visibilityFilter
        )
      }
      onTodoClick={id =>
        store.dispatch({
          type: 'TOGGLE_TODO',
          id
         })
      }
    />
    <Footer
      visibilityFilter={visibilityFilter}
      onFilterClick={filter =>
        store.dispatch({
          type: 'SET_VISIBILITY_FILTER',
          filter
        })
      }
    />
 </div>
 );
}

const render = () => {
  ReactDOM.render(
    // Render the TodoApp Component to the <div> with id 'root'
    <TodoApp
      {...store.getState()}
    />,
    document.getElementById('root')
  );
};

store.subscribe(render);
render();
</code>```

答:
Make sure you have added the correct ID in index.js
it should look like this.
document.getElementById('your div id from index.html should go here')</p>

Body:
I'm following egghead.io Redux course by Dan.
However I've no idea why my todo app is not working. It doesn't output any error and any warning, just doesn't work.

Can you please give me some hint.

This is my jsbin.
https://jsbin.com/cozecip/33/edit?js,output

const todo = (state, action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false
      };
    case 'TOGGLE_TODO':
      if (state.id !== action.id) {
        return state;
      }

      return {
        id: state.id,
        text: state.text,
        completed: !state.completed
      };
    default:
      return state;
  }
};

const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        todo(undefined, action)
      ];
    case 'TOGGLE_TODO':
      return state.map(t =>
        todo(t, action)
      );
    default:
      return state;
  }
};

const visibilityFilter = (state = 'SHOW_ALL', action) =>
{
  switch (action.type) {
    case 'SET_VISIBILITY_FILTER':
      return action.filter;
    default:
      return state;
  }
};

const { combineReducers } = Redux;

const todoApp = combineReducers({
  todos,
  visibilityFilter
});

const { createStore } = Redux;
const store = createStore(todoApp);

const { Component } = React;

const FilterLink = ({
    filter,
    currentFilter,
    children,
    onClick
}) => {
    if (filter === currentFilter){
      return {children}
    }

    return (
      {children}
    );
};

const Todo = ({
  onClick,
  completed,
  text
}) => (

    {text}

);

const TodoList = ({
  todos,
  onTodoClick
}) => (

    {todos.map(todo =>
      <Todo
        key={todo.id}
        {...todo}
        onClick={() => onTodoClick(todo.id)}
      />
    )}

)

const AddTodo = ({
  onAddClick
}) => {
  let input;

  return (

    <input ref={node => {
       input = node;
    }} />
    <button onClick={() => {
      onAddClick(input.value)
      input.value = '';
    }}>
    Add Todo
    </button>

  );
}

const Footer = ({
  visibilityFilter,
  onFilterClick
}) => (

          Show:
          {' '}
          <FilterLink
            filter='SHOW_ALL'
            currentFilter={visibilityFilter}
            onClick={onFilterClick}>
              All
          </FilterLink>
          {' '}
          <FilterLink
            filter='SHOW_ACTIVE'
            currentFilter={visibilityFilter}
            onClick={onFilterClick}>
            Active
          </FilterLink>
          {' '}
          <FilterLink
            filter='SHOW_COMPLETED'
            currentFilter={visibilityFilter}
            onClick={onFilterClick}>
            Completed
          </FilterLink>

)

const getVisibleTodos = (todos, filter) => {
  switch(filter){
    case 'SHOW_ALL':
      return todos;
    case 'SHOW_COMPLETED':
      return todos.filter(t => t.completed);
    case 'SHOW_ACTIVE':
      return todos.filter(t => !t.completed);
    default:
      return todos;
  }
}

let nextTodoId = 0;
const TodoApp = ({
  todos,
  visibilityFilter
}) => {
  return (

    <AddTodo
      onAddClick={
        text =>
          store.dispatch({
            type: 'ADD_TODO',
            text: this.input.value,
            id: nextTodoId++
           })
      }
    />
    <TodoList
      todos={
        getVisibleTodos(
               todos,
               visibilityFilter
        )
      }
      onTodoClick={id =>
        store.dispatch({
          type: 'TOGGLE_TODO',
          id
         })
      }
    />

        store.dispatch({
          type: 'SET_VISIBILITY_FILTER',
          filter
        })
      }
    />

 );
}

const render = () => {
  ReactDOM.render(
    // Render the TodoApp Component to the
 with id 'root'
    <TodoApp
      {...store.getState()}
    />,
    document.getElementById('root')
  );
};

store.subscribe(render);
render();


问:
Performance implications of handling CLOBs with Oracle JDBC using SetBigStringTryClob
I am in process of reviewing some old Java/JDBC code for CLOB-handling on oracle database. Existing code uses approach similar to the approach mentioned in this question.

I found an article that states:

Prior to Oracle JDBC 10g, to manipulate the CLOB data in JDBC, Oracle extension class oracle.sql.CLOB was used. But now, Oracle JDBC 10g has a few enhancements that simplifies the CLOB manipulation in JDBC applications. This enables handling of large data using some of the available standard APIs, instead of using the Oracle extension classes.

The article gives following information about the details of this enhancement:

By default, the method preparedStatement.setString() will allow processing of the strings up to 32765 bytes. In order to insert data greater than 32765 bytes, a newly introduced Connection property - SetBigStringTryClob can be set. This forces the preparedStatement.setString() to use another newly introduced method, OraclePreparedStatement.setStringForClob() instead.

However it warns:

... handling very large amounts of data this way may not be a wise; streaming the data is a better alternative.

But above is the only performance-related warning in that article.
My question is that if all of the CLOB access in my code is already being done through String objects, should I worry about any other potential performance problems that this change of approach might cause? In other words, my app is not using the benefit offered by streaming as it already always load the CLOBs in String objects so above warning can probably be ignored because we are not aiming at performance improvement at the moment. Are there any other performance-related issues that might arise because of switching to this technique?

答: How big are you talking about?  I regularly handle short audio files and web images in memory without any performance issues.  These are all kilobyte scale files.  I think if you run megabyte sizes then streaming would be better.  Using the streaming to a LOB is actually pretty easy now with the standardized stuff. </p>


问:
Scala: importing object in the same file with a different name
Lets say I have in the same file:

```<code>object x {
  case object z
}

object y {
  .. //want to internally refer to x.z as xxx.z
}
</code>```

In other words I need to rename an import of an object in the same file.

currently I resort to:

```<code>object y {
  import x
  val xxx=x
  .. //referring to x.z as xxx.z
}
</code>```

is there a better way of doing this? perhaps something along the lines of:

```<code>import .{x->xxx}
</code>```

答:
Yes, you can do it like this:

```<code>package packagename

object x {
    case object z
}

object y {
    import packagename.{x => xxx}
    xxx.z
}
</code>```

Note that you cannot import something that resides in the default package.

Body:
Lets say I have in the same file:

object x {
  case object z
}

object y {
  .. //want to internally refer to x.z as xxx.z
}

In other words I need to rename an import of an object in the same file.

currently I resort to:

object y {
  import x
  val xxx=x
  .. //referring to x.z as xxx.z
}

is there a better way of doing this? perhaps something along the lines of:

import .{x->xxx}

Body:
Yes, you can do it like this:

package packagename

object x {
    case object z
}

object y {
    import packagename.{x => xxx}
    xxx.z
}

Note that you cannot import something that resides in the default package.


问:
The client disconnected
I'm getting the following error in logs for WebAPI

System.Web.HttpException (0x800703E3): The client disconnected.    at
  System.Web.Hosting.IIS7WorkerRequest.EndRead(IAsyncResult asyncResult)
  at System.Web.HttpBufferlessInputStream.EndRead(IAsyncResult
  asyncResult)    at System.Threading.Tasks.TaskFactory
  1.FromAsyncTrimPromise 1.Complete(TInstance thisRef, Func 3 endMethod, IAsyncResult asyncResult, Boolean requiresSynchronization)
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at System.IO.StreamReader.d__97.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  System.IO.StreamReader.d__62.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at Microsoft.Owin.OwinRequest.d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.d__22.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at
  Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware
  1.d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---    at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)    at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)    at Web.API.Middleware.OwinMiddleware.d__1.MoveNext()
  in D:\UAT\Web.API\Middleware\OwinMiddleware.cs:line 49

How can I handle and ignore these exceptions by exception filter? Why this error occurs and how can I reproduce that? I wanna catch and ignore only The client disconnected but not all HttpException

I saw this similar question but how can I do that in exception filter?

答:
```<code>try
{
   // Open Connection
   // Do stuff
}
catch (HttpException  ex)
{
   // Log it?
   // Ignore it?
   // Do what you want with it?
}
finally
{
   // Close connection
}
</code>```

Title: The client disconnected


问:
Error when converting from Java to Kotlin. Error - org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'
I am converting my Android project from Java to Kotlin. I have done this process with 3 other projects already and successfully.

But this one a little large and has a complicated structure. I've converted some files to Kotlin and project compiles. But there are some files throws compile exception when I convert them to Kotlin.

Compile issue I'm facing appears in Debug and Release mode. Short is as following (Have listed all below)

```<code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
</code>```

What do you think, how can I solve the problem?

I think this is a bug in Android Studio.

I have tried. Has not any result:

Invalidate Caches/Restart

Build -> Clean Project

Update kotlin plugin, used the latest version of kotlin, google APIs.

My app build.gradle is:

```<code>buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 25
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        applicationId "package.id"
        versionCode 10
        versionName "2.5.0"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }

        debug {
            debuggable true
            minifyEnabled false
        }
    }
}

dependencies {
    compile project(':androidViewUtilslibrary')
    compile('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:answers:1.3.10@aar') {
        transitive = true;
    }
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.google.firebase:firebase-ads:10.2.0'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.google.firebase:firebase-analytics:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.facebook.android:facebook-android-sdk:4.18.0'
    compile 'com.mobapphome.library:mah-ads:2.2.0'
    compile 'com.mobapphome.library:mah-android-updater:1.1.7'
    compile 'com.mobapphome.library:mah-encryptor-lib:1.0.1'
    compile 'com.google.code.gson:gson:2.7'
    compile 'jp.wasabeef:blurry:2.1.1'
    compile project(':BaseGameUtils')

    //For testing
    // App's dependencies, including test
    androidTestCompile 'com.android.support:support-annotations:25.3.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:0.5'
    compile project(':libCommonNotations')
}

apply plugin: 'com.google.gms.google-services'
</code>```

Top level build.gradle:

```<code>common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = '1.1.3'
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        jcenter()
    }
}
</code>```

Error log I'm facing:

with option: --info  --stacktrace

```<code>Using kotlin incremental compilation e: Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath:
    class com.hummatli.view.MainActivity, unresolved supertypes: DlgGeneralListener

[KOTLIN] deleting /Volumes/Disk_2/projects/Project/app/build/tmp/kotlin-classes/debug on error
[KOTLIN] deleting /Volumes/Disk_2/projects/Project/app/build/tmp/kotlin-classes/debug on error
:app:compileDebugKotlin FAILED
:app:compileDebugKotlin (Thread[Daemon worker Thread 5,5,main]) completed. Took 0.61 secs.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
        at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:8)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.processCompilerExitCode(Tasks.kt:291)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:265)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:168)
        at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:147)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:163)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
        ... 70 more

BUILD FAILED

Total time: 3.431 secs
Stopped 0 worker daemon(s).
Received result Failure[value=org.gradle.initialization.ReportedException: org.gradle.internal.exceptions.LocationAwareException: Execution failed for task ':app:compileDebugKotlin'.] from daemon DaemonInfo{pid=896, address=[46c9a211-21e2-41b0-bb5e-0e1b5552400b port:50150, addresses:[/0:0:0:0:0:0:0:1, /127.0.0.1]], state=Idle, lastBusy=1499244624479, context=DefaultDaemonContext[uid=e2bdc700-5856-41ee-bb69-75c0a63ea675,javaHome=/Library/Java/JavaVirtualMachines/jdk_from_intteluj_for_sierra_problem/Contents/Home,daemonRegistryDir=/Users/ss/.gradle/daemon,pid=896,idleTimeout=10800000,daemonOpts=-XX:MaxPermSize=256m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=UTF-8,-Duser.country=US,-Duser.language=en,-Duser.variant]} (build should be done).
</code>```

答:
The class DlgGeneralListener is missing in your classpath.
Ensure that

The library (jar-file) containing this class is on the classpath

OR if the class is part of your project, that the classfile is contained

Body:
I am converting my Android project from Java to Kotlin. I have done this process with 3 other projects already and successfully.

But this one a little large and has a complicated structure. I've converted some files to Kotlin and project compiles. But there are some files throws compile exception when I convert them to Kotlin.

Compile issue I'm facing appears in Debug and Release mode. Short is as following (Have listed all below)

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details

What do you think, how can I solve the problem?

I think this is a bug in Android Studio.

I have tried. Has not any result:

Invalidate Caches/Restart

Build -> Clean Project

Update kotlin plugin, used the latest version of kotlin, google APIs.

My app build.gradle is:

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-android'

repositories {
    maven { url 'https://maven.fabric.io/public' }
}

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 25
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        applicationId "package.id"
        versionCode 10
        versionName "2.5.0"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }

        debug {
            debuggable true
            minifyEnabled false
        }
    }
}

dependencies {
    compile project(':androidViewUtilslibrary')
    compile('com.crashlytics.sdk.android:crashlytics:2.6.5@aar') {
        transitive = true;
    }
    compile('com.crashlytics.sdk.android:answers:1.3.10@aar') {
        transitive = true;
    }
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.google.firebase:firebase-ads:10.2.0'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.google.firebase:firebase-analytics:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.facebook.android:facebook-android-sdk:4.18.0'
    compile 'com.mobapphome.library:mah-ads:2.2.0'
    compile 'com.mobapphome.library:mah-android-updater:1.1.7'
    compile 'com.mobapphome.library:mah-encryptor-lib:1.0.1'
    compile 'com.google.code.gson:gson:2.7'
    compile 'jp.wasabeef:blurry:2.1.1'
    compile project(':BaseGameUtils')

    //For testing
    // App's dependencies, including test
    androidTestCompile 'com.android.support:support-annotations:25.3.1'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:0.5'
    compile project(':libCommonNotations')
}

apply plugin: 'com.google.gms.google-services'

Top level build.gradle:

common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = '1.1.3'
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
        classpath 'com.google.gms:google-services:3.0.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Error log I'm facing:

with option: --info  --stacktrace

Using kotlin incremental compilation e: Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath:
    class com.hummatli.view.MainActivity, unresolved supertypes: DlgGeneralListener

[KOTLIN] deleting /Volumes/Disk_2/projects/Project/app/build/tmp/kotlin-classes/debug on error
[KOTLIN] deleting /Volumes/Disk_2/projects/Project/app/build/tmp/kotlin-classes/debug on error
:app:compileDebugKotlin FAILED
:app:compileDebugKotlin (Thread[Daemon worker Thread 5,5,main]) completed. Took 0.61 secs.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details

* Try:
Run with --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileDebugKotlin'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:84)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:55)
        at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
        at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
        at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
        at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
        at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:236)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:61)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:228)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:215)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:77)
        at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:58)
        at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:32)
        at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:113)
        at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
        at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
        at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
        at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:196)
        at org.gradle.initialization.DefaultGradleLauncher$3.execute(DefaultGradleLauncher.java:193)
        at org.gradle.internal.Transformers$4.transform(Transformers.java:169)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:106)
        at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:56)
        at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:193)
        at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:119)
        at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:102)
        at org.gradle.launcher.exec.GradleBuildController.run(GradleBuildController.java:71)
        at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
        at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
        at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
        at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:49)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:44)
        at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:29)
        at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:47)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
        at org.gradle.util.Swapper.swap(Swapper.java:38)
        at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:60)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:72)
        at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
        at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
        at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
        at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
        at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
        at org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:8)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.processCompilerExitCode(Tasks.kt:291)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:265)
        at org.jetbrains.kotlin.gradle.tasks.KotlinCompile.callCompiler$kotlin_gradle_plugin(Tasks.kt:168)
        at org.jetbrains.kotlin.gradle.tasks.AbstractKotlinCompile.execute(Tasks.kt:147)
        at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:163)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
        at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:123)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:95)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:76)
        ... 70 more

BUILD FAILED

Total time: 3.431 secs
Stopped 0 worker daemon(s).
Received result Failure[value=org.gradle.initialization.ReportedException: org.gradle.internal.exceptions.LocationAwareException: Execution failed for task ':app:compileDebugKotlin'.] from daemon DaemonInfo{pid=896, address=[46c9a211-21e2-41b0-bb5e-0e1b5552400b port:50150, addresses:[/0:0:0:0:0:0:0:1, /127.0.0.1]], state=Idle, lastBusy=1499244624479, context=DefaultDaemonContext[uid=e2bdc700-5856-41ee-bb69-75c0a63ea675,javaHome=/Library/Java/JavaVirtualMachines/jdk_from_intteluj_for_sierra_problem/Contents/Home,daemonRegistryDir=/Users/ss/.gradle/daemon,pid=896,idleTimeout=10800000,daemonOpts=-XX:MaxPermSize=256m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=UTF-8,-Duser.country=US,-Duser.language=en,-Duser.variant]} (build should be done).


问:
underscorejs - Group objects by property and print them
I have this array:

```<code>var ty = [
    {
      "Language": "en-GB",
      "Section": "Sales",
      "ItemName": "Type",
      "Texts": "Having selected the account heading select the calculation ..."
    },
    {
      "Language": "en-GB",
      "Section": "Sales",
      "ItemName": "Try",
      "Texts": "This is not happenning tho ..."
    },
    {
      "Language": "en-GB",
      "Section": "Taxes",
      "ItemName": "Save",
      "Texts": "The Master Tax Table has been pre populated with the current UK, ..."
    }];
</code>```

and i need to group it in a way that according to the section it will contain all the properties that have the same section, like this:

```<code>[
    {section: 'Sales', ItemName: ['Type', 'Try'] Texts: ["Having selected the account heading select the calculation ...", "This is not happenning tho."]},

    {section: 'Taxes', ItemName: ['Type'] Texts: ['Having selected the account heading select the calculation.']}
]
</code>```

So When I print it it will print just the text of each section.

This is the code I have so far:

```<code>var log = function(contents) {
  if (_.isArray(contents)) {
    _.each(contents, function(e, i, l) {
      log(e);
      $('#result');
      $('#result').append('</br></br>');
    });
  } else {
    console.log(contents);
    $('#result').append(contents);
  }
};

var ty = [
{
  "Language": "en-GB",
  "Section": "Sales",
  "ItemName": "Type",
  "Texts": "Having selected the account heading select the calculation ..."
},
{
  "Language": "en-GB",
  "Section": "Sales",
  "ItemName": "Try",
  "Texts": "This is not happenning tho ..."
},
{
  "Language": "en-GB",
  "Section": "Taxes",
  "ItemName": "Save",
  "Texts": "The Master Tax Table has been pre populated with the current UK, ..."
}];
var out = [];
_.groupBy(ty.Section, function(item){
    section: item.Section
    _.each(ty, function(item) {
    var hold = {};
    hold.options = {};
    hold.options.section[item.ItemName] = {
        text: item.Texts,
    };
    out.push(hold)
    });
});
log(out);
</code>```

I have tried:

```<code>//More code above
_.each(ty, function(item) {
    iName: item.itemName;
    var hold = {};
    hold.options = {};
    hold.options.section.iName = {
        text: item.Texts,
    };
    out.push(hold)
</code>```

but still it won't print anything. in my dev tools it doesn't show anything.

any tips?

答:
You can do it without underscore:

var ty = [{Language:"en-GB",Section:"Sales",ItemName:"Type",Texts:"Having selected the account heading select the calculation ..."},{Language:"en-GB",Section:"Sales",ItemName:"Try",Texts:"This is not happenning tho ..."},{Language:"en-GB",Section:"Taxes",ItemName:"Save",Texts:"The Master Tax Table has been pre populated with the current UK, ..."}];

var sections = {};
ty.forEach(o => sections[o.Section] = (sections[o.Section] || []).concat(o));

var result = Object.keys(sections).map(k => ({
    section: k,
    ItemName: sections[k].map(s => s.ItemName),
    Texts: sections[k].map(s => s.Texts),
}));

console.log(result);```
</div>
</div>
</p>

<p>Or, using underscore:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var ty = [{Language:"en-GB",Section:"Sales",ItemName:"Type",Texts:"Having selected the account heading select the calculation ..."},{Language:"en-GB",Section:"Sales",ItemName:"Try",Texts:"This is not happenning tho ..."},{Language:"en-GB",Section:"Taxes",ItemName:"Save",Texts:"The Master Tax Table has been pre populated with the current UK, ..."}];

var result = _.chain(ty)
              .groupBy('Section')
              .map((group, k) => ({
                  section: k,
                  ItemName: _.pluck(group, 'ItemName'),
                  Texts: _.pluck(group, 'Texts'),
              }))
              .value();

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

```

Body:
I have this array:

var ty = [
    {
      "Language": "en-GB",
      "Section": "Sales",
      "ItemName": "Type",
      "Texts": "Having selected the account heading select the calculation ..."
    },
    {
      "Language": "en-GB",
      "Section": "Sales",
      "ItemName": "Try",
      "Texts": "This is not happenning tho ..."
    },
    {
      "Language": "en-GB",
      "Section": "Taxes",
      "ItemName": "Save",
      "Texts": "The Master Tax Table has been pre populated with the current UK, ..."
    }];

and i need to group it in a way that according to the section it will contain all the properties that have the same section, like this:

[
    {section: 'Sales', ItemName: ['Type', 'Try'] Texts: ["Having selected the account heading select the calculation ...", "This is not happenning tho."]},

    {section: 'Taxes', ItemName: ['Type'] Texts: ['Having selected the account heading select the calculation.']}
]

So When I print it it will print just the text of each section.

This is the code I have so far:

var log = function(contents) {
  if (_.isArray(contents)) {
    _.each(contents, function(e, i, l) {
      log(e);
      $('#result');
      $('#result').append('

');
    });
  } else {
    console.log(contents);
    $('#result').append(contents);
  }
};

var ty = [
{
  "Language": "en-GB",
  "Section": "Sales",
  "ItemName": "Type",
  "Texts": "Having selected the account heading select the calculation ..."
},
{
  "Language": "en-GB",
  "Section": "Sales",
  "ItemName": "Try",
  "Texts": "This is not happenning tho ..."
},
{
  "Language": "en-GB",
  "Section": "Taxes",
  "ItemName": "Save",
  "Texts": "The Master Tax Table has been pre populated with the current UK, ..."
}];
var out = [];
_.groupBy(ty.Section, function(item){
    section: item.Section
    _.each(ty, function(item) {
    var hold = {};
    hold.options = {};
    hold.options.section[item.ItemName] = {
        text: item.Texts,
    };
    out.push(hold)
    });
});
log(out);

I have tried:

//More code above
_.each(ty, function(item) {
    iName: item.itemName;
    var hold = {};
    hold.options = {};
    hold.options.section.iName = {
        text: item.Texts,
    };
    out.push(hold)

but still it won't print anything. in my dev tools it doesn't show anything.

any tips?

Body:
You can do it without underscore:

var ty = [{Language:"en-GB",Section:"Sales",ItemName:"Type",Texts:"Having selected the account heading select the calculation ..."},{Language:"en-GB",Section:"Sales",ItemName:"Try",Texts:"This is not happenning tho ..."},{Language:"en-GB",Section:"Taxes",ItemName:"Save",Texts:"The Master Tax Table has been pre populated with the current UK, ..."}];

var sections = {};
ty.forEach(o => sections[o.Section] = (sections[o.Section] || []).concat(o));

var result = Object.keys(sections).map(k => ({
    section: k,
    ItemName: sections[k].map(s => s.ItemName),
    Texts: sections[k].map(s => s.Texts),
}));

console.log(result);

Or, using underscore:

var ty = [{Language:"en-GB",Section:"Sales",ItemName:"Type",Texts:"Having selected the account heading select the calculation ..."},{Language:"en-GB",Section:"Sales",ItemName:"Try",Texts:"This is not happenning tho ..."},{Language:"en-GB",Section:"Taxes",ItemName:"Save",Texts:"The Master Tax Table has been pre populated with the current UK, ..."}];

var result = _.chain(ty)
              .groupBy('Section')
              .map((group, k) => ({
                  section: k,
                  ItemName: _.pluck(group, 'ItemName'),
                  Texts: _.pluck(group, 'Texts'),
              }))
              .value();

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>


问:
Interpolating a string in c#
I want to use string interpolation for the below:

```<code>payloadArgs = string.Format("{0}TrackingID: \"{1}\"", payload.ToString().Replace("\n", "; "), trackingId);
</code>```

I have tried

```<code>payloadArgs = $"{trackingId} TrackingId, \"{payload.ToString().Replace("\n", "; "), trackingId};
</code>```

but I am obviously getting it wrong as I am getting a compile error "Cannot implicitly convert a string to int" over the "trackingId" and a warning about "newline in constant"

What's the correct way to do this?

答:
You are close. You changed the order between the variables, you had trackingId as the first variable instead as the second. In addition, string interpolation doesn't receive parameters in the structure of (string, parameter, parameter), it get it inside the curly brackets

```<code>payloadArgs = $"{payload.ToString().Replace("\n", "; ")}TrackingID: \"{trackingId}\"";
</code>```

Title: Interpolating a string in c#

Body:
I want to use string interpolation for the below:

payloadArgs = string.Format("{0}TrackingID: \"{1}\"", payload.ToString().Replace("\n", "; "), trackingId);

I have tried

payloadArgs = $"{trackingId} TrackingId, \"{payload.ToString().Replace("\n", "; "), trackingId};

but I am obviously getting it wrong as I am getting a compile error "Cannot implicitly convert a string to int" over the "trackingId" and a warning about "newline in constant"

What's the correct way to do this?

Body:
You are close. You changed the order between the variables, you had trackingId as the first variable instead as the second. In addition, string interpolation doesn't receive parameters in the structure of (string, parameter, parameter), it get it inside the curly brackets

payloadArgs = $"{payload.ToString().Replace("\n", "; ")}TrackingID: \"{trackingId}\"";


问:
Email-based DCV Issue (multiple domains) - Amazon Certificate Manager (ACM)
Is there a way to validate domain control without using the email process? As I need to be able to add additional domains to the certificate for new clients...

The problem I'm facing is I can't add to the existing AWS certificate and have to create a new one with all the domains. When I do that everyone for every domain get's emailed and asked to confirm at:

```<code>administrator@domain.com
hostmaster@domain.com
admin@domain.com
postmaster@domain.com
webmaster@domain.com
</code>```

So I have had to register a seperate certificate and upload it to ACM instead which is not ideal. Mainly as it's limited to 99 domains and was hoping to automate the whole process.

Is this possible with AWS?

Thank you.

答:
Q: Are any other methods for validating a domain or approving a certificate supported?

Not at this time.

https://aws.amazon.com/certificate-manager/faqs/#provisioning

Having so many domains on one certificate isn't really a good practice, for other reasons, as well.

You're making your certificate physically longer and longer, wasting some amount of bandwidth, because the cert is sent to every connecting client, on every new connection.

Renewals will also be messy, if any of the domains on the cert are no longer pointing to your site, because auto-renewal requires that the issued cert be reachable on the Internet for each hostname.

ACM tries to automatically renew your Amazon-issued SSL/TLS certificates before they expire so that no action is required from you. To renew your certificate automatically, the following must be true:

ACM must be able to establish an HTTPS connection with each domain in the certificate.

For each connection, the certificate that is returned must match the one that ACM is renewing.

http://docs.aws.amazon.com/acm/latest/userguide/configure-domain-for-automatic-validation.html

One cleaner solution (the one I am using) is to provision each domain's cert individually, and attach each one to its own CloudFront distribution, pointing that to your origin server (which I assume in this context to be an ELB) and whitelisting all headers for forwarding to the origin, which bypasses caching and causes CloudFront to function as a simple but distributed reverse proxy.  Setting "compress objects automatically" in CloudFront may also save some bandwidth charges, and even with caching disabled, CloudFront should improve the responsiveness of your sites by keeping traffic on the AWS network for more of the path between origin and viewer.

Body:
Is there a way to validate domain control without using the email process? As I need to be able to add additional domains to the certificate for new clients...

The problem I'm facing is I can't add to the existing AWS certificate and have to create a new one with all the domains. When I do that everyone for every domain get's emailed and asked to confirm at:

administrator@domain.com
hostmaster@domain.com
admin@domain.com
postmaster@domain.com
webmaster@domain.com

So I have had to register a seperate certificate and upload it to ACM instead which is not ideal. Mainly as it's limited to 99 domains and was hoping to automate the whole process.

Is this possible with AWS?

Thank you.


问:
WPF: Problems with DataContext and ViewModel
I'm having a problem getting the content to display in my program, and I suspect I messed up something relating to the DataContext. The controls I am using come from an extension called Syncfusion (to display graphs) but it could be any other control displaying these items.

MainWindow.xaml.cs:

```<code>       public MainWindow()
    {
        InitializeComponent();
        ViewModel _viewModel = new ViewModel();
        DataContext = _viewModel;
    }
</code>```

ViewModel.cs

```<code>    public class ViewModel
{
    public ObservableCollection<TotalData> TotalDataColl { get; set; }

    public ViewModel()
    {
        TotalDataColl = new ObservableCollection<TotalData>();
        var vm = new ChartViewModel
        {
            Series = new ObservableCollection<SeriesViewModel>
            {
                new SeriesViewModel{type="Lemons", Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 25}, new ItemViewModel{source = "February", value = 35}}},
                new SeriesViewModel{type="Oranges",Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 22}, new ItemViewModel{source = "February", value = 36}}}
            }

        };
    }

}
</code>```

MainWindow.xaml

```<code>    <Grid>
    <local:ExtendedChart ItemsSource="{Binding Series}" Margin="0,-38,0,97">
        <local:ExtendedChart.ItemTemplate>
            <DataTemplate>
                <chart:ColumnSeries ItemsSource="{Binding Items}" DependentValuePath="value" IndependentValuePath="source" Title="{Binding type}" />
            </DataTemplate>
        </local:ExtendedChart.ItemTemplate>
    </local:ExtendedChart>
</Grid>
</code>```

DataClass.cs

```<code>public class ChartViewModel : ObservableObject
{
    private ObservableCollection<SeriesViewModel> _series;
    public ObservableCollection<SeriesViewModel> Series
    {
        get
        {
            return _series;
        }
        set
        {
            _series = value;
            OnPropertyChanged("Series");
        }
    }
}

public class SeriesViewModel : ObservableObject
{
    private ObservableCollection<ItemViewModel> items;
    private string _type;
    public string type { get { return _type; } set { _type = value; OnPropertyChanged("_type"); } }
    public ObservableCollection<ItemViewModel> Items { get { return items; } set { items = value; OnPropertyChanged("Items"); } }
}

public class ItemViewModel : ObservableObject
{
    private string _source;
    private double _value;
    public string Source { get { return _source;} set { _source = value; OnPropertyChanged("Source"); } }

    public double Value { get { return _value; } set { _value = value;OnPropertyChanged("Value"); } }
}
</code>```

答:
ViewModel

```<code>   public class ViewModel
   {
    public ObservableCollection<TotalData> TotalDataColl { get; set; }
    public ChartViewModel ChartSeriesViewModel { get; set; }
    public ViewModel()
    {
        TotalDataColl = new ObservableCollection<TotalData>();
        ChartSeriesViewModel = new ChartViewModel
        {
            Series = new ObservableCollection<SeriesViewModel>
            {
                new SeriesViewModel{type="Lemons", Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 25}, new ItemViewModel{source = "February", value = 35}}},
                new SeriesViewModel{type="Oranges",Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 22}, new ItemViewModel{source = "February", value = 36}}}
            }

        };
    }

}
</code>```

MainWindow.Xaml

```<code><Grid>
    <local:ExtendedChart ItemsSource="{Binding ChartSeriesViewModel.Series}" Margin="0,-38,0,97">
        <local:ExtendedChart.ItemTemplate>
            <DataTemplate>
                <chart:ColumnSeries ItemsSource="{Binding Items}" DependentValuePath="value" IndependentValuePath="source" Title="{Binding type}" />
            </DataTemplate>
        </local:ExtendedChart.ItemTemplate>
    </local:ExtendedChart>
</Grid>
</code>```

Body:
I'm having a problem getting the content to display in my program, and I suspect I messed up something relating to the DataContext. The controls I am using come from an extension called Syncfusion (to display graphs) but it could be any other control displaying these items.

MainWindow.xaml.cs:

       public MainWindow()
    {
        InitializeComponent();
        ViewModel _viewModel = new ViewModel();
        DataContext = _viewModel;
    }

ViewModel.cs

    public class ViewModel
{
    public ObservableCollection<TotalData> TotalDataColl { get; set; }

    public ViewModel()
    {
        TotalDataColl = new ObservableCollection<TotalData>();
        var vm = new ChartViewModel
        {
            Series = new ObservableCollection<SeriesViewModel>
            {
                new SeriesViewModel{type="Lemons", Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 25}, new ItemViewModel{source = "February", value = 35}}},
                new SeriesViewModel{type="Oranges",Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 22}, new ItemViewModel{source = "February", value = 36}}}
            }

        };
    }

}

MainWindow.xaml

    <Grid>
    <local:ExtendedChart ItemsSource="{Binding Series}" Margin="0,-38,0,97">
        <local:ExtendedChart.ItemTemplate>
            <DataTemplate>
                <chart:ColumnSeries ItemsSource="{Binding Items}" DependentValuePath="value" IndependentValuePath="source" Title="{Binding type}" />
            </DataTemplate>
        </local:ExtendedChart.ItemTemplate>
    </local:ExtendedChart>
</Grid>

DataClass.cs

public class ChartViewModel : ObservableObject
{
    private ObservableCollection<SeriesViewModel> _series;
    public ObservableCollection<SeriesViewModel> Series
    {
        get
        {
            return _series;
        }
        set
        {
            _series = value;
            OnPropertyChanged("Series");
        }
    }
}

public class SeriesViewModel : ObservableObject
{
    private ObservableCollection<ItemViewModel> items;
    private string _type;
    public string type { get { return _type; } set { _type = value; OnPropertyChanged("_type"); } }
    public ObservableCollection<ItemViewModel> Items { get { return items; } set { items = value; OnPropertyChanged("Items"); } }
}

public class ItemViewModel : ObservableObject
{
    private string _source;
    private double _value;
    public string Source { get { return _source;} set { _source = value; OnPropertyChanged("Source"); } }

    public double Value { get { return _value; } set { _value = value;OnPropertyChanged("Value"); } }
}

Body:
ViewModel

   public class ViewModel
   {
    public ObservableCollection<TotalData> TotalDataColl { get; set; }
    public ChartViewModel ChartSeriesViewModel { get; set; }
    public ViewModel()
    {
        TotalDataColl = new ObservableCollection<TotalData>();
        ChartSeriesViewModel = new ChartViewModel
        {
            Series = new ObservableCollection<SeriesViewModel>
            {
                new SeriesViewModel{type="Lemons", Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 25}, new ItemViewModel{source = "February", value = 35}}},
                new SeriesViewModel{type="Oranges",Items = new ObservableCollection<ItemViewModel>{new ItemViewModel{source = "January", value = 22}, new ItemViewModel{source = "February", value = 36}}}
            }

        };
    }

}

MainWindow.Xaml

<Grid>
    <local:ExtendedChart ItemsSource="{Binding ChartSeriesViewModel.Series}" Margin="0,-38,0,97">
        <local:ExtendedChart.ItemTemplate>
            <DataTemplate>
                <chart:ColumnSeries ItemsSource="{Binding Items}" DependentValuePath="value" IndependentValuePath="source" Title="{Binding type}" />
            </DataTemplate>
        </local:ExtendedChart.ItemTemplate>
    </local:ExtendedChart>
</Grid>


答:
I'm sorry to say, but the code you posted is totally unreasonable.

Instead of messing around with dynamic SQL you should simply change your table structure to contain only 2 columns - One for index and another for value:

```<code>CREATE TABLE aaa (
    id int identity(1, 1),
    val char(40)
)

INSERT INTO aaa VALUES
('aaaa'),
('qqqq'),
('eeee')

SELECT val
FROM aaa
WHERE Id = 3
</code>```

Title: SQL: columns name based on variable

Body:
I'm sorry to say, but the code you posted is totally unreasonable.

Instead of messing around with dynamic SQL you should simply change your table structure to contain only 2 columns - One for index and another for value:

CREATE TABLE aaa (
    id int identity(1, 1),
    val char(40)
)

INSERT INTO aaa VALUES
('aaaa'),
('qqqq'),
('eeee')

SELECT val
FROM aaa
WHERE Id = 3


问:
Cannot start Google Admob Campaign (status always a red triangle)
I have created an Google Admob campaign to advertize my Android app. Everything is ok when creating but after I click Done, the status of campain is always a red triangle, I have try many time with several settings but it was not OK.
Red triangle in status

About Ad Design, I use Text Ad, it seems not problem.
I have search on Google this problem but no answer for resolving it.

答:
Per admob documentation red triangle can mean the following (please see https://support.google.com/admob/answer/6177178?hl=en):

Inactive and there is a problem with the campaign that needs to be fixed.

Active but the campaign is behind schedule.

Also for house ads campaign type should be "Mediated house ad".

Note: it seems like it is important to have valid billing info in your AdWords account. If you dont have a valid card there your ads would not be served (also house ads which are free). To update this info go to Settings -> Billing. It will open approprite page in AdWords. Be sure to wait some time to take effect, for me it was overnight


问:
Symfony 3.3.3 - default controller and container
I downloaded last stable version of Symfony (3.3.3) and on start I have error:

```<code>Attempted to call an undefined method named "getParameter" of class "AppBundle\Controller\DefaultController".
</code>```

This is:

```<code>'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,
</code>```

Before 3.3.3 version Symfony controllers extended

Symfony\Bundle\FrameworkBundle\Controller\Controller.php

Now extends:

Symfony\Bundle\FrameworkBundle\Controller\AbstractController\AbstractController.php

So... How can I get data from container? In documentation (3.3 and 4.0 versions) Controller extends Controller, not AbstractController.

If I change AbstractController to Controller application works well, but do I should this change?

答: They have already reverted the change on the symfony standard edition so I would say that going back to Controller instead of AbstractController is the way to go.

Body:
I downloaded last stable version of Symfony (3.3.3) and on start I have error:

Attempted to call an undefined method named "getParameter" of class "AppBundle\Controller\DefaultController".

This is:

'base_dir' => realpath($this->getParameter('kernel.project_dir')).DIRECTORY_SEPARATOR,

Before 3.3.3 version Symfony controllers extended

Symfony\Bundle\FrameworkBundle\Controller\Controller.php

Now extends:

Symfony\Bundle\FrameworkBundle\Controller\AbstractController\AbstractController.php

So... How can I get data from container? In documentation (3.3 and 4.0 versions) Controller extends Controller, not AbstractController.

If I change AbstractController to Controller application works well, but do I should this change?


问:
How to query a bag with Nhibernate
I need to get publications which the country list doesn't contain a country (research on IsoCode2)

The sql query is :

```<code>select * from pub_head ph
where not exists
(select 1 from pub_head_forbidden_country phfc , country c
                where phfc.pub_head_id = ph.pub_head_id
                and phfc.country_id = c.country_id
                and c.iso_code2 = 'CA');
</code>```

And the model :

```<code><class name="Publication" table="PUB_HEAD">

  <id name="Id" column="PUB_HEAD_ID">
   <generator class="native">
    <param name="sequence">SEQ_PUB_HEAD</param>
   </generator>
  </id>

  <idbag name="Countries" table="PUB_HEAD_COUNTRY" lazy="true">
   <collection-id column="PUB_HEAD_COUNTRY_ID">
    <generator class="native">
     <param name="sequence">SEQ_PUB_HEAD_COUNTRY</param>
    </generator>
   </collection-id>

   <key column ="PUB_HEAD_ID"  />
   <many-to-many class="Model.Referential.Country, Model" column="COUNTRY_ID"/>
  </idbag>
</class>

<class name="Country" table="Country">
  <id name="Id" column="COUNTRY_ID">
   <generator class="native">
   </generator>
  </id>
  <property name="Name">
   <column name="NAME"></column>
  </property>
  <property name="IsoCode2">
   <column name="ISO_CODE2"></column>
  </property>
  <property name="IsoCode3">
   <column name="ISO_CODE3"></column>
  </property>

 </class>
</code>```

I began with SubQueries, but I didn't success to do it.

Thanks

答:
The Sql could be like this too</p>

```<code>SELECT * FROM pub_head ph
WHERE ph.pub_head_id not IN (
  SELECT phfc.pub_head_id
  FROM pub_head_forbidden_country phfc
    INNER JOIN country  c ON phfc.country_id = c.country_id
  WHERE c.iso_code2 = 'CA'
)
</code>```

Title: How to query a bag with Nhibernate

Body:
I need to get publications which the country list doesn't contain a country (research on IsoCode2)

The sql query is :

select * from pub_head ph
where not exists
(select 1 from pub_head_forbidden_country phfc , country c
                where phfc.pub_head_id = ph.pub_head_id
                and phfc.country_id = c.country_id
                and c.iso_code2 = 'CA');

And the model :

<class name="Publication" table="PUB_HEAD">

  <id name="Id" column="PUB_HEAD_ID">
   <generator class="native">
    <param name="sequence">SEQ_PUB_HEAD</param>
   </generator>
  </id>

  <idbag name="Countries" table="PUB_HEAD_COUNTRY" lazy="true">
   <collection-id column="PUB_HEAD_COUNTRY_ID">
    <generator class="native">
     <param name="sequence">SEQ_PUB_HEAD_COUNTRY</param>
    </generator>
   </collection-id>

   <key column ="PUB_HEAD_ID"  />
   <many-to-many class="Model.Referential.Country, Model" column="COUNTRY_ID"/>
  </idbag>
</class>

<class name="Country" table="Country">
  <id name="Id" column="COUNTRY_ID">
   <generator class="native">
   </generator>
  </id>
  <property name="Name">
   <column name="NAME"></column>
  </property>
  <property name="IsoCode2">
   <column name="ISO_CODE2"></column>
  </property>
  <property name="IsoCode3">
   <column name="ISO_CODE3"></column>
  </property>

 </class>

I began with SubQueries, but I didn't success to do it.

Thanks

Body:
The Sql could be like this too

SELECT * FROM pub_head ph
WHERE ph.pub_head_id not IN (
  SELECT phfc.pub_head_id
  FROM pub_head_forbidden_country phfc
    INNER JOIN country  c ON phfc.country_id = c.country_id
  WHERE c.iso_code2 = 'CA'
)


问:
Spring 4 application register as client to Eureka
I have a Spring 4 application (not Spring Boot) and I want it to register to Eureka service discovery.

Is there any way to do it? because all tutorials are tightly connected to Spring Boot.

答:
What I have done:

In the "webapp" module, I have created a class which implements InitalizingBean, and override the methods. In post construct method, I have just send POST request to Eureka, and register my application as a service.

My application is now registered as microservice in Eureka