问:
IntelliJ 15 / Grails 3 : Cannot connect to mySql DB
The question have been asked many time, but none of the given answers solve my problem : I create a new Grails 3 project with IntelliJ IDEA 15.0.1, add no extra code : it runs. When I try to configure my project to connect to MySql Database, i've got the following error :

```<code>ERROR org.apache.tomcat.jdbc.pool.ConnectionPool - Unable to create initial connections of pool. java.sql.SQLException: Unable to load class: com.mysql.jdbc.Driver from ClassLoader:sun.misc.Launcher$AppClassLoader@77abfbdc;ClassLoader:sun.misc.Launcher$AppClassLoader@77abfbdc
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:280)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:200)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:708)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:642)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:464)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:141)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:115)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:102)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:126)
at org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy.afterPropertiesSet(LazyConnectionDataSourceProxy.java:162)
at org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy.<init>(LazyConnectionDataSourceProxy.java:106)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrConstructorNewInstance(ReflectiveInterceptor.java:1075)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
</code>```

My config is : JDK 1.7.072 / Grails 3.1.8 / IntelliJ 15.0.1

Build.gradle :

```<code>   buildscript {
    ext {
        grailsVersion = project.grailsVersion
    }
    repositories {
        mavenLocal()
        maven { url "https://repo.grails.org/grails/core" }
    }
    dependencies {
        classpath "org.grails:grails-gradle-plugin:$grailsVersion"
        classpath "com.bertramlabs.plugins:asset-pipeline-gradle:2.8.2"
        classpath "org.grails.plugins:hibernate4:5.0.6"
    }
}

version "0.1"
group "testgrails3"

apply plugin: "eclipse"
apply plugin: "idea"
apply plugin: "war"
apply plugin: "org.grails.grails-web"
apply plugin: "org.grails.grails-gsp"
apply plugin: "asset-pipeline"

ext {
    grailsVersion = project.grailsVersion
    gradleWrapperVersion = project.gradleWrapperVersion
}

repositories {
    mavenLocal()
    maven { url "https://repo.grails.org/grails/core" }
}

dependencyManagement {
    imports {
        mavenBom "org.grails:grails-bom:$grailsVersion"
    }
    applyMavenExclusions false
}

dependencies {

    compile "org.springframework.boot:spring-boot-starter-logging"
    compile "org.springframework.boot:spring-boot-autoconfigure"
    compile "org.grails:grails-core"
    compile "org.springframework.boot:spring-boot-starter-actuator"
    compile "org.springframework.boot:spring-boot-starter-tomcat"
    compile "org.grails:grails-dependencies"
    compile "org.grails:grails-web-boot"
    compile "org.grails.plugins:cache"
    compile "org.grails.plugins:scaffolding"
    compile "org.grails.plugins:hibernate4"
    compile "org.hibernate:hibernate-ehcache"
    console "org.grails:grails-console"
    profile "org.grails.profiles:web:3.1.8"
    runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.8.2"
    runtime "mysql:mysql-connector-java:5.1.39"
    testCompile "org.grails:grails-plugin-testing"
    testCompile "org.grails.plugins:geb"
    testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
    testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"
}

task wrapper(type: Wrapper) {
    gradleVersion = gradleWrapperVersion
}

assets {
    minifyJs = true
    minifyCss = true
}
</code>```

Application.yml :

```<code>hibernate:
    cache:
        queries: false
        use_second_level_cache: true
        use_query_cache: false
        region.factory_class: 'org.hibernate.cache.ehcache.EhCacheRegionFactory'

dataSource:
    pooled: true
    jmxExport: true
    driverClassName: com.mysql.jdbc.Driver
    dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    username: myuser
    password: mypassword

environments:
    development:
        dataSource:
            dbCreate: update
            url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/myappdev;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    test:
        dataSource:
            dbCreate: update
            url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/myapptest;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    production:
        dataSource:
            dbCreate: update
            url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/myappprod;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
            properties:
                jmxEnabled: true
                initialSize: 5
                maxActive: 50
                minIdle: 5
                maxIdle: 25
                maxWait: 10000
                maxAge: 600000
                timeBetweenEvictionRunsMillis: 5000
                minEvictableIdleTimeMillis: 60000
                validationQuery: SELECT 1
                validationQueryTimeout: 3
                validationInterval: 15000
                testOnBorrow: true
                testWhileIdle: true
                testOnReturn: false
                jdbcInterceptors: ConnectionState
                defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED

---
</code>```

Of course, the jdbc:mysql://xxx.xxx.xxx.xxx:3306/ is a valid IP.

Thanks for any help : i spend several days on this problem ...

答:
Try to use
"Compile 'mysql:mysql-connector-java:5.1.37' in the buildConfig. Apparently you are not being able  to load the class of mysql conector </p>

Body:
The question have been asked many time, but none of the given answers solve my problem : I create a new Grails 3 project with IntelliJ IDEA 15.0.1, add no extra code : it runs. When I try to configure my project to connect to MySql Database, i've got the following error :

ERROR org.apache.tomcat.jdbc.pool.ConnectionPool - Unable to create initial connections of pool. java.sql.SQLException: Unable to load class: com.mysql.jdbc.Driver from ClassLoader:sun.misc.Launcher$AppClassLoader@77abfbdc;ClassLoader:sun.misc.Launcher$AppClassLoader@77abfbdc
at org.apache.tomcat.jdbc.pool.PooledConnection.connectUsingDriver(PooledConnection.java:280)
at org.apache.tomcat.jdbc.pool.PooledConnection.connect(PooledConnection.java:200)
at org.apache.tomcat.jdbc.pool.ConnectionPool.createConnection(ConnectionPool.java:708)
at org.apache.tomcat.jdbc.pool.ConnectionPool.borrowConnection(ConnectionPool.java:642)
at org.apache.tomcat.jdbc.pool.ConnectionPool.init(ConnectionPool.java:464)
at org.apache.tomcat.jdbc.pool.ConnectionPool.<init>(ConnectionPool.java:141)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.pCreatePool(DataSourceProxy.java:115)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.createPool(DataSourceProxy.java:102)
at org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection(DataSourceProxy.java:126)
at org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy.afterPropertiesSet(LazyConnectionDataSourceProxy.java:162)
at org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy.<init>(LazyConnectionDataSourceProxy.java:106)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrConstructorNewInstance(ReflectiveInterceptor.java:1075)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)

My config is : JDK 1.7.072 / Grails 3.1.8 / IntelliJ 15.0.1

Build.gradle :

   buildscript {
    ext {
        grailsVersion = project.grailsVersion
    }
    repositories {
        mavenLocal()
        maven { url "https://repo.grails.org/grails/core" }
    }
    dependencies {
        classpath "org.grails:grails-gradle-plugin:$grailsVersion"
        classpath "com.bertramlabs.plugins:asset-pipeline-gradle:2.8.2"
        classpath "org.grails.plugins:hibernate4:5.0.6"
    }
}

version "0.1"
group "testgrails3"

apply plugin: "eclipse"
apply plugin: "idea"
apply plugin: "war"
apply plugin: "org.grails.grails-web"
apply plugin: "org.grails.grails-gsp"
apply plugin: "asset-pipeline"

ext {
    grailsVersion = project.grailsVersion
    gradleWrapperVersion = project.gradleWrapperVersion
}

repositories {
    mavenLocal()
    maven { url "https://repo.grails.org/grails/core" }
}

dependencyManagement {
    imports {
        mavenBom "org.grails:grails-bom:$grailsVersion"
    }
    applyMavenExclusions false
}

dependencies {

    compile "org.springframework.boot:spring-boot-starter-logging"
    compile "org.springframework.boot:spring-boot-autoconfigure"
    compile "org.grails:grails-core"
    compile "org.springframework.boot:spring-boot-starter-actuator"
    compile "org.springframework.boot:spring-boot-starter-tomcat"
    compile "org.grails:grails-dependencies"
    compile "org.grails:grails-web-boot"
    compile "org.grails.plugins:cache"
    compile "org.grails.plugins:scaffolding"
    compile "org.grails.plugins:hibernate4"
    compile "org.hibernate:hibernate-ehcache"
    console "org.grails:grails-console"
    profile "org.grails.profiles:web:3.1.8"
    runtime "com.bertramlabs.plugins:asset-pipeline-grails:2.8.2"
    runtime "mysql:mysql-connector-java:5.1.39"
    testCompile "org.grails:grails-plugin-testing"
    testCompile "org.grails.plugins:geb"
    testRuntime "org.seleniumhq.selenium:selenium-htmlunit-driver:2.47.1"
    testRuntime "net.sourceforge.htmlunit:htmlunit:2.18"
}

task wrapper(type: Wrapper) {
    gradleVersion = gradleWrapperVersion
}

assets {
    minifyJs = true
    minifyCss = true
}

Application.yml :

hibernate:
    cache:
        queries: false
        use_second_level_cache: true
        use_query_cache: false
        region.factory_class: 'org.hibernate.cache.ehcache.EhCacheRegionFactory'

dataSource:
    pooled: true
    jmxExport: true
    driverClassName: com.mysql.jdbc.Driver
    dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    username: myuser
    password: mypassword

environments:
    development:
        dataSource:
            dbCreate: update
            url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/myappdev;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    test:
        dataSource:
            dbCreate: update
            url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/myapptest;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
    production:
        dataSource:
            dbCreate: update
            url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/myappprod;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE
            properties:
                jmxEnabled: true
                initialSize: 5
                maxActive: 50
                minIdle: 5
                maxIdle: 25
                maxWait: 10000
                maxAge: 600000
                timeBetweenEvictionRunsMillis: 5000
                minEvictableIdleTimeMillis: 60000
                validationQuery: SELECT 1
                validationQueryTimeout: 3
                validationInterval: 15000
                testOnBorrow: true
                testWhileIdle: true
                testOnReturn: false
                jdbcInterceptors: ConnectionState
                defaultTransactionIsolation: 2 # TRANSACTION_READ_COMMITTED

---

Of course, the jdbc:mysql://xxx.xxx.xxx.xxx:3306/ is a valid IP.

Thanks for any help : i spend several days on this problem ...


来源: stackexchange

问:
Ruby on rails updating model via rails console
I have run rails g model Task description:text. Then I have run rails console and put in a few tasks. I would now like to add more attributes to the create_tasks.rb file. Such as  .string :title.

What I tried:

opened the file(create_tasks.rb), put the new line in. Then ran rake
db:migrate then went back into the console and opened the first task
and it doesn't show the title attribute.

also tried creating a new task using the title attribute. Error:
unknown title attribute for Task.

So, how do I update the model?

答:
Welcome to Rails!

Here you can find some tutorials about how to deal with migrations:

http://edgeguides.rubyonrails.org/active_record_migrations.html

https://www.tutorialspoint.com/ruby-on-rails/rails-migrations.htm

Basically, every time you want to modify a migration, you must:

run rake db:rollback

modify the migration

run rake db:migrate

I hope this helps. Good coding!!

ContentLicense: CC BY-SA 3.0


问:
explode function doesn't work for me?
I want to change the string into array after using foreach() so
          how is it done? </p>

```<code>$g = "";
$changer = explode(",", $g);
foreach ($y as $key => $c) {
    foreach ($c['movie'] as $rr) {
        $g .= $rr->movieName . ",";
    }
}
</code>```

答:
Based on your answer, theres a much easier way to do it than what you're doing:</p>

```<code>foreach ($y as $key => $c) {
    foreach ($c['movie'] as $rr) {
        $changer[] = $rr->movieName;
    }
}
</code>```

Title: explode function doesn't work for me?

Body:
I want to change the string into array after using foreach() so
          how is it done?

$g = "";
$changer = explode(",", $g);
foreach ($y as $key => $c) {
    foreach ($c['movie'] as $rr) {
        $g .= $rr->movieName . ",";
    }
}

Body:
Based on your answer, theres a much easier way to do it than what you're doing:

foreach ($y as $key => $c) {
    foreach ($c['movie'] as $rr) {
        $changer[] = $rr->movieName;
    }
}


问:
Upgraded R but RTVS points to old version
I'm using R Tools for Visual Studio (RTVS version 1.0.30321.1407) in Microsoft Visual Studio Professional 2015 (version 14.0.25431.01 Update 3).  I've been using R version 3.3.1, but today I installed R version 3.4.0.

My RStudio was smart enough to now point to the new version of R, but my RTVS is still pointing to the old one.

How do I get RTVS to point to the latest version of R?

Addendum:  The solution is not to simply uninstall the old R from my machine.  That just makes Visual Studio hang for what seems like forever upon startup.

答:
The answer, it turns out, is to get the latest version (1.1) of RTVS because this is a known bug as discussed here.

It's not obvious where to download it from, but I found it here.


问:
how to execute different system commands in differrent threads with python3
I want to execute two different commands in different thread with python3,below is my code:

```<code>import time
import threading
import os

class MyThread(threading.Thread):

    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result():
        return self.result

def sniffdata1():
    while 1:
        time.sleep(1)
        os.system("echo 2")

def sniffdata2():
        time.sleep(1)
        os.system("echo 1")

sniffThread1=MyThread(sniffdata1,())
sniffThread2=MyThread(sniffdata2,())
sniffThread1.start()
sniffThread2.start()
sniffThread1.join()
sniffThread2.join()
</code>```

But I can not get my 121212...,the result is 1 2 2 2 2 2 2 2 ...(no more 1),but alway echo 2,can someone help me?

答:
If you want get more 1, you should add while to sniffdata2():

```<code>def sniffdata2():
    while 1:
        time.sleep(1)
        os.system("echo 1")
</code>```

But if you want to get 12121212... all the times, you should use this code:

```<code>import time
import threading
import os
flag2 = False;
flag1 = True;

class MyThread(threading.Thread):

    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        return self.result

def sniffdata1():
    global flag2, flag1
    while 1:
        if flag1:
            flag2 = False
            time.sleep(1)
            os.system("echo 1")
            flag1 = False
            flag2 = True

def sniffdata2():
    global flag2, flag1
    while 1:
        if flag2:
            flag1 = False
            time.sleep(1)
            os.system("echo 2")
            flag2 = False
            flag1 =True

sniffThread1=MyThread(sniffdata1,())
sniffThread2=MyThread(sniffdata2,())
sniffThread1.start()
sniffThread2.start()
</code>```

Body:
I want to execute two different commands in different thread with python3,below is my code:

import time
import threading
import os

class MyThread(threading.Thread):

    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result():
        return self.result

def sniffdata1():
    while 1:
        time.sleep(1)
        os.system("echo 2")

def sniffdata2():
        time.sleep(1)
        os.system("echo 1")

sniffThread1=MyThread(sniffdata1,())
sniffThread2=MyThread(sniffdata2,())
sniffThread1.start()
sniffThread2.start()
sniffThread1.join()
sniffThread2.join()

But I can not get my 121212...,the result is 1 2 2 2 2 2 2 2 ...(no more 1),but alway echo 2,can someone help me?

Body:
If you want get more 1, you should add while to sniffdata2():

def sniffdata2():
    while 1:
        time.sleep(1)
        os.system("echo 1")

But if you want to get 12121212... all the times, you should use this code:

import time
import threading
import os
flag2 = False;
flag1 = True;

class MyThread(threading.Thread):

    def __init__(self, func, args, name=''):
        threading.Thread.__init__(self)
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        return self.result

def sniffdata1():
    global flag2, flag1
    while 1:
        if flag1:
            flag2 = False
            time.sleep(1)
            os.system("echo 1")
            flag1 = False
            flag2 = True

def sniffdata2():
    global flag2, flag1
    while 1:
        if flag2:
            flag1 = False
            time.sleep(1)
            os.system("echo 2")
            flag2 = False
            flag1 =True

sniffThread1=MyThread(sniffdata1,())
sniffThread2=MyThread(sniffdata2,())
sniffThread1.start()
sniffThread2.start()


问:
how can i increase bootstrap modal height
I am simply trying to make a bootstrap modal display extremely tall on a iphone 5/6 device.

I cannot get this to work for anything. I have tried increasing the height in the modal-content, as well as in modal-dialog, but it just wont work.

Any easy solutions out there?

.modal-dialog{
    height:90% !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
    Launch modal
  </button>
</div>

<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">My modal</h4>
      </div>
    </div>
  </div>
</div>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script></code>```

答:
That is because the model is inside the class modal-content and I dont know how is your code and if your content have some reference, for now you can specific in pixels:

```<code>.modal-content{
  height:500px;
}
</code>```

Body:
I am simply trying to make a bootstrap modal display extremely tall on a iphone 5/6 device.

I cannot get this to work for anything. I have tried increasing the height in the modal-content, as well as in modal-dialog, but it just wont work.

Any easy solutions out there?

.modal-dialog{
    height:90% !important;
}

  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
    Launch modal
  </button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

My modal

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Body:
That is because the model is inside the class modal-content and I dont know how is your code and if your content have some reference, for now you can specific in pixels:

.modal-content{
  height:500px;
}


问:
WordPress to changing simple quotes for double quotes
CONTEXT. I work with WordPress 4.7.5 and shortcodes.

GOAL. Put a link that displays information hidden as an accordion. The simple way to do this is to insert a shortcode Accordion type:

```<code>[su_accordion]
    [su_spoiler title="My link"]
        <h1>Lorem ipsum dolor sit amet</h1>
    [/su_spoiler]
[/su_accordion]
</code>```

This works perfectly. But my goal is slightly more complex: the link (My link) must be embedded within an HTML tag, for example a table:

```<code>[su_accordion]
    [su_spoiler title="
        <table class='my-custom-class-1'>
            <tbody>
                <tr>
                    <td class='my-custom-class-2'>My link</td>
                </tr>
            </tbody>
        </table>
        "]
        <h1>Lorem ipsum dolor sit amet</h1>
    [/su_spoiler]
[/su_accordion]
</code>```

As you can see, my-custom-class-1 and my-custom-class-2 are in single quotes. They can not are in double quotes because WordPress would be confused with the double quotation marks of the accordion.

Now, this also works perfectly.

PROBLEM. The problem comes when, some time later, I want to edit this item. WordPress automatically modifies the shortcode, changing my single quotes by double quotation marks, which evidently breaks the shortcode, so that the link is no longer visible in the frontend.

How to prevent WordPress from changing the quotes?
Or any other ideas on how to fix this?

答:
I answer my own question.

I found this plugin that does the following: any HTML located between the [raw] and [/raw] tags will not be modified by anything or anyone: https://wordpress.org/plugins/raw-html/

Body:
CONTEXT. I work with WordPress 4.7.5 and shortcodes.

GOAL. Put a link that displays information hidden as an accordion. The simple way to do this is to insert a shortcode Accordion type:

[su_accordion]
    [su_spoiler title="My link"]

Lorem ipsum dolor sit amet

    [/su_spoiler]
[/su_accordion]

This works perfectly. But my goal is slightly more complex: the link (My link) must be embedded within an HTML tag, for example a table:

[su_accordion]
    [su_spoiler title="

                    My link

        "]

Lorem ipsum dolor sit amet

    [/su_spoiler]
[/su_accordion]

As you can see, my-custom-class-1 and my-custom-class-2 are in single quotes. They can not are in double quotes because WordPress would be confused with the double quotation marks of the accordion.

Now, this also works perfectly.

PROBLEM. The problem comes when, some time later, I want to edit this item. WordPress automatically modifies the shortcode, changing my single quotes by double quotation marks, which evidently breaks the shortcode, so that the link is no longer visible in the frontend.

How to prevent WordPress from changing the quotes?
Or any other ideas on how to fix this?


问:
How to correctly set expression Query.CommandText in SSRS?
In my SSRS report builder I have an expression set for one of my dataset (name is dsTagAttributes).  The query type is text.

This is the query expression

```<code>="select m.TagName, ta.descriptor, t.[State]  from MasterTags m inner join TagAttributesClassic ta on m.ID = ta.TagID inner join TagStates t on t.ID = m.StateID where m.PIServerID = @ServerID and t.[State] = @State and m.MetaData1 = @Station " & Parameters!AndOr.Value & "m.MetaData2 = @Device"
</code>```

The above query expression has a parameter which is concatenated in the select statement.

The parameter @AndOr data type is text, has a default value of "or", and parameter visibility is set to hidden (screen shot below). I have set this parameter because it will be used to dynamically change the dataset result from or to and during the report runtime.

But when I run the report, an exception is thrown saying,

What could go wrong in my query command text?

Any help is greatly appreciated.

答:
You can run Profiler against Data Source to see the query.

I assume the problem is that you miss "'" before and after each varchar value (@State, @Station).

I wouldn't use that way to use OrAnd condition

You can modify TSQL like

```<code>...
    AND
    (m.MetaData2 = @Device AND @OrAnd = 'AND')
)
    OR
    (m.MetaData2 = @Device AND @OrAnd = 'OR')
</code>```

Just make sure you place ')' and '(' correctly, depending on business logic.

Body:
In my SSRS report builder I have an expression set for one of my dataset (name is dsTagAttributes).  The query type is text.

This is the query expression

="select m.TagName, ta.descriptor, t.[State]  from MasterTags m inner join TagAttributesClassic ta on m.ID = ta.TagID inner join TagStates t on t.ID = m.StateID where m.PIServerID = @ServerID and t.[State] = @State and m.MetaData1 = @Station " & Parameters!AndOr.Value & "m.MetaData2 = @Device"

The above query expression has a parameter which is concatenated in the select statement.

The parameter @AndOr data type is text, has a default value of "or", and parameter visibility is set to hidden (screen shot below). I have set this parameter because it will be used to dynamically change the dataset result from or to and during the report runtime.

But when I run the report, an exception is thrown saying,

What could go wrong in my query command text?

Any help is greatly appreciated.

Body:
You can run Profiler against Data Source to see the query.

I assume the problem is that you miss "'" before and after each varchar value (@State, @Station).

I wouldn't use that way to use OrAnd condition

You can modify TSQL like

...
    AND
    (m.MetaData2 = @Device AND @OrAnd = 'AND')
)
    OR
    (m.MetaData2 = @Device AND @OrAnd = 'OR')

Just make sure you place ')' and '(' correctly, depending on business logic.


问:
JDBC: complains about invalid sign but seems fine
I have to use JDBC to write to a database (hibernate/ibatis is not an option) and my database is Oracle 11g.

I create the following query: insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL, 'Jack', 19,TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS'));

However my statetement.execeuteUpdate(above sql). generates an invalid sign exception.
But when I perform the query in squirrel it gets commited just fine.
Does anyone know why this is happening?

```<code>Edit:
user table:
id: number : not null
username varchar2(30) not null
age number(10) not null
creation_ts timestamp not null

Error:
ORA-00911: invalid character

Java snippet:
try
        {
            DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
            String url = "privatized";
            Connection conn = DriverManager.getConnection(url, "username", "password");

            Statement st = conn.createStatement();

            Format formatter = new SimpleDateFormat(dateTimeFormatString);
            String formattedDate = formatter.format(Calendar.getInstance(TimeZone.getDefault()).getTime());

            StringBuilder insertQuery = new StringBuilder("insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL,");
                insertQuery.append(username);
                insertQuery.append(",");
            insertQuery.append(age);
            insertQuery.append(",TO_TIMESTAMP('");
            insertQuery.append(formattedDate);
            insertQuery.append("', 'DD/MM/RR HH24/MI/SS'));");
            System.err.println(insertQuery.toString());
            st.executeUpdate(insertQuery.toString());

            conn.close();
        } catch (SQLException ex){
            System.err.println(ex.getMessage());
            System.err.println(ex.getCause().toString());
            ex.printStackTrace();
            System.out.println("=========================================");
        } catch(Exception ex) {
            System.err.println(ex.getMessage());
        }
</code>```

答:
```<code>TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS')
</code>```

You send a 4-digit year but the format string defines a 2-digit year (no century)

Give this a try:

```<code>insertQuery.append("', 'DD/MM/RRRR HH24/MI/SS'));");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have to use JDBC to write to a database (hibernate/ibatis is not an option) and my database is Oracle 11g.

I create the following query: insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL, 'Jack', 19,TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS'));

However my statetement.execeuteUpdate(above sql). generates an invalid sign exception.
But when I perform the query in squirrel it gets commited just fine.
Does anyone know why this is happening?

Edit:
user table:
id: number : not null
username varchar2(30) not null
age number(10) not null
creation_ts timestamp not null

Error:
ORA-00911: invalid character

Java snippet:
try
        {
            DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
            String url = "privatized";
            Connection conn = DriverManager.getConnection(url, "username", "password");

            Statement st = conn.createStatement();

            Format formatter = new SimpleDateFormat(dateTimeFormatString);
            String formattedDate = formatter.format(Calendar.getInstance(TimeZone.getDefault()).getTime());

            StringBuilder insertQuery = new StringBuilder("insert into user(user_id, username, age, creation_ts) values(seq_userid.NEXTVAL,");
                insertQuery.append(username);
                insertQuery.append(",");
            insertQuery.append(age);
            insertQuery.append(",TO_TIMESTAMP('");
            insertQuery.append(formattedDate);
            insertQuery.append("', 'DD/MM/RR HH24/MI/SS'));");
            System.err.println(insertQuery.toString());
            st.executeUpdate(insertQuery.toString());

            conn.close();
        } catch (SQLException ex){
            System.err.println(ex.getMessage());
            System.err.println(ex.getCause().toString());
            ex.printStackTrace();
            System.out.println("=========================================");
        } catch(Exception ex) {
            System.err.println(ex.getMessage());
        }

Body:
TO_TIMESTAMP('14/12/2010 15/09/46', 'DD/MM/RR HH24/MI/SS')

You send a 4-digit year but the format string defines a 2-digit year (no century)

Give this a try:

insertQuery.append("', 'DD/MM/RRRR HH24/MI/SS'));");


问:
Javascript does not send data to the output
I am trying to run a JavaScript when the selected value in a dropdown is changed. But the script isnt working.

Here is my dropdown:

```<code><div class="form-group">
  <label>Status</label>
    <div>
      <select class="form-control select2" id="data" name="data" style="width: 100%;">
        <option value="1">Data one</option>
        <option value="0">Data two</option>
    </select>
  </div>
</div>
</code>```

Here is my javascript:

```<code><script type="text/javascript">
  var dataEl = document.querySelector('#data'),
    outputEl = document.querySelector('#output');

    dataEl.onchange = function() {
      outputEl.innerHTML = dataEl.value
        if (1 === dataEl.value) { '<b>Value one</b>' }
        if (0 === dataEl.value) { '<b>Value two</b>' }
  };
</script>
</code>```

When the selected value = 1 the script needs to send Value one to the output. When the selected value = 0 the script needs to send Value two to the output.

The output looks like:

I also tried to add selected to the options, but the script still not sends the data to the output.

Does someone know what is wrong?

https://jsfiddle.net/7fa84ufc/

答:
<select> element .value is a string, not a number. Use == operator for 1 == "1"

```<code>dataEl.onchange = function() {
    if (dataEl.value == 1) { outputEl.innerHTML = '<b>Value one</b>' }
    if (dataEl.value == 0) { outputEl.innerHTML = '<b>Value two</b>' }
};
</code>```

Body:
I am trying to run a JavaScript when the selected value in a dropdown is changed. But the script isnt working.

Here is my dropdown:

  Status

      <select class="form-control select2" id="data" name="data" style="width: 100%;">
        <option value="1">Data one</option>
        <option value="0">Data two</option>
    </select>

Here is my javascript:

When the selected value = 1 the script needs to send Value one to the output. When the selected value = 0 the script needs to send Value two to the output.

The output looks like:

I also tried to add selected to the options, but the script still not sends the data to the output.

Does someone know what is wrong?

https://jsfiddle.net/7fa84ufc/

Body:
<select> element .value is a string, not a number. Use == operator for 1 == "1"

dataEl.onchange = function() {
    if (dataEl.value == 1) { outputEl.innerHTML = '<b>Value one</b>' }
    if (dataEl.value == 0) { outputEl.innerHTML = '<b>Value two</b>' }
};


问:
Angular 4 component get selected checkbox
I am new to Angular, and I want to get the current selected checkbox id. I have checked other threads in SO, but most of them are using with Controller, I am using in component.

Here is detailed information.
I have such a component

```<code><table class='table table-striped table-hover admin-form' *ngIf="deviceCategories">
<a (click)="test()">test</a>
<thead>
    <tr>
        <td class="text-center">序列</td>
        <th class="text-center">组名</th>
        <th class="text-center">LOGO</th>
        <th class="text-center">操作</th>
    </tr>
</thead>
<tbody>
    <tr *ngFor="let deviceCategory of deviceCategories | paginate: config">
        <td class="center">
            <input type="checkbox" ng-model="selected[deviceCategory.id]" id="checkbox_{{deviceCategory.id}}">
        </td>
        <td class="text-center">{{deviceCategory.id}}</td>
        <td class="text-center">{{deviceCategory.name}}</td>
        <td class="text-center"><img src="{{deviceCategory.logoUrl}}" width="30" alt=""></td>
        <td class="text-center project-actions">
            <a [routerLink]="['/management/deviceCategory/edit/',deviceCategory.id]" class="btn btn-white btn-xs text-muted"> <i class="fa fa-eye text-system"></i> 修改 </a>
            <a (click)="OnDelete(deviceCategory.id)" class="btn btn-white btn-xs text-muted"> <i class="fa fa-eye text-system"></i> 删除 </a>
        </td>
    </tr>
</tbody>
</code>```

And here is my ts

```<code>import { Component, OnInit, Input } from '@angular/core';
import { PaginationInstance } from 'ng2-pagination';
import { DeviceCategoryService}from '../../../services/deviceCategory.service';
import { DeviceCategoryViewModel } from "../../../model/deviceCategory";

@Component({
  selector: 'app-device-category-admin-table',
  templateUrl: './device-category-admin-table.component.html',
  styleUrls: ['./device-category-admin-table.component.css'],
  providers:[DeviceCategoryService]
})
export class DeviceCategoryAdminTableComponent implements OnInit {

  @Input() deviceCategories :any;
  @Input() config:any;

  public selected:{}

  constructor(
    private deviceCategorySvc:DeviceCategoryService
  ) { }

  ngOnInit() {
  }

  OnDelete(id:number){
      this.deviceCategorySvc.deleteDeviceCategory(id).subscribe(result=>{
          if(result.ok)
          {
            this.deviceCategorySvc.currentCategorys().subscribe(result=>{
              this.deviceCategories=result.data as DeviceCategoryViewModel[];
            });

          }

      });
  }
  test(){
    var result=this.selected;
      console.log(result);
  }
</code>```

Any help would be appreciated.

答:
With the suggestion from @Sajeetharan, I could achieve my requirement by below code.

html

```<code>   <td class="text-center">
        <input type="checkbox" [(ngModel)]="deviceCategory.checked" />
    </td>
</code>```

model for deviceCategory

```<code> export interface DeviceCategoryViewModel {
        id?: number;
        name?: string;
        checked?:boolean;
    }
</code>```

ts code to get the current checked boxes.

```<code>  console.log(this.deviceCategories.filter(d=>d.checked===true));
</code>```

Body:
I am new to Angular, and I want to get the current selected checkbox id. I have checked other threads in SO, but most of them are using with Controller, I am using in component.

Here is detailed information.
I have such a component

test

        序列
        组名
        LOGO
        操作

            <input type="checkbox" ng-model="selected[deviceCategory.id]" id="checkbox_{{deviceCategory.id}}">

        {{deviceCategory.id}}
        {{deviceCategory.name}}

              修改
              删除

And here is my ts

import { Component, OnInit, Input } from '@angular/core';
import { PaginationInstance } from 'ng2-pagination';
import { DeviceCategoryService}from '../../../services/deviceCategory.service';
import { DeviceCategoryViewModel } from "../../../model/deviceCategory";

@Component({
  selector: 'app-device-category-admin-table',
  templateUrl: './device-category-admin-table.component.html',
  styleUrls: ['./device-category-admin-table.component.css'],
  providers:[DeviceCategoryService]
})
export class DeviceCategoryAdminTableComponent implements OnInit {

  @Input() deviceCategories :any;
  @Input() config:any;

  public selected:{}

  constructor(
    private deviceCategorySvc:DeviceCategoryService
  ) { }

  ngOnInit() {
  }

  OnDelete(id:number){
      this.deviceCategorySvc.deleteDeviceCategory(id).subscribe(result=>{
          if(result.ok)
          {
            this.deviceCategorySvc.currentCategorys().subscribe(result=>{
              this.deviceCategories=result.data as DeviceCategoryViewModel[];
            });

          }

      });
  }
  test(){
    var result=this.selected;
      console.log(result);
  }

Any help would be appreciated.

Body:
With the suggestion from @Sajeetharan, I could achieve my requirement by below code.

html

   <td class="text-center">
        <input type="checkbox" [(ngModel)]="deviceCategory.checked" />
    </td>

model for deviceCategory

 export interface DeviceCategoryViewModel {
        id?: number;
        name?: string;
        checked?:boolean;
    }

ts code to get the current checked boxes.

  console.log(this.deviceCategories.filter(d=>d.checked===true));


问:
Umbraco Application BeginRequest never fired
I want to fire the BeginRequest event in Umbraco but it doesn't work. The rest of the code works just fine.

```<code>public class ApplicationEventHandler : IApplicationEventHandler
{
    public void OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { }

    public void OnApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { }

    public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        umbracoApplication.BeginRequest += umbracoApplication_BeginRequest;

        BundleConfig.RegisterBundles(BundleTable.Bundles);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }

    void umbracoApplication_BeginRequest(object sender, EventArgs e)
    {
        // Create HttpApplication and HttpContext objects to access
        // request and response properties.
        UmbracoApplicationBase application = (UmbracoApplicationBase)sender;
        HttpContext context = application.Context;

        if (context.Response.Cookies[Const.LANGUAGE_COOKIE_NAME] == null)
        {
            context.Response.Cookies.Add(new HttpCookie(Const.LANGUAGE_COOKIE_NAME, Thread.CurrentThread.CurrentUICulture.Name));
            return;
        }

        //cookie exists already
        else
        {
            //if no 404
            if (UmbracoContext.Current.PublishedContentRequest != null && !UmbracoContext.Current.PublishedContentRequest.Is404)
            {
                //cookie value different than the current thread: user switched language.
                if (context.Response.Cookies[Const.LANGUAGE_COOKIE_NAME].Value != Thread.CurrentThread.CurrentUICulture.Name)
                {
                    //we set the cookie
                    context.Response.Cookies[Const.LANGUAGE_COOKIE_NAME].Value = Thread.CurrentThread.CurrentUICulture.Name;
                }
            }
        }
    }
}
</code>```

Do you have any idea why it is not working ?
I am using umbraco 7, local IIS (not express) and I can't log messages inside the function umbracoApplication_BeginRequest.

答:
First, you should create a HttpModel class that inherit System.Web.IHttpModule interface

```<code>public class HttpModule : IHttpModule
{
    void IHttpModule.Init(HttpApplication context)
    {
        context.BeginRequest += ContextBeginRequest;
    }

    private void ContextBeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;

        if (app != null)
        {
            //do stuff
        }
    }

    void IHttpModule.Dispose()
    {
        // Nothing to dispose;
    }
}
</code>```

Then, in your web.config

```<code><system.webServer><modules runAllManagedModulesForAllRequests="true">
  <remove name="DoStuff" />
  <add name="DoStuff" type="YourNameSpace.HttpModule, YourAssembly" /></modules></system.webServer>
</code>```

Body:
I want to fire the BeginRequest event in Umbraco but it doesn't work. The rest of the code works just fine.

public class ApplicationEventHandler : IApplicationEventHandler
{
    public void OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { }

    public void OnApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { }

    public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        umbracoApplication.BeginRequest += umbracoApplication_BeginRequest;

        BundleConfig.RegisterBundles(BundleTable.Bundles);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }

    void umbracoApplication_BeginRequest(object sender, EventArgs e)
    {
        // Create HttpApplication and HttpContext objects to access
        // request and response properties.
        UmbracoApplicationBase application = (UmbracoApplicationBase)sender;
        HttpContext context = application.Context;

        if (context.Response.Cookies[Const.LANGUAGE_COOKIE_NAME] == null)
        {
            context.Response.Cookies.Add(new HttpCookie(Const.LANGUAGE_COOKIE_NAME, Thread.CurrentThread.CurrentUICulture.Name));
            return;
        }

        //cookie exists already
        else
        {
            //if no 404
            if (UmbracoContext.Current.PublishedContentRequest != null && !UmbracoContext.Current.PublishedContentRequest.Is404)
            {
                //cookie value different than the current thread: user switched language.
                if (context.Response.Cookies[Const.LANGUAGE_COOKIE_NAME].Value != Thread.CurrentThread.CurrentUICulture.Name)
                {
                    //we set the cookie
                    context.Response.Cookies[Const.LANGUAGE_COOKIE_NAME].Value = Thread.CurrentThread.CurrentUICulture.Name;
                }
            }
        }
    }
}

Do you have any idea why it is not working ?
I am using umbraco 7, local IIS (not express) and I can't log messages inside the function umbracoApplication_BeginRequest.

Body:
First, you should create a HttpModel class that inherit System.Web.IHttpModule interface

public class HttpModule : IHttpModule
{
    void IHttpModule.Init(HttpApplication context)
    {
        context.BeginRequest += ContextBeginRequest;
    }

    private void ContextBeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;

        if (app != null)
        {
            //do stuff
        }
    }

    void IHttpModule.Dispose()
    {
        // Nothing to dispose;
    }
}

Then, in your web.config

<system.webServer><modules runAllManagedModulesForAllRequests="true">
  <remove name="DoStuff" />
  <add name="DoStuff" type="YourNameSpace.HttpModule, YourAssembly" /></modules></system.webServer>


问:
boto3 can't delete AWS tags
boto3 mentioned on Github that they added support for deleting tags. However, when I execute the code below, it throws an exception:

```<code>ec2 = boto3.resource('ec2', region_name=aws_region)
ec2.delete_tags(Resources=[instance.id],Tags=[{"Key": non_compliant_tag_name}])

'ec2.ServiceResource' object has no attribute 'delete_tags'

$ pip show boto3
Name: boto3
Version: 1.4.4
</code>```

What am I doing wrong?

答:
The delete_tags() method should be called on a client object rather than a resource object:

```<code>import boto3
client = boto3.client('ec2', region_name='ap-southeast-2')
...
client.delete_tags(Resources=[instance.id],Tags=[{"Key": non_compliant_tag_name}])
</code>```

ContentLicense: CC BY-SA 4.0

Title: boto3 can't delete AWS tags

Body:
boto3 mentioned on Github that they added support for deleting tags. However, when I execute the code below, it throws an exception:

ec2 = boto3.resource('ec2', region_name=aws_region)
ec2.delete_tags(Resources=[instance.id],Tags=[{"Key": non_compliant_tag_name}])

'ec2.ServiceResource' object has no attribute 'delete_tags'

$ pip show boto3
Name: boto3
Version: 1.4.4

What am I doing wrong?

Body:
The delete_tags() method should be called on a client object rather than a resource object:

import boto3
client = boto3.client('ec2', region_name='ap-southeast-2')
...
client.delete_tags(Resources=[instance.id],Tags=[{"Key": non_compliant_tag_name}])


问:
How to install Rails without using sudo gem install
I have installed rbenv using Homebrew.

```<code>$ rbenv local
2.4.0

$ rbenv global
2.4.0

$ ruby -v
ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-darwin16]
</code>```

When I check the Rails version I get the following message;

```<code>Rails is not currently installed on this system. To get the latest version, simply type:

$ sudo gem install rails

You can then rerun your "rails" command.
</code>```

I have been told not to install Rails using sudo, so I have tried running gem install rails but it gives me the following error;

```<code>ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied @ rb_sysopen -        /Users/USER1/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/thread_safe-0.3.6/.rspec
</code>```

Is it correct that I should not install rails with sudo, and if so how can I?

答:
I installed RVM (requires download and use of GPG) and followed the steps on RVM's install page.  Should you use sudo? I've read both ways.  Here is the page link:

https://rvm.io/rvm/install

The command once RVM is installed:

```<code>\curl -sSL https://get.rvm.io | bash -s stable --rails
</code>```

That will install the latest stable version of rails available.  I did this as a complete novice and it has worked for me (as a slightly higher novice) so far.

Body:
I have installed rbenv using Homebrew.

$ rbenv local
2.4.0

$ rbenv global
2.4.0

$ ruby -v
ruby 2.4.0p0 (2016-12-24 revision 57164) [x86_64-darwin16]

When I check the Rails version I get the following message;

Rails is not currently installed on this system. To get the latest version, simply type:

$ sudo gem install rails

You can then rerun your "rails" command.

I have been told not to install Rails using sudo, so I have tried running gem install rails but it gives me the following error;

ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied @ rb_sysopen -        /Users/USER1/.rbenv/versions/2.4.0/lib/ruby/gems/2.4.0/gems/thread_safe-0.3.6/.rspec

Is it correct that I should not install rails with sudo, and if so how can I?

Body:
I installed RVM (requires download and use of GPG) and followed the steps on RVM's install page.  Should you use sudo? I've read both ways.  Here is the page link:

https://rvm.io/rvm/install

The command once RVM is installed:

\curl -sSL https://get.rvm.io | bash -s stable --rails

That will install the latest stable version of rails available.  I did this as a complete novice and it has worked for me (as a slightly higher novice) so far.


问:
Flash Builder keeps changing perspectives. Need to reset
I have accidentally setup my Flash Builder to change to the Debug Perspective when debugging my applications. This is useful when the application crashes, but not every run.

I can´t seem to find the settings to change it back to default. Anyone know where to look?

答:
Under Window --> Preferences in Run/Debug --> Perspectives there is an option there "Open the associated perspective when an application suspends". The default is "Prompt" which is what will ask you if you want to switch to the Debug Perspective when the application encounters something. Alternatively you could set it to Never which means you will always have to switch perspectives manually.

Cheers


问:
get info from a specific user in mysql database using php
When i enter a user id that is in the database, i want it to echo/print all the data from that one users file. So if i enter "user_id = 2", i want the users "name", "age" etc etc. I got to where that it gives me everything without the parameters. The code:

```<code>$link = mysqli_connect("localhost", "root", "");
mysqli_select_db($link, "magicsever");

if(mysqli_connect_error()){
    die ("Database connection error");
}

$query = "SELECT * FROM classified_videos";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result)){
    print_r ($row);
}
</code>```

But i want from a specific user and this is what i think is the code

```<code>if(isset($_POST['submit'])){

    $link = mysqli_connect("localhost", "root", "");
    mysqli_select_db($link, "magicsever");

    if(mysqli_connect_error()){
        die ("Database connection error");
    }

    $query = "SELECT * FROM classified_videos WHERE user_id ='".mysqli_real_escape_string($link, $_POST['userid'])."' LIMIT 1";
    $result = mysqli_query($link, $query);
    while($row = mysqli_fetch_array($result)){
        print_r ($row['vid_category_1']);
    }
}
?>

<form method="post">
    <input type="text" name="userid" placeholder="user id...">
    <input type="submit" value="submit">
</form>
</code>```

答:
This if(isset($_POST['submit'])) expects that an input with name submit is submitted, but youre currently sending only userid

add this name="submit" to your button:

```<code><input type="submit" value="submit" name="submit">
</code>```

Body:
When i enter a user id that is in the database, i want it to echo/print all the data from that one users file. So if i enter "user_id = 2", i want the users "name", "age" etc etc. I got to where that it gives me everything without the parameters. The code:

$link = mysqli_connect("localhost", "root", "");
mysqli_select_db($link, "magicsever");

if(mysqli_connect_error()){
    die ("Database connection error");
}

$query = "SELECT * FROM classified_videos";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_array($result)){
    print_r ($row);
}

But i want from a specific user and this is what i think is the code

if(isset($_POST['submit'])){

    $link = mysqli_connect("localhost", "root", "");
    mysqli_select_db($link, "magicsever");

    if(mysqli_connect_error()){
        die ("Database connection error");
    }

    $query = "SELECT * FROM classified_videos WHERE user_id ='".mysqli_real_escape_string($link, $_POST['userid'])."' LIMIT 1";
    $result = mysqli_query($link, $query);
    while($row = mysqli_fetch_array($result)){
        print_r ($row['vid_category_1']);
    }
}
?>

<form method="post">
    <input type="text" name="userid" placeholder="user id...">
    <input type="submit" value="submit">
</form>

Body:
This if(isset($_POST['submit'])) expects that an input with name submit is submitted, but youre currently sending only userid

add this name="submit" to your button:

<input type="submit" value="submit" name="submit">


问:
How to apply multiple masks to an array and count occurrences per row
Let's say I have a 2D array with positive integers:

```<code>a = numpy.array([[1, 1, 2],
                 [1, 2, 5],
                 [1, 3, 6],
                 [3, 3, 3],
                 [3, 4, 6],
                 [4, 5, 6],
                ])
</code>```

and a threshold (positive integer). I want to count, for each row, how many ocurrences are < threshold, how many >= threshold and < threshold+2, and how many >= threshold+2. The results are to be stored on a size 3 x n array, where n = a.shape[0] and each of the 3 columns corresponds to the threshold partition.

For the example above and threshold = 3, it would be:

```<code>b = numpy.array([[3, 0, 0],
                 [2, 0, 1],
                 [1, 1, 1],
                 [0, 3, 0],
                 [0, 2, 1],
                 [0, 1, 2],
                ])
</code>```

My solution was to use a for loop combined with masks, so that I could apply the masks individually for each row. But using for loops on arrays feels wrong. Is there a more optimized way to accomplish that?

My solution so far:

```<code>b = []
for row in a:
    b.append((numpy.sum(row < threshold),
              numpy.sum((row >= threshold) * (row < threshold + 2)),
              numpy.sum(row >= threshold + 2)))
b = numpy.array(b)
</code>```

答:
You have to break points 3 and 5.  We can use np.searchsorted to find where each element of a falls with respect to our break points.

np.searchsorted([3, 5], 1, side='right') will return 0 because 1 should be inserted at position 0 to maintain sorted-ness.

np.searchsorted([3, 5], 3, side='right') will return 1 because 3 can be inserted at position 0 or any other in which a value of 3 occupies to maintain sorted-ness.  The default behavior to insert to the left of elements that are equal.  We can change this to insert to the right of all elements that are equal.  This accounts for the condition < threshold

np.searchsorted([3, 5], 5) will return 1

np.searchsorted([3, 5], 7) will return 2

I use np.eye to build sub arrays to sum over in order to count how many fall within each bin.

```<code>np.eye(3, dtype=int)[np.searchsorted([3, 5], a, side='right')].sum(1)

array([[3, 0, 0],
       [2, 0, 1],
       [1, 1, 1],
       [0, 3, 0],
       [0, 2, 1],
       [0, 1, 2]])
</code>```

We can generalize this with a function

```<code>def count_bins(a, threshold, interval_sizes):
    edges = np.append(threshold, interval_sizes).cumsum()
    eye = np.eye(edges.size + 1, dtype=int)
    return eye[edges.searchsorted(a, side='right')].sum(1)

count_bins(a, 3, [2])

array([[3, 0, 0],
       [2, 0, 1],
       [1, 1, 1],
       [0, 3, 0],
       [0, 2, 1],
       [0, 1, 2]])
</code>```

Or

```<code>count_bins(a, 3, [1, 1])

array([[3, 0, 0, 0],
       [2, 0, 0, 1],
       [1, 1, 0, 1],
       [0, 3, 0, 0],
       [0, 1, 1, 1],
       [0, 0, 1, 2]])
</code>```

But I'd rather return a pandas dataframe to see things more clearly

```<code>def count_bins(a, threshold, interval_sizes):
    edges = np.append(threshold, interval_sizes).cumsum()
    eye = np.eye(edges.size + 1, dtype=int)
    labels = ['{:0.0f} to {:0.0f}'.format(i, j) for i, j in zip(np.append(-np.inf, edges), np.append(edges, np.inf))]
    return pd.DataFrame(
        eye[edges.searchsorted(a, side='right')].sum(1),
        columns=labels
    )

count_bins(a, 3, [2])

   -inf to 3  3 to 5  5 to inf
0          3       0         0
1          2       0         1
2          1       1         1
3          0       3         0
4          0       2         1
5          0       1         2
</code>```

Body:
Let's say I have a 2D array with positive integers:

a = numpy.array([[1, 1, 2],
                 [1, 2, 5],
                 [1, 3, 6],
                 [3, 3, 3],
                 [3, 4, 6],
                 [4, 5, 6],
                ])

and a threshold (positive integer). I want to count, for each row, how many ocurrences are < threshold, how many >= threshold and < threshold+2, and how many >= threshold+2. The results are to be stored on a size 3 x n array, where n = a.shape[0] and each of the 3 columns corresponds to the threshold partition.

For the example above and threshold = 3, it would be:

b = numpy.array([[3, 0, 0],
                 [2, 0, 1],
                 [1, 1, 1],
                 [0, 3, 0],
                 [0, 2, 1],
                 [0, 1, 2],
                ])

My solution was to use a for loop combined with masks, so that I could apply the masks individually for each row. But using for loops on arrays feels wrong. Is there a more optimized way to accomplish that?

My solution so far:

b = []
for row in a:
    b.append((numpy.sum(row < threshold),
              numpy.sum((row >= threshold) * (row < threshold + 2)),
              numpy.sum(row >= threshold + 2)))
b = numpy.array(b)

Body:
You have to break points 3 and 5.  We can use np.searchsorted to find where each element of a falls with respect to our break points.

np.searchsorted([3, 5], 1, side='right') will return 0 because 1 should be inserted at position 0 to maintain sorted-ness.

np.searchsorted([3, 5], 3, side='right') will return 1 because 3 can be inserted at position 0 or any other in which a value of 3 occupies to maintain sorted-ness.  The default behavior to insert to the left of elements that are equal.  We can change this to insert to the right of all elements that are equal.  This accounts for the condition < threshold

np.searchsorted([3, 5], 5) will return 1

np.searchsorted([3, 5], 7) will return 2

I use np.eye to build sub arrays to sum over in order to count how many fall within each bin.

np.eye(3, dtype=int)[np.searchsorted([3, 5], a, side='right')].sum(1)

array([[3, 0, 0],
       [2, 0, 1],
       [1, 1, 1],
       [0, 3, 0],
       [0, 2, 1],
       [0, 1, 2]])

We can generalize this with a function

def count_bins(a, threshold, interval_sizes):
    edges = np.append(threshold, interval_sizes).cumsum()
    eye = np.eye(edges.size + 1, dtype=int)
    return eye[edges.searchsorted(a, side='right')].sum(1)

count_bins(a, 3, [2])

array([[3, 0, 0],
       [2, 0, 1],
       [1, 1, 1],
       [0, 3, 0],
       [0, 2, 1],
       [0, 1, 2]])

Or

count_bins(a, 3, [1, 1])

array([[3, 0, 0, 0],
       [2, 0, 0, 1],
       [1, 1, 0, 1],
       [0, 3, 0, 0],
       [0, 1, 1, 1],
       [0, 0, 1, 2]])

But I'd rather return a pandas dataframe to see things more clearly

def count_bins(a, threshold, interval_sizes):
    edges = np.append(threshold, interval_sizes).cumsum()
    eye = np.eye(edges.size + 1, dtype=int)
    labels = ['{:0.0f} to {:0.0f}'.format(i, j) for i, j in zip(np.append(-np.inf, edges), np.append(edges, np.inf))]
    return pd.DataFrame(
        eye[edges.searchsorted(a, side='right')].sum(1),
        columns=labels
    )

count_bins(a, 3, [2])

   -inf to 3  3 to 5  5 to inf
0          3       0         0
1          2       0         1
2          1       1         1
3          0       3         0
4          0       2         1
5          0       1         2


问:
Why won't my code run on my physical device (iOS)
I'm building a practice app from scratch again with React Native to start off fresh. On my previous project, I ran code on my iPhone 5 (physical device) just fine with Xcode.

But now, since I started a brand new project, it gives me these errors when I run my code on Xcode (when I hit the play button):

Signing for "myAppName" requires a development team. Select a development team in the project editor.

Code signing is required for product type 'Unit Test Bundle' in SDK 'iOS 10.2'

The thing is, I'm already in a development team that of which I selected under Signing in Xcode.

I remember when doing my old project, I had to verify my account or something like that on my iPhone by navigating to Settings > General and then after that I had verify my app so that it can successfully run on my iPhone.

I've searched this up on SO for quite some time and the answers that I'm seeing aren't rectifying my issue.

答: what does it say for your signing team? Also check the preferences to see if you have the agent or the personal team selected. It needs to be the Agent. If that doesnt work, can you send a screenshot to supply more info?


问:
unable to parse simple grammar using antlr4
I am doing some hands-on with antlr4 for parsing a file and seem to be stuck with an issue that has keep me awake for few hours now.. Following is the simple grammar i have defined in ESQLGrammar.g4 file that is placed in my projects src/main/antlr4.

grammar ESQLGrammar;

esqlCode:
    declBrokerSchema? esqlContents;

declBrokerSchema
    :   BROKER SCHEMA schemaName (PATH schemaPathList ';')?;
schemaName
    :   IDENTIFIER;
schemaPathList
    :   IDENTIFIER (',' IDENTIFIER)*;

esqlContents
    :   (declareVariable)*?;

declareVariable
    :   DECLARE variableNames esqlDataType ';';
variableNames
    :   variableName (',' variableName)*;
variableName
    :   IDENTIFIER;
esqlDataType
    :   (BLOB|CHARACTER|BOOLEAN|NAMESPACE);

WS              :   [ \r\t\n]+    -> skip ;
IDENTIFIER      :   [a-zA-Z_][a-zA-Z0-9_.]*;

BROKER  :   'BROKER';
SCHEMA  :   'SCHEMA';
PATH    :   'PATH';
DECLARE :   'DECLARE';
BLOB        :   'BLOB';
CHARACTER   :   'CHARACTER';
BOOLEAN :   'BOOLEAN';
NAMESPACE   :   'NAMESPACE';
```

<p>My Input is a file </p>

```BROKER SCHEMA nameOfSchema PATH pathVal1,pathVal2;
DECLARE iSharedVar CHARACTER;
```

<p>However, when i change the grammar lines as below to use fixed keywords with extra spaces in them </p>

```declBrokerSchema
    :   'BROKER SCHEMA ' schemaName ('PATH ' schemaPathList ';')?;
// Notice the keywords in ' ' with extra space at end.
declareVariable
    :   'DECLARE ' variableNames esqlDataType ';';
```

<p>then it seems to parse the lines and throws the error provided below:</p>

```line 2:19 mismatched input 'CHARACTER' expecting {'BLOB', 'CHARACTER', 'BOOLEAN', 'NAMESPACE'}

DeclBrokerSchema(schemaName=nameOfSchema, schemaPathList=pathVal1,pathVal2)
[DeclareVariable(varibleNames=iSharedVar, dataType=CHARACTER, defultValue=null, modifier=null, isConstant=false, aliasType=null, initialValueExpression=null)]
```

which appears to recognise it but with an error. So need your expert view on these:

I can't find any of the rules that could have matched 'CHARACTER' during the lexer phase.. then why does it throw an error ?

Also, why does it require me to use the tokens in ' ' that too with an extra space? If i remove the space it fails to parse it..

Am i missing something here .. pls help..!

答:
Your original grammar is fine, except for a small but significant error in your lexer rules. As a result of this error, almost all of your input is being tokenized by the lexer as an IDENTIFIER:

```<code>[@0,0:5='BROKER',<IDENTIFIER>,1:0]
[@1,7:12='SCHEMA',<IDENTIFIER>,1:7]
[@2,14:25='nameOfSchema',<IDENTIFIER>,1:14]
[@3,27:30='PATH',<IDENTIFIER>,1:27]
[@4,32:39='pathVal1',<IDENTIFIER>,1:32]
[@5,40:40=',',<','>,1:40]
[@6,41:48='pathVal2',<IDENTIFIER>,1:41]
[@7,49:49=';',<';'>,1:49]
[@8,52:58='DECLARE',<IDENTIFIER>,2:0]
[@9,60:69='iSharedVar',<IDENTIFIER>,2:8]
[@10,71:79='CHARACTER',<IDENTIFIER>,2:19]
[@11,80:80=';',<';'>,2:28]
[@12,83:82='<EOF>',<EOF>,3:0]
</code>```

So let's fix that by moving the lexer rule for IDENTIFIER to the bottom so that that rule doesn't match before everything else:

```<code>etc...
BLOB        :   'BLOB';
CHARACTER   :   'CHARACTER';
BOOLEAN :   'BOOLEAN';
NAMESPACE   :   'NAMESPACE';
IDENTIFIER      :   [a-zA-Z_][a-zA-Z0-9._]*;
</code>```

Now if you run it the lexer tokenizes the way you'd expect:

```<code>[@0,0:5='BROKER',<'BROKER'>,1:0]
[@1,7:12='SCHEMA',<'SCHEMA'>,1:7]
[@2,14:25='nameOfSchema',<IDENTIFIER>,1:14]
[@3,27:30='PATH',<'PATH'>,1:27]
[@4,32:39='pathVal1',<IDENTIFIER>,1:32]
[@5,40:40=',',<','>,1:40]
[@6,41:48='pathVal2',<IDENTIFIER>,1:41]
[@7,49:49=';',<';'>,1:49]
[@8,52:58='DECLARE',<'DECLARE'>,2:0]
[@9,60:69='iSharedVar',<IDENTIFIER>,2:8]
[@10,71:79='CHARACTER',<'CHARACTER'>,2:19]
[@11,80:80=';',<';'>,2:28]
[@12,83:82='<EOF>',<EOF>,3:0]
</code>```

Now it works.  The order of lexer rules matters.  Remember that rules are evaluated top to bottom.  ;)

Body:
I am doing some hands-on with antlr4 for parsing a file and seem to be stuck with an issue that has keep me awake for few hours now.. Following is the simple grammar i have defined in ESQLGrammar.g4 file that is placed in my projects src/main/antlr4.

grammar ESQLGrammar;

esqlCode:
    declBrokerSchema? esqlContents;

declBrokerSchema
    :   BROKER SCHEMA schemaName (PATH schemaPathList ';')?;
schemaName
    :   IDENTIFIER;
schemaPathList
    :   IDENTIFIER (',' IDENTIFIER)*;

esqlContents
    :   (declareVariable)*?;

declareVariable
    :   DECLARE variableNames esqlDataType ';';
variableNames
    :   variableName (',' variableName)*;
variableName
    :   IDENTIFIER;
esqlDataType
    :   (BLOB|CHARACTER|BOOLEAN|NAMESPACE);

WS              :   [ \r\t\n]+    -> skip ;
IDENTIFIER      :   [a-zA-Z_][a-zA-Z0-9_.]*;

BROKER  :   'BROKER';
SCHEMA  :   'SCHEMA';
PATH    :   'PATH';
DECLARE :   'DECLARE';
BLOB        :   'BLOB';
CHARACTER   :   'CHARACTER';
BOOLEAN :   'BOOLEAN';
NAMESPACE   :   'NAMESPACE';

My Input is a file

BROKER SCHEMA nameOfSchema PATH pathVal1,pathVal2;
DECLARE iSharedVar CHARACTER;

However, when i change the grammar lines as below to use fixed keywords with extra spaces in them

declBrokerSchema
    :   'BROKER SCHEMA ' schemaName ('PATH ' schemaPathList ';')?;
// Notice the keywords in ' ' with extra space at end.
declareVariable
    :   'DECLARE ' variableNames esqlDataType ';';

then it seems to parse the lines and throws the error provided below:

line 2:19 mismatched input 'CHARACTER' expecting {'BLOB', 'CHARACTER', 'BOOLEAN', 'NAMESPACE'}

DeclBrokerSchema(schemaName=nameOfSchema, schemaPathList=pathVal1,pathVal2)
[DeclareVariable(varibleNames=iSharedVar, dataType=CHARACTER, defultValue=null, modifier=null, isConstant=false, aliasType=null, initialValueExpression=null)]

which appears to recognise it but with an error. So need your expert view on these:

I can't find any of the rules that could have matched 'CHARACTER' during the lexer phase.. then why does it throw an error ?

Also, why does it require me to use the tokens in ' ' that too with an extra space? If i remove the space it fails to parse it..

Am i missing something here .. pls help..!

Body:
Your original grammar is fine, except for a small but significant error in your lexer rules. As a result of this error, almost all of your input is being tokenized by the lexer as an IDENTIFIER:

[@0,0:5='BROKER',<IDENTIFIER>,1:0]
[@1,7:12='SCHEMA',<IDENTIFIER>,1:7]
[@2,14:25='nameOfSchema',<IDENTIFIER>,1:14]
[@3,27:30='PATH',<IDENTIFIER>,1:27]
[@4,32:39='pathVal1',<IDENTIFIER>,1:32]
[@5,40:40=',',<','>,1:40]
[@6,41:48='pathVal2',<IDENTIFIER>,1:41]
[@7,49:49=';',<';'>,1:49]
[@8,52:58='DECLARE',<IDENTIFIER>,2:0]
[@9,60:69='iSharedVar',<IDENTIFIER>,2:8]
[@10,71:79='CHARACTER',<IDENTIFIER>,2:19]
[@11,80:80=';',<';'>,2:28]
[@12,83:82='<EOF>',<EOF>,3:0]

So let's fix that by moving the lexer rule for IDENTIFIER to the bottom so that that rule doesn't match before everything else:

etc...
BLOB        :   'BLOB';
CHARACTER   :   'CHARACTER';
BOOLEAN :   'BOOLEAN';
NAMESPACE   :   'NAMESPACE';
IDENTIFIER      :   [a-zA-Z_][a-zA-Z0-9._]*;

Now if you run it the lexer tokenizes the way you'd expect:

[@0,0:5='BROKER',<'BROKER'>,1:0]
[@1,7:12='SCHEMA',<'SCHEMA'>,1:7]
[@2,14:25='nameOfSchema',<IDENTIFIER>,1:14]
[@3,27:30='PATH',<'PATH'>,1:27]
[@4,32:39='pathVal1',<IDENTIFIER>,1:32]
[@5,40:40=',',<','>,1:40]
[@6,41:48='pathVal2',<IDENTIFIER>,1:41]
[@7,49:49=';',<';'>,1:49]
[@8,52:58='DECLARE',<'DECLARE'>,2:0]
[@9,60:69='iSharedVar',<IDENTIFIER>,2:8]
[@10,71:79='CHARACTER',<'CHARACTER'>,2:19]
[@11,80:80=';',<';'>,2:28]
[@12,83:82='<EOF>',<EOF>,3:0]

Now it works.  The order of lexer rules matters.  Remember that rules are evaluated top to bottom.  ;)


问:
DateTime.ParseExact to NodaTime ZonedDateTime issue
I'm having an issue converting a parsed string into a correct NodaTime ZonedDateTime. The below method takes a string (allegedly in UTC) pushed by the brokers server, and returns a ZonedDateTime with the DateTimeZone being set to UTC. The domain model will only accept ZonedDateTime objects so this is happening at the system boundary.

For example, a string being passed as the argument being exactly '2017060623:20:10' would then return a ZonedDateTime like 2017-06-06T13-:20:10 (curiously a ten hour difference, my local time zone here in Sydney is +10 UTC).

```<code>public static ZonedDateTime GetZonedDateTimeUtcFromMarketDataString(string dateTime)
{
    var dotNetDateTime = DateTime.ParseExact(
        dateTime,
        "yyyyMMddHH:mm:ss,
        CultureInfo.InvariantCulture)
        .ToUniversalTime();

    return new ZonedDateTime(Instant.FromDateTimeUtc(dotNetDateTime), DateTimeZone.Utc);
}
</code>```

So I changed the method to the below, which works, but I'm sure there's a better way. I'm certain my error is that I'm somehow involving my local time zone, rather than keeping everything in UTC.

```<code>public static ZonedDateTime GetZonedDateTimeUtcFromMarketDataString(string dateTime)
{
    var parsedDateTime = DateTime.ParseExact(
        dateTime,
        "yyyyMMddHH:mm:ss",
        CultureInfo.InvariantCulture);

    var dotNetDateTime = new DateTime(
        parsedDateTime.Year,
        parsedDateTime.Month,
        parsedDateTime.Day,
        parsedDateTime.Hour,
        parsedDateTime.Minute,
        parsedDateTime.Second,
        DateTimeKind.Utc);

    return new ZonedDateTime(Instant.FromDateTimeUtc(dotNetDateTime), DateTimeZone.Utc);
}
</code>```

答:
The DateTime.ParseExact function can take DateTimeStyle as a parameter.

Try this

```<code>var parsedDateTime = DateTime.ParseExact(
    dateTime,
    "yyyyMMddHH:mm:ss",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
</code>```

Body:
I'm having an issue converting a parsed string into a correct NodaTime ZonedDateTime. The below method takes a string (allegedly in UTC) pushed by the brokers server, and returns a ZonedDateTime with the DateTimeZone being set to UTC. The domain model will only accept ZonedDateTime objects so this is happening at the system boundary.

For example, a string being passed as the argument being exactly '2017060623:20:10' would then return a ZonedDateTime like 2017-06-06T13-:20:10 (curiously a ten hour difference, my local time zone here in Sydney is +10 UTC).

public static ZonedDateTime GetZonedDateTimeUtcFromMarketDataString(string dateTime)
{
    var dotNetDateTime = DateTime.ParseExact(
        dateTime,
        "yyyyMMddHH:mm:ss,
        CultureInfo.InvariantCulture)
        .ToUniversalTime();

    return new ZonedDateTime(Instant.FromDateTimeUtc(dotNetDateTime), DateTimeZone.Utc);
}

So I changed the method to the below, which works, but I'm sure there's a better way. I'm certain my error is that I'm somehow involving my local time zone, rather than keeping everything in UTC.

public static ZonedDateTime GetZonedDateTimeUtcFromMarketDataString(string dateTime)
{
    var parsedDateTime = DateTime.ParseExact(
        dateTime,
        "yyyyMMddHH:mm:ss",
        CultureInfo.InvariantCulture);

    var dotNetDateTime = new DateTime(
        parsedDateTime.Year,
        parsedDateTime.Month,
        parsedDateTime.Day,
        parsedDateTime.Hour,
        parsedDateTime.Minute,
        parsedDateTime.Second,
        DateTimeKind.Utc);

    return new ZonedDateTime(Instant.FromDateTimeUtc(dotNetDateTime), DateTimeZone.Utc);
}

Body:
The DateTime.ParseExact function can take DateTimeStyle as a parameter.

Try this

var parsedDateTime = DateTime.ParseExact(
    dateTime,
    "yyyyMMddHH:mm:ss",
    CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);


问:
how to add grand child element in xml child elements section C# XML
I want to add a 3rd level grand child section into my XML.

Before:

```<code><level1>
    <level2>
          <coolstuff name="name"/>
    </level2>
</level1>
</code>```

After:

```<code><level1>
    <level2>
          <stupidtags>
               <stupidtag name ="stupidname"/>
          <stupidtags>
          <coolstuff name="coolname"/>
    </level2>
</level1>
</code>```

How should I add the stupidtags into the level2 tag in C#?
I implement a little bit, how should i pass two level and let newNode append it that and it should above coolstuff tag?

```<code>XDocument doc = XDocument.Load(fileOfReportInXML);
XElement newNode= new XElement("stupidtags");
</code>```

答:
Using xml linq (XDocument)</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<level1>" +
                    "<level2>" +
                          "<coolstuff name=\"name\"/>" +
                    "</level2>" +
                "</level1>";

            XDocument doc = XDocument.Parse(xml);

            XElement level2 = doc.Descendants("level2").FirstOrDefault();

            level2.Add(new XElement("stupidtags", new object[] {
                    new XElement("stupidtag", new object[] {
                    new XAttribute("name", "stupidname")
                })
            }));
        }
    }
}
</code>```

Body:
I want to add a 3rd level grand child section into my XML.

Before:

<level1>
    <level2>
          <coolstuff name="name"/>
    </level2>
</level1>

After:

<level1>
    <level2>
          <stupidtags>
               <stupidtag name ="stupidname"/>
          <stupidtags>
          <coolstuff name="coolname"/>
    </level2>
</level1>

How should I add the stupidtags into the level2 tag in C#?
I implement a little bit, how should i pass two level and let newNode append it that and it should above coolstuff tag?

XDocument doc = XDocument.Load(fileOfReportInXML);
XElement newNode= new XElement("stupidtags");

Body:
Using xml linq (XDocument)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string xml =
                "<level1>" +
                    "<level2>" +
                          "<coolstuff name=\"name\"/>" +
                    "</level2>" +
                "</level1>";

            XDocument doc = XDocument.Parse(xml);

            XElement level2 = doc.Descendants("level2").FirstOrDefault();

            level2.Add(new XElement("stupidtags", new object[] {
                    new XElement("stupidtag", new object[] {
                    new XAttribute("name", "stupidname")
                })
            }));
        }
    }
}


问:
How to develop site which dynamically changes og:image facebook property?
Basically, I am making a website which has dynamic og:image property. I have added 100 images and changing the images by rand function in PHP.
The problem I am getting is that Facebook have cached my website and everytime user shares the URL, it shows the same image every time. I want Facebook to recrawl everytime the link is posted and shows random images.

Here is the code of the page I have developed:

```<code><html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1">
        <meta name="twitter:card" value="summary">

        <meta property="fb:app_id" content="xxxxxxxxxxxxx10" />
        <meta property="og:description" content="Like it? Share with friends... "/>
        <meta property="og:title" content="Your future company is" />
        <meta property="og:type" content="article" />
        <meta property="og:url" content="http://justtodo.xyz/company/" />
        <?php
            $imageURL = 'http://justtodo.xyz/company/images/' . rand(1, 100) . '_260x135.jpg';
        ?>
        <meta property="og:image" content="<?php echo($imageURL)?>"  />
        <meta property="og:image:type" content="image/jpeg" />
        <meta property="og:image:width" content="200" />
        <meta property="og:image:height" content="200" />

    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

      ga('create', 'UA-100487432-1', 'auto');
      ga('send', 'pageview');

    </script>

    <script  src="https://code.jquery.com/jquery-1.7.1.min.js"  integrity="sha256-iBcUE/x23aI6syuqF7EeT/+JFBxjPs5zeFJEXxumwb0="  crossorigin="anonymous"></script>

    <script>

    window.fbAsyncInit = function() {
        FB.init({
          appId            : 'xxxxxxxxxxxxx10',
          autoLogAppEvents : true,
          xfbml            : true,
          version          : 'v2.9'
        });
        FB.AppEvents.logPageView();
      };

      (function(d, s, id){
         var js, fjs = d.getElementsByTagName(s)[0];
         if (d.getElementById(id)) {return;}
         js = d.createElement(s); js.id = id;
         js.src = "//connect.facebook.net/en_US/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));

        FB.api('https://graph.facebook.com/', 'post', {
            id: '<?php echo($imageURL)?>',
            scrape: true
        }, function(response) {
            //console.log('rescrape!',response);
        });
    </script>

    <title>Your future company...</title>

    <META HTTP-EQUIV="REFRESH" CONTENT="0; URL=https://youtu.be/uqJNjb-zg3s">
    <script>
    setTimeout(function () {
    window.location.href = "https://youtu.be/uqJNjb-zg3s";
    },10);
    </script>

    </head>
<body>

    <div style="text-align: center;font-size:2em;font-family:Consolas, Andale Mono, Lucida Console,Lucida Sans Typewriter, Monaco, Courier New, monospace">Loading your company...</div>
</body>
</html>
</code>```

答:
Do you only have 100 pictures? I already have over 500 and I also want to know how you do it. This "Facebook comments game" has already turned into a fever. Well, as far as I've researched, there are 3 ways to change the Facebook cache image.
1.) Every 24 hours Facebook searches for a new image automatically (this is not useful for us).
2.) Using https://developers.facebook.com/tools/debug/ (I think we could do with the "extract again" button is in infinite loop, but I do not know how to do this and besides this only works while we have the site open in the browser).
3.) You can request the update with this AJAX code:

```<code>Var fbxhr = new XMLHttpRequest ();
fbxhr.open ("POST", "https://graph.facebook.com", true);
fbxhr.setRequestHeader ("Content-type", "application / x-www-form-urlencoded");
fbxhr.send ("id = http: //you_site.com/&scrape=true");
</code>```

This JavaScript code plus this tag:

```<code><Meta http-equiv = "refresh" content = "0"/>
</code>```

And with this PHP code:

```<code><Meta property = "og: image" content = "<? Php echo 'http://your_site.com/'.mt_rand(1,100).'.jpg';?>"/>
</code>```

This causes the page to be updated every 0 seconds and receive a new random image that can be named from "1.jpg" to "100.jpg".
Then request via AJAX that the image be updated.
You can also do the loop inside the Javascript itself, but you would have to make PHP out to be called inside the loop. I just have not tested it yet.

My problem is: this only works while I have my site open in the browser giving infinite refresh.

Edit: The response of this post was on 06/03/2017 the same day that this game began to appear. Only I do not understand anything about Python. Can you tell me how to put Python in my HTML?

Link: Dynamic Image for Facebook Opengraph og:image meta tag

Body:
Basically, I am making a website which has dynamic og:image property. I have added 100 images and changing the images by rand function in PHP.
The problem I am getting is that Facebook have cached my website and everytime user shares the URL, it shows the same image every time. I want Facebook to recrawl everytime the link is posted and shows random images.

Here is the code of the page I have developed:

        <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1">
        <meta name="twitter:card" value="summary">

        <meta property="fb:app_id" content="xxxxxxxxxxxxx10" />
        <meta property="og:description" content="Like it? Share with friends... "/>
        <meta property="og:title" content="Your future company is" />
        <meta property="og:type" content="article" />
        <meta property="og:url" content="http://justtodo.xyz/company/" />
        <?php
            $imageURL = 'http://justtodo.xyz/company/images/' . rand(1, 100) . '_260x135.jpg';
        ?>
        <meta property="og:image" content="<?php echo($imageURL)?>"  />
        <meta property="og:image:type" content="image/jpeg" />
        <meta property="og:image:width" content="200" />
        <meta property="og:image:height" content="200" />

    <title>Your future company...</title>

    <META HTTP-EQUIV="REFRESH" CONTENT="0; URL=https://youtu.be/uqJNjb-zg3s">

Loading your company...

Body:
Do you only have 100 pictures? I already have over 500 and I also want to know how you do it. This "Facebook comments game" has already turned into a fever. Well, as far as I've researched, there are 3 ways to change the Facebook cache image.
1.) Every 24 hours Facebook searches for a new image automatically (this is not useful for us).
2.) Using https://developers.facebook.com/tools/debug/ (I think we could do with the "extract again" button is in infinite loop, but I do not know how to do this and besides this only works while we have the site open in the browser).
3.) You can request the update with this AJAX code:

Var fbxhr = new XMLHttpRequest ();
fbxhr.open ("POST", "https://graph.facebook.com", true);
fbxhr.setRequestHeader ("Content-type", "application / x-www-form-urlencoded");
fbxhr.send ("id = http: //you_site.com/&scrape=true");

This JavaScript code plus this tag:

<Meta http-equiv = "refresh" content = "0"/>

And with this PHP code:

<Meta property = "og: image" content = "<? Php echo 'http://your_site.com/'.mt_rand(1,100).'.jpg';?>"/>

This causes the page to be updated every 0 seconds and receive a new random image that can be named from "1.jpg" to "100.jpg".
Then request via AJAX that the image be updated.
You can also do the loop inside the Javascript itself, but you would have to make PHP out to be called inside the loop. I just have not tested it yet.

My problem is: this only works while I have my site open in the browser giving infinite refresh.

Edit: The response of this post was on 06/03/2017 the same day that this game began to appear. Only I do not understand anything about Python. Can you tell me how to put Python in my HTML?

Link: Dynamic Image for Facebook Opengraph og:image meta tag


问:
how can i increase bootstrap modal height
I am simply trying to make a bootstrap modal display extremely tall on a iphone 5/6 device.

I cannot get this to work for anything. I have tried increasing the height in the modal-content, as well as in modal-dialog, but it just wont work.

Any easy solutions out there?

.modal-dialog{
    height:90% !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
    Launch modal
  </button>
</div>

<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">My modal</h4>
      </div>
    </div>
  </div>
</div>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script></code>```

答:
The .modal-content block is inside the .modal-dialog block. Hence, tell the child to be of the same height as the parent. Try:

```<code>.modal-dialog {
  height: 90%; /* = 90% of the .modal-backdrop block = %90 of the screen */
}
.modal-content {
  height: 100%; /* = 100% of the .modal-dialog block */
}
</code>```

Check:

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

.modal-tall .modal-dialog {
  height: 90%;
}
.modal-tall .modal-content {
  height: 100%;
}

/* fix SO stick navigation ;) */
@media (min-width: 768px) { body { padding-top: 75px; } }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#modalDefault">
    Default modal
  </button>

  <button type="button" class="btn btn-warning btn-lg" data-toggle="modal" data-target="#modalTall">
    Tall modal
  </button>
</div>

<div id="modalDefault" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">Default modal</h4>
      </div>
    </div>
  </div>
</div>

<div id="modalTall" class="modal modal-tall fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal has 90% height</h4>
      </div>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script></code>```

Body:
I am simply trying to make a bootstrap modal display extremely tall on a iphone 5/6 device.

I cannot get this to work for anything. I have tried increasing the height in the modal-content, as well as in modal-dialog, but it just wont work.

Any easy solutions out there?

.modal-dialog{
    height:90% !important;
}

  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
    Launch modal
  </button>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

My modal

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Body:
The .modal-content block is inside the .modal-dialog block. Hence, tell the child to be of the same height as the parent. Try:

.modal-dialog {
  height: 90%; /* = 90% of the .modal-backdrop block = %90 of the screen */
}
.modal-content {
  height: 100%; /* = 100% of the .modal-dialog block */
}

Check:

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');

.modal-tall .modal-dialog {
  height: 90%;
}
.modal-tall .modal-content {
  height: 100%;
}

/* fix SO stick navigation ;) */
@media (min-width: 768px) { body { padding-top: 75px; } }

<div class="container">
  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#modalDefault">
    Default modal
  </button>

  <button type="button" class="btn btn-warning btn-lg" data-toggle="modal" data-target="#modalTall">
    Tall modal
  </button>
</div>

<div id="modalDefault" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Default modal</h4>
      </div>
    </div>
  </div>
</div>

<div id="modalTall" class="modal modal-tall fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal has 90% height</h4>
      </div>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


问:
Vision SDK only recognise faces in landscape right mode on iPad
I am trying to create an app that use the Vision SDK to track a face in real time, using the camera.

So far, it's only working when I hold the iPad in landscape right mode.

The process is the following:

```<code>// This  is the AVCaptureVideoDataOutputSampleBufferDelegate
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
            sequenceHandler.perform(requests, on: imageBuffer)
        }
    }
</code>```

Is there a way to rotate the stream easily, or hint the Vision SDK the correct orientation ?

答:
It's actually super easy:

```<code> open func perform(_ requests: [VNRequest], on image: CGImage, orientation: Int32) throws
</code>```

Use the orientation parameter (not sure how I didn't saw it earlier.)

Body:
I am trying to create an app that use the Vision SDK to track a face in real time, using the camera.

So far, it's only working when I hold the iPad in landscape right mode.

The process is the following:

// This  is the AVCaptureVideoDataOutputSampleBufferDelegate
    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
        if let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) {
            sequenceHandler.perform(requests, on: imageBuffer)
        }
    }

Is there a way to rotate the stream easily, or hint the Vision SDK the correct orientation ?

Body:
It's actually super easy:

 open func perform(_ requests: [VNRequest], on image: CGImage, orientation: Int32) throws

Use the orientation parameter (not sure how I didn't saw it earlier.)