问:
Spring Boot fails to create database schema
I have the following entities in my Spring Boot web application all defined in the entities package:

```<code>AccessPath.java
Component.java
ComponentInstance.java
ComponentOrder.java
Customer.java
HardwareComponent.java
HardwareGraphicsComponent.java
HardwareProcessingComponent.java
HardwareRamComponent.java
HardwareStorageComponent.java
Invoice.java
Manager.java
Order.java
Product.java
Report.java
ScmManager.java
ScmStaff.java
SoftwareComponent.java
Staff.java
Supplier.java
User.java
WarehouseManager.java
</code>```

I'm using a properly configured PostgreSQL instance as the database:

```<code>spring.thymeleaf.cache=false
#
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/foundationdb
spring.datasource.username=foundationdb
spring.datasource.password=
#
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
</code>```

When running the application with gradle bootRun I get a lot of error messages regarding invalid SQL statements. It seems like the framework is trying to create the tables in the wrong order and basically fails to create tables for any entity with some sort of relationship. For instance the SQL for creating the order tables fails with the following error most likely because the customer table to which order has a foreign key isn't created yet.

```<code>2017-06-09 10:51:35.737 ERROR 85908 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: create table order (id int8 not null, assembly_date date, confirmation_date date, creation_date date, shipping_date date, status varchar(255), customer_username varchar(255), product_id int8, primary key (id))
2017-06-09 10:51:35.737 ERROR 85908 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: syntax error at or near "order"
</code>```

The only tables created at the end are these:

```<code>List of relations
Schema |            Name             | Type  |    Owner
--------+-----------------------------+-------+--------------
public | component                   | table | foundationdb
public | component_instance          | table | foundationdb
public | component_order             | table | foundationdb
public | invoice                     | table | foundationdb
public | product                     | table | foundationdb
public | product_software_components | table | foundationdb
public | report                      | table | foundationdb
public | supplier                    | table | foundationdb
</code>```

My entities were scattered across different packages at first and I tried putting them all in a single package to streamline the process but that didn't help.

This is definitely a framework related issue as testing with in-memory h2 or HSQLDB instances results in similar errors.

The source code for all these classes is available here:
https://gist.github.com/Parsoa/f463fbef548f3a678c1e067e9aad5b21

Any help is appreciated.

答:
order is a reserved SQL keyword (order by ...). Choose another name for your table.

As the error message shows, it has nothing to do with foreign keys:

```<code>ERROR: syntax error at or near "order"
</code>```

Body:
I have the following entities in my Spring Boot web application all defined in the entities package:

AccessPath.java
Component.java
ComponentInstance.java
ComponentOrder.java
Customer.java
HardwareComponent.java
HardwareGraphicsComponent.java
HardwareProcessingComponent.java
HardwareRamComponent.java
HardwareStorageComponent.java
Invoice.java
Manager.java
Order.java
Product.java
Report.java
ScmManager.java
ScmStaff.java
SoftwareComponent.java
Staff.java
Supplier.java
User.java
WarehouseManager.java

I'm using a properly configured PostgreSQL instance as the database:

spring.thymeleaf.cache=false
#
spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/foundationdb
spring.datasource.username=foundationdb
spring.datasource.password=
#
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop

When running the application with gradle bootRun I get a lot of error messages regarding invalid SQL statements. It seems like the framework is trying to create the tables in the wrong order and basically fails to create tables for any entity with some sort of relationship. For instance the SQL for creating the order tables fails with the following error most likely because the customer table to which order has a foreign key isn't created yet.

2017-06-09 10:51:35.737 ERROR 85908 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000389: Unsuccessful: create table order (id int8 not null, assembly_date date, confirmation_date date, creation_date date, shipping_date date, status varchar(255), customer_username varchar(255), product_id int8, primary key (id))
2017-06-09 10:51:35.737 ERROR 85908 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : ERROR: syntax error at or near "order"

The only tables created at the end are these:

List of relations
Schema |            Name             | Type  |    Owner
--------+-----------------------------+-------+--------------
public | component                   | table | foundationdb
public | component_instance          | table | foundationdb
public | component_order             | table | foundationdb
public | invoice                     | table | foundationdb
public | product                     | table | foundationdb
public | product_software_components | table | foundationdb
public | report                      | table | foundationdb
public | supplier                    | table | foundationdb

My entities were scattered across different packages at first and I tried putting them all in a single package to streamline the process but that didn't help.

This is definitely a framework related issue as testing with in-memory h2 or HSQLDB instances results in similar errors.

The source code for all these classes is available here:
https://gist.github.com/Parsoa/f463fbef548f3a678c1e067e9aad5b21

Any help is appreciated.

Body:
order is a reserved SQL keyword (order by ...). Choose another name for your table.

As the error message shows, it has nothing to do with foreign keys:

ERROR: syntax error at or near "order"


来源: stackexchange

问:
DropBoxManager use cases?
I noticed that a DropBoxManager has been introduced in Android API since FroYo (API 8).

It looks like an alternative logger capable of logging not only text but also files or byte arrays, but I could not find any detailed doc anywhere about how and when we should use it.

The latest android dev blog post introducing StrictMode talks about it, StrictMode can append data to the DropBox, and we are given a shell command to retrieve these data.

Please share here your knowledge about this! Why has it been implemented in addition to the usual logcat? Can we use this to share data across apps? What kind of apps use it?

答:
There are basically three logs on the system:

Log:

for short, textual data

in-memory ringbuffer, fast

ephemeral (you'll lose it on a crash, or the ringbuffer scrolls)

intended for app developers

EventLog is:

for short, binary data

in-memory ringbuffer, fast

ephemeral (you'll lose it on a crash, or the ringbuffer scrolls)

intended for platform developers to collect statistics

DropBox:

for long text or binary data

persistent, written to disk

kinda slow (disk)

meant for platform developers too, mostly to collect crashes & large statistics

subject to limits, deleted by tag if a tag's count and/or size get too large

DropBox is what we used during development to capture all the StrictMode violations in Gingerbread.

You can use DropBox for one-off debugging, but it's not really recommended.  It's definitely not recommended as a way to share data between apps.  It's not reliable enough, and you can't put permissions on the data.  You should just use a shared userid and use the normal filesystem with appropriate permissions.

ContentLicense: CC BY-SA 3.0

Title: DropBoxManager use cases?

ContentLicense: CC BY-SA 2.5


问:
When Checkbox value is null. Program throws this error" Object cannot be cast from DBNull to other types."
When the checkbox value in database is null it throws error. When it is 0 or 1 it works as expected.

```<code>if (Request.QueryString["Sckey"] != null && Request.QueryString["Sckey"].ToString() != "")
{
    string str_sql1 = "select ScenarioSeq,ScenarioName,FileName,ScenarioNotes,IsUpperCase from Scenario where ScenarioKey=@ScenarioKey;";
    SqlCommand cm = new SqlCommand(str_sql1);
    cm.Parameters.AddWithValue("@ScenarioKey", str_ScKey);
    DataSet ds2 = this.DA.GetDataSet(cm);

    DataRow dr = ds2.Tables[0].Rows[0];
    txt_ScenarioName.Text = dr["ScenarioName"].ToString();
    txt_ScenarioNotes.Text = dr["ScenarioNotes"].ToString();
    ch_Uppercase.Checked = Convert.ToBoolean(dr["IsUpperCase"]);
}
</code>```

答:
Do something like this..</p>

```<code>ch_Uppercase.Checked =
     Convert.ToBoolean(dr["IsUpperCase"] == DBNull.Value? 0: dr["IsUpperCase"]);
</code>```

Body:
When the checkbox value in database is null it throws error. When it is 0 or 1 it works as expected.

if (Request.QueryString["Sckey"] != null && Request.QueryString["Sckey"].ToString() != "")
{
    string str_sql1 = "select ScenarioSeq,ScenarioName,FileName,ScenarioNotes,IsUpperCase from Scenario where ScenarioKey=@ScenarioKey;";
    SqlCommand cm = new SqlCommand(str_sql1);
    cm.Parameters.AddWithValue("@ScenarioKey", str_ScKey);
    DataSet ds2 = this.DA.GetDataSet(cm);

    DataRow dr = ds2.Tables[0].Rows[0];
    txt_ScenarioName.Text = dr["ScenarioName"].ToString();
    txt_ScenarioNotes.Text = dr["ScenarioNotes"].ToString();
    ch_Uppercase.Checked = Convert.ToBoolean(dr["IsUpperCase"]);
}

Body:
Do something like this..

ch_Uppercase.Checked =
     Convert.ToBoolean(dr["IsUpperCase"] == DBNull.Value? 0: dr["IsUpperCase"]);


问:
What is the best approach for quick fix the errors/bugs in phase1 code through the DevOps?
I have two branches like dev and master in VSTS to manage my code. After completed phase 1 development, I have published my web application code from master branch through my Dev Ops configuration.

But every day we do pull request from dev to master, so every day master having latest code.

I have doubt like

After completed phase 1, my development team will started to work on phase 2 development on dev branch. But at some point time customers will raise the bugs/errors on phase 1 release of web application at that time how to quick fix those issues of phase 1 web application without interrupting the phase 2 development already started.
Can you please tell what is the best approach to quick fix the errors/bugs in phase 1 and how to release only phase 1 code after fixed the errors/bugs.

答:
You can create a new branch (e.g. devPhase2) from master after phase, then to work on phase2 with this new branch. After that, you can fix the bugs on old branch (e.g. dev) and merge to master and release. After phase 2 finishing, merge DevPhase2 branch to master and release.

You also can fix the issue in phase and release phase 2 with fixed bugs of phase during release phase 2.


问:
Why does spark-shell fail to load a file with class with RDD imported?
I use Spark 2.1.1 with Scala 2.11.8.

Inside spark-shell I use :load command to load a class that has methods with RDDs.

When I try to load the class I get the following compilation error:

error: not found: type RDD

Why? I've got the import statement.

This is the code I'm working with

答:
That seems a feature of :load in spark-shell. A solution is to move import org.apache.spark.rdd.RDD (no dot and underscore) to your class definition.

This seems not specific to the RDD class but any classes imported. It won't work unless the import statement is defined inside the class itself.

With that said, the following won't work due to import being outside the class.

```<code>import org.apache.spark.rdd.RDD
class Hello {
  def get(rdd: RDD[String]): RDD[String] = rdd
}

scala> :load hello.scala
Loading hello.scala...
import org.apache.spark.rdd.RDD
<console>:12: error: not found: type RDD
         def get(rdd: RDD[String]): RDD[String] = rdd
                                    ^
<console>:12: error: not found: type RDD
         def get(rdd: RDD[String]): RDD[String] = rdd
                      ^
</code>```

You can see what happens under the covers using -v flag of :load.

```<code>scala> :load -v hello.scala
Loading hello.scala...

scala>

scala> import org.apache.spark.rdd.RDD
import org.apache.spark.rdd.RDD

scala> class Hello {
     |   def get(rdd: RDD[String]): RDD[String] = rdd
     | }
<console>:12: error: not found: type RDD
         def get(rdd: RDD[String]): RDD[String] = rdd
                                    ^
<console>:12: error: not found: type RDD
         def get(rdd: RDD[String]): RDD[String] = rdd
                      ^
</code>```

That led me to guess that having the import inside the class definition could help. And it did! (to my great surprise)

```<code>class Hello {
  import org.apache.spark.rdd.RDD
  def get(rdd: RDD[String]): RDD[String] = rdd
}

scala> :load -v hello.scala
Loading hello.scala...

scala> class Hello {
     |   import org.apache.spark.rdd.RDD
     |   def get(rdd: RDD[String]): RDD[String] = rdd
     | }
defined class Hello
</code>```

You could also use :paste command to paste the class to spark-shell. There's the so-called raw mode when you could define classes in their own package.

```<code>package mypackage

class Hello {
  import org.apache.spark.rdd.RDD
  def get(rdd: RDD[String]): RDD[String] = rdd
}

scala> :load -v hello.scala
Loading hello.scala...

scala> package mypackage
<console>:1: error: illegal start of definition
package mypackage
^

scala>

scala> class Hello {
     |   import org.apache.spark.rdd.RDD
     |   def get(rdd: RDD[String]): RDD[String] = rdd
     | }
defined class Hello

scala> :paste -raw
// Entering paste mode (ctrl-D to finish)

package mypackage

class Hello {
  import org.apache.spark.rdd.RDD
  def get(rdd: RDD[String]): RDD[String] = rdd
}

// Exiting paste mode, now interpreting.
</code>```

Body:
That seems a feature of :load in spark-shell. A solution is to move import org.apache.spark.rdd.RDD (no dot and underscore) to your class definition.

This seems not specific to the RDD class but any classes imported. It won't work unless the import statement is defined inside the class itself.

With that said, the following won't work due to import being outside the class.

import org.apache.spark.rdd.RDD
class Hello {
  def get(rdd: RDD[String]): RDD[String] = rdd
}

scala> :load hello.scala
Loading hello.scala...
import org.apache.spark.rdd.RDD
<console>:12: error: not found: type RDD
         def get(rdd: RDD[String]): RDD[String] = rdd
                                    ^
<console>:12: error: not found: type RDD
         def get(rdd: RDD[String]): RDD[String] = rdd
                      ^

You can see what happens under the covers using -v flag of :load.

scala> :load -v hello.scala
Loading hello.scala...

scala>

scala> import org.apache.spark.rdd.RDD
import org.apache.spark.rdd.RDD

scala> class Hello {
     |   def get(rdd: RDD[String]): RDD[String] = rdd
     | }
<console>:12: error: not found: type RDD
         def get(rdd: RDD[String]): RDD[String] = rdd
                                    ^
<console>:12: error: not found: type RDD
         def get(rdd: RDD[String]): RDD[String] = rdd
                      ^

That led me to guess that having the import inside the class definition could help. And it did! (to my great surprise)

class Hello {
  import org.apache.spark.rdd.RDD
  def get(rdd: RDD[String]): RDD[String] = rdd
}

scala> :load -v hello.scala
Loading hello.scala...

scala> class Hello {
     |   import org.apache.spark.rdd.RDD
     |   def get(rdd: RDD[String]): RDD[String] = rdd
     | }
defined class Hello

You could also use :paste command to paste the class to spark-shell. There's the so-called raw mode when you could define classes in their own package.

package mypackage

class Hello {
  import org.apache.spark.rdd.RDD
  def get(rdd: RDD[String]): RDD[String] = rdd
}

scala> :load -v hello.scala
Loading hello.scala...

scala> package mypackage
<console>:1: error: illegal start of definition
package mypackage
^

scala>

scala> class Hello {
     |   import org.apache.spark.rdd.RDD
     |   def get(rdd: RDD[String]): RDD[String] = rdd
     | }
defined class Hello

scala> :paste -raw
// Entering paste mode (ctrl-D to finish)

package mypackage

class Hello {
  import org.apache.spark.rdd.RDD
  def get(rdd: RDD[String]): RDD[String] = rdd
}

// Exiting paste mode, now interpreting.


问:
Git Not Pushing nor Source Tree
As per comments:

I've been following bitbuckets instructions

Already have a Git repository on your computer? Let's push it up to Bitbucket.

```<code>cd /path/to/my/repo
git remote add origin git@bitbucket.org:...
git push -u origin --all # pushes up the repo and its refs for the first time
git push origin --tags # pushes up any tags
</code>```

I am getting this error message when trying to push through Atlassian Source Tree

```<code>git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master
Pushing to C:\...
remote: error: refusing to update checked out branch: refs/heads/master[K
remote: error: By default, updating the current branch in a non-bare     repository[K
remote: error: is denied, because it will make the index and work tree inconsistent[K

remote: error: with what you pushed, and will require 'git reset --hard' to match[K
remote: error: the work tree to HEAD.[K
remote: error: [K
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to[K
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into[K
remote: error: its current branch; however, this is not recommended unless you[K
remote: error: arranged to update its work tree to match what you pushed in some[K
remote: error: other way.[K
remote: error: [K
remote: error: To squelch this message and still keep the default behaviour, set[K
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.[K
To C:\...
! [remote rejected] master -> master (branch is currently checked out)

error: failed to push some refs to 'C:\...'
</code>```

Then I get this in the git terminal

```<code>No refs in common and none specified; doing nothing.
Perhaps you should specify a branch such as 'master'.
fatal: The remote end hung up unexpectedly
Everything up-to-date
</code>```

I've added the SSH keys generated by SourceTree (puTTy) and from the terminal. Followed all the steps, yet I'm lost. I am brand new on this like 2 hours old HA. Can anyone step me in the correct location.

答: In SourceTree, try changing SSH Client from PuTTY/Plink to Open SSH.

Title: Git Not Pushing nor Source Tree

Body:
As per comments:

I've been following bitbuckets instructions

Already have a Git repository on your computer? Let's push it up to Bitbucket.

cd /path/to/my/repo
git remote add origin git@bitbucket.org:...
git push -u origin --all # pushes up the repo and its refs for the first time
git push origin --tags # pushes up any tags

I am getting this error message when trying to push through Atlassian Source Tree

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master
Pushing to C:\...
remote: error: refusing to update checked out branch: refs/heads/master[K
remote: error: By default, updating the current branch in a non-bare     repository[K
remote: error: is denied, because it will make the index and work tree inconsistent[K

remote: error: with what you pushed, and will require 'git reset --hard' to match[K
remote: error: the work tree to HEAD.[K
remote: error: [K
remote: error: You can set 'receive.denyCurrentBranch' configuration variable to[K
remote: error: 'ignore' or 'warn' in the remote repository to allow pushing into[K
remote: error: its current branch; however, this is not recommended unless you[K
remote: error: arranged to update its work tree to match what you pushed in some[K
remote: error: other way.[K
remote: error: [K
remote: error: To squelch this message and still keep the default behaviour, set[K
remote: error: 'receive.denyCurrentBranch' configuration variable to 'refuse'.[K
To C:\...
! [remote rejected] master -> master (branch is currently checked out)

error: failed to push some refs to 'C:\...'

Then I get this in the git terminal

No refs in common and none specified; doing nothing.
Perhaps you should specify a branch such as 'master'.
fatal: The remote end hung up unexpectedly
Everything up-to-date

I've added the SSH keys generated by SourceTree (puTTy) and from the terminal. Followed all the steps, yet I'm lost. I am brand new on this like 2 hours old HA. Can anyone step me in the correct location.


问:
Onclick function is not working in Chrome browser
This is working fine in Internet Explorer and Firefox but not working in Chrome browser

<select name="Consolidate Report" class="input">
    <option value="">Consolidate Report</option>
    <option value="" onclick="view_graph()">View Graph</option>
    <option value="" onclick="export_graph()">Export Excel</option>
</select>```

答:
I have another suggestion           </p>

```<code><select onchange="valueChanged(this.value);" name="Consolidate Report" class="input">
        <option value="">Consolidate Report</option>
        <option value="view_graph" >View Graph</option>
        <option value="export_graph">Export Excel</option>
 </select>

        <script>

         function valueChanged(value){

            if(value == 'view_graph')
            {
                alert('view_graph');
            }else if(value == 'export_graph')
            {
                alert('export_graph');
            }
          }
        </script>
</code>```

Body:
I have another suggestion

<select onchange="valueChanged(this.value);" name="Consolidate Report" class="input">
        <option value="">Consolidate Report</option>
        <option value="view_graph" >View Graph</option>
        <option value="export_graph">Export Excel</option>
 </select>

        <script>

         function valueChanged(value){

            if(value == 'view_graph')
            {
                alert('view_graph');
            }else if(value == 'export_graph')
            {
                alert('export_graph');
            }
          }
        </script>


问:
TFS showing Checked in by name as Service Account
I have online TFS account.

Whenever I do a check-in it shows check in done by "Service Account(TFS)" instead of my name.

I want to show my name against the Checked-In by Name.

Any help is appreciated.

答:
Firstly, please make sure you connect the online TFS (VSTS) with the correct account.

If connect with wrong account, you need to remove TFS credentials from Windows Vault to clear and force to ask new TFS credentials in Visual Studio. Please reference this thread: How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up? to do that.

If the account is correct, just please check your VSTS account Profile, make sure the full name is not "Service Account(TFS)". If it is, just change it to your name, save the profile and check in again, check the Checked-In by Name, it will be changed to your name.


问:
ClassNotFoundException: org.springframework.cloud.client.actuator.HasFeatures
When i run eureka server，the console print this exception:

Caused by: java.lang.ClassNotFoundException: org.springframework.cloud.client.actuator.HasFeatures

the pom.xml is:

答:
if you use official demo you will find your application can't run!  because it's lost 3 jars

commons-configuration,commons-lang,com.google.guava
enter image description here


问:
Unable to django start server after commited some migration files to smartgit
enter code here(kemgo-api-v2) ronnie@vax-PC-88:/var/www/html/kemgo-api-v2$ python manage.py runserver

```<code>Performing system checks...

System check identified no issues (0 silenced).
Unhandled exception in thread started by <function wrapper at 0x7f22b50abcf8>
Traceback (most recent call last):
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 222, in wrapper
    fn(*args, **kwargs)
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run
    self.check_migrations()
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 159, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 17, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 48, in __init__
    self.build_graph()
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 241, in build_graph
    self.graph.add_dependency(migration, key, parent)
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/graph.py", line 42, in add_dependency
    raise KeyError("Migration %s dependencies references nonexistent parent node %r" % (migration, parent))
KeyError: u"Migration storefront.0002_storeview dependencies references nonexistent parent node (u'km', u'0010_auto_20170327_0841')"
</code>```

0002_storeview.py

```<code># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone

class Migration(migrations.Migration):

    dependencies = [
        ('km', '0010_auto_20170327_0841'),
        ('storefront', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='StoreView',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('ip', models.GenericIPAddressField(default=b'', null=True, blank=True)),
                ('viewtype', models.CharField(default=b'1', max_length=1, null=True, blank=True, choices=[(b'1', b'View'), (b'2', b'Mobile'), (b'3', b'Website'), (b'4', b'Email'), (b'5', b'Contact Tab'), (b'6', b'TDS Download')])),
                ('source', models.CharField(default=b'IOS', max_length=20, null=True, blank=True)),
                ('status', models.CharField(default=b'0', max_length=1, null=True, blank=True, choices=[(b'0', b'Inactive'), (b'1', b'Active')])),
                ('created_date', models.DateTimeField(default=django.utils.timezone.now)),
                ('store', models.ForeignKey(related_name=b'storeview', to='km.Store')),
                ('user', models.ForeignKey(related_name=b'store_userview', to='km.User', null=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]
</code>```

i have deleted the following files and then commit:
    globalmarket/migrations/init.py
    inquiry/migrations/init.py
    km/migrations/.gitignore
    km/migrations/0001_initial.py
    km/migrations/0002_store1.py
    km/migrations/0003_remove_storemodule_created_date.py
    km/migrations/0004_storemodule_created_date.py
    km/migrations/0005_delete_store1.py
    km/migrations/init.py
    km/migrations/back/.gitignore
    km/migrations_bck/.gitignore
    km/migrations_bck/0025_auto_20150224_1547.py.bak
    km/migrations_bck/0026_auto_20150225_0958.py.bak
    km/migrations_bck/0107_auto_20151023_0541.py.bak
    km/migrations_bck/@
    storefront/migrations/0001_initial.py
    storefront/migrations/0002_storeview.py
    storefront/migrations/init.py

答:
Ex for migrate: my file: (0002_auto...)

```<code> class Migration(migrations.Migration):

    dependencies = [
        ('svace', '0001_initial'),
    ]

    operations = [
        migrations.RenameField(
            model_name='application',
            old_name='type',
            new_name='application_type',
        ),
    ]
</code>```

The dependencies will so the lastest update (before you make this new migrate). In your case, check the link (*/project_name/app_name/migrations) and give me the list of file (show the data of 0002.xxx file too)

Body:
enter code here(kemgo-api-v2) ronnie@vax-PC-88:/var/www/html/kemgo-api-v2$ python manage.py runserver

Performing system checks...

System check identified no issues (0 silenced).
Unhandled exception in thread started by <function wrapper at 0x7f22b50abcf8>
Traceback (most recent call last):
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 222, in wrapper
    fn(*args, **kwargs)
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run
    self.check_migrations()
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 159, in check_migrations
    executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 17, in __init__
    self.loader = MigrationLoader(self.connection)
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 48, in __init__
    self.build_graph()
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 241, in build_graph
    self.graph.add_dependency(migration, key, parent)
  File "/home/mohit/.virtualenvs/kemgo-api-v2/local/lib/python2.7/site-packages/django/db/migrations/graph.py", line 42, in add_dependency
    raise KeyError("Migration %s dependencies references nonexistent parent node %r" % (migration, parent))
KeyError: u"Migration storefront.0002_storeview dependencies references nonexistent parent node (u'km', u'0010_auto_20170327_0841')"

0002_storeview.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone

class Migration(migrations.Migration):

    dependencies = [
        ('km', '0010_auto_20170327_0841'),
        ('storefront', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='StoreView',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('ip', models.GenericIPAddressField(default=b'', null=True, blank=True)),
                ('viewtype', models.CharField(default=b'1', max_length=1, null=True, blank=True, choices=[(b'1', b'View'), (b'2', b'Mobile'), (b'3', b'Website'), (b'4', b'Email'), (b'5', b'Contact Tab'), (b'6', b'TDS Download')])),
                ('source', models.CharField(default=b'IOS', max_length=20, null=True, blank=True)),
                ('status', models.CharField(default=b'0', max_length=1, null=True, blank=True, choices=[(b'0', b'Inactive'), (b'1', b'Active')])),
                ('created_date', models.DateTimeField(default=django.utils.timezone.now)),
                ('store', models.ForeignKey(related_name=b'storeview', to='km.Store')),
                ('user', models.ForeignKey(related_name=b'store_userview', to='km.User', null=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]

i have deleted the following files and then commit:
    globalmarket/migrations/init.py
    inquiry/migrations/init.py
    km/migrations/.gitignore
    km/migrations/0001_initial.py
    km/migrations/0002_store1.py
    km/migrations/0003_remove_storemodule_created_date.py
    km/migrations/0004_storemodule_created_date.py
    km/migrations/0005_delete_store1.py
    km/migrations/init.py
    km/migrations/back/.gitignore
    km/migrations_bck/.gitignore
    km/migrations_bck/0025_auto_20150224_1547.py.bak
    km/migrations_bck/0026_auto_20150225_0958.py.bak
    km/migrations_bck/0107_auto_20151023_0541.py.bak
    km/migrations_bck/@
    storefront/migrations/0001_initial.py
    storefront/migrations/0002_storeview.py
    storefront/migrations/init.py

Body:
Ex for migrate: my file: (0002_auto...)

 class Migration(migrations.Migration):

    dependencies = [
        ('svace', '0001_initial'),
    ]

    operations = [
        migrations.RenameField(
            model_name='application',
            old_name='type',
            new_name='application_type',
        ),
    ]

The dependencies will so the lastest update (before you make this new migrate). In your case, check the link (*/project_name/app_name/migrations) and give me the list of file (show the data of 0002.xxx file too)


问:
How to import modules in Paver?
I am using Paver for the first time and I can't import in my pavement.py a module I created in the same directory. The module was working when imported in a standalone script in the same directory. I guess paver is running from somewhere else, not the same directory.

Any suggestion?

答:
After a bit of investigation I found a solution...</p>

```<code>import sys
sys.path.append( os.path.abspath('.') )
import mymodule.myscript as myscript
</code>```

Title: How to import modules in Paver?

Body:
After a bit of investigation I found a solution...

import sys
sys.path.append( os.path.abspath('.') )
import mymodule.myscript as myscript


问:
k-means not clustering correct in python
I'm trying to clusterize a dataset using k-means. When I run my algorithm with just one iteration returns random clusters, as it should, but when I try multiple iterations, it returns only 0s. The matrix I'm using is a 50k x 140 binary matrix. Each row represents a user and each column represents an item.

```<code> def clusterizator(matriz, nDeClusters, it=10): # matrix, number of clusters, number of iterations

    nOfLines = matriz.shape[0] # number of lines (users)
    nOfColumns = matriz.shape[1] # number of columns (items)
    clusterCurrently = np.zeros((nOfLines, 1)) # currently cluster assigned to each user
    listOfCurrentlyAssigneds = [] # list with numberOfClusters size, each element is a list of currently elements assigned to this cluster
    clusterCentroid = [] # centroid of each cluster

    clusterCentroid = np.random.randint(2, size=(nDeClusters, nOfColumns)) # starts with randoms centroids

    for repeat in xrange(it): # number of iterations
        listOfCurrentlyAssigneds = [[] for i in xrange(nDeClusters)] # create empty lists for each cluster

        for i in xrange(nOfLines): # for each user
            closestCentroid = clusterMaisProximo(matriz[i], clusterCentroid) # calculates the closest centroid
            clusterCurrently[i] = closestCentroid                            # assign the user to closest centroid
            listOfCurrentlyAssigneds[closestCentroid].append(matriz[i])      # put user on that centroid list

        for i in xrange(nDeClusters): # for each cluster
            if listOfCurrentlyAssigneds[i] != []: # if the list is not empty
                clusterCentroid[i] = centeroidnp(listOfCurrentlyAssigneds[i])   # calculates the new centroid

    return clusterCurrently    # return 1-column matrix with user x cluster

def distanciaEucl(elemento1, elemento2):
    return np.linalg.norm(elemento2-elemento1)  #calculates the distance between to items (or one user and one cluster)

def clusterMaisProximo(elemento, listaDeClusters):  # receive one user and the cluster's centroids list, return the closest one
    closest = 0
    closestDist = distanciaEucl(elemento, listaDeClusters[0]) # starts with the cluster[0]

    for i in xrange(len(listaDeClusters)-1): # for each cluster
        dist = distanciaEucl(elemento, listaDeClusters[i+1]) # get the distance to currently cluster's centroid
        if dist < closestDist: # if it is closer to the element
            closest = i+1 # update new closest element
            closestDist = dist # update new closest distance

    return closest   # return closest

# from https://stackoverflow.com/questions/23020659/fastest-way-to-calculate-the-centroid-of-a-set-of-coordinate-tuples-in-python-wi
# by Retozi (adapted)
def centeroidnp(lista):   # get a list of elements (number of elements x items)
    shape = list(lista[0].shape)
    shape[:0] = [len(lista)]
    arr = np.concatenate(lista).reshape(shape)   # get an array from the list
    length = arr.shape[0]
    somas = np.zeros(arr.shape[1])
    for i in xrange(arr.shape[1]): # for each item (dimension)
        somas[i] = (np.sum(arr[:, i]))/length   # sum all elements and divide by number of elements
    return somas  # return array that will be the new centroid position
</code>```

I commented everything to try to make clear what each row is doing, some comments are dumb because at first my variables were written in Portuguese, then I translated to make it more clear.

I'm running it like this:

```<code>clust = clusterizator(train, 10, 2)
</code>```

Example matrix:

```<code>train = [[0, 1, 1, 0], [1, 0, 0, 0], [0, 1, 1, 1], [1, 0, 0, 1], [1, 0, 0, 0]]
</code>```

答:
My guess is that you have an integer division problem.

Look at your new centroids. They probably are all zeros?
It's because that in programming (except Python 3) 1/2=0 because of integer math.

The algorithm is called k-means, not kNN. It doesn't use the k nearest neighbors of every point, but the 1 nearest centroid.

Body:
I'm trying to clusterize a dataset using k-means. When I run my algorithm with just one iteration returns random clusters, as it should, but when I try multiple iterations, it returns only 0s. The matrix I'm using is a 50k x 140 binary matrix. Each row represents a user and each column represents an item.

 def clusterizator(matriz, nDeClusters, it=10): # matrix, number of clusters, number of iterations

    nOfLines = matriz.shape[0] # number of lines (users)
    nOfColumns = matriz.shape[1] # number of columns (items)
    clusterCurrently = np.zeros((nOfLines, 1)) # currently cluster assigned to each user
    listOfCurrentlyAssigneds = [] # list with numberOfClusters size, each element is a list of currently elements assigned to this cluster
    clusterCentroid = [] # centroid of each cluster

    clusterCentroid = np.random.randint(2, size=(nDeClusters, nOfColumns)) # starts with randoms centroids

    for repeat in xrange(it): # number of iterations
        listOfCurrentlyAssigneds = [[] for i in xrange(nDeClusters)] # create empty lists for each cluster

        for i in xrange(nOfLines): # for each user
            closestCentroid = clusterMaisProximo(matriz[i], clusterCentroid) # calculates the closest centroid
            clusterCurrently[i] = closestCentroid                            # assign the user to closest centroid
            listOfCurrentlyAssigneds[closestCentroid].append(matriz[i])      # put user on that centroid list

        for i in xrange(nDeClusters): # for each cluster
            if listOfCurrentlyAssigneds[i] != []: # if the list is not empty
                clusterCentroid[i] = centeroidnp(listOfCurrentlyAssigneds[i])   # calculates the new centroid

    return clusterCurrently    # return 1-column matrix with user x cluster

def distanciaEucl(elemento1, elemento2):
    return np.linalg.norm(elemento2-elemento1)  #calculates the distance between to items (or one user and one cluster)

def clusterMaisProximo(elemento, listaDeClusters):  # receive one user and the cluster's centroids list, return the closest one
    closest = 0
    closestDist = distanciaEucl(elemento, listaDeClusters[0]) # starts with the cluster[0]

    for i in xrange(len(listaDeClusters)-1): # for each cluster
        dist = distanciaEucl(elemento, listaDeClusters[i+1]) # get the distance to currently cluster's centroid
        if dist < closestDist: # if it is closer to the element
            closest = i+1 # update new closest element
            closestDist = dist # update new closest distance

    return closest   # return closest

# from https://stackoverflow.com/questions/23020659/fastest-way-to-calculate-the-centroid-of-a-set-of-coordinate-tuples-in-python-wi
# by Retozi (adapted)
def centeroidnp(lista):   # get a list of elements (number of elements x items)
    shape = list(lista[0].shape)
    shape[:0] = [len(lista)]
    arr = np.concatenate(lista).reshape(shape)   # get an array from the list
    length = arr.shape[0]
    somas = np.zeros(arr.shape[1])
    for i in xrange(arr.shape[1]): # for each item (dimension)
        somas[i] = (np.sum(arr[:, i]))/length   # sum all elements and divide by number of elements
    return somas  # return array that will be the new centroid position

I commented everything to try to make clear what each row is doing, some comments are dumb because at first my variables were written in Portuguese, then I translated to make it more clear.

I'm running it like this:

clust = clusterizator(train, 10, 2)

Example matrix:

train = [[0, 1, 1, 0], [1, 0, 0, 0], [0, 1, 1, 1], [1, 0, 0, 1], [1, 0, 0, 0]]


问:
In c language, Embedded Application, how to compare members from an Array of structure
I have a Memory chip that has data read by an embedded system serially. The memory device has 10 locations with each location having the following information: customerID, NumOfParts, MFGName.
Here is my version of C code I wrote for this.

IN C FILE "PartName.h"

```<code>    //"PartName.h"
    #ifndef PartName_H
    #define PartName_H

    typedef UINT8 MFGName_Struct_t [10];

    typedef struct
    {
        UINT8 customerID;
        UINT8 NumOfParts;
        MFGName_Struct_t MFGName;
    }IDENT_Struct_t;

    typedef struct MFG_Struct_t
    {
        UINT8 <some other variable>;
        UINT8 <some other variable>;
        IDENT_Struct_t Ident1;
        IDENT_Struct_t Ident2;
        IDENT_Struct_t Ident3;
        IDENT_Struct_t Ident4;
        IDENT_Struct_t Ident5;
        IDENT_Struct_t Ident6;
        IDENT_Struct_t Ident7;
        IDENT_Struct_t Ident8;
        IDENT_Struct_t Ident9;
        IDENT_Struct_t Ident10;
    } MFG_Struct_t;

    #endif
</code>```

IN C FILE "HighNum.c"

```<code>    //"HighNum.c"
    #include "PartName.h"
    static MFG_Struct_t  MFG;
    UINT8 HighNum(void)
   {
     //UINT8 i;
       UINT8 highestNum = 0;
     //for (i = 0;(i < 10);i++)

       if (MFG.Ident1.NumOfParts > MFG.Ident2.NumOfParts)
       {
           highestNum = MFG.Ident1.NumOfParts;
       }
       if (MFG.Ident2.NumOfParts > MFG.Ident3.NumOfParts)
       {
           highestNum = MFG.Ident2.NumOfParts;
       }
       if (MFG.Ident3.NumOfParts > MFG.Ident4.NumOfParts)
       {
           highestNum = MFG.Ident3.NumOfParts;
       }
       if (MFG.Ident4.NumOfParts > MFG.Ident5.NumOfParts)
       {
           highestNum = MFG.Ident4.NumOfParts;
       }
       <and so on>
     return highestNum;
   }
</code>```

How can this be done more efficient in C? using for statements or While statements? I thought about concatenating the number portion and cycling through the variables...

答:
You could redefine the structure to put the 10 "Ident" values in an array, then use a for-loop to test your values:

```<code>typedef struct MFG_Struct_t
{
    UINT8 <some other variable>;
    UINT8 <some other variable>;
    IDENT_Struct_t Ident[10];
} MFG_Struct_t;
    :
    :
UINT8 HighNum(void) {
    UINT8 i, highestNum = 0;

    for (i = 0; i < 9; i++) {
        if (MFG.Ident[i].NumOfParts > MFG.Ident[i+1].NumOfParts) {
            highestNum = MFG.Ident[i].NumOfParts;
        }
    }
    return highestNum;
}
</code>```

or, better yet... change the HighNum function to be more efficient, as follows:

```<code>UINT8 HighNum(void) {
    UINT8 i, highestNum = MFG.Ident[0].NumOfParts;

    for (i = 1; i < 10; i++) {
        if (MFG.Ident[i].NumOfParts > highestNum) {
            highestNum = MFG.Ident[i].NumOfParts;
        }
    }
    return highestNum;
}
</code>```

Body:
I have a Memory chip that has data read by an embedded system serially. The memory device has 10 locations with each location having the following information: customerID, NumOfParts, MFGName.
Here is my version of C code I wrote for this.

IN C FILE "PartName.h"

    //"PartName.h"
    #ifndef PartName_H
    #define PartName_H

    typedef UINT8 MFGName_Struct_t [10];

    typedef struct
    {
        UINT8 customerID;
        UINT8 NumOfParts;
        MFGName_Struct_t MFGName;
    }IDENT_Struct_t;

    typedef struct MFG_Struct_t
    {
        UINT8 <some other variable>;
        UINT8 <some other variable>;
        IDENT_Struct_t Ident1;
        IDENT_Struct_t Ident2;
        IDENT_Struct_t Ident3;
        IDENT_Struct_t Ident4;
        IDENT_Struct_t Ident5;
        IDENT_Struct_t Ident6;
        IDENT_Struct_t Ident7;
        IDENT_Struct_t Ident8;
        IDENT_Struct_t Ident9;
        IDENT_Struct_t Ident10;
    } MFG_Struct_t;

    #endif

IN C FILE "HighNum.c"

    //"HighNum.c"
    #include "PartName.h"
    static MFG_Struct_t  MFG;
    UINT8 HighNum(void)
   {
     //UINT8 i;
       UINT8 highestNum = 0;
     //for (i = 0;(i < 10);i++)

       if (MFG.Ident1.NumOfParts > MFG.Ident2.NumOfParts)
       {
           highestNum = MFG.Ident1.NumOfParts;
       }
       if (MFG.Ident2.NumOfParts > MFG.Ident3.NumOfParts)
       {
           highestNum = MFG.Ident2.NumOfParts;
       }
       if (MFG.Ident3.NumOfParts > MFG.Ident4.NumOfParts)
       {
           highestNum = MFG.Ident3.NumOfParts;
       }
       if (MFG.Ident4.NumOfParts > MFG.Ident5.NumOfParts)
       {
           highestNum = MFG.Ident4.NumOfParts;
       }
       <and so on>
     return highestNum;
   }

How can this be done more efficient in C? using for statements or While statements? I thought about concatenating the number portion and cycling through the variables...

Body:
You could redefine the structure to put the 10 "Ident" values in an array, then use a for-loop to test your values:

typedef struct MFG_Struct_t
{
    UINT8 <some other variable>;
    UINT8 <some other variable>;
    IDENT_Struct_t Ident[10];
} MFG_Struct_t;
    :
    :
UINT8 HighNum(void) {
    UINT8 i, highestNum = 0;

    for (i = 0; i < 9; i++) {
        if (MFG.Ident[i].NumOfParts > MFG.Ident[i+1].NumOfParts) {
            highestNum = MFG.Ident[i].NumOfParts;
        }
    }
    return highestNum;
}

or, better yet... change the HighNum function to be more efficient, as follows:

UINT8 HighNum(void) {
    UINT8 i, highestNum = MFG.Ident[0].NumOfParts;

    for (i = 1; i < 10; i++) {
        if (MFG.Ident[i].NumOfParts > highestNum) {
            highestNum = MFG.Ident[i].NumOfParts;
        }
    }
    return highestNum;
}


问:
Android floating button not coming proper
I am using a floating button. The image source I am using is also proper but not sure while setting it is showing it as dot in the center. Screenshot and Code below :

```<code><android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="10dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        android:src="@drawable/addbutton"/>
</code>```

答:
Add the latest support libraries to your app build gradle file and build your project

dependencies {

```<code>compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.android.support:design:23.0.1'
</code>```

}

```<code><android.support.design.widget.FloatingActionButton
 android:id="id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:clickable="true"
android:src="@drawable/ic_done_white_24px"
/>
</code>```

Body:
I am using a floating button. The image source I am using is also proper but not sure while setting it is showing it as dot in the center. Screenshot and Code below :

<android.support.design.widget.FloatingActionButton
        android:id="@+id/fab_add_cg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:elevation="10dp"
        app:borderWidth="0dp"
        app:backgroundTint="@color/blue_4a90e2"
        android:src="@drawable/addbutton"/>

Body:
Add the latest support libraries to your app build gradle file and build your project

dependencies {

compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.android.support:design:23.0.1'

}

<android.support.design.widget.FloatingActionButton
 android:id="id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:clickable="true"
android:src="@drawable/ic_done_white_24px"
/>


问:
Set data of a Multiple Select2 element through javascript
I'm loading multiple values into a Select2 element through Javascript, ajax and jquery. While the data is loading properly and can be accessed once loaded, I'm unable to set stored data in the Select2 element.

Edit: I'm using Select2 v3.5.

My code:

HTML:

```<code><input class="jsData" style="width: 100%"  id="select2Data"></input>
</code>```

Javascript:

```<code> $(".jsData").select2({
                        ajax: {
                            minimumInputLength: 4,
                            contentType: 'application/json',
                            url: '<%=Url.Action("GetData","Controller")%>',
                            type: 'POST',
                            dataType: 'json',
                            data: function (term) {
                                return {
                                    sSearchTerm: term
                                };
                            },
                            results: function (data) {
                                return {
                                    results: $.map(JSON.parse(data), function (item) {
                                        return {
                                            text: item.term,
                                            slug: item.slug,
                                            id: item.Id
                                        }
                                    })
                                };
                            }
                        },
                        multiple: true
                    });
</code>```

So, this creates a Select2 element where I can traverse to and from a database and load data depending on what I've typed. I can also access the data (entered by the user) using the following line:

```<code>$('.jsData').select2('val')
</code>```

The above line returns an array, which I can store in the database. My current objective is to set the stored data back into the Select2 element. Any help in this matter would be most welcome.

Update: A relevant link for what I want to accomplish:
https://select2.github.io/examples.html#programmatic

I want the example of setting multiple elements in Select2. However, the difference would be in the fact that the example in the Select2 documentation brings data at the time of loading the page, while I will be making trips to fetch the data.

答:
The Select2 v3.5.4 docs are a bit confusing around this. I think there's a typo in the docs that's misleading.

First, notice that when I retrieve the data from the remote source I'm returning it as an object in the format of {id: ##, name: NAME}.

The first step is to add the initSelection parameter and pass the function to retrieve the previously selected items.

The next step, where I believe there's a typo, is to define the formatSelection parameter (not the formatResult it states in the docs). This function defines how the previously selected result is displayed. In this case I'm merely showing the name property of the result.

The formatResult parameter defines how newly selected options are displayed. You'll notice formatResult and formatSelection are the same below. I could have reused a single function but felt this was better for demonstration.

```<code>$(document).ready(function() {
  function formatResult(data) {
    return data.name;
  };

  function formatSelection(data) {
    return data.name;
  }

  $(".jsData").select2({
    ajax: {
      minimumInputLength: 4,
      url: "https://jsonplaceholder.typicode.com/users",
      type: "GET",
      dataType: "json",
      results: function(data) {
        return {
          results: $.map(data, function(user) {
            return {
              name: user.name,
              id: user.id
            };
          })
        };
      }
    },
    initSelection: function(element, callback) {
      var id = $(element).val();
      if (id !== "") {
        $.ajax("https://jsonplaceholder.typicode.com/users/" + id, {
          dataType: "json"
        }).done(function(data) {
          callback(data);
        });
      }
    },
    formatResult: formatResult,
    formatSelection: formatSelection,
    multiple: true
  });
});
</code>```

Here's the full working example:

$(document).ready(function() {
  function formatResult(data) {
    return data.name;
  };

  function formatSelection(data) {
    return data.name;
  }

  $(".jsData").select2({
    ajax: {
      minimumInputLength: 4,
      url: "https://jsonplaceholder.typicode.com/users",
      type: "GET",
      dataType: "json",
      results: function(data) {
        return {
          results: $.map(data, function(user) {
            return {
              name: user.name,
              id: user.id
            };
          })
        };
      }
    },
    initSelection: function(element, callback) {
      var id = $(element).val();
      if (id !== "") {
        $.ajax("https://jsonplaceholder.typicode.com/users/" + id, {
          dataType: "json"
        }).done(function(data) {
          callback(data);
        });
      }
    },
    formatResult: formatResult,
    formatSelection: formatSelection,
    multiple: true
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.jsData {
  width: 200px;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css" rel="stylesheet"/>

<input class="jsData" style="width: 100%"  id="select2Data" value="10"></input>```

Body:
I'm loading multiple values into a Select2 element through Javascript, ajax and jquery. While the data is loading properly and can be accessed once loaded, I'm unable to set stored data in the Select2 element.

Edit: I'm using Select2 v3.5.

My code:

HTML:

<input class="jsData" style="width: 100%"  id="select2Data"></input>

Javascript:

 $(".jsData").select2({
                        ajax: {
                            minimumInputLength: 4,
                            contentType: 'application/json',
                            url: '<%=Url.Action("GetData","Controller")%>',
                            type: 'POST',
                            dataType: 'json',
                            data: function (term) {
                                return {
                                    sSearchTerm: term
                                };
                            },
                            results: function (data) {
                                return {
                                    results: $.map(JSON.parse(data), function (item) {
                                        return {
                                            text: item.term,
                                            slug: item.slug,
                                            id: item.Id
                                        }
                                    })
                                };
                            }
                        },
                        multiple: true
                    });

So, this creates a Select2 element where I can traverse to and from a database and load data depending on what I've typed. I can also access the data (entered by the user) using the following line:

$('.jsData').select2('val')

The above line returns an array, which I can store in the database. My current objective is to set the stored data back into the Select2 element. Any help in this matter would be most welcome.

Update: A relevant link for what I want to accomplish:
https://select2.github.io/examples.html#programmatic

I want the example of setting multiple elements in Select2. However, the difference would be in the fact that the example in the Select2 documentation brings data at the time of loading the page, while I will be making trips to fetch the data.

Body:
The Select2 v3.5.4 docs are a bit confusing around this. I think there's a typo in the docs that's misleading.

First, notice that when I retrieve the data from the remote source I'm returning it as an object in the format of {id: ##, name: NAME}.

The first step is to add the initSelection parameter and pass the function to retrieve the previously selected items.

The next step, where I believe there's a typo, is to define the formatSelection parameter (not the formatResult it states in the docs). This function defines how the previously selected result is displayed. In this case I'm merely showing the name property of the result.

The formatResult parameter defines how newly selected options are displayed. You'll notice formatResult and formatSelection are the same below. I could have reused a single function but felt this was better for demonstration.

$(document).ready(function() {
  function formatResult(data) {
    return data.name;
  };

  function formatSelection(data) {
    return data.name;
  }

  $(".jsData").select2({
    ajax: {
      minimumInputLength: 4,
      url: "https://jsonplaceholder.typicode.com/users",
      type: "GET",
      dataType: "json",
      results: function(data) {
        return {
          results: $.map(data, function(user) {
            return {
              name: user.name,
              id: user.id
            };
          })
        };
      }
    },
    initSelection: function(element, callback) {
      var id = $(element).val();
      if (id !== "") {
        $.ajax("https://jsonplaceholder.typicode.com/users/" + id, {
          dataType: "json"
        }).done(function(data) {
          callback(data);
        });
      }
    },
    formatResult: formatResult,
    formatSelection: formatSelection,
    multiple: true
  });
});

Here's the full working example:

$(document).ready(function() {
  function formatResult(data) {
    return data.name;
  };

  function formatSelection(data) {
    return data.name;
  }

  $(".jsData").select2({
    ajax: {
      minimumInputLength: 4,
      url: "https://jsonplaceholder.typicode.com/users",
      type: "GET",
      dataType: "json",
      results: function(data) {
        return {
          results: $.map(data, function(user) {
            return {
              name: user.name,
              id: user.id
            };
          })
        };
      }
    },
    initSelection: function(element, callback) {
      var id = $(element).val();
      if (id !== "") {
        $.ajax("https://jsonplaceholder.typicode.com/users/" + id, {
          dataType: "json"
        }).done(function(data) {
          callback(data);
        });
      }
    },
    formatResult: formatResult,
    formatSelection: formatSelection,
    multiple: true
  });
});

.jsData {
  width: 200px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css" rel="stylesheet"/>

<input class="jsData" style="width: 100%"  id="select2Data" value="10"></input>


答:
Null in the terms of RDBMS has a special meaning, it stands for unknown, invalid, can't be applied to etc., and that's why can't be cast (what bool value (true, false) should be used for unknown?). Try  dr.IsNull("IsUpperCase"):

```<code> ch_Uppercase.Checked = !dr.IsNull("IsUpperCase") && Convert.ToBoolean(dr["IsUpperCase"]);
</code>```

Title: When Checkbox value is null. Program throws this error" Object cannot be cast from DBNull to other types."

Body:
Null in the terms of RDBMS has a special meaning, it stands for unknown, invalid, can't be applied to etc., and that's why can't be cast (what bool value (true, false) should be used for unknown?). Try  dr.IsNull("IsUpperCase"):

 ch_Uppercase.Checked = !dr.IsNull("IsUpperCase") && Convert.ToBoolean(dr["IsUpperCase"]);


问:
VBA load large data from text file to Excel
I have a problem loading data to Excel from a text file.
The text file has about 230,000 lines and each line has exactly 130 characters. My goal is to get, from each line, specific data for what I'm trying to load the file into Excel and then retrieve the data I need.

First, I used the following code, but it takes about 7 minutes.

```<code>Sub leerTXT()
Dim strArchivo As String 'ruta del archivo
Dim intResultado As Integer 'resultado del dialogo

'---------- RUTA DEL ARCHIVO ----------
'Abrir dialog y preparar
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intResultado = Application.FileDialog(msoFileDialogOpen).Show

'sólo si hay resultado positivo abrir fichero y leer
If intResultado <> 0 Then
    strArchivo = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
    On Error GoTo lblError:

Dim strFila As String 'filas que se van a leer
Dim iFila As Long  'numero de fila en la que se esta en el fichero
Dim jFila As Long 'numero de fila en el excel
'posicionarse en la fila 1
iFila = 1
jFila = 1

    'abrir el archivo
    Open strArchivo For Input As #1
    'loop mientras no se ha llegado al final del archivo
    Do Until EOF(1)

        If iFila Mod 70 > 17 Then
            'leer la fila actual
            Line Input #1, strFila

            'leer la linea y copiar a celda
            Cells(jFila, 1) = strFila

            jFila = jFila + 1
        End If

        'incrementar iFila en uno y pasar a la siguiente fila
        iFila = iFila + 1

    'loopear mientras condicion
    Loop

End If

'cerrar el archivo
Close #1

lblError:
If Err.Number <> 0 Then
MsgBox (Err.Number)
MsgBox (Err.Description)
Err.Clear
'cerrar el archivo
Close #1
End If

End Sub
</code>```

But as I said, that takes too long, so I searched for other ways and I saw something like the following:

```<code>Dim FSO As Object, MyFile As Object
Dim FileName As String, Arr As Variant
Dim f As Long

FileName = textfilename
Set FSO = CreateObject("Scripting.FileSystemObject")
Set MyFile = FSO.OpenTextFile(FileName, 1)
Arr = Split(MyFile.ReadAll, vbNewLine) ' Arr is zero-based array

Dim BigGuy(0 To UBound(Arr, 1), 1 To 1) As Long

Dim I As Long
For I = 0 To UBound(Arr)
    BigGuy(I, 1) = I
Next
'For test
'Fill column A from this Array Arr
   'UBound(Arr) + 1 Application.Transpose(
Range("A1:A500") = BigGuy
</code>```

The clue is to use array and paste range at it seems to be faster, but as the file is too long to transpose, I need to transpose it manually, but UBound(Arr) doesn't work and I don't know how to import the data.

And by the way, is there any way of just retrieving specific characters from the file (in an exact position), as every line has exactly the same length?

答:
The array size is limited to 65 536 elements (Integer is 16-bit number). In fact only to 32767 because it is signed number.

You can combine first method with second approach reading file in chunks of 32767 elements and fill them by array.

Something like this:

```<code>Option Explicit
Public Sub test()
Dim strFila As String
Dim i As Integer, j As Long
Dim rng As String

    Dim BigGuy(1 To 32767, 1 To 1)
    i = 1
    j = 1
    Open "c:\temp\data.txt" For Input As #1
    Do Until EOF(1)
        Line Input #1, strFila
        BigGuy(i, 1) = strFila
        i = i + 1
        If i = 32767 Then
            rng = "A" & j & ":A" & j + i - 1
            Range(rng) = BigGuy
            j = j + 32766
            i = 1
        End If
    Loop

    If i > 1 Then
        rng = "A" & j & ":A" & j + i - 2
        Range(rng) = BigGuy
    End If
    Close #1

End Sub
</code>```

Performance - around 3 sec on my station.

To extract part of text on well known position use mid$()

Body:
I have a problem loading data to Excel from a text file.
The text file has about 230,000 lines and each line has exactly 130 characters. My goal is to get, from each line, specific data for what I'm trying to load the file into Excel and then retrieve the data I need.

First, I used the following code, but it takes about 7 minutes.

Sub leerTXT()
Dim strArchivo As String 'ruta del archivo
Dim intResultado As Integer 'resultado del dialogo

'---------- RUTA DEL ARCHIVO ----------
'Abrir dialog y preparar
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intResultado = Application.FileDialog(msoFileDialogOpen).Show

'sólo si hay resultado positivo abrir fichero y leer
If intResultado <> 0 Then
    strArchivo = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
    On Error GoTo lblError:

Dim strFila As String 'filas que se van a leer
Dim iFila As Long  'numero de fila en la que se esta en el fichero
Dim jFila As Long 'numero de fila en el excel
'posicionarse en la fila 1
iFila = 1
jFila = 1

    'abrir el archivo
    Open strArchivo For Input As #1
    'loop mientras no se ha llegado al final del archivo
    Do Until EOF(1)

        If iFila Mod 70 > 17 Then
            'leer la fila actual
            Line Input #1, strFila

            'leer la linea y copiar a celda
            Cells(jFila, 1) = strFila

            jFila = jFila + 1
        End If

        'incrementar iFila en uno y pasar a la siguiente fila
        iFila = iFila + 1

    'loopear mientras condicion
    Loop

End If

'cerrar el archivo
Close #1

lblError:
If Err.Number <> 0 Then
MsgBox (Err.Number)
MsgBox (Err.Description)
Err.Clear
'cerrar el archivo
Close #1
End If

End Sub

But as I said, that takes too long, so I searched for other ways and I saw something like the following:

Dim FSO As Object, MyFile As Object
Dim FileName As String, Arr As Variant
Dim f As Long

FileName = textfilename
Set FSO = CreateObject("Scripting.FileSystemObject")
Set MyFile = FSO.OpenTextFile(FileName, 1)
Arr = Split(MyFile.ReadAll, vbNewLine) ' Arr is zero-based array

Dim BigGuy(0 To UBound(Arr, 1), 1 To 1) As Long

Dim I As Long
For I = 0 To UBound(Arr)
    BigGuy(I, 1) = I
Next
'For test
'Fill column A from this Array Arr
   'UBound(Arr) + 1 Application.Transpose(
Range("A1:A500") = BigGuy

The clue is to use array and paste range at it seems to be faster, but as the file is too long to transpose, I need to transpose it manually, but UBound(Arr) doesn't work and I don't know how to import the data.

And by the way, is there any way of just retrieving specific characters from the file (in an exact position), as every line has exactly the same length?

Body:
The array size is limited to 65 536 elements (Integer is 16-bit number). In fact only to 32767 because it is signed number.

You can combine first method with second approach reading file in chunks of 32767 elements and fill them by array.

Something like this:

Option Explicit
Public Sub test()
Dim strFila As String
Dim i As Integer, j As Long
Dim rng As String

    Dim BigGuy(1 To 32767, 1 To 1)
    i = 1
    j = 1
    Open "c:\temp\data.txt" For Input As #1
    Do Until EOF(1)
        Line Input #1, strFila
        BigGuy(i, 1) = strFila
        i = i + 1
        If i = 32767 Then
            rng = "A" & j & ":A" & j + i - 1
            Range(rng) = BigGuy
            j = j + 32766
            i = 1
        End If
    Loop

    If i > 1 Then
        rng = "A" & j & ":A" & j + i - 2
        Range(rng) = BigGuy
    End If
    Close #1

End Sub

Performance - around 3 sec on my station.

To extract part of text on well known position use mid$()


问:
How to enable scaling-up the X & Y Axis es based on the data set in C#?
I want to scale X and Y axis by considering data set in C#.

This is part of data set in .csv file

```<code>Name,Speed,Distance
Amal,20.50,100.20
Kamal,52.60,254.90
Nimal,42.00,245.00
Perera,20.30,142.00
Kasun,56.40,368.00
Piyal,45.60,784.00
Roy,45.00,521.00
Tony,25.00,36.00
Nikky,36.00,56.00
Jems,47.00,48.00
Jully,56.00,120.00
Tizz,78.00,354.00
Taly,45.00,100.00
Row,18.00,350.00
Saga,15.60,250.00
Peter,45.00,120.00
Taw,89.00,56.00
Nanny,78.60,487.00
Jumo,108.00,150.00
</code>```

This is the code that I used to plot the graph.

```<code>private void Output_Load(object sender, EventArgs e)
{

    List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

    // Loops through each lines in the CSV
    foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
    {
        // here line stands for each line in the csv file

        string[] InCsvLine = line.Split(',');

        // creating an object of type Graph based on the each csv line

        Graph Inst1 = new Graph();

        Inst1.Speed = double.Parse(InCsvLine[1]);
        Inst1.Distance= double.Parse(InCsvLine[2]);

        chart1.Series["Distance"].YAxisType = AxisType.Primary;
        chart1.Series["Distance"].Points.AddXY(Inst1.Speed, Inst1.Distance);
        chart1.Series["Distance"].ChartType = SeriesChartType.FastLine;

        ChartArea CA = chart1.ChartAreas[0];
        CA.AxisX.ScaleView.Zoomable = false;
        CA.AxisY.ScaleView.Zoomable = false;
        CA.CursorX.AutoScroll = true;
        CA.CursorX.IsUserSelectionEnabled = true;

    }
}
</code>```

and this is the class that store data.

```<code>class Graph
{
    public string Name { get; set; } // property to  store Name
    public double Speed{ get; set; } // property to store Speed
    public double Distance { get; set; } // property to store Distance
}
</code>```

Now I want to scale this X and Y axis by considering data set in .csv file. Scale should be under condition.

I explain that by getting an example for that.
lets say in data set we have:

the Distance max = 784.00 & min = 36.00

then that Y axis should show values only from 33 to 787

```<code>(means + / - 0.3)
</code>```

program should be want to get Min and Max value in .csv file during in file read.

like wise think about X axis.

Can you tell me how I to code that? Any help very appreciated.

答:
program should be want to get Min and Max value in .csv file during in file read.

Why not get the min and max values after all data is loaded? In your case it seems to be preferable to split the loading the data part from the initialization of the chart details. One point I see in your code that you don't use List<Graph> ObservingData to store the items. I added it in the solution because this will enable you to pull out the minimum and maximum distance values after the entire data set is loaded. Then you can set the axis interval.

```<code>private void Output_Load(object sender, EventArgs e)
{

    List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

    // Loops through each lines in the CSV
    foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
    {
        // here line stands for each line in the csv file

        string[] InCsvLine = line.Split(',');

        // creating an object of type Graph based on the each csv line
        Graph Inst1 = new Graph();
        Inst1.Speed = double.Parse(InCsvLine[1]);
        Inst1.Distance= double.Parse(InCsvLine[2]);

        chart1.Series["Distance"].Points.AddXY(Inst1.Speed, Inst1.Distance);

        // you forgot to store the items:
        ObservingData.Add(Inst1);
    }

        // after the loop you can pull out the min and max values to adjust your axes:
        double min = ObservingData.Min(x=>x.Distance);
        double max = ObservingData.Maxn(x=>x.Distance);

        chart1.ChartAreas[0].AxisY.Minimum = min - 3;
        chart1.ChartAreas[0].AxisY.Maximum = max + 3;

        chart1.Series["Distance"].YAxisType = AxisType.Primary;
        chart1.Series["Distance"].ChartType = SeriesChartType.FastLine;

        ChartArea CA = chart1.ChartAreas[0];
        CA.AxisX.ScaleView.Zoomable = false;
        CA.AxisY.ScaleView.Zoomable = false;
        CA.CursorX.AutoScroll = true;
        CA.CursorX.IsUserSelectionEnabled = true;
}
</code>```

EDIT:

As for you X-Axis:

You cannot treat the X-axis as you treat the Y-axis. The X-axis shows values of Speed
so you should also get these values for the minimum and maximum of it:

```<code>double minX = ObservingData.Min(x=>x.Speed);
double maxX = ObservingData.Maxn(x=>x.Speed);
</code>```

The next point would be also to use these values! Also the + and - values should fit the
range of the Speed values 0.3 seems to be more appropriate in this case:

```<code>chart1.ChartAreas[0].AxisX.Minimum = minX - 0.3;
chart1.ChartAreas[0].AxisX.Maximum = maxX + 0.3;
</code>```

Body:
I want to scale X and Y axis by considering data set in C#.

This is part of data set in .csv file

Name,Speed,Distance
Amal,20.50,100.20
Kamal,52.60,254.90
Nimal,42.00,245.00
Perera,20.30,142.00
Kasun,56.40,368.00
Piyal,45.60,784.00
Roy,45.00,521.00
Tony,25.00,36.00
Nikky,36.00,56.00
Jems,47.00,48.00
Jully,56.00,120.00
Tizz,78.00,354.00
Taly,45.00,100.00
Row,18.00,350.00
Saga,15.60,250.00
Peter,45.00,120.00
Taw,89.00,56.00
Nanny,78.60,487.00
Jumo,108.00,150.00

This is the code that I used to plot the graph.

private void Output_Load(object sender, EventArgs e)
{

    List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

    // Loops through each lines in the CSV
    foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
    {
        // here line stands for each line in the csv file

        string[] InCsvLine = line.Split(',');

        // creating an object of type Graph based on the each csv line

        Graph Inst1 = new Graph();

        Inst1.Speed = double.Parse(InCsvLine[1]);
        Inst1.Distance= double.Parse(InCsvLine[2]);

        chart1.Series["Distance"].YAxisType = AxisType.Primary;
        chart1.Series["Distance"].Points.AddXY(Inst1.Speed, Inst1.Distance);
        chart1.Series["Distance"].ChartType = SeriesChartType.FastLine;

        ChartArea CA = chart1.ChartAreas[0];
        CA.AxisX.ScaleView.Zoomable = false;
        CA.AxisY.ScaleView.Zoomable = false;
        CA.CursorX.AutoScroll = true;
        CA.CursorX.IsUserSelectionEnabled = true;

    }
}

and this is the class that store data.

class Graph
{
    public string Name { get; set; } // property to  store Name
    public double Speed{ get; set; } // property to store Speed
    public double Distance { get; set; } // property to store Distance
}

Now I want to scale this X and Y axis by considering data set in .csv file. Scale should be under condition.

I explain that by getting an example for that.
lets say in data set we have:

the Distance max = 784.00 & min = 36.00

then that Y axis should show values only from 33 to 787

(means + / - 0.3)

program should be want to get Min and Max value in .csv file during in file read.

like wise think about X axis.

Can you tell me how I to code that? Any help very appreciated.

Body:
program should be want to get Min and Max value in .csv file during in file read.

Why not get the min and max values after all data is loaded? In your case it seems to be preferable to split the loading the data part from the initialization of the chart details. One point I see in your code that you don't use List<Graph> ObservingData to store the items. I added it in the solution because this will enable you to pull out the minimum and maximum distance values after the entire data set is loaded. Then you can set the axis interval.

private void Output_Load(object sender, EventArgs e)
{

    List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

    // Loops through each lines in the CSV
    foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
    {
        // here line stands for each line in the csv file

        string[] InCsvLine = line.Split(',');

        // creating an object of type Graph based on the each csv line
        Graph Inst1 = new Graph();
        Inst1.Speed = double.Parse(InCsvLine[1]);
        Inst1.Distance= double.Parse(InCsvLine[2]);

        chart1.Series["Distance"].Points.AddXY(Inst1.Speed, Inst1.Distance);

        // you forgot to store the items:
        ObservingData.Add(Inst1);
    }

        // after the loop you can pull out the min and max values to adjust your axes:
        double min = ObservingData.Min(x=>x.Distance);
        double max = ObservingData.Maxn(x=>x.Distance);

        chart1.ChartAreas[0].AxisY.Minimum = min - 3;
        chart1.ChartAreas[0].AxisY.Maximum = max + 3;

        chart1.Series["Distance"].YAxisType = AxisType.Primary;
        chart1.Series["Distance"].ChartType = SeriesChartType.FastLine;

        ChartArea CA = chart1.ChartAreas[0];
        CA.AxisX.ScaleView.Zoomable = false;
        CA.AxisY.ScaleView.Zoomable = false;
        CA.CursorX.AutoScroll = true;
        CA.CursorX.IsUserSelectionEnabled = true;
}

EDIT:

As for you X-Axis:

You cannot treat the X-axis as you treat the Y-axis. The X-axis shows values of Speed
so you should also get these values for the minimum and maximum of it:

double minX = ObservingData.Min(x=>x.Speed);
double maxX = ObservingData.Maxn(x=>x.Speed);

The next point would be also to use these values! Also the + and - values should fit the
range of the Speed values 0.3 seems to be more appropriate in this case:

chart1.ChartAreas[0].AxisX.Minimum = minX - 0.3;
chart1.ChartAreas[0].AxisX.Maximum = maxX + 0.3;


问:
How can I use checkboxGroupInput in Shiny to control several reactive layers in a ggplot2 plot efficiently?
I have made three reactive layers in my graph. In the reproducible example below, the graph starts with function1 drawn. If I check function2, shiny recalculates and redraws function1 and function2. Then if I tick function3, all 3 functions are recalculated and redrawn.

Say the functions I want to run are very long inferences that take several minutes each.

How can I make it so that when I check (or uncheck) one function, shiny does not recalculate and redraw all checked functions?

In the code below, I have included print statements which show that each reactive is run each time renderPlot is called (which is when input$fun changes).

```<code>library(shiny)
library(ggplot2)
x <-  seq(0, 10, by=0.1)

runApp(shinyApp(

  ui = shinyUI(fluidPage(
    titlePanel("Test Shiny"),
    sidebarLayout(
      sidebarPanel(
        checkboxGroupInput("fun", label = "Function",
                           choices = list("function1: x^2" = 1,
                                          "function2: x^2 + x" = 2,
                                          "function3: x^2 - x" = 3),
                           selected = c(1))
      ),
      mainPanel(
        plotOutput("plot")
      )
    )
  )),

  server = shinyServer(function(input, output) {

    fn1 <- reactive({
      print("we are in fn1 <- reactive({})")
      if (1 %in% input$fun ) {
        geom_line(mapping = aes(x, y=x^2), color="blue") }
    })

    fn2 <- reactive({
      print("we are in fn2 <- reactive({})")
      if (2 %in% input$fun)  {
        geom_line(mapping = aes(x, y=x^2 + x), color="red") }
    })

    fn3 <- reactive({
      print("we are in fn3 <- reactive({})")
      if (3 %in% input$fun) {
        geom_line(mapping = aes(x, y=x^2 - x), color="green") }
    })

    output$plot <- renderPlot({

      cat("\n we are in output$plot <-  renderPlot({}) \n")
      ggplot() + fn1() + fn2() + fn3()
    })
  })
))
</code>```

I can achieve this efficiency using single checkboxes (checkboxInput) but I would prefer not to use single checkboxes. Single checkboxes don’t look as good, unless there is a way to make them look more like checkbox Group Inputs?

I have been trying to work this out and searching SO for some time. I would be very grateful for any help with this!!!

EDIT
Here is some code in response to @Jimbou ’s shiny code using base R plot() and lines(). Please see my comment below the shiny code @Jimbou provided.

```<code>    output$plot <- renderPlot({
  cat("\n we are in output$plot <- renderPlot({}) \n")
  plot(NULL, xlim = c(0,10), ylim = c(0,100))
  if(1 %in% input$fun) {
    print("we are in  if(1 %in% input$fun){} ")
    lines(x=x, y=x^2, col=2)
  }
  if(2 %in% input$fun) {
    print("we are in  if(2 %in% input$fun){} ")
    lines(x=x, y=x^2 + x, col=3)
  }
  if(3 %in% input$fun) {
    print("we are in  if(3 %in% input$fun){} ")
    lines(x=x, y=x^2 - x, col=4)
  }
})
</code>```

答:
Here a solution using the base R plotting functionality with lines.</p>

```<code>library(shiny)
library(ggplot2)
x <-  seq(0, 10, by=0.1)

runApp(shinyApp(

  ui = shinyUI(fluidPage(
    titlePanel("Test Shiny"),
    sidebarLayout(
      sidebarPanel(
        checkboxGroupInput("fun", label = "Function",
                           choices = list("function1: x^2" = 1,
                                          "function2: x^2 + x" = 2,
                                          "function3: x^2 - x" = 3),
                           selected = c(1))
      ),
      mainPanel(
        plotOutput("plot")
      )
    )
  )),

  server = shinyServer(function(input, output) {

    output$plot <- renderPlot({
      plot(NULL, xlim = c(0,10), ylim = c(0,100))
      if(1 %in% input$fun) lines(x=x, y=x^2, col=2)
      if(2 %in% input$fun) lines(x=x, y=x^2 + x, col=3)
      if(3 %in% input$fun) lines(x=x, y=x^2 - x, col=4)
    })
  })
))
</code>```

Body:
I have made three reactive layers in my graph. In the reproducible example below, the graph starts with function1 drawn. If I check function2, shiny recalculates and redraws function1 and function2. Then if I tick function3, all 3 functions are recalculated and redrawn.

Say the functions I want to run are very long inferences that take several minutes each.

How can I make it so that when I check (or uncheck) one function, shiny does not recalculate and redraw all checked functions?

In the code below, I have included print statements which show that each reactive is run each time renderPlot is called (which is when input$fun changes).

library(shiny)
library(ggplot2)
x <-  seq(0, 10, by=0.1)

runApp(shinyApp(

  ui = shinyUI(fluidPage(
    titlePanel("Test Shiny"),
    sidebarLayout(
      sidebarPanel(
        checkboxGroupInput("fun", label = "Function",
                           choices = list("function1: x^2" = 1,
                                          "function2: x^2 + x" = 2,
                                          "function3: x^2 - x" = 3),
                           selected = c(1))
      ),
      mainPanel(
        plotOutput("plot")
      )
    )
  )),

  server = shinyServer(function(input, output) {

    fn1 <- reactive({
      print("we are in fn1 <- reactive({})")
      if (1 %in% input$fun ) {
        geom_line(mapping = aes(x, y=x^2), color="blue") }
    })

    fn2 <- reactive({
      print("we are in fn2 <- reactive({})")
      if (2 %in% input$fun)  {
        geom_line(mapping = aes(x, y=x^2 + x), color="red") }
    })

    fn3 <- reactive({
      print("we are in fn3 <- reactive({})")
      if (3 %in% input$fun) {
        geom_line(mapping = aes(x, y=x^2 - x), color="green") }
    })

    output$plot <- renderPlot({

      cat("\n we are in output$plot <-  renderPlot({}) \n")
      ggplot() + fn1() + fn2() + fn3()
    })
  })
))

I can achieve this efficiency using single checkboxes (checkboxInput) but I would prefer not to use single checkboxes. Single checkboxes don’t look as good, unless there is a way to make them look more like checkbox Group Inputs?

I have been trying to work this out and searching SO for some time. I would be very grateful for any help with this!!!

EDIT
Here is some code in response to @Jimbou ’s shiny code using base R plot() and lines(). Please see my comment below the shiny code @Jimbou provided.

    output$plot <- renderPlot({
  cat("\n we are in output$plot <- renderPlot({}) \n")
  plot(NULL, xlim = c(0,10), ylim = c(0,100))
  if(1 %in% input$fun) {
    print("we are in  if(1 %in% input$fun){} ")
    lines(x=x, y=x^2, col=2)
  }
  if(2 %in% input$fun) {
    print("we are in  if(2 %in% input$fun){} ")
    lines(x=x, y=x^2 + x, col=3)
  }
  if(3 %in% input$fun) {
    print("we are in  if(3 %in% input$fun){} ")
    lines(x=x, y=x^2 - x, col=4)
  }
})

Body:
Here a solution using the base R plotting functionality with lines.

library(shiny)
library(ggplot2)
x <-  seq(0, 10, by=0.1)

runApp(shinyApp(

  ui = shinyUI(fluidPage(
    titlePanel("Test Shiny"),
    sidebarLayout(
      sidebarPanel(
        checkboxGroupInput("fun", label = "Function",
                           choices = list("function1: x^2" = 1,
                                          "function2: x^2 + x" = 2,
                                          "function3: x^2 - x" = 3),
                           selected = c(1))
      ),
      mainPanel(
        plotOutput("plot")
      )
    )
  )),

  server = shinyServer(function(input, output) {

    output$plot <- renderPlot({
      plot(NULL, xlim = c(0,10), ylim = c(0,100))
      if(1 %in% input$fun) lines(x=x, y=x^2, col=2)
      if(2 %in% input$fun) lines(x=x, y=x^2 + x, col=3)
      if(3 %in% input$fun) lines(x=x, y=x^2 - x, col=4)
    })
  })
))


问:
Chef insufficient Permissions error on file resource
I have a file, let say xyz.sh, mounted from different file system on centos and root user does not have access to change the permissions of the file.
Current permissions are 755 for the file.
My cookbook's file resource checks for the permissions and if it is not 755 then change it to 755.
When I run the cookbook as root user it is giving an exception as 'Insufficient Permissions'.
Now I would have expected this exception if the file had some different permissions and chef tried to change it but not able to do that, but here as permissions are same as expectation, then why am I getting this exception?
Please help me!</p>

答: Root is supposed to have permission to access any file in most cases (give or take some retrofits of the Unix filesystem model like POSIX ACLs). Regardless, just remove the mode property from the resource and Chef won't try to enforce anything.


答:
Use onchange() for <select></select> tag instead of onclick().

function view_graph(val){
alert(val);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="Consolidate Report" class="input" id="x" onchange="view_graph(this.value)">
   <option value="0">--Select--</option>
    <option value="report">Consolidate Report</option>
    <option value="graph">View Graph</option>
    <option value="excel">Export Excel</option>
</select></code>```

Title: Onclick function is not working in Chrome browser

Body:
This is working fine in Internet Explorer and Firefox but not working in Chrome browser

<select name="Consolidate Report" class="input">
    <option value="">Consolidate Report</option>
    <option value="" onclick="view_graph()">View Graph</option>
    <option value="" onclick="export_graph()">Export Excel</option>
</select>

Body:
Use onchange() for <select></select> tag instead of onclick().

function view_graph(val){
alert(val);
}

<select name="Consolidate Report" class="input" id="x" onchange="view_graph(this.value)">
   <option value="0">--Select--</option>
    <option value="report">Consolidate Report</option>
    <option value="graph">View Graph</option>
    <option value="excel">Export Excel</option>
</select>


问:
Selenium-java,TestNG and jenkins on CentOS
I have recently setup integration of Selenium (Java bindings) with TestNG and Jenkins in a Windows environment, which is running absolutely fine.

I have created a batch file of TestNG and executed it through Jenkins using Windows batch file command. Now the situation is that I have to run these Selenium test cases on a Linux (Centos 7) environment as the Jenkins is setup there.

I am not quite sure how I should approach that. I have gone through some articles, but really could not find anything related to this for Selenium/Java things.

I have already done some initial steps, but I'm stuck after that:

I have setup CentOS 7;

Installed Java on it;

Installed Jenkins on it;

I have also installed xvfb as it would be required for headless execution.

From here I need some guidance in terms of how to proceed further, or put all things together. For example, should I move Selenium/Java project on VM and somehow run the TestNG file through Jenkins? (but not sure how to do that need some steps to follow or are there any more prerequisite to it). Or some other approach which is better.

It would be great if someone can guide me towards any article or can explain here with steps.

答:
Here's what you can try doing to get this working:

You need a version control system(VCS) such as GIT/SVN, wherein you would need to push in your test code. That way, your Jenkins Instance will be able to pull in code from the VCS.

Once you have pushed in your code into the VCS, you can create a build job which would pull code from your VCS, build it using a build tool such as Maven/Gradle/Ant and then execute your tests (again using the build tool)

To learn how to setup your Jenkins instance with Git (One of the popular VCS flavors), please refer to this blog.

To learn how to go about setting up a Continuous Integration system with Selenium, you can also refer to this blog post of mine.


问:
How to replace string with another string and keep case in php and mysql?
I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.
I need to replace it in PHP string and MySQL query too.

Example:

```<code>Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.
</code>```

I want to replace word 'place' with 'garden'.

```<code>Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.
</code>```

It should also work with phrases.

答:
I've created a function that will replace the word for you and keep the cases.

```<code>function replaceWithCase($source, $replacement, $string) {
    // Does the string contain the source word?
    if (strpos($string, $source) === false) {
        return false;
    }

    // If everything is uppercase, return the replacement fully uppercase
    if (ctype_upper($source)) {
        return str_replace($source, strtoupper($replacement));
    }

    // Set an array to work with
    $characters = array();

    // Split the source into characters
    $sourceParts = explode('', $source);

    // Loop throug the characters and set the case
    foreach ($sourceParts as $k => $sp) {
        if (ctype_upper($sp)) {
            $characters[$k] = true;
        } else {
            $characters[$k] = false;
        }
    }

    // Split the replacement into characters
    $replacementParts = explode('', $replacement);

    // Loop through characters and compare their case type
    foreach ($replacementParts as $k => $rp) {
        if (array_key_exists($k, $characters) && $characters[$k] === true) {
            $newWord[] = strtoupper($rp);
        } else {
            $newWord[] = strtolower($rp);
        }
    }

    return substr_replace($source, implode('', $newWord), $string);
}

// usage
echo replaceWithCase('AppLes', 'bananas', 'Comparing AppLes to pears');
</code>```

Note: it is untested and might need some tweaking

Body:
I'm trying to do some sort of translator which would be able to keep text uppercase/lowercase.
I need to replace it in PHP string and MySQL query too.

Example:

Potato is jumping all over the PLACE.
Potato is jumping all over the pLAcE. (optional)
Potato is jumping all over the place.
Potato is jumping all over the Place.

I want to replace word 'place' with 'garden'.

Potato is jumping all over the GARDEN.
Potato is jumping all over the gARdEe. (optional)
Potato is jumping all over the garden.
Potato is jumping all over the Garden.

It should also work with phrases.

Body:
I've created a function that will replace the word for you and keep the cases.

function replaceWithCase($source, $replacement, $string) {
    // Does the string contain the source word?
    if (strpos($string, $source) === false) {
        return false;
    }

    // If everything is uppercase, return the replacement fully uppercase
    if (ctype_upper($source)) {
        return str_replace($source, strtoupper($replacement));
    }

    // Set an array to work with
    $characters = array();

    // Split the source into characters
    $sourceParts = explode('', $source);

    // Loop throug the characters and set the case
    foreach ($sourceParts as $k => $sp) {
        if (ctype_upper($sp)) {
            $characters[$k] = true;
        } else {
            $characters[$k] = false;
        }
    }

    // Split the replacement into characters
    $replacementParts = explode('', $replacement);

    // Loop through characters and compare their case type
    foreach ($replacementParts as $k => $rp) {
        if (array_key_exists($k, $characters) && $characters[$k] === true) {
            $newWord[] = strtoupper($rp);
        } else {
            $newWord[] = strtolower($rp);
        }
    }

    return substr_replace($source, implode('', $newWord), $string);
}

// usage
echo replaceWithCase('AppLes', 'bananas', 'Comparing AppLes to pears');

Note: it is untested and might need some tweaking


问:
Jquery not working to hide and show div until Bootstrap tab clicked
I have 2 different divs that need to appear depending on which tab is active.

If tab "#myTab class overview" is active then the "rental div" should show. If "#myTab class overview" is not active them the "homeo div" should show.

My function does not work on page load, on page load both divs appear. If i click either tab then only does my function work.

Do you know how to get my function to be working on page load.

jQuery(document).ready(function () {
            jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

            });
        })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rental">
DOWNLOAD APPLICATION
</div>

<div id="homeo">
Test
</div>

  <ul class="nav nav-pills">
    <li id="myTab" class="overview active">RENTAL</li>
    <li>HOMEOWNER</li>
  </ul></code>```

答:
Here is with demo

https://jsfiddle.net/jalayoza/cnsLfbza/

```<code>jQuery(document).ready(function () {
            if($('#myTab').hasClass('overview active'))
            {
                jQuery('#rental').show(), jQuery('#homeo').hide();
            }else
            {
                jQuery('#rental').hide(), jQuery('#homeo').show();
            }
            jQuery('a[data-toggle="tab"]').on('click', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

            });
        })

<div id="rental">
<a href="" target="_blank" class="btn btn-info btn-lg blue" role="button">DOWNLOAD APPLICATION</a>
</div>

<div id="homeo">
<a href="" target="_blank" class="btn btn-info btn-lg blue" role="button">Test</a>
</div>

  <ul class="nav nav-pills">
    <li id="myTab" class="overview active"><a data-toggle="tab" href="#home">RENTAL</a></li>
    <li><a data-toggle="tab" href="#homeowner">HOMEOWNER</a></li>
  </ul>
</code>```

Body:
I have 2 different divs that need to appear depending on which tab is active.

If tab "#myTab class overview" is active then the "rental div" should show. If "#myTab class overview" is not active them the "homeo div" should show.

My function does not work on page load, on page load both divs appear. If i click either tab then only does my function work.

Do you know how to get my function to be working on page load.

jQuery(document).ready(function () {
            jQuery('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

            });
        })

DOWNLOAD APPLICATION

Test

RENTAL

HOMEOWNER

Body:
Here is with demo

https://jsfiddle.net/jalayoza/cnsLfbza/

jQuery(document).ready(function () {
            if($('#myTab').hasClass('overview active'))
            {
                jQuery('#rental').show(), jQuery('#homeo').hide();
            }else
            {
                jQuery('#rental').hide(), jQuery('#homeo').show();
            }
            jQuery('a[data-toggle="tab"]').on('click', function (e) {
                if ($("#myTab")[0].className=='overview active')
                    jQuery('#rental').show(), jQuery('#homeo').hide();
                else
                    jQuery('#rental').hide(), jQuery('#homeo').show();

            });
        })

<div id="rental">
<a href="" target="_blank" class="btn btn-info btn-lg blue" role="button">DOWNLOAD APPLICATION</a>
</div>

<div id="homeo">
<a href="" target="_blank" class="btn btn-info btn-lg blue" role="button">Test</a>
</div>

  <ul class="nav nav-pills">
    <li id="myTab" class="overview active"><a data-toggle="tab" href="#home">RENTAL</a></li>
    <li><a data-toggle="tab" href="#homeowner">HOMEOWNER</a></li>
  </ul>