问:
Trouble converting a date to a string and passing to SQL
I'm getting the following error message:

System.InvalidCastException: Conversion from string "select * from [tbl_FBNK_Limit_Hi" to type 'Integer' is not valid.

My setup is really pretty simple. Here is all the code:

```<code>Imports System.Data.OleDb

Public Class Form1

    'Change Path Here:
    Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=path_here.accdb"
    Dim MyConn As OleDbConnection
    Dim da As OleDbDataAdapter
    Dim ds As DataSet
    Dim tables As DataTableCollection
    Dim source1 As New BindingSource
    Dim SqlStr As String
    Dim startDate As String
    Dim endDate As String

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        MyConn = New OleDbConnection
        MyConn.ConnectionString = connString
        ds = New DataSet
        tables = ds.Tables

        Dim startDate As DateTime = DateTimePicker1.Value.ToString("MM/dd/yyyy")
        Dim endDate As DateTime = DateTimePicker2.Value.ToString("MM/dd/yyyy")

        SqlStr = "select * from [tbl_Hist_Current] where AsOfDate >= #" & startDate & "# and AsOfDate <=#" & endDate & "#"

        da = New OleDbDataAdapter(SqlStr, MyConn)
        da.Fill(SqlStr, "tbl_Limit_Hist_Current")
        Dim view As New DataView(tables(0))
        source1.DataSource = view
        DataGridView1.DataSource = view
    End Sub
End Class
</code>```

When I copy/paste the SqlStr into Access it works fine, so it's gotta be something with the way the dates are being handled, or not handled. Can someone here give me a nudge in the right direction?

```<code>Private Sub LoadData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim connectionString As String = "Data Source=server_name;Initial Catalog=database_name;Integrated Security=True"
    Dim SqlStr As String
    Dim startDate As DateTime = DateTimePicker1.Value.ToString("MM/dd/yyyy")
    Dim endDate As DateTime = DateTimePicker2.Value.ToString("MM/dd/yyyy")

    SqlStr = "Select Field1, Field2, Field3, AsOfDate FROM [TBL_DATA_HIST] where AsOfDate >= '" & startDate & "' and AsOfDate <='" & endDate & "'"

    Dim connection As New SqlConnection(connectionString)
    Dim dataadapter As New SqlDataAdapter(SqlStr, connection)
    Dim ds As New DataSet()
    connection.Open()
    dataadapter.Fill(ds, "TBL_DATA_HIST")
    connection.Close()
    DataGridView1.DataSource = ds
    DataGridView1.DataMember = "TBL_DATA_HIST"

    ' Count rows in DG
    Dim int As Integer
    int = DataGridView1.Rows.Count()
    TextBox1.Text = int

End Sub
</code>```

答:
You can use the following solution, using parameter placeholders:

```<code>'Change Path Here:
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=path_here.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim SqlStr As String
Dim startDate As String
Dim endDate As String

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    MyConn = New OleDbConnection
    MyConn.ConnectionString = connString

    Dim startDate As DateTime = DateTimePicker1.Value
    Dim endDate As DateTime = DateTimePicker2.Value

    SqlStr = "select * from [tbl_Limit_Hist_Current] where AsOfDate >= ? and AsOfDate <= ?"

    da = New OleDbDataAdapter(SqlStr, MyConn)
    Dim selectCMD As New OleDbCommand(SqlStr, MyConn)
    da.SelectCommand = selectCMD

    selectCMD.Parameters.Add("@AsOfDate1", OleDbType.Date).Value = startDate
    selectCMD.Parameters.Add("@AsOfDate2", OleDbType.Date).Value = endDate

    ds = New DataSet
    da.Fill(ds, "tbl_Limit_Hist_Current")
    tables = ds.Tables
    Dim view As New DataView(tables(0))
    source1.DataSource = view
    DataGridView1.DataSource = view
End Sub
</code>```

You should also remove the ToString("MM/dd/yyyy") on the DateTimePicker values. On my system (german setup - dd.mm.yyyy date format by default) I got an error message like the following:

Invalid conversion of the string 11.13.2017 to type Date - translated from german

As Joel Coehoorn also mentioned in the comments, is it a performance waste and in some situations a security issue.

Body:
I'm getting the following error message:

System.InvalidCastException: Conversion from string "select * from [tbl_FBNK_Limit_Hi" to type 'Integer' is not valid.

My setup is really pretty simple. Here is all the code:

Imports System.Data.OleDb

Public Class Form1

    'Change Path Here:
    Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=path_here.accdb"
    Dim MyConn As OleDbConnection
    Dim da As OleDbDataAdapter
    Dim ds As DataSet
    Dim tables As DataTableCollection
    Dim source1 As New BindingSource
    Dim SqlStr As String
    Dim startDate As String
    Dim endDate As String

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        MyConn = New OleDbConnection
        MyConn.ConnectionString = connString
        ds = New DataSet
        tables = ds.Tables

        Dim startDate As DateTime = DateTimePicker1.Value.ToString("MM/dd/yyyy")
        Dim endDate As DateTime = DateTimePicker2.Value.ToString("MM/dd/yyyy")

        SqlStr = "select * from [tbl_Hist_Current] where AsOfDate >= #" & startDate & "# and AsOfDate <=#" & endDate & "#"

        da = New OleDbDataAdapter(SqlStr, MyConn)
        da.Fill(SqlStr, "tbl_Limit_Hist_Current")
        Dim view As New DataView(tables(0))
        source1.DataSource = view
        DataGridView1.DataSource = view
    End Sub
End Class

When I copy/paste the SqlStr into Access it works fine, so it's gotta be something with the way the dates are being handled, or not handled. Can someone here give me a nudge in the right direction?

Private Sub LoadData_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim connectionString As String = "Data Source=server_name;Initial Catalog=database_name;Integrated Security=True"
    Dim SqlStr As String
    Dim startDate As DateTime = DateTimePicker1.Value.ToString("MM/dd/yyyy")
    Dim endDate As DateTime = DateTimePicker2.Value.ToString("MM/dd/yyyy")

    SqlStr = "Select Field1, Field2, Field3, AsOfDate FROM [TBL_DATA_HIST] where AsOfDate >= '" & startDate & "' and AsOfDate <='" & endDate & "'"

    Dim connection As New SqlConnection(connectionString)
    Dim dataadapter As New SqlDataAdapter(SqlStr, connection)
    Dim ds As New DataSet()
    connection.Open()
    dataadapter.Fill(ds, "TBL_DATA_HIST")
    connection.Close()
    DataGridView1.DataSource = ds
    DataGridView1.DataMember = "TBL_DATA_HIST"

    ' Count rows in DG
    Dim int As Integer
    int = DataGridView1.Rows.Count()
    TextBox1.Text = int

End Sub

Body:
You can use the following solution, using parameter placeholders:

'Change Path Here:
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=path_here.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim SqlStr As String
Dim startDate As String
Dim endDate As String

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    MyConn = New OleDbConnection
    MyConn.ConnectionString = connString

    Dim startDate As DateTime = DateTimePicker1.Value
    Dim endDate As DateTime = DateTimePicker2.Value

    SqlStr = "select * from [tbl_Limit_Hist_Current] where AsOfDate >= ? and AsOfDate <= ?"

    da = New OleDbDataAdapter(SqlStr, MyConn)
    Dim selectCMD As New OleDbCommand(SqlStr, MyConn)
    da.SelectCommand = selectCMD

    selectCMD.Parameters.Add("@AsOfDate1", OleDbType.Date).Value = startDate
    selectCMD.Parameters.Add("@AsOfDate2", OleDbType.Date).Value = endDate

    ds = New DataSet
    da.Fill(ds, "tbl_Limit_Hist_Current")
    tables = ds.Tables
    Dim view As New DataView(tables(0))
    source1.DataSource = view
    DataGridView1.DataSource = view
End Sub

You should also remove the ToString("MM/dd/yyyy") on the DateTimePicker values. On my system (german setup - dd.mm.yyyy date format by default) I got an error message like the following:

Invalid conversion of the string 11.13.2017 to type Date - translated from german

As Joel Coehoorn also mentioned in the comments, is it a performance waste and in some situations a security issue.


来源: stackexchange

问:
TransactionTooLargeException when Activity is Paused
I am creating an application and in there I am sending very big data in Bundle from Service to the Activity. But I am not using Messenger for that. Instead, I am assigning data to a variable in singleton class and then I am retrieving data from that singleton class and assigning it to the activity.

In the Activity, I have a ViewPager in which two fragments are inflated. The Bundle is being sent to both of these Fragment classes.

Now, when the activity is paused, application is throwing following exception:

```<code>at android.app.ActivityThread$StopInfo.run(ActivityThread.java:4209)
                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                                                                     Caused by: android.os.TransactionTooLargeException: data parcel size 4538408 bytes
                                                                        at android.os.BinderProxy.transactNative(Native Method)
                                                                        at android.os.BinderProxy.transact(Binder.java:628)
                                                                        at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:4183)
                                                                        at android.app.ActivityThread$StopInfo.run(ActivityThread.java:4201)
                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

Please help.

答:
The bundle is being sent to both of these fragment classes.

Do not put large things into the saved instance state Bundle. In the case of fragments, the "arguments" Bundle (setArguments()) becomes part of the saved instance state Bundle, and so do not put large things into the arguments Bundle. The saved instance state Bundle is for tiny bits of data: as little as possible, but enough for you to restore your UI state after your process is terminated.

Instead, do something else, such as:

Have the fragments call methods on the hosting activity to get this data, or

Use a ViewModel, so that this data is retained across configuration changes but is not part of the saved instance state Bundle

ContentLicense: CC BY-SA 3.0

Body:
I am creating an application and in there I am sending very big data in Bundle from Service to the Activity. But I am not using Messenger for that. Instead, I am assigning data to a variable in singleton class and then I am retrieving data from that singleton class and assigning it to the activity.

In the Activity, I have a ViewPager in which two fragments are inflated. The Bundle is being sent to both of these Fragment classes.

Now, when the activity is paused, application is throwing following exception:

at android.app.ActivityThread$StopInfo.run(ActivityThread.java:4209)
                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                                                                     Caused by: android.os.TransactionTooLargeException: data parcel size 4538408 bytes
                                                                        at android.os.BinderProxy.transactNative(Native Method)
                                                                        at android.os.BinderProxy.transact(Binder.java:628)
                                                                        at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:4183)
                                                                        at android.app.ActivityThread$StopInfo.run(ActivityThread.java:4201)
                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

Please help.


问:
How can I extract and store and key/value returned by a server response in pharo/smalltalk
In my ZnClient request I get a response from the server which is a HTML format containing key and value that I would like to extract and store for later use. How do I do it in Pharo?

Connectez-vous pour accÃ©der Ã  Tool Platform

   <form method="post" action="." id="login_form"><input type='hidden' name='csrfmiddlewaretoken' value='fLTzkLA7yhy7YKDvohM0PJstFJJCEk2JinfjOyzCe2NA495QKznLgO1wzi64P2S8' />

EmailÂ : <input class="login" id="id_email" maxlength="75" name="email" type="text" required />

PasswordÂ : <input class="login" id="id_password" name="password" type="password" required />

      <button type="submit" class="btn btn-connect pull-right">Connexion</button>
    </form>

```

答:
You can extract this information using a HTML parser like Soup.

Here's a cut-down working example:

```<code>|content soup dict|

content := '
<div>
  <form method="post" action="." id="login_form">
    <input type="hidden" name="csrfmiddlewaretoken" value="***special***" />
    <input class="login" id="id_email" name="email" type="text" required />
  </form>
</div>'.

dict := Dictionary new.
soup := Soup fromString: content.

(soup findAllTags: 'input') do: [ :each |
    dict at: (each attributeAt: 'name') put: (each attributeAt: 'value') ].
</code>```

dict now contains the following:

```<code>'csrfmiddlewaretoken'->'***special***'
'email'->nil
</code>```

Body:
You can extract this information using a HTML parser like Soup.

Here's a cut-down working example:

|content soup dict|

content := '
<div>
  <form method="post" action="." id="login_form">
    <input type="hidden" name="csrfmiddlewaretoken" value="***special***" />
    <input class="login" id="id_email" name="email" type="text" required />
  </form>
</div>'.

dict := Dictionary new.
soup := Soup fromString: content.

(soup findAllTags: 'input') do: [ :each |
    dict at: (each attributeAt: 'name') put: (each attributeAt: 'value') ].

dict now contains the following:

'csrfmiddlewaretoken'->'***special***'
'email'->nil


问:
How to put sidekiq into Docker in a rails application?
I am using rails, sidekiq and docker.

My docker-compose.yml file

```<code>sidekiq:
  build: .
  command: bundle exec sidekiq -C config/sidekiq.yml
  links:
    - db
    - redis
</code>```

config/sidekiq.yml file

```<code>:pidfile: ./tmp/pids/sidekiq.pid
:logfile: ./log/sidekiq.log
:queues:
  - default
</code>```

After I run docker-compose up, the sidekiq service can not start rightly.

```<code>sidekiq_1 | No such file or directory @ rb_sysopen - /testapp/tmp/pids/sidekiq.pid
sidekiq_1 | /usr/local/bundle/gems/sidekiq-3.5.3/lib/sidekiq/cli.rb:365:in `initialize'
sidekiq_1 | /usr/local/bundle/gems/sidekiq-3.5.3/lib/sidekiq/cli.rb:365:in `open'
sidekiq_1 | /usr/local/bundle/gems/sidekiq-3.5.3/lib/sidekiq/cli.rb:365:in `write_pid'
sidekiq_1 | /usr/local/bundle/gems/sidekiq-3.5.3/lib/sidekiq/cli.rb:42:in `parse'
sidekiq_1 | /usr/local/bundle/gems/sidekiq-3.5.3/bin/sidekiq:12:in `<top (required)>'
sidekiq_1 | /usr/local/bundle/bin/sidekiq:16:in `load'
sidekiq_1 | /usr/local/bundle/bin/sidekiq:16:in `<main>'
testapp_sidekiq_1 exited with code 1
</code>```

答:
A little bit more details in general on how to put Sidekiq into Docker in a Rails application. And for your reference, all the code is available on a GitHub repository.

Configure a Redis container

Sidekiq depends on Redis. So first of all, you need a Redis container to run alongside.

In your docker-compose.yml, add (as an example):

```<code>redis:
  image: redis:4.0-alpine
</code>```

Dockerize Sidekiq

Share the same Dockerfile with your Rails app:

```<code>FROM ruby:2.3.3
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp
</code>```

Update your docker-compose.yml

```<code>sidekiq:
  build: .
  command: bundle exec sidekiq
  depends_on:
    - redis
  volumes:
    - .:/myapp
  env_file:
    - .env
</code>```

The environment file .env looks like this:

```<code>JOB_WORKER_URL=redis://redis:6379/0
</code>```

Also in your docker-compose.yml, add sidekiq to your Rails application's dependency list:

```<code>web:
  build: .
  command: bundle exec rails s -p 3000 -b '0.0.0.0'
  volumes:
    - .:/myapp
  ports:
    - "3000:3000"
  depends_on:
    - db
    - sidekiq
  env_file:
    - .env
</code>```

Add to your Gemfile

```<code>gem 'sidekiq'
gem 'sidekiq-scheduler'
gem 'sidekiq-unique-jobs'
gem 'sinatra', require: nil
</code>```

The sinatra gem is needed for the Sidekiq web UI (the dashboard shown below)

Configure Sidekiq

Add file config/initializers/sidekiq.rb:

```<code>sidekiq_config = { url: ENV['JOB_WORKER_URL'] }

Sidekiq.configure_server do |config|
  config.redis = sidekiq_config
end

Sidekiq.configure_client do |config|
  config.redis = sidekiq_config
end
</code>```

Add a Sidekiq worker

Under directory app/workers/, add a file my_worker.rb:

```<code>class MyWorker
  include Sidekiq::Worker
  def perform(who, message)
    logger.info "Message from #{who} is #{message}"
  end
end
</code>```

That's it. Now you can submit a job in Rails, e.g., in a controller.

```<code>MyWorker.perform_async(who, message)
</code>```

And the worker will pick up the job, and output a message in the log file.

Build and run with docker compose

Once everything is in place, you can build docker images and run your app with docker compose:

```<code>docker-compose build
docker-compose up

$ docker ps
CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                    NAMES
c0515ac60a8b        hellosidekiq_web       "bundle exec rails..."   23 minutes ago      Up 23 minutes       0.0.0.0:3000->3000/tcp   hellosidekiq_web_1
080e33963e3a        hellosidekiq_sidekiq   "bundle exec sidekiq"    23 minutes ago      Up 23 minutes                                hellosidekiq_sidekiq_1
80d1c03f0573        redis:4.0-alpine       "docker-entrypoint..."   4 days ago          Up 23 minutes       6379/tcp                 hellosidekiq_redis_1
5915869772e4        postgres               "docker-entrypoint..."   4 days ago          Up 23 minutes       5432/tcp                 hellosidekiq_db_1
</code>```

Test

Now open the following URL to submit a job:

```<code>FROM ruby:2.3.3
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp
</code>```0

And in the log file, you will see something like this:

```<code>FROM ruby:2.3.3
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp
</code>```1

Sidekiq dashboard

If you would like to use the Sidekiq dashboard, as below

You can add the route to your routes.rb

```<code>FROM ruby:2.3.3
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp
</code>```2

Hope it helps.

By the way, if you would like to find out how to dockerize your Rails application using docker compose, refer to docker compose documentation.

Body:
I am using rails, sidekiq and docker.

My docker-compose.yml file

sidekiq:
  build: .
  command: bundle exec sidekiq -C config/sidekiq.yml
  links:
    - db
    - redis

config/sidekiq.yml file

:pidfile: ./tmp/pids/sidekiq.pid
:logfile: ./log/sidekiq.log
:queues:
  - default

After I run docker-compose up, the sidekiq service can not start rightly.

sidekiq_1 | No such file or directory @ rb_sysopen - /testapp/tmp/pids/sidekiq.pid
sidekiq_1 | /usr/local/bundle/gems/sidekiq-3.5.3/lib/sidekiq/cli.rb:365:in `initialize'
sidekiq_1 | /usr/local/bundle/gems/sidekiq-3.5.3/lib/sidekiq/cli.rb:365:in `open'
sidekiq_1 | /usr/local/bundle/gems/sidekiq-3.5.3/lib/sidekiq/cli.rb:365:in `write_pid'
sidekiq_1 | /usr/local/bundle/gems/sidekiq-3.5.3/lib/sidekiq/cli.rb:42:in `parse'
sidekiq_1 | /usr/local/bundle/gems/sidekiq-3.5.3/bin/sidekiq:12:in `<top (required)>'
sidekiq_1 | /usr/local/bundle/bin/sidekiq:16:in `load'
sidekiq_1 | /usr/local/bundle/bin/sidekiq:16:in `'
testapp_sidekiq_1 exited with code 1

Body:
A little bit more details in general on how to put Sidekiq into Docker in a Rails application. And for your reference, all the code is available on a GitHub repository.

Configure a Redis container

Sidekiq depends on Redis. So first of all, you need a Redis container to run alongside.

In your docker-compose.yml, add (as an example):

redis:
  image: redis:4.0-alpine

Dockerize Sidekiq

Share the same Dockerfile with your Rails app:

FROM ruby:2.3.3
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
RUN mkdir /myapp
WORKDIR /myapp
ADD Gemfile /myapp/Gemfile
ADD Gemfile.lock /myapp/Gemfile.lock
RUN bundle install
ADD . /myapp

Update your docker-compose.yml

sidekiq:
  build: .
  command: bundle exec sidekiq
  depends_on:
    - redis
  volumes:
    - .:/myapp
  env_file:
    - .env

The environment file .env looks like this:

JOB_WORKER_URL=redis://redis:6379/0

Also in your docker-compose.yml, add sidekiq to your Rails application's dependency list:

web:
  build: .
  command: bundle exec rails s -p 3000 -b '0.0.0.0'
  volumes:
    - .:/myapp
  ports:
    - "3000:3000"
  depends_on:
    - db
    - sidekiq
  env_file:
    - .env

Add to your Gemfile

gem 'sidekiq'
gem 'sidekiq-scheduler'
gem 'sidekiq-unique-jobs'
gem 'sinatra', require: nil

The sinatra gem is needed for the Sidekiq web UI (the dashboard shown below)

Configure Sidekiq

Add file config/initializers/sidekiq.rb:

sidekiq_config = { url: ENV['JOB_WORKER_URL'] }

Sidekiq.configure_server do |config|
  config.redis = sidekiq_config
end

Sidekiq.configure_client do |config|
  config.redis = sidekiq_config
end

Add a Sidekiq worker

Under directory app/workers/, add a file my_worker.rb:

class MyWorker
  include Sidekiq::Worker
  def perform(who, message)
    logger.info "Message from #{who} is #{message}"
  end
end

That's it. Now you can submit a job in Rails, e.g., in a controller.

MyWorker.perform_async(who, message)

And the worker will pick up the job, and output a message in the log file.

Build and run with docker compose

Once everything is in place, you can build docker images and run your app with docker compose:

docker-compose build
docker-compose up

$ docker ps
CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                    NAMES
c0515ac60a8b        hellosidekiq_web       "bundle exec rails..."   23 minutes ago      Up 23 minutes       0.0.0.0:3000->3000/tcp   hellosidekiq_web_1
080e33963e3a        hellosidekiq_sidekiq   "bundle exec sidekiq"    23 minutes ago      Up 23 minutes                                hellosidekiq_sidekiq_1
80d1c03f0573        redis:4.0-alpine       "docker-entrypoint..."   4 days ago          Up 23 minutes       6379/tcp                 hellosidekiq_redis_1
5915869772e4        postgres               "docker-entrypoint..."   4 days ago          Up 23 minutes       5432/tcp                 hellosidekiq_db_1

Test

Now open the following URL to submit a job:

http://localhost:3000/job/submit/John/Prepare%20ye%20the%20way

And in the log file, you will see something like this:

sidekiq_1  | 2017-11-13T17:08:45.876Z 1 TID-qw47g MyWorker JID-b7b6d39b0d5193cd01e97cb1 INFO: Message from John is Prepare ye the way

Sidekiq dashboard

If you would like to use the Sidekiq dashboard, as below

You can add the route to your routes.rb

require 'sidekiq/web'
require 'sidekiq-scheduler/web'

Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  mount Sidekiq::Web => '/sidekiq'

  get 'job/submit/:who/:message', to: 'job#submit'
end

Hope it helps.

By the way, if you would like to find out how to dockerize your Rails application using docker compose, refer to docker compose documentation.


问:
Calling the same ColdFusion component from different templates
In a.cfm I have:

```<code><CFSET VerObj = New cfcomponents.VerFold.Ver_Users()>
<CFSET VerObj.Functiion_1(userid)>
</code>```

In the next few templates, c.cfm, I need to call a different function within Ver_Users.cfc I can do:

```<code><CFSET VerObj = New cfcomponents.VerFold.Ver_Users()>
<CFSET VerObj.Function_2(userid)>
</code>```

If I need to call the same cfc again from yet another template down the road and I keep doing this I think it is very awkward and repetitive? the purpose of using .cfc is so that I can reuse or call the functions by just doing:

```<code> <CFSET VerObj,Function_1()> or calling Function_2
</code>```

from anywhere without keep instantiating the cfc am I correct? is there any example on how to accomplish This?

答: @Rbt - you could create an Application.cfc that instantiates the Ver_Users component, and call application.Function1() and application.Function2() in your cfm files. You could create a session and use Session scope, or use Application scope which would treat it as a global, depending on how you want to use it.</p>

Body:
In a.cfm I have:

<CFSET VerObj = New cfcomponents.VerFold.Ver_Users()>
<CFSET VerObj.Functiion_1(userid)>

In the next few templates, c.cfm, I need to call a different function within Ver_Users.cfc I can do:

<CFSET VerObj = New cfcomponents.VerFold.Ver_Users()>
<CFSET VerObj.Function_2(userid)>

If I need to call the same cfc again from yet another template down the road and I keep doing this I think it is very awkward and repetitive? the purpose of using .cfc is so that I can reuse or call the functions by just doing:

 <CFSET VerObj,Function_1()> or calling Function_2

from anywhere without keep instantiating the cfc am I correct? is there any example on how to accomplish This?


问:
onclick not firing if element is reinserted into DOM mid-click
I made a simple popup manager, which used the dom to decide which popup should be in front, without any z-index rule : when I click on a popup, it's moved in first position, so it is on top of the other popup. Unfortunately : this dom movement breaks the onclick event in my popup.

I made a simple case of the issue : the following code should output the three click events : mousedown, mouseup and click, it works on Firefox, and I think it used to work in previous versions of Chrome, but it doesn't anymore.

Click

```

Do you know how can I fix this issue, and get back my onclick event ?

答:
It's not that event stops firing, it's just that you are not clicking the divs with the event anymore.

Be careful on zIndexing since zIndex is relative to it's container. You cannot have a container with less zIndex than it's parent or you will move it behind it. The "dirty" solution is to have zIndex grow with every click:

```<code><style type="text/css">
html, body{
    width: 100%;
    height: 100%;
}

.Movable{
    height: 100px;
    position: absolute;
    width: 100px;
}

.black{
    background-color: black;
}

.gray{
    background-color: gray;
}

.wheat{
    background-color: lightgray;
}
</code>```

```<code><div style="position: relative; z-index: 20;">
    <p id="log" style="height: 1em; overflow-y: scroll;"></p>
    <div onclick="log( 'clicked', this )" onmousedown="log( 'mousedown', this )" onmouseup="log( 'mouseup', this )" class="Movable black"></div>
    <div onclick="log( 'clicked', this )" onmousedown="log( 'mousedown', this )" onmouseup="log( 'mouseup', this )" style="left: 25px; top: 55px;" class="Movable gray"></div>
    <div onclick="log( 'clicked', this )" onmousedown="log( 'mousedown', this )" onmouseup="log( 'mouseup', this )" style="left: 55px; top: 75px;" class="Movable wheat"></div>
</div>
<script type="text/javascript">
    var index = 1;
    function log( msg, element )
    {
        element.style.zIndex = index++;
        document.getElementById( 'log' ).innerHTML += "Log: " + msg + " -> " + element.className + "</br>";
    }
</script>
</code>```

Body:
I made a simple popup manager, which used the dom to decide which popup should be in front, without any z-index rule : when I click on a popup, it's moved in first position, so it is on top of the other popup. Unfortunately : this dom movement breaks the onclick event in my popup.

I made a simple case of the issue : the following code should output the three click events : mousedown, mouseup and click, it works on Firefox, and I think it used to work in previous versions of Chrome, but it doesn't anymore.

Click

Do you know how can I fix this issue, and get back my onclick event ?

Body:
It's not that event stops firing, it's just that you are not clicking the divs with the event anymore.

Be careful on zIndexing since zIndex is relative to it's container. You cannot have a container with less zIndex than it's parent or you will move it behind it. The "dirty" solution is to have zIndex grow with every click:

<style type="text/css">
html, body{
    width: 100%;
    height: 100%;
}

.Movable{
    height: 100px;
    position: absolute;
    width: 100px;
}

.black{
    background-color: black;
}

.gray{
    background-color: gray;
}

.wheat{
    background-color: lightgray;
}

<div style="position: relative; z-index: 20;">
    <p id="log" style="height: 1em; overflow-y: scroll;"></p>
    <div onclick="log( 'clicked', this )" onmousedown="log( 'mousedown', this )" onmouseup="log( 'mouseup', this )" class="Movable black"></div>
    <div onclick="log( 'clicked', this )" onmousedown="log( 'mousedown', this )" onmouseup="log( 'mouseup', this )" style="left: 25px; top: 55px;" class="Movable gray"></div>
    <div onclick="log( 'clicked', this )" onmousedown="log( 'mousedown', this )" onmouseup="log( 'mouseup', this )" style="left: 55px; top: 75px;" class="Movable wheat"></div>
</div>
<script type="text/javascript">
    var index = 1;
    function log( msg, element )
    {
        element.style.zIndex = index++;
        document.getElementById( 'log' ).innerHTML += "Log: " + msg + " -> " + element.className + "</br>";
    }
</script>


问:
Can I use git or another versioning system to private repository on http hosting acount without ssh?
I have 2 www/ftp accounts with php and sql in hosting companies but I haven't access to ssh. Can I install there any Version Control System like git or Mercurial? Or is any public free site to set up a private encoding developing repository?</p>

答: Also have a look at Perforce Helix Team Hub. 1 - 5 users and 1GB / year is free.</p>

ContentLicense: CC BY-SA 2.5


问:
How to delete queried results from Splunk database?
Query is on Splunk DB data delete:

My requirement:

I do a query to splunk, based on time stamp, "from date" & "to date".

After I got the list of all events results between the timestamp, I want to delete these list of events from the Splunk database.

Each queried results data will be stored in the destination database, hence I want to delete each queried results data from querying Splunk DB, so that my next query will not end up in giving repetitive results, also I want to free up the storage space in source Splunk DB.

Hence I want a effective solution on how to delete completely the Queried result data, from querying Splunk DB?

Thanks & Regards,
Dharmendra Setty

答:
I'm not sure you can actually delete them to free up storage space.
As written here, what you can do is simply mask the results from ever showing up again in the next searches.

To do this, simply pipe the "delete" command to your search query.

BE CAREFUL: First make sure these really are the events you want to delete

Example:

```<code>index=<index-name> sourcetype=<sourcetype-name> source=<source-name>
earliest="%m/%d/%Y:%H:%M:%S" latest="%m/%d/%Y:%H:%M:%S" | delete
</code>```

Where

```<code>index=<index-name> sourcetype=<sourcetype-name> source=<source-name>
earliest="%m/%d/%Y:%H:%M:%S" latest="%m/%d/%Y:%H:%M:%S"
</code>```

is the search query

Body:
I'm not sure you can actually delete them to free up storage space.
As written here, what you can do is simply mask the results from ever showing up again in the next searches.

To do this, simply pipe the "delete" command to your search query.

BE CAREFUL: First make sure these really are the events you want to delete

Example:

index=<index-name> sourcetype=<sourcetype-name> source=<source-name>
earliest="%m/%d/%Y:%H:%M:%S" latest="%m/%d/%Y:%H:%M:%S" | delete

Where

index=<index-name> sourcetype=<sourcetype-name> source=<source-name>
earliest="%m/%d/%Y:%H:%M:%S" latest="%m/%d/%Y:%H:%M:%S"

is the search query


问:
using like condition in Subsonic 2.2
I need some help in using "like" condition in Subsonic 2.2

Following is my query

```<code>DAL.DB.Select()
    .From("tblName")
    .Where("NewFirstName")
    .Like(strFirstName)
    .Or("PrevFirstName")
    .Like(strFirstName)
    .ExecuteDataSet();
</code>```

the result returned by above query contains records those have firstname euqal to strFirstName not like strFirstName

example: there are two records which has NewFirstName as 'joe' and 'joe J' so above query just returns record that has 'joe' as NewFirstName .

答: Did you try this : strFirstName = 'joe*' or strFirstName = 'joe%' ?

Title: using like condition in Subsonic 2.2

Body:
I need some help in using "like" condition in Subsonic 2.2

Following is my query

DAL.DB.Select()
    .From("tblName")
    .Where("NewFirstName")
    .Like(strFirstName)
    .Or("PrevFirstName")
    .Like(strFirstName)
    .ExecuteDataSet();

the result returned by above query contains records those have firstname euqal to strFirstName not like strFirstName

example: there are two records which has NewFirstName as 'joe' and 'joe J' so above query just returns record that has 'joe' as NewFirstName .


问:
Storing files as list and reading data from them in python
I was wondering if I had a directory full of similar .txt files, if there was a way to store these as a list of lists in python, iterate through the list to open the files, and then iterate through the objects in the file to achieve something. For example:

```<code>ls /Path/to/directory/
1.txt 2.txt 3.txt 4.txt
</code>```

the contents of each file would be like:

```<code>more 1.txt
1
2
3
4
</code>```

For the python script something like:

```<code>import os
pathname = os.path.join("directory",filenames)
for i in pathname:
    file_open = open(pathname[i])
    for j in file_open:
        file_sum = sum(int[j])
    return file_sum
</code>```

or would it just be better to do this with a shell script to run the python command for each file individually and write output to file? I just wanted to see if there was a cool pythonic way to do this.

```<code>#!/bin/bash

RUN_PATH=$1; shift
cd $RUN_PATH

for file in $RUN_PATH*
do
    MONEY=`basename $file`
    BAG=`python my_script.py $file`
    echo $MONEY "      " $BAG >> money_bag.txt
done;
</code>```

thanks for the help

答:
You can try in one line:

Assuming you have stored all files names in one list now and each file contain numbers like:

1.txt file:

```<code>1
2
3
4
</code>```

You can try :

```<code>pathname = ['1.txt','2.txt','3.txt','4.txt']

print([sum([int(i) for i in open(i,'r+')]) for i in pathname])
</code>```

output:

```<code>[10, 14, 26, 30]
</code>```

Body:
I was wondering if I had a directory full of similar .txt files, if there was a way to store these as a list of lists in python, iterate through the list to open the files, and then iterate through the objects in the file to achieve something. For example:

ls /Path/to/directory/
1.txt 2.txt 3.txt 4.txt

the contents of each file would be like:

more 1.txt
1
2
3
4

For the python script something like:

import os
pathname = os.path.join("directory",filenames)
for i in pathname:
    file_open = open(pathname[i])
    for j in file_open:
        file_sum = sum(int[j])
    return file_sum

or would it just be better to do this with a shell script to run the python command for each file individually and write output to file? I just wanted to see if there was a cool pythonic way to do this.

#!/bin/bash

RUN_PATH=$1; shift
cd $RUN_PATH

for file in $RUN_PATH*
do
    MONEY=`basename $file`
    BAG=`python my_script.py $file`
    echo $MONEY "      " $BAG >> money_bag.txt
done;

thanks for the help

Body:
You can try in one line:

Assuming you have stored all files names in one list now and each file contain numbers like:

1.txt file:

1
2
3
4

You can try :

pathname = ['1.txt','2.txt','3.txt','4.txt']

print([sum([int(i) for i in open(i,'r+')]) for i in pathname])

output:

[10, 14, 26, 30]


问:
Enabling Redirection in Kamailio SIP Server
How can we enable redirection in Kamilio SIP Server?</p>

答:
If you are asking about the "User Agent Client redirection", there is a module in kamailio.
It has the following functionality: UAC REDIRECT - module enhance Kamailio with the functionality of being able to handle (interpret, filter, log and follow) redirect responses ( 3xx replies class). Please find the usage examples and description on the official website https://kamailio.org/docs/modules/3.3.x/modules_k/uac_redirect.html</p>


问:
Get Creation Time of an AWS Batch job
When executing an AWS Batch job, I would like to know when the job was created. The API provides a way to get job details, including createdAt. But how do I know the job id to fetch those details?

答:
A list of job IDs on which this job depends. A job can depend upon a maximum of 20 jobs. The job ID of the AWS Batch job associated with this dependency.

Use following link might help,

http://docs.aws.amazon.com/batch/latest/APIReference/API_JobDependency.html

Title: Get Creation Time of an AWS Batch job


问:
How do I convert datetime to ISO 8601 in PHP
How do I convert my time from 2010-12-30 23:21:46 to ISO 8601 date format? (-_-;)

答:
If you try set a value in datetime-local</p>

```<code>date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));

//output : 2010-12-30T23:21
</code>```

Body:
If you try set a value in datetime-local

date("Y-m-d\TH:i",strtotime('2010-12-30 23:21:46'));

//output : 2010-12-30T23:21


问:
Removing stand-alone numbers from string in Python
There are a lot of similar questions, but I have not found a solution for my problem. I have a data frame with the following structure/form:

```<code>   col_1
0  BULKA TARTA 500G KAJO 1
1  CUKIER KRYSZTAL 1KG KSC 4
2  KASZA JĘCZMIENNA 4*100G 2 0.92
3  LEWIATAN MAKARON WSTĄŻKA 1 0.89
</code>```

However, I want to achieve the effect:

```<code>   col_1
0  BULKA TARTA 500G KAJO
1  CUKIER KRYSZTAL 1KG KSC
2  KASZA JĘCZMIENNA 4*100G
3  LEWIATAN MAKARON WSTĄŻKA
</code>```

So I want to remove the independent natural and decimal numbers, but leave the numbers in the string with the letters.

I tried to use df.col_1.str.isdigit().replace([True, False],[np.nan, df.col_1]) , but it only works on comparing the entire cell whether it is a number or not.

You have some ideas how to do it? Or maybe it would be good to break the column with spaces and then compare?

答:
Sure,

You could use a regex.

```<code>import re
df.col_1 = re.sub("\d+\.?\d+?", "",  df.col_1)
</code>```

Body:
There are a lot of similar questions, but I have not found a solution for my problem. I have a data frame with the following structure/form:

   col_1
0  BULKA TARTA 500G KAJO 1
1  CUKIER KRYSZTAL 1KG KSC 4
2  KASZA JĘCZMIENNA 4*100G 2 0.92
3  LEWIATAN MAKARON WSTĄŻKA 1 0.89

However, I want to achieve the effect:

   col_1
0  BULKA TARTA 500G KAJO
1  CUKIER KRYSZTAL 1KG KSC
2  KASZA JĘCZMIENNA 4*100G
3  LEWIATAN MAKARON WSTĄŻKA

So I want to remove the independent natural and decimal numbers, but leave the numbers in the string with the letters.

I tried to use df.col_1.str.isdigit().replace([True, False],[np.nan, df.col_1]) , but it only works on comparing the entire cell whether it is a number or not.

You have some ideas how to do it? Or maybe it would be good to break the column with spaces and then compare?

Body:
Sure,

You could use a regex.

import re
df.col_1 = re.sub("\d+\.?\d+?", "",  df.col_1)


问:
Add existing code to existing project using git
I am working on a IOS App, and had an existing project on bitbucket. I then downloaded the project, and started working on it, changing a lot of the files. Now, my question is, how do I connect my local project, to the existing bitbucket project? All I can find is creating a new repository, or connecting from an existing, which I'm afraid will overwrite my changes.

EDIT:
So I did the following and here is what I get.

```<code>git init
git add .
git commit -m "changing stuff"
git remote add origin https.bitbucket.org/myrepository
git push -u origin master
</code>```

and the error I get is,

hint: Updates were rejected because the remote contains work that you do
not have locally. This is usually caused by another repository pushing
to the same ref. You may want to first integrate the remote changes (e.g., 'git pull ...') before pushing again. See the 'Note about fast-forwards' in 'git push --help' for details.

答:
So here is what I did, I forced my new project in to the repository. </p>

```<code>git init
git add .
git commit -m "changing stuff"
git remote add origin https.bitbucket.org/myrepository
git push -f origin master
</code>```

Body:
I am working on a IOS App, and had an existing project on bitbucket. I then downloaded the project, and started working on it, changing a lot of the files. Now, my question is, how do I connect my local project, to the existing bitbucket project? All I can find is creating a new repository, or connecting from an existing, which I'm afraid will overwrite my changes.

EDIT:
So I did the following and here is what I get.

git init
git add .
git commit -m "changing stuff"
git remote add origin https.bitbucket.org/myrepository
git push -u origin master

and the error I get is,

hint: Updates were rejected because the remote contains work that you do
not have locally. This is usually caused by another repository pushing
to the same ref. You may want to first integrate the remote changes (e.g., 'git pull ...') before pushing again. See the 'Note about fast-forwards' in 'git push --help' for details.

Body:
So here is what I did, I forced my new project in to the repository.

git init
git add .
git commit -m "changing stuff"
git remote add origin https.bitbucket.org/myrepository
git push -f origin master


问:
Logstash with Windows shows JAVA error
Logstash is giving me this error: "Cannot find Java 1.5 or higher."

The command I'm running is "bin\logstash -f \mypath\logstash-simple.conf"

I DO NOT have ruby installed on my windows 10 computer.
I have JAVA my PATH. "C:\Program Files\Java\jre1.8.0_151\bin"

How do I fix this issue? Do I need ruby?

答: You need to set JAVA_HOME system variable, that needs to point to your Java installation directory.

Title: Logstash with Windows shows JAVA error


问:
How to Convert between Interface derived types?
In the most simplest for here is what I want to do:

```<code>interface InterfaceA
{
    string var1 { get; set; }
    string var2 { get; set; }
}

public class DerivedA : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DerivedB : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DoEverything
{
    InterfaceA A = new DerivedA();
    InterfaceA B = new DerivedB();

    A.var1 = "Test1";
    A.var2 = "Test2";

    B = ConvertObject<DerivedB>(A);

    write(B.var1 + ", " + B.var2);

    // This doesn't work, I would like it to though.
    public T ConvertObject<T>(object obj)
    {
        T result = (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });

        foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
        {
            if (propertyInfo.CanRead)
            {
                try
                {
                    object value = propertyInfo.GetValue(obj, null);
                    propertyInfo.SetValue(result, value, null);
                }
                catch { }
            }
        }

        return result;
    }
}
</code>```

Right now I have to manually convert each property in my objects and when a new property is added I have to remember to go the conversion methods and add it. I would much prefer that this be done automatically.

Any help would be greatly appreciated.

thanks in advance

答: I guess I don't know what you're getting at. Why wouldn't you just declare constructors for DerivedA and DerivedB that take an InterfaceA for initialization? It would be simpler and more flexible, as each derived type would be responsible for initializing itself from the interface type. You could later add more types that implement the interface and they'd be usable by the other classes without any further changes.</p>

Body:
In the most simplest for here is what I want to do:

interface InterfaceA
{
    string var1 { get; set; }
    string var2 { get; set; }
}

public class DerivedA : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DerivedB : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DoEverything
{
    InterfaceA A = new DerivedA();
    InterfaceA B = new DerivedB();

    A.var1 = "Test1";
    A.var2 = "Test2";

    B = ConvertObject<DerivedB>(A);

    write(B.var1 + ", " + B.var2);

    // This doesn't work, I would like it to though.
    public T ConvertObject<T>(object obj)
    {
        T result = (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });

        foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
        {
            if (propertyInfo.CanRead)
            {
                try
                {
                    object value = propertyInfo.GetValue(obj, null);
                    propertyInfo.SetValue(result, value, null);
                }
                catch { }
            }
        }

        return result;
    }
}

Right now I have to manually convert each property in my objects and when a new property is added I have to remember to go the conversion methods and add it. I would much prefer that this be done automatically.

Any help would be greatly appreciated.

thanks in advance


问:
c - function pointer - why pass a struct as an argument?
I'm reading the source code below for a program and trying to understand function pointers. Taking lwm2m_read_callback_t as an example, this is a function pointer correct? Is there an obvious reason why the 4th argument takes a pointer to the lwm2m_object_t struct itself?

```<code>/*
 * LWM2M Objects
 *
 * For the read callback, if *numDataP is not zero, *dataArrayP is pre-allocated
 * and contains the list of resources to read.
 *
 */

typedef struct _lwm2m_object_t lwm2m_object_t;

typedef uint8_t (*lwm2m_read_callback_t) (uint16_t instanceId, int * numDataP, lwm2m_data_t ** dataArrayP, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_discover_callback_t) (uint16_t instanceId, int * numDataP, lwm2m_data_t ** dataArrayP, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_write_callback_t) (uint16_t instanceId, int numData, lwm2m_data_t * dataArray, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_execute_callback_t) (uint16_t instanceId, uint16_t resourceId, uint8_t * buffer, int length, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_create_callback_t) (uint16_t instanceId, int numData, lwm2m_data_t * dataArray, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_delete_callback_t) (uint16_t instanceId, lwm2m_object_t * objectP);

struct _lwm2m_object_t
{
    struct _lwm2m_object_t * next;           // for internal use only.
    uint16_t       objID;
    lwm2m_list_t * instanceList;
    lwm2m_read_callback_t     readFunc;
    lwm2m_write_callback_t    writeFunc;
    lwm2m_execute_callback_t  executeFunc;
    lwm2m_create_callback_t   createFunc;
    lwm2m_delete_callback_t   deleteFunc;
    lwm2m_discover_callback_t discoverFunc;
    void * userData;
};

typedef struct _lwm2m_list_t
{
    struct _lwm2m_list_t * next;
    uint16_t    id;
} lwm2m_list_t;
</code>```

答:
All those typedef functions are saying that, the fourth parameter is a struct pointer type "lwm2m_object_t".

Obviously you will be passing the respective struct object as parameter, when you invoke those functions.

Body:
I'm reading the source code below for a program and trying to understand function pointers. Taking lwm2m_read_callback_t as an example, this is a function pointer correct? Is there an obvious reason why the 4th argument takes a pointer to the lwm2m_object_t struct itself?

/*
 * LWM2M Objects
 *
 * For the read callback, if *numDataP is not zero, *dataArrayP is pre-allocated
 * and contains the list of resources to read.
 *
 */

typedef struct _lwm2m_object_t lwm2m_object_t;

typedef uint8_t (*lwm2m_read_callback_t) (uint16_t instanceId, int * numDataP, lwm2m_data_t ** dataArrayP, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_discover_callback_t) (uint16_t instanceId, int * numDataP, lwm2m_data_t ** dataArrayP, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_write_callback_t) (uint16_t instanceId, int numData, lwm2m_data_t * dataArray, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_execute_callback_t) (uint16_t instanceId, uint16_t resourceId, uint8_t * buffer, int length, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_create_callback_t) (uint16_t instanceId, int numData, lwm2m_data_t * dataArray, lwm2m_object_t * objectP);
typedef uint8_t (*lwm2m_delete_callback_t) (uint16_t instanceId, lwm2m_object_t * objectP);

struct _lwm2m_object_t
{
    struct _lwm2m_object_t * next;           // for internal use only.
    uint16_t       objID;
    lwm2m_list_t * instanceList;
    lwm2m_read_callback_t     readFunc;
    lwm2m_write_callback_t    writeFunc;
    lwm2m_execute_callback_t  executeFunc;
    lwm2m_create_callback_t   createFunc;
    lwm2m_delete_callback_t   deleteFunc;
    lwm2m_discover_callback_t discoverFunc;
    void * userData;
};

typedef struct _lwm2m_list_t
{
    struct _lwm2m_list_t * next;
    uint16_t    id;
} lwm2m_list_t;


问:
What is equivalent for curl --noproxy '*' in rieman.config for defining influxdb-creds
I'm forwarding riemann events by code below in riemann.config:

```<code>(def influxdb-creds {
     :version :0.9
     :host "127.0.0.1"
     :port 8086
     :db "riemann"
     ; :username "riemann"
     ; :password "riemann_password"
})

(def influxBatchSender
    (batch 100 1/10
     (async-queue! :agg {:queue-size 1000
                         :core-pool-size 1
                         :max-pool-size 4
                         :keep-alive-time 60000}
                   (influxdb influxdb-creds))))
</code>```

In my environment I need to use curl --noproxy '*' to access influxdb, how I can code it in my riemann.config?

答:
http_proxy and https_proxy environment variables responsible for this.
Make sure there are no http_proxy and https_proxy variables in your environment.</p>

Body:
I'm forwarding riemann events by code below in riemann.config:

(def influxdb-creds {
     :version :0.9
     :host "127.0.0.1"
     :port 8086
     :db "riemann"
     ; :username "riemann"
     ; :password "riemann_password"
})

(def influxBatchSender
    (batch 100 1/10
     (async-queue! :agg {:queue-size 1000
                         :core-pool-size 1
                         :max-pool-size 4
                         :keep-alive-time 60000}
                   (influxdb influxdb-creds))))

In my environment I need to use curl --noproxy '*' to access influxdb, how I can code it in my riemann.config?


问:
Top 1 & Top 1 1 ( Expr1000 1 ) typical output
```<code>SELECT TOP 1 * FROM Customers;
</code>```

This gives me all customer details of first row

```<code>( customerid, customer name etc..,)
</code>```

```<code>SELECT TOP 1 1 FROM Customers;
</code>```

I got o/p as

```<code>  Expr1000
 ------------
     1
</code>```

But I genuinely don't understand above output, and I searched for it but couldn't get the clear understanding of it.

答:
If your first query * mean show all fields

But:

```<code>SELECT TOP 1 1 FROM Customers;
</code>```

is equal to:

```<code>SELECT TOP 1
       1 as myConstantField FROM Customers;
</code>```

So you create a single constant field and you will get 1 for every row in Customers, but TOP 1 will filter to only the first one

Body:
SELECT TOP 1 * FROM Customers;

This gives me all customer details of first row

( customerid, customer name etc..,)

SELECT TOP 1 1 FROM Customers;

I got o/p as

  Expr1000
 ------------
     1

But I genuinely don't understand above output, and I searched for it but couldn't get the clear understanding of it.

Body:
If your first query * mean show all fields

But:

SELECT TOP 1 1 FROM Customers;

is equal to:

SELECT TOP 1
       1 as myConstantField FROM Customers;

So you create a single constant field and you will get 1 for every row in Customers, but TOP 1 will filter to only the first one


问:
Table value insertion using angular JS
I am trying to insert table values into the row-wise.The row has two checkboxes.How will I differentiate checkboxes row-wise
HTML:

```<code><div class="col-md-8"  ng-controller="checklistController" ng-init='populateChecklist(<%=request.getParameter("id")%>)'>
           <div class="table-responsive">
              <table class="table table-bordered">
                <thead>
                  <tr>
                    <th>Checklist Name</th>
                    <th>Not Required</th>
                    <th>Completed</th>
                    <th>Link</th>
                  </tr>
                </thead>
                  <tbody>
                   <tr ng-repeat = "x in list">
                     <td>{{x.name}}</td>
                    <td><input type="checkbox" ng-model='notRequiredCheckList'  ng-disabled="completedCheckList" ng-disabled="linkForCheckList"/></td>
                    <td><input type="checkbox" ng-disabled="notRequiredCheckList" ng-model="completedCheckList" /></td>
                    <td><input type="text" ng-model="linkForCheckList" size="50" ng-disabled="notRequiredCheckList"/></td>
                   </tr>
                  </tbody>
              </table>
          </div>
             <button type"button" ng-click="savelist(list)">Send</input>
      <div>
</code>```

Javascript:

```<code>app.controller("checklistController",function($scope,$http){
      $scope.populateChecklist =  function(a){
           $http.get("commonAppGet.jsp?sqlStr=select name from checklist where
         where id="+a).then(function(resp){
                $scope.list = resp.data;
             });
}
       $scope.savelist = function(list){
         $scope.res=list;
         alert($scope.res.length);
         alert($scope.res[0].name);
         alert($scope.res[1].name);
     }
});
</code>```

Here how I can i fetch the check box values corresponding row.I could not achieve this.How to send this data to the server for storing in the database using JSP?
Help will be greatly appreciated.

答:
First of all, your code has severe security problems. You should not be passing a raw string argument into a SQL statement since it allows SQL Injection. You need to use prepared queries if you don't want to get your entire database dropped.

About your question you can track your rows by index if you want to know at what row your checkboxes are inserted, for example:

```<code><tr ng-repeat="x in list track by $index">
   <td>
      <input type="checkbox" data-row-index="$index">
   </td>
</tr>
</code>```

This will make your input have an attribute that points to the current row. Note that $index starts at 0.
I hope this answers your question.

Title: Table value insertion using angular JS

Body:
I am trying to insert table values into the row-wise.The row has two checkboxes.How will I differentiate checkboxes row-wise
HTML:

<div class="col-md-8"  ng-controller="checklistController" ng-init='populateChecklist(<%=request.getParameter("id")%>)'>

                    Checklist Name
                    Not Required
                    Completed
                    Link

                     {{x.name}}
                    <input type="checkbox" ng-model='notRequiredCheckList'  ng-disabled="completedCheckList" ng-disabled="linkForCheckList"/>
                    <input type="checkbox" ng-disabled="notRequiredCheckList" ng-model="completedCheckList" />
                    <input type="text" ng-model="linkForCheckList" size="50" ng-disabled="notRequiredCheckList"/>

             <button type"button" ng-click="savelist(list)">Send</input>

Javascript:

app.controller("checklistController",function($scope,$http){
      $scope.populateChecklist =  function(a){
           $http.get("commonAppGet.jsp?sqlStr=select name from checklist where
         where id="+a).then(function(resp){
                $scope.list = resp.data;
             });
}
       $scope.savelist = function(list){
         $scope.res=list;
         alert($scope.res.length);
         alert($scope.res[0].name);
         alert($scope.res[1].name);
     }
});

Here how I can i fetch the check box values corresponding row.I could not achieve this.How to send this data to the server for storing in the database using JSP?
Help will be greatly appreciated.

Body:
First of all, your code has severe security problems. You should not be passing a raw string argument into a SQL statement since it allows SQL Injection. You need to use prepared queries if you don't want to get your entire database dropped.

About your question you can track your rows by index if you want to know at what row your checkboxes are inserted, for example:

<tr ng-repeat="x in list track by $index">
   <td>
      <input type="checkbox" data-row-index="$index">
   </td>
</tr>

This will make your input have an attribute that points to the current row. Note that $index starts at 0.
I hope this answers your question.


问:
IONIC Build failed transformClassesWithDexForDebug
I'm trying to run my IONIC app in my android device running the command ionic cordova run android --device. But when its building, cordova returns this error

```<code>FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException:java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/zxing/BarcodeFormat;

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 51.779 secs
Error: cmd: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException:java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/zxing/BarcodeFormat;

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

[ERROR] An error occurred while running cordova run android --device (exit code1).
</code>```

The Output of cordova plugin ls:

```<code>com.synconset.imagepicker 2.1.8 "ImagePicker"
cordova-plugin-compat 1.1.0 "Compat"
cordova-plugin-console 1.0.5 "Console"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-dialogs 1.3.3 "Notification"
cordova-plugin-facebook4 1.9.1 "Facebook Connect"
cordova-plugin-geolocation 2.4.3 "Geolocation"
cordova-plugin-google-analytics 1.8.3 "Google Universal Analytics Plugin"
cordova-plugin-googleplus 5.1.1 "Google SignIn"
cordova-plugin-nativestorage 2.2.2 "NativeStorage"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.1 "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
cordova-plugin-x-socialsharing 5.1.8 "SocialSharing"
es6-promise-plugin 4.1.0 "Promise"
ionic-plugin-keyboard 2.2.1 "Keyboard"
phonegap-plugin-barcodescanner 6.0.8 "BarcodeScanner"
phonegap-plugin-push 1.10.5 "PushPlugin"
</code>```

答:
Go to Platforms -> android -> build.gradle

Add multiDexEnabled true under defaultConfig like this

```<code>defaultConfig {
    multiDexEnabled true
}
</code>```

This worked for me..

https://forum.ionicframework.com/t/help-with-build-failed-android-ionic/94396/8

Body:
I'm trying to run my IONIC app in my android device running the command ionic cordova run android --device. But when its building, cordova returns this error

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException:java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/zxing/BarcodeFormat;

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 51.779 secs
Error: cmd: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException:java.util.concurrent.ExecutionException: com.android.dex.DexException: Multiple dex files define Lcom/google/zxing/BarcodeFormat;

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

[ERROR] An error occurred while running cordova run android --device (exit code1).

The Output of cordova plugin ls:

com.synconset.imagepicker 2.1.8 "ImagePicker"
cordova-plugin-compat 1.1.0 "Compat"
cordova-plugin-console 1.0.5 "Console"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-dialogs 1.3.3 "Notification"
cordova-plugin-facebook4 1.9.1 "Facebook Connect"
cordova-plugin-geolocation 2.4.3 "Geolocation"
cordova-plugin-google-analytics 1.8.3 "Google Universal Analytics Plugin"
cordova-plugin-googleplus 5.1.1 "Google SignIn"
cordova-plugin-nativestorage 2.2.2 "NativeStorage"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.1 "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
cordova-plugin-x-socialsharing 5.1.8 "SocialSharing"
es6-promise-plugin 4.1.0 "Promise"
ionic-plugin-keyboard 2.2.1 "Keyboard"
phonegap-plugin-barcodescanner 6.0.8 "BarcodeScanner"
phonegap-plugin-push 1.10.5 "PushPlugin"

Body:
Go to Platforms -> android -> build.gradle

Add multiDexEnabled true under defaultConfig like this

defaultConfig {
    multiDexEnabled true
}

This worked for me..

https://forum.ionicframework.com/t/help-with-build-failed-android-ionic/94396/8


问:
Invalid identifier error but i can't see why
Started learning SQL and am having a go at creating a script. The code looks perfectly fine to me but I keep getting the invalid identifier error. I've checked the code over and over again but everything seems ok. I'm going mad here. I am using oracle by the way.</p>

```<code>create table Products ( ID int not null, Item varchar(30) not null, Size
varchar(1) not null);
insert into Products values ( 321, 'T-shirt', 'M');
insert into Products values ( 211, 'Jeans', 'L');
</code>```

答:
Size is a reserved word in Oracle, try changing the column name to an unreserved word.

See here for the full list of reserved words

Body:
Started learning SQL and am having a go at creating a script. The code looks perfectly fine to me but I keep getting the invalid identifier error. I've checked the code over and over again but everything seems ok. I'm going mad here. I am using oracle by the way.

create table Products ( ID int not null, Item varchar(30) not null, Size
varchar(1) not null);
insert into Products values ( 321, 'T-shirt', 'M');
insert into Products values ( 211, 'Jeans', 'L');


问:
Error inflating class android.support.v7.widget.CardView?
I am trying to add card view in my XML but I keep getting this exception

```<code>android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v7.widget.CardView
</code>```

I am using the google code

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
... >
<!-- A CardView that contains a TextView -->
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="200dp"
    android:layout_height="200dp"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:id="@+id/info_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.v7.widget.CardView>
</code>```

Create Cards

I have even added the card view jar. I am using eclipse for dev.

What is the issue?

答:
check out whether you added the right dependency </p>

```<code> dependencies {
    compile 'com.android.support:cardview-v7:26.1.0'
   }
</code>```

<p>The version number  26.1.0  should be same as </p>

```<code> implementation 'com.android.support:appcompat-v7:26.1.0'
</code>```

Body:
I am trying to add card view in my XML but I keep getting this exception

android.view.InflateException: Binary XML file line #9: Error inflating class android.support.v7.widget.CardView

I am using the google code

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
... >

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="200dp"
    android:layout_height="200dp"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:id="@+id/info_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</android.support.v7.widget.CardView>

Create Cards

I have even added the card view jar. I am using eclipse for dev.

What is the issue?

Body:
check out whether you added the right dependency

 dependencies {
    compile 'com.android.support:cardview-v7:26.1.0'
   }

The version number  26.1.0  should be same as

 implementation 'com.android.support:appcompat-v7:26.1.0'


问:
My program is outputting strange colors in RGBA from a 2D Array using the python PIL class. How do I fix it?
```<code>def arrayconv(a):
    black = [0, 0, 0, 1]   #RGBA value for black
    white = [255, 255, 255, 1]   #RGBA value for white
    red = [255, 0, 0, 1]   #RGBA value for red
    b = np.zeros(shape=(10, 10), dtype=object)   #creates an array of zeroes
    for i in range(10):
        for j in range(10):
            if a[i][j] == 0:   #Copies the values of a into b except in rgba.
                b[i][j] = black
            if a[i][j] == 1:
                b[i][j] = white
            if a[i][j] == 2:
                b[i][j] = red
    print(b)
    return Image.fromarray(b, 'RGBA') #Makes a picture with PIL's fromarray().
</code>```

I am writing a program that solves a ten by ten pixel maze. This code is from the back end of the program, and it is supposed to convert an array of 0s, 1s, and 2s into a new array with a corresponding rgba value. That part works fine.

But when I use fromarray() to print this picture, it is different colors than intended. The image prints out with the correct amount of colors (three) and the right arrangement but in shades of blue or in shades of green. The same incorrect color scheme does not print every time as well.

答:
You have to create a 3 dimensional array with dtype='uint8' for b.

This code works for me:

```<code>def arrayconv(a):
    b = np.zeros(shape=(a.shape[0], a.shape[1], 4), dtype="uint8")   #creates an array of zeroes
    colormap = {
        0: (0, 0, 0, 1),
        1: (255, 255, 255, 1),
        2: (255, 0, 0, 1),
    }
    for index_x, row in enumerate(a):
        for index_y, pixel in enumerate(row):
                b[index_x, index_y] = colormap[pixel]
    return Image.fromarray(b, 'RGBA') #Makes a picture with PIL's fromarray().

#create test data
data = [random.randint(0, 2) for i in range(100 * 100)]
data = np.reshape(data, (100, 100))
img = arrayconv(data)
img.show()
</code>```

If you only change

```<code> b = np.zeros(shape=(10, 10), dtype=object)
</code>```

to

```<code> b = np.zeroes(shape=(10, 10, 4), dtype="uint8")
</code>```

your code should work as well.

Body:
def arrayconv(a):
    black = [0, 0, 0, 1]   #RGBA value for black
    white = [255, 255, 255, 1]   #RGBA value for white
    red = [255, 0, 0, 1]   #RGBA value for red
    b = np.zeros(shape=(10, 10), dtype=object)   #creates an array of zeroes
    for i in range(10):
        for j in range(10):
            if a[i][j] == 0:   #Copies the values of a into b except in rgba.
                b[i][j] = black
            if a[i][j] == 1:
                b[i][j] = white
            if a[i][j] == 2:
                b[i][j] = red
    print(b)
    return Image.fromarray(b, 'RGBA') #Makes a picture with PIL's fromarray().

I am writing a program that solves a ten by ten pixel maze. This code is from the back end of the program, and it is supposed to convert an array of 0s, 1s, and 2s into a new array with a corresponding rgba value. That part works fine.

But when I use fromarray() to print this picture, it is different colors than intended. The image prints out with the correct amount of colors (three) and the right arrangement but in shades of blue or in shades of green. The same incorrect color scheme does not print every time as well.

Body:
You have to create a 3 dimensional array with dtype='uint8' for b.

This code works for me:

def arrayconv(a):
    b = np.zeros(shape=(a.shape[0], a.shape[1], 4), dtype="uint8")   #creates an array of zeroes
    colormap = {
        0: (0, 0, 0, 1),
        1: (255, 255, 255, 1),
        2: (255, 0, 0, 1),
    }
    for index_x, row in enumerate(a):
        for index_y, pixel in enumerate(row):
                b[index_x, index_y] = colormap[pixel]
    return Image.fromarray(b, 'RGBA') #Makes a picture with PIL's fromarray().

#create test data
data = [random.randint(0, 2) for i in range(100 * 100)]
data = np.reshape(data, (100, 100))
img = arrayconv(data)
img.show()

If you only change

 b = np.zeros(shape=(10, 10), dtype=object)

to

 b = np.zeroes(shape=(10, 10, 4), dtype="uint8")

your code should work as well.


问:
Redeclaration of const javascript with aJax call
I'm trying to load page just changing the .loadPage html element using jQuery. I call a new page using the function loadPage(page) and this load the page using aJax. In my loadPage function has this:

```<code>$.ajax(`assets/views/${page}.html`)
    .done(html => {
        $('.loadPage').html(html);
    })
    .fail(() => {
        global.loadPage('error');
    });
</code>```

But when I try to call the below page, this returns to me on console:  SyntaxError: redeclaration of const perfil

perfil.html page

```<code><script src="assets/js/ctrl/perfil.js" type="text/javascript"></script>
</code>```

perfil.js archive

```<code>const perfil = {
    load(){
        //more code here
    }
    //more code here...
}
</code>```

When I use the var type, this error isn't showed, but I don't want to use var.

What does mean? I have to use the var type?
Note: When I tried to use let the same error occurred.

答:
You should check if perfil does exist already, like this:

```<code>window.perfil = window.perfil || {
  load(){ /*...*/ }
};
</code>```

Or you somehow load it only once.

Body:
I'm trying to load page just changing the .loadPage html element using jQuery. I call a new page using the function loadPage(page) and this load the page using aJax. In my loadPage function has this:

$.ajax(`assets/views/${page}.html`)
    .done(html => {
        $('.loadPage').html(html);
    })
    .fail(() => {
        global.loadPage('error');
    });

But when I try to call the below page, this returns to me on console:  SyntaxError: redeclaration of const perfil

perfil.html page

perfil.js archive

const perfil = {
    load(){
        //more code here
    }
    //more code here...
}

When I use the var type, this error isn't showed, but I don't want to use var.

What does mean? I have to use the var type?
Note: When I tried to use let the same error occurred.

Body:
You should check if perfil does exist already, like this:

window.perfil = window.perfil || {
  load(){ /*...*/ }
};

Or you somehow load it only once.


问:
Strange SQL Performance: Parameter slower than Function call
I've had a project dumped in my lap, and I'm pretty far outside of my element.  There is a table with roughly 10,000,000 rows that is being queried.  There is one query in particular that is taking too long to run, and is timing out.  The query generated by Linq is

```<code>-- Region Parameters
DECLARE @p0 Int = 335
DECLARE @p1 DateTime = DATEADD(day,-7,GETDATE())
-- EndRegion
SELECT *
FROM [Events] AS [t0],
    [Devices] AS [t1],
    [EventTypes] AS [t2],
    [DeviceTypes] AS [t3]
WHERE ([t1].[DeviceID] = [t0].[DeviceID])
    AND ([t2].[EventTypeID] = [t0].[EventTypeID])
    AND ([t3].[DeviceTypeID] = [t1].[DeviceTypeID])
    AND ([t1].[RoomID] = @p0)
    AND ([t0].[EventTime] >= @p1)
</code>```

If I change the last line to be [t0].[EventTime] >= DATEADD(day,-7,GETDATE()) instead of using the variable @p1, the query goes from taking 45 seconds to run, to taking 3 seconds to run.

My two questions are 1) Why does this simple change increase performance so drastically and 2) is there a way to force Linq to not use the variable and inline the datetime object?

The Linq code is C# .NET 3.5 and the server is MSSQL 2005

Edit: I added the SELECT * for brevity, the actual query does not do that.

答:
DATEADD(day,-7,GETDATE()) can be optimised because it's constant

@p1 is a parameterisation to improved plan re-use

It's quite common to see literal vs parameter differences

The other option is that [t0].[EventTime] is smalldatetime and you have datatype precedence forcing a conversion to datetime to match @p1. With direct use of DATEADD, the optimiser will change the DATEADD expression to smalldatetime

Body:
I've had a project dumped in my lap, and I'm pretty far outside of my element.  There is a table with roughly 10,000,000 rows that is being queried.  There is one query in particular that is taking too long to run, and is timing out.  The query generated by Linq is

-- Region Parameters
DECLARE @p0 Int = 335
DECLARE @p1 DateTime = DATEADD(day,-7,GETDATE())
-- EndRegion
SELECT *
FROM [Events] AS [t0],
    [Devices] AS [t1],
    [EventTypes] AS [t2],
    [DeviceTypes] AS [t3]
WHERE ([t1].[DeviceID] = [t0].[DeviceID])
    AND ([t2].[EventTypeID] = [t0].[EventTypeID])
    AND ([t3].[DeviceTypeID] = [t1].[DeviceTypeID])
    AND ([t1].[RoomID] = @p0)
    AND ([t0].[EventTime] >= @p1)

If I change the last line to be [t0].[EventTime] >= DATEADD(day,-7,GETDATE()) instead of using the variable @p1, the query goes from taking 45 seconds to run, to taking 3 seconds to run.

My two questions are 1) Why does this simple change increase performance so drastically and 2) is there a way to force Linq to not use the variable and inline the datetime object?

The Linq code is C# .NET 3.5 and the server is MSSQL 2005

Edit: I added the SELECT * for brevity, the actual query does not do that.


问:
mongodb create the index to only the first item in array
I have a json input like:

```<code>        {
            "Wells": {
               "mywell 1": {
                 "X": 0,
                 "Y": 0,
                 "Tags": {
                   "READING": [
                      {
                         "Time": "11/13/2017 9:54:59 AM",
                         "Value": 959.9707
                       }
                   ]
                }
              }
            },
            "Errors": []
        }
</code>```

that i am loading into mongodb via pymongo. I am trying to set the index for the first item in Wells. So in this case it would be "mywell 1"

I thought perhaps

```<code>db.log_events.ensureIndex( { Wells.[0]: 1 }, { unique: true } )
</code>```

or something similar, so each well would only be entered once. Does anyone know how to set the index to only the first item?

答:
You can only index static document keys, so you can't do what you're asking.

Instead, change the schema of your document so that Wells is an array (it's currently an object) and move your dynamic "mywell 1" key into a name property of your array elements:

```<code>"Wells": [
 {
   "name": "mywell 1",
   "X": 0,
   "Y": 0,
   "Tags": {
     "READING": [
        {
           "Time": "11/13/2017 9:54:59 AM",
           "Value": 959.9707
         }
     ]
   }
 }]
</code>```

With the document restructured, you can now add an index on Wells.name, letting you efficiently query by well name.

```<code>db.log_events.ensureIndex({ 'Wells.name': 1 })
</code>```

Body:
I have a json input like:

        {
            "Wells": {
               "mywell 1": {
                 "X": 0,
                 "Y": 0,
                 "Tags": {
                   "READING": [
                      {
                         "Time": "11/13/2017 9:54:59 AM",
                         "Value": 959.9707
                       }
                   ]
                }
              }
            },
            "Errors": []
        }

that i am loading into mongodb via pymongo. I am trying to set the index for the first item in Wells. So in this case it would be "mywell 1"

I thought perhaps

db.log_events.ensureIndex( { Wells.[0]: 1 }, { unique: true } )

or something similar, so each well would only be entered once. Does anyone know how to set the index to only the first item?

Body:
You can only index static document keys, so you can't do what you're asking.

Instead, change the schema of your document so that Wells is an array (it's currently an object) and move your dynamic "mywell 1" key into a name property of your array elements:

"Wells": [
 {
   "name": "mywell 1",
   "X": 0,
   "Y": 0,
   "Tags": {
     "READING": [
        {
           "Time": "11/13/2017 9:54:59 AM",
           "Value": 959.9707
         }
     ]
   }
 }]

With the document restructured, you can now add an index on Wells.name, letting you efficiently query by well name.

db.log_events.ensureIndex({ 'Wells.name': 1 })


答:
The same variable name occurs as a function parameter and is then redeclared using a let/var assignment in a function body again. Redeclaring the same variable within the same function or block scope using let/var is not allowed in JavaScript. So what you can do is if the variable is not present then only you have to create that variable.

like below..

if (!perfil){
// do something
}```

Title: Redeclaration of const javascript with aJax call


答:
size is a reserved word in Oracle's SQL (not sure if it is according to the ANSI standard, but some databases, like MySQL, definitely allow it).

You could escape it by using double quotes ("):

```<code>CREATE TABLE Products (
    ID INT NOT NULL,
    Item VARCHAR(30) NOT NULL,
    "Size" VARCHAR(1) NOT NULL
);
</code>```

But it would be much easier to just choose a name that isn't a reserved word:

```<code>CREATE TABLE Products (
    ID INT NOT NULL,
    Item VARCHAR(30) NOT NULL,
    ProductSize VARCHAR(1) NOT NULL
);
</code>```

Title: Invalid identifier error but i can't see why

Body:
size is a reserved word in Oracle's SQL (not sure if it is according to the ANSI standard, but some databases, like MySQL, definitely allow it).

You could escape it by using double quotes ("):

CREATE TABLE Products (
    ID INT NOT NULL,
    Item VARCHAR(30) NOT NULL,
    "Size" VARCHAR(1) NOT NULL
);

But it would be much easier to just choose a name that isn't a reserved word:

CREATE TABLE Products (
    ID INT NOT NULL,
    Item VARCHAR(30) NOT NULL,
    ProductSize VARCHAR(1) NOT NULL
);


问:
Universal Windows 10 WebView - how to clear/disable cache?
I am having a lot of trouble clearing the WebView cache in my UWP app.

If I edit the content of a JS file linked from my HTML page, I can't get the change into my app unless I re-install the app.

The static WebView.ClearTemporaryWebDataAsync() method doesn't seem to work.

I have also tried adding headers to the request to disable caching:

```<code>private void reloadPage()
{
    string url = getUrl();
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
    request.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
    request.Headers.Add("Pragma", "no-cache");
    myWebView.NavigateWithHttpRequestMessage(request);
}
</code>```

I also tried the following, on a punt (I'm not sure if this affects the WebView's caching behaviour), but still no joy:

```<code>private void onWebviewLoaded(object sender, RoutedEventArgs e)
{
    Windows.Web.Http.Filters.HttpBaseProtocolFilter myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
    myFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
    myFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.Default;

    WebView.ClearTemporaryWebDataAsync().AsTask().Wait();
    reloadPage();
}
</code>```

Any help would be very much appreciated!

EDIT (14/12/15):
I have found that adding headers to the request (as in the first code example above) does work, but only if this has been in place for the lifetime of the app, since install. Which makes sense, as it's just saying not to cache this particular request - it could still use an old cached version.

This works as a cludge for now, but it would be much nicer to be able to make use of caching (e.g. for the duration of an app session), then later clear the cache (e.g. on next startup).

EDIT (14/07/16): The above approach doesn't seem to bear out. Caching behaviour seems to be erratic in the webview...

On a clean install of the app, I can see changes to CSS/JS files with absolutely NO code to clear/disable cache. Then at some seemingly arbitrary point, files seem to be cached, and I cannot clear them from the cache.

答: I had a similar problem with css in an UWP app not getting cleared. I ran ProcessMon and found that the UWP app was caching .css and .js files in Windows 10 at: C:\Users\\AppData\Local\Packages\microsoft.windows.authhost.sso.p_8wekyb3d8bbwe\AC\INetCache\Q8IHZDMV. I'm using the Web Authentication Broker so the scenario might be slightly different. If a location similar to this doesn't pan-out, you might want to try to run processmon (part of the SysInternals suite) when you start-up your UWP app to see if you can identify the path the UWP app is using for caching these assets. Once there, deleting these assets and restarting the app did the trick.</p>

Body:
I am having a lot of trouble clearing the WebView cache in my UWP app.

If I edit the content of a JS file linked from my HTML page, I can't get the change into my app unless I re-install the app.

The static WebView.ClearTemporaryWebDataAsync() method doesn't seem to work.

I have also tried adding headers to the request to disable caching:

private void reloadPage()
{
    string url = getUrl();
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, new Uri(url));
    request.Headers.Add("Cache-Control", "no-cache, no-store, must-revalidate");
    request.Headers.Add("Pragma", "no-cache");
    myWebView.NavigateWithHttpRequestMessage(request);
}

I also tried the following, on a punt (I'm not sure if this affects the WebView's caching behaviour), but still no joy:

private void onWebviewLoaded(object sender, RoutedEventArgs e)
{
    Windows.Web.Http.Filters.HttpBaseProtocolFilter myFilter = new Windows.Web.Http.Filters.HttpBaseProtocolFilter();
    myFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;
    myFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.Default;

    WebView.ClearTemporaryWebDataAsync().AsTask().Wait();
    reloadPage();
}

Any help would be very much appreciated!

EDIT (14/12/15):
I have found that adding headers to the request (as in the first code example above) does work, but only if this has been in place for the lifetime of the app, since install. Which makes sense, as it's just saying not to cache this particular request - it could still use an old cached version.

This works as a cludge for now, but it would be much nicer to be able to make use of caching (e.g. for the duration of an app session), then later clear the cache (e.g. on next startup).

EDIT (14/07/16): The above approach doesn't seem to bear out. Caching behaviour seems to be erratic in the webview...

On a clean install of the app, I can see changes to CSS/JS files with absolutely NO code to clear/disable cache. Then at some seemingly arbitrary point, files seem to be cached, and I cannot clear them from the cache.


问:
TransactionTooLargeException when Activity is Paused
I am creating an application and in there I am sending very big data in Bundle from Service to the Activity. But I am not using Messenger for that. Instead, I am assigning data to a variable in singleton class and then I am retrieving data from that singleton class and assigning it to the activity.

In the Activity, I have a ViewPager in which two fragments are inflated. The Bundle is being sent to both of these Fragment classes.

Now, when the activity is paused, application is throwing following exception:

```<code>at android.app.ActivityThread$StopInfo.run(ActivityThread.java:4209)
                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                                                                     Caused by: android.os.TransactionTooLargeException: data parcel size 4538408 bytes
                                                                        at android.os.BinderProxy.transactNative(Native Method)
                                                                        at android.os.BinderProxy.transact(Binder.java:628)
                                                                        at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:4183)
                                                                        at android.app.ActivityThread$StopInfo.run(ActivityThread.java:4201)
                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

Please help.

答:
From Android Developers - TransactionTooLargeException

The Binder transaction buffer has a limited fixed size, currently 1Mb

And from similar question:
What to do on TransactionTooLargeException

Actually data size was around 500kb, and the IPC transaction buffer size is set to 1024KB.

So, data parcel size 4538408 bytes (4MB) is too large to send at once. Split it.

Body:
I am creating an application and in there I am sending very big data in Bundle from Service to the Activity. But I am not using Messenger for that. Instead, I am assigning data to a variable in singleton class and then I am retrieving data from that singleton class and assigning it to the activity.

In the Activity, I have a ViewPager in which two fragments are inflated. The Bundle is being sent to both of these Fragment classes.

Now, when the activity is paused, application is throwing following exception:

at android.app.ActivityThread$StopInfo.run(ActivityThread.java:4209)
                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                                                                     Caused by: android.os.TransactionTooLargeException: data parcel size 4538408 bytes
                                                                        at android.os.BinderProxy.transactNative(Native Method)
                                                                        at android.os.BinderProxy.transact(Binder.java:628)
                                                                        at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:4183)
                                                                        at android.app.ActivityThread$StopInfo.run(ActivityThread.java:4201)
                                                                        at android.os.Handler.handleCallback(Handler.java:751)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:154)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

Please help.