问:
How do I pass Redux props to a separate component in a different Route with React Router v4?
I'm creating a real time chat app with react, react router v4 and redux. The problem is that, as you may know, react router v4 changes a lot of stuff and nesting routes is not working for me.

So I have this code with a nested route that is not working:

```<code><Route path='/' component={App}>
    <Route path="/user" component={AddUser}/>
</Route>
</code>```

It's giving me this error Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored.

Where component={App}, in the first <Route path='/' is a redux connect:

```<code>const App = connect(mapStateToProps, mapDispatchToProps)(Header)
</code>```

So my component App has all the the props I need. All works fine except by the fact that I need to pass those props from App to the nested route component AddUser.

How do I pass the redux props to a separate component in a different Route?

答:
With react-router v4 when we need nested routes, we don't nest Routes. Instead, we put them inside nested components. You can read about this more here: Nested routes with react router v4

In your case, you can put your "/user" route inside the App component and then use render instead of component. So you can pass your App props to AddUser as usual.

```<code><Route path='/' component={App}/>
</code>```

App.js

```<code>class App extends Component{
  //...
  render(){
    return(
      //....
      <Route path="/user"
        render={() => <AddUser myProp={this.props.myAppProp}/>}/>
      //....
    )
  }
}
</code>```

Body:
I'm creating a real time chat app with react, react router v4 and redux. The problem is that, as you may know, react router v4 changes a lot of stuff and nesting routes is not working for me.

So I have this code with a nested route that is not working:

<Route path='/' component={App}>
    <Route path="/user" component={AddUser}/>
</Route>

It's giving me this error Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored.

Where component={App}, in the first <Route path='/' is a redux connect:

const App = connect(mapStateToProps, mapDispatchToProps)(Header)

So my component App has all the the props I need. All works fine except by the fact that I need to pass those props from App to the nested route component AddUser.

How do I pass the redux props to a separate component in a different Route?

Body:
With react-router v4 when we need nested routes, we don't nest Routes. Instead, we put them inside nested components. You can read about this more here: Nested routes with react router v4

In your case, you can put your "/user" route inside the App component and then use render instead of component. So you can pass your App props to AddUser as usual.

<Route path='/' component={App}/>

App.js

class App extends Component{
  //...
  render(){
    return(
      //....
      <Route path="/user"
        render={() => <AddUser myProp={this.props.myAppProp}/>}/>
      //....
    )
  }
}


来源: stackexchange

问:
Sending 250ms UDP price ticks over socket connection from C++ to nodejs processes crashing, why?
Attempting to send UDP price ticks from a C++ "talker" process to a nodejs "listener" process, and I'm getting a crash.

Tick talking and listening is working for C++ to C++ processes. When I added the Nodejs piece listener, it blew up.

Any insight? Thx, Keith :^)

Tick Data Looks good:

```<code>Price unicasted: 49.58
Price unicasted: 50.00
Price unicasted: 50.24
Price unicasted: 50.09
Price unicasted: 49.81
</code>```

C++ Talker

```<code>#define SERVERPORT "4950"

int main(int argc, char *argv[])
{
    int sockfd;
    struct addrinfo hints, *servinfo;
    int rv;
    size_t numbytes;
    char* address = "192.168.1.100";

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_protocol = 0;

    if ((rv = getaddrinfo(address, SERVERPORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }
    sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);

    char myPrice[7];
    float f;
    while(1) {
        f = randPrice();
        ftoa(f, myPrice, 2); // Convert price to string
        myPrice[5] = '\n'; myPrice[6] = '\0';

        std::cout << "Price unicasted: " << myPrice;
        if ((numbytes = sendto(sockfd, myPrice, strlen(myPrice), 0, servinfo->ai_addr, servinfo->ai_addrlen)) == -1) {
            perror("talker: sendto");
            exit(1);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(250));
    }
    freeaddrinfo(servinfo);
    close(sockfd);

    return 0;
}
</code>```

Node.js Listener

```<code>var PORT = 4950;
var HOST = '192.168.1.100';

var dgram = require('dgram');
var server = dgram.createSocket('udp4');

server.on('listening', function () {
    var address = server.address();
    console.log('UDP Server listening on ' + address.address + ":" + address.port);
});

while(1) {
    server.on('message', function (message, remote) {
        console.log(remote.address + ':' + remote.port +' - ' + message);
    });
}

server.bind(PORT, HOST);
</code>```

Error Eek!

```<code>pickledEgg> node udp.listener.js
#
# Fatal error in , line 0
# API fatal error handler returned after process out of memory
#
==== C stack trace ===============================
#
# Fatal error in , line 0
# API fatal error handler returned after process out of memory
#
==== C stack trace ===============================
<--- Last few GCs --->

[14801:0x102806800]    13404 ms: Mark-sweep 1385.7 (1425.8) -> 1385.7 (1441.3) MB, 1099.6 / 0.0 ms  allocation failure scavenge might not succeed
[14801:0x102806800]    14533 ms: Mark-sweep 1400.7 (1441.3) -> 1400.7 (1441.8) MB, 1099.3 / 0.0 ms  allocation failure scavenge might not succeed
[14801:0x102806800]    15852 ms: Mark-sweep 1401.5 (1441.8) -> 1401.5 (1456.3) MB, 1317.5 / 0.0 ms  allocation failure scavenge might not succeed

<--- JS stacktrace --->
Cannot get stack trace in GC.
FATAL ERROR: MarkCompactCollector: semi-space copy, fallback in old gen Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/local/bin/node]
 2: node::FatalException(v8::Isolate*, v8::Local<v8::Value>, v8::Local<v8::Message>) [/usr/local/bin/node]
 3: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/local/bin/node]
 4: v8::internal::MarkCompactCollector::EvacuateNewSpaceVisitor::AllocateTargetObject(v8::internal::HeapObject*, v8::internal::HeapObject**) [/usr/local/bin/node]
 5: v8::internal::MarkCompactCollector::EvacuateNewSpaceVisitor::Visit(v8::internal::HeapObject*) [/usr/local/bin/node]
 6: v8::internal::MarkCompactCollector::Evacuator::EvacuatePage(v8::internal::Page*) [/usr/local/bin/node]
 7: v8::internal::PageParallelJob<v8::internal::EvacuationJobTraits>::Task::RunInternal() [/usr/local/bin/node]
 8: v8::internal::MarkCompactCollector::EvacuatePagesInParallel() [/usr/local/bin/node]
 9: v8::internal::MarkCompactCollector::EvacuateNewSpaceAndCandidates() [/usr/local/bin/node]
10: v8::internal::MarkCompactCollector::CollectGarbage() [/usr/local/bin/node]
11:     0   node                                0x0000000100bf1593 v8::base::debug::StackTrace::StackTrace() + 19
    1   node                                0x0000000100bee739 V8_Fatal + 233
    2   node                                0x0000000100143e48 v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) + 744
    3   node                                0x00000001005e03bb v8::internal::MarkCompactCollector::EvacuateNewSpaceVisitor::AllocateTargetObject(v8::internal::HeapObject*, v8::internal::HeapObject**) + 1019
    4   node                                0x00000001005df6be v8::internal::MarkCompactCollector::EvacuateNewSpaceVisitor::Visit(v8::internal::HeapObject*) + 318
    5   node                                0x00000001005eb8eb v8::internal::MarkCompactCollector::Evacuator::EvacuatePage(v8::internal::Page*) + 235
    6   node                                0x00000001005eb786 v8::internal::PageParallelJob<v8::internal::EvacuationJobTraits>::Task::RunInternal() + 198
    7   node                                0x0000000100b067d9 v8::platform::WorkerThread::Run() + 25
    8   node                                0x0000000100bf3187 v8::base::ThreadEntry(void*) + 87
    9   libsystem_pthread.dylib             0x00007fff9250bc13 _pthread_body + 131
    10  libsystem_pthread.dylib             0x00007fff9250bb90 _pthread_body + 0
    11  libsystem_pthread.dylib             0x00007fff92509375 thread_start + 13
Illegal instruction: 4
</code>```

EDIT 1: Subsequent Error

```<code>node udp.listener.js
events.js:182
  throw er; // Unhandled 'error' event
  ^

Error: bind EADDRINUSE 192.168.1.100:4950
    at Object.exports._errnoException (util.js:1026:11)
    at exports._exceptionWithHostPort (util.js:1049:20)
    at _handle.lookup (dgram.js:242:18)
    at _combinedTickCallback (internal/process/next_tick.js:105:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)
    at Function.Module.runMain (module.js:607:11)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3
</code>```

答: You seem to insert message event handlers in endless loop while(1) so you get out of memory error. Most likely you only need to set handler only once.

ContentLicense: CC BY-SA 3.0

Body:
Attempting to send UDP price ticks from a C++ "talker" process to a nodejs "listener" process, and I'm getting a crash.

Tick talking and listening is working for C++ to C++ processes. When I added the Nodejs piece listener, it blew up.

Any insight? Thx, Keith :^)

Tick Data Looks good:

Price unicasted: 49.58
Price unicasted: 50.00
Price unicasted: 50.24
Price unicasted: 50.09
Price unicasted: 49.81

C++ Talker

#define SERVERPORT "4950"

int main(int argc, char *argv[])
{
    int sockfd;
    struct addrinfo hints, *servinfo;
    int rv;
    size_t numbytes;
    char* address = "192.168.1.100";

    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_protocol = 0;

    if ((rv = getaddrinfo(address, SERVERPORT, &hints, &servinfo)) != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        return 1;
    }
    sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);

    char myPrice[7];
    float f;
    while(1) {
        f = randPrice();
        ftoa(f, myPrice, 2); // Convert price to string
        myPrice[5] = '\n'; myPrice[6] = '\0';

        std::cout << "Price unicasted: " << myPrice;
        if ((numbytes = sendto(sockfd, myPrice, strlen(myPrice), 0, servinfo->ai_addr, servinfo->ai_addrlen)) == -1) {
            perror("talker: sendto");
            exit(1);
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(250));
    }
    freeaddrinfo(servinfo);
    close(sockfd);

    return 0;
}

Node.js Listener

var PORT = 4950;
var HOST = '192.168.1.100';

var dgram = require('dgram');
var server = dgram.createSocket('udp4');

server.on('listening', function () {
    var address = server.address();
    console.log('UDP Server listening on ' + address.address + ":" + address.port);
});

while(1) {
    server.on('message', function (message, remote) {
        console.log(remote.address + ':' + remote.port +' - ' + message);
    });
}

server.bind(PORT, HOST);

Error Eek!

pickledEgg> node udp.listener.js
#
# Fatal error in , line 0
# API fatal error handler returned after process out of memory
#
==== C stack trace ===============================
#
# Fatal error in , line 0
# API fatal error handler returned after process out of memory
#
==== C stack trace ===============================
<--- Last few GCs --->

[14801:0x102806800]    13404 ms: Mark-sweep 1385.7 (1425.8) -> 1385.7 (1441.3) MB, 1099.6 / 0.0 ms  allocation failure scavenge might not succeed
[14801:0x102806800]    14533 ms: Mark-sweep 1400.7 (1441.3) -> 1400.7 (1441.8) MB, 1099.3 / 0.0 ms  allocation failure scavenge might not succeed
[14801:0x102806800]    15852 ms: Mark-sweep 1401.5 (1441.8) -> 1401.5 (1456.3) MB, 1317.5 / 0.0 ms  allocation failure scavenge might not succeed

<--- JS stacktrace --->
Cannot get stack trace in GC.
FATAL ERROR: MarkCompactCollector: semi-space copy, fallback in old gen Allocation failed - JavaScript heap out of memory
 1: node::Abort() [/usr/local/bin/node]
 2: node::FatalException(v8::Isolate*, v8::Local<v8::Value>, v8::Local<v8::Message>) [/usr/local/bin/node]
 3: v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) [/usr/local/bin/node]
 4: v8::internal::MarkCompactCollector::EvacuateNewSpaceVisitor::AllocateTargetObject(v8::internal::HeapObject*, v8::internal::HeapObject**) [/usr/local/bin/node]
 5: v8::internal::MarkCompactCollector::EvacuateNewSpaceVisitor::Visit(v8::internal::HeapObject*) [/usr/local/bin/node]
 6: v8::internal::MarkCompactCollector::Evacuator::EvacuatePage(v8::internal::Page*) [/usr/local/bin/node]
 7: v8::internal::PageParallelJob<v8::internal::EvacuationJobTraits>::Task::RunInternal() [/usr/local/bin/node]
 8: v8::internal::MarkCompactCollector::EvacuatePagesInParallel() [/usr/local/bin/node]
 9: v8::internal::MarkCompactCollector::EvacuateNewSpaceAndCandidates() [/usr/local/bin/node]
10: v8::internal::MarkCompactCollector::CollectGarbage() [/usr/local/bin/node]
11:     0   node                                0x0000000100bf1593 v8::base::debug::StackTrace::StackTrace() + 19
    1   node                                0x0000000100bee739 V8_Fatal + 233
    2   node                                0x0000000100143e48 v8::internal::V8::FatalProcessOutOfMemory(char const*, bool) + 744
    3   node                                0x00000001005e03bb v8::internal::MarkCompactCollector::EvacuateNewSpaceVisitor::AllocateTargetObject(v8::internal::HeapObject*, v8::internal::HeapObject**) + 1019
    4   node                                0x00000001005df6be v8::internal::MarkCompactCollector::EvacuateNewSpaceVisitor::Visit(v8::internal::HeapObject*) + 318
    5   node                                0x00000001005eb8eb v8::internal::MarkCompactCollector::Evacuator::EvacuatePage(v8::internal::Page*) + 235
    6   node                                0x00000001005eb786 v8::internal::PageParallelJob<v8::internal::EvacuationJobTraits>::Task::RunInternal() + 198
    7   node                                0x0000000100b067d9 v8::platform::WorkerThread::Run() + 25
    8   node                                0x0000000100bf3187 v8::base::ThreadEntry(void*) + 87
    9   libsystem_pthread.dylib             0x00007fff9250bc13 _pthread_body + 131
    10  libsystem_pthread.dylib             0x00007fff9250bb90 _pthread_body + 0
    11  libsystem_pthread.dylib             0x00007fff92509375 thread_start + 13
Illegal instruction: 4

EDIT 1: Subsequent Error

node udp.listener.js
events.js:182
  throw er; // Unhandled 'error' event
  ^

Error: bind EADDRINUSE 192.168.1.100:4950
    at Object.exports._errnoException (util.js:1026:11)
    at exports._exceptionWithHostPort (util.js:1049:20)
    at _handle.lookup (dgram.js:242:18)
    at _combinedTickCallback (internal/process/next_tick.js:105:11)
    at process._tickCallback (internal/process/next_tick.js:161:9)
    at Function.Module.runMain (module.js:607:11)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:575:3


问:
Hibernate 5.x migration suggestions script
I'm trying to convert my working (with Hibernate 4.x) script that suggests migrations from the actual database. This is convenient expecially when I want track changes and store them in sql script used from FlyWay.

This is my class:

```<code>public class SchemaGenerator {

private static Configuration cfg;
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost/test?tinyInt1isBit=false";
private static String username = "root";
private static String password = "password";

public SchemaGenerator(String packageName) throws Exception {
    cfg = new Configuration();
    cfg.setProperty("hibernate.hbm2ddl.auto", "update");
    cfg.setProperty("hibernate.connection.driver_class", driver);
    cfg.setProperty("hibernate.connection.url", url);
    cfg.setProperty("hibernate.connection.username", username);
    cfg.setProperty("hibernate.connection.password", password);
    cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

    Reflections reflections = new Reflections("com.test");
    Set<Class<? extends Object>> allClasses = reflections.getTypesAnnotatedWith(Entity.class);
    for (Class c : allClasses) {
        cfg.addAnnotatedClass(c);
    }

}

public static void validate() {
    SchemaValidator schemaValidator = new SchemaValidator(cfg);
    schemaValidator.validate();
}

public List<SchemaUpdateScript> createUpdateScript(DataSource dataSource, org.hibernate.dialect.Dialect dialect)
        throws SQLException {
    DatabaseMetadata meta = new DatabaseMetadata(dataSource.getConnection(), dialect, cfg);
    List<SchemaUpdateScript> createSQL = cfg.generateSchemaUpdateScriptList(dialect, meta);

    return createSQL;
}

/**
 * @param args
 */
public static void main(String[] args) throws Exception {
    SchemaGenerator gen = new SchemaGenerator("com.test");
    Driver driver = com.mysql.jdbc.Driver.class.newInstance();
    DataSource dataSource = new SimpleDriverDataSource(driver, url, username, password);

    List<SchemaUpdateScript> updateCommands = gen.createUpdateScript(dataSource,
            new org.hibernate.dialect.MySQL5Dialect());
    if (updateCommands.size() != 0)
        System.out.println("" + formatSqlSuggestionScript(updateCommands));
    else
        System.out.println("Already up to date");
}

private static String formatSqlSuggestionScript(List<SchemaUpdateScript> sqls) {
    StringBuilder builder = new StringBuilder("\n\n****update sql suggestion:***\n\n");
    for (SchemaUpdateScript str : sqls) {
        builder.append("\n" + str.getScript() + ";");
    }
    builder.append("\n\n");
    return builder.toString();
}
</code>```

}

I've some problems with schemaValidator.validate(); because now it expects Metadata and with cfg.generateSchemaUpdateScriptList(dialect, meta) that doesn't exist anymore.

Do you have some good hints to start with? Or maybe is there a better approach to do this now with Hibernate 5x?

答: You can instantiate org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl and use the SchemaValidator.

Body:
I'm trying to convert my working (with Hibernate 4.x) script that suggests migrations from the actual database. This is convenient expecially when I want track changes and store them in sql script used from FlyWay.

This is my class:

public class SchemaGenerator {

private static Configuration cfg;
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost/test?tinyInt1isBit=false";
private static String username = "root";
private static String password = "password";

public SchemaGenerator(String packageName) throws Exception {
    cfg = new Configuration();
    cfg.setProperty("hibernate.hbm2ddl.auto", "update");
    cfg.setProperty("hibernate.connection.driver_class", driver);
    cfg.setProperty("hibernate.connection.url", url);
    cfg.setProperty("hibernate.connection.username", username);
    cfg.setProperty("hibernate.connection.password", password);
    cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

    Reflections reflections = new Reflections("com.test");
    Set<Class<? extends Object>> allClasses = reflections.getTypesAnnotatedWith(Entity.class);
    for (Class c : allClasses) {
        cfg.addAnnotatedClass(c);
    }

}

public static void validate() {
    SchemaValidator schemaValidator = new SchemaValidator(cfg);
    schemaValidator.validate();
}

public List<SchemaUpdateScript> createUpdateScript(DataSource dataSource, org.hibernate.dialect.Dialect dialect)
        throws SQLException {
    DatabaseMetadata meta = new DatabaseMetadata(dataSource.getConnection(), dialect, cfg);
    List<SchemaUpdateScript> createSQL = cfg.generateSchemaUpdateScriptList(dialect, meta);

    return createSQL;
}

/**
 * @param args
 */
public static void main(String[] args) throws Exception {
    SchemaGenerator gen = new SchemaGenerator("com.test");
    Driver driver = com.mysql.jdbc.Driver.class.newInstance();
    DataSource dataSource = new SimpleDriverDataSource(driver, url, username, password);

    List<SchemaUpdateScript> updateCommands = gen.createUpdateScript(dataSource,
            new org.hibernate.dialect.MySQL5Dialect());
    if (updateCommands.size() != 0)
        System.out.println("" + formatSqlSuggestionScript(updateCommands));
    else
        System.out.println("Already up to date");
}

private static String formatSqlSuggestionScript(List<SchemaUpdateScript> sqls) {
    StringBuilder builder = new StringBuilder("\n\n****update sql suggestion:***\n\n");
    for (SchemaUpdateScript str : sqls) {
        builder.append("\n" + str.getScript() + ";");
    }
    builder.append("\n\n");
    return builder.toString();
}

}

I've some problems with schemaValidator.validate(); because now it expects Metadata and with cfg.generateSchemaUpdateScriptList(dialect, meta) that doesn't exist anymore.

Do you have some good hints to start with? Or maybe is there a better approach to do this now with Hibernate 5x?


问:
Reading values from Json file
I am trying to read an attribute from a Json file using this:
    d['text']['entities']['mention'][0]['screen_name']

Json File

```<code>{
    "text" : {
        "content" : "@narendramodi Did u even know the fare of metro has been increased by 65%",

        "entities" : {
            "user_mentions" : [ ],
            "mention" : [
                {
                    "indices" : [
                        0,
                        13
                    ],
                    "id_str" : "18839785",
                    "screen_name" : "narendramodi",
                    "name" : "Narendra Modi",
                    "id" : 18839785
                }
            ],
            "hashtags" : [ ],
        },

    }
}
</code>```

I am trying to load many json files in Neo4J Database using py2neo library.

While accesing    d['text']['entities']['mention'][0]['screen_name']
in one of the json file in which "mention" : [ ], mention field is empty it says

IndexError: list index out of range

Error is pretty obvious but how should I handle this?

答:
try this -</p>

```<code>   mentions = d.get('text',{}).get('entities',{}).get('mention' ,[])
   if len(mentions)>0:
        print(mentions[0].get('screen_name',None))
   else:
        print(None)
</code>```

Title: Reading values from Json file

Body:
I am trying to read an attribute from a Json file using this:
    d['text']['entities']['mention'][0]['screen_name']

Json File

{
    "text" : {
        "content" : "@narendramodi Did u even know the fare of metro has been increased by 65%",

        "entities" : {
            "user_mentions" : [ ],
            "mention" : [
                {
                    "indices" : [
                        0,
                        13
                    ],
                    "id_str" : "18839785",
                    "screen_name" : "narendramodi",
                    "name" : "Narendra Modi",
                    "id" : 18839785
                }
            ],
            "hashtags" : [ ],
        },

    }
}

I am trying to load many json files in Neo4J Database using py2neo library.

While accesing    d['text']['entities']['mention'][0]['screen_name']
in one of the json file in which "mention" : [ ], mention field is empty it says

IndexError: list index out of range

Error is pretty obvious but how should I handle this?

Body:
try this -

   mentions = d.get('text',{}).get('entities',{}).get('mention' ,[])
   if len(mentions)>0:
        print(mentions[0].get('screen_name',None))
   else:
        print(None)


问:
Unexpected Token error in ExpressJS hello work example
Was attempting to use Webtask.io as a middleware solution in my current application, but my problem is that I can't get the express.js hello world example to work. All I want is this express server to reply "Hello Grails" when hit with a GET request. My code:

Webtask:

```<code>var express    = require('express');
var Webtask    = require('webtask-tools');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

app.get('/', function (req, res) {
    res.send({greeting: 'Hello Grails!'})
});

module.exports = Webtask.fromExpress(app);
</code>```

The error that both postman and my Grails app receive is:

```<code>{
 "code": 400,
 "message": "Compilation failed: Unexpected token <",
 "error": "Unexpected token <",
 "stack": "SyntaxError: Unexpected token <\n
 at Object.exports.runInThisContext (vm.js:53:16)\n ... "
}
</code>```

The built-in runner for webtask returns "Hello Grails", but plain get requests from Postman and my application don't. What am I doing wrong?

答:
your code is working fine, replace your code by this and run

```<code>var express    = require('express');
var Webtask    = require('webtask-tools');`

var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.get('/', function (req, res) {
    res.send({greeting: 'Hello Grails!'})
});

module.exports = Webtask.fromExpress(app);

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})
</code>```

cheers...

Body:
Was attempting to use Webtask.io as a middleware solution in my current application, but my problem is that I can't get the express.js hello world example to work. All I want is this express server to reply "Hello Grails" when hit with a GET request. My code:

Webtask:

var express    = require('express');
var Webtask    = require('webtask-tools');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

app.get('/', function (req, res) {
    res.send({greeting: 'Hello Grails!'})
});

module.exports = Webtask.fromExpress(app);

The error that both postman and my Grails app receive is:

{
 "code": 400,
 "message": "Compilation failed: Unexpected token <",
 "error": "Unexpected token <",
 "stack": "SyntaxError: Unexpected token <\n
 at Object.exports.runInThisContext (vm.js:53:16)\n ... "
}

The built-in runner for webtask returns "Hello Grails", but plain get requests from Postman and my application don't. What am I doing wrong?

Body:
your code is working fine, replace your code by this and run

var express    = require('express');
var Webtask    = require('webtask-tools');`

var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.get('/', function (req, res) {
    res.send({greeting: 'Hello Grails!'})
});

module.exports = Webtask.fromExpress(app);

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

cheers...


问:
Mass delete Cloudwatch log groups using Boto3 - delete_log_group
I have a pretty lengthy list of cloudwatch log groups i need to delete....like close to a hundred. Since you have to delete them one at a time I thought a little python script could help me out but now im stuck.

here's my script so far...

```<code>import boto3
from botocore.exceptions import ClientError
import json

#Connect to AWS using default AWS credentials in awscli config
cwlogs = boto3.client('logs')

loglist = cwlogs.describe_log_groups(
    logGroupNamePrefix='/aws/lambda/staging-east1-'
)

#writes json output to file...
with open('loglist.json', 'w') as outfile:
    json.dump(loglist, outfile, ensure_ascii=False, indent=4,
sort_keys=True)

#Opens file and searches through to find given loggroup name
with open("loglist.json") as f:
    file_parsed = json.load(f)

for i in file_parsed['logGroups']:
    print i['logGroupName']

#   cwlogs.delete_log_group(
#       logGroupName='string'   <---here is where im stuck
#   )
</code>```

How do I take the value of 'logGroupName' in i and convert it to a string that the delete_log_group command can use and iterate through to delete all of my log groups I need to be gone?
I tried using json.loads and it errored out with the following...

Traceback (most recent call last):
File "CWLogCleaner.py", line 18, in
file_parsed = json.loads(f)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())

Or am I totally going about this the wrong way?

TIA

答:
Unless you specifically need to save the JSON responses to disk for some other purpose, perhaps you could simply use some variant of this code:</p>
```<code>import boto3

def delete_log_streams(prefix=None):
    """Delete CloudWatch Logs log streams with given prefix or all."""
    next_token = None
    logs = boto3.client('logs')

    if prefix:
        log_groups = logs.describe_log_groups(logGroupNamePrefix=prefix)
    else:
        log_groups = logs.describe_log_groups()

    for log_group in log_groups['logGroups']:
        log_group_name = log_group['logGroupName']
        print("Delete log group:", log_group_name)

        while True:
            if next_token:
                log_streams = logs.describe_log_streams(logGroupName=log_group_name,
                                                        nextToken=next_token)
            else:
                log_streams = logs.describe_log_streams(logGroupName=log_group_name)

            next_token = log_streams.get('nextToken', None)

            for stream in log_streams['logStreams']:
                log_stream_name = stream['logStreamName']
                print("Delete log stream:", log_stream_name)
                logs.delete_log_stream(logGroupName=log_group_name, logStreamName=log_stream_name)
                # delete_log_stream(log_group_name, log_stream_name, logs)

            if not next_token or len(log_streams['logStreams']) == 0:
                break
</code>```

Body:
I have a pretty lengthy list of cloudwatch log groups i need to delete....like close to a hundred. Since you have to delete them one at a time I thought a little python script could help me out but now im stuck.

here's my script so far...

import boto3
from botocore.exceptions import ClientError
import json

#Connect to AWS using default AWS credentials in awscli config
cwlogs = boto3.client('logs')

loglist = cwlogs.describe_log_groups(
    logGroupNamePrefix='/aws/lambda/staging-east1-'
)

#writes json output to file...
with open('loglist.json', 'w') as outfile:
    json.dump(loglist, outfile, ensure_ascii=False, indent=4,
sort_keys=True)

#Opens file and searches through to find given loggroup name
with open("loglist.json") as f:
    file_parsed = json.load(f)

for i in file_parsed['logGroups']:
    print i['logGroupName']

#   cwlogs.delete_log_group(
#       logGroupName='string'   <---here is where im stuck
#   )

How do I take the value of 'logGroupName' in i and convert it to a string that the delete_log_group command can use and iterate through to delete all of my log groups I need to be gone?
I tried using json.loads and it errored out with the following...

Traceback (most recent call last):
File "CWLogCleaner.py", line 18, in
file_parsed = json.loads(f)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())

Or am I totally going about this the wrong way?

TIA

Body:
Unless you specifically need to save the JSON responses to disk for some other purpose, perhaps you could simply use some variant of this code:

import boto3

def delete_log_streams(prefix=None):
    """Delete CloudWatch Logs log streams with given prefix or all."""
    next_token = None
    logs = boto3.client('logs')

    if prefix:
        log_groups = logs.describe_log_groups(logGroupNamePrefix=prefix)
    else:
        log_groups = logs.describe_log_groups()

    for log_group in log_groups['logGroups']:
        log_group_name = log_group['logGroupName']
        print("Delete log group:", log_group_name)

        while True:
            if next_token:
                log_streams = logs.describe_log_streams(logGroupName=log_group_name,
                                                        nextToken=next_token)
            else:
                log_streams = logs.describe_log_streams(logGroupName=log_group_name)

            next_token = log_streams.get('nextToken', None)

            for stream in log_streams['logStreams']:
                log_stream_name = stream['logStreamName']
                print("Delete log stream:", log_stream_name)
                logs.delete_log_stream(logGroupName=log_group_name, logStreamName=log_stream_name)
                # delete_log_stream(log_group_name, log_stream_name, logs)

            if not next_token or len(log_streams['logStreams']) == 0:
                break

ContentLicense: CC BY-SA 4.0


问:
Visual Studio 2010 Designer Bug: Unable to copy from obj\debug to bin\debug
Wondering if anyone has a solution to this 2010 bug.  I have a project that built fine in Visual Studio 2008 that wont build in 2010 because Visual Studio is holding on to the dll after the application is run ONLY if a designer window is open.   I created a really light weight project that shows this problem.  If you create an application then create a lib dll.  Put one form in the dll, open the form in design view and then run the application.  It will run fine, then close the app, go to the code view of the form in design view, and change the code ( I just renamed a single variable) then try to recompile you get the following:

Error 1 Unable to copy file "obj\Debug\customlib.dll" to "build\debug\customlib.dll". The process cannot access the file 'build\debug\Customlib.dll' because it is being used by another process.

If you run Process Explorer and search for the dll, the only process holding the dll is devenv.exe!!!

I have done a ton of searching on this problem and have found similar issues with older versions of Dev Studio where people were able to just add a pre-step to move the locked dll to another name (.locked) and build.  Well that works the first time, but the next time you run then edit you are locked out of both the current dll and the one you moved to .locked, so unless I am willing to add code to randomly generate a name for the locked dll, this wont work for me (I don't want my debug directory size to grow with files never getting deleted.)

I have only found one workaround and if you are in this same boat this is what I have to do to edit and run.  I make sure EVERY design view window is closed BEFORE I ever run my project in the debugger.  If you close all the open design view windows devenv.exe will not hold the dll.

Does anyone have a better solution to this problem?

答:
I have had the same problems for a long time and then suddenly they disappeared. I realized that the source of the problems was initializing code in the constructors of WCF services and WPF controls. After cleaning the constructors from any dependencies to other assemblies everything has been fine.

So my suggestion is: Clean your constructors.

In WPF it is possible that inserting:

```<code>if (DesignerProperties.GetIsInDesignMode(this)) return;
</code>```

or similar will have the same effect.

Body:
I have had the same problems for a long time and then suddenly they disappeared. I realized that the source of the problems was initializing code in the constructors of WCF services and WPF controls. After cleaning the constructors from any dependencies to other assemblies everything has been fine.

So my suggestion is: Clean your constructors.

In WPF it is possible that inserting:

if (DesignerProperties.GetIsInDesignMode(this)) return;

or similar will have the same effect.

ContentLicense: CC BY-SA 2.5


问:
Training and Testing data structure : Mallet Classifier
I am trying to use Mallet- Naive-Bayes classifier API. I have modeled the training set and Test set as follows

Training : [ID] [Label] [Data]

Testing:   [ID] [ ] [Data]

Below is the code which I have used:

```<code>    public static void main(String[] args) throws FileNotFoundException {
        classify();
        System.out.println("Finished");
    }

    public static void classify() throws FileNotFoundException{

        //prepare instance transformation pipeline
        ArrayList<Pipe> pipes = new ArrayList<Pipe>();
        pipes.add(new Target2Label());
        pipes.add(new CharSequence2TokenSequence());
        pipes.add(new TokenSequence2FeatureSequence());
        pipes.add(new FeatureSequence2FeatureVector());
        SerialPipes pipe = new SerialPipes(pipes);

        //prepare training instances
        InstanceList trainingInstanceList = new InstanceList(pipe);
        trainingInstanceList.addThruPipe(new CsvIterator(new FileReader("resources/training.csv"),  "(\\w+)\\s+(\\w+)\\s+(.*)",  3, 2, 1));  // (data, label, name) field indices ));

        //prepare test instances
        InstanceList testingInstanceList = new InstanceList(pipe);
        testingInstanceList.addThruPipe(new CsvIterator(new FileReader("resources/testing.csv"), "(\\w+)\\s+(\\w+)\\s+(.*)",  3, 2, 1));

        ClassifierTrainer trainer = new NaiveBayesTrainer();
        Classifier classifier = trainer.train(trainingInstanceList);

        for(Instance testInstance :testingInstanceList){
        Labeling labeling = (Labeling) classifier.classify(testInstance);
        Label l = labeling.getBestLabel();
        System.out.println(testInstance + " =  " +  l);
        }

        System.out.println("Accuracy: " + classifier.getAccuracy(testingInstanceList));

   }
}
</code>```

It somehow throws me an error as to Line 'x' does not match regex. I understand its a problem when importing the data. But, what is the actual format for representing training and testing set when using mallet.

答:
It's important to distinguish "Testing" from "Production". Testing implies that you actually know the label, you just want to see if the classifier can guess it correctly. If you don't have a label and want to predict the label, you can classify directly from text data. Here's the documentation from the Mallet website:

To apply a saved classifier to new unlabeled data, use Csv2Classify (for one-instance-per-line data) or Text2Classify (for one-instance-per-file data).

```<code>bin/mallet classify-file --input data --output - --classifier classifier
bin/mallet classify-dir --input datadir --output - --classifier classifier
</code>```

Using the above commands, classifications are written to standard output. Note that the input for these commands is a raw text file, not an imported Mallet file. This command is designed to be used in "production" mode, where labels are not available.

Body:
I am trying to use Mallet- Naive-Bayes classifier API. I have modeled the training set and Test set as follows

Training : [ID] [Label] [Data]

Testing:   [ID] [ ] [Data]

Below is the code which I have used:

    public static void main(String[] args) throws FileNotFoundException {
        classify();
        System.out.println("Finished");
    }

    public static void classify() throws FileNotFoundException{

        //prepare instance transformation pipeline
        ArrayList<Pipe> pipes = new ArrayList<Pipe>();
        pipes.add(new Target2Label());
        pipes.add(new CharSequence2TokenSequence());
        pipes.add(new TokenSequence2FeatureSequence());
        pipes.add(new FeatureSequence2FeatureVector());
        SerialPipes pipe = new SerialPipes(pipes);

        //prepare training instances
        InstanceList trainingInstanceList = new InstanceList(pipe);
        trainingInstanceList.addThruPipe(new CsvIterator(new FileReader("resources/training.csv"),  "(\\w+)\\s+(\\w+)\\s+(.*)",  3, 2, 1));  // (data, label, name) field indices ));

        //prepare test instances
        InstanceList testingInstanceList = new InstanceList(pipe);
        testingInstanceList.addThruPipe(new CsvIterator(new FileReader("resources/testing.csv"), "(\\w+)\\s+(\\w+)\\s+(.*)",  3, 2, 1));

        ClassifierTrainer trainer = new NaiveBayesTrainer();
        Classifier classifier = trainer.train(trainingInstanceList);

        for(Instance testInstance :testingInstanceList){
        Labeling labeling = (Labeling) classifier.classify(testInstance);
        Label l = labeling.getBestLabel();
        System.out.println(testInstance + " =  " +  l);
        }

        System.out.println("Accuracy: " + classifier.getAccuracy(testingInstanceList));

   }
}

It somehow throws me an error as to Line 'x' does not match regex. I understand its a problem when importing the data. But, what is the actual format for representing training and testing set when using mallet.

Body:
It's important to distinguish "Testing" from "Production". Testing implies that you actually know the label, you just want to see if the classifier can guess it correctly. If you don't have a label and want to predict the label, you can classify directly from text data. Here's the documentation from the Mallet website:

To apply a saved classifier to new unlabeled data, use Csv2Classify (for one-instance-per-line data) or Text2Classify (for one-instance-per-file data).

bin/mallet classify-file --input data --output - --classifier classifier
bin/mallet classify-dir --input datadir --output - --classifier classifier

Using the above commands, classifications are written to standard output. Note that the input for these commands is a raw text file, not an imported Mallet file. This command is designed to be used in "production" mode, where labels are not available.


问:
Create Visio Database Diagram from Excel Table and Field List
I have an Excel worksheet, which has the following columns:
Table Name
Field Name
Data Type

My goal is to import this into Visio, and have it generate the table shapes, for each table, filling them with each field/data type.

I can then draw the relationship lines and arrange everything.

I've seen posts here and on other sites, about importing Excel, but it seems to be the data, not the data plan.

Anyone know how to do this?  Please let me know if you need more info.

I'm using Office 2010.

Thank you!

答: I ended up creating a series of excel formulas, to generate CREATE TABLE statements.  I ran those in a scratch SQL database.  Now I'm using a new SQL diagram to map the relationships between the tables, then I will see if I can bring this into Visio.</p>


问:
Disable lightweight visual studio 2017
Any way to disable light weight load in visual studio 2017?
When I load the solution it has "Solution 'MySolutionName' (loading... - lightweight)". I don't want this feature because my intellesens won't work correctly.</p>

答: Right click on the solution in solution explorer and select 'Disable lightweight solution load'</p>

Title: Disable lightweight visual studio 2017


问:
Retrieve Values From List In Entity Framework
There are two different models in my project: Movie and Actor.  Movie has a list of actors and Actor has a list of movies.  What I want to do is given a movie, get all of the actors, and then for each actor examine their movies acted in.

So, to get the information, I use:

```<code>var movie = context.Movies.Include("Cast.ActingCredits").FirstOrDefault(m => m.Key == key);
</code>```

The problem is that while the list ActingCredits is not null, there are no values in it.  Is there something that I am missing to load the values in the list?  ActingCredits is an ICollection<Movie>.

```<code> public class Actor : ModelBase
 {
     public ICollection<Movie> ActingCredits { get; set; }
 }

public class Movie : ModelBase
{
    public string Title { get; set; }
    public DateTime Year { get; set; }
    public Genre Genre { get; set; }
    public int RunTime { get; set; }
    public int Sales { get; set; }
    public ICollection<Actor> Cast { get; set; }
}
</code>```

EDIT: It has come to my attention that this may be wrong and is the cause of the issue.

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany();
        modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany();
    }
</code>```

答:
You are not typing the correct name of the property in the include.
Try this:

```<code>    var movie = context.Movies.Include("Cast").FirstOrDefault(m => m.Key == key);
</code>```

Also, make sure that your database is populated before executing this. I tested this and it works, it retrieves everything.

Body:
There are two different models in my project: Movie and Actor.  Movie has a list of actors and Actor has a list of movies.  What I want to do is given a movie, get all of the actors, and then for each actor examine their movies acted in.

So, to get the information, I use:

var movie = context.Movies.Include("Cast.ActingCredits").FirstOrDefault(m => m.Key == key);

The problem is that while the list ActingCredits is not null, there are no values in it.  Is there something that I am missing to load the values in the list?  ActingCredits is an ICollection<Movie>.

 public class Actor : ModelBase
 {
     public ICollection<Movie> ActingCredits { get; set; }
 }

public class Movie : ModelBase
{
    public string Title { get; set; }
    public DateTime Year { get; set; }
    public Genre Genre { get; set; }
    public int RunTime { get; set; }
    public int Sales { get; set; }
    public ICollection<Actor> Cast { get; set; }
}

EDIT: It has come to my attention that this may be wrong and is the cause of the issue.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Movie>().HasMany(p => p.Cast).WithMany();
        modelBuilder.Entity<Actor>().HasMany(m => m.ActingCredits).WithMany();
    }

Body:
You are not typing the correct name of the property in the include.
Try this:

    var movie = context.Movies.Include("Cast").FirstOrDefault(m => m.Key == key);

Also, make sure that your database is populated before executing this. I tested this and it works, it retrieves everything.


问:
Reading floats from binary file javascript
I'm trying to read floats in javascript from a binary file that is created using Java.

The file is created in Java using DataOutputStream:

```<code>DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
dos.writeFloat(-222);
dos.writeFloat(222000);
dos.writeFloat(130.329f);
dos.flush();
dos.close();
</code>```

The file is retreived by http request and read like this:

```<code>var client = new XMLHttpRequest();
client.addEventListener("load", dataLoaded);
client.open("GET", "/ajax-requests.php?data=true", true);
client.responseType = "arraybuffer";
client.send();
</code>```

dataLoaded function:

```<code>function dataLoaded () {
    console.log("Float32Array: " + new Float32Array(this.response));
}
</code>```

Output:

```<code>Float32Array: 3.3994099446055737e-41,1.8766110561523948e-38,0.00020218738063704222
</code>```

Expecting:

```<code>Float32Array: -222,222000,130.329
</code>```

The file is sent with php:

```<code>if(isset($_GET['data'])) {
  $file_path = "data/filename.ext";

  if (file_exists($file_path)) {
    if(false !== ($handler = fopen($file_path, 'r'))) {
        header("Content-Type: application/octet-stream");
        header("Content-Length: " . filesize($file_path));

        readfile($file_path);
    }
    exit;
  }
  echo "<h1>Content error</h1><p>The file does not exist!</p>";
}
</code>```

It seems that somewhere there is a flaw in the conversion but I can't figure out where.

UPDATE:

The problem was just as Sean Van Gorder stated, a difference in endianness. To work around this I used DataView to read the arrayBuffer (since the file will be read both in java and in javascript this was the best sulotion)

```<code>var dataView = new DataView(arrayBuffer);
console.log("dataView: " + dataView.getFloat32(0, false));
console.log("dataView: " + dataView.getFloat32(4, false));
console.log("dataView: " + dataView.getFloat32(8, false));
</code>```

Output:

```<code>dataView: -222
dataView: 222000
dataView: 130.32899475097656
</code>```

答: You've got a byte order mismatch. DataOutputStream writes in big-endian, but Float32Array usually reads in little-endian (depending on hardware). You'll have to change the Java side or the Javascript side to match.</p>

Body:
I'm trying to read floats in javascript from a binary file that is created using Java.

The file is created in Java using DataOutputStream:

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
dos.writeFloat(-222);
dos.writeFloat(222000);
dos.writeFloat(130.329f);
dos.flush();
dos.close();

The file is retreived by http request and read like this:

var client = new XMLHttpRequest();
client.addEventListener("load", dataLoaded);
client.open("GET", "/ajax-requests.php?data=true", true);
client.responseType = "arraybuffer";
client.send();

dataLoaded function:

function dataLoaded () {
    console.log("Float32Array: " + new Float32Array(this.response));
}

Output:

Float32Array: 3.3994099446055737e-41,1.8766110561523948e-38,0.00020218738063704222

Expecting:

Float32Array: -222,222000,130.329

The file is sent with php:

if(isset($_GET['data'])) {
  $file_path = "data/filename.ext";

  if (file_exists($file_path)) {
    if(false !== ($handler = fopen($file_path, 'r'))) {
        header("Content-Type: application/octet-stream");
        header("Content-Length: " . filesize($file_path));

        readfile($file_path);
    }
    exit;
  }
  echo "
Content error

The file does not exist!
";
}

It seems that somewhere there is a flaw in the conversion but I can't figure out where.

UPDATE:

The problem was just as Sean Van Gorder stated, a difference in endianness. To work around this I used DataView to read the arrayBuffer (since the file will be read both in java and in javascript this was the best sulotion)

var dataView = new DataView(arrayBuffer);
console.log("dataView: " + dataView.getFloat32(0, false));
console.log("dataView: " + dataView.getFloat32(4, false));
console.log("dataView: " + dataView.getFloat32(8, false));

Output:

dataView: -222
dataView: 222000
dataView: 130.32899475097656


问:
how can I convert string into HTML. I want the actual href to show/display instead of the text
how can I convert string into HTML. I want the actual href to show/display instead of the text. </p>

```<code>    var zzz = "test";
    var value0 = 14251876;
    var value1 = "AAAA";

    var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
    var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
    EmailBody = EmailBody + $($.parseHTML('<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>'));
    send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);
</code>```

答:
Use this method of jquery

```<code>string a = '<div id="send"></div>';
var html = $(a);
</code>```

I guess This will Work and HTML will be parsed.

Body:
how can I convert string into HTML. I want the actual href to show/display instead of the text.

    var zzz = "test";
    var value0 = 14251876;
    var value1 = "AAAA";

    var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
    var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
    EmailBody = EmailBody + $($.parseHTML('
' + value0 + '
'));
    send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);

Body:
Use this method of jquery

string a = '<div id="send"></div>';
var html = $(a);

I guess This will Work and HTML will be parsed.


问:
Python: Resetting A Matplotlib From An Ipywidget Button
When using iPyWidgets and Matplotlib in a Jupyter notebook, it is fairly easy to get a live-updating figure, even with multiple subplots, and multiple variables with multiple sliders.  Simply set an interact to contain the activated plot function, and constructors for two slider variables:

```<code>%pylab inline
from ipywidgets import *
from IPython.display import display
import numpy as np
import matplotlib

t = np.arange(0.0, 4*pi, 0.01)

def pltsin(f1, f2):
    ax11 = plt.subplot(121)
    ax11.set_title('Plot 1')
    ax11.plot(t, sin(2*pi*t*f1/4/pi), 'k'); ax11.grid(True)
    ax11.plot(t, cos(2*pi*t*f1/4/pi), 'r'); ax11.grid(True)

    ax12 = plt.subplot(122)
    ax12.set_title('Plot 2')
    ax12.plot(t, sin(2*pi*t*f2/4/pi), 'k'); ax12.grid(True)
    ax12.plot(t, cos(2*pi*t*f2/4/pi), 'r'); ax11.grid(True)

    plt.show()

interact(pltsin, f1 = (1, 2, 0.01), f2 = (1, 2, 0.01))
</code>```

This could easily be extended to a plot where (say) three sliders control three polynomial coefficients all in a single window (i.e., no subplots).

But, it would be highly useful to have a reset button, which returns all variables to their default condition.  How can I cause an ipywidget button's on_click method to affect the variables of the slider, and the figure itself?

答:
This can be done by leveraging the interactive function.

```<code>%pylab inline
from ipywidgets import widgets
from IPython.display import display
import numpy as np
import matplotlib

t = np.arange(0.0, 4*pi, 0.01)

def pltsin(f1, f2):
    ax11 = plt.subplot(121)
    ax11.set_title('Plot 1')
    ax11.plot(t, sin(2*pi*t*f1/4/pi), 'k'); ax11.grid(True)
    ax11.plot(t, cos(2*pi*t*f1/4/pi), 'r'); ax11.grid(True)

    ax12 = plt.subplot(122)
    ax12.set_title('Plot 2')
    ax12.plot(t, sin(2*pi*t*f2/4/pi), 'k'); ax12.grid(True)
    ax12.plot(t, cos(2*pi*t*f2/4/pi), 'r'); ax11.grid(True)

    plt.show()

def reset_values(b):
    """Reset the interactive plots to inital values."""
    my_plts.children[0].value = 1
    my_plts.children[1].value = 1

reset_button = widgets.Button(description = "Reset")
reset_button.on_click(reset_values)

my_plts = widgets.interactive(pltsin, f1 = (1, 2, 0.01), f2 = (1, 2, 0.01))
display(my_plts, reset_button)
</code>```

Can't stand hard-coded variables? Then replace the reset_values function with this more elastic version:

```<code>def reset_values(b):
    """Reset the interactive plots to inital values."""

    my_plts.children[0].value = my_plts.children[0].min
    my_plts.children[1].value = my_plts.children[1].min
</code>```

Hope that helps.

Body:
When using iPyWidgets and Matplotlib in a Jupyter notebook, it is fairly easy to get a live-updating figure, even with multiple subplots, and multiple variables with multiple sliders.  Simply set an interact to contain the activated plot function, and constructors for two slider variables:

%pylab inline
from ipywidgets import *
from IPython.display import display
import numpy as np
import matplotlib

t = np.arange(0.0, 4*pi, 0.01)

def pltsin(f1, f2):
    ax11 = plt.subplot(121)
    ax11.set_title('Plot 1')
    ax11.plot(t, sin(2*pi*t*f1/4/pi), 'k'); ax11.grid(True)
    ax11.plot(t, cos(2*pi*t*f1/4/pi), 'r'); ax11.grid(True)

    ax12 = plt.subplot(122)
    ax12.set_title('Plot 2')
    ax12.plot(t, sin(2*pi*t*f2/4/pi), 'k'); ax12.grid(True)
    ax12.plot(t, cos(2*pi*t*f2/4/pi), 'r'); ax11.grid(True)

    plt.show()

interact(pltsin, f1 = (1, 2, 0.01), f2 = (1, 2, 0.01))

This could easily be extended to a plot where (say) three sliders control three polynomial coefficients all in a single window (i.e., no subplots).

But, it would be highly useful to have a reset button, which returns all variables to their default condition.  How can I cause an ipywidget button's on_click method to affect the variables of the slider, and the figure itself?

Body:
This can be done by leveraging the interactive function.

%pylab inline
from ipywidgets import widgets
from IPython.display import display
import numpy as np
import matplotlib

t = np.arange(0.0, 4*pi, 0.01)

def pltsin(f1, f2):
    ax11 = plt.subplot(121)
    ax11.set_title('Plot 1')
    ax11.plot(t, sin(2*pi*t*f1/4/pi), 'k'); ax11.grid(True)
    ax11.plot(t, cos(2*pi*t*f1/4/pi), 'r'); ax11.grid(True)

    ax12 = plt.subplot(122)
    ax12.set_title('Plot 2')
    ax12.plot(t, sin(2*pi*t*f2/4/pi), 'k'); ax12.grid(True)
    ax12.plot(t, cos(2*pi*t*f2/4/pi), 'r'); ax11.grid(True)

    plt.show()

def reset_values(b):
    """Reset the interactive plots to inital values."""
    my_plts.children[0].value = 1
    my_plts.children[1].value = 1

reset_button = widgets.Button(description = "Reset")
reset_button.on_click(reset_values)

my_plts = widgets.interactive(pltsin, f1 = (1, 2, 0.01), f2 = (1, 2, 0.01))
display(my_plts, reset_button)

Can't stand hard-coded variables? Then replace the reset_values function with this more elastic version:

def reset_values(b):
    """Reset the interactive plots to inital values."""

    my_plts.children[0].value = my_plts.children[0].min
    my_plts.children[1].value = my_plts.children[1].min

Hope that helps.


问:
undefined method `rebuild' for #<BottleSpecification:0x00000000e9fdb8>
I have installed LinuxBrew in Ubuntu. After that on running the following command-

```<code>   brew install rbenv ruby-build
</code>```

I get the following error:

```<code>   Error: undefined method `rebuild' for #<BottleSpecification:0x00000000e9fdb8>
</code>```

How do you resolve this?Please help.

答:
Try updating brew first and then installing rbenv followed by ruby-build:

```<code>$ brew update
$ brew install rbenv
$ brew install ruby-build
</code>```

Body:
I have installed LinuxBrew in Ubuntu. After that on running the following command-

   brew install rbenv ruby-build

I get the following error:

   Error: undefined method `rebuild' for #<BottleSpecification:0x00000000e9fdb8>

How do you resolve this?Please help.

Body:
Try updating brew first and then installing rbenv followed by ruby-build:

$ brew update
$ brew install rbenv
$ brew install ruby-build


问:
Submit jobs to Apache-Spark while being behind a firewall
Usecase:
I'm behind a firewall, and I have a remote spark cluster I can access to, however those machines cannot connect directly to me.

As Spark doc states it is necessary for the worker to be able to reach the driver program:

Because the driver schedules tasks on the cluster, it should be run
  close to the worker nodes, preferably on the same local area network.
  If you’d like to send requests to the cluster remotely, it’s better to
  open an RPC to the driver and have it submit operations from nearby
  than to run a driver far away from the worker nodes.

The suggested solution is to have a server process running on the cluster listening to RPC and let it execute itself the spark driver program locally.

Does such a program already exists? Such a process should manage 1+ RPC, returning exceptions and handling logs.

Also in that case, is my local program or the spark driver who has to create the SparkContext?

Note:
I have a standalone cluster

Solution1:

A simple way would be to use cluster mode (similar to --deploy-mode cluster) for the standalone cluster, however the doc says:

Currently, standalone mode does not support cluster mode for Python
  applications.

答:
Just a few options:

Connect to the cluster node using ssh, start screen, submit Spark application, go back to check the results.

Deploy middleware like Job Server, Livy or Mist on your cluster, and use it for submissions.

Deploy notebook (Zeppelin, Toree) on your cluster and submit applications from the notebook.

Set fixed spark.driver.port and ssh forward all connections through one of the cluster nodes, using its IP as spark.driver.bindAddress.


问:
Check if date and time is free
so I'm trying to solve out how to check if selected time is free. As example I have record in database:

```<code>date_from: 2017-06-05
date_till: 2017-07-05
Time_showed: 17:00 - 17:05
</code>```

Time showed means that video begins to play at 17:00 and ends at 17:05.
So now new order is incoming:

```<code>date_from: 2017-06-12
date_till: 2017-09-05
Time_showed: 17:02 - 17:06
</code>```

So as we see time between 17:02 and 17:06 is taken (17:03-17:05). Any Ideas how to check it with sql and php, so that in this situation it would return an error "Time is taken" ?

And Yeah stackoverflow wasn't the first place wjere I came to ask. Before that I tried to google a lot and solve it on my own... Seems like I'm not tough enough to solve it, lol.

答:
Ok, I can kind of see why you would need the data designed this way but it may be worth your time to see if it could be designed differently.
However, you came for help so that is what we all should be doing instead of making judgement. We have all worked on DBs that have not been designed in the best way and had to live with it for whatever reason. (Stepping off my soap box..)

So I think you may want to put this as a stored proc that you pass in the dates and the show time and return a true false.
The conditions you need to check for are:
    Is this during existing hold date period AND --Will assume this period can be null
    Is this during existing hold time. -- will assume this has to be inputted. If all day would have a time like 00:00 - 24:59

I came up with the below script:

```<code>IF EXISTS (SELECT * FROM sys.tables where tables.name like  '#myTable%')
begin
    drop table #myTable
end;

CREATE TABLE #myTable
(
    date_from date NULL,
    date_till date NULL,
    Time_showed varchar(20)
);

INSERT INTO #myTable
VALUES
    ('2017-06-05', '2017-07-05', '17:00 - 17:05'),
    ('2017-06-05', '2017-06-05', '08:00 - 08:05');

--test data
DECLARE
    @test_from date,
    @test_till as date,
    @test_time_showed as varchar(20);
--SELECT
--  @test_from = '2017-06-12',
--  @test_till = '2017-07-05',
--  @test_time_showed = '17:02 - 17:06';--1
SELECT
    @test_from = '2017-06-05',
    @test_till = '2017-06-05',
    @test_time_showed = '08:00 - 08:00';--0
--SELECT
--  @test_from = '2017-06-05',
--  @test_till = '2017-06-05',
--  @test_time_showed = '07:59 - 08:00';--0
--SELECT
--  @test_from = '2017-06-12',
--  @test_till = '2017-07-05',
--  @test_time_showed = '17:07 - 17:16';--0

--SPLIT
DECLARE @start_time time = CONVERT(TIME,RTRIM(SUBSTRING(@test_time_showed,0,CHARINDEX('-',@test_time_showed))));--you should turn this into a function (GetStartTime)
DECLARE @end_time time = CONVERT(TIME,LTRIM(SUBSTRING(@test_time_showed,CHARINDEX('-',@test_time_showed) + 1,len(@test_time_showed))));--you should turn this into a function (GetEndTime)

----checking values CAN BE DELETED
--SELECT @start_time,@end_time;

--SELECT  date_from, date_till,
--  CONVERT(TIME,RTRIM(SUBSTRING(Time_showed,0,CHARINDEX('-',Time_showed)))) AS START_T,
--  CONVERT(TIME,LTRIM(SUBSTRING(Time_showed,CHARINDEX('-',Time_showed) + 1,len(Time_showed)))) AS END_T
--FROM #MYTABLE

--VALIDATION
--TODO: You need to add some validation to insure that you are getting the correct data.

--CHECK
    -- IS
SELECT CASE
        WHEN EXISTS ( SELECT date_from
                        FROM #myTable
                        WHERE
                            --check if any records on file is for any date in span
                            ((date_from BETWEEN @test_from AND @test_till) OR
                            (date_till BETWEEN @test_from AND @test_till) ) AND
                            --if a record is for any date in span, check if times overlap (THE NASTY STUFF)
                            (
                                @start_time > CONVERT(TIME,RTRIM(SUBSTRING(Time_showed,0,CHARINDEX('-',Time_showed))))--you should turn this into a function (GetStartTime)
                                AND
                                @start_time < CONVERT(TIME,LTRIM(SUBSTRING(Time_showed,CHARINDEX('-',Time_showed) + 1,len(Time_showed))))--you should turn this into a function (GetEndTime)
                            ) OR
                            (
                                @end_time > CONVERT(TIME,RTRIM(SUBSTRING(Time_showed,0,CHARINDEX('-',Time_showed))))--you should turn this into a function (GetStartTime)
                                AND
                                @end_time < CONVERT(TIME,LTRIM(SUBSTRING(Time_showed,CHARINDEX('-',Time_showed) + 1,len(Time_showed))))--you should turn this into a function (GetEndTime)
                            )
                    )
        THEN 1 --TIME PERIOD ALREADY USED
        ELSE 0 --TIME PERIOD NOT USED
        END;
</code>```

Note: this is just a start script and there are some notes where I think you need to add some additional functionality.
    Also, you would want to turn this into a stored procedure as I mentioned earlier and create two helper functions to handle the splitting and conversion to time as I can see you will need this other places.
    I didn't use between because as you stated the actual time taken is between the 'time_showed' (...time between 17:02 and 17:06 is taken (17:03-17:05)... ). 'BETWEEN' will match to '08:00 - 08:05' and '08:05 - 09:45'.

Title: Check if date and time is free

Body:
so I'm trying to solve out how to check if selected time is free. As example I have record in database:

date_from: 2017-06-05
date_till: 2017-07-05
Time_showed: 17:00 - 17:05

Time showed means that video begins to play at 17:00 and ends at 17:05.
So now new order is incoming:

date_from: 2017-06-12
date_till: 2017-09-05
Time_showed: 17:02 - 17:06

So as we see time between 17:02 and 17:06 is taken (17:03-17:05). Any Ideas how to check it with sql and php, so that in this situation it would return an error "Time is taken" ?

And Yeah stackoverflow wasn't the first place wjere I came to ask. Before that I tried to google a lot and solve it on my own... Seems like I'm not tough enough to solve it, lol.

Body:
Ok, I can kind of see why you would need the data designed this way but it may be worth your time to see if it could be designed differently.
However, you came for help so that is what we all should be doing instead of making judgement. We have all worked on DBs that have not been designed in the best way and had to live with it for whatever reason. (Stepping off my soap box..)

So I think you may want to put this as a stored proc that you pass in the dates and the show time and return a true false.
The conditions you need to check for are:
    Is this during existing hold date period AND --Will assume this period can be null
    Is this during existing hold time. -- will assume this has to be inputted. If all day would have a time like 00:00 - 24:59

I came up with the below script:

IF EXISTS (SELECT * FROM sys.tables where tables.name like  '#myTable%')
begin
    drop table #myTable
end;

CREATE TABLE #myTable
(
    date_from date NULL,
    date_till date NULL,
    Time_showed varchar(20)
);

INSERT INTO #myTable
VALUES
    ('2017-06-05', '2017-07-05', '17:00 - 17:05'),
    ('2017-06-05', '2017-06-05', '08:00 - 08:05');

--test data
DECLARE
    @test_from date,
    @test_till as date,
    @test_time_showed as varchar(20);
--SELECT
--  @test_from = '2017-06-12',
--  @test_till = '2017-07-05',
--  @test_time_showed = '17:02 - 17:06';--1
SELECT
    @test_from = '2017-06-05',
    @test_till = '2017-06-05',
    @test_time_showed = '08:00 - 08:00';--0
--SELECT
--  @test_from = '2017-06-05',
--  @test_till = '2017-06-05',
--  @test_time_showed = '07:59 - 08:00';--0
--SELECT
--  @test_from = '2017-06-12',
--  @test_till = '2017-07-05',
--  @test_time_showed = '17:07 - 17:16';--0

--SPLIT
DECLARE @start_time time = CONVERT(TIME,RTRIM(SUBSTRING(@test_time_showed,0,CHARINDEX('-',@test_time_showed))));--you should turn this into a function (GetStartTime)
DECLARE @end_time time = CONVERT(TIME,LTRIM(SUBSTRING(@test_time_showed,CHARINDEX('-',@test_time_showed) + 1,len(@test_time_showed))));--you should turn this into a function (GetEndTime)

----checking values CAN BE DELETED
--SELECT @start_time,@end_time;

--SELECT  date_from, date_till,
--  CONVERT(TIME,RTRIM(SUBSTRING(Time_showed,0,CHARINDEX('-',Time_showed)))) AS START_T,
--  CONVERT(TIME,LTRIM(SUBSTRING(Time_showed,CHARINDEX('-',Time_showed) + 1,len(Time_showed)))) AS END_T
--FROM #MYTABLE

--VALIDATION
--TODO: You need to add some validation to insure that you are getting the correct data.

--CHECK
    -- IS
SELECT CASE
        WHEN EXISTS ( SELECT date_from
                        FROM #myTable
                        WHERE
                            --check if any records on file is for any date in span
                            ((date_from BETWEEN @test_from AND @test_till) OR
                            (date_till BETWEEN @test_from AND @test_till) ) AND
                            --if a record is for any date in span, check if times overlap (THE NASTY STUFF)
                            (
                                @start_time > CONVERT(TIME,RTRIM(SUBSTRING(Time_showed,0,CHARINDEX('-',Time_showed))))--you should turn this into a function (GetStartTime)
                                AND
                                @start_time < CONVERT(TIME,LTRIM(SUBSTRING(Time_showed,CHARINDEX('-',Time_showed) + 1,len(Time_showed))))--you should turn this into a function (GetEndTime)
                            ) OR
                            (
                                @end_time > CONVERT(TIME,RTRIM(SUBSTRING(Time_showed,0,CHARINDEX('-',Time_showed))))--you should turn this into a function (GetStartTime)
                                AND
                                @end_time < CONVERT(TIME,LTRIM(SUBSTRING(Time_showed,CHARINDEX('-',Time_showed) + 1,len(Time_showed))))--you should turn this into a function (GetEndTime)
                            )
                    )
        THEN 1 --TIME PERIOD ALREADY USED
        ELSE 0 --TIME PERIOD NOT USED
        END;

Note: this is just a start script and there are some notes where I think you need to add some additional functionality.
    Also, you would want to turn this into a stored procedure as I mentioned earlier and create two helper functions to handle the splitting and conversion to time as I can see you will need this other places.
    I didn't use between because as you stated the actual time taken is between the 'time_showed' (...time between 17:02 and 17:06 is taken (17:03-17:05)... ). 'BETWEEN' will match to '08:00 - 08:05' and '08:05 - 09:45'.


问:
How to check array of dates are consecutive from todays date?
I have an array of unique dates from each time the user completes a task. I want to check if the dates within the array are consecutive from and including todays date.

If the array contains dates: "2017/6/2, 2017/6/3, 2017/6/4, 2017/6/5" then based on today's date being 2017/6/5 the function would return 4 as there are 4 consecutive dates from and including today.

If the array contains dates "2017/6/2, 2017/6/3, 2017/6/4" then it would return 0 as the array does not include today's date. Otherwise the count would be broken upon a non consecutive date.

```<code>List<Date> dateList = new ArrayList<Date>();
int count = 0;
Date todayDate = new Date();

for (int i=0; i<dateList.size(); i++){
    // Check if dates within the array are consecutive from todayDate, if so then increment count by 1.
}
</code>```

答:
If I understand the requirement correctly, you have an array of Date objects, ordered by date, and guaranteed not to have two Date objects for the same day, but possibly with gaps between the days. Your goal is to return the length of the maximum sub-array that contains only consecutive days and also includes the current day, or to return 0 if there is no such sub-array. The current day may fall anywhere inside that sub-array, not necessarily at the beginning or end.

It's not clear if you need to support crossing year boundaries, but I'll assume so. I also assume that all the Date objects in the list are for the same time zone which is also the time zone for the device on which you are running. If that's not the case, you should refer to this answer for more information on testing whether two Date objects refer to the same day.

It's fairly simple to do this if you work with Calendar objects instead of Date objects. You don't need any third-party libraries, as both Date and Calendar are parts of the standard Android API. I suggest doing this in two phases: first search for the current date in the array and then scan in both directions for either a gap in the dates or an array boundary. Then just count how far you could go in each direction.

```<code>public int getDateSpanCount(List<Date> dateList) {
    final int n = dateList.size();
    final Calendar today = Calendar.getInstance();
    final Calendar other = Calendar.getInstance();
    int count = 0;

    // First search for today in the date array
    int posToday = -1;
    for (int i=0; i<n; i++) {
        other.setTime(dateList.get(i));
        if (areSameDay(today, other)) {
            posToday = i;
            break;
        }
    }

    // If today is in the list, count the size of the sub-array containing today
    if (posToday >= 0) {
        count++; // count today, at least
        final Calendar probe = Calendar.getInstance();

        // scan backwards from position of today's date
        for (int prevPos = posToday - 1; prevPos >= 0; prevPos--) {
            final Date prev = dateList.get(prevPos);
            probe.setTime(prev);
            other.add(Calendar.DAY_OF_YEAR, -1);
            if (areSameDay(probe, other)) {
                count++;
                other.setTime(prev);
            } else {
                break;
            }
        }

        // reset the other time
        other.setTime(today.getTime());

        // scan forward from position of today's date
        for (int nextPos = posToday + 1; nextPos < n; nextPos++) {
            final Date next = dateList.get(nextPos);
            probe.setTime(next);
            other.add(Calendar.DAY_OF_YEAR, 1);
            if (areSameDay(probe, other)) {
                count++;
                other.setTime(next);
            } else {
                break;
            }
        }
    }
    return count;
}

/** Test whether two Calendar objects are set to the same day */
private static boolean areSameDay(Calendar c1, Calendar c2) {
    // see discussion above if dates may not all be for the local time zone
    return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) &&
           c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR);
}
</code>```

Body:
I have an array of unique dates from each time the user completes a task. I want to check if the dates within the array are consecutive from and including todays date.

If the array contains dates: "2017/6/2, 2017/6/3, 2017/6/4, 2017/6/5" then based on today's date being 2017/6/5 the function would return 4 as there are 4 consecutive dates from and including today.

If the array contains dates "2017/6/2, 2017/6/3, 2017/6/4" then it would return 0 as the array does not include today's date. Otherwise the count would be broken upon a non consecutive date.

List<Date> dateList = new ArrayList<Date>();
int count = 0;
Date todayDate = new Date();

for (int i=0; i<dateList.size(); i++){
    // Check if dates within the array are consecutive from todayDate, if so then increment count by 1.
}

Body:
If I understand the requirement correctly, you have an array of Date objects, ordered by date, and guaranteed not to have two Date objects for the same day, but possibly with gaps between the days. Your goal is to return the length of the maximum sub-array that contains only consecutive days and also includes the current day, or to return 0 if there is no such sub-array. The current day may fall anywhere inside that sub-array, not necessarily at the beginning or end.

It's not clear if you need to support crossing year boundaries, but I'll assume so. I also assume that all the Date objects in the list are for the same time zone which is also the time zone for the device on which you are running. If that's not the case, you should refer to this answer for more information on testing whether two Date objects refer to the same day.

It's fairly simple to do this if you work with Calendar objects instead of Date objects. You don't need any third-party libraries, as both Date and Calendar are parts of the standard Android API. I suggest doing this in two phases: first search for the current date in the array and then scan in both directions for either a gap in the dates or an array boundary. Then just count how far you could go in each direction.

public int getDateSpanCount(List<Date> dateList) {
    final int n = dateList.size();
    final Calendar today = Calendar.getInstance();
    final Calendar other = Calendar.getInstance();
    int count = 0;

    // First search for today in the date array
    int posToday = -1;
    for (int i=0; i<n; i++) {
        other.setTime(dateList.get(i));
        if (areSameDay(today, other)) {
            posToday = i;
            break;
        }
    }

    // If today is in the list, count the size of the sub-array containing today
    if (posToday >= 0) {
        count++; // count today, at least
        final Calendar probe = Calendar.getInstance();

        // scan backwards from position of today's date
        for (int prevPos = posToday - 1; prevPos >= 0; prevPos--) {
            final Date prev = dateList.get(prevPos);
            probe.setTime(prev);
            other.add(Calendar.DAY_OF_YEAR, -1);
            if (areSameDay(probe, other)) {
                count++;
                other.setTime(prev);
            } else {
                break;
            }
        }

        // reset the other time
        other.setTime(today.getTime());

        // scan forward from position of today's date
        for (int nextPos = posToday + 1; nextPos < n; nextPos++) {
            final Date next = dateList.get(nextPos);
            probe.setTime(next);
            other.add(Calendar.DAY_OF_YEAR, 1);
            if (areSameDay(probe, other)) {
                count++;
                other.setTime(next);
            } else {
                break;
            }
        }
    }
    return count;
}

/** Test whether two Calendar objects are set to the same day */
private static boolean areSameDay(Calendar c1, Calendar c2) {
    // see discussion above if dates may not all be for the local time zone
    return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR) &&
           c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR);
}


问:
Search and Replace in PHPMyAdmin database for Wordpress (absolute beginner)
I apologise in advance for I know that this question has been asked several times already, but being a complete beginner at wordpress coding and database handling, I am still not sure about what those answers really meant.
So having just coded a website and converted it into WordPress, I now find myself having to change all of the localhost strings to the accurate ones, but with hundreds to go through, I just wanted to know if any of you were able to recommend a program or technique within PHPMyAdmin (that I may not be aware of) to avoid having to change them one at a time.
Thank you all in advance for your time and attention.</p>

答:
First, let me start by saying this is very dangerous, especially for an absolute beginner such as yourself. Please use this with extreme caution as you can potentially bring the entire site down by replacing values in your database with the wrong data.

With that said, there is a script specifically designed for doing search and replace on the WordPress MySQL database. http://interconnectit.com/products/search-and-replace-for-wordpress-databases/

Here's the direct download link: https://github.com/interconnectit/Search-Replace-DB/archive/master.zip

You will extract the folder from the donwloaded zip, then upload the folder to the root of your WordPress install. Once its uploaded just reference the folder in the browser. I always rename the folder to sr (shorthand for search and replace) so its easier to write out the full URL. So as an example, once its in the root of the WordPress install you'd access it like www.example.com/sr/.

After you access the script in the browser, you'll have a GUI with two boxes at the top. The first you'll enter the string you're searching for, and the replace string goes in the second box. Your MySQL details/login should already be populated. After entering your S&R terms scroll down and click "Update Details", then do the "Dry Run" option first. It'll run through the database and show you the values that will be changed. If you are satisfied with the changes, click "Live Run".

Depending on the database size it'll take just a short time to complete. This is the easiest way to S&R the WordPress database.

Important: for security reasons you'll want to delete this folder from your server after you have finished using it. You don't want a database S&R utility just lingering around for no reason.

Another possible option if you're familiar with WP-CLI is to use the wp search-replace command: https://developer.wordpress.org/cli/commands/search-replace/ This would be done through Terminal or another command line utility.


问:
MySQL : How to give a default value to a foreign key when I don't use it?
Right now I have a table that has two foreign key, both that reference to different tables. When I insert a value in one foreign key field, but not in the other one, my insert fails because the foreign key constraint. How can I give a default value, like NULL or 0, to a column that references a foreign key, when I am not using it, or make the foreign key optional? I am using MySQL and XAMPP for my tables.</p>

答:
Declare the column as nullable.

Then use NULL in the column when you aren't using the foreign key.


问:
Difference Between HTML <audio>, <bgsound> and <embed> audio tags
What is the difference between <audio>, <bgsound> and <embed> tags ?

I am trying to add background sound on my website. tried <embed> but it doesn't works on mobile . similarly <bgsound> had some limitations. <audio> tag works for me.

can anybody explain how each differ from one another?

答:
< bgsound > : The HTML  tag is used to play a soundtrack in the background. This tag is for Internet Explorer only.

< bgsound >  :  Only For Internet Explorer

Summary :  The HTML Background Sound Element () is an Internet Explorer element associating a background sound with a page.

Example:

```<code><bgsound src="sound1.mid">
<bgsound src="sound2.au" loop="infinite">
</code>```

< audio > & < video >  :  Standard Way To Implement audio and video in Website currently

< audio >   :   HTML5  element specifies a standard way to embed audio in a web page. ( ogg,mp3.etc. supported )

Example :

```<code><audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio
</code>```

< embed >  : 3rd partiy Plugins like Java application , Flash apps.. etc,

< embed >  : its 3rd Partiy Plugins which are outdated now. ( The  element creates an embedded panel in which a third-party application, such as a Flash-based object, can run.

Example :

```<code><!DOCTYPE html>
<html>
<head>
<title>HTML Embed Tag</title>
</head>
<body>
<embed src="www.abc./html/yourfile.mdi" width="250" height="100" />
</body>
</html>
</code>```

Body:
< bgsound > : The HTML  tag is used to play a soundtrack in the background. This tag is for Internet Explorer only.

< bgsound >  :  Only For Internet Explorer

Summary :  The HTML Background Sound Element () is an Internet Explorer element associating a background sound with a page.

Example:

<bgsound src="sound1.mid">
<bgsound src="sound2.au" loop="infinite">

< audio > & < video >  :  Standard Way To Implement audio and video in Website currently

< audio >   :   HTML5  element specifies a standard way to embed audio in a web page. ( ogg,mp3.etc. supported )

Example :

<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio

< embed >  : 3rd partiy Plugins like Java application , Flash apps.. etc,

< embed >  : its 3rd Partiy Plugins which are outdated now. ( The  element creates an embedded panel in which a third-party application, such as a Flash-based object, can run.

Example :

<!DOCTYPE html>
<html>
<head>
<title>HTML Embed Tag</title>
</head>
<body>
<embed src="www.abc./html/yourfile.mdi" width="250" height="100" />
</body>
</html>


问:
How to protect a video file in html?
If someone adds a video to a webpage using the video tag you can find its link in the source code of the webpage very easily and download it. But websites like netflix, lynda, hulo, youtube, vimeo, dailymotion etc somehow manage to prevent you from being able to do it. How do they do it? How can I do it? I tried googling but didn't find anything useful. Can anyone help?

P.S I would like a client-side solution so if possible no php, perl, ruby etc

答:
They are using flash from what i can see. But with just a video tag, you can not protect its source.
This was an interesting question !</p>

Title: How to protect a video file in html?


问:
Get the Microsoft Research Sentence Completion Challenge
I am currently working on natural language processing for scholar purposes, and I would like to get the Microsoft Research Sentence Completion Challenge dataset.

Unfortunately, it seems that it is no more available on Microsoft's website : when I click on any of the two links to get the training or test data, I am redirected to the main page of Microsoft Research. I tried to contact Microsoft's technical support, but they didn't answer me, and I couldn't find the dataset on an other website.

Do you know where I could find this dataset (I'm mainly interested in the test set) ?

Thanks in advance for your help.

答:
I did some research, I have two sources (were quite hard to find):

Kaggle - https://inclass.kaggle.com/c/mlsd-hw3/data

Github repo/google drive link - https://drive.google.com/drive/folders/0B5eGOMdyHn2mWDYtQzlQeGNKa2s

Hope they are correct :)


问:
Accessing a Promises Value outside of its context
I understand to access a value of a Promise, I will use the "then" callback attach to it.

However, I was wondering how I can affect the context outside of it?

```<code>let outsideVar = 0;
promiseA.then(value => {
    outsideVar = 1;
})
console.log(outsideVar); //0
</code>```

As you can see I would like to change outsideVar to 1

[Edit] This question was to see if promises can affect global variables outside of it and if there were any possibilities to do that.

Unfortunately, it is not possible.

答:
`

let ousideVar = 0;

function promiseA(){
 return new Promise( function(resolve, reject){
  resolve();
 })
}

promiseA().then(function(){
 ousideVar = 1;
  //when promise resolved
  console.log(ousideVar) // 1
})

console.log(ousideVar) // 0```
</div>
</div>
</p>

<p>`When your promise resolved your "outsideVar" replace with the new value inside of then.<br>
Example:</p>

```let outsideVar = 0;
promiseA().then(value => {
outsideVar = 1;
})
console.log(outsideVar);
```

When promiseA calls it return a callback and your value replaced with the new one

outsideVar = 1;

Body:
I understand to access a value of a Promise, I will use the "then" callback attach to it.

However, I was wondering how I can affect the context outside of it?

let outsideVar = 0;
promiseA.then(value => {
    outsideVar = 1;
})
console.log(outsideVar); //0

As you can see I would like to change outsideVar to 1

[Edit] This question was to see if promises can affect global variables outside of it and if there were any possibilities to do that.

Unfortunately, it is not possible.

Body:
`

let ousideVar = 0;

function promiseA(){
 return new Promise( function(resolve, reject){
  resolve();
 })
}

promiseA().then(function(){
 ousideVar = 1;
  //when promise resolved
  console.log(ousideVar) // 1
})

console.log(ousideVar) // 0

`When your promise resolved your "outsideVar" replace with the new value inside of then.

Example:

let outsideVar = 0;
promiseA().then(value => {
outsideVar = 1;
})
console.log(outsideVar);

When promiseA calls it return a callback and your value replaced with the new one

outsideVar = 1;


问:
Sort table by integer value stored in varchar field
Me working in spring hibernate

I have column in my database table, that of type VARCHAR, but it store integer value. So if i sort it using sql or hql or Criteria(Order.asc), all are sorting it as string. I need it to be sorted as integer value it store. Here i cannot alter my table.

Is There anyway to sort it as integer using Criteria

Is the only solution for me is, after reading it to some list and sort inside my service?

Edited : me using MYSQL

Thank you

答:
You could try casting it before sorting it. In mysql, something like this:

```<code>SELECT CAST(myVarcharField AS DECIMAL(10)) as myIntField order by myIntField;
</code>```

or as an unsigned integer:

```<code>SELECT CAST(myVarcharField AS UNSIGNED) as myIntField order by myIntField;
</code>```

cast appears to be a valid HQL expression too.

Body:
You could try casting it before sorting it. In mysql, something like this:

SELECT CAST(myVarcharField AS DECIMAL(10)) as myIntField order by myIntField;

or as an unsigned integer:

SELECT CAST(myVarcharField AS UNSIGNED) as myIntField order by myIntField;

cast appears to be a valid HQL expression too.


问:
Javascript button multiple audio source
So i am working on a school project and am pretty new to coding. My project is to make a little playlist with javascript, but I only want my project to have one universal button and have multiple audio sources. I want the user to be able to select the song and be able to play it with the button. Any ideas?</p>

答:
This uses HtmlAudioElement, I did not test with the audios, but that's the idea, may help you as a reference to implement your code.

var aux = 1;

function playAudiox() {
  if (aux == 1) {
    console.log("Playing Track 1.");
    var track1 = new Audio('track1.mp3');
    track1.play();
    aux++;
  } else if (aux == 2) {
    console.log("Playing Track 2.");
    var track2 = new Audio('track2.mp3');
    track2.play();
    aux++;
  } else if (aux == 3) {
    console.log("Playing Track 3.");
    var track3 = new Audio('track3.mp3');
    track3.play();
    aux = 1;
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#tracklist {
  height: 200px;
  height: 100px;
  border: 2px solid black;
}

.tracks {
  border: 1px solid red;
  height: 100px;
  width: 80px;
  float: left;
}</code>```

track1

track2

track3

<button id="universalPlay" onclick="playAudiox()">Universal Play</button>```

Title: Javascript button multiple audio source

Body:
This uses HtmlAudioElement, I did not test with the audios, but that's the idea, may help you as a reference to implement your code.

var aux = 1;

function playAudiox() {
  if (aux == 1) {
    console.log("Playing Track 1.");
    var track1 = new Audio('track1.mp3');
    track1.play();
    aux++;
  } else if (aux == 2) {
    console.log("Playing Track 2.");
    var track2 = new Audio('track2.mp3');
    track2.play();
    aux++;
  } else if (aux == 3) {
    console.log("Playing Track 3.");
    var track3 = new Audio('track3.mp3');
    track3.play();
    aux = 1;
  }
}

#tracklist {
  height: 200px;
  height: 100px;
  border: 2px solid black;
}

.tracks {
  border: 1px solid red;
  height: 100px;
  width: 80px;
  float: left;
}

<div id="tracklist">

  <div class="tracks">track1</div>
  <div class="tracks">track2</div>
  <div class="tracks">track3</div>
</div><br>
<button id="universalPlay" onclick="playAudiox()">Universal Play</button>


问:
In-App Purchases stuck in "Missing Metadata" state
I am trying to set up in-app purchases but I don't know how to get rid of the "Missing Metadata" shown below.

The only yellow dot I see from the page is the "Localizations" section, but I completed the "Display Name" and "Description".

I don't know what else I can do or what I am doing wrong.

答: Any 1024x768 png image file added to the screenshot in Review Information has solved the issue</p>


问:
How to open view controller when popup is open - swift 3
I'm using the PopupDialog library and have a button that when tapped loads a popup as shown in the code below:

```<code>// Create the dialog
let popup_around_me = AroundMePopUpViewController(nibName: "popup_around_me", bundle: nil)
popup_around_me.gh = self.getJobByLatitude(latitude: marker.position.latitude)
let popup = PopupDialog(viewController: popup_around_me, buttonAlignment: .horizontal, transitionStyle: .bounceDown, gestureDismissal: true)

present(popup, animated: true, completion: nil)
//print("marker.position.latitude: \(marker.position.latitude)")
</code>```

Within my popup there are two buttons that open controllers.

Because I'm using a navigation bar, I think I should first close the popup and then open my controller. Without doing so my navigation bar is not loaded.

But I don't know whether this is the correct way to do it.
If it's ok, how can I do(close popup and open controller)?

my button function:

```<code> func cliclOnContent(tapGestureRecognizer: UITapGestureRecognizer)
    {
        print("job id: \(self.gh.id)")

//below codes not load my navigation.
//        let vc = self.storyboard!.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
//        vc.job_id = self.gh.id
//        self.navigationController?.pushViewController(vc, animated: true)

       // let storyboard = UIStoryboard(name: "Main", bundle: nil)
//        let controller = storyboard?.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
//        controller.job_id = self.gh.id
//        self.present(controller, animated: true, completion: nil)

    }
</code>```

答:
Edited:

Actually you don't have to close it. It automatically close itself all you have to do is to call your View controller in respective button action.

I have a view controller and i made a call using segue like this in cancel button.

And my output is like this.by the way i just used their demo file for quick response.

Body:
I'm using the PopupDialog library and have a button that when tapped loads a popup as shown in the code below:

// Create the dialog
let popup_around_me = AroundMePopUpViewController(nibName: "popup_around_me", bundle: nil)
popup_around_me.gh = self.getJobByLatitude(latitude: marker.position.latitude)
let popup = PopupDialog(viewController: popup_around_me, buttonAlignment: .horizontal, transitionStyle: .bounceDown, gestureDismissal: true)

present(popup, animated: true, completion: nil)
//print("marker.position.latitude: \(marker.position.latitude)")

Within my popup there are two buttons that open controllers.

Because I'm using a navigation bar, I think I should first close the popup and then open my controller. Without doing so my navigation bar is not loaded.

But I don't know whether this is the correct way to do it.
If it's ok, how can I do(close popup and open controller)?

my button function:

 func cliclOnContent(tapGestureRecognizer: UITapGestureRecognizer)
    {
        print("job id: \(self.gh.id)")

//below codes not load my navigation.
//        let vc = self.storyboard!.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
//        vc.job_id = self.gh.id
//        self.navigationController?.pushViewController(vc, animated: true)

       // let storyboard = UIStoryboard(name: "Main", bundle: nil)
//        let controller = storyboard?.instantiateViewController(withIdentifier: "ContentAJobViewController") as! ContentAJobViewController
//        controller.job_id = self.gh.id
//        self.present(controller, animated: true, completion: nil)

    }


问:
mongo db rest Api returns allways same entry
I am working on the development af a MEAN app and I have a curious problem:

I have created an API which allows me to get one single document by id:

```<code>//Get Single Line
router.get('/lines/:id', function(req, res, next){
    db.lines.findOne(
        { _id: mongojs.ObjectId(req.params.id)},
        function(err, line){
        if(err){
            res.send(err);
        }
        res.json(line);
    });
});
</code>```

Now when I call http://localhost:3000/api/lines/593379eb0cbd3a4efcdc1875 I get what I expect:

```<code>{"_id":"593379eb0cbd3a4efcdc1875","name":...
</code>```

But, when I move this project to a live Server, when I call http://mydomain/api/lines/593379eb0cbd3a4efcdc1875 I allways get the first document in my collection:

```<code>{"_id":"59337c480cbd3a4efcdc1876","name":
</code>```

Even if I try some id that does not exist - I allways get only the first document.
I really cant figure out, what the probem here is....

答: Did you try to debug the code to find whether correct _id passed to the controller and to the query? Recheck the database names and collection names matched with your repository for both local and live environments.</p>

Body:
I am working on the development af a MEAN app and I have a curious problem:

I have created an API which allows me to get one single document by id:

//Get Single Line
router.get('/lines/:id', function(req, res, next){
    db.lines.findOne(
        { _id: mongojs.ObjectId(req.params.id)},
        function(err, line){
        if(err){
            res.send(err);
        }
        res.json(line);
    });
});

Now when I call http://localhost:3000/api/lines/593379eb0cbd3a4efcdc1875 I get what I expect:

{"_id":"593379eb0cbd3a4efcdc1875","name":...

But, when I move this project to a live Server, when I call http://mydomain/api/lines/593379eb0cbd3a4efcdc1875 I allways get the first document in my collection:

{"_id":"59337c480cbd3a4efcdc1876","name":

Even if I try some id that does not exist - I allways get only the first document.
I really cant figure out, what the probem here is....